aKode fase 2b-2: rimosso login ChatGPT e tutti i sottosistemi solo-ChatGPT
- Login: resta solo chiave API (+ header, Bedrock). Rimossi OAuth/browser, device code, refresh/revoke su auth.openai.com, PAT, agent/workload identity, runtime agent instance, backend-client e openapi-models, workspace routing. - Rimossi: generazione immagini (ext + skill imagegen), history notes, plugin remoti (catalogo, sync, share), cyber access program, daybreak, cloud config e requirements (config_server ora fail-closed), attestation, frozen cloud skills, EMA MCP auth, Codex Apps/connettori, ricerca ospitata, header/zstd/ routing/cookie del backend Codex, fallback OPENAI_API_KEY del realtime. - Messaggi d'errore senza link a chatgpt.com. - Chiavi di config legacy accettate e ignorate; feature rimosse = Stage::Removed. - Test: cancellati solo quelli del codice rimosso; test di sicurezza (sandbox estensioni, permessi, redazione, auth storage, requirements) adattati. Restano solo fallimenti d'ambiente (code-mode-host/V8, ~/.agents). - Istruzioni di sistema invariate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,73 +4,20 @@ use super::bedrock_auth::prepare_bedrock_provider;
|
||||
use super::config_processor::map_error as map_config_error;
|
||||
use super::*;
|
||||
use crate::auth_mode::auth_mode_to_api;
|
||||
use crate::external_auth::ExternalAuthBridge;
|
||||
use crate::model_catalog::ModelCatalog;
|
||||
use crate::outgoing_message::AccountNotification;
|
||||
use codex_app_server_protocol::DesktopOnboardingEntrypoint;
|
||||
use codex_login::LoginOnboardingEntrypoint;
|
||||
use codex_login::login_with_bedrock_access_keys;
|
||||
use codex_mcp::ema_auth_scope;
|
||||
use codex_model_provider::is_supported_amazon_bedrock_region;
|
||||
use codex_otel::auth_storage::AuthStorageOriginator;
|
||||
use codex_rmcp_client::EnterpriseOAuthCredentialGuard;
|
||||
|
||||
mod account_read;
|
||||
mod bedrock_gov_cloud;
|
||||
mod bedrock_setup;
|
||||
mod enterprise_login;
|
||||
mod gateway_oauth;
|
||||
mod gcp_setup;
|
||||
mod security_setup;
|
||||
mod workspace_routing;
|
||||
mod workspace_switching;
|
||||
|
||||
pub(super) use enterprise_login::EnterpriseLoginCompletion;
|
||||
pub(super) use enterprise_login::EnterpriseLoginTarget;
|
||||
pub(crate) use gcp_setup::handle_gcp_setup;
|
||||
|
||||
// Duration before a browser ChatGPT login attempt is abandoned.
|
||||
const LOGIN_CHATGPT_TIMEOUT: Duration = Duration::from_secs(10 * 60);
|
||||
// Packaged clients use this together with the OAuth client ID override for staging login.
|
||||
const LOGIN_ISSUER_OVERRIDE_ENV_VAR: &str = "CODEX_APP_SERVER_LOGIN_ISSUER";
|
||||
// The development success-page redirect remains debug-only.
|
||||
#[cfg(debug_assertions)]
|
||||
const LOGIN_OPEN_APP_URL_OVERRIDE_ENV_VAR: &str = "CODEX_APP_SERVER_DEV_OPEN_APP_URL";
|
||||
|
||||
enum ActiveLogin {
|
||||
Browser {
|
||||
shutdown_handle: ShutdownHandle,
|
||||
login_id: Uuid,
|
||||
},
|
||||
DeviceCode {
|
||||
cancel: CancellationToken,
|
||||
login_id: Uuid,
|
||||
},
|
||||
}
|
||||
|
||||
impl ActiveLogin {
|
||||
fn login_id(&self) -> Uuid {
|
||||
match self {
|
||||
ActiveLogin::Browser { login_id, .. } | ActiveLogin::DeviceCode { login_id, .. } => {
|
||||
*login_id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel(&self) {
|
||||
match self {
|
||||
ActiveLogin::Browser {
|
||||
shutdown_handle, ..
|
||||
} => shutdown_handle.shutdown(),
|
||||
ActiveLogin::DeviceCode { cancel, .. } => cancel.cancel(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum CancelLoginError {
|
||||
NotFound,
|
||||
}
|
||||
|
||||
enum RefreshTokenRequestOutcome {
|
||||
NotAttemptedOrSucceeded,
|
||||
FailedTransiently,
|
||||
@@ -91,12 +38,6 @@ enum BedrockLoginCredentials {
|
||||
},
|
||||
}
|
||||
|
||||
impl Drop for ActiveLogin {
|
||||
fn drop(&mut self) {
|
||||
self.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct AccountRequestProcessor {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
@@ -105,15 +46,10 @@ pub(crate) struct AccountRequestProcessor {
|
||||
config: Arc<Config>,
|
||||
config_manager: ConfigManager,
|
||||
model_catalog: Arc<ModelCatalog>,
|
||||
active_login: Arc<Mutex<Option<ActiveLogin>>>,
|
||||
workspace_routing: Arc<Mutex<Option<workspace_routing::CachedWorkspaceRouting>>>,
|
||||
workspace_routing_fetches: Arc<Mutex<workspace_routing::WorkspaceRoutingFetches>>,
|
||||
workspace_routing_shutdown: CancellationToken,
|
||||
gateway_login: Arc<std::sync::Mutex<Option<gateway_oauth::ActiveGatewayLogin>>>,
|
||||
gateway_clients:
|
||||
Arc<std::sync::Mutex<HashMap<String, Arc<codex_model_provider::GatewayAuthManager>>>>,
|
||||
_gateway_notifications: Arc<tokio_util::task::AbortOnDropHandle<()>>,
|
||||
pub(super) enterprise_login: Arc<enterprise_login::EnterpriseLoginState>,
|
||||
}
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
@@ -130,12 +66,7 @@ impl AccountRequestProcessor {
|
||||
config_manager.clone(),
|
||||
Arc::clone(&outgoing),
|
||||
);
|
||||
let enterprise_login = Arc::new(enterprise_login::EnterpriseLoginState::new(
|
||||
Arc::clone(&auth_manager),
|
||||
Arc::clone(&thread_manager),
|
||||
config_manager.clone(),
|
||||
));
|
||||
let processor = Arc::new(Self {
|
||||
Arc::new(Self {
|
||||
_gateway_notifications: Arc::new(gateway_notifications),
|
||||
auth_manager,
|
||||
thread_manager,
|
||||
@@ -143,25 +74,9 @@ impl AccountRequestProcessor {
|
||||
config,
|
||||
config_manager,
|
||||
model_catalog,
|
||||
active_login: Arc::new(Mutex::new(None)),
|
||||
gateway_login: Arc::new(std::sync::Mutex::new(/*t*/ None)),
|
||||
gateway_clients: Arc::new(std::sync::Mutex::new(HashMap::new())),
|
||||
workspace_routing: Arc::new(Mutex::new(None)),
|
||||
workspace_routing_fetches: Arc::new(Mutex::new(HashMap::new())),
|
||||
workspace_routing_shutdown: CancellationToken::new(),
|
||||
enterprise_login,
|
||||
});
|
||||
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
|
||||
.read_account_for_background_workspace_routing()
|
||||
.await;
|
||||
});
|
||||
processor
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn login_account(
|
||||
@@ -199,15 +114,9 @@ impl AccountRequestProcessor {
|
||||
|
||||
pub(crate) async fn cancel_active_login(&self) {
|
||||
self.cancel_gateway_login();
|
||||
self.enterprise_login.cancel(/*login_id*/ None).await;
|
||||
let mut guard = self.active_login.lock().await;
|
||||
if let Some(active_login) = guard.take() {
|
||||
drop(active_login);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn clear_external_auth(&self) {
|
||||
self.workspace_routing_shutdown.cancel();
|
||||
self.auth_manager.clear_external_auth();
|
||||
}
|
||||
|
||||
@@ -218,7 +127,6 @@ impl AccountRequestProcessor {
|
||||
.as_ref()
|
||||
.map(CodexAuth::api_auth_mode)
|
||||
.map(auth_mode_to_api),
|
||||
plan_type: auth.as_ref().and_then(CodexAuth::account_plan_type),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,55 +144,15 @@ impl AccountRequestProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
async fn maybe_refresh_plugin_caches_for_current_config(
|
||||
/// Account changes alter app routing, so loaded plugin capabilities must be rebuilt.
|
||||
fn refresh_plugin_caches_after_account_change(
|
||||
config_manager: &ConfigManager,
|
||||
thread_manager: &Arc<ThreadManager>,
|
||||
auth: Option<CodexAuth>,
|
||||
) {
|
||||
thread_manager
|
||||
.plugins_manager()
|
||||
.clear_recommended_plugins_cache();
|
||||
|
||||
match config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await
|
||||
{
|
||||
Ok(config) => {
|
||||
let runtime_auth = thread_manager.runtime_auth_for_config(&config);
|
||||
Self::spawn_effective_plugins_changed_task(
|
||||
Arc::clone(thread_manager),
|
||||
config_manager.clone(),
|
||||
);
|
||||
let plugins_config = config.plugins_config_input();
|
||||
let refresh_thread_manager = Arc::clone(thread_manager);
|
||||
let refresh_config_manager = config_manager.clone();
|
||||
let on_effective_plugins_changed: Arc<
|
||||
dyn Fn(codex_core_plugins::EffectivePluginsChange) + Send + Sync,
|
||||
> = Arc::new(move |_change| {
|
||||
Self::spawn_effective_plugins_changed_task(
|
||||
Arc::clone(&refresh_thread_manager),
|
||||
refresh_config_manager.clone(),
|
||||
);
|
||||
});
|
||||
// aKode: no curated marketplace sync after account changes.
|
||||
if let Err(err) = runtime_auth {
|
||||
warn!("failed to initialize runtime auth for remote plugin refresh: {err}");
|
||||
return;
|
||||
}
|
||||
thread_manager
|
||||
.plugins_manager()
|
||||
.maybe_start_remote_plugin_caches_refresh(
|
||||
&plugins_config,
|
||||
auth,
|
||||
Some(on_effective_plugins_changed),
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"failed to reload config after account changed, skipping remote installed plugins cache refresh: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Self::spawn_effective_plugins_changed_task(
|
||||
Arc::clone(thread_manager),
|
||||
config_manager.clone(),
|
||||
);
|
||||
}
|
||||
|
||||
fn spawn_effective_plugins_changed_task(
|
||||
@@ -305,53 +173,11 @@ impl AccountRequestProcessor {
|
||||
request_id: ConnectionRequestId,
|
||||
params: LoginAccountParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
if self.auth_manager.is_workload_identity_selected() {
|
||||
return Err(self.configured_auth_owned_by_host_error());
|
||||
}
|
||||
self.enterprise_login.cancel(/*login_id*/ None).await;
|
||||
match params {
|
||||
LoginAccountParams::ApiKey { api_key } => {
|
||||
self.login_api_key_v2(request_id, LoginApiKeyParams { api_key })
|
||||
.await;
|
||||
}
|
||||
LoginAccountParams::Chatgpt {
|
||||
app_brand,
|
||||
codex_streamlined_login,
|
||||
use_hosted_login_success_page,
|
||||
} => {
|
||||
let login_success_page = if use_hosted_login_success_page {
|
||||
let app_brand = match app_brand.unwrap_or_default() {
|
||||
LoginAppBrand::Codex => LoginSuccessPageBrand::Codex,
|
||||
LoginAppBrand::Chatgpt => LoginSuccessPageBrand::Chatgpt,
|
||||
};
|
||||
LoginSuccessPage::Hosted {
|
||||
url: CODEX_OPEN_APP_URL.parse().map_err(|err| {
|
||||
internal_error(format!("invalid Codex open app URL: {err}"))
|
||||
})?,
|
||||
app_brand,
|
||||
}
|
||||
} else {
|
||||
LoginSuccessPage::default()
|
||||
};
|
||||
self.login_chatgpt_v2(request_id, codex_streamlined_login, login_success_page)
|
||||
.await;
|
||||
}
|
||||
LoginAccountParams::ChatgptDeviceCode => {
|
||||
self.login_chatgpt_device_code_v2(request_id).await;
|
||||
}
|
||||
LoginAccountParams::ChatgptAuthTokens {
|
||||
access_token,
|
||||
chatgpt_account_id,
|
||||
chatgpt_plan_type,
|
||||
} => {
|
||||
self.login_chatgpt_auth_tokens(
|
||||
request_id,
|
||||
access_token,
|
||||
chatgpt_account_id,
|
||||
chatgpt_plan_type,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
LoginAccountParams::AmazonBedrock { api_key, region } => {
|
||||
self.login_amazon_bedrock_v2(
|
||||
request_id,
|
||||
@@ -381,28 +207,10 @@ impl AccountRequestProcessor {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn external_auth_active_error(&self) -> JSONRPCErrorError {
|
||||
invalid_request(
|
||||
"External auth is active. Use account/login/start (chatgptAuthTokens) to update it or account/logout to clear it.",
|
||||
)
|
||||
}
|
||||
|
||||
fn configured_auth_owned_by_host_error(&self) -> JSONRPCErrorError {
|
||||
invalid_request(
|
||||
"Configured external authentication is owned by the app-server host and cannot be changed through account RPCs.",
|
||||
)
|
||||
}
|
||||
|
||||
fn ensure_provider_login_allowed(
|
||||
&self,
|
||||
provider: CloudLoginProvider,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
if self.auth_manager.is_workload_identity_selected() {
|
||||
return Err(self.configured_auth_owned_by_host_error());
|
||||
}
|
||||
if self.auth_manager.is_external_chatgpt_auth_active() {
|
||||
return Err(self.external_auth_active_error());
|
||||
}
|
||||
if !self
|
||||
.auth_manager
|
||||
.is_login_method_allowed(ForcedLoginMethod::Api)
|
||||
@@ -412,7 +220,7 @@ impl AccountRequestProcessor {
|
||||
CloudLoginProvider::Gcp => "Google Cloud setup",
|
||||
};
|
||||
return Err(invalid_request(format!(
|
||||
"{operation} is disabled. Use ChatGPT login instead."
|
||||
"{operation} is disabled by the configured login policy."
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
@@ -422,27 +230,15 @@ impl AccountRequestProcessor {
|
||||
&self,
|
||||
params: &LoginApiKeyParams,
|
||||
) -> std::result::Result<(), JSONRPCErrorError> {
|
||||
if self.auth_manager.is_external_chatgpt_auth_active() {
|
||||
return Err(self.external_auth_active_error());
|
||||
}
|
||||
|
||||
if !self
|
||||
.auth_manager
|
||||
.is_login_method_allowed(ForcedLoginMethod::Api)
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"API key login is disabled. Use ChatGPT login instead.",
|
||||
"API key login is disabled by the configured login policy.",
|
||||
));
|
||||
}
|
||||
|
||||
// Cancel any active login attempt.
|
||||
{
|
||||
let mut guard = self.active_login.lock().await;
|
||||
if let Some(active) = guard.take() {
|
||||
drop(active);
|
||||
}
|
||||
}
|
||||
|
||||
match login_with_api_key(
|
||||
&self.config.codex_home,
|
||||
¶ms.api_key,
|
||||
@@ -451,7 +247,6 @@ impl AccountRequestProcessor {
|
||||
) {
|
||||
Ok(()) => {
|
||||
self.auth_manager.reload().await;
|
||||
self.config_manager.clear_chatgpt_config_loader();
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => Err(internal_error(format!("failed to save api key: {err}"))),
|
||||
@@ -553,7 +348,6 @@ impl AccountRequestProcessor {
|
||||
}
|
||||
.map_err(|err| internal_error(format!("failed to save Amazon Bedrock auth: {err}")))?;
|
||||
self.auth_manager.reload().await;
|
||||
self.config_manager.clear_chatgpt_config_loader();
|
||||
Ok(LoginAccountResponse::AmazonBedrock {})
|
||||
}
|
||||
.await;
|
||||
@@ -569,340 +363,17 @@ impl AccountRequestProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
// Build options for a ChatGPT login attempt; performs validation.
|
||||
async fn login_chatgpt_common(
|
||||
&self,
|
||||
codex_streamlined_login: bool,
|
||||
login_success_page: LoginSuccessPage,
|
||||
) -> std::result::Result<LoginServerOptions, JSONRPCErrorError> {
|
||||
let config = self.config.as_ref();
|
||||
|
||||
if self.auth_manager.is_external_chatgpt_auth_active() {
|
||||
return Err(self.external_auth_active_error());
|
||||
}
|
||||
|
||||
if !self
|
||||
.auth_manager
|
||||
.is_login_method_allowed(ForcedLoginMethod::Chatgpt)
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"ChatGPT login is disabled. Use API key login instead.",
|
||||
));
|
||||
}
|
||||
|
||||
let mut opts = LoginServerOptions {
|
||||
open_browser: false,
|
||||
codex_streamlined_login,
|
||||
login_success_page,
|
||||
..LoginServerOptions::new(
|
||||
config.codex_home.to_path_buf(),
|
||||
oauth_client_id(),
|
||||
self.auth_manager.effective_chatgpt_workspaces(),
|
||||
config.cli_auth_credentials_store_mode,
|
||||
config.auth_keyring_backend_kind(),
|
||||
config.auth_route_config(),
|
||||
)
|
||||
};
|
||||
if let Ok(issuer) = std::env::var(LOGIN_ISSUER_OVERRIDE_ENV_VAR)
|
||||
&& !issuer.trim().is_empty()
|
||||
{
|
||||
opts.issuer = issuer;
|
||||
}
|
||||
#[cfg(debug_assertions)]
|
||||
if let LoginSuccessPage::Hosted { url, .. } = &mut opts.login_success_page
|
||||
&& let Ok(open_app_url) = std::env::var(LOGIN_OPEN_APP_URL_OVERRIDE_ENV_VAR)
|
||||
&& !open_app_url.trim().is_empty()
|
||||
{
|
||||
*url = open_app_url
|
||||
.parse()
|
||||
.map_err(|err| internal_error(format!("invalid Codex open app URL: {err}")))?;
|
||||
}
|
||||
|
||||
Ok(opts)
|
||||
}
|
||||
|
||||
fn login_chatgpt_device_code_start_error(err: IoError) -> JSONRPCErrorError {
|
||||
let is_not_found = err.kind() == std::io::ErrorKind::NotFound;
|
||||
if is_not_found {
|
||||
invalid_request(err.to_string())
|
||||
} else {
|
||||
internal_error(format!("failed to request device code: {err}"))
|
||||
}
|
||||
}
|
||||
|
||||
async fn login_chatgpt_v2(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
codex_streamlined_login: bool,
|
||||
login_success_page: LoginSuccessPage,
|
||||
) {
|
||||
let result = self
|
||||
.login_chatgpt_response(codex_streamlined_login, login_success_page)
|
||||
.await;
|
||||
self.outgoing.send_result(request_id, result).await;
|
||||
}
|
||||
|
||||
async fn login_chatgpt_response(
|
||||
&self,
|
||||
codex_streamlined_login: bool,
|
||||
login_success_page: LoginSuccessPage,
|
||||
) -> Result<LoginAccountResponse, JSONRPCErrorError> {
|
||||
let opts = self
|
||||
.login_chatgpt_common(codex_streamlined_login, login_success_page)
|
||||
.await?;
|
||||
let (login_id, auth_url) = self.start_browser_login(opts, /*pause*/ None).await?;
|
||||
Ok(LoginAccountResponse::Chatgpt { login_id, auth_url })
|
||||
}
|
||||
|
||||
async fn start_browser_login(
|
||||
&self,
|
||||
opts: LoginServerOptions,
|
||||
pause: Option<crate::turn_admission::TurnAdmissionPause>,
|
||||
) -> Result<(String, String), JSONRPCErrorError> {
|
||||
let server = run_login_server(opts)
|
||||
.map_err(|err| internal_error(format!("failed to start login server: {err}")))?;
|
||||
let login_id = Uuid::new_v4();
|
||||
let shutdown_handle = server.cancel_handle();
|
||||
|
||||
// Replace active login if present.
|
||||
{
|
||||
let mut guard = self.active_login.lock().await;
|
||||
if let Some(existing) = guard.take() {
|
||||
drop(existing);
|
||||
}
|
||||
*guard = Some(ActiveLogin::Browser {
|
||||
shutdown_handle: shutdown_handle.clone(),
|
||||
login_id,
|
||||
});
|
||||
}
|
||||
|
||||
let processor = self.clone();
|
||||
let active_login = self.active_login.clone();
|
||||
let auth_url = server.auth_url.clone();
|
||||
let task = async move {
|
||||
// Workspace credentials may change in the callback. Resume turns after caches and clients are updated.
|
||||
let _pause = pause;
|
||||
let (success, error_msg, onboarding_entrypoint) = match tokio::time::timeout(
|
||||
LOGIN_CHATGPT_TIMEOUT,
|
||||
server.block_until_done_with_callback_result(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(result)) => (
|
||||
true,
|
||||
None,
|
||||
result
|
||||
.onboarding_entrypoint
|
||||
.map(|LoginOnboardingEntrypoint::LifeSciences| {
|
||||
DesktopOnboardingEntrypoint::LifeSciences
|
||||
}),
|
||||
),
|
||||
Ok(Err(err)) => (false, Some(format!("Login server error: {err}")), None),
|
||||
Err(_elapsed) => {
|
||||
shutdown_handle.shutdown();
|
||||
(false, Some("Login timed out".to_string()), None)
|
||||
}
|
||||
};
|
||||
|
||||
processor
|
||||
.send_chatgpt_login_completion_notifications(AccountLoginCompletedNotification {
|
||||
login_id: Some(login_id.to_string()),
|
||||
success,
|
||||
error: error_msg,
|
||||
onboarding_entrypoint,
|
||||
})
|
||||
.await;
|
||||
|
||||
// Clear the active login if it matches this attempt. It may have been replaced or cancelled.
|
||||
let mut guard = active_login.lock().await;
|
||||
if guard.as_ref().map(ActiveLogin::login_id) == Some(login_id) {
|
||||
*guard = None;
|
||||
}
|
||||
};
|
||||
tokio::spawn(AuthStorageOriginator::current().scope(task));
|
||||
|
||||
Ok((login_id.to_string(), auth_url))
|
||||
}
|
||||
|
||||
async fn login_chatgpt_device_code_v2(&self, request_id: ConnectionRequestId) {
|
||||
let result = self.login_chatgpt_device_code_response().await;
|
||||
self.outgoing.send_result(request_id, result).await;
|
||||
}
|
||||
|
||||
async fn login_chatgpt_device_code_response(
|
||||
&self,
|
||||
) -> Result<LoginAccountResponse, JSONRPCErrorError> {
|
||||
let opts = self
|
||||
.login_chatgpt_common(
|
||||
/*codex_streamlined_login*/ false,
|
||||
LoginSuccessPage::default(),
|
||||
)
|
||||
.await?;
|
||||
let device_code = request_device_code(&opts)
|
||||
.await
|
||||
.map_err(Self::login_chatgpt_device_code_start_error)?;
|
||||
let login_id = Uuid::new_v4();
|
||||
let cancel = CancellationToken::new();
|
||||
|
||||
{
|
||||
let mut guard = self.active_login.lock().await;
|
||||
if let Some(existing) = guard.take() {
|
||||
drop(existing);
|
||||
}
|
||||
*guard = Some(ActiveLogin::DeviceCode {
|
||||
cancel: cancel.clone(),
|
||||
login_id,
|
||||
});
|
||||
}
|
||||
|
||||
let verification_url = device_code.verification_url.clone();
|
||||
let user_code = device_code.user_code.clone();
|
||||
|
||||
let processor = self.clone();
|
||||
let active_login = self.active_login.clone();
|
||||
let task = async move {
|
||||
let (success, error_msg) = tokio::select! {
|
||||
_ = cancel.cancelled() => {
|
||||
(false, Some("Login was not completed".to_string()))
|
||||
}
|
||||
r = complete_device_code_login(opts, device_code) => {
|
||||
match r {
|
||||
Ok(()) => (true, None),
|
||||
Err(err) => (false, Some(err.to_string())),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
processor
|
||||
.send_chatgpt_login_completion_notifications(AccountLoginCompletedNotification {
|
||||
login_id: Some(login_id.to_string()),
|
||||
success,
|
||||
error: error_msg,
|
||||
onboarding_entrypoint: None,
|
||||
})
|
||||
.await;
|
||||
|
||||
let mut guard = active_login.lock().await;
|
||||
if guard.as_ref().map(ActiveLogin::login_id) == Some(login_id) {
|
||||
*guard = None;
|
||||
}
|
||||
};
|
||||
tokio::spawn(AuthStorageOriginator::current().scope(task));
|
||||
|
||||
Ok(LoginAccountResponse::ChatgptDeviceCode {
|
||||
login_id: login_id.to_string(),
|
||||
verification_url,
|
||||
user_code,
|
||||
})
|
||||
}
|
||||
|
||||
async fn cancel_login_chatgpt_common(
|
||||
&self,
|
||||
login_id: Uuid,
|
||||
) -> std::result::Result<(), CancelLoginError> {
|
||||
let mut guard = self.active_login.lock().await;
|
||||
if guard.as_ref().map(ActiveLogin::login_id) == Some(login_id) {
|
||||
if let Some(active) = guard.take() {
|
||||
drop(active);
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CancelLoginError::NotFound)
|
||||
}
|
||||
}
|
||||
|
||||
async fn cancel_login_response(
|
||||
&self,
|
||||
params: CancelLoginAccountParams,
|
||||
) -> Result<CancelLoginAccountResponse, JSONRPCErrorError> {
|
||||
let login_id = params.login_id;
|
||||
let uuid = Uuid::parse_str(&login_id)
|
||||
Uuid::parse_str(&login_id)
|
||||
.map_err(|_| invalid_request(format!("invalid login id: {login_id}")))?;
|
||||
if self.enterprise_login.cancel(Some(&login_id)).await {
|
||||
return Ok(CancelLoginAccountResponse {
|
||||
status: CancelLoginAccountStatus::Canceled,
|
||||
});
|
||||
}
|
||||
let status = match self.cancel_login_chatgpt_common(uuid).await {
|
||||
Ok(()) => CancelLoginAccountStatus::Canceled,
|
||||
Err(CancelLoginError::NotFound) => CancelLoginAccountStatus::NotFound,
|
||||
};
|
||||
Ok(CancelLoginAccountResponse { status })
|
||||
}
|
||||
|
||||
async fn login_chatgpt_auth_tokens(
|
||||
&self,
|
||||
request_id: ConnectionRequestId,
|
||||
access_token: String,
|
||||
chatgpt_account_id: String,
|
||||
chatgpt_plan_type: Option<String>,
|
||||
) {
|
||||
let result = self
|
||||
.login_chatgpt_auth_tokens_response(access_token, chatgpt_account_id, chatgpt_plan_type)
|
||||
.await;
|
||||
let logged_in = result.is_ok();
|
||||
if logged_in {
|
||||
self.model_catalog.invalidate().await;
|
||||
}
|
||||
self.outgoing.send_result(request_id, result).await;
|
||||
|
||||
if logged_in {
|
||||
self.send_login_success_notifications(/*login_id*/ None)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn login_chatgpt_auth_tokens_response(
|
||||
&self,
|
||||
access_token: String,
|
||||
chatgpt_account_id: String,
|
||||
chatgpt_plan_type: Option<String>,
|
||||
) -> Result<LoginAccountResponse, JSONRPCErrorError> {
|
||||
if !self
|
||||
.auth_manager
|
||||
.is_login_method_allowed(ForcedLoginMethod::Chatgpt)
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"External ChatGPT auth is disabled. Use API key login instead.",
|
||||
));
|
||||
}
|
||||
|
||||
// Cancel any active login attempt to avoid persisting managed auth state.
|
||||
{
|
||||
let mut guard = self.active_login.lock().await;
|
||||
if let Some(active) = guard.take() {
|
||||
drop(active);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(expected_workspaces) = self.auth_manager.effective_chatgpt_workspaces()
|
||||
&& !expected_workspaces.contains(&chatgpt_account_id)
|
||||
{
|
||||
return Err(invalid_request(format!(
|
||||
"External auth must use one of workspace(s) {expected_workspaces:?}, but received {chatgpt_account_id:?}.",
|
||||
)));
|
||||
}
|
||||
|
||||
let auth = CodexAuth::from_external_chatgpt_tokens(
|
||||
&access_token,
|
||||
&chatgpt_account_id,
|
||||
chatgpt_plan_type.as_deref(),
|
||||
)
|
||||
.map_err(|err| internal_error(format!("failed to set external auth: {err}")))?;
|
||||
self.auth_manager
|
||||
.set_external_auth(Arc::new(ExternalAuthBridge::new(
|
||||
Arc::clone(&self.outgoing),
|
||||
auth,
|
||||
)))
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to set external auth: {err}")))?;
|
||||
self.config_manager
|
||||
.update_managed_config_loader(self.auth_manager.clone(), &self.config);
|
||||
self.config_manager
|
||||
.sync_default_client_residency_requirement()
|
||||
.await;
|
||||
|
||||
Ok(LoginAccountResponse::ChatgptAuthTokens {})
|
||||
// No account login flow is cancellable by id.
|
||||
Ok(CancelLoginAccountResponse {
|
||||
status: CancelLoginAccountStatus::NotFound,
|
||||
})
|
||||
}
|
||||
|
||||
async fn send_login_success_notifications(&self, login_id: Option<Uuid>) {
|
||||
@@ -911,7 +382,6 @@ impl AccountRequestProcessor {
|
||||
login_id: login_id.map(|id| id.to_string()),
|
||||
success: true,
|
||||
error: None,
|
||||
onboarding_entrypoint: None,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
@@ -923,18 +393,16 @@ 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.read_account(/*request*/ None).await
|
||||
&& let Err(error) = self.read_account().await
|
||||
{
|
||||
payload.success = false;
|
||||
payload.error = Some(error.to_string());
|
||||
}
|
||||
if payload.success && auth_changes.borrow().owner_generation == owner_generation {
|
||||
Self::maybe_refresh_plugin_caches_for_current_config(
|
||||
Self::refresh_plugin_caches_after_account_change(
|
||||
&self.config_manager,
|
||||
&self.thread_manager,
|
||||
self.auth_manager.auth_cached(),
|
||||
)
|
||||
.await;
|
||||
);
|
||||
}
|
||||
|
||||
let success = payload.success;
|
||||
@@ -960,35 +428,7 @@ impl AccountRequestProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
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.thread_manager.invalidate_mcp_runtimes().await;
|
||||
self.config_manager
|
||||
.update_managed_config_loader(self.auth_manager.clone(), &self.config);
|
||||
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());
|
||||
}
|
||||
}
|
||||
if payload_v2.success {
|
||||
self.model_catalog.invalidate().await;
|
||||
}
|
||||
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());
|
||||
}
|
||||
self.cancel_active_login().await;
|
||||
let config =
|
||||
logout_configured_account(&self.config_manager, &self.auth_manager, &self.config)
|
||||
@@ -997,14 +437,11 @@ impl AccountRequestProcessor {
|
||||
clear_account_configuration(&self.config_manager, &config).await?;
|
||||
|
||||
self.model_catalog.invalidate().await;
|
||||
*self.workspace_routing.lock().await = None;
|
||||
|
||||
Self::maybe_refresh_plugin_caches_for_current_config(
|
||||
Self::refresh_plugin_caches_after_account_change(
|
||||
&self.config_manager,
|
||||
&self.thread_manager,
|
||||
self.auth_manager.auth_cached(),
|
||||
)
|
||||
.await;
|
||||
);
|
||||
|
||||
// Reflect the current auth method after logout (likely None).
|
||||
Ok(self
|
||||
@@ -1017,15 +454,11 @@ impl AccountRequestProcessor {
|
||||
|
||||
async fn logout_v2(&self, request_id: ConnectionRequestId) -> Result<(), JSONRPCErrorError> {
|
||||
let result = self.logout_common().await;
|
||||
let account_updated =
|
||||
result
|
||||
.as_ref()
|
||||
.ok()
|
||||
.cloned()
|
||||
.map(|auth_mode| AccountUpdatedNotification {
|
||||
auth_mode,
|
||||
plan_type: None,
|
||||
});
|
||||
let account_updated = result
|
||||
.as_ref()
|
||||
.ok()
|
||||
.cloned()
|
||||
.map(|auth_mode| AccountUpdatedNotification { auth_mode });
|
||||
self.outgoing
|
||||
.send_result(request_id, result.map(|_| LogoutAccountResponse {}))
|
||||
.await;
|
||||
@@ -1039,9 +472,6 @@ impl AccountRequestProcessor {
|
||||
}
|
||||
|
||||
async fn refresh_token_if_requested(&self, do_refresh: bool) -> RefreshTokenRequestOutcome {
|
||||
if self.auth_manager.is_external_chatgpt_auth_active() {
|
||||
return RefreshTokenRequestOutcome::NotAttemptedOrSucceeded;
|
||||
}
|
||||
if do_refresh && let Err(err) = self.auth_manager.refresh_token().await {
|
||||
let failed_reason = err.failed_reason();
|
||||
if failed_reason.is_none() {
|
||||
@@ -1085,31 +515,24 @@ impl AccountRequestProcessor {
|
||||
let permanent_refresh_failure =
|
||||
self.auth_manager.refresh_failure_for_auth(&auth).is_some();
|
||||
let auth_mode = auth_mode_to_api(auth.api_auth_mode());
|
||||
let (reported_auth_method, token_opt) =
|
||||
if self.auth_manager.is_workload_identity_selected()
|
||||
|| matches!(
|
||||
auth,
|
||||
CodexAuth::Headers(_)
|
||||
| CodexAuth::AgentIdentity(_)
|
||||
| CodexAuth::PersonalAccessToken(_)
|
||||
)
|
||||
|| include_token && permanent_refresh_failure
|
||||
{
|
||||
// Host-owned and metadata-bearing credentials are never exported.
|
||||
(Some(auth_mode), None)
|
||||
} else {
|
||||
match auth.get_token() {
|
||||
Ok(token) if !token.is_empty() => {
|
||||
let tok = if include_token { Some(token) } else { None };
|
||||
(Some(auth_mode), tok)
|
||||
}
|
||||
Ok(_) => (None, None),
|
||||
Err(err) => {
|
||||
tracing::warn!("failed to get token for auth status: {err}");
|
||||
(None, None)
|
||||
}
|
||||
let (reported_auth_method, token_opt) = if matches!(auth, CodexAuth::Headers(_))
|
||||
|| include_token && permanent_refresh_failure
|
||||
{
|
||||
// Host-owned and metadata-bearing credentials are never exported.
|
||||
(Some(auth_mode), None)
|
||||
} else {
|
||||
match auth.get_token() {
|
||||
Ok(token) if !token.is_empty() => {
|
||||
let tok = if include_token { Some(token) } else { None };
|
||||
(Some(auth_mode), tok)
|
||||
}
|
||||
};
|
||||
Ok(_) => (None, None),
|
||||
Err(err) => {
|
||||
tracing::warn!("failed to get token for auth status: {err}");
|
||||
(None, None)
|
||||
}
|
||||
}
|
||||
};
|
||||
GetAuthStatusResponse {
|
||||
auth_method: reported_auth_method,
|
||||
auth_token: token_opt,
|
||||
@@ -1134,60 +557,23 @@ pub(crate) async fn logout_configured_account(
|
||||
auth_manager: &Arc<AuthManager>,
|
||||
fallback_config: &Config,
|
||||
) -> Result<Config, JSONRPCErrorError> {
|
||||
// Another process may have changed the persisted workspace. Reload both
|
||||
// Another process may have changed the persisted credentials. Reload both
|
||||
// account authority and its policy before selecting a grant to remove.
|
||||
auth_manager
|
||||
.reload_with_cached_auth()
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("logout failed: {err}")))?;
|
||||
config_manager.update_managed_config_loader(Arc::clone(auth_manager), fallback_config);
|
||||
let config = config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
.await;
|
||||
let scope = ema_auth_scope(auth_manager.auth_cached().as_ref());
|
||||
let enterprise_policy_failed = scope.is_some() && config.is_err();
|
||||
// Startup policy may belong to another workspace. Never use that fallback
|
||||
// to select a credential; a policy failure must not block primary logout.
|
||||
let enterprise_grant = config.as_ref().ok().and_then(|config| {
|
||||
scope
|
||||
.as_ref()
|
||||
.zip(config.mcp_enterprise_managed_auth.as_ref())
|
||||
.map(|(scope, profile)| {
|
||||
(
|
||||
profile.idp.credential_name(scope),
|
||||
profile.idp.issuer.clone(),
|
||||
config.auth_keyring_backend_kind(),
|
||||
)
|
||||
})
|
||||
});
|
||||
let config = config.unwrap_or_else(|_| fallback_config.clone());
|
||||
|
||||
// Retain the credential lock through primary logout. Otherwise a second
|
||||
// process can commit after deletion but before the account is removed.
|
||||
let enterprise_guard =
|
||||
if let Some((credential_name, issuer, keyring_backend)) = enterprise_grant {
|
||||
EnterpriseOAuthCredentialGuard::acquire(&credential_name, &issuer, keyring_backend)
|
||||
.await
|
||||
.map(Some)
|
||||
} else {
|
||||
Ok(None)
|
||||
};
|
||||
let cleanup_failed = match &enterprise_guard {
|
||||
Ok(Some(guard)) => guard.delete_tokens().is_err(),
|
||||
Ok(None) => false,
|
||||
Err(_) => true,
|
||||
};
|
||||
if enterprise_policy_failed || cleanup_failed {
|
||||
tracing::warn!("Failed to remove enterprise authorization; continuing account logout");
|
||||
}
|
||||
|
||||
match auth_manager.logout_with_revoke().await {
|
||||
match auth_manager.logout().await {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
return Err(internal_error(format!("logout failed: {err}")));
|
||||
}
|
||||
}
|
||||
drop(enterprise_guard);
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
@@ -1196,7 +582,6 @@ pub(crate) async fn clear_account_configuration(
|
||||
config_manager: &ConfigManager,
|
||||
config: &Config,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
config_manager.clear_chatgpt_config_loader();
|
||||
if config.model_provider.is_amazon_bedrock() {
|
||||
clear_user_model_provider_if_bedrock(config_manager, config).await?;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//! Reads the provider-reported account for the current configuration and credentials.
|
||||
|
||||
use super::*;
|
||||
use codex_model_provider::ProviderAccountError;
|
||||
use codex_model_provider::ProviderAccountState;
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(crate) async fn get_account(
|
||||
&self,
|
||||
_params: GetAccountParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let account_state = self
|
||||
.read_account()
|
||||
.await
|
||||
.map_err(|error| invalid_request(error.to_string()))?;
|
||||
Ok(Some(
|
||||
GetAccountResponse {
|
||||
account: account_state.account.map(Account::from),
|
||||
requires_openai_auth: account_state.requires_openai_auth,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn read_account(&self) -> Result<ProviderAccountState, ProviderAccountError> {
|
||||
let config = self.load_latest_config().await;
|
||||
create_model_provider(
|
||||
config.model_provider.clone(),
|
||||
Some(self.auth_manager.clone()),
|
||||
)
|
||||
.account_state()
|
||||
}
|
||||
}
|
||||
@@ -1,313 +0,0 @@
|
||||
//! Owns one explicit enterprise sign-in attempt for a configured MCP server.
|
||||
//! Start, replacement, cancellation, and local commit admission all pass through this state.
|
||||
//! The credential store separately fences logins invalidated by another process.
|
||||
|
||||
use super::*;
|
||||
use anyhow::Context;
|
||||
use codex_config::McpEmaRegistration;
|
||||
use codex_config::types::AuthKeyringBackendKind;
|
||||
use codex_mcp::ema_auth_scope;
|
||||
use codex_rmcp_client::EmaErrorDetail;
|
||||
use codex_rmcp_client::EnterpriseOAuthLoginRequest;
|
||||
use codex_rmcp_client::perform_enterprise_oauth_login_return_url;
|
||||
use futures::FutureExt;
|
||||
use tokio::sync::watch;
|
||||
|
||||
pub(crate) struct EnterpriseLoginTarget {
|
||||
pub(crate) thread_id: String,
|
||||
pub(crate) server_name: String,
|
||||
pub(crate) registration: McpEmaRegistration,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
pub(crate) enum EnterpriseLoginCompletion {
|
||||
Pending,
|
||||
Succeeded,
|
||||
Failed(EmaErrorDetail),
|
||||
}
|
||||
|
||||
impl EnterpriseLoginCompletion {
|
||||
pub(crate) fn is_complete(self) -> bool {
|
||||
matches!(self, Self::Succeeded | Self::Failed(_))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct EnterpriseLogin {
|
||||
pub(crate) login_id: String,
|
||||
pub(crate) authorization_url: String,
|
||||
pub(crate) completion: watch::Receiver<EnterpriseLoginCompletion>,
|
||||
}
|
||||
|
||||
pub(crate) struct EnterpriseLoginState {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config_manager: ConfigManager,
|
||||
// Cancellation and commit admission use this same lock. A cancelled attempt cannot commit.
|
||||
active: Mutex<Option<EnterpriseLoginAttempt>>,
|
||||
// Start and cancel hold this through callback shutdown; the worker never acquires it.
|
||||
start_gate: Mutex<()>,
|
||||
// Account changes cancel queued and running setup before waiting for start_gate.
|
||||
setup_cancel: Mutex<CancellationToken>,
|
||||
}
|
||||
|
||||
struct EnterpriseLoginAttempt {
|
||||
login_id: String,
|
||||
cancel: CancellationToken,
|
||||
completion: watch::Receiver<EnterpriseLoginCompletion>,
|
||||
}
|
||||
|
||||
impl Drop for EnterpriseLoginAttempt {
|
||||
fn drop(&mut self) {
|
||||
self.cancel.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
impl EnterpriseLoginState {
|
||||
pub(super) fn new(
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config_manager: ConfigManager,
|
||||
) -> Self {
|
||||
Self {
|
||||
auth_manager,
|
||||
thread_manager,
|
||||
config_manager,
|
||||
active: Mutex::new(None),
|
||||
start_gate: Mutex::new(()),
|
||||
setup_cancel: Mutex::new(CancellationToken::new()),
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "serialize start/cancel through callback shutdown; the worker uses a separate state lock"
|
||||
)]
|
||||
pub(super) async fn cancel(&self, login_id: Option<&str>) -> bool {
|
||||
if login_id.is_none() {
|
||||
let mut setup_cancel = self.setup_cancel.lock().await;
|
||||
setup_cancel.cancel();
|
||||
*setup_cancel = CancellationToken::new();
|
||||
}
|
||||
let (login_id, mut completion) = {
|
||||
let active = self.active.lock().await;
|
||||
if login_id.is_some_and(|id| active.as_ref().is_none_or(|a| a.login_id != id)) {
|
||||
return false;
|
||||
}
|
||||
let Some(attempt) = active.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
attempt.cancel.cancel();
|
||||
(attempt.login_id.clone(), attempt.completion.clone())
|
||||
};
|
||||
// A partial callback request can stall the blocking HTTP worker. Cancellation
|
||||
// already fences commit; primary logout must not wait indefinitely for I/O.
|
||||
if tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
let _start = self.start_gate.lock().await;
|
||||
completion.wait_for(|state| state.is_complete()).await
|
||||
})
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
self.clear(&login_id).await;
|
||||
}
|
||||
// Retain a timed-out attempt so a replacement still waits for port cleanup.
|
||||
true
|
||||
}
|
||||
|
||||
async fn clear(&self, login_id: &str) {
|
||||
let mut active = self.active.lock().await;
|
||||
if active
|
||||
.as_ref()
|
||||
.is_some_and(|attempt| attempt.login_id == login_id)
|
||||
{
|
||||
*active = None;
|
||||
}
|
||||
}
|
||||
|
||||
async fn configuration_is_current(
|
||||
&self,
|
||||
target: &EnterpriseLoginTarget,
|
||||
keyring_backend: AuthKeyringBackendKind,
|
||||
) -> bool {
|
||||
let Ok(thread_id) = ThreadId::from_string(&target.thread_id) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(thread) = self.thread_manager.get_thread(thread_id).await else {
|
||||
return false;
|
||||
};
|
||||
let current = thread.config().await;
|
||||
let Ok(config) = self
|
||||
.config_manager
|
||||
.load_latest_config_with_session_layers(¤t.config_layer_stack, ¤t.cwd)
|
||||
.await
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let config = thread.runtime_mcp_config_and_context(&config).await.0;
|
||||
let auth = self.auth_manager.auth_cached();
|
||||
let servers = codex_mcp::effective_mcp_servers(&config, auth.as_ref());
|
||||
config.xaa_enabled
|
||||
&& config.auth_keyring_backend_kind == keyring_backend
|
||||
&& servers.get(&target.server_name).is_some_and(|server| {
|
||||
server.config().enabled
|
||||
&& server.config().ema_registration() == Some(&target.registration)
|
||||
})
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "serialize start/cancel through callback shutdown; the worker uses a separate state lock"
|
||||
)]
|
||||
pub(crate) async fn start(
|
||||
self: &Arc<Self>,
|
||||
request: EnterpriseOAuthLoginRequest<'_>,
|
||||
scope: codex_config::McpEmaAuthScope,
|
||||
target: EnterpriseLoginTarget,
|
||||
) -> Result<EnterpriseLogin, JSONRPCErrorError> {
|
||||
// MCP requests are not in the account request queue. Serialize start and
|
||||
// cancellation here; the separate commit gate stays responsive to the worker.
|
||||
let setup_cancel = self.setup_cancel.lock().await.child_token();
|
||||
let _start = tokio::select! {
|
||||
biased;
|
||||
_ = setup_cancel.cancelled() => return Err(internal_error("enterprise sign-in was cancelled")),
|
||||
guard = self.start_gate.lock() => guard,
|
||||
};
|
||||
let previous = {
|
||||
let active = self.active.lock().await;
|
||||
// Keep the cancelled attempt installed until its callback worker closes.
|
||||
// A cancelled replacement request leaves the next start responsible for waiting.
|
||||
active.as_ref().map(|attempt| {
|
||||
attempt.cancel.cancel();
|
||||
(attempt.login_id.clone(), attempt.completion.clone())
|
||||
})
|
||||
};
|
||||
if let Some((login_id, mut completion)) = previous {
|
||||
// An abandoned setup request drops its flow and closes this channel.
|
||||
let _ = tokio::select! {
|
||||
biased;
|
||||
_ = setup_cancel.cancelled() => return Err(internal_error("enterprise sign-in was cancelled")),
|
||||
result = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(10),
|
||||
completion.wait_for(|state| state.is_complete()),
|
||||
) => result.map_err(|_| internal_error("previous enterprise sign-in did not close"))?,
|
||||
};
|
||||
self.clear(&login_id).await;
|
||||
}
|
||||
let login_generation = self
|
||||
.auth_manager
|
||||
.auth_change_state_receiver()
|
||||
.borrow()
|
||||
.login_generation;
|
||||
let account = self
|
||||
.auth_manager
|
||||
.auth_cached()
|
||||
.filter(|auth| ema_auth_scope(Some(auth)).as_ref() == Some(&scope))
|
||||
.ok_or_else(|| internal_error("Codex account changed during enterprise sign-in"))?;
|
||||
if !self
|
||||
.auth_manager
|
||||
.account_login_is_current(&account)
|
||||
.await
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err(internal_error(
|
||||
"Codex account changed during enterprise sign-in",
|
||||
));
|
||||
}
|
||||
let keyring_backend = request.keyring_backend_kind;
|
||||
// Keep commit cancellation under `active`; cancelling the setup epoch must
|
||||
// not race an already-admitted synchronous credential write.
|
||||
let cancel = CancellationToken::new();
|
||||
let login_id = Uuid::new_v4().to_string();
|
||||
let (completed, completion) = watch::channel(EnterpriseLoginCompletion::Pending);
|
||||
*self.active.lock().await = Some(EnterpriseLoginAttempt {
|
||||
login_id: login_id.clone(),
|
||||
cancel: cancel.clone(),
|
||||
completion: completion.clone(),
|
||||
});
|
||||
let handle = tokio::select! {
|
||||
biased;
|
||||
_ = setup_cancel.cancelled() => Err(internal_error("enterprise sign-in was cancelled")),
|
||||
_ = cancel.cancelled() => Err(internal_error("enterprise sign-in was cancelled")),
|
||||
result = perform_enterprise_oauth_login_return_url(request) =>
|
||||
result.map_err(|error| internal_error(
|
||||
EmaErrorDetail::from_error(
|
||||
&error.context(EmaErrorDetail::new("failed to start enterprise sign-in")),
|
||||
).to_string(),
|
||||
)),
|
||||
};
|
||||
let handle = match handle {
|
||||
Ok(handle) => handle,
|
||||
Err(error) => {
|
||||
self.clear(&login_id).await;
|
||||
completed.send_replace(EnterpriseLoginCompletion::Failed(EmaErrorDetail::new(
|
||||
"failed to start enterprise sign-in",
|
||||
)));
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let callback_closed = handle.callback_closed().shared();
|
||||
let authorization_url = handle.authorization_url();
|
||||
let lifecycle = Arc::clone(self);
|
||||
let completion_id = login_id.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() =>
|
||||
Err(EmaErrorDetail::new("Enterprise sign-in was cancelled.").into()),
|
||||
result = async {
|
||||
let credentials = handle.wait().await.context(EmaErrorDetail::new(
|
||||
"Enterprise sign-in authorization failed.",
|
||||
))?;
|
||||
callback_closed.clone().await;
|
||||
let mut active = credentials.commit_if(|| async {
|
||||
lifecycle.auth_manager.reload().await;
|
||||
let eligible = lifecycle.auth_manager.account_login_is_current(&account).await.unwrap_or(false)
|
||||
&& lifecycle.configuration_is_current(&target, keyring_backend).await;
|
||||
// Reread persisted account authority after acquiring the credential
|
||||
// lock, including changes made by another app-server process.
|
||||
lifecycle.auth_manager.reload().await;
|
||||
if !eligible || !lifecycle.auth_manager.account_login_is_current(&account).await.unwrap_or(false) {
|
||||
return None;
|
||||
}
|
||||
// Keep cancellation responsive during the async checks above.
|
||||
// Once admitted, retain this guard through the synchronous write.
|
||||
let active = lifecycle.active.lock().await;
|
||||
let current = active.as_ref().is_some_and(|attempt| {
|
||||
attempt.login_id == completion_id && !attempt.cancel.is_cancelled()
|
||||
})
|
||||
&& lifecycle.auth_manager.auth_change_state_receiver().borrow().login_generation == login_generation
|
||||
&& ema_auth_scope(lifecycle.auth_manager.auth_cached().as_ref()).as_ref() == Some(&scope);
|
||||
if !current {
|
||||
return None;
|
||||
}
|
||||
// The credential lock is held: revoke cached bearers before replacing
|
||||
// the grant, and let new threads pin only the committed credential.
|
||||
lifecycle.config_manager.revoke_mcp_ema();
|
||||
Some(active)
|
||||
}).await.context(EmaErrorDetail::new(
|
||||
"Enterprise sign-in credential commit failed.",
|
||||
))?;
|
||||
// A successful commit is no longer cancelable. Clear it while
|
||||
// still holding the commit gate.
|
||||
*active = None;
|
||||
Ok(())
|
||||
} => result,
|
||||
};
|
||||
// The canceled wait future has dropped its listener guard. Also wait
|
||||
// for the blocking callback worker before allowing a fixed-port retry.
|
||||
callback_closed.await;
|
||||
if result.is_err() {
|
||||
lifecycle.clear(&completion_id).await;
|
||||
}
|
||||
completed.send_replace(match result {
|
||||
Ok(()) => EnterpriseLoginCompletion::Succeeded,
|
||||
Err(error) => EnterpriseLoginCompletion::Failed(EmaErrorDetail::from_error(&error)),
|
||||
});
|
||||
});
|
||||
Ok(EnterpriseLogin {
|
||||
login_id,
|
||||
authorization_url,
|
||||
completion,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,115 +1,10 @@
|
||||
//! Keep optional security reminders on the app-server's existing runtime identity.
|
||||
//! Only saved ChatGPT credentials matching the active login may fetch a notice.
|
||||
//! Security reminders are a ChatGPT account feature; aKode credentials never have one.
|
||||
|
||||
use super::*;
|
||||
use codex_app_server_protocol::AccountSecuritySetupAction;
|
||||
use codex_app_server_protocol::AccountSecuritySetupNotice;
|
||||
use codex_app_server_protocol::GetAccountSecuritySetupResponse;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Response {
|
||||
notice: Option<Notice>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Notice {
|
||||
title: String,
|
||||
description: String,
|
||||
action: AccountSecuritySetupAction,
|
||||
}
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(crate) async fn get_account_security_setup(&self) -> GetAccountSecuritySetupResponse {
|
||||
let notice = tokio::time::timeout(Duration::from_secs(/*secs*/ 3), async {
|
||||
let config = self.load_latest_config().await;
|
||||
let (auth, factory) = self.auth_manager.auth_with_http_client_factory().await?;
|
||||
let source_generation = self
|
||||
.auth_manager
|
||||
.auth_change_state_for(&auth)?
|
||||
.source_generation;
|
||||
let saved = config
|
||||
.auth_config()
|
||||
.load_auth(/*enable_codex_api_key_env*/ false)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()?;
|
||||
if !matches!(saved, CodexAuth::Chatgpt(_)) || saved.is_fedramp_account() {
|
||||
return None;
|
||||
}
|
||||
if auth.auth_mode() != codex_protocol::auth::AuthMode::Chatgpt
|
||||
|| saved.get_token().ok()? != auth.get_token().ok()?
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let account_id = auth.get_account_id()?;
|
||||
let user_id = auth.get_chatgpt_user_id()?;
|
||||
let url = format!(
|
||||
"{}/wham/security-setup",
|
||||
config.chatgpt_base_url.trim_end_matches('/')
|
||||
);
|
||||
let runtime = self
|
||||
.thread_manager
|
||||
.runtime_auth_for_config(&config)
|
||||
.ok()?
|
||||
.filter(|_| codex_runtime_agent_instance::is_openai_api_url(&url));
|
||||
let resolved = codex_model_provider::auth_provider_for_request(
|
||||
&auth,
|
||||
runtime.as_ref(),
|
||||
/*headers*/ &Default::default(),
|
||||
)
|
||||
.await
|
||||
.ok()?;
|
||||
let factory = resolved.bind_http_client_factory(factory).ok()?;
|
||||
let client =
|
||||
RouteAwareClientPool::new_without_redirects(factory, ClientRouteClass::Api);
|
||||
let mut headers = resolved
|
||||
.auth
|
||||
.apply_auth_headers(Default::default())
|
||||
.await
|
||||
.ok()?;
|
||||
headers.insert("chatgpt-account-id", account_id.parse().ok()?);
|
||||
resolved.validate_headers(&headers).ok()?;
|
||||
let response = client
|
||||
.get(&url)
|
||||
.headers(headers)
|
||||
.header(
|
||||
"User-Agent",
|
||||
codex_login::default_client::get_codex_user_agent(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.ok()?;
|
||||
if !response.status().is_success() {
|
||||
return None;
|
||||
}
|
||||
let notice = response.json::<Response>().await.ok()?.notice?;
|
||||
let current = self.auth_manager.auth().await?;
|
||||
if self
|
||||
.auth_manager
|
||||
.auth_change_state_for(&auth)?
|
||||
.source_generation
|
||||
!= source_generation
|
||||
|| current.auth_mode() != codex_protocol::auth::AuthMode::Chatgpt
|
||||
|| current.get_account_id().as_ref() != Some(&account_id)
|
||||
|| current.get_chatgpt_user_id().as_ref() != Some(&user_id)
|
||||
|| current.is_fedramp_account()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(AccountSecuritySetupNotice {
|
||||
account_id,
|
||||
user_id,
|
||||
title: notice.title,
|
||||
description: notice.description,
|
||||
action: notice.action,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten();
|
||||
GetAccountSecuritySetupResponse { notice }
|
||||
GetAccountSecuritySetupResponse { notice: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,641 +0,0 @@
|
||||
//! 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_backend_client::AccountEntry;
|
||||
use codex_config::ConfigLoadError;
|
||||
use codex_http_client::NetworkPolicyDenied;
|
||||
use codex_login::RefreshTokenError;
|
||||
use codex_login::WorkspaceRouting;
|
||||
use codex_login::WorkspaceRoutingRequest;
|
||||
use codex_login::WorkspaceRoutingResolver;
|
||||
use codex_login::auth::RefreshTokenFailedError;
|
||||
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;
|
||||
|
||||
#[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<CachedWorkspaceRouting>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct CachedWorkspaceRouting {
|
||||
key: WorkspaceRoutingKey,
|
||||
routing: WorkspaceRouting,
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) struct AccountRead {
|
||||
account_state: ProviderAccountState,
|
||||
user_id: Option<String>,
|
||||
pub(super) workspace_routing: Option<WorkspaceRouting>,
|
||||
workspace_name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub(super) enum AccountReadError {
|
||||
#[error(transparent)]
|
||||
InvalidAccount(#[from] ProviderAccountError),
|
||||
#[error(transparent)]
|
||||
Routing(#[from] WorkspaceRoutingError),
|
||||
}
|
||||
|
||||
/// Routing failures carry no account, URL, or backend data. Config failures retain
|
||||
/// only a location or structured error category, never the raw config error.
|
||||
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub(super) enum WorkspaceRoutingError {
|
||||
#[error("failed to load workspace requirements: {0}")]
|
||||
RequirementsLoad(String),
|
||||
#[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(transparent)]
|
||||
RefreshTokenRejected(RefreshTokenFailedError),
|
||||
#[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: {0}")]
|
||||
RequirementsReload(String),
|
||||
#[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,
|
||||
}
|
||||
|
||||
fn workspace_config_load_reason(error: &io::Error) -> String {
|
||||
// Parser messages and cloud bundle errors can quote secrets, even without
|
||||
// their source snippets. Retain only structured diagnostics before these
|
||||
// errors reach JSON-RPC clients, login notifications, or tracing.
|
||||
let mut current = error
|
||||
.get_ref()
|
||||
.map(|source| source as &(dyn std::error::Error + 'static));
|
||||
while let Some(source) = current {
|
||||
if let Some(config) = source.downcast_ref::<ConfigLoadError>() {
|
||||
let config = config.config_error();
|
||||
let start = config.range.start;
|
||||
// Non-file diagnostics store a display name, which can contain
|
||||
// backend-supplied policy names and IDs, in this field.
|
||||
if !config.path.is_absolute() {
|
||||
return format!(
|
||||
"invalid non-file configuration at line {}, column {}",
|
||||
start.line, start.column
|
||||
);
|
||||
}
|
||||
return format!(
|
||||
"invalid configuration at {}:{}:{}",
|
||||
config.path.display(),
|
||||
start.line,
|
||||
start.column
|
||||
);
|
||||
}
|
||||
if let Some(cloud) = source.downcast_ref::<CloudConfigBundleLoadError>() {
|
||||
let reason = match cloud.code() {
|
||||
CloudConfigBundleLoadErrorCode::Timeout => "request timed out",
|
||||
CloudConfigBundleLoadErrorCode::Auth
|
||||
| CloudConfigBundleLoadErrorCode::RequestFailed => {
|
||||
// Cloud loading currently erases the typed denial. Match
|
||||
// only known safe policy messages, never forward raw text.
|
||||
let message = cloud.to_string();
|
||||
if let Some(policy) = [
|
||||
NetworkPolicyDenied::Unavailable,
|
||||
NetworkPolicyDenied::Destination,
|
||||
NetworkPolicyDenied::Revoked,
|
||||
NetworkPolicyDenied::UnsupportedTransport,
|
||||
]
|
||||
.into_iter()
|
||||
.find(|policy| policy.to_string() == message)
|
||||
{
|
||||
return policy.to_string();
|
||||
}
|
||||
if cloud.code() == CloudConfigBundleLoadErrorCode::Auth {
|
||||
"authentication failed"
|
||||
} else {
|
||||
"request failed"
|
||||
}
|
||||
}
|
||||
CloudConfigBundleLoadErrorCode::InvalidBundle => "invalid bundle",
|
||||
CloudConfigBundleLoadErrorCode::Internal => "internal error",
|
||||
};
|
||||
return match cloud.status_code() {
|
||||
Some(status) => format!("cloud config: {reason} (HTTP {status})"),
|
||||
None => format!("cloud config: {reason}"),
|
||||
};
|
||||
}
|
||||
if let Some(policy) = source.downcast_ref::<NetworkPolicyDenied>() {
|
||||
return policy.to_string();
|
||||
}
|
||||
current = source.source();
|
||||
}
|
||||
// Use the OS error or kind, never an untyped error's potentially secret message.
|
||||
match error.raw_os_error() {
|
||||
Some(code) => io::Error::from_raw_os_error(code).to_string(),
|
||||
None => error.kind().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
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(WorkspaceRoutingError::RefreshTokenRejected(
|
||||
error,
|
||||
)) => io::Error::new(io::ErrorKind::PermissionDenied, error),
|
||||
AccountReadError::Routing(error) => io::Error::new(
|
||||
if error == WorkspaceRoutingError::DiscoveryUnauthorized {
|
||||
io::ErrorKind::PermissionDenied
|
||||
} else {
|
||||
io::ErrorKind::Other
|
||||
},
|
||||
error,
|
||||
),
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(super) async fn read_account_for_background_workspace_routing(
|
||||
&self,
|
||||
) -> Result<Option<AccountRead>, AccountReadError> {
|
||||
if !self
|
||||
.auth_manager
|
||||
.auth_cached()
|
||||
.as_ref()
|
||||
.is_some_and(CodexAuth::is_chatgpt_auth)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
self.read_account(/*request*/ None).await.map(Some)
|
||||
}
|
||||
|
||||
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(Some(response)) = processor
|
||||
.read_account_for_background_workspace_routing()
|
||||
.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(crate) async fn get_account(
|
||||
&self,
|
||||
params: GetAccountParams,
|
||||
) -> 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()),
|
||||
})?;
|
||||
let mut account = read.account_state.account.map(Account::from);
|
||||
if let Some(Account::Chatgpt { workspace_name, .. }) = &mut account {
|
||||
*workspace_name = read.workspace_name;
|
||||
}
|
||||
Ok(Some(
|
||||
GetAccountResponse {
|
||||
account,
|
||||
user_id: read.user_id,
|
||||
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 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
|
||||
.auth_manager
|
||||
.auth_cached()
|
||||
.as_ref()
|
||||
.is_some_and(CodexAuth::is_chatgpt_auth) =>
|
||||
{
|
||||
self.config.as_ref().clone()
|
||||
}
|
||||
Err(error) => {
|
||||
return Err(WorkspaceRoutingError::RequirementsLoad(
|
||||
workspace_config_load_reason(&error),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
};
|
||||
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(AccountReadError::InvalidAccount)?;
|
||||
let user_id = auth
|
||||
.as_ref()
|
||||
.filter(|_| {
|
||||
matches!(
|
||||
&account_state.account,
|
||||
Some(ProviderAccount::Chatgpt { .. })
|
||||
)
|
||||
})
|
||||
.and_then(CodexAuth::get_chatgpt_user_id);
|
||||
let mut workspace_routing = if let Some((auth, account_id)) = auth
|
||||
.as_ref()
|
||||
.filter(|auth| {
|
||||
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(WorkspaceRoutingError::MissingAccountId.into());
|
||||
}
|
||||
let required_chatgpt_base_url = config
|
||||
.config_layer_stack
|
||||
.requirements_toml()
|
||||
.chatgpt_base_url
|
||||
.clone();
|
||||
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
|
||||
.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
|
||||
.as_ref()
|
||||
.filter(|cached| cached.key == key)
|
||||
.cloned(),
|
||||
};
|
||||
let routing = if let Some(cached) = cached {
|
||||
cached
|
||||
} else {
|
||||
let runtime = self
|
||||
.thread_manager
|
||||
.runtime_auth_for_config(&config)
|
||||
.map_err(|_| WorkspaceRoutingError::DiscoveryFailed)?;
|
||||
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_with_runtime(
|
||||
&config.chatgpt_base_url,
|
||||
&discovery_auth,
|
||||
config.http_client_factory(),
|
||||
runtime.as_ref(),
|
||||
/*headers*/ &Default::default(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| WorkspaceRoutingError::DiscoveryFailed)?;
|
||||
match client.get_accounts_check().await {
|
||||
Ok(response) => break response,
|
||||
Err(error) => {
|
||||
let unauthorized = error.is_unauthorized();
|
||||
if unauthorized && recovery.has_next() {
|
||||
let result = recovery.next().await;
|
||||
let refreshed = *current_auth_changes.borrow();
|
||||
if refreshed.owner_generation != auth_state.owner_generation {
|
||||
return Err(WorkspaceRoutingError::AccountChanged.into());
|
||||
}
|
||||
if let Err(error) = result
|
||||
&& refreshed.generation == discovery_generation
|
||||
{
|
||||
let cached_failure = self
|
||||
.auth_manager
|
||||
.refresh_failure_for_auth(&discovery_auth);
|
||||
if let RefreshTokenError::Permanent(failed) = error
|
||||
&& !self.auth_manager.has_external_auth()
|
||||
&& cached_failure.as_ref() == Some(&failed)
|
||||
{
|
||||
return Err(
|
||||
WorkspaceRoutingError::RefreshTokenRejected(failed)
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
return Err(
|
||||
WorkspaceRoutingError::DiscoveryUnauthorized.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 mut entry = accounts
|
||||
.next()
|
||||
.ok_or(WorkspaceRoutingError::MissingWorkspace)?;
|
||||
if accounts.next().is_some() {
|
||||
return Err(WorkspaceRoutingError::DuplicateWorkspace.into());
|
||||
}
|
||||
let latest_config = load_config().await.map_err(|error| {
|
||||
WorkspaceRoutingError::RequirementsReload(workspace_config_load_reason(
|
||||
&error,
|
||||
))
|
||||
})?;
|
||||
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(WorkspaceRoutingError::ConfigurationChanged.into());
|
||||
}
|
||||
let name = entry.name.take();
|
||||
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(WorkspaceRoutingError::AccountChanged.into());
|
||||
}
|
||||
let routing = CachedWorkspaceRouting {
|
||||
key: WorkspaceRoutingKey {
|
||||
auth_generation: discovery_generation,
|
||||
..key
|
||||
},
|
||||
routing,
|
||||
name,
|
||||
};
|
||||
// Same-owner refresh can complete a newer discovery first.
|
||||
if current_auth_changes.borrow().generation == discovery_generation {
|
||||
*cached = Some(routing.clone());
|
||||
}
|
||||
routing
|
||||
};
|
||||
*fetch.routing.lock().await = Some(routing.clone());
|
||||
Some(routing)
|
||||
} else {
|
||||
*self.workspace_routing.lock().await = None;
|
||||
None
|
||||
};
|
||||
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.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());
|
||||
}
|
||||
}
|
||||
let (workspace_routing, workspace_name) = workspace_routing
|
||||
.map(|workspace| (Some(workspace.routing), workspace.name))
|
||||
.unwrap_or_default();
|
||||
Ok(AccountRead {
|
||||
account_state,
|
||||
user_id,
|
||||
workspace_routing,
|
||||
workspace_name,
|
||||
})
|
||||
});
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = self.workspace_routing_shutdown.cancelled() => {
|
||||
return Err(WorkspaceRoutingError::Shutdown.into());
|
||||
}
|
||||
_ = auth_changes.wait_for(|state| state.owner_generation != auth_state.owner_generation) => {
|
||||
return Err(WorkspaceRoutingError::AccountChanged.into());
|
||||
}
|
||||
result = tokio::time::timeout(Duration::from_secs(/*secs*/ 15), read) => {
|
||||
result.map_err(|_| WorkspaceRoutingError::DiscoveryTimeout)?
|
||||
}
|
||||
};
|
||||
if auth_changes.borrow().owner_generation != auth_state.owner_generation {
|
||||
return Err(WorkspaceRoutingError::AccountChanged.into());
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_routing(
|
||||
entry: AccountEntry,
|
||||
required_chatgpt_base_url: Option<&str>,
|
||||
effective_base_url: &str,
|
||||
) -> Result<WorkspaceRouting, AccountReadError> {
|
||||
let backend = entry
|
||||
.workspace_backend_origin
|
||||
.ok_or(WorkspaceRoutingError::MissingBackendOrigin)?;
|
||||
let account_routing_override = match entry.account_routing_override.as_deref() {
|
||||
Some(value @ ("NO_CONSTRAINT" | "us" | "us_cr")) => value.to_owned(),
|
||||
_ => {
|
||||
return Err(WorkspaceRoutingError::InvalidRoutingOverride.into());
|
||||
}
|
||||
};
|
||||
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(WorkspaceRoutingError::BackendIsNotOrigin.into());
|
||||
}
|
||||
Some(url)
|
||||
};
|
||||
let origin = match (required, discovered) {
|
||||
(Some(required), Some(discovered)) => {
|
||||
if required.origin() != discovered.origin() {
|
||||
return Err(WorkspaceRoutingError::BackendConflict.into());
|
||||
}
|
||||
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, 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(WorkspaceRoutingError::InvalidBackendOrigin.into());
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "workspace_routing_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,243 +0,0 @@
|
||||
//! Origin resolution, strict discovery validation, and background read eligibility.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use test_case::test_case;
|
||||
|
||||
#[test_case(CloudConfigBundleLoadErrorCode::RequestFailed, "cloud config: request failed"; "request")]
|
||||
#[test_case(CloudConfigBundleLoadErrorCode::Auth, "cloud config: authentication failed"; "refresh")]
|
||||
fn cloud_failures_preserve_policy_denials_but_redact_other_messages(
|
||||
code: CloudConfigBundleLoadErrorCode,
|
||||
redacted: &str,
|
||||
) {
|
||||
let denied = NetworkPolicyDenied::Destination.to_string();
|
||||
for (message, expected) in [
|
||||
(denied.clone(), denied),
|
||||
(
|
||||
"destination denied by application network policy: sk-test-private-value".into(),
|
||||
redacted.into(),
|
||||
),
|
||||
] {
|
||||
let error = io::Error::other(CloudConfigBundleLoadError::new(
|
||||
code, /*status_code*/ None, message,
|
||||
));
|
||||
assert_eq!(workspace_config_load_reason(&error), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test_case(None; "signed_out")]
|
||||
#[test_case(Some("dummy"); "api_key")]
|
||||
#[tokio::test]
|
||||
async fn background_routing_skips_config_until_chatgpt_sign_in(
|
||||
api_key: Option<&str>,
|
||||
) -> anyhow::Result<()> {
|
||||
use app_test_support::ChatGptAuthFixture;
|
||||
use app_test_support::write_chatgpt_auth;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let home = tempfile::tempdir()?;
|
||||
let backend = wiremock::MockServer::start().await;
|
||||
app_test_support::mount_workspace_routing(&backend).await;
|
||||
let loads = Arc::new(AtomicUsize::new(/*v*/ 0));
|
||||
let calls = Arc::clone(&loads);
|
||||
let loader = CloudConfigBundleLoader::from_getter(move || {
|
||||
calls.fetch_add(/*val*/ 1, Ordering::SeqCst);
|
||||
async { Ok(None) }
|
||||
});
|
||||
let manager = ConfigManager::new_for_tests(
|
||||
home.path().to_path_buf(),
|
||||
vec![(
|
||||
"chatgpt_base_url".into(),
|
||||
format!("{}/backend-api", backend.uri()).into(),
|
||||
)],
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
loader,
|
||||
);
|
||||
let config = Arc::new(
|
||||
manager
|
||||
.load_latest_config(Some(home.path().to_path_buf()))
|
||||
.await?,
|
||||
);
|
||||
if let Some(api_key) = api_key {
|
||||
codex_login::login_with_api_key(
|
||||
home.path(),
|
||||
api_key,
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)?;
|
||||
}
|
||||
let auth_manager = Arc::new(
|
||||
AuthManager::new(
|
||||
home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
Some(config.chatgpt_base_url.clone()),
|
||||
AuthKeyringBackendKind::default(),
|
||||
config.auth_config().auth_route_config,
|
||||
)
|
||||
.await,
|
||||
);
|
||||
let threads = Arc::new(
|
||||
codex_core::test_support::thread_manager_with_models_provider_and_home(
|
||||
CodexAuth::from_api_key("dummy"),
|
||||
config.model_provider.clone(),
|
||||
config.codex_home.to_path_buf(),
|
||||
Arc::new(EnvironmentManager::default_for_tests()),
|
||||
),
|
||||
);
|
||||
let (sender, _receiver) = tokio::sync::mpsc::channel(16);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(sender));
|
||||
let model_catalog = Arc::new(crate::model_catalog::ModelCatalog::new(
|
||||
manager.clone(),
|
||||
Some(config.cwd.to_path_buf()),
|
||||
Arc::clone(&config),
|
||||
Arc::clone(&threads),
|
||||
));
|
||||
let processor = AccountRequestProcessor::new(
|
||||
Arc::clone(&auth_manager),
|
||||
threads,
|
||||
outgoing,
|
||||
config,
|
||||
manager,
|
||||
model_catalog,
|
||||
);
|
||||
let initial_loads = loads.load(Ordering::SeqCst);
|
||||
for _ in 0..3 {
|
||||
assert!(
|
||||
processor
|
||||
.read_account_for_background_workspace_routing()
|
||||
.await?
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
assert_eq!(loads.load(Ordering::SeqCst), initial_loads);
|
||||
|
||||
processor.read_account(/*request*/ None).await?;
|
||||
assert!(loads.load(Ordering::SeqCst) > initial_loads);
|
||||
|
||||
write_chatgpt_auth(
|
||||
home.path(),
|
||||
ChatGptAuthFixture::new("access-chatgpt").account_id("account-123"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)?;
|
||||
assert!(auth_manager.reload().await);
|
||||
let initial_loads = loads.load(Ordering::SeqCst);
|
||||
let read = processor
|
||||
.read_account_for_background_workspace_routing()
|
||||
.await?
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
read.workspace_routing,
|
||||
Some(WorkspaceRouting {
|
||||
chatgpt_account_id: "account-123".into(),
|
||||
backend_origin: "https://chatgpt.com".into(),
|
||||
account_routing_override: "NO_CONSTRAINT".into(),
|
||||
})
|
||||
);
|
||||
assert!(loads.load(Ordering::SeqCst) > initial_loads);
|
||||
|
||||
let config_path = home.path().join("config.toml");
|
||||
std::fs::write(&config_path, "invalid = [ 'sk-test-private-value',")?;
|
||||
let Err(error) = processor
|
||||
.read_account_for_background_workspace_routing()
|
||||
.await
|
||||
else {
|
||||
panic!("invalid config must prevent workspace routing");
|
||||
};
|
||||
let message = error.to_string();
|
||||
assert!(
|
||||
message.starts_with(&format!(
|
||||
"failed to load workspace requirements: invalid configuration at {}:1:",
|
||||
config_path.display(),
|
||||
)),
|
||||
"{message}"
|
||||
);
|
||||
assert!(!message.contains("sk-test-private-value"), "{message}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[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: "NO_CONSTRAINT".into(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[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"), 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_eq!(
|
||||
resolve_routing(
|
||||
entry,
|
||||
/*required_chatgpt_base_url*/ None,
|
||||
"https://chatgpt.com"
|
||||
),
|
||||
Err(AccountReadError::Routing(expected))
|
||||
);
|
||||
}
|
||||
|
||||
#[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: "us".into(),
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -1,255 +0,0 @@
|
||||
//! Lists the active managed login and switches its workspace through the account-session API.
|
||||
|
||||
use super::*;
|
||||
use codex_app_server_protocol::AccountSession;
|
||||
use codex_app_server_protocol::AccountSessionWorkspace;
|
||||
use codex_app_server_protocol::AccountSessionWorkspaceKind;
|
||||
use codex_app_server_protocol::AccountSessionsListParams;
|
||||
use codex_app_server_protocol::AccountSessionsResponse;
|
||||
use codex_app_server_protocol::AccountSessionsSwitchParams;
|
||||
use codex_app_server_protocol::AccountSessionsSwitchResponse;
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(crate) async fn list_account_sessions(
|
||||
&self,
|
||||
params: AccountSessionsListParams,
|
||||
) -> Result<AccountSessionsResponse, JSONRPCErrorError> {
|
||||
let auth = if params.refresh_workspace_metadata {
|
||||
self.auth_manager.auth().await
|
||||
} else {
|
||||
self.auth_manager.auth_cached()
|
||||
}
|
||||
.filter(|_| !self.auth_manager.has_external_auth());
|
||||
let session_id = auth
|
||||
.as_ref()
|
||||
.and_then(CodexAuth::managed_account_session_id);
|
||||
let (Some(auth), Some(session_id)) = (auth, session_id) else {
|
||||
return Ok(AccountSessionsResponse {
|
||||
active_session_id: None,
|
||||
sessions: vec![],
|
||||
});
|
||||
};
|
||||
let account_id = auth.get_account_id();
|
||||
let mut workspaces = account_id
|
||||
.iter()
|
||||
.map(|id| AccountSessionWorkspace {
|
||||
account_id: id.clone(),
|
||||
name: None,
|
||||
image_url: None,
|
||||
kind: None,
|
||||
})
|
||||
.collect();
|
||||
if params.refresh_workspace_metadata {
|
||||
let accounts = self.workspace_memberships(&auth).await?;
|
||||
workspaces = accounts
|
||||
.accounts
|
||||
.into_iter()
|
||||
.map(|account| AccountSessionWorkspace {
|
||||
account_id: account.id,
|
||||
name: account.name,
|
||||
image_url: account.profile_picture_url,
|
||||
kind: match account.structure.as_str() {
|
||||
"personal" => Some(AccountSessionWorkspaceKind::Personal),
|
||||
"workspace" => Some(AccountSessionWorkspaceKind::Workspace),
|
||||
_ => None,
|
||||
},
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
workspaces.sort_by_key(|workspace| {
|
||||
accounts
|
||||
.account_ordering
|
||||
.iter()
|
||||
.position(|id| id == &workspace.account_id)
|
||||
.unwrap_or(usize::MAX)
|
||||
});
|
||||
let current = self.auth_manager.auth_cached();
|
||||
if self.auth_manager.has_external_auth()
|
||||
|| current
|
||||
.as_ref()
|
||||
.and_then(CodexAuth::managed_account_session_id)
|
||||
.as_deref()
|
||||
!= Some(&session_id)
|
||||
|| current.and_then(|auth| auth.get_account_id()) != account_id
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"Authentication changed while listing account sessions",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(AccountSessionsResponse {
|
||||
active_session_id: Some(session_id.clone()),
|
||||
sessions: vec![AccountSession {
|
||||
session_id,
|
||||
email: auth.get_account_email(),
|
||||
user_id: auth.get_chatgpt_user_id(),
|
||||
display_name: None,
|
||||
image_url: None,
|
||||
last_used_at: chrono::Utc::now().timestamp(),
|
||||
is_active: true,
|
||||
selected_workspace_account_id: account_id,
|
||||
workspaces,
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
async fn workspace_memberships(
|
||||
&self,
|
||||
auth: &CodexAuth,
|
||||
) -> Result<codex_backend_client::AccountsCheckResponse, JSONRPCErrorError> {
|
||||
let client = BackendClient::from_auth(
|
||||
self.config.chatgpt_base_url.clone(),
|
||||
auth,
|
||||
self.config.http_client_factory(),
|
||||
);
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(/*secs*/ 30),
|
||||
client.get_accounts_check(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| internal_error("Workspace metadata request timed out"))?
|
||||
.map_err(|_| internal_error("Failed to fetch workspace metadata"))
|
||||
}
|
||||
|
||||
pub(crate) async fn switch_account_session(
|
||||
&self,
|
||||
params: AccountSessionsSwitchParams,
|
||||
threads: &crate::request_processors::ThreadRequestProcessor,
|
||||
admission: &crate::turn_admission::TurnAdmission,
|
||||
) -> Result<AccountSessionsSwitchResponse, JSONRPCErrorError> {
|
||||
if self.active_login.lock().await.is_some() {
|
||||
return Err(invalid_request(
|
||||
"Finish or cancel the current login before switching workspaces",
|
||||
));
|
||||
}
|
||||
self.auth_manager
|
||||
.validate_workspace_switch(¶ms.session_id, ¶ms.account_id)
|
||||
.map_err(|error| invalid_request(error.to_string()))?;
|
||||
if self
|
||||
.auth_manager
|
||||
.auth_cached()
|
||||
.and_then(|auth| auth.get_account_id())
|
||||
.as_deref()
|
||||
== Some(¶ms.account_id)
|
||||
{
|
||||
return self.account_session_switch_response(¶ms).await;
|
||||
}
|
||||
let auth = self
|
||||
.auth_manager
|
||||
.auth_cached()
|
||||
.ok_or_else(|| invalid_request("Authentication is unavailable"))?;
|
||||
let memberships = self.workspace_memberships(&auth).await?;
|
||||
let mut matches = memberships
|
||||
.accounts
|
||||
.iter()
|
||||
.filter(|account| account.id == params.account_id);
|
||||
let Some(target) = matches.next() else {
|
||||
return Err(invalid_request("The selected workspace is unavailable"));
|
||||
};
|
||||
if matches.next().is_some() || target.is_deactivated {
|
||||
return Err(invalid_request("The selected workspace is unavailable"));
|
||||
}
|
||||
// The exchange strips the FedRAMP hint from the server session's token templates.
|
||||
if auth.is_fedramp_account()
|
||||
|| target.is_fedramp_compliant_workspace
|
||||
|| target.workspace_backend_origin.as_deref() == Some("https://gov.chatgpt.com")
|
||||
{
|
||||
return Err(invalid_request("Sign in to switch government workspaces"));
|
||||
}
|
||||
self.auth_manager
|
||||
.validate_workspace_switch(¶ms.session_id, ¶ms.account_id)
|
||||
.map_err(|error| invalid_request(error.to_string()))?;
|
||||
if target.can_access_with_session == Some(false) {
|
||||
if !params.allow_browser_login {
|
||||
return Err(invalid_request(
|
||||
"The selected workspace requires a new sign-in",
|
||||
));
|
||||
}
|
||||
let mut opts = self
|
||||
.login_chatgpt_common(
|
||||
/*codex_streamlined_login*/ true,
|
||||
LoginSuccessPage::default(),
|
||||
)
|
||||
.await?;
|
||||
opts.workspace_login = Some(
|
||||
auth.workspace_login(
|
||||
¶ms.session_id,
|
||||
params.account_id.clone(),
|
||||
target.sso_connection_name.clone(),
|
||||
)
|
||||
.map_err(|error| invalid_request(error.to_string()))?,
|
||||
);
|
||||
opts.forced_chatgpt_workspace_id = Some(vec![params.account_id]);
|
||||
let pause = admission.pause().await?;
|
||||
threads.unload_for_workspace_switch().await?;
|
||||
let (login_id, auth_url) = self.start_browser_login(opts, Some(pause)).await?;
|
||||
return Ok(AccountSessionsSwitchResponse::BrowserLogin { login_id, auth_url });
|
||||
}
|
||||
let _pause = admission.pause().await?;
|
||||
threads.unload_for_workspace_switch().await?;
|
||||
let switched = self
|
||||
.auth_manager
|
||||
.switch_workspace(¶ms.session_id, ¶ms.account_id)
|
||||
.await
|
||||
.map_err(|error| invalid_request(error.to_string()))?;
|
||||
let auth_changes = self.auth_manager.auth_change_state_receiver();
|
||||
let owner_generation = auth_changes.borrow().owner_generation;
|
||||
self.reload_workspace_config().await;
|
||||
// Routing includes fatal authorization and policy checks. Restore the
|
||||
// previous login on any failure, unless another auth operation replaced it.
|
||||
if let Err(error) = self.read_account(/*request*/ None).await {
|
||||
let rollback = self.auth_manager.rollback_workspace_switch(switched).await;
|
||||
self.reload_workspace_config().await;
|
||||
rollback.map_err(|rollback| internal_error(format!("Workspace validation failed: {error}; could not restore the previous workspace: {rollback}")))?;
|
||||
return Err(internal_error(format!(
|
||||
"Workspace validation failed: {error}"
|
||||
)));
|
||||
}
|
||||
self.thread_manager.invalidate_mcp_runtimes().await;
|
||||
self.model_catalog.invalidate().await;
|
||||
Self::maybe_refresh_plugin_caches_for_current_config(
|
||||
&self.config_manager,
|
||||
&self.thread_manager,
|
||||
self.auth_manager.auth_cached(),
|
||||
)
|
||||
.await;
|
||||
self.outgoing
|
||||
.send_account_notification(
|
||||
/*connection_id*/ None,
|
||||
&auth_changes,
|
||||
owner_generation,
|
||||
AccountNotification::Updated(self.current_account_updated_notification()),
|
||||
)
|
||||
.await;
|
||||
self.account_session_switch_response(¶ms).await
|
||||
}
|
||||
|
||||
async fn reload_workspace_config(&self) {
|
||||
self.config_manager
|
||||
.update_managed_config_loader(self.auth_manager.clone(), &self.config);
|
||||
self.config_manager
|
||||
.sync_default_client_residency_requirement()
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn account_session_switch_response(
|
||||
&self,
|
||||
params: &AccountSessionsSwitchParams,
|
||||
) -> Result<AccountSessionsSwitchResponse, JSONRPCErrorError> {
|
||||
let response = self
|
||||
.list_account_sessions(AccountSessionsListParams {
|
||||
refresh_workspace_metadata: false,
|
||||
})
|
||||
.await?;
|
||||
if response.active_session_id.as_deref() != Some(¶ms.session_id)
|
||||
|| !response.sessions.iter().any(|session| {
|
||||
session.session_id == params.session_id
|
||||
&& session.selected_workspace_account_id.as_deref() == Some(¶ms.account_id)
|
||||
})
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"Authentication changed during workspace switching",
|
||||
));
|
||||
}
|
||||
Ok(AccountSessionsSwitchResponse::Switched { sessions: response })
|
||||
}
|
||||
}
|
||||
@@ -38,8 +38,7 @@ fn skills_to_info(
|
||||
short_description: interface.short_description,
|
||||
icon_small: interface.icon_small,
|
||||
icon_large: interface.icon_large,
|
||||
icon_small_url: None,
|
||||
icon_large_url: None,
|
||||
|
||||
brand_color: interface.brand_color,
|
||||
default_prompt: interface.default_prompt,
|
||||
}
|
||||
|
||||
@@ -1,18 +1,5 @@
|
||||
use super::*;
|
||||
|
||||
fn cloud_config_bundle_load_error(err: &std::io::Error) -> Option<&CloudConfigBundleLoadError> {
|
||||
let mut current: Option<&(dyn std::error::Error + 'static)> = err
|
||||
.get_ref()
|
||||
.map(|source| source as &(dyn std::error::Error + 'static));
|
||||
while let Some(source) = current {
|
||||
if let Some(cloud_error) = source.downcast_ref::<CloudConfigBundleLoadError>() {
|
||||
return Some(cloud_error);
|
||||
}
|
||||
current = source.source();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(super) fn model_provider_error(provider: &ModelProviderError) -> JSONRPCErrorError {
|
||||
let mut error = invalid_request(provider.to_string());
|
||||
error.data = serde_json::to_value(provider).ok();
|
||||
@@ -29,22 +16,5 @@ pub(crate) fn config_load_error(err: &std::io::Error) -> JSONRPCErrorError {
|
||||
}
|
||||
current = source.source();
|
||||
}
|
||||
let data = cloud_config_bundle_load_error(err).map(|cloud_error| {
|
||||
let mut data = serde_json::json!({
|
||||
"reason": "cloudConfigBundle",
|
||||
"errorCode": format!("{:?}", cloud_error.code()),
|
||||
"detail": cloud_error.to_string(),
|
||||
});
|
||||
if let Some(status_code) = cloud_error.status_code() {
|
||||
data["statusCode"] = serde_json::json!(status_code);
|
||||
}
|
||||
if cloud_error.code() == CloudConfigBundleLoadErrorCode::Auth {
|
||||
data["action"] = serde_json::json!("relogin");
|
||||
}
|
||||
data
|
||||
});
|
||||
|
||||
let mut error = invalid_request(format!("failed to load configuration: {err}"));
|
||||
error.data = data;
|
||||
error
|
||||
invalid_request(format!("failed to load configuration: {err}"))
|
||||
}
|
||||
|
||||
@@ -65,18 +65,15 @@ const BACKGROUND_PAGINATED_ROLLOUT_MIGRATION_FEATURE: &str =
|
||||
"background_paginated_rollout_migration";
|
||||
|
||||
const SUPPORTED_EXPERIMENTAL_FEATURE_ENABLEMENT: &[&str] = &[
|
||||
"api_key_cyber_access_programs",
|
||||
"api_key_model_discovery",
|
||||
"auth_elicitation",
|
||||
BACKGROUND_PAGINATED_ROLLOUT_MIGRATION_FEATURE,
|
||||
"codex_apps_mcp_2026_07_28",
|
||||
"mcp_2026_07_28",
|
||||
"mcp_connection_sharing",
|
||||
"mcp_lazy_stdio_startup",
|
||||
"memories",
|
||||
"mentions_v2",
|
||||
"remote_control",
|
||||
"remote_plugin",
|
||||
"tool_suggest",
|
||||
"windows_sandbox_service",
|
||||
];
|
||||
@@ -241,7 +238,6 @@ impl ConfigRequestProcessor {
|
||||
let provider = create_model_provider(config.model_provider, /*auth_manager*/ None);
|
||||
let capabilities = provider.capabilities();
|
||||
Ok(ModelProviderCapabilitiesReadResponse {
|
||||
image_generation: capabilities.image_generation,
|
||||
web_search: capabilities.web_search,
|
||||
})
|
||||
}
|
||||
@@ -358,14 +354,8 @@ pub(super) async fn reload_user_config(
|
||||
}
|
||||
|
||||
async fn reload_user_config_inner(config_manager: &ConfigManager, thread_manager: &ThreadManager) {
|
||||
config_manager.revoke_mcp_ema_startups();
|
||||
if let Err(err) = config_manager.load_config_layers(/*cwd*/ None).await {
|
||||
tracing::warn!("failed to rebuild user config for runtime refresh: {err}");
|
||||
for thread_id in thread_manager.list_thread_ids().await {
|
||||
if let Ok(thread) = thread_manager.get_thread(thread_id).await {
|
||||
thread.disable_mcp_enterprise_auth().await;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let thread_ids = thread_manager.list_thread_ids().await;
|
||||
@@ -385,7 +375,6 @@ async fn reload_user_config_inner(config_manager: &ConfigManager, thread_manager
|
||||
Ok(config) => config,
|
||||
Err(err) => {
|
||||
tracing::warn!(%thread_id, %err, "failed to reload thread configuration");
|
||||
thread.disable_mcp_enterprise_auth().await;
|
||||
break;
|
||||
}
|
||||
};
|
||||
@@ -416,8 +405,7 @@ async fn reload_user_config_inner(config_manager: &ConfigManager, thread_manager
|
||||
}
|
||||
}
|
||||
if attempt == 3 {
|
||||
thread.disable_mcp_enterprise_auth().await;
|
||||
tracing::warn!(%thread_id, "configuration kept changing during user reload; enterprise MCP disabled");
|
||||
tracing::warn!(%thread_id, "configuration kept changing during user reload");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -933,7 +921,6 @@ mod tests {
|
||||
use codex_config::BrowserUseAccessApprovalLifetimeToml;
|
||||
use codex_config::BrowserUseOriginPolicyToml;
|
||||
use codex_config::BrowserUseRequirementsToml;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::ComputerUseMacosRequirementsToml;
|
||||
use codex_config::ComputerUseRequirementsToml;
|
||||
use codex_config::ComputerUseWindowsExeRequirementToml;
|
||||
@@ -962,14 +949,8 @@ mod tests {
|
||||
std::fs::write(
|
||||
&managed_config_path,
|
||||
r#"
|
||||
[features]
|
||||
use_xaa = true
|
||||
[mcp_enterprise_managed_auth.idp]
|
||||
issuer = "https://idp.example"
|
||||
client_id = "idp-client"
|
||||
[mcp_servers.enterprise]
|
||||
url = "https://resource.example/mcp"
|
||||
auth = "ema_auth"
|
||||
oauth_resource = "https://resource.example/mcp"
|
||||
[mcp_servers.enterprise.oauth]
|
||||
client_id = "mcp-client"
|
||||
@@ -984,7 +965,6 @@ client_id = "mcp-client"
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
LoaderOverrides::with_managed_config_path_for_tests(managed_config_path),
|
||||
CloudConfigBundleLoader::default(),
|
||||
);
|
||||
let initial = config_manager
|
||||
.load_latest_config(Some(home.path().to_path_buf()))
|
||||
|
||||
@@ -86,7 +86,6 @@ async fn user_reload_promotes_plugin_and_feature_requirements_without_server_cha
|
||||
Vec::new(),
|
||||
overrides,
|
||||
/*strict_config*/ false,
|
||||
codex_config::CloudConfigBundleLoader::default(),
|
||||
codex_arg0::Arg0DispatchPaths::default(),
|
||||
Arc::new(codex_config::NoopThreadConfigLoader),
|
||||
);
|
||||
@@ -153,100 +152,3 @@ async fn user_reload_promotes_plugin_and_feature_requirements_without_server_cha
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case::test_case(codex_config::CloudConfigBundleBindingStatus::Stale)]
|
||||
#[test_case::test_case(codex_config::CloudConfigBundleBindingStatus::Suspended)]
|
||||
#[tokio::test]
|
||||
async fn mcp_refresh_rejects_superseded_app_server_policy(
|
||||
status: codex_config::CloudConfigBundleBindingStatus,
|
||||
) -> anyhow::Result<()> {
|
||||
use codex_config::CloudConfigBundle;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::CloudConfigBundlePolicy;
|
||||
use codex_config::CloudConfigBundleSnapshot;
|
||||
use codex_core::ConfigRefreshOutcome;
|
||||
|
||||
let home = tempfile::tempdir()?;
|
||||
let policy = CloudConfigBundlePolicy::default();
|
||||
let mut snapshot = CloudConfigBundleSnapshot {
|
||||
config_server: None,
|
||||
bundle: Ok(None),
|
||||
binding: None,
|
||||
};
|
||||
policy.publish_snapshot(&mut snapshot);
|
||||
let loader =
|
||||
CloudConfigBundleLoader::default().with_ema_policy_snapshots(policy.clone(), move || {
|
||||
let snapshot = snapshot.clone();
|
||||
async move { snapshot }
|
||||
});
|
||||
let manager = ConfigManager::new(
|
||||
home.path().to_path_buf(),
|
||||
Vec::new(),
|
||||
codex_config::LoaderOverrides::without_managed_config_for_tests(),
|
||||
/*strict_config*/ false,
|
||||
loader,
|
||||
codex_arg0::Arg0DispatchPaths::default(),
|
||||
Arc::new(codex_config::NoopThreadConfigLoader),
|
||||
);
|
||||
let initial = manager
|
||||
.load_latest_config(Some(home.path().to_path_buf()))
|
||||
.await?;
|
||||
let threads = codex_core::test_support::thread_manager_with_models_provider_and_home(
|
||||
CodexAuth::from_api_key("dummy"),
|
||||
initial.model_provider.clone(),
|
||||
initial.codex_home.to_path_buf(),
|
||||
Arc::new(EnvironmentManager::default_for_tests()),
|
||||
);
|
||||
let thread = threads
|
||||
.start_thread(codex_core::StartThreadOptions::new(initial))
|
||||
.await?
|
||||
.thread;
|
||||
let current = thread.config().await;
|
||||
let next = manager
|
||||
.load_latest_config_with_session_layers(¤t.config_layer_stack, ¤t.cwd)
|
||||
.await?;
|
||||
let mut replacement = CloudConfigBundle::default();
|
||||
replacement
|
||||
.config_toml
|
||||
.enterprise_managed
|
||||
.push(codex_config::CloudConfigFragment {
|
||||
id: "replacement".into(),
|
||||
name: "replacement".into(),
|
||||
contents: "model = 'replacement-model'".into(),
|
||||
});
|
||||
policy.observe_remote_bundle(&replacement);
|
||||
if status == codex_config::CloudConfigBundleBindingStatus::Stale {
|
||||
policy.publish_snapshot(&mut CloudConfigBundleSnapshot {
|
||||
config_server: None,
|
||||
bundle: Ok(Some(replacement)),
|
||||
binding: None,
|
||||
});
|
||||
}
|
||||
assert_eq!(
|
||||
next.config_layer_stack
|
||||
.cloud_config_binding()
|
||||
.expect("app-server must retain the policy binding")
|
||||
.read()
|
||||
.status,
|
||||
status,
|
||||
);
|
||||
let outcome = thread.refresh_mcp_config(Arc::clone(¤t), next).await;
|
||||
let expected = match status {
|
||||
codex_config::CloudConfigBundleBindingStatus::Stale => ConfigRefreshOutcome::Stale,
|
||||
codex_config::CloudConfigBundleBindingStatus::Suspended => ConfigRefreshOutcome::Rejected,
|
||||
codex_config::CloudConfigBundleBindingStatus::Current => unreachable!(),
|
||||
};
|
||||
assert_eq!(outcome, expected);
|
||||
if status == codex_config::CloudConfigBundleBindingStatus::Stale {
|
||||
assert!(Arc::ptr_eq(¤t, &thread.config().await));
|
||||
} else {
|
||||
assert!(
|
||||
thread
|
||||
.config()
|
||||
.await
|
||||
.config_layer_stack
|
||||
.cloud_config_binding()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -94,7 +94,6 @@ impl ThreadRequestProcessor {
|
||||
turn_trigger: Some("daemon_recovery".to_string()),
|
||||
final_output_json_schema: saved.output_schema,
|
||||
service_tier: saved.service_tier,
|
||||
cyber_access_program: saved.cyber_access_program,
|
||||
root_turn_id: previous_context.root_turn_id.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
|
||||
@@ -44,7 +44,6 @@ impl ThreadRequestProcessor {
|
||||
turn_id,
|
||||
output_schema: options.final_output_json_schema,
|
||||
service_tier: options.service_tier,
|
||||
cyber_access_program: options.cyber_access_program,
|
||||
local_environment: Some((&environment).into()),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -3,11 +3,6 @@ use super::*;
|
||||
use crate::error_code::OVERLOADED_ERROR_CODE;
|
||||
use codex_app_server_protocol::FeedbackSaveParams;
|
||||
use codex_app_server_protocol::FeedbackSaveResponse;
|
||||
use codex_connectors::ConnectorDirectoryCacheContext;
|
||||
use codex_connectors::ConnectorDirectoryCacheKey;
|
||||
use codex_connectors::connector_runtime_cache_path;
|
||||
use codex_feedback::CODEX_APP_DIRECTORY_CACHE_ATTACHMENT_FILENAME;
|
||||
use codex_feedback::CODEX_APPS_TOOLS_CACHE_ATTACHMENT_FILENAME;
|
||||
use codex_feedback::FeedbackAttachment;
|
||||
use codex_feedback::FeedbackSnapshot;
|
||||
#[cfg(target_os = "windows")]
|
||||
@@ -28,7 +23,6 @@ struct SavedFeedback {
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct FeedbackRequestProcessor {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config: Arc<Config>,
|
||||
feedback: CodexFeedback,
|
||||
@@ -39,7 +33,6 @@ pub(crate) struct FeedbackRequestProcessor {
|
||||
|
||||
impl FeedbackRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config: Arc<Config>,
|
||||
feedback: CodexFeedback,
|
||||
@@ -47,7 +40,6 @@ impl FeedbackRequestProcessor {
|
||||
state_db: Option<StateDbHandle>,
|
||||
) -> Self {
|
||||
Self {
|
||||
auth_manager,
|
||||
thread_manager,
|
||||
config,
|
||||
feedback,
|
||||
@@ -115,7 +107,6 @@ impl FeedbackRequestProcessor {
|
||||
None => None,
|
||||
};
|
||||
|
||||
let auth = self.auth_manager.auth_cached();
|
||||
let turn_metadata = if let Some(conversation_id) = conversation_id
|
||||
&& let Some(rollout_path) = self
|
||||
.resolve_rollout_path(conversation_id, self.state_db.as_ref())
|
||||
@@ -132,18 +123,6 @@ impl FeedbackRequestProcessor {
|
||||
apply_feedback_turn_metadata(&mut report_tags, turn_metadata);
|
||||
let prompt_hash = report_tags.get("prompt_hash").cloned();
|
||||
|
||||
if let Some(chatgpt_user_id) = auth
|
||||
.as_ref()
|
||||
.and_then(codex_login::CodexAuth::get_chatgpt_user_id)
|
||||
{
|
||||
tracing::info!(target: "feedback_tags", chatgpt_user_id);
|
||||
}
|
||||
if let Some(account_id) = auth
|
||||
.as_ref()
|
||||
.and_then(codex_login::CodexAuth::get_account_id)
|
||||
{
|
||||
tracing::info!(target: "feedback_tags", account_id);
|
||||
}
|
||||
let snapshot = self.feedback.snapshot(conversation_id);
|
||||
let mut extra_attachments = Vec::new();
|
||||
let mut feedback_index = None;
|
||||
@@ -255,15 +234,6 @@ impl FeedbackRequestProcessor {
|
||||
{
|
||||
attachment_paths.push(sandbox_log_attachment);
|
||||
}
|
||||
for cache_attachment in tool_cache_feedback_attachments(
|
||||
self.config.codex_home.as_path(),
|
||||
&self.config.chatgpt_base_url,
|
||||
auth.as_ref(),
|
||||
) {
|
||||
if seen_attachment_paths.insert(cache_attachment.path.clone()) {
|
||||
attachment_paths.push(cache_attachment);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(extra_log_files) = extra_log_files {
|
||||
for extra_log_file in extra_log_files {
|
||||
@@ -461,47 +431,6 @@ fn normalized_prompt_hash(prompt: &str) -> String {
|
||||
format!("{:x}", Sha256::digest(normalized_prompt.as_bytes()))
|
||||
}
|
||||
|
||||
fn tool_cache_feedback_attachments(
|
||||
codex_home: &Path,
|
||||
chatgpt_base_url: &str,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> Vec<FeedbackAttachmentPath> {
|
||||
let mut attachments = Vec::with_capacity(2);
|
||||
let tools_cache_path = connector_runtime_cache_path(codex_home, auth);
|
||||
if tools_cache_path.is_file() {
|
||||
attachments.push(FeedbackAttachmentPath {
|
||||
path: tools_cache_path,
|
||||
attachment_filename_override: Some(
|
||||
CODEX_APPS_TOOLS_CACHE_ATTACHMENT_FILENAME.to_string(),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
let Some(auth) = auth.filter(|auth| auth.uses_codex_backend()) else {
|
||||
return attachments;
|
||||
};
|
||||
let directory_cache_context = ConnectorDirectoryCacheContext::new(
|
||||
codex_home.to_path_buf(),
|
||||
ConnectorDirectoryCacheKey::new(
|
||||
chatgpt_base_url.to_string(),
|
||||
auth.get_account_id(),
|
||||
auth.get_chatgpt_user_id(),
|
||||
auth.is_workspace_account(),
|
||||
),
|
||||
);
|
||||
let directory_cache_path = directory_cache_context.cache_path();
|
||||
if directory_cache_path.is_file() {
|
||||
attachments.push(FeedbackAttachmentPath {
|
||||
path: directory_cache_path,
|
||||
attachment_filename_override: Some(
|
||||
CODEX_APP_DIRECTORY_CACHE_ATTACHMENT_FILENAME.to_string(),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
attachments
|
||||
}
|
||||
|
||||
fn auto_review_rollout_filename(thread_id: ThreadId) -> String {
|
||||
format!("auto-review-rollout-{thread_id}.jsonl")
|
||||
}
|
||||
@@ -589,7 +518,6 @@ mod tests {
|
||||
use codex_rollout::RolloutLine;
|
||||
use core_test_support::responses::start_mock_server;
|
||||
use core_test_support::test_codex::test_codex;
|
||||
use http::HeaderMap;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
@@ -826,7 +754,6 @@ mod tests {
|
||||
collaboration_mode: None,
|
||||
multi_agent_version: None,
|
||||
realtime_active: None,
|
||||
cyber_access_program: None,
|
||||
effort: effort.clone(),
|
||||
summary: Some(ReasoningSummary::Auto),
|
||||
}),
|
||||
@@ -843,98 +770,6 @@ mod tests {
|
||||
(tempdir, rollout_path)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_cache_feedback_attachments_include_existing_active_cache_files() {
|
||||
let codex_home = tempfile::tempdir().expect("create tempdir");
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
let tools_cache_path = connector_runtime_cache_path(codex_home.path(), Some(&auth));
|
||||
std::fs::create_dir_all(tools_cache_path.parent().expect("tools cache parent"))
|
||||
.expect("create tools cache directory");
|
||||
std::fs::write(&tools_cache_path, b"tools").expect("write tools cache");
|
||||
|
||||
let account_id = auth.get_account_id().expect("dummy auth account id");
|
||||
let directory_cache_context = ConnectorDirectoryCacheContext::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
ConnectorDirectoryCacheKey::new(
|
||||
"https://chatgpt.com/backend-api".to_string(),
|
||||
Some(account_id),
|
||||
auth.get_chatgpt_user_id(),
|
||||
auth.is_workspace_account(),
|
||||
),
|
||||
);
|
||||
let directory_cache_path = directory_cache_context.cache_path();
|
||||
std::fs::create_dir_all(
|
||||
directory_cache_path
|
||||
.parent()
|
||||
.expect("directory cache parent"),
|
||||
)
|
||||
.expect("create directory cache directory");
|
||||
std::fs::write(&directory_cache_path, b"directory").expect("write directory cache");
|
||||
|
||||
let attachments = tool_cache_feedback_attachments(
|
||||
codex_home.path(),
|
||||
"https://chatgpt.com/backend-api",
|
||||
Some(&auth),
|
||||
)
|
||||
.into_iter()
|
||||
.map(|attachment| (attachment.path, attachment.attachment_filename_override))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(
|
||||
attachments,
|
||||
vec![
|
||||
(
|
||||
tools_cache_path,
|
||||
Some(CODEX_APPS_TOOLS_CACHE_ATTACHMENT_FILENAME.to_string()),
|
||||
),
|
||||
(
|
||||
directory_cache_path,
|
||||
Some(CODEX_APP_DIRECTORY_CACHE_ATTACHMENT_FILENAME.to_string()),
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_cache_feedback_attachments_include_directory_cache_without_account_id() {
|
||||
let codex_home = tempfile::tempdir().expect("create tempdir");
|
||||
let auth = CodexAuth::Headers(codex_login::AuthHeaders::new(HeaderMap::new()));
|
||||
let directory_cache_context = ConnectorDirectoryCacheContext::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
ConnectorDirectoryCacheKey::new(
|
||||
"https://chatgpt.com/backend-api".to_string(),
|
||||
/*account_id*/ None,
|
||||
auth.get_chatgpt_user_id(),
|
||||
auth.is_workspace_account(),
|
||||
),
|
||||
);
|
||||
let directory_cache_path = directory_cache_context.cache_path();
|
||||
std::fs::create_dir_all(
|
||||
directory_cache_path
|
||||
.parent()
|
||||
.expect("directory cache parent"),
|
||||
)
|
||||
.expect("create directory cache directory");
|
||||
std::fs::write(&directory_cache_path, b"directory").expect("write directory cache");
|
||||
|
||||
let attachments = tool_cache_feedback_attachments(
|
||||
codex_home.path(),
|
||||
"https://chatgpt.com/backend-api",
|
||||
Some(&auth),
|
||||
)
|
||||
.into_iter()
|
||||
.map(|attachment| (attachment.path, attachment.attachment_filename_override))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(
|
||||
attachments,
|
||||
vec![(
|
||||
directory_cache_path,
|
||||
Some(CODEX_APP_DIRECTORY_CACHE_ATTACHMENT_FILENAME.to_string()),
|
||||
)]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn windows_sandbox_log_attachment_uses_current_log() {
|
||||
|
||||
@@ -70,7 +70,6 @@ impl InitializeRequestProcessor {
|
||||
// with initialize-time mismatch rejection.
|
||||
let capabilities = params.capabilities.unwrap_or_default();
|
||||
let experimental_api_enabled = capabilities.experimental_api;
|
||||
let request_attestation = capabilities.request_attestation;
|
||||
let extensions = capabilities.extensions.as_ref();
|
||||
let mut client_mcp_extensions = codex_mcp::client_mcp_extensions(
|
||||
extensions,
|
||||
@@ -126,7 +125,6 @@ impl InitializeRequestProcessor {
|
||||
opted_out_notification_methods: opt_out_notification_methods.into_iter().collect(),
|
||||
app_server_client_name: name.clone(),
|
||||
client_version: version,
|
||||
request_attestation,
|
||||
client_mcp_extensions,
|
||||
})
|
||||
.is_err()
|
||||
|
||||
@@ -1,335 +0,0 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::McpServerEventNotification;
|
||||
use codex_app_server_protocol::McpServerEventStreamNotification;
|
||||
use codex_app_server_protocol::McpServerEventStreamStartParams;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_core::CodexThread;
|
||||
use codex_login::AuthManager;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::McpEventStream;
|
||||
use codex_protocol::ThreadId;
|
||||
use serde_json::Value;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use super::mcp_processor::McpRequestProcessor;
|
||||
use crate::error_code::OVERLOADED_ERROR_CODE;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
|
||||
const MAX_MCP_EVENT_STREAMS_PER_CONNECTION: usize = 64;
|
||||
const MAX_MCP_EVENT_STREAM_RECONNECT_ATTEMPTS: u32 = 3;
|
||||
const MCP_EVENT_STREAM_RECONNECT_DELAY: Duration = Duration::from_secs(/*secs*/ 1);
|
||||
const MCP_EVENT_STREAM_STARTUP_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 90);
|
||||
|
||||
pub(crate) type McpEventStreamReady = oneshot::Receiver<Result<(), JSONRPCErrorError>>;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct McpEventStreamTask {
|
||||
thread_id: ThreadId,
|
||||
task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct McpEventStreams {
|
||||
tasks: Mutex<HashMap<String, McpEventStreamTask>>,
|
||||
}
|
||||
|
||||
impl McpEventStreams {
|
||||
pub(crate) async fn start(
|
||||
&self,
|
||||
connection_id: ConnectionId,
|
||||
params: McpServerEventStreamStartParams,
|
||||
processor: McpRequestProcessor,
|
||||
) -> Result<McpEventStreamReady, JSONRPCErrorError> {
|
||||
if params.server != CODEX_APPS_MCP_SERVER_NAME {
|
||||
return Err(invalid_request(
|
||||
"MCP event subscriptions are only supported for hosted apps",
|
||||
));
|
||||
}
|
||||
let thread_id = ThreadId::from_string(¶ms.thread_id)
|
||||
.map_err(|error| invalid_request(format!("invalid thread id: {error}")))?;
|
||||
let subscription_id = params.subscription_id.clone();
|
||||
let (ready_tx, ready_rx) = oneshot::channel();
|
||||
{
|
||||
let mut tasks = self.tasks.lock().await;
|
||||
tasks.retain(|_, task| !task.task.is_finished());
|
||||
if tasks.contains_key(&subscription_id) {
|
||||
return Err(invalid_request(format!(
|
||||
"MCP event subscription '{subscription_id}' already exists"
|
||||
)));
|
||||
}
|
||||
if tasks.len() >= MAX_MCP_EVENT_STREAMS_PER_CONNECTION {
|
||||
return Err(JSONRPCErrorError {
|
||||
code: OVERLOADED_ERROR_CODE,
|
||||
message: format!(
|
||||
"MCP event subscription limit of {MAX_MCP_EVENT_STREAMS_PER_CONNECTION} reached"
|
||||
),
|
||||
data: None,
|
||||
});
|
||||
}
|
||||
let task = tokio::spawn(async move {
|
||||
let mut auth_changes =
|
||||
McpEventStreamAuthChanges::new(Arc::clone(&processor.auth_manager));
|
||||
let opened = tokio::select! {
|
||||
() = auth_changes.changed() => Err(internal_error(
|
||||
"MCP event subscription authentication changed during startup",
|
||||
)),
|
||||
result = async {
|
||||
if !processor
|
||||
.thread_state_manager
|
||||
.subscribed_connection_ids(thread_id)
|
||||
.await
|
||||
.contains(&connection_id)
|
||||
{
|
||||
return Err(invalid_request(format!(
|
||||
"connection is not subscribed to thread '{thread_id}'"
|
||||
)));
|
||||
}
|
||||
let (_, thread) = processor.load_thread(¶ms.thread_id).await?;
|
||||
let stream = thread
|
||||
.start_mcp_event_stream(
|
||||
¶ms.name,
|
||||
params.arguments.clone(),
|
||||
params.meta.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| internal_error(format!(
|
||||
"failed to start MCP event stream for '{}': {error:#}",
|
||||
params.server
|
||||
)))?;
|
||||
Ok((stream, thread))
|
||||
} => result,
|
||||
};
|
||||
match opened {
|
||||
Ok((stream, thread)) => {
|
||||
forward_events(
|
||||
connection_id,
|
||||
¶ms,
|
||||
processor.outgoing.as_ref(),
|
||||
thread,
|
||||
stream,
|
||||
auth_changes,
|
||||
ready_tx,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = ready_tx.send(Err(error));
|
||||
}
|
||||
}
|
||||
});
|
||||
tasks.insert(subscription_id, McpEventStreamTask { thread_id, task });
|
||||
}
|
||||
Ok(ready_rx)
|
||||
}
|
||||
|
||||
pub(crate) async fn wait_for_activation(
|
||||
&self,
|
||||
subscription_id: &str,
|
||||
ready: McpEventStreamReady,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
match tokio::time::timeout(MCP_EVENT_STREAM_STARTUP_TIMEOUT, ready).await {
|
||||
Ok(Ok(result)) => result,
|
||||
Ok(Err(_)) => Err(internal_error(
|
||||
"MCP event stream ended before becoming active",
|
||||
)),
|
||||
Err(_) => {
|
||||
self.stop(subscription_id).await;
|
||||
Err(internal_error("MCP event stream startup timed out"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn stop(&self, subscription_id: &str) {
|
||||
let task = self.tasks.lock().await.remove(subscription_id);
|
||||
if let Some(task) = task {
|
||||
task.task.abort();
|
||||
let _ = task.task.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn stop_thread(&self, thread_id: ThreadId) {
|
||||
self.stop_matching(Some(thread_id)).await;
|
||||
}
|
||||
|
||||
pub(crate) async fn clear(&self) {
|
||||
self.stop_matching(/*thread_id*/ None).await;
|
||||
}
|
||||
|
||||
async fn stop_matching(&self, thread_id: Option<ThreadId>) {
|
||||
let tasks = self
|
||||
.tasks
|
||||
.lock()
|
||||
.await
|
||||
.extract_if(|_, task| thread_id.is_none_or(|id| task.thread_id == id))
|
||||
.map(|(_, task)| task)
|
||||
.collect::<Vec<_>>();
|
||||
for task in tasks {
|
||||
task.task.abort();
|
||||
let _ = task.task.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn forward_events(
|
||||
connection_id: ConnectionId,
|
||||
params: &McpServerEventStreamStartParams,
|
||||
outgoing: &OutgoingMessageSender,
|
||||
thread: Arc<CodexThread>,
|
||||
mut stream: McpEventStream,
|
||||
mut auth_changes: McpEventStreamAuthChanges,
|
||||
ready: oneshot::Sender<Result<(), JSONRPCErrorError>>,
|
||||
) {
|
||||
let mut ready = Some(ready);
|
||||
let mut reconnect_attempts = 0;
|
||||
let mut reconnect_deadline = None;
|
||||
let send = |notification| {
|
||||
outgoing.send_server_notification_to_connection_and_wait(
|
||||
connection_id,
|
||||
ServerNotification::McpServerEventStream(McpServerEventStreamNotification {
|
||||
subscription_id: params.subscription_id.clone(),
|
||||
notification,
|
||||
}),
|
||||
)
|
||||
};
|
||||
loop {
|
||||
let notification = tokio::select! {
|
||||
biased;
|
||||
() = auth_changes.changed() => break,
|
||||
() = thread.wait_until_terminated() => break,
|
||||
result = stream.recv() => match result {
|
||||
Ok(Some(notification)) => notification,
|
||||
Ok(None)
|
||||
if ready.is_none()
|
||||
&& reconnect_attempts < MAX_MCP_EVENT_STREAM_RECONNECT_ATTEMPTS =>
|
||||
{
|
||||
reconnect_attempts += 1;
|
||||
let deadline = *reconnect_deadline.get_or_insert_with(|| {
|
||||
tokio::time::Instant::now() + MCP_EVENT_STREAM_STARTUP_TIMEOUT
|
||||
});
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = auth_changes.changed() => break,
|
||||
() = thread.wait_until_terminated() => break,
|
||||
result = tokio::time::timeout_at(deadline, async {
|
||||
tokio::time::sleep(
|
||||
MCP_EVENT_STREAM_RECONNECT_DELAY
|
||||
* (1 << (reconnect_attempts - 1)),
|
||||
)
|
||||
.await;
|
||||
let mut stream = thread
|
||||
.start_mcp_event_stream(
|
||||
¶ms.name,
|
||||
params.arguments.clone(),
|
||||
params.meta.clone(),
|
||||
)
|
||||
.await?;
|
||||
let notification = stream.recv().await?;
|
||||
Ok::<_, anyhow::Error>((stream, notification))
|
||||
}) => match result {
|
||||
Ok(Ok((reconnected, Some(notification)))) => {
|
||||
stream = reconnected;
|
||||
notification
|
||||
}
|
||||
Ok(Ok((_, None)) | Err(_)) => continue,
|
||||
Err(_) => break,
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok(None) => break,
|
||||
Err(error) => {
|
||||
if let Some(ready) = ready.take() {
|
||||
let _ = ready.send(Err(internal_error(format!("{error:#}"))));
|
||||
}
|
||||
break;
|
||||
}
|
||||
},
|
||||
};
|
||||
let active = notification.method == "notifications/events/active";
|
||||
let terminated = notification.method == "notifications/events/terminated";
|
||||
if !send(McpServerEventNotification {
|
||||
method: notification.method,
|
||||
params: notification
|
||||
.params
|
||||
.unwrap_or_else(|| Value::Object(Default::default())),
|
||||
})
|
||||
.await
|
||||
{
|
||||
break;
|
||||
}
|
||||
if active && let Some(ready) = ready.take() {
|
||||
let _ = ready.send(Ok(()));
|
||||
}
|
||||
if terminated {
|
||||
return;
|
||||
}
|
||||
if !active {
|
||||
reconnect_attempts = 0;
|
||||
reconnect_deadline = None;
|
||||
}
|
||||
}
|
||||
if let Some(ready) = ready {
|
||||
let _ = ready.send(Err(internal_error(
|
||||
"MCP event stream ended before becoming active",
|
||||
)));
|
||||
} else {
|
||||
send(McpServerEventNotification {
|
||||
method: "notifications/events/terminated".to_string(),
|
||||
params: Value::Object(Default::default()),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
struct McpEventStreamAuthChanges {
|
||||
manager: Arc<AuthManager>,
|
||||
receiver: watch::Receiver<u64>,
|
||||
revision: u64,
|
||||
principal: Option<(Option<String>, Option<String>)>,
|
||||
}
|
||||
|
||||
impl McpEventStreamAuthChanges {
|
||||
fn new(manager: Arc<AuthManager>) -> Self {
|
||||
let receiver = manager.auth_change_receiver();
|
||||
let revision = *receiver.borrow();
|
||||
let principal = manager
|
||||
.auth_cached()
|
||||
.map(|auth| (auth.get_account_id(), auth.get_chatgpt_user_id()));
|
||||
Self {
|
||||
manager,
|
||||
receiver,
|
||||
revision,
|
||||
principal,
|
||||
}
|
||||
}
|
||||
|
||||
async fn changed(&mut self) {
|
||||
loop {
|
||||
if self
|
||||
.manager
|
||||
.auth_cached()
|
||||
.map(|auth| (auth.get_account_id(), auth.get_chatgpt_user_id()))
|
||||
!= self.principal
|
||||
{
|
||||
return;
|
||||
}
|
||||
if self.receiver.changed().await.is_err() || self.principal == Some((None, None)) {
|
||||
return;
|
||||
}
|
||||
let revision = *self.receiver.borrow_and_update();
|
||||
if revision.wrapping_sub(self.revision) > 1 {
|
||||
return;
|
||||
}
|
||||
self.revision = revision;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,12 @@
|
||||
use super::account_processor::EnterpriseLoginCompletion;
|
||||
use super::account_processor::EnterpriseLoginTarget;
|
||||
use super::thread_input::ensure_direct_input_allowed;
|
||||
use super::*;
|
||||
use codex_config::types::McpServerAuth;
|
||||
use codex_mcp::McpServerSource;
|
||||
use codex_mcp::ReadResourceRequestParams;
|
||||
use codex_mcp::ema_auth_scope;
|
||||
use codex_mcp::resolve_oauth_callback;
|
||||
use codex_otel::auth_storage::AuthStorageOriginator;
|
||||
use codex_rmcp_client::EnterpriseOAuthLoginRequest;
|
||||
use std::future::Future;
|
||||
|
||||
use crate::thread_state::ThreadStateManager;
|
||||
|
||||
const MCP_THREAD_ID_META_KEY: &str = "threadId";
|
||||
|
||||
@@ -21,26 +16,20 @@ pub(crate) struct McpRequestProcessor {
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
pub(super) outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
account_processor: Arc<AccountRequestProcessor>,
|
||||
pub(super) thread_state_manager: ThreadStateManager,
|
||||
}
|
||||
|
||||
impl McpRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
thread_state_manager: ThreadStateManager,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
account_processor: Arc<AccountRequestProcessor>,
|
||||
) -> Self {
|
||||
Self {
|
||||
auth_manager,
|
||||
thread_manager,
|
||||
outgoing,
|
||||
config_manager,
|
||||
account_processor,
|
||||
thread_state_manager,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,97 +163,16 @@ impl McpRequestProcessor {
|
||||
StreamableHttpRedirectMode::Legacy
|
||||
};
|
||||
let server = server.config();
|
||||
let enterprise = matches!(server.auth, McpServerAuth::EmaAuth);
|
||||
if matches!(server.auth, McpServerAuth::EmaAuth) {
|
||||
return Err(invalid_request(format!(
|
||||
"MCP server '{name}' uses enterprise-managed authorization, which is not supported."
|
||||
)));
|
||||
}
|
||||
let (authorization_url, login_id, completion): (
|
||||
String,
|
||||
String,
|
||||
futures::future::BoxFuture<'static, anyhow::Result<()>>,
|
||||
) = if enterprise {
|
||||
let thread_id = thread_id.clone().ok_or_else(|| {
|
||||
invalid_request("enterprise MCP login requires a connected thread")
|
||||
})?;
|
||||
if !mcp_config.xaa_enabled {
|
||||
return Err(invalid_request(
|
||||
"enterprise MCP authentication requires `[features].use_xaa = true`",
|
||||
));
|
||||
}
|
||||
if !server.enabled {
|
||||
return Err(invalid_request(format!("MCP server '{name}' is disabled.")));
|
||||
}
|
||||
server
|
||||
.validate_ema_auth_transport()
|
||||
.map_err(|reason| invalid_request(format!("MCP server '{name}' {reason}")))?;
|
||||
if client_registration.is_some() {
|
||||
return Err(invalid_request(
|
||||
"enterprise MCP login uses the configured enterprise client and does not support clientRegistration overrides",
|
||||
));
|
||||
}
|
||||
// Resource scopes and per-server callbacks do not alter the shared IdP registration.
|
||||
let scope = ema_auth_scope(auth.as_ref()).ok_or_else(|| {
|
||||
invalid_request(
|
||||
"enterprise MCP authentication requires a signed-in Codex user and workspace",
|
||||
)
|
||||
})?;
|
||||
let idp = server.oauth_idp().ok_or_else(|| {
|
||||
invalid_request(format!(
|
||||
"MCP server '{name}' has no configured enterprise IdP"
|
||||
))
|
||||
})?;
|
||||
let registration = server.ema_registration().cloned().ok_or_else(|| {
|
||||
invalid_request(format!(
|
||||
"MCP server '{name}' has no validated enterprise registration"
|
||||
))
|
||||
})?;
|
||||
let credential_name = idp.credential_name(&scope);
|
||||
let http_client =
|
||||
runtime_context
|
||||
.resolve_http_client(&name, server)
|
||||
.map_err(|err| {
|
||||
internal_error(format!("failed to resolve MCP server runtime: {err}"))
|
||||
})?;
|
||||
let login = self
|
||||
.account_processor
|
||||
.enterprise_login
|
||||
.start(
|
||||
EnterpriseOAuthLoginRequest {
|
||||
credential_name: &credential_name,
|
||||
issuer: &idp.issuer,
|
||||
client_id: &idp.client_id,
|
||||
client_secret: idp.client_secret.as_ref().map(|secret| secret.as_str()),
|
||||
token_endpoint_auth_method: idp.token_endpoint_auth_method,
|
||||
keyring_backend_kind: mcp_config.auth_keyring_backend_kind,
|
||||
callback_port: mcp_config.mcp_oauth_callback_port,
|
||||
callback_url: mcp_config.mcp_oauth_callback_url.as_deref(),
|
||||
timeout_secs,
|
||||
http_client,
|
||||
redirect_mode,
|
||||
},
|
||||
scope,
|
||||
EnterpriseLoginTarget {
|
||||
thread_id,
|
||||
server_name: name.clone(),
|
||||
registration,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let mut completion = login.completion;
|
||||
(
|
||||
login.authorization_url,
|
||||
login.login_id,
|
||||
Box::pin(async move {
|
||||
match completion.wait_for(|state| state.is_complete()).await {
|
||||
Ok(result) => match *result {
|
||||
EnterpriseLoginCompletion::Succeeded => Ok(()),
|
||||
EnterpriseLoginCompletion::Failed(detail) => Err(detail.into()),
|
||||
EnterpriseLoginCompletion::Pending => {
|
||||
Err(anyhow::anyhow!("Enterprise sign-in failed."))
|
||||
}
|
||||
},
|
||||
_ => Err(anyhow::anyhow!("Enterprise sign-in failed.")),
|
||||
}
|
||||
}),
|
||||
)
|
||||
} else {
|
||||
) = {
|
||||
let (url, http_headers, env_http_headers) = match &server.transport {
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
url,
|
||||
@@ -350,7 +258,7 @@ impl McpRequestProcessor {
|
||||
Ok(()) => (true, None),
|
||||
Err(err) => (false, Some(err.to_string())),
|
||||
};
|
||||
if success && !enterprise {
|
||||
if success {
|
||||
thread_manager.invalidate_mcp_runtimes().await;
|
||||
}
|
||||
|
||||
@@ -432,11 +340,7 @@ impl McpRequestProcessor {
|
||||
.as_ref()
|
||||
.map(|thread| thread.mcp_manager())
|
||||
.unwrap_or_else(|| self.thread_manager.mcp_manager());
|
||||
self.thread_manager
|
||||
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
let auth = mcp_manager.auth_manager().auth().await;
|
||||
let runtime_auth = mcp_manager.runtime_auth_for_config(&config);
|
||||
let (mcp_config, runtime_context) = match thread.as_ref() {
|
||||
Some(thread) => thread.runtime_mcp_config_and_context(&config).await,
|
||||
None => (
|
||||
@@ -447,66 +351,15 @@ impl McpRequestProcessor {
|
||||
),
|
||||
),
|
||||
};
|
||||
let mut snapshot = collect_mcp_server_status_snapshot_with_detail(
|
||||
let snapshot = collect_mcp_server_status_snapshot_with_detail(
|
||||
&mcp_config,
|
||||
auth.as_ref(),
|
||||
Some(&self.auth_manager),
|
||||
runtime_auth,
|
||||
runtime_context,
|
||||
mcp_manager.codex_apps_tools_cache(),
|
||||
mcp_manager.tool_catalog_cache(),
|
||||
detail,
|
||||
params.server_name.as_deref(),
|
||||
)
|
||||
.await;
|
||||
if mcp_config.xaa_enabled
|
||||
&& let Some(thread) = thread.as_ref()
|
||||
{
|
||||
// EMA can only use its admitted thread connection. Keep ordinary
|
||||
// status discovery unchanged and replace the threadless EMA results.
|
||||
for (name, server) in mcp_config.mcp_server_catalog.configured_servers() {
|
||||
if !matches!(server.auth, McpServerAuth::EmaAuth) {
|
||||
continue;
|
||||
}
|
||||
let (selected_config, mut selected) = thread
|
||||
.mcp_server_status_snapshot(
|
||||
&name,
|
||||
detail,
|
||||
mcp_config.mcp_server_catalog.server(&name),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
internal_error(format!("failed to read MCP server status: {error:#}"))
|
||||
})?;
|
||||
if selected_config.mcp_server_catalog.server(&name)
|
||||
!= mcp_config.mcp_server_catalog.server(&name)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
snapshot.server_infos.remove(&name);
|
||||
snapshot.server_infos.extend(selected.server_infos);
|
||||
snapshot.server_capabilities.remove(&name);
|
||||
if let Some(capabilities) = selected.server_capabilities.remove(&name) {
|
||||
snapshot
|
||||
.server_capabilities
|
||||
.insert(name.clone(), capabilities);
|
||||
}
|
||||
snapshot.tools_by_server.remove(&name);
|
||||
snapshot.tools_by_server.extend(selected.tools_by_server);
|
||||
snapshot.tool_list_meta.remove(&name);
|
||||
snapshot.tool_list_meta.extend(selected.tool_list_meta);
|
||||
snapshot.tools_errors.remove(&name);
|
||||
snapshot.tools_errors.extend(selected.tools_errors);
|
||||
snapshot.resources.remove(&name);
|
||||
snapshot.resources.extend(selected.resources);
|
||||
snapshot.resource_templates.remove(&name);
|
||||
snapshot
|
||||
.resource_templates
|
||||
.extend(selected.resource_templates);
|
||||
snapshot.auth_statuses.remove(&name);
|
||||
snapshot.auth_statuses.extend(selected.auth_statuses);
|
||||
}
|
||||
}
|
||||
(Arc::new(mcp_config), snapshot)
|
||||
};
|
||||
|
||||
@@ -621,59 +474,24 @@ impl McpRequestProcessor {
|
||||
let McpResourceReadParams {
|
||||
meta,
|
||||
thread_id,
|
||||
origin_call_id,
|
||||
server,
|
||||
uri,
|
||||
connector_id,
|
||||
target,
|
||||
} = params;
|
||||
let mut resource_params = ReadResourceRequestParams::new(uri);
|
||||
let mut meta = meta.unwrap_or_default();
|
||||
let is_codex_apps = server == codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
let reserved_key = meta.iter().find_map(|(key, value)| match key.as_str() {
|
||||
"x-codex-turn-metadata"
|
||||
| MCP_THREAD_ID_META_KEY
|
||||
| codex_mcp::MCP_CONNECTION_LEASE_META_KEY => Some(key.as_str()),
|
||||
"connector_id" | "link_id" if is_codex_apps => Some(key.as_str()),
|
||||
// This legacy routing hint can override an explicit app and account target.
|
||||
"_codex_apps" if is_codex_apps && value.get("resource_uri").is_some() => {
|
||||
Some("_codex_apps.resource_uri")
|
||||
}
|
||||
_ => None,
|
||||
let meta = meta.unwrap_or_default();
|
||||
let reserved_key = meta.keys().find(|key| {
|
||||
matches!(
|
||||
key.as_str(),
|
||||
"x-codex-turn-metadata"
|
||||
| MCP_THREAD_ID_META_KEY
|
||||
| codex_mcp::MCP_CONNECTION_LEASE_META_KEY
|
||||
)
|
||||
});
|
||||
if let Some(key) = reserved_key {
|
||||
return Err(invalid_request(format!(
|
||||
"reserved resource read metadata key: {key}"
|
||||
)));
|
||||
}
|
||||
if let Some(connector_id) = connector_id {
|
||||
meta.insert(
|
||||
"x-codex-turn-metadata".to_string(),
|
||||
serde_json::json!({
|
||||
"mcp_request_meta": {"selected_connector_ids": [connector_id]},
|
||||
}),
|
||||
);
|
||||
}
|
||||
if origin_call_id.is_none()
|
||||
&& let Some(target) = target
|
||||
{
|
||||
if !is_codex_apps
|
||||
|| target.connector_id.trim().is_empty()
|
||||
|| target
|
||||
.link_id
|
||||
.as_ref()
|
||||
.is_some_and(|id| id.trim().is_empty() || id.starts_with("synthetic_link::"))
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"target requires codex_apps, a connectorId, and a real linkId or null",
|
||||
));
|
||||
}
|
||||
meta.insert(
|
||||
"connector_id".to_string(),
|
||||
serde_json::json!(target.connector_id),
|
||||
);
|
||||
meta.insert("link_id".to_string(), serde_json::json!(target.link_id));
|
||||
}
|
||||
if !meta.is_empty() {
|
||||
resource_params.meta = Some(meta.into());
|
||||
}
|
||||
@@ -683,35 +501,17 @@ impl McpRequestProcessor {
|
||||
let request_id = request_id.clone();
|
||||
|
||||
let task = async move {
|
||||
let origin_call_id = origin_call_id.filter(|_| is_codex_apps);
|
||||
let result = match origin_call_id.as_deref() {
|
||||
Some(call_id) => {
|
||||
thread
|
||||
.read_mcp_resource_for_call(call_id, resource_params)
|
||||
.await
|
||||
}
|
||||
None => thread.read_mcp_resource(&server, resource_params).await,
|
||||
};
|
||||
Self::send_mcp_resource_read_response(outgoing, request_id, result, origin_call_id)
|
||||
.await;
|
||||
let result = thread.read_mcp_resource(&server, resource_params).await;
|
||||
Self::send_mcp_resource_read_response(outgoing, request_id, result).await;
|
||||
};
|
||||
tokio::spawn(AuthStorageOriginator::current().scope(task));
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if origin_call_id.is_some() {
|
||||
return Err(invalid_request("originCallId requires threadId"));
|
||||
}
|
||||
|
||||
let config = self.load_global_config().await?;
|
||||
let mcp_manager = self.thread_manager.mcp_manager();
|
||||
let mcp_config = mcp_manager.runtime_config(&config).await;
|
||||
let codex_apps_tools_cache = mcp_manager.codex_apps_tools_cache();
|
||||
let tool_catalog_cache = mcp_manager.tool_catalog_cache();
|
||||
self.thread_manager
|
||||
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
let runtime_auth = mcp_manager.runtime_auth_for_config(&config);
|
||||
let auth = mcp_manager.auth_manager().auth().await;
|
||||
let environment_manager = self.thread_manager.environment_manager();
|
||||
// This threadless resource-read path has no turn cwd or turn-selected
|
||||
@@ -725,19 +525,14 @@ impl McpRequestProcessor {
|
||||
let result = read_mcp_resource_without_thread(
|
||||
&mcp_config,
|
||||
auth.as_ref(),
|
||||
runtime_auth,
|
||||
runtime_context,
|
||||
codex_apps_tools_cache,
|
||||
tool_catalog_cache,
|
||||
&server,
|
||||
resource_params,
|
||||
)
|
||||
.await
|
||||
.and_then(|result| serde_json::to_value(result).map_err(anyhow::Error::from));
|
||||
Self::send_mcp_resource_read_response(
|
||||
outgoing, request_id, result, /*origin_call_id*/ None,
|
||||
)
|
||||
.await;
|
||||
Self::send_mcp_resource_read_response(outgoing, request_id, result).await;
|
||||
};
|
||||
tokio::spawn(AuthStorageOriginator::current().scope(task));
|
||||
Ok(())
|
||||
@@ -747,7 +542,6 @@ impl McpRequestProcessor {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
request_id: ConnectionRequestId,
|
||||
result: anyhow::Result<serde_json::Value>,
|
||||
origin_call_id: Option<String>,
|
||||
) {
|
||||
let result = result
|
||||
.map_err(mcp_operation_error)
|
||||
@@ -757,10 +551,6 @@ impl McpRequestProcessor {
|
||||
"failed to deserialize MCP resource read response: {error}"
|
||||
))
|
||||
})
|
||||
})
|
||||
.map(|mut response| {
|
||||
response.origin_call_id = origin_call_id;
|
||||
response
|
||||
});
|
||||
outgoing.send_result(request_id, result).await;
|
||||
}
|
||||
|
||||
@@ -79,7 +79,6 @@ fn turn_context_item(
|
||||
collaboration_mode: None,
|
||||
multi_agent_version: None,
|
||||
realtime_active: None,
|
||||
cyber_access_program: None,
|
||||
effort: None,
|
||||
summary: Some(codex_protocol::config_types::ReasoningSummary::Auto),
|
||||
})
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,111 +0,0 @@
|
||||
//! Exposes shared installed-plugin reconciliation with hook lifecycle updates.
|
||||
|
||||
use super::*;
|
||||
use crate::effective_plugin_change::trust_materialized_plugin_hooks;
|
||||
use crate::request_serialization::RequestSerializationAccess;
|
||||
use crate::request_serialization::RequestSerializationQueueKey;
|
||||
use crate::request_serialization::RequestSerializationQueues;
|
||||
use codex_app_server_protocol::PluginReconcileChangedPlugin;
|
||||
use codex_app_server_protocol::PluginReconcileParams;
|
||||
use codex_app_server_protocol::PluginReconcileResponse;
|
||||
use codex_core_plugins::remote::RemotePluginShareDiscoverability;
|
||||
|
||||
impl PluginRequestProcessor {
|
||||
#[tracing::instrument(level = "debug", skip_all, fields(reason = ?params.reason))]
|
||||
pub(crate) async fn plugin_reconcile(
|
||||
&self,
|
||||
params: PluginReconcileParams,
|
||||
config_processor: ConfigRequestProcessor,
|
||||
request_serialization_queues: &RequestSerializationQueues,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let config = self.load_latest_config(/*fallback_cwd*/ None).await?;
|
||||
let plugins_input = config.plugins_config_input();
|
||||
let auth = self.auth_manager.auth().await;
|
||||
if !plugins_input.plugins_enabled
|
||||
|| !auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)
|
||||
{
|
||||
return Ok(Some(PluginReconcileResponse::default().into()));
|
||||
}
|
||||
|
||||
// Match background bundle sync: remote_plugin controls catalog visibility, not sync.
|
||||
// The shared reconciler owns synchronization, auth checks, and cache publication.
|
||||
let outcome = self
|
||||
.thread_manager
|
||||
.plugins_manager()
|
||||
.reconcile_remote_installed_plugins(&plugins_input, auth.as_ref())
|
||||
.await
|
||||
.map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to reconcile remote installed plugins: {err}"
|
||||
))
|
||||
})?;
|
||||
|
||||
let hooks_changed = outcome
|
||||
.changed_plugins
|
||||
.iter()
|
||||
.any(|plugin| plugin.capabilities.has_hooks);
|
||||
// Preserve materialization-owned trust: unchanged background passes cannot recover it.
|
||||
// Serialize hook updates with config writes, after releasing the bundle writer gate.
|
||||
// Changes without hooks or eligible materializations still skip this queue.
|
||||
if hooks_changed
|
||||
|| outcome.materialized_remote_plugins.iter().any(|plugin| {
|
||||
plugin.scope == RemotePluginScope::Workspace
|
||||
&& plugin.discoverability == Some(RemotePluginShareDiscoverability::Listed)
|
||||
})
|
||||
{
|
||||
let materializations = outcome.materialized_remote_plugins.clone();
|
||||
let processor = self.clone();
|
||||
let (complete, completion) = tokio::sync::oneshot::channel();
|
||||
request_serialization_queues
|
||||
.enqueue_background(
|
||||
RequestSerializationQueueKey::Global("config"),
|
||||
RequestSerializationAccess::Exclusive,
|
||||
async move {
|
||||
let result = trust_materialized_plugin_hooks(
|
||||
materializations,
|
||||
&processor.auth_manager,
|
||||
&processor.thread_manager,
|
||||
&processor.config_manager,
|
||||
&config_processor,
|
||||
)
|
||||
.await;
|
||||
// Removals and disablements have no trust write to rebuild loaded hooks.
|
||||
// Rebuild after the trust attempt, even if it failed, to drop stale hooks.
|
||||
if hooks_changed {
|
||||
processor.thread_manager.refresh_hook_runtimes().await;
|
||||
}
|
||||
let _ = complete.send(result);
|
||||
},
|
||||
)
|
||||
.await;
|
||||
completion
|
||||
.await
|
||||
.map_err(|err| {
|
||||
internal_error(format!("plugin hook trust update was cancelled: {err}"))
|
||||
})?
|
||||
.map_err(|err| {
|
||||
internal_error(format!("failed to trust materialized plugin hooks: {err}"))
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(Some(
|
||||
PluginReconcileResponse {
|
||||
changed_plugins: outcome
|
||||
.changed_plugins
|
||||
.into_iter()
|
||||
.map(|plugin| PluginReconcileChangedPlugin {
|
||||
id: plugin.plugin_id,
|
||||
has_mcps: plugin.capabilities.has_mcps,
|
||||
has_apps: plugin.capabilities.has_apps,
|
||||
has_hooks: plugin.capabilities.has_hooks,
|
||||
has_skills: plugin.capabilities.has_skills,
|
||||
})
|
||||
.collect(),
|
||||
failed_remote_plugin_ids: outcome.failed_remote_plugin_ids,
|
||||
failed_materialization_remote_plugin_ids: outcome
|
||||
.failed_materialization_remote_plugin_ids,
|
||||
}
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -4,11 +4,8 @@ use codex_app_server_protocol::PluginSearchResponse;
|
||||
use codex_app_server_protocol::PluginSearchResult;
|
||||
use codex_app_server_protocol::PluginSearchScope;
|
||||
use codex_core_plugins::OPENAI_BUNDLED_MARKETPLACE_NAME;
|
||||
use codex_core_plugins::remote::RemotePluginSearchRequest;
|
||||
use codex_core_plugins::remote::search_remote_plugins;
|
||||
use codex_core_plugins::is_openai_curated_marketplace_name;
|
||||
|
||||
const DEFAULT_PLUGIN_SEARCH_LIMIT: u32 = 16;
|
||||
const MAX_PLUGIN_SEARCH_LIMIT: u32 = 1_000;
|
||||
const MAX_LOCAL_PLUGIN_SEARCH_RESULTS: usize = 100;
|
||||
const PLUGIN_SEARCH_NO_MATCH_RANK: usize = 6;
|
||||
|
||||
@@ -31,14 +28,16 @@ impl PluginRequestProcessor {
|
||||
scope,
|
||||
cwds,
|
||||
cursor,
|
||||
limit,
|
||||
// Pagination limits only applied to the removed remote catalog.
|
||||
limit: _,
|
||||
} = params;
|
||||
let search_term = search_term.trim();
|
||||
let empty_response = || PluginSearchResponse {
|
||||
data: Vec::new(),
|
||||
next_cursor: None,
|
||||
};
|
||||
if search_term.is_empty() {
|
||||
// All local results are returned on the first page.
|
||||
if search_term.is_empty() || cursor.is_some() {
|
||||
return Ok(empty_response());
|
||||
}
|
||||
|
||||
@@ -48,88 +47,6 @@ impl PluginRequestProcessor {
|
||||
if !config.features.enabled(Feature::Plugins) {
|
||||
return Ok(empty_response());
|
||||
}
|
||||
let plugin_sharing_enabled = config.features.enabled(Feature::PluginSharing);
|
||||
|
||||
let auth = self.auth_manager.auth().await;
|
||||
let auth_mode = auth.as_ref().map(CodexAuth::api_auth_mode);
|
||||
let remote_plugin_enabled = config.features.enabled(Feature::RemotePlugin);
|
||||
let use_remote_global_catalog =
|
||||
remote_plugin_enabled && auth_mode.is_some_and(DomainAuthMode::uses_codex_backend);
|
||||
let remote_scope = if remote_plugin_enabled {
|
||||
Some(scope.map(|scope| match scope {
|
||||
PluginSearchScope::Global => RemotePluginScope::Global,
|
||||
PluginSearchScope::Workspace => RemotePluginScope::Workspace,
|
||||
PluginSearchScope::Personal => RemotePluginScope::User,
|
||||
}))
|
||||
} else {
|
||||
match scope {
|
||||
None | Some(PluginSearchScope::Workspace) => {
|
||||
Some(Some(RemotePluginScope::Workspace))
|
||||
}
|
||||
Some(PluginSearchScope::Global | PluginSearchScope::Personal) => None,
|
||||
}
|
||||
};
|
||||
let limit = limit
|
||||
.unwrap_or(DEFAULT_PLUGIN_SEARCH_LIMIT)
|
||||
.clamp(1, MAX_PLUGIN_SEARCH_LIMIT);
|
||||
let mut next_cursor = None;
|
||||
let mut remote_results = Vec::new();
|
||||
if auth_mode.is_some_and(DomainAuthMode::uses_codex_backend)
|
||||
&& let Some(remote_scope) = remote_scope
|
||||
{
|
||||
let page = search_remote_plugins(
|
||||
&remote_plugin_service_config(&self.thread_manager, &config)?,
|
||||
auth.as_ref(),
|
||||
RemotePluginSearchRequest {
|
||||
query: search_term,
|
||||
scope: remote_scope,
|
||||
limit,
|
||||
page_token: cursor.as_deref(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
remote_plugin_catalog_error_to_jsonrpc(err, "search remote plugin catalog")
|
||||
})?;
|
||||
|
||||
next_cursor = page.next_page_token;
|
||||
remote_results.reserve(page.plugins.len());
|
||||
let plugin_policy = &config.plugins;
|
||||
for plugin in page.plugins {
|
||||
let plugin_id = PluginId::parse(&plugin.id).map_err(|err| {
|
||||
internal_error(format!("invalid remote plugin search result id: {err}"))
|
||||
})?;
|
||||
|
||||
// NOTE: (brisebois) filter out plugins from the results that belong to "shared"
|
||||
// marketplaces if plugin sharing is disabled. There is a chance that this filters
|
||||
// out all results and returns an empty list to the client. Ideally this filtering
|
||||
// would be done server-side to avoid this problem.
|
||||
if !plugin_sharing_enabled
|
||||
&& matches!(
|
||||
plugin_id.marketplace_name.as_str(),
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME
|
||||
| REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME
|
||||
| REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME
|
||||
)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
remote_results.push(plugin_search_result(
|
||||
remote_plugin_summary_to_info(plugin, plugin_policy),
|
||||
plugin_id.marketplace_name,
|
||||
/*marketplace_path*/ None,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// All local results are stitched into the first page; if
|
||||
// we are not on the first page, don't even check local
|
||||
if cursor.is_some() {
|
||||
return Ok(PluginSearchResponse {
|
||||
data: remote_results,
|
||||
next_cursor,
|
||||
});
|
||||
}
|
||||
|
||||
let normalized_search_term = normalize_search_text(search_term);
|
||||
let mut local_results = Vec::new();
|
||||
@@ -137,19 +54,11 @@ impl PluginRequestProcessor {
|
||||
let roots = cwds.unwrap_or_default();
|
||||
let plugins_input = config.plugins_config_input();
|
||||
let plugins_manager = self.thread_manager.plugins_manager();
|
||||
let shared_plugin_ids_by_local_path = load_shared_plugin_ids_by_local_path(&config)
|
||||
.unwrap_or_else(|err| {
|
||||
warn!(
|
||||
error = %err.message,
|
||||
"plugin/search could not load shared plugin identities"
|
||||
);
|
||||
Default::default()
|
||||
});
|
||||
let outcome = tokio::task::spawn_blocking(move || {
|
||||
plugins_manager.list_marketplaces_for_config(
|
||||
&plugins_input,
|
||||
&roots,
|
||||
/*include_openai_curated*/ !use_remote_global_catalog,
|
||||
/*include_openai_curated*/ true,
|
||||
)
|
||||
})
|
||||
.await
|
||||
@@ -170,10 +79,7 @@ impl PluginRequestProcessor {
|
||||
}
|
||||
|
||||
for plugin in marketplace.plugins {
|
||||
let plugin = convert_configured_marketplace_plugin_to_plugin_summary(
|
||||
plugin,
|
||||
&shared_plugin_ids_by_local_path,
|
||||
);
|
||||
let plugin = convert_configured_marketplace_plugin_to_plugin_summary(plugin);
|
||||
local_results.push(plugin_search_result(
|
||||
plugin,
|
||||
marketplace.name.clone(),
|
||||
@@ -183,60 +89,19 @@ impl PluginRequestProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
let mut data = Vec::with_capacity(
|
||||
local_results.len().min(MAX_LOCAL_PLUGIN_SEARCH_RESULTS) + remote_results.len(),
|
||||
);
|
||||
let mut local_matches = Vec::new();
|
||||
let mut remote_results = remote_results.into_iter().map(Some).collect::<Vec<_>>();
|
||||
let mut seen_local_plugin_identities = HashSet::new();
|
||||
|
||||
for local_result in local_results {
|
||||
let local_remote_plugin_id =
|
||||
local_result.plugin.remote_plugin_id.as_deref().or_else(|| {
|
||||
local_result
|
||||
.plugin
|
||||
.share_context
|
||||
.as_ref()
|
||||
.map(|context| context.remote_plugin_id.as_str())
|
||||
});
|
||||
let remote_result_index = remote_results.iter().position(|remote_result| {
|
||||
remote_result.as_ref().is_some_and(|remote_result| {
|
||||
local_remote_plugin_id.is_some_and(|remote_plugin_id| {
|
||||
remote_result.plugin.remote_plugin_id.as_deref() == Some(remote_plugin_id)
|
||||
}) || local_result.plugin.id == remote_result.plugin.id
|
||||
|| (is_openai_curated_marketplace_name(&local_result.marketplace_name)
|
||||
&& remote_result.marketplace_name == REMOTE_GLOBAL_MARKETPLACE_NAME
|
||||
&& local_result.plugin.name == remote_result.plugin.name)
|
||||
})
|
||||
});
|
||||
|
||||
if remote_result_index.is_none()
|
||||
&& plugin_search_match_rank(&local_result.plugin, &normalized_search_term).is_none()
|
||||
{
|
||||
if plugin_search_match_rank(&local_result.plugin, &normalized_search_term).is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let local_identity = local_remote_plugin_id.map_or_else(
|
||||
|| {
|
||||
if is_openai_curated_marketplace_name(&local_result.marketplace_name) {
|
||||
format!("curated:{}", local_result.plugin.name)
|
||||
} else {
|
||||
format!("plugin:{}", local_result.plugin.id)
|
||||
}
|
||||
},
|
||||
|remote_plugin_id| format!("remote:{remote_plugin_id}"),
|
||||
);
|
||||
if !seen_local_plugin_identities.insert(local_identity) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(remote_result_index) = remote_result_index
|
||||
&& let Some(mut remote_result) = remote_results[remote_result_index].take()
|
||||
{
|
||||
remote_result.plugin.installed = local_result.plugin.installed;
|
||||
remote_result.plugin.local_version = local_result.plugin.local_version;
|
||||
data.push(remote_result);
|
||||
} else {
|
||||
let local_identity =
|
||||
if is_openai_curated_marketplace_name(&local_result.marketplace_name) {
|
||||
format!("curated:{}", local_result.plugin.name)
|
||||
} else {
|
||||
format!("plugin:{}", local_result.plugin.id)
|
||||
};
|
||||
if seen_local_plugin_identities.insert(local_identity) {
|
||||
local_matches.push(local_result);
|
||||
}
|
||||
}
|
||||
@@ -246,14 +111,11 @@ impl PluginRequestProcessor {
|
||||
.unwrap_or(PLUGIN_SEARCH_NO_MATCH_RANK)
|
||||
});
|
||||
local_matches.truncate(MAX_LOCAL_PLUGIN_SEARCH_RESULTS);
|
||||
data.extend(local_matches);
|
||||
data.extend(remote_results.into_iter().flatten());
|
||||
data.sort_by_key(|result| {
|
||||
plugin_search_match_rank(&result.plugin, &normalized_search_term)
|
||||
.unwrap_or(PLUGIN_SEARCH_NO_MATCH_RANK)
|
||||
});
|
||||
|
||||
Ok(PluginSearchResponse { data, next_cursor })
|
||||
Ok(PluginSearchResponse {
|
||||
data: local_matches,
|
||||
next_cursor: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,7 +145,6 @@ fn marketplace_matches_search_scope(
|
||||
OPENAI_BUNDLED_MARKETPLACE_NAME
|
||||
| "openai-bundled-alpha"
|
||||
| "codex-official"
|
||||
| "openai-curated-remote"
|
||||
| "openai-primary-runtime"
|
||||
);
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ use crate::config_manager::ConfigManager;
|
||||
use crate::outgoing_message::OutgoingEnvelope;
|
||||
use crate::outgoing_message::OutgoingMessage;
|
||||
use crate::thread_sample::SampleResponseRegistry;
|
||||
use crate::thread_state::ConnectionCapabilities;
|
||||
use crate::thread_state::PendingNetworkApproval;
|
||||
use crate::thread_state::resolve_server_request_on_thread_listener;
|
||||
use anyhow::Context;
|
||||
@@ -99,7 +98,7 @@ async fn listener_shutdown_releases_runtime_and_preserves_other_subscribers(
|
||||
];
|
||||
for &connection_id in &connection_ids {
|
||||
processor
|
||||
.connection_initialized(connection_id, ConnectionCapabilities::default())
|
||||
.connection_initialized(connection_id)
|
||||
.await;
|
||||
}
|
||||
let network_request_id = RequestId::Integer(4);
|
||||
|
||||
@@ -4,11 +4,6 @@ mod daemon_continuation;
|
||||
#[path = "daemon_snapshot.rs"]
|
||||
mod daemon_snapshot;
|
||||
|
||||
mod workspace_switching;
|
||||
|
||||
#[path = "thread_resume_account.rs"]
|
||||
mod thread_resume_account;
|
||||
|
||||
use super::persisted_resume_settings::PersistedResumeSettings;
|
||||
use super::persisted_resume_settings::latest_owned_thread_settings;
|
||||
use super::persisted_resume_settings::latest_persisted_model_settings;
|
||||
@@ -1296,7 +1291,6 @@ impl ThreadRequestProcessor {
|
||||
session_start_source,
|
||||
thread_source,
|
||||
project_id,
|
||||
daybreak_enabled,
|
||||
environments,
|
||||
} = params;
|
||||
if matches!(
|
||||
@@ -1381,7 +1375,6 @@ impl ThreadRequestProcessor {
|
||||
session_start_source,
|
||||
thread_source.map(Into::into),
|
||||
project_id,
|
||||
daybreak_enabled,
|
||||
environment_requests,
|
||||
service_name,
|
||||
allow_provider_model_fallback,
|
||||
@@ -1463,7 +1456,6 @@ impl ThreadRequestProcessor {
|
||||
session_start_source: Option<codex_app_server_protocol::ThreadStartSource>,
|
||||
thread_source: Option<codex_protocol::protocol::ThreadSource>,
|
||||
project_id: Option<String>,
|
||||
daybreak_enabled: Option<bool>,
|
||||
environment_requests: Option<Vec<TurnEnvironmentRequest>>,
|
||||
service_name: Option<String>,
|
||||
allow_provider_model_fallback: bool,
|
||||
@@ -1477,11 +1469,6 @@ impl ThreadRequestProcessor {
|
||||
.load_with_overrides(config_overrides.clone(), typesafe_overrides.clone())
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
if config.ephemeral && daybreak_enabled.is_some() {
|
||||
return Err(invalid_request(
|
||||
"daybreakEnabled is not supported for ephemeral threads",
|
||||
));
|
||||
}
|
||||
// Project-local config can launch host processes, so only the effective
|
||||
// permissions after managed constraints can imply project trust.
|
||||
let effective_permission_profile = config.permissions.effective_permission_profile();
|
||||
@@ -1611,7 +1598,6 @@ impl ThreadRequestProcessor {
|
||||
thread_store.as_ref(),
|
||||
StoreThreadMetadataPatch {
|
||||
project_id: project_id.clone().map(Some),
|
||||
daybreak_enabled,
|
||||
..Default::default()
|
||||
},
|
||||
"thread/start",
|
||||
@@ -1622,7 +1608,7 @@ impl ThreadRequestProcessor {
|
||||
.unwrap_or_else(|| listener_task_context.thread_manager.reserve_thread_id());
|
||||
start_options.reserved_thread_id = Some(thread_id);
|
||||
// Startup can prewarm the Responses socket before start_thread returns.
|
||||
// Register the creating client first so that handshake can request attestation.
|
||||
// Register the creating client first so it observes the startup handshake.
|
||||
listener_task_context
|
||||
.thread_state_manager
|
||||
.try_add_connection_to_thread(thread_id, request_id.connection_id)
|
||||
@@ -1706,7 +1692,6 @@ impl ThreadRequestProcessor {
|
||||
session_configured.rollout_path.clone(),
|
||||
);
|
||||
thread.project_id = project_id.clone();
|
||||
thread.daybreak_enabled = daybreak_enabled;
|
||||
|
||||
// Auto-attach a thread listener when starting a thread.
|
||||
log_listener_attach_result(
|
||||
@@ -2057,7 +2042,6 @@ impl ThreadRequestProcessor {
|
||||
thread_id,
|
||||
project_id,
|
||||
git_info,
|
||||
daybreak_enabled,
|
||||
} = params;
|
||||
let thread_uuid = ThreadId::from_string(&thread_id)
|
||||
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
|
||||
@@ -2080,7 +2064,7 @@ impl ThreadRequestProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
if git_info.is_none() && project_id.is_none() && daybreak_enabled.is_none() {
|
||||
if git_info.is_none() && project_id.is_none() {
|
||||
return Err(invalid_request(
|
||||
"thread metadata update must include at least one field",
|
||||
));
|
||||
@@ -2158,7 +2142,6 @@ impl ThreadRequestProcessor {
|
||||
let patch = StoreThreadMetadataPatch {
|
||||
git_info,
|
||||
project_id: project_update.clone(),
|
||||
daybreak_enabled,
|
||||
..Default::default()
|
||||
};
|
||||
let updated_thread = self
|
||||
@@ -2283,15 +2266,7 @@ impl ThreadRequestProcessor {
|
||||
"thread/revert only supports paginated threads",
|
||||
));
|
||||
}
|
||||
let mut config = thread.config().await.as_ref().clone();
|
||||
// Give the replacement its own pending lifetime before removal revokes the old runtime.
|
||||
let ema_cancellation = config
|
||||
.config_layer_stack
|
||||
.mcp_ema_cancellation()
|
||||
.for_startup();
|
||||
config.config_layer_stack = config
|
||||
.config_layer_stack
|
||||
.with_mcp_ema_cancellation(ema_cancellation);
|
||||
let config = thread.config().await.as_ref().clone();
|
||||
let runtime_snapshot = ThreadRevertRuntimeSnapshot {
|
||||
config,
|
||||
settings: thread.restorable_thread_settings().await,
|
||||
@@ -3128,17 +3103,6 @@ impl ThreadRequestProcessor {
|
||||
thread_id: ThreadId,
|
||||
include_turns: bool,
|
||||
) -> Result<Thread, ThreadReadViewError> {
|
||||
// Read staging first: persistence can consume it while the stored thread is read.
|
||||
let pending_daybreak_enabled = self
|
||||
.thread_store
|
||||
.read_pending_thread_metadata(thread_id)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
ThreadReadViewError::Internal(format!(
|
||||
"failed to read pending thread metadata: {err}"
|
||||
))
|
||||
})?
|
||||
.and_then(|metadata| metadata.daybreak_enabled);
|
||||
let loaded_thread = self.thread_manager.get_thread(thread_id).await.ok();
|
||||
let mut thread = if include_turns {
|
||||
if let Some(loaded_thread) = loaded_thread.as_ref() {
|
||||
@@ -3192,8 +3156,6 @@ impl ThreadRequestProcessor {
|
||||
)));
|
||||
};
|
||||
|
||||
thread.daybreak_enabled = thread.daybreak_enabled.or(pending_daybreak_enabled);
|
||||
|
||||
let has_live_in_progress_turn = if let Some(loaded_thread) = loaded_thread.as_ref() {
|
||||
matches!(loaded_thread.agent_status().await, AgentStatus::Running)
|
||||
} else {
|
||||
@@ -3920,13 +3882,9 @@ impl ThreadRequestProcessor {
|
||||
self.thread_manager.subscribe_thread_created()
|
||||
}
|
||||
|
||||
pub(crate) async fn connection_initialized(
|
||||
&self,
|
||||
connection_id: ConnectionId,
|
||||
capabilities: ConnectionCapabilities,
|
||||
) {
|
||||
pub(crate) async fn connection_initialized(&self, connection_id: ConnectionId) {
|
||||
self.thread_state_manager
|
||||
.connection_initialized(connection_id, capabilities)
|
||||
.connection_initialized(connection_id)
|
||||
.await;
|
||||
}
|
||||
|
||||
@@ -4074,12 +4032,6 @@ impl ThreadRequestProcessor {
|
||||
.await?
|
||||
}
|
||||
};
|
||||
thread_resume_account::check(
|
||||
&self.config.features,
|
||||
app_server_client_name.as_deref(),
|
||||
&self.auth_manager,
|
||||
&stored_thread,
|
||||
)?;
|
||||
let (thread_history, stored_thread) = self
|
||||
.load_resume_initial_history_from_stored_thread(
|
||||
stored_thread,
|
||||
@@ -4726,12 +4678,6 @@ impl ThreadRequestProcessor {
|
||||
};
|
||||
|
||||
if let Some((existing_thread_id, existing_thread, mut source_thread)) = running_thread {
|
||||
thread_resume_account::check(
|
||||
&self.config.features,
|
||||
app_server_client_name.as_deref(),
|
||||
&self.auth_manager,
|
||||
&source_thread,
|
||||
)?;
|
||||
let paginated_resume =
|
||||
matches!(source_thread.history_mode, ThreadHistoryMode::Paginated);
|
||||
let existing_thread_rollout_path = existing_thread.rollout_path();
|
||||
@@ -5736,7 +5682,6 @@ impl ThreadRequestProcessor {
|
||||
self.thread_store.as_ref(),
|
||||
StoreThreadMetadataPatch {
|
||||
project_id: inherited_project_id.clone().map(Some),
|
||||
daybreak_enabled: source_thread.daybreak_enabled,
|
||||
..Default::default()
|
||||
},
|
||||
"thread/fork",
|
||||
@@ -6043,8 +5988,8 @@ impl ThreadRequestProcessor {
|
||||
return None;
|
||||
}
|
||||
Some(LocalHistoryAccount {
|
||||
user_id: auth.as_ref().and_then(CodexAuth::get_chatgpt_user_id),
|
||||
account_id: auth.as_ref().and_then(CodexAuth::get_account_id),
|
||||
user_id: None,
|
||||
account_id: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6749,7 +6694,6 @@ fn thread_from_stored_thread(
|
||||
thread_source: thread.thread_source.map(Into::into),
|
||||
git_info,
|
||||
name: thread.name,
|
||||
daybreak_enabled: thread.daybreak_enabled,
|
||||
turns: Vec::new(),
|
||||
};
|
||||
(thread, history)
|
||||
@@ -6935,7 +6879,6 @@ fn build_thread_from_snapshot(
|
||||
thread_source: config_snapshot.thread_source.clone().map(Into::into),
|
||||
git_info: None,
|
||||
name: None,
|
||||
daybreak_enabled: None,
|
||||
turns: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
//! Unloads old-workspace runtimes while turn admission is paused by the account switch.
|
||||
//! Resuming a thread builds fresh policy and transport state for the new workspace.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl ThreadRequestProcessor {
|
||||
pub(crate) async fn unload_for_workspace_switch(&self) -> Result<(), JSONRPCErrorError> {
|
||||
let report = self
|
||||
.thread_manager
|
||||
.shutdown_all_threads_bounded(Duration::from_secs(/*secs*/ 10))
|
||||
.await;
|
||||
for thread_id in report.completed {
|
||||
self.finalize_thread_teardown(thread_id).await;
|
||||
self.outgoing
|
||||
.send_server_notification(ServerNotification::ThreadClosed(
|
||||
codex_app_server_protocol::ThreadClosedNotification {
|
||||
thread_id: thread_id.to_string(),
|
||||
},
|
||||
))
|
||||
.await;
|
||||
}
|
||||
// A delegated child may have started while its parent was shutting down.
|
||||
// Never replace credentials until every runtime has stopped.
|
||||
if !report.submit_failed.is_empty()
|
||||
|| !report.timed_out.is_empty()
|
||||
|| !self.thread_manager.list_thread_ids().await.is_empty()
|
||||
{
|
||||
return Err(internal_error(
|
||||
"Some threads are still running; retry the workspace switch",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -155,7 +155,6 @@ mod thread_processor_behavior_tests {
|
||||
use codex_app_server_protocol::ThreadItem;
|
||||
use codex_app_server_protocol::ThreadItemPayload;
|
||||
use codex_app_server_protocol::ToolRequestUserInputParams;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::SessionThreadConfig;
|
||||
use codex_config::StaticThreadConfigLoader;
|
||||
@@ -523,7 +522,6 @@ mod thread_processor_behavior_tests {
|
||||
section_position: None,
|
||||
section_entered_at: None,
|
||||
project_id: None,
|
||||
daybreak_enabled: None,
|
||||
cwd: PathBuf::from("/tmp"),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
source: SessionSource::Cli,
|
||||
@@ -553,34 +551,7 @@ mod thread_processor_behavior_tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_load_error_marks_cloud_config_bundle_failures_for_relogin() {
|
||||
let err = std::io::Error::other(CloudConfigBundleLoadError::new(
|
||||
CloudConfigBundleLoadErrorCode::Auth,
|
||||
Some(401),
|
||||
"Your authentication session could not be refreshed automatically. Please log out and sign in again.",
|
||||
));
|
||||
|
||||
let error = config_load_error(&err);
|
||||
|
||||
assert_eq!(
|
||||
error.data,
|
||||
Some(json!({
|
||||
"reason": "cloudConfigBundle",
|
||||
"errorCode": "Auth",
|
||||
"action": "relogin",
|
||||
"statusCode": 401,
|
||||
"detail": "Your authentication session could not be refreshed automatically. Please log out and sign in again.",
|
||||
}))
|
||||
);
|
||||
assert!(
|
||||
error.message.contains("failed to load configuration"),
|
||||
"unexpected error message: {}",
|
||||
error.message
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_load_error_leaves_non_cloud_config_bundle_failures_unmarked() {
|
||||
fn config_load_error_leaves_generic_failures_unmarked() {
|
||||
let err = std::io::Error::other("required MCP servers failed to initialize");
|
||||
|
||||
let error = config_load_error(&err);
|
||||
@@ -593,46 +564,6 @@ mod thread_processor_behavior_tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_load_error_marks_non_auth_cloud_config_bundle_failures_without_relogin() {
|
||||
let err = std::io::Error::other(CloudConfigBundleLoadError::new(
|
||||
CloudConfigBundleLoadErrorCode::RequestFailed,
|
||||
/*status_code*/ None,
|
||||
"Failed to load cloud config bundle (workspace-managed policies).",
|
||||
));
|
||||
|
||||
let error = config_load_error(&err);
|
||||
|
||||
assert_eq!(
|
||||
error.data,
|
||||
Some(json!({
|
||||
"reason": "cloudConfigBundle",
|
||||
"errorCode": "RequestFailed",
|
||||
"detail": "Failed to load cloud config bundle (workspace-managed policies).",
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_load_error_marks_invalid_cloud_config_bundle_failures_without_relogin() {
|
||||
let err = std::io::Error::other(CloudConfigBundleLoadError::new(
|
||||
CloudConfigBundleLoadErrorCode::InvalidBundle,
|
||||
/*status_code*/ None,
|
||||
"invalid cloud config bundle: invalid cloud config fragment Base policy (cfg_123)",
|
||||
));
|
||||
|
||||
let error = config_load_error(&err);
|
||||
|
||||
assert_eq!(
|
||||
error.data,
|
||||
Some(json!({
|
||||
"reason": "cloudConfigBundle",
|
||||
"errorCode": "InvalidBundle",
|
||||
"detail": "invalid cloud config bundle: invalid cloud config fragment Base policy (cfg_123)",
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn derive_config_from_params_uses_session_thread_config_model_provider() -> Result<()> {
|
||||
let temp_dir = TempDir::new()?;
|
||||
@@ -668,7 +599,6 @@ mod thread_processor_behavior_tests {
|
||||
Vec::new(),
|
||||
LoaderOverrides::default(),
|
||||
/*strict_config*/ false,
|
||||
CloudConfigBundleLoader::default(),
|
||||
Arg0DispatchPaths::default(),
|
||||
Arc::new(StaticThreadConfigLoader::new(vec![
|
||||
ThreadConfigSource::Session(SessionThreadConfig {
|
||||
@@ -1241,7 +1171,7 @@ mod thread_processor_behavior_tests {
|
||||
let (cancel_tx, cancel_rx) = oneshot::channel();
|
||||
|
||||
manager
|
||||
.connection_initialized(connection, ConnectionCapabilities::default())
|
||||
.connection_initialized(connection)
|
||||
.await;
|
||||
assert!(
|
||||
manager
|
||||
@@ -1289,10 +1219,10 @@ mod thread_processor_behavior_tests {
|
||||
let (cancel_tx, mut cancel_rx) = oneshot::channel();
|
||||
|
||||
manager
|
||||
.connection_initialized(connection_a, ConnectionCapabilities::default())
|
||||
.connection_initialized(connection_a)
|
||||
.await;
|
||||
manager
|
||||
.connection_initialized(connection_b, ConnectionCapabilities::default())
|
||||
.connection_initialized(connection_b)
|
||||
.await;
|
||||
assert!(
|
||||
manager
|
||||
@@ -1334,10 +1264,10 @@ mod thread_processor_behavior_tests {
|
||||
let connection_b = ConnectionId(2);
|
||||
|
||||
manager
|
||||
.connection_initialized(connection_a, ConnectionCapabilities::default())
|
||||
.connection_initialized(connection_a)
|
||||
.await;
|
||||
manager
|
||||
.connection_initialized(connection_b, ConnectionCapabilities::default())
|
||||
.connection_initialized(connection_b)
|
||||
.await;
|
||||
assert!(
|
||||
manager
|
||||
@@ -1381,7 +1311,7 @@ mod thread_processor_behavior_tests {
|
||||
let thread_id = ThreadId::from_string("ba62fd70-2ec2-4b1b-9d94-355694332dd2")?;
|
||||
let connection = ConnectionId(1);
|
||||
manager
|
||||
.connection_initialized(connection, ConnectionCapabilities::default())
|
||||
.connection_initialized(connection)
|
||||
.await;
|
||||
|
||||
let wait_for_subscriber = manager.wait_for_thread_subscriber(thread_id);
|
||||
@@ -1407,7 +1337,7 @@ mod thread_processor_behavior_tests {
|
||||
let connection = ConnectionId(1);
|
||||
|
||||
manager
|
||||
.connection_initialized(connection, ConnectionCapabilities::default())
|
||||
.connection_initialized(connection)
|
||||
.await;
|
||||
let threads_to_unload = manager.remove_connection(connection).await;
|
||||
assert_eq!(threads_to_unload, Vec::<ThreadId>::new());
|
||||
@@ -1421,78 +1351,4 @@ mod thread_processor_behavior_tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn first_attestation_capable_connection_for_thread_only_uses_thread_subscribers()
|
||||
-> Result<()> {
|
||||
let manager = ThreadStateManager::new();
|
||||
let thread_id = ThreadId::from_string("dfbd9a95-2f44-470a-8bd8-1cfc04efc243")?;
|
||||
let other_thread_id = ThreadId::from_string("6c9a74e4-5e59-479e-90bf-5c5798bb50aa")?;
|
||||
let unrelated_supported_connection = ConnectionId(1);
|
||||
let earlier_supported_connection = ConnectionId(2);
|
||||
let later_supported_connection = ConnectionId(3);
|
||||
let unsupported_connection = ConnectionId(4);
|
||||
|
||||
manager
|
||||
.connection_initialized(
|
||||
unrelated_supported_connection,
|
||||
ConnectionCapabilities {
|
||||
request_attestation: true,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
manager
|
||||
.connection_initialized(
|
||||
earlier_supported_connection,
|
||||
ConnectionCapabilities {
|
||||
request_attestation: true,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
manager
|
||||
.connection_initialized(
|
||||
later_supported_connection,
|
||||
ConnectionCapabilities {
|
||||
request_attestation: true,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
manager
|
||||
.connection_initialized(unsupported_connection, ConnectionCapabilities::default())
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
manager
|
||||
.try_add_connection_to_thread(other_thread_id, unrelated_supported_connection)
|
||||
.await
|
||||
);
|
||||
assert!(
|
||||
manager
|
||||
.try_add_connection_to_thread(thread_id, later_supported_connection)
|
||||
.await
|
||||
);
|
||||
assert!(
|
||||
manager
|
||||
.try_add_connection_to_thread(thread_id, earlier_supported_connection)
|
||||
.await
|
||||
);
|
||||
assert!(
|
||||
manager
|
||||
.try_add_connection_to_thread(thread_id, unsupported_connection)
|
||||
.await
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
manager
|
||||
.first_attestation_capable_connection_for_thread(thread_id)
|
||||
.await,
|
||||
Some(earlier_supported_connection)
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.first_attestation_capable_connection_for_thread(other_thread_id)
|
||||
.await,
|
||||
Some(unrelated_supported_connection)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
//! Applies the rollout-gated CLI account check before resuming or attaching to a local thread.
|
||||
//! Creator tags are immutable; untagged threads and other clients retain existing behavior.
|
||||
|
||||
use crate::error_code::invalid_request;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_features::Feature;
|
||||
use codex_features::Features;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_thread_store::StoredThread;
|
||||
|
||||
pub(super) fn check(
|
||||
features: &Features,
|
||||
client_name: Option<&str>,
|
||||
auth_manager: &AuthManager,
|
||||
thread: &StoredThread,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
if !features.enabled(Feature::CliResumeAccountCheck)
|
||||
|| !matches!(client_name, Some("codex-tui" | "codex_exec"))
|
||||
|| thread.rollout_path.is_none()
|
||||
|| (thread.creator_user_id.is_none() && thread.creator_account_id.is_none())
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let Some(auth) = auth_manager
|
||||
.auth_cached()
|
||||
.filter(CodexAuth::is_chatgpt_auth)
|
||||
else {
|
||||
// API keys and other auth modes do not identify a comparable ChatGPT account.
|
||||
return Ok(());
|
||||
};
|
||||
if thread
|
||||
.creator_user_id
|
||||
.as_ref()
|
||||
.is_some_and(|creator| auth.get_chatgpt_user_id().as_ref() != Some(creator))
|
||||
|| thread
|
||||
.creator_account_id
|
||||
.as_ref()
|
||||
.is_some_and(|creator| auth.get_account_id().as_ref() != Some(creator))
|
||||
{
|
||||
return Err(invalid_request(
|
||||
"This thread was created with a different ChatGPT account or workspace. Sign in with the original account to resume it.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -226,7 +226,6 @@ mod tests {
|
||||
section: None,
|
||||
section_entered_at: None,
|
||||
project_id: None,
|
||||
daybreak_enabled: None,
|
||||
history_mode: Default::default(),
|
||||
model_provider: "mock_provider".to_string(),
|
||||
model: None,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use super::*;
|
||||
#[cfg(test)]
|
||||
use std::io::Error as IoError;
|
||||
#[cfg(test)]
|
||||
use chrono::DateTime;
|
||||
#[cfg(test)]
|
||||
use chrono::Utc;
|
||||
@@ -290,7 +292,6 @@ pub(crate) fn summary_to_thread(
|
||||
thread_source: None,
|
||||
git_info,
|
||||
name: None,
|
||||
daybreak_enabled: None,
|
||||
turns: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -653,7 +653,6 @@ impl TurnRequestProcessor {
|
||||
final_output_json_schema: params.output_schema,
|
||||
service_tier: params.service_tier_for_turn,
|
||||
prompt_cache_ttl: None,
|
||||
cyber_access_program: params.cyber_access_program.map(Into::into),
|
||||
..Default::default()
|
||||
})
|
||||
.with_additional_context(additional_context)
|
||||
|
||||
Reference in New Issue
Block a user