mirror of
https://github.com/openai/codex.git
synced 2026-11-17 14:58:36 +00:00
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:
1 parent
b44af92ca0
commit
a4354e2d27
32 files changed
+1547
-120
No files matched your search
@@ -57,14 +57,17 @@ use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use serial_test::serial;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
use test_case::test_case;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::time::timeout;
|
||||
use url::Url;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
@@ -80,6 +83,16 @@ const WORKSPACE_ID_REFRESHED: &str = "123e4567-e89b-42d3-a456-426614174012";
|
||||
const WORKSPACE_ID_DEVICE: &str = "123e4567-e89b-42d3-a456-426614174013";
|
||||
const WORKSPACE_ID_STALE: &str = "123e4567-e89b-42d3-a456-426614174014";
|
||||
|
||||
fn expected_workspace_routing(
|
||||
account_id: &str,
|
||||
) -> Option<codex_app_server_protocol::WorkspaceRouting> {
|
||||
Some(codex_app_server_protocol::WorkspaceRouting {
|
||||
chatgpt_account_id: account_id.to_string(),
|
||||
backend_origin: "https://chatgpt.com".to_string(),
|
||||
account_routing_override: codex_app_server_protocol::AccountRoutingOverride::NoConstraint,
|
||||
})
|
||||
}
|
||||
|
||||
// Helper to create a minimal config.toml for the app server
|
||||
#[derive(Default)]
|
||||
struct CreateConfigTomlParams {
|
||||
@@ -426,6 +439,7 @@ async fn set_auth_token_updates_account_and_notifies() -> Result<()> {
|
||||
)?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
.with_env_overrides(&[("OPENAI_API_KEY", None)])
|
||||
@@ -465,6 +479,7 @@ async fn set_auth_token_updates_account_and_notifies() -> Result<()> {
|
||||
assert_eq!(
|
||||
account,
|
||||
GetAccountResponse {
|
||||
workspace_routing: expected_workspace_routing(WORKSPACE_ID_EMBEDDED),
|
||||
account: Some(Account::Chatgpt {
|
||||
email: Some("embedded@example.com".to_string()),
|
||||
plan_type: AccountPlanType::Pro,
|
||||
@@ -509,6 +524,7 @@ async fn account_read_refresh_token_is_noop_in_external_mode() -> Result<()> {
|
||||
)?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
.with_env_overrides(&[("OPENAI_API_KEY", None)])
|
||||
@@ -541,6 +557,7 @@ async fn account_read_refresh_token_is_noop_in_external_mode() -> Result<()> {
|
||||
assert_eq!(
|
||||
account,
|
||||
GetAccountResponse {
|
||||
workspace_routing: expected_workspace_routing(WORKSPACE_ID_EMBEDDED),
|
||||
account: Some(Account::Chatgpt {
|
||||
email: Some("embedded@example.com".to_string()),
|
||||
plan_type: AccountPlanType::Pro,
|
||||
@@ -588,6 +605,7 @@ async fn respond_to_refresh_request(
|
||||
}
|
||||
|
||||
async fn mount_disabled_attribution_settings(mock_server: &MockServer) {
|
||||
app_test_support::mount_workspace_routing(mock_server).await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/wham/settings/user"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
@@ -642,6 +660,7 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
|
||||
)?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.with_env_overrides(&[("OPENAI_API_KEY", None)])
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
@@ -743,6 +762,7 @@ async fn external_auth_refresh_error_fails_turn() -> Result<()> {
|
||||
)?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.with_env_overrides(&[("OPENAI_API_KEY", None)])
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
@@ -860,6 +880,7 @@ async fn external_auth_refresh_mismatched_workspace_fails_turn() -> Result<()> {
|
||||
)?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.with_env_overrides(&[("OPENAI_API_KEY", None)])
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
@@ -970,6 +991,7 @@ async fn external_auth_refresh_invalid_access_token_fails_turn() -> Result<()> {
|
||||
)?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.with_env_overrides(&[("OPENAI_API_KEY", None)])
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
@@ -1225,6 +1247,7 @@ async fn login_amazon_bedrock_replaces_primary_auth_and_persists_provider(
|
||||
assert_eq!(
|
||||
read_account(&mut mcp).await?,
|
||||
GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: Some(Account::AmazonBedrock {
|
||||
uses_codex_managed_credentials: true,
|
||||
}),
|
||||
@@ -1255,6 +1278,7 @@ async fn login_amazon_bedrock_replaces_primary_auth_and_persists_provider(
|
||||
assert_eq!(
|
||||
read_account(&mut mcp).await?,
|
||||
GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: None,
|
||||
requires_openai_auth: true,
|
||||
}
|
||||
@@ -1468,6 +1492,7 @@ async fn logout_managed_bedrock_restores_default_account(
|
||||
assert_eq!(
|
||||
read_account(&mut mcp).await?,
|
||||
GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: Some(Account::AmazonBedrock {
|
||||
uses_codex_managed_credentials: true,
|
||||
}),
|
||||
@@ -1518,6 +1543,7 @@ async fn logout_managed_bedrock_restores_default_account(
|
||||
assert_eq!(
|
||||
read_account(&mut mcp).await?,
|
||||
GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: None,
|
||||
requires_openai_auth: true,
|
||||
}
|
||||
@@ -1582,6 +1608,7 @@ async fn logout_aws_managed_bedrock_clears_provider_and_restores_default_account
|
||||
assert_eq!(
|
||||
read_account(&mut mcp).await?,
|
||||
GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: Some(Account::AmazonBedrock {
|
||||
uses_codex_managed_credentials: false,
|
||||
}),
|
||||
@@ -1620,6 +1647,7 @@ async fn logout_aws_managed_bedrock_clears_provider_and_restores_default_account
|
||||
assert_eq!(
|
||||
read_account(&mut mcp).await?,
|
||||
GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: None,
|
||||
requires_openai_auth: true,
|
||||
}
|
||||
@@ -1688,6 +1716,7 @@ async fn logout_managed_bedrock_preserves_changed_provider_without_experimental_
|
||||
assert_eq!(
|
||||
read_account(&mut mcp).await?,
|
||||
GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: None,
|
||||
requires_openai_auth: false,
|
||||
}
|
||||
@@ -1767,6 +1796,7 @@ async fn login_managed_bedrock_updates_active_bedrock_account() -> Result<()> {
|
||||
assert_eq!(
|
||||
read_account(&mut mcp).await?,
|
||||
GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: Some(Account::AmazonBedrock {
|
||||
uses_codex_managed_credentials: true,
|
||||
}),
|
||||
@@ -1885,6 +1915,7 @@ async fn login_account_amazon_bedrock_rejected_with_external_chatgpt_auth() -> R
|
||||
)?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
@@ -1939,6 +1970,7 @@ async fn login_account_api_key_rejected_when_forced_chatgpt() -> Result<()> {
|
||||
)?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
@@ -2008,6 +2040,7 @@ async fn login_account_chatgpt_device_code_returns_error_when_disabled() -> Resu
|
||||
|
||||
let issuer = mock_server.uri();
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
.with_env_overrides(&[
|
||||
@@ -2073,6 +2106,7 @@ async fn login_account_chatgpt_device_code_succeeds_and_notifies() -> Result<()>
|
||||
|
||||
let issuer = mock_server.uri();
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
.with_env_overrides(&[
|
||||
@@ -2127,6 +2161,198 @@ async fn login_account_chatgpt_device_code_succeeds_and_notifies() -> Result<()>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum LoginRefreshTrigger {
|
||||
AuthStatus,
|
||||
UnauthorizedConfig,
|
||||
}
|
||||
|
||||
#[test_case("/backend-api/wham/config/bundle", LoginRefreshTrigger::AuthStatus; "refresh_during_requirements")]
|
||||
#[test_case("/backend-api/wham/accounts/check", LoginRefreshTrigger::AuthStatus; "refresh_during_routing")]
|
||||
#[test_case("/backend-api/wham/config/bundle", LoginRefreshTrigger::UnauthorizedConfig; "refresh_during_account_read_requirements")]
|
||||
#[tokio::test]
|
||||
async fn login_survives_same_owner_token_refresh(
|
||||
delayed_path: &str,
|
||||
refresh_trigger: LoginRefreshTrigger,
|
||||
) -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let backend = MockServer::start().await;
|
||||
create_config_toml(
|
||||
codex_home.path(),
|
||||
CreateConfigTomlParams {
|
||||
requires_openai_auth: Some(true),
|
||||
chatgpt_base_url: Some(format!("{}/backend-api", backend.uri())),
|
||||
..Default::default()
|
||||
},
|
||||
)?;
|
||||
write_models_cache(codex_home.path()).await?;
|
||||
mock_device_code_usercode(&backend, /*interval_seconds*/ 0).await;
|
||||
mock_device_code_token_success(&backend).await;
|
||||
let id_token = encode_id_token(
|
||||
&ChatGptIdTokenClaims::new()
|
||||
.email("device@example.com")
|
||||
.plan_type("enterprise")
|
||||
.chatgpt_user_id("device-user")
|
||||
.chatgpt_account_id(WORKSPACE_ID_DEVICE),
|
||||
)?;
|
||||
mock_oauth_token(&backend, &id_token).await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/refresh"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"id_token": id_token,
|
||||
"access_token": "refreshed-access-token",
|
||||
"refresh_token": "refreshed-refresh-token",
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&backend)
|
||||
.await;
|
||||
let started = Arc::new(Notify::new());
|
||||
for (request_path, response) in [
|
||||
("/backend-api/wham/config/bundle", json!({})),
|
||||
(
|
||||
"/backend-api/wham/accounts/check",
|
||||
json!({"accounts": [{
|
||||
"id": WORKSPACE_ID_DEVICE, "workspace_backend_origin": "https://chatgpt.com",
|
||||
"account_routing_override": "NO_CONSTRAINT",
|
||||
}]}),
|
||||
),
|
||||
] {
|
||||
let mock = Mock::given(method("GET")).and(path(request_path));
|
||||
let mock = if request_path == "/backend-api/wham/accounts/check" {
|
||||
mock.and(header("authorization", "Bearer refreshed-access-token"))
|
||||
} else {
|
||||
mock
|
||||
};
|
||||
mock.respond_with(ResponseTemplate::new(200).set_body_json(response.clone()))
|
||||
.mount(&backend)
|
||||
.await;
|
||||
if request_path == delayed_path {
|
||||
let request_started = Arc::clone(&started);
|
||||
Mock::given(method("GET"))
|
||||
.and(path(request_path))
|
||||
.and(header("authorization", "Bearer access-token-123"))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
request_started.notify_one();
|
||||
ResponseTemplate::new(match refresh_trigger {
|
||||
LoginRefreshTrigger::AuthStatus => 200,
|
||||
LoginRefreshTrigger::UnauthorizedConfig => 401,
|
||||
})
|
||||
.set_delay(Duration::from_secs(/*secs*/ 2))
|
||||
.set_body_json(response.clone())
|
||||
})
|
||||
.with_priority(1)
|
||||
.expect(1..=2)
|
||||
.mount(&backend)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
let issuer = backend.uri();
|
||||
let refresh_url = format!("{issuer}/oauth/refresh");
|
||||
let mut server = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.with_env_overrides(&[
|
||||
("OPENAI_API_KEY", None),
|
||||
(LOGIN_ISSUER_ENV_VAR, Some(issuer.as_str())),
|
||||
(
|
||||
REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR,
|
||||
Some(refresh_url.as_str()),
|
||||
),
|
||||
])
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
.await?;
|
||||
let request = server
|
||||
.send_login_account_chatgpt_device_code_request()
|
||||
.await?;
|
||||
let login: LoginAccountResponse =
|
||||
timeout(DEFAULT_READ_TIMEOUT, server.read_response(request)).await??;
|
||||
let LoginAccountResponse::ChatgptDeviceCode { login_id, .. } = login else {
|
||||
bail!("unexpected login response: {login:?}");
|
||||
};
|
||||
timeout(DEFAULT_READ_TIMEOUT, started.notified()).await?;
|
||||
let expected_account = GetAccountResponse {
|
||||
account: Some(Account::Chatgpt {
|
||||
email: Some("device@example.com".into()),
|
||||
plan_type: AccountPlanType::Enterprise,
|
||||
}),
|
||||
requires_openai_auth: true,
|
||||
workspace_routing: expected_workspace_routing(WORKSPACE_ID_DEVICE),
|
||||
};
|
||||
match refresh_trigger {
|
||||
LoginRefreshTrigger::AuthStatus => {
|
||||
let request = server
|
||||
.send_get_auth_status_request(GetAuthStatusParams {
|
||||
include_token: Some(true),
|
||||
refresh_token: Some(true),
|
||||
})
|
||||
.await?;
|
||||
let refreshed: GetAuthStatusResponse =
|
||||
timeout(DEFAULT_READ_TIMEOUT, server.read_response(request)).await??;
|
||||
assert_eq!(
|
||||
refreshed.auth_token.as_deref(),
|
||||
Some("refreshed-access-token")
|
||||
);
|
||||
}
|
||||
LoginRefreshTrigger::UnauthorizedConfig => {
|
||||
assert_eq!(read_account(&mut server).await?, expected_account);
|
||||
}
|
||||
}
|
||||
let completed: AccountLoginCompletedNotification = timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
server.read_notification("account/login/completed"),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(
|
||||
completed,
|
||||
AccountLoginCompletedNotification {
|
||||
login_id: Some(login_id),
|
||||
success: true,
|
||||
error: None,
|
||||
onboarding_entrypoint: None,
|
||||
}
|
||||
);
|
||||
let updated: AccountUpdatedNotification = timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
server.read_notification("account/updated"),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(
|
||||
updated,
|
||||
AccountUpdatedNotification {
|
||||
auth_mode: Some(AuthMode::Chatgpt),
|
||||
plan_type: Some(AccountPlanType::Enterprise),
|
||||
}
|
||||
);
|
||||
assert_eq!(read_account(&mut server).await?, expected_account);
|
||||
let requests = backend
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("recorded requests");
|
||||
let routing_tokens = requests
|
||||
.iter()
|
||||
.filter(|request| request.url.path() == "/backend-api/wham/accounts/check")
|
||||
.map(|request| {
|
||||
request.headers["authorization"]
|
||||
.to_str()
|
||||
.expect("routing authorization header")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
routing_tokens,
|
||||
if delayed_path == "/backend-api/wham/accounts/check" {
|
||||
vec!["Bearer access-token-123", "Bearer refreshed-access-token"]
|
||||
} else if matches!(refresh_trigger, LoginRefreshTrigger::UnauthorizedConfig) {
|
||||
vec![
|
||||
"Bearer refreshed-access-token",
|
||||
"Bearer refreshed-access-token",
|
||||
]
|
||||
} else {
|
||||
vec!["Bearer refreshed-access-token"]
|
||||
}
|
||||
);
|
||||
backend.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn login_account_chatgpt_device_code_failure_notifies_without_account_update() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
@@ -2146,6 +2372,7 @@ async fn login_account_chatgpt_device_code_failure_notifies_without_account_upda
|
||||
|
||||
let issuer = mock_server.uri();
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
.with_env_overrides(&[
|
||||
@@ -2217,6 +2444,7 @@ async fn login_account_chatgpt_device_code_can_be_cancelled() -> Result<()> {
|
||||
|
||||
let issuer = mock_server.uri();
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
.with_env_overrides(&[
|
||||
@@ -2282,6 +2510,7 @@ async fn login_account_chatgpt_start_can_be_cancelled() -> Result<()> {
|
||||
create_config_toml(codex_home.path(), CreateConfigTomlParams::default())?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
@@ -2351,6 +2580,7 @@ async fn login_account_chatgpt_uses_oauth_overrides() -> Result<()> {
|
||||
let issuer = mock_server.uri();
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
// Exercise packaged-build behavior without the debug-only startup flag.
|
||||
@@ -2550,6 +2780,7 @@ async fn set_auth_token_cancels_active_chatgpt_login() -> Result<()> {
|
||||
create_config_toml(codex_home.path(), CreateConfigTomlParams::default())?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
@@ -2615,6 +2846,7 @@ async fn login_account_chatgpt_includes_forced_workspace_query_param() -> Result
|
||||
)?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
@@ -2650,6 +2882,7 @@ async fn login_account_chatgpt_includes_forced_workspace_allowlist_query_param()
|
||||
)?;
|
||||
|
||||
let mut mcp = TestAppServer::builder()
|
||||
.with_mock_chatgpt_backend()
|
||||
.with_codex_home(codex_home.path())
|
||||
.without_auto_env()
|
||||
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
|
||||
@@ -2738,6 +2971,7 @@ async fn get_account_with_api_key() -> Result<()> {
|
||||
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??;
|
||||
|
||||
let expected = GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: Some(Account::ApiKey {}),
|
||||
requires_openai_auth: true,
|
||||
};
|
||||
@@ -2771,6 +3005,7 @@ async fn get_account_when_auth_not_required() -> Result<()> {
|
||||
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??;
|
||||
|
||||
let expected = GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: None,
|
||||
requires_openai_auth: false,
|
||||
};
|
||||
@@ -2811,6 +3046,7 @@ region = "us-west-2"
|
||||
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??;
|
||||
|
||||
let expected = GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: Some(Account::AmazonBedrock {
|
||||
uses_codex_managed_credentials: false,
|
||||
}),
|
||||
@@ -2849,6 +3085,7 @@ command = "print-token"
|
||||
assert_eq!(
|
||||
read_account(&mut mcp).await?,
|
||||
GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: Some(Account::AmazonBedrock {
|
||||
uses_codex_managed_credentials: false,
|
||||
}),
|
||||
@@ -2887,6 +3124,7 @@ region = "us-west-2"
|
||||
assert_eq!(
|
||||
read_account(&mut mcp).await?,
|
||||
GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: Some(Account::AmazonBedrock {
|
||||
uses_codex_managed_credentials: false,
|
||||
}),
|
||||
@@ -2952,6 +3190,7 @@ async fn get_account_with_managed_bedrock_provider() -> Result<()> {
|
||||
assert_eq!(
|
||||
received,
|
||||
GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: Some(Account::AmazonBedrock {
|
||||
uses_codex_managed_credentials: true,
|
||||
}),
|
||||
@@ -2974,6 +3213,7 @@ async fn get_account_with_chatgpt() -> Result<()> {
|
||||
write_chatgpt_auth(
|
||||
codex_home.path(),
|
||||
ChatGptAuthFixture::new("access-chatgpt")
|
||||
.account_id("account-123")
|
||||
.email("user@example.com")
|
||||
.plan_type("pro"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
@@ -2995,6 +3235,7 @@ async fn get_account_with_chatgpt() -> Result<()> {
|
||||
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??;
|
||||
|
||||
let expected = GetAccountResponse {
|
||||
workspace_routing: expected_workspace_routing("account-123"),
|
||||
account: Some(Account::Chatgpt {
|
||||
email: Some("user@example.com".to_string()),
|
||||
plan_type: AccountPlanType::Pro,
|
||||
@@ -3024,6 +3265,7 @@ async fn get_account_with_chatgpt_plan_variants_returns_plan_type(
|
||||
write_chatgpt_auth(
|
||||
codex_home.path(),
|
||||
ChatGptAuthFixture::new("access-chatgpt")
|
||||
.account_id("account-123")
|
||||
.email("user@example.com")
|
||||
.plan_type(plan_type),
|
||||
AuthCredentialsStoreMode::File,
|
||||
@@ -3047,6 +3289,7 @@ async fn get_account_with_chatgpt_plan_variants_returns_plan_type(
|
||||
assert_eq!(
|
||||
received,
|
||||
GetAccountResponse {
|
||||
workspace_routing: expected_workspace_routing("account-123"),
|
||||
account: Some(Account::Chatgpt {
|
||||
email: Some("user@example.com".to_string()),
|
||||
plan_type: expected_plan,
|
||||
@@ -3069,7 +3312,9 @@ async fn get_account_with_chatgpt_without_email() -> Result<()> {
|
||||
)?;
|
||||
write_chatgpt_auth(
|
||||
codex_home.path(),
|
||||
ChatGptAuthFixture::new("access-chatgpt").plan_type("pro"),
|
||||
ChatGptAuthFixture::new("access-chatgpt")
|
||||
.account_id("account-123")
|
||||
.plan_type("pro"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
|
||||
@@ -3091,6 +3336,7 @@ async fn get_account_with_chatgpt_without_email() -> Result<()> {
|
||||
assert_eq!(
|
||||
received,
|
||||
GetAccountResponse {
|
||||
workspace_routing: expected_workspace_routing("account-123"),
|
||||
account: Some(Account::Chatgpt {
|
||||
email: None,
|
||||
plan_type: AccountPlanType::Pro,
|
||||
@@ -3172,6 +3418,7 @@ async fn get_account_omits_chatgpt_after_permanent_refresh_failure() -> Result<(
|
||||
assert_eq!(
|
||||
received,
|
||||
GetAccountResponse {
|
||||
workspace_routing: None,
|
||||
account: None,
|
||||
requires_openai_auth: true,
|
||||
}
|
||||
@@ -3192,7 +3439,9 @@ async fn get_account_with_chatgpt_missing_plan_claim_returns_unknown() -> Result
|
||||
)?;
|
||||
write_chatgpt_auth(
|
||||
codex_home.path(),
|
||||
ChatGptAuthFixture::new("access-chatgpt").email("user@example.com"),
|
||||
ChatGptAuthFixture::new("access-chatgpt")
|
||||
.account_id("account-123")
|
||||
.email("user@example.com"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
|
||||
@@ -3212,6 +3461,7 @@ async fn get_account_with_chatgpt_missing_plan_claim_returns_unknown() -> Result
|
||||
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??;
|
||||
|
||||
let expected = GetAccountResponse {
|
||||
workspace_routing: expected_workspace_routing("account-123"),
|
||||
account: Some(Account::Chatgpt {
|
||||
email: Some("user@example.com".to_string()),
|
||||
plan_type: AccountPlanType::Unknown,
|
||||
|
||||
@@ -170,6 +170,7 @@ command = "print-token"
|
||||
uses_codex_managed_credentials: false
|
||||
}),
|
||||
requires_openai_auth: false,
|
||||
workspace_routing: None,
|
||||
}
|
||||
);
|
||||
assert!(
|
||||
|
||||
@@ -146,6 +146,7 @@ mod turn_steer;
|
||||
mod view_image;
|
||||
mod web_search;
|
||||
mod windows_sandbox_setup;
|
||||
mod workspace_routing;
|
||||
|
||||
mod user_verification;
|
||||
mod user_verification_mcp;
|
||||
@@ -389,7 +389,8 @@ plugin_sharing = false
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("wiremock should record requests")
|
||||
.is_empty()
|
||||
.iter()
|
||||
.all(|request| request.url.path() == "/backend-api/wham/accounts/check")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -228,6 +228,16 @@ async fn consume_account_rate_limit_reset_credit_surfaces_backend_failure() -> R
|
||||
#[tokio::test]
|
||||
async fn consume_timeout_releases_account_auth_queue() -> Result<()> {
|
||||
let (codex_home, server) = chatgpt_test_context().await?;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/api/codex/accounts/check"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200).set_body_json(json!({"accounts": [{
|
||||
"id": "account-123", "workspace_backend_origin": "https://chatgpt.com",
|
||||
"account_routing_override": "NO_CONSTRAINT"
|
||||
}]})),
|
||||
)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/api/codex/rate-limit-reset-credits/consume"))
|
||||
.respond_with(
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
//! Selected-workspace discovery through the public account API.
|
||||
|
||||
use anyhow::Result;
|
||||
use app_test_support::ChatGptAuthFixture;
|
||||
use app_test_support::ChatGptIdTokenClaims;
|
||||
use app_test_support::TestAppServer;
|
||||
use app_test_support::encode_id_token;
|
||||
use app_test_support::write_chatgpt_auth;
|
||||
use codex_app_server_protocol::ClientInfo;
|
||||
use codex_app_server_protocol::GetAccountParams;
|
||||
use codex_app_server_protocol::LoginAccountResponse;
|
||||
use codex_app_server_protocol::LogoutAccountResponse;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::time::timeout;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
const READ_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 60);
|
||||
|
||||
async fn config(home: &TempDir, backend: &MockServer) -> Result<()> {
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!(
|
||||
"chatgpt_base_url = '{}/backend-api/'\ncli_auth_credentials_store = 'file'\n",
|
||||
backend.uri()
|
||||
),
|
||||
)?;
|
||||
Mock::given(method("GET")).and(path("/backend-api/wham/config/bundle"))
|
||||
.respond_with(|request: &wiremock::Request| {
|
||||
let account_id = request.headers.get("chatgpt-account-id").expect("workspace header")
|
||||
.to_str().expect("workspace header text");
|
||||
ResponseTemplate::new(200).set_body_json(json!({"requirements_toml": {"enterprise_managed": [{
|
||||
"id": "workspace-policy", "name": "Workspace policy",
|
||||
"contents": format!("[application.network.domains]\n'{account_id}.example' = 'allow'"),
|
||||
}]}}))
|
||||
}).mount(backend).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn start(home: &TempDir) -> Result<TestAppServer> {
|
||||
TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.with_env_overrides(&[("OPENAI_API_KEY", None)])
|
||||
.build_initialized_with_timeout(READ_TIMEOUT)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn read(server: &mut TestAppServer) -> Result<Value> {
|
||||
let request = server
|
||||
.send_get_account_request(GetAccountParams {
|
||||
refresh_token: false,
|
||||
})
|
||||
.await?;
|
||||
timeout(READ_TIMEOUT, server.read_response(request)).await?
|
||||
}
|
||||
|
||||
async fn login(server: &mut TestAppServer, account: &str) -> Result<()> {
|
||||
let token = encode_id_token(
|
||||
&ChatGptIdTokenClaims::new()
|
||||
.email("user@example.com")
|
||||
.plan_type("enterprise")
|
||||
.chatgpt_account_id(account),
|
||||
)?;
|
||||
let request = server
|
||||
.send_chatgpt_auth_tokens_login_request(token, account.into(), Some("enterprise".into()))
|
||||
.await?;
|
||||
let _: LoginAccountResponse = timeout(READ_TIMEOUT, server.read_response(request)).await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn routing(account: &str, origin: &str, routing: &str) -> Value {
|
||||
json!({"chatgptAccountId": account, "backendOrigin": origin, "accountRoutingOverride": routing})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn saved_workspace_is_discovered_once_and_not_the_default_account() -> Result<()> {
|
||||
let backend = MockServer::start().await;
|
||||
Mock::given(method("GET")).and(path("/backend-api/wham/accounts/check"))
|
||||
.and(header("chatgpt-account-id", "selected"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"accounts": [
|
||||
{"id": "other", "workspace_backend_origin": "https://other.example", "account_routing_override": "us"},
|
||||
{"id": "selected", "workspace_backend_origin": "https://gov.chatgpt.com", "account_routing_override": "NO_CONSTRAINT"}
|
||||
], "default_account_id": "other"
|
||||
}))).expect(1).mount(&backend).await;
|
||||
let home = TempDir::new()?;
|
||||
config(&home, &backend).await?;
|
||||
write_chatgpt_auth(
|
||||
home.path(),
|
||||
ChatGptAuthFixture::new("token")
|
||||
.account_id("selected")
|
||||
.email("user@example.com")
|
||||
.plan_type("pro"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
let mut server = start(&home).await?;
|
||||
let notification = timeout(
|
||||
READ_TIMEOUT,
|
||||
server.read_stream_until_notification_message("account/updated"),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(
|
||||
notification.params,
|
||||
Some(json!({"authMode": "chatgpt", "planType": "pro"}))
|
||||
);
|
||||
let expected = json!({
|
||||
"account": {"type": "chatgpt", "email": "user@example.com", "planType": "pro"},
|
||||
"requiresOpenaiAuth": true, "workspaceRouting": routing("selected", "https://gov.chatgpt.com", "NO_CONSTRAINT")
|
||||
});
|
||||
assert_eq!(read(&mut server).await?, expected);
|
||||
assert_eq!(read(&mut server).await?, expected);
|
||||
backend.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn saved_chatgpt_login_without_selected_workspace_preserves_account() -> Result<()> {
|
||||
let backend = MockServer::start().await;
|
||||
Mock::given(path("/backend-api/wham/accounts/check"))
|
||||
.respond_with(ResponseTemplate::new(500))
|
||||
.expect(0)
|
||||
.mount(&backend)
|
||||
.await;
|
||||
let home = TempDir::new()?;
|
||||
config(&home, &backend).await?;
|
||||
write_chatgpt_auth(
|
||||
home.path(),
|
||||
ChatGptAuthFixture::new("token").plan_type("pro"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
let mut server = start(&home).await?;
|
||||
assert_eq!(
|
||||
read(&mut server).await?,
|
||||
json!({"account": {"type": "chatgpt", "email": null, "planType": "pro"},
|
||||
"requiresOpenaiAuth": true, "workspaceRouting": null})
|
||||
);
|
||||
backend.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stable_clients_do_not_treat_failed_workspace_discovery_as_unrestricted() -> Result<()> {
|
||||
let backend = MockServer::start().await;
|
||||
Mock::given(path("/backend-api/wham/accounts/check"))
|
||||
.respond_with(ResponseTemplate::new(503))
|
||||
.mount(&backend)
|
||||
.await;
|
||||
let home = TempDir::new()?;
|
||||
config(&home, &backend).await?;
|
||||
write_chatgpt_auth(
|
||||
home.path(),
|
||||
ChatGptAuthFixture::new("token")
|
||||
.account_id("selected")
|
||||
.plan_type("pro"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
let mut server = TestAppServer::builder()
|
||||
.with_codex_home(home.path())
|
||||
.with_env_overrides(&[("OPENAI_API_KEY", None)])
|
||||
.build()
|
||||
.await?;
|
||||
timeout(
|
||||
READ_TIMEOUT,
|
||||
server.initialize_with_capabilities(
|
||||
ClientInfo {
|
||||
name: "routing-stable-client".into(),
|
||||
title: None,
|
||||
version: "1.0.0".into(),
|
||||
},
|
||||
/*capabilities*/ None,
|
||||
),
|
||||
)
|
||||
.await??;
|
||||
let request = server
|
||||
.send_get_account_request(GetAccountParams {
|
||||
refresh_token: false,
|
||||
})
|
||||
.await?;
|
||||
let error = timeout(
|
||||
READ_TIMEOUT,
|
||||
server.read_stream_until_error_message(RequestId::Integer(request)),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(error.error.message, "workspace routing discovery failed");
|
||||
backend.reset().await;
|
||||
Mock::given(path("/backend-api/wham/accounts/check"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"accounts": [{
|
||||
"id": "selected", "workspace_backend_origin": "https://chatgpt.com", "account_routing_override": "NO_CONSTRAINT"
|
||||
}]})))
|
||||
.mount(&backend)
|
||||
.await;
|
||||
assert_eq!(
|
||||
read(&mut server).await?,
|
||||
json!({"account": {"type": "chatgpt", "email": null, "planType": "pro"},
|
||||
"requiresOpenaiAuth": true, "workspaceRouting": routing("selected", "https://chatgpt.com", "NO_CONSTRAINT")})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn login_and_workspace_switch_notify_after_routing_is_ready_then_logout_clears_it()
|
||||
-> Result<()> {
|
||||
let backend = MockServer::start().await;
|
||||
Mock::given(method("GET")).and(path("/backend-api/wham/accounts/check"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"accounts": [
|
||||
{"id": "first", "workspace_backend_origin": "https://chatgpt.com", "account_routing_override": "us_cr"},
|
||||
{"id": "second", "workspace_backend_origin": "https://gov.chatgpt.com", "account_routing_override": "us"}
|
||||
]}))).expect(2).mount(&backend).await;
|
||||
let home = TempDir::new()?;
|
||||
config(&home, &backend).await?;
|
||||
let mut server = start(&home).await?;
|
||||
for (account, origin, value) in [
|
||||
("first", "https://chatgpt.com", "us_cr"),
|
||||
("second", "https://gov.chatgpt.com", "us"),
|
||||
] {
|
||||
login(&mut server, account).await?;
|
||||
let notification = timeout(
|
||||
READ_TIMEOUT,
|
||||
server.read_stream_until_notification_message("account/updated"),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(
|
||||
notification.params,
|
||||
Some(json!({"authMode": "chatgptAuthTokens", "planType": "enterprise"}))
|
||||
);
|
||||
assert_eq!(
|
||||
read(&mut server).await?["workspaceRouting"],
|
||||
routing(account, origin, value)
|
||||
);
|
||||
let request = server.send_config_requirements_read_request().await?;
|
||||
let requirements: Value = timeout(READ_TIMEOUT, server.read_response(request)).await??;
|
||||
assert_eq!(
|
||||
requirements["requirements"]["application"],
|
||||
json!({"network": {
|
||||
"enabled": true, "domains": {format!("{account}.example"): "allow"}
|
||||
}})
|
||||
);
|
||||
}
|
||||
let request = server.send_logout_account_request().await?;
|
||||
let _: LogoutAccountResponse = timeout(READ_TIMEOUT, server.read_response(request)).await??;
|
||||
assert_eq!(
|
||||
read(&mut server).await?,
|
||||
json!({"account": null, "requiresOpenaiAuth": true, "workspaceRouting": null})
|
||||
);
|
||||
backend.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unavailable_or_malformed_discovery_never_returns_unrestricted_success() -> Result<()> {
|
||||
for response in [
|
||||
ResponseTemplate::new(503),
|
||||
ResponseTemplate::new(200).set_body_json(json!({"accounts": [{"id": "selected"}]})),
|
||||
ResponseTemplate::new(200).set_body_json(json!({"accounts": [{"id": "selected", "account_routing_override": "us_cr"}]})),
|
||||
ResponseTemplate::new(200).set_body_json(json!({"accounts": [{"id": "selected", "workspace_backend_origin": "NO_CONSTRAINT"}]})),
|
||||
ResponseTemplate::new(200).set_body_json(json!({"accounts": [{"id": "selected", "workspace_backend_origin": null, "account_routing_override": null}]})),
|
||||
ResponseTemplate::new(200).set_body_json(json!({"accounts": [{"id": "selected", "workspace_backend_origin": 7, "account_routing_override": "us_cr"}]})),
|
||||
ResponseTemplate::new(200).set_body_json(json!({"accounts": [{"id": "selected", "workspace_backend_origin": "NO_CONSTRAINT", "account_routing_override": "unknown"}]})),
|
||||
ResponseTemplate::new(200).set_body_json(json!({"accounts": []})),
|
||||
] {
|
||||
let backend = MockServer::start().await;
|
||||
Mock::given(method("GET")).and(path("/backend-api/wham/accounts/check"))
|
||||
.respond_with(response).mount(&backend).await;
|
||||
let home = TempDir::new()?;
|
||||
config(&home, &backend).await?;
|
||||
write_chatgpt_auth(home.path(), ChatGptAuthFixture::new("token").account_id("selected"), AuthCredentialsStoreMode::File)?;
|
||||
let mut server = start(&home).await?;
|
||||
let request = server.send_get_account_request(GetAccountParams { refresh_token: false }).await?;
|
||||
let error = timeout(READ_TIMEOUT, server.read_stream_until_error_message(RequestId::Integer(request))).await??;
|
||||
assert!(error.error.message.contains("routing"), "{error:?}");
|
||||
backend.reset().await;
|
||||
Mock::given(method("GET")).and(path("/backend-api/wham/accounts/check"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"accounts": [{
|
||||
"id": "selected", "workspace_backend_origin": "https://chatgpt.com", "account_routing_override": "NO_CONSTRAINT"
|
||||
}]}))).mount(&backend).await;
|
||||
assert_eq!(read(&mut server).await?["workspaceRouting"], routing("selected", "https://chatgpt.com", "NO_CONSTRAINT"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn late_startup_discovery_is_discarded_on_workspace_switch_and_logout() -> Result<()> {
|
||||
for next_account in [Some("second"), Some("first"), None] {
|
||||
let backend = MockServer::start().await;
|
||||
let started = Arc::new(Notify::new());
|
||||
let request_started = Arc::clone(&started);
|
||||
Mock::given(method("GET")).and(path("/backend-api/wham/accounts/check"))
|
||||
.and(header("chatgpt-account-id", "first"))
|
||||
.and(header("authorization", "Bearer token"))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
request_started.notify_one();
|
||||
ResponseTemplate::new(200).set_delay(Duration::from_secs(/*secs*/ 2))
|
||||
.set_body_json(json!({"accounts": [{"id": "first", "workspace_backend_origin": "https://old.example", "account_routing_override": "us_cr"}]}))
|
||||
}).with_priority(1).mount(&backend).await;
|
||||
Mock::given(method("GET")).and(path("/backend-api/wham/accounts/check"))
|
||||
.and(header("chatgpt-account-id", next_account.unwrap_or("second")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"accounts": [
|
||||
{"id": next_account.unwrap_or("second"), "workspace_backend_origin": "https://new.example", "account_routing_override": "us"}
|
||||
]}))).mount(&backend).await;
|
||||
let home = TempDir::new()?;
|
||||
config(&home, &backend).await?;
|
||||
write_chatgpt_auth(
|
||||
home.path(),
|
||||
ChatGptAuthFixture::new("token").account_id("first"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
let mut server = start(&home).await?;
|
||||
timeout(READ_TIMEOUT, started.notified()).await?;
|
||||
if let Some(account) = next_account {
|
||||
login(&mut server, account).await?;
|
||||
} else {
|
||||
let request = server.send_logout_account_request().await?;
|
||||
let _: LogoutAccountResponse =
|
||||
timeout(READ_TIMEOUT, server.read_response(request)).await??;
|
||||
}
|
||||
let expected = next_account
|
||||
.map(|account| routing(account, "https://new.example", "us"))
|
||||
.unwrap_or(Value::Null);
|
||||
assert_eq!(read(&mut server).await?["workspaceRouting"], expected);
|
||||
tokio::time::sleep(Duration::from_secs(/*secs*/ 2)).await;
|
||||
assert_eq!(read(&mut server).await?["workspaceRouting"], expected);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn api_only_login_does_not_discover_chatgpt_routing() -> Result<()> {
|
||||
let backend = MockServer::start().await;
|
||||
Mock::given(path("/backend-api/wham/accounts/check"))
|
||||
.respond_with(ResponseTemplate::new(500))
|
||||
.expect(0)
|
||||
.mount(&backend)
|
||||
.await;
|
||||
let home = TempDir::new()?;
|
||||
config(&home, &backend).await?;
|
||||
std::fs::write(
|
||||
home.path().join("requirements.toml"),
|
||||
"allowed_login_methods = ['api']",
|
||||
)?;
|
||||
let mut server = start(&home).await?;
|
||||
let request = server.send_login_account_api_key_request("sk-test").await?;
|
||||
let _: LoginAccountResponse = timeout(READ_TIMEOUT, server.read_response(request)).await??;
|
||||
assert_eq!(
|
||||
read(&mut server).await?,
|
||||
json!({"account": {"type": "apiKey"}, "requiresOpenaiAuth": true, "workspaceRouting": null})
|
||||
);
|
||||
backend.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_workspace_requirements_do_not_fall_back_to_startup_config() -> Result<()> {
|
||||
let backend = MockServer::start().await;
|
||||
let home = TempDir::new()?;
|
||||
config(&home, &backend).await?;
|
||||
let mut server = start(&home).await?;
|
||||
backend.reset().await;
|
||||
Mock::given(path("/backend-api/wham/config/bundle"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(
|
||||
json!({"requirements_toml": {"enterprise_managed": [{
|
||||
"id": "invalid", "name": "Invalid requirements", "contents": "application = true",
|
||||
}]}}),
|
||||
))
|
||||
.mount(&backend)
|
||||
.await;
|
||||
Mock::given(path("/backend-api/wham/accounts/check"))
|
||||
.respond_with(ResponseTemplate::new(200))
|
||||
.expect(0)
|
||||
.mount(&backend)
|
||||
.await;
|
||||
login(&mut server, "selected").await?;
|
||||
let notification = timeout(
|
||||
READ_TIMEOUT,
|
||||
server.read_stream_until_notification_message("account/login/completed"),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(notification.params.unwrap()["success"], false);
|
||||
let request = server
|
||||
.send_get_account_request(GetAccountParams {
|
||||
refresh_token: false,
|
||||
})
|
||||
.await?;
|
||||
let error = timeout(
|
||||
READ_TIMEOUT,
|
||||
server.read_stream_until_error_message(RequestId::Integer(request)),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(error.error.message, "failed to load workspace requirements");
|
||||
backend.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn backend_config_changed_during_discovery_is_retried_with_fresh_config() -> Result<()> {
|
||||
let old_backend = MockServer::start().await;
|
||||
let new_backend = MockServer::start().await;
|
||||
let started = Arc::new(Notify::new());
|
||||
let request_started = Arc::clone(&started);
|
||||
Mock::given(path("/backend-api/wham/accounts/check"))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
request_started.notify_one();
|
||||
ResponseTemplate::new(200)
|
||||
.set_delay(Duration::from_secs(/*secs*/ 2))
|
||||
.set_body_json(json!({"accounts": [{
|
||||
"id": "selected", "workspace_backend_origin": "https://old.example",
|
||||
"account_routing_override": "us_cr"
|
||||
}]}))
|
||||
})
|
||||
.mount(&old_backend)
|
||||
.await;
|
||||
Mock::given(path("/backend-api/wham/accounts/check"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200).set_body_json(json!({"accounts": [{
|
||||
"id": "selected", "workspace_backend_origin": "https://new.example",
|
||||
"account_routing_override": "us"
|
||||
}]})),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&new_backend)
|
||||
.await;
|
||||
let home = TempDir::new()?;
|
||||
config(&home, &old_backend).await?;
|
||||
let mut server = start(&home).await?;
|
||||
login(&mut server, "selected").await?;
|
||||
timeout(READ_TIMEOUT, started.notified()).await?;
|
||||
config(&home, &new_backend).await?;
|
||||
let completed = timeout(
|
||||
READ_TIMEOUT,
|
||||
server.read_stream_until_notification_message("account/login/completed"),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(
|
||||
completed.params,
|
||||
Some(json!({
|
||||
"loginId": null, "success": false,
|
||||
"error": "configuration changed during workspace routing discovery; retry account/read",
|
||||
"onboardingEntrypoint": null,
|
||||
}))
|
||||
);
|
||||
assert_eq!(
|
||||
read(&mut server).await?["workspaceRouting"],
|
||||
routing("selected", "https://new.example", "us")
|
||||
);
|
||||
new_backend.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user