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:
andrea.difonzo
2026-11-10 16:20:15 +01:00
parent 82347a58ed
commit 6089fbde91
1573 changed files with 10289 additions and 177679 deletions

View File

@@ -7,7 +7,6 @@ use std::path::PathBuf;
use std::process::Stdio;
use anyhow::Context as _;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_core::config::Config;
use codex_core::config::ConfigBuilder;
@@ -666,7 +665,6 @@ async fn load_debug_sandbox_config(
codex_linux_sandbox_exe,
options,
/*codex_home*/ None,
CloudConfigBundleLoader::default(),
strict_config,
)
.await
@@ -677,7 +675,6 @@ async fn load_debug_sandbox_config_with_codex_home(
codex_linux_sandbox_exe: Option<PathBuf>,
options: DebugSandboxConfigOptions,
codex_home: Option<PathBuf>,
cloud_config_bundle: CloudConfigBundleLoader,
strict_config: bool,
) -> anyhow::Result<Config> {
let DebugSandboxConfigOptions {
@@ -711,7 +708,6 @@ async fn load_debug_sandbox_config_with_codex_home(
codex_home.clone(),
managed_requirements_mode,
loader_overrides.clone(),
cloud_config_bundle.clone(),
strict_config,
)
.await?;
@@ -731,7 +727,6 @@ async fn load_debug_sandbox_config_with_codex_home(
codex_home,
managed_requirements_mode,
loader_overrides,
cloud_config_bundle,
strict_config,
)
.await
@@ -744,13 +739,11 @@ async fn build_debug_sandbox_config_with_loader_overrides(
codex_home: Option<PathBuf>,
managed_requirements_mode: ManagedRequirementsMode,
mut loader_overrides: LoaderOverrides,
cloud_config_bundle: CloudConfigBundleLoader,
strict_config: bool,
) -> std::io::Result<Config> {
let mut builder = ConfigBuilder::default()
.cli_overrides(cli_overrides)
.harness_overrides(harness_overrides)
.cloud_config_bundle(cloud_config_bundle)
.strict_config(strict_config);
if matches!(managed_requirements_mode, ManagedRequirementsMode::Ignore) {
loader_overrides.ignore_managed_requirements = true;
@@ -782,20 +775,20 @@ fn cli_overrides_use_legacy_sandbox_mode(cli_overrides: &[(String, TomlValue)])
mod tests {
use super::*;
use codex_config::ConfigRequirementsToml;
use codex_config::test_support::CloudConfigBundleFixture;
use codex_config::test_support::ManagedConfigFixture;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
const CLOUD_MANAGED_PERMISSION_PROFILE_REQUIREMENTS: &str = r#"
default_permissions = "managed-cloud"
const MANAGED_PERMISSION_PROFILE_REQUIREMENTS: &str = r#"
default_permissions = "managed-profile"
[allowed_permission_profiles]
managed-cloud = true
managed-profile = true
[permissions.managed-cloud]
[permissions.managed-profile]
extends = ":workspace"
[permissions.managed-cloud.network]
[permissions.managed-profile.network]
enabled = true
"#;
@@ -812,7 +805,6 @@ enabled = true
codex_home,
managed_requirements_mode,
LoaderOverrides::default(),
CloudConfigBundleLoader::default(),
strict_config,
)
.await
@@ -896,7 +888,6 @@ enabled = true
loader_overrides: LoaderOverrides::default(),
},
Some(codex_home_path),
CloudConfigBundleLoader::default(),
/*strict_config*/ false,
)
.await?;
@@ -940,7 +931,6 @@ enabled = true
Some(codex_home_path.clone()),
ManagedRequirementsMode::Include,
loader_overrides.clone(),
CloudConfigBundleLoader::default(),
/*strict_config*/ false,
)
.await?;
@@ -967,7 +957,6 @@ enabled = true
loader_overrides,
},
Some(codex_home_path),
CloudConfigBundleLoader::default(),
/*strict_config*/ false,
)
.await?;
@@ -1026,7 +1015,6 @@ enabled = true
loader_overrides: LoaderOverrides::default(),
},
Some(codex_home_path),
CloudConfigBundleLoader::default(),
/*strict_config*/ false,
)
.await?;
@@ -1086,7 +1074,6 @@ enabled = true
loader_overrides: LoaderOverrides::default(),
},
Some(codex_home_path),
CloudConfigBundleLoader::default(),
/*strict_config*/ false,
)
.await?;
@@ -1115,7 +1102,6 @@ enabled = true
loader_overrides: LoaderOverrides::default(),
},
Some(codex_home.path().to_path_buf()),
CloudConfigBundleLoader::default(),
/*strict_config*/ false,
)
.await?;
@@ -1138,7 +1124,7 @@ enabled = true
}
#[tokio::test]
async fn debug_sandbox_honors_explicit_cloud_managed_permission_profile() -> anyhow::Result<()>
async fn debug_sandbox_honors_explicit_managed_permission_profile() -> anyhow::Result<()>
{
let codex_home = TempDir::new()?;
@@ -1147,15 +1133,15 @@ enabled = true
/*codex_linux_sandbox_exe*/ None,
DebugSandboxConfigOptions {
sandbox_state: Default::default(),
permissions_profile: Some("managed-cloud".to_string()),
permissions_profile: Some("managed-profile".to_string()),
cwd: None,
managed_requirements_mode: ManagedRequirementsMode::Include,
loader_overrides: LoaderOverrides::without_managed_config_for_tests(),
loader_overrides: ManagedConfigFixture::requirements(
MANAGED_PERMISSION_PROFILE_REQUIREMENTS,
)
.loader_overrides_for_tests(codex_home.path())?,
},
Some(codex_home.path().to_path_buf()),
CloudConfigBundleFixture::loader_with_enterprise_requirement(
CLOUD_MANAGED_PERMISSION_PROFILE_REQUIREMENTS,
),
/*strict_config*/ false,
)
.await?;
@@ -1165,7 +1151,7 @@ enabled = true
.permissions
.active_permission_profile()
.map(|profile| profile.id),
Some("managed-cloud".to_string()),
Some("managed-profile".to_string()),
);
assert_eq!(
config.permissions.network_sandbox_policy(),
@@ -1174,7 +1160,7 @@ enabled = true
assert_eq!(
config.config_layer_stack.requirements_toml(),
&toml::from_str::<ConfigRequirementsToml>(
CLOUD_MANAGED_PERMISSION_PROFILE_REQUIREMENTS,
MANAGED_PERMISSION_PROFILE_REQUIREMENTS,
)?,
);
@@ -1182,7 +1168,7 @@ enabled = true
}
#[tokio::test]
async fn debug_sandbox_ignores_cloud_managed_permission_profiles_by_default()
async fn debug_sandbox_ignores_managed_permission_profiles_by_default()
-> anyhow::Result<()> {
let codex_home = TempDir::new()?;
@@ -1194,12 +1180,12 @@ enabled = true
permissions_profile: Some(":workspace".to_string()),
cwd: None,
managed_requirements_mode: ManagedRequirementsMode::Ignore,
loader_overrides: LoaderOverrides::without_managed_config_for_tests(),
loader_overrides: ManagedConfigFixture::requirements(
MANAGED_PERMISSION_PROFILE_REQUIREMENTS,
)
.loader_overrides_for_tests(codex_home.path())?,
},
Some(codex_home.path().to_path_buf()),
CloudConfigBundleFixture::loader_with_enterprise_requirement(
CLOUD_MANAGED_PERMISSION_PROFILE_REQUIREMENTS,
),
/*strict_config*/ false,
)
.await?;
@@ -1242,7 +1228,6 @@ enabled = true
loader_overrides: LoaderOverrides::default(),
},
Some(codex_home.path().to_path_buf()),
CloudConfigBundleLoader::default(),
/*strict_config*/ false,
)
.await?;
@@ -1283,7 +1268,6 @@ enabled = true
loader_overrides: LoaderOverrides::default(),
},
Some(codex_home.path().to_path_buf()),
CloudConfigBundleLoader::default(),
/*strict_config*/ false,
)
.await?;

View File

@@ -41,7 +41,6 @@ use codex_core::config::ConfigOverrides;
use codex_core::config::LoaderOverrides;
use codex_core::config::find_codex_home;
use codex_features::FEATURES;
use codex_features::Feature;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_http_client::OpenAiDestination;
@@ -54,7 +53,6 @@ use codex_install_context::InstallMethod;
use codex_install_context::StandalonePlatform;
use codex_login::AuthDotJson;
use codex_login::AuthManager;
use codex_login::CODEX_ACCESS_TOKEN_ENV_VAR;
use codex_login::CODEX_API_KEY_ENV_VAR;
use codex_login::CodexAuth;
use codex_login::OPENAI_API_KEY_ENV_VAR;
@@ -642,7 +640,7 @@ async fn load_config(
..config_overrides_from_interactive(interactive, arg0_paths)
};
let config = crate::cloud_config::config_builder(
let config = crate::local_config::config_builder(
&root_config_overrides,
LoaderOverrides::default(),
overrides,
@@ -1119,7 +1117,7 @@ fn codex_path_entries() -> Vec<String> {
fn config_check(config: &Config) -> DoctorCheck {
let mut details = Vec::new();
details
.push("configuration scope: invocation config, including cloud-managed policy".to_string());
.push("configuration scope: invocation config, including managed policy".to_string());
details.push("active thread overrides: not inspected".to_string());
details.push(format!("CODEX_HOME: {}", config.codex_home.display()));
details.push(format!("cwd: {}", config.cwd.display()));
@@ -1232,14 +1230,10 @@ fn auth_check(config: &Config) -> DoctorCheck {
));
details.push(format!("auth file: {}", auth_path.display()));
let env_auth_vars = [
OPENAI_API_KEY_ENV_VAR,
CODEX_API_KEY_ENV_VAR,
CODEX_ACCESS_TOKEN_ENV_VAR,
]
.into_iter()
.filter(|name| env_var_present(name))
.collect::<Vec<_>>();
let env_auth_vars = [OPENAI_API_KEY_ENV_VAR, CODEX_API_KEY_ENV_VAR]
.into_iter()
.filter(|name| env_var_present(name))
.collect::<Vec<_>>();
if !env_auth_vars.is_empty() {
details.push(format!(
"auth env vars present: {}",
@@ -1264,11 +1258,6 @@ fn auth_check(config: &Config) -> DoctorCheck {
Ok(Some(auth)) => {
details.push(format!("stored auth mode: {}", stored_auth_mode(&auth)));
details.push(format!("stored API key: {}", auth.openai_api_key.is_some()));
details.push(format!("stored ChatGPT tokens: {}", auth.tokens.is_some()));
details.push(format!(
"stored agent identity: {}",
auth.agent_identity.is_some()
));
let auth_issues = stored_auth_issues(&auth, env_var_present);
details.extend(
auth_issues
@@ -1296,7 +1285,9 @@ fn auth_check(config: &Config) -> DoctorCheck {
DoctorCheck::new("auth.credentials", "auth", status, summary).details(details);
if status == CheckStatus::Fail {
check =
check.remediation("Run codex login again or provide a supported auth env var.");
check.remediation(
"Run codex login --with-api-key again or provide a supported auth env var.",
);
}
check
}
@@ -1314,7 +1305,9 @@ fn auth_check(config: &Config) -> DoctorCheck {
"no Codex credentials were found",
)
.details(details)
.remediation("Run codex login or provide an API key through a supported auth env var."),
.remediation(
"Run codex login --with-api-key or provide an API key through a supported auth env var.",
),
Err(err) => DoctorCheck::new(
"auth.credentials",
"auth",
@@ -1383,31 +1376,27 @@ fn provider_specific_auth_check(
fn stored_auth_mode(auth: &codex_login::AuthDotJson) -> &'static str {
match stored_auth_mode_value(auth) {
AuthMode::ApiKey => "api_key",
AuthMode::Chatgpt => "chatgpt",
AuthMode::ChatgptAuthTokens => "chatgpt_auth_tokens",
AuthMode::Headers => "headers",
AuthMode::AgentIdentity => "agent_identity",
AuthMode::PersonalAccessToken => "personal_access_token",
AuthMode::BedrockApiKey => "bedrock_api_key",
AuthMode::BedrockAccessKeys => "bedrock_access_keys",
Some(AuthMode::ApiKey) => "api_key",
Some(AuthMode::Headers) => "headers",
Some(AuthMode::BedrockApiKey) => "bedrock_api_key",
Some(AuthMode::BedrockAccessKeys) => "bedrock_access_keys",
None => "unsupported",
}
}
fn stored_auth_mode_value(auth: &AuthDotJson) -> AuthMode {
/// Returns `None` for records written by sign-in methods that are no longer supported.
fn stored_auth_mode_value(auth: &AuthDotJson) -> Option<AuthMode> {
if let Some(mode) = auth.auth_mode {
return mode;
return Some(mode);
}
if auth.personal_access_token.is_some() {
AuthMode::PersonalAccessToken
} else if auth.bedrock_api_key.is_some() {
AuthMode::BedrockApiKey
if auth.bedrock_api_key.is_some() {
Some(AuthMode::BedrockApiKey)
} else if auth.bedrock_access_keys.is_some() {
AuthMode::BedrockAccessKeys
Some(AuthMode::BedrockAccessKeys)
} else if auth.openai_api_key.is_some() {
AuthMode::ApiKey
Some(AuthMode::ApiKey)
} else {
AuthMode::Chatgpt
None
}
}
@@ -1416,7 +1405,13 @@ fn stored_auth_issues(
env_var_present: impl Fn(&str) -> bool,
) -> Vec<&'static str> {
let mut issues = Vec::new();
match stored_auth_mode_value(auth) {
let Some(mode) = stored_auth_mode_value(auth) else {
issues.push(
"stored credentials use an unsupported sign-in method; run codex logout and codex login --with-api-key",
);
return issues;
};
match mode {
AuthMode::ApiKey => {
let stored_key_present = auth
.openai_api_key
@@ -1428,59 +1423,9 @@ fn stored_auth_issues(
issues.push("API key auth is missing an API key");
}
}
AuthMode::Chatgpt => {
match auth.tokens.as_ref() {
Some(tokens) => {
if tokens.access_token.trim().is_empty() {
issues.push("ChatGPT auth is missing an access token");
}
if tokens.refresh_token.trim().is_empty() {
issues.push("ChatGPT auth is missing a refresh token");
}
}
None => issues.push("ChatGPT auth is missing token data"),
}
if auth.last_refresh.is_none() {
issues.push("ChatGPT auth is missing refresh metadata");
}
}
AuthMode::ChatgptAuthTokens => {
match auth.tokens.as_ref() {
Some(tokens) => {
if tokens.access_token.trim().is_empty() {
issues.push("external ChatGPT auth is missing an access token");
}
if tokens.account_id.is_none() && tokens.id_token.chatgpt_account_id.is_none() {
issues.push("external ChatGPT auth is missing a ChatGPT account id");
}
}
None => issues.push("external ChatGPT auth is missing token data"),
}
if auth.last_refresh.is_none() {
issues.push("external ChatGPT auth is missing refresh metadata");
}
}
AuthMode::Headers => {
issues.push("header auth cannot be loaded from auth storage");
}
AuthMode::AgentIdentity => {
if auth
.agent_identity
.as_ref()
.is_none_or(|agent_identity| !agent_identity.has_auth_material())
{
issues.push("agent identity auth is missing an agent identity token");
}
}
AuthMode::PersonalAccessToken => {
if auth
.personal_access_token
.as_deref()
.is_none_or(|token| token.trim().is_empty())
{
issues.push("personal access token auth is missing a personal access token");
}
}
AuthMode::BedrockApiKey => {
if auth.bedrock_api_key.is_none() {
issues.push("Bedrock API key auth is missing a Bedrock API key");
@@ -2357,31 +2302,13 @@ async fn websocket_reachability_check(
));
let setup = async {
let runtime_auth = if config.features.enabled(Feature::RuntimeAgentInstances)
&& let Some(credentials) = &auth_manager
{
let installation_id = codex_core::resolve_installation_id(&config.codex_home).await?;
codex_core::build_runtime_auth_manager(
config,
Arc::clone(credentials),
&installation_id,
)
.map(|runtime| (runtime, config.runtime_auth_mode))
} else {
None
};
let runtime_provider = match auth_manager {
Some(credentials) => codex_model_provider::ProviderAuthContext {
credentials,
runtime_auth,
}
.model_provider(provider.clone()),
Some(credentials) => codex_model_provider::ProviderAuthContext { credentials }
.model_provider(provider.clone()),
None => create_model_provider(provider.clone(), /*auth_manager*/ None),
};
codex_model_provider::resolve_request(
runtime_provider.as_ref(),
/*scope*/ None,
Some(&config.workspace_routing_context()),
config.http_client_factory(),
)
.await
@@ -2565,11 +2492,7 @@ fn close_reason_detail(reason: &str) -> &'static str {
fn auth_mode_name(auth: &CodexAuth) -> &'static str {
match auth.auth_mode() {
AuthMode::ApiKey => "api_key",
AuthMode::Chatgpt => "chatgpt",
AuthMode::ChatgptAuthTokens => "chatgpt_auth_tokens",
AuthMode::Headers => "headers",
AuthMode::AgentIdentity => "agent_identity",
AuthMode::PersonalAccessToken => "personal_access_token",
AuthMode::BedrockApiKey => "bedrock_api_key",
AuthMode::BedrockAccessKeys => "bedrock_access_keys",
}
@@ -2641,7 +2564,6 @@ struct ReachabilityEndpoint {
enum ProviderAuthReachabilityMode {
NotRequired,
ApiKey,
Chatgpt,
}
impl ProviderAuthReachabilityMode {
@@ -2649,7 +2571,6 @@ impl ProviderAuthReachabilityMode {
match self {
Self::NotRequired => "provider auth",
Self::ApiKey => "API key auth",
Self::Chatgpt => "ChatGPT auth",
}
}
}
@@ -2716,21 +2637,11 @@ fn provider_auth_reachability_mode_from_auth(
{
return ProviderAuthReachabilityMode::ApiKey;
}
if env_var_present(CODEX_ACCESS_TOKEN_ENV_VAR) {
return ProviderAuthReachabilityMode::Chatgpt;
}
match stored_auth.map(stored_auth_mode_value) {
match stored_auth.and_then(stored_auth_mode_value) {
Some(AuthMode::ApiKey | AuthMode::BedrockApiKey | AuthMode::BedrockAccessKeys) => {
ProviderAuthReachabilityMode::ApiKey
}
Some(
AuthMode::Chatgpt
| AuthMode::ChatgptAuthTokens
| AuthMode::Headers
| AuthMode::AgentIdentity
| AuthMode::PersonalAccessToken,
)
| None => ProviderAuthReachabilityMode::Chatgpt,
Some(AuthMode::Headers) | None => ProviderAuthReachabilityMode::NotRequired,
}
}
@@ -2809,7 +2720,7 @@ async fn provider_reachability_check(plan: ReachabilityPlan) -> DoctorCheck {
.details(details);
}
let client = RouteAwareClientPool::with_chatgpt_cloudflare_cookies_without_request_logging(
let client = RouteAwareClientPool::new_without_request_logging(
plan.http_client_factory,
ClientRouteClass::Api,
)
@@ -3776,10 +3687,6 @@ mod tests {
let auth = AuthDotJson {
auth_mode: Some(AuthMode::ApiKey),
openai_api_key: None,
tokens: None,
last_refresh: None,
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
@@ -3792,60 +3699,28 @@ mod tests {
}
#[test]
fn stored_auth_validation_rejects_missing_chatgpt_tokens() {
let auth = AuthDotJson {
auth_mode: None,
openai_api_key: None,
tokens: None,
last_refresh: None,
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
fn stored_auth_validation_flags_unsupported_legacy_credentials() {
let auth: AuthDotJson = serde_json::from_value(serde_json::json!({
"auth_mode": "chatgpt",
"OPENAI_API_KEY": null,
"tokens": {"access_token": "legacy", "refresh_token": "legacy"},
}))
.expect("legacy auth.json still parses");
assert_eq!(stored_auth_mode(&auth), "unsupported");
assert_eq!(
stored_auth_issues(&auth, |_| false),
vec![
"ChatGPT auth is missing token data",
"ChatGPT auth is missing refresh metadata",
"stored credentials use an unsupported sign-in method; run codex logout and codex login --with-api-key"
]
);
}
#[test]
fn stored_auth_validation_handles_personal_access_token() {
let mut auth = AuthDotJson {
auth_mode: None,
openai_api_key: None,
tokens: None,
last_refresh: None,
agent_identity: None,
personal_access_token: Some("at-test".to_string()),
bedrock_api_key: None,
bedrock_access_keys: None,
};
assert_eq!(stored_auth_mode(&auth), "personal_access_token");
assert!(stored_auth_issues(&auth, |_| false).is_empty());
auth.auth_mode = Some(AuthMode::PersonalAccessToken);
auth.personal_access_token = None;
assert_eq!(
stored_auth_issues(&auth, |_| false),
vec!["personal access token auth is missing a personal access token"]
);
}
#[test]
fn provider_reachability_mode_uses_api_key_auth() {
let api_key_auth = AuthDotJson {
auth_mode: Some(AuthMode::ApiKey),
openai_api_key: Some("sk-test".to_string()),
tokens: None,
last_refresh: None,
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
@@ -3871,8 +3746,8 @@ mod tests {
ProviderAuthReachabilityMode::ApiKey
);
let chatgpt_auth = AuthDotJson {
auth_mode: Some(AuthMode::Chatgpt),
let env_key_auth = AuthDotJson {
auth_mode: Some(AuthMode::Headers),
openai_api_key: None,
..api_key_auth
};
@@ -3882,9 +3757,9 @@ mod tests {
/*provider_env_key*/ None,
Some("https://custom.example/v1"),
|name| name == OPENAI_API_KEY_ENV_VAR,
Some(&chatgpt_auth),
Some(&env_key_auth),
),
ProviderAuthReachabilityMode::Chatgpt
ProviderAuthReachabilityMode::NotRequired
);
assert_eq!(
provider_auth_reachability_mode_from_auth(
@@ -3892,7 +3767,7 @@ mod tests {
Some(OPENAI_API_KEY_ENV_VAR),
Some("https://custom.example/v1"),
|name| name == OPENAI_API_KEY_ENV_VAR,
Some(&chatgpt_auth),
Some(&env_key_auth),
),
ProviderAuthReachabilityMode::ApiKey
);
@@ -3902,7 +3777,7 @@ mod tests {
/*provider_env_key*/ None,
/*provider_base_url*/ None,
|name| name == CODEX_API_KEY_ENV_VAR,
Some(&chatgpt_auth),
Some(&env_key_auth),
),
ProviderAuthReachabilityMode::ApiKey
);
@@ -3938,7 +3813,7 @@ mod tests {
for (mode, description) in [
(ProviderAuthReachabilityMode::NotRequired, "provider auth"),
(ProviderAuthReachabilityMode::Chatgpt, "ChatGPT auth"),
(ProviderAuthReachabilityMode::ApiKey, "API key auth"),
] {
assert_eq!(
provider_reachability_plan_from_parts(
@@ -4000,7 +3875,7 @@ mod tests {
"https://chatgpt.com/backend-api/",
] {
let plan = provider_reachability_plan_from_parts(
ProviderAuthReachabilityMode::Chatgpt,
ProviderAuthReachabilityMode::NotRequired,
"openai",
"OpenAI",
Some(base_url),

View File

@@ -83,7 +83,6 @@ pub(super) fn sandbox_check(config: &Config, arg0_paths: &Arg0DispatchPaths) ->
{
None => "none",
Some(RequirementSource::Unknown) => "unknown",
Some(RequirementSource::EnterpriseManaged { .. }) => "cloud",
Some(RequirementSource::Composite { .. }) => "multiple layers",
Some(RequirementSource::MdmManagedPreferences { .. }) => "MDM",
Some(RequirementSource::SystemRequirementsToml { .. }) => "system",

View File

@@ -142,7 +142,6 @@ fn terminal_title_item_id(item: &str) -> Option<&'static str> {
"total-output-tokens" => Some("total-output-tokens"),
"thread-id" | "session-id" => Some("thread-id"),
"fast-mode" => Some("fast-mode"),
"daybreak" => Some("daybreak"),
"model" | "model-name" => Some("model"),
"model-with-reasoning" => Some("model-with-reasoning"),
"reasoning" => Some("reasoning"),
@@ -315,7 +314,7 @@ mod tests {
configured_items: Some(vec![
"thread-credits".to_string(),
"estimated-thread-cost".to_string(),
"daybreak".to_string(),
"fast-mode".to_string(),
]),
cwd: PathBuf::from("/workspace/project"),
project_root: None,
@@ -324,7 +323,7 @@ mod tests {
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(check.summary, "terminal title configured");
assert!(check.details.contains(
&"terminal title items: thread-credits, estimated-thread-cost, daybreak".to_string()
&"terminal title items: thread-credits, estimated-thread-cost, fast-mode".to_string()
));
assert!(check.issues.is_empty());
}

View File

@@ -1,30 +0,0 @@
//! Snapshot coverage for the public exec command's argument help.
use super::MultitoolCli;
use clap::CommandFactory;
use pretty_assertions::assert_eq;
#[test]
fn exec_help_documents_cyber_access_program() {
let help = MultitoolCli::command()
.term_width(80)
.try_get_matches_from(["codex", "exec", "--help"])
.expect_err("help should short-circuit");
assert_eq!(help.kind(), clap::error::ErrorKind::DisplayHelp);
let program_help = help
.to_string()
.lines()
.skip_while(|line| !line.contains("--cyber-access-program"))
.take_while(|line| !line.is_empty())
.map(str::trim_end)
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(program_help.trim(), @r"
--cyber-access-program <PROGRAM>
Request an experimental Cyber access program for this turn (OpenAI
provider only). Omit to use server defaults. Not supported with
review; fork requires a prompt
[possible values: standard, daybreak_blue, daybreak_red]
");
}

View File

@@ -1,4 +1,4 @@
pub mod cloud_config;
pub mod local_config;
pub(crate) mod debug_sandbox;
mod exit_status;
pub(crate) mod login;
@@ -13,14 +13,9 @@ use std::path::PathBuf;
pub use debug_sandbox::run_command_under_landlock;
pub use debug_sandbox::run_command_under_seatbelt;
pub use debug_sandbox::run_command_under_windows_sandbox;
pub use login::read_access_token_from_stdin;
pub use login::read_api_key_from_stdin;
pub use login::run_login_status;
pub use login::run_login_with_access_token;
pub use login::run_login_with_api_key;
pub use login::run_login_with_browser;
pub use login::run_login_with_device_code;
pub use login::run_login_with_device_code_fallback_to_browser;
pub use login::run_logout;
#[derive(Debug, Default, Args)]

View File

@@ -7,31 +7,16 @@
//! into a one-shot CLI command while still producing a durable `codex-login.log` artifact that
//! support can request from users.
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::config::Config;
use codex_core::config::edit::ConfigEdit;
use codex_core::config::edit::ConfigEditsBuilder;
use codex_login::AuthKeyringBackendKind;
use codex_login::AuthManager;
use codex_login::AuthRouteConfig;
use codex_login::CLIENT_ID;
use codex_login::ServerOptions;
use codex_login::is_workload_identity_selected;
use codex_login::login_with_access_token;
use codex_login::login_with_api_key;
use codex_login::logout_with_revoke;
use codex_login::run_device_code_login;
use codex_login::run_login_server;
use codex_mcp::ema_auth_scope;
use codex_protocol::auth::AuthMode;
use codex_protocol::config_types::ForcedLoginMethod;
use codex_rmcp_client::EnterpriseOAuthCredentialGuard;
use codex_utils_cli::CliConfigOverrides;
use std::fs::OpenOptions;
use std::io::IsTerminal;
use std::io::Read;
use std::path::Path;
use std::path::PathBuf;
use tracing_appender::non_blocking;
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::EnvFilter;
@@ -39,13 +24,8 @@ use tracing_subscriber::Layer;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
const CHATGPT_LOGIN_DISABLED_MESSAGE: &str =
"ChatGPT login is disabled. Use API key login instead.";
const API_KEY_LOGIN_DISABLED_MESSAGE: &str =
"API key login is disabled. Use ChatGPT login instead.";
const ACCESS_TOKEN_LOGIN_DISABLED_MESSAGE: &str =
"Access token login is disabled. Use API key login instead.";
const LOGIN_SUCCESS_MESSAGE: &str = "Successfully logged in";
"API key login is disabled by the configured login restrictions.";
const API_KEY_AUTHENTICATION_NOTICE: &str = "Authentication is checked when you send a request.";
const DEFAULT_LOGIN_LOG_FILTER: &str =
"codex_cli=info,codex_core=info,codex_login=info,codex_otel::auth_storage=warn";
@@ -118,60 +98,6 @@ fn init_login_file_logging(config: &Config) -> Option<WorkerGuard> {
Some(guard)
}
fn print_login_server_start(actual_port: u16, auth_url: &str) {
eprintln!(
"Starting local login server on http://localhost:{actual_port}.\nIf your browser did not open, navigate to this URL to authenticate:\n\n{auth_url}\n\nOn a remote or headless machine? Use `codex login --device-auth` instead."
);
}
async fn clear_existing_auth_before_login(
codex_home: &Path,
auth_credentials_store_mode: AuthCredentialsStoreMode,
auth_keyring_backend_kind: AuthKeyringBackendKind,
auth_route_config: &AuthRouteConfig,
) {
if let Err(err) = logout_with_revoke(
codex_home,
auth_credentials_store_mode,
auth_keyring_backend_kind,
auth_route_config,
)
.await
{
tracing::warn!("failed to clear existing auth before login: {err}");
}
}
pub async fn login_with_chatgpt(
codex_home: PathBuf,
forced_chatgpt_workspace_id: Option<Vec<String>>,
cli_auth_credentials_store_mode: AuthCredentialsStoreMode,
auth_keyring_backend_kind: AuthKeyringBackendKind,
auth_route_config: AuthRouteConfig,
) -> std::io::Result<()> {
clear_existing_auth_before_login(
&codex_home,
cli_auth_credentials_store_mode,
auth_keyring_backend_kind,
&auth_route_config,
)
.await;
let opts = ServerOptions::new(
codex_home,
CLIENT_ID.to_string(),
forced_chatgpt_workspace_id,
cli_auth_credentials_store_mode,
auth_keyring_backend_kind,
auth_route_config,
);
let server = run_login_server(opts)?;
print_login_server_start(server.actual_port, &server.auth_url);
server.block_until_done().await
}
/// Remote managed configuration (config server / cloud bundles) is not
/// supported in aKode: requirements that demand it cannot be satisfied.
async fn sign_in_to_config_server_and_reload_config(
@@ -186,10 +112,7 @@ async fn sign_in_to_config_server_and_reload_config(
fn finish_login(result: std::io::Result<()>) -> ! {
match result {
Ok(_) => {
eprintln!("{LOGIN_SUCCESS_MESSAGE}");
std::process::exit(0);
}
Ok(_) => std::process::exit(0),
Err(e) => {
eprintln!("Error logging in: {e}");
std::process::exit(1);
@@ -197,54 +120,6 @@ fn finish_login(result: std::io::Result<()>) -> ! {
}
}
async fn run_interactive_login<F>(
cli_config_overrides: CliConfigOverrides,
chatgpt_login: impl FnOnce(Config) -> F,
) -> !
where
F: std::future::Future<Output = std::io::Result<()>>,
{
let mut config = load_config_or_exit(cli_config_overrides.clone()).await;
if !config
.config_layer_stack
.requirements_toml()
.requires_remote_config()
{
let _login_log_guard = init_login_file_logging(&config);
finish_login(chatgpt_login(config).await);
}
let result =
sign_in_to_config_server_and_reload_config(&mut config, &cli_config_overrides).await;
let _login_log_guard = init_login_file_logging(&config);
finish_login(result)
}
pub async fn run_login_with_browser(cli_config_overrides: CliConfigOverrides) -> ! {
run_interactive_login(cli_config_overrides, |config| async move {
tracing::info!("starting browser login flow");
if !config
.auth_config()
.is_login_method_allowed(ForcedLoginMethod::Chatgpt)
{
eprintln!("{CHATGPT_LOGIN_DISABLED_MESSAGE}");
std::process::exit(1);
}
let effective_chatgpt_workspaces = config.auth_config().effective_chatgpt_workspaces();
login_with_chatgpt(
config.codex_home.to_path_buf(),
effective_chatgpt_workspaces,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
config.auth_route_config(),
)
.await
})
.await
}
pub async fn run_login_with_api_key(
cli_config_overrides: CliConfigOverrides,
api_key: String,
@@ -278,46 +153,6 @@ pub async fn run_login_with_api_key(
}
}
pub async fn run_login_with_access_token(
cli_config_overrides: CliConfigOverrides,
access_token: String,
) -> ! {
let config = load_managed_login_config_or_exit(cli_config_overrides).await;
let _login_log_guard = init_login_file_logging(&config);
tracing::info!("starting access token login flow");
if !config
.auth_config()
.is_login_method_allowed(ForcedLoginMethod::Chatgpt)
{
eprintln!("{ACCESS_TOKEN_LOGIN_DISABLED_MESSAGE}");
std::process::exit(1);
}
let auth_route_config = config.auth_route_config();
let effective_chatgpt_workspaces = config.auth_config().effective_chatgpt_workspaces();
match login_with_access_token(
&config.codex_home,
&access_token,
config.cli_auth_credentials_store_mode,
effective_chatgpt_workspaces.as_deref(),
Some(&config.chatgpt_base_url),
config.auth_keyring_backend_kind(),
&auth_route_config,
)
.await
{
Ok(_) => {
eprintln!("{LOGIN_SUCCESS_MESSAGE}");
std::process::exit(0);
}
Err(e) => {
eprintln!("Error logging in with access token: {e}");
std::process::exit(1);
}
}
}
pub fn read_api_key_from_stdin() -> String {
read_stdin_secret(
"--with-api-key expects the API key on stdin. Try piping it, e.g. `printenv OPENAI_API_KEY | codex login --with-api-key`.",
@@ -326,14 +161,6 @@ pub fn read_api_key_from_stdin() -> String {
)
}
pub fn read_access_token_from_stdin() -> String {
read_stdin_secret(
"--with-access-token expects the access token on stdin. Try piping it, e.g. `printenv CODEX_ACCESS_TOKEN | codex login --with-access-token`.",
"Reading access token from stdin...",
"No access token provided via stdin.",
)
}
fn read_stdin_secret(terminal_message: &str, reading_message: &str, empty_message: &str) -> String {
let mut stdin = std::io::stdin();
@@ -360,138 +187,9 @@ fn read_stdin_secret(terminal_message: &str, reading_message: &str, empty_messag
}
/// Login using the OAuth device code flow.
pub async fn run_login_with_device_code(
cli_config_overrides: CliConfigOverrides,
issuer_base_url: Option<String>,
client_id: Option<String>,
) -> ! {
run_interactive_login(cli_config_overrides, |config| async move {
tracing::info!("starting device code login flow");
if !config
.auth_config()
.is_login_method_allowed(ForcedLoginMethod::Chatgpt)
{
eprintln!("{CHATGPT_LOGIN_DISABLED_MESSAGE}");
std::process::exit(1);
}
let auth_route_config = config.auth_route_config();
clear_existing_auth_before_login(
&config.codex_home,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
&auth_route_config,
)
.await;
let effective_chatgpt_workspaces = config.auth_config().effective_chatgpt_workspaces();
let mut opts = ServerOptions::new(
config.codex_home.to_path_buf(),
client_id.unwrap_or(CLIENT_ID.to_string()),
effective_chatgpt_workspaces,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
auth_route_config,
);
if let Some(iss) = issuer_base_url {
opts.issuer = iss;
}
run_device_code_login(opts).await
})
.await
}
/// Prefers device-code login (with `open_browser = false`) when headless environment is detected, but keeps
/// `codex login` working in environments where device-code may be disabled/feature-gated.
/// If `run_device_code_login` returns `ErrorKind::NotFound` ("device-code unsupported"), this
/// falls back to starting the local browser login server.
pub async fn run_login_with_device_code_fallback_to_browser(
cli_config_overrides: CliConfigOverrides,
issuer_base_url: Option<String>,
client_id: Option<String>,
) -> ! {
let config = load_config_or_exit(cli_config_overrides).await;
let _login_log_guard = init_login_file_logging(&config);
tracing::info!("starting login flow with device code fallback");
if !config
.auth_config()
.is_login_method_allowed(ForcedLoginMethod::Chatgpt)
{
eprintln!("{CHATGPT_LOGIN_DISABLED_MESSAGE}");
std::process::exit(1);
}
let auth_route_config = config.auth_route_config();
clear_existing_auth_before_login(
&config.codex_home,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
&auth_route_config,
)
.await;
let effective_chatgpt_workspaces = config.auth_config().effective_chatgpt_workspaces();
let mut opts = ServerOptions::new(
config.codex_home.to_path_buf(),
client_id.unwrap_or(CLIENT_ID.to_string()),
effective_chatgpt_workspaces,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
auth_route_config,
);
if let Some(iss) = issuer_base_url {
opts.issuer = iss;
}
opts.open_browser = false;
match run_device_code_login(opts.clone()).await {
Ok(()) => {
eprintln!("{LOGIN_SUCCESS_MESSAGE}");
std::process::exit(0);
}
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
eprintln!("Device code login is not enabled; falling back to browser login.");
match run_login_server(opts) {
Ok(server) => {
print_login_server_start(server.actual_port, &server.auth_url);
match server.block_until_done().await {
Ok(()) => {
eprintln!("{LOGIN_SUCCESS_MESSAGE}");
std::process::exit(0);
}
Err(e) => {
eprintln!("Error logging in: {e}");
std::process::exit(1);
}
}
}
Err(e) => {
eprintln!("Error logging in: {e}");
std::process::exit(1);
}
}
} else {
eprintln!("Error logging in with device code: {e}");
std::process::exit(1);
}
}
}
}
pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
let config = load_config_or_exit(cli_config_overrides).await;
if is_workload_identity_selected() {
match AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await {
Ok(_) => {
eprintln!("Logged in using workload identity");
std::process::exit(0);
}
Err(err) => {
eprintln!("Error checking login status: {err}");
std::process::exit(1);
}
}
}
let auth_config = config.auth_config();
match auth_config
.load_auth(/*enable_codex_api_key_env*/ false)
@@ -509,21 +207,9 @@ pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
std::process::exit(1);
}
},
AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens => {
eprintln!("Logged in using ChatGPT");
std::process::exit(0);
}
AuthMode::Headers => {
unreachable!("header auth cannot be loaded from auth storage")
}
AuthMode::AgentIdentity => {
eprintln!("Logged in using access token");
std::process::exit(0);
}
AuthMode::PersonalAccessToken => {
eprintln!("Logged in using personal access token");
std::process::exit(0);
}
AuthMode::BedrockApiKey => {
eprintln!("Logged in using Amazon Bedrock API key");
std::process::exit(0);
@@ -546,53 +232,17 @@ pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
pub async fn run_logout(cli_config_overrides: CliConfigOverrides) -> ! {
let config = load_config_or_exit(cli_config_overrides).await;
let auth_route_config = config.auth_route_config();
// Cleanup is independent of the current feature gate. Retain the grant lock
// through account removal so another process cannot commit a late login.
let enterprise_guard = async {
let Some(profile) = &config.mcp_enterprise_managed_auth else {
return Ok::<_, anyhow::Error>(None);
};
let auth = config
.auth_config()
.load_auth(/*enable_codex_api_key_env*/ false)
.await?;
let Some(scope) = ema_auth_scope(auth.as_ref()) else {
return Ok(None);
};
EnterpriseOAuthCredentialGuard::acquire(
&profile.idp.credential_name(&scope),
&profile.idp.issuer,
config.auth_keyring_backend_kind(),
)
.await
.map(Some)
}
.await;
let cleanup_failed = match &enterprise_guard {
Ok(Some(guard)) => guard.delete_tokens().is_err(),
Ok(None) => false,
Err(_) => true,
};
if cleanup_failed {
eprintln!("Warning: failed to remove enterprise authorization; continuing account logout");
}
let logged_out = match logout_with_revoke(
let logged_out = match codex_login::logout(
&config.codex_home,
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
&auth_route_config,
)
.await
{
) {
Ok(logged_out) => logged_out,
Err(err) => {
eprintln!("Error logging out: {err}");
std::process::exit(1);
}
};
drop(enterprise_guard);
let cleared_bedrock_config =
if let Some(paths) = ConfigEditsBuilder::bedrock_provider_config_paths_to_clear(&config) {
@@ -673,44 +323,10 @@ mod storage_tests;
#[cfg(test)]
mod tests {
use codex_config::types::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::load_auth_dot_json;
use codex_login::login_with_api_key;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
use super::clear_existing_auth_before_login;
use super::safe_format_key;
#[tokio::test]
async fn clears_existing_auth_before_login() {
let codex_home = tempdir().expect("create temporary Codex home");
login_with_api_key(
codex_home.path(),
"sk-existing",
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)
.expect("save existing auth");
clear_existing_auth_before_login(
codex_home.path(),
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
&codex_login::test_support::transport_default_auth_route_config(),
)
.await;
let auth = load_auth_dot_json(
codex_home.path(),
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)
.expect("load auth after cleanup");
assert_eq!(auth, None);
}
#[test]
fn formats_long_key() {
let key = "sk-proj-1234567890ABCDE";

View File

@@ -7,14 +7,10 @@ use codex_app_server_daemon::BootstrapOptions as AppServerBootstrapOptions;
use codex_app_server_daemon::LifecycleCommand as AppServerLifecycleCommand;
use codex_arg0::Arg0DispatchPaths;
use codex_arg0::arg0_dispatch_or_else;
use codex_cli::cloud_config;
use codex_cli::read_access_token_from_stdin;
use codex_cli::local_config;
use codex_cli::read_api_key_from_stdin;
use codex_cli::run_login_status;
use codex_cli::run_login_with_access_token;
use codex_cli::run_login_with_api_key;
use codex_cli::run_login_with_browser;
use codex_cli::run_login_with_device_code;
use codex_cli::run_logout;
use codex_exec::Cli as ExecCli;
use codex_exec::Command as ExecCommand;
@@ -50,9 +46,6 @@ mod config_override_args;
mod daemon_install;
mod doctor;
#[cfg(test)]
#[path = "exec_args_tests.rs"]
mod exec_args_tests;
#[cfg(test)]
#[path = "exec_server_args_tests.rs"]
mod exec_server_args_tests;
mod marketplace_cmd;
@@ -498,12 +491,6 @@ struct LoginCommand {
)]
with_api_key: bool,
#[arg(
long = "with-access-token",
help = "Read the access token from stdin (e.g. `printenv CODEX_ACCESS_TOKEN | codex login --with-access-token`)"
)]
with_access_token: bool,
#[arg(
long = "api-key",
num_args = 0..=1,
@@ -514,18 +501,6 @@ struct LoginCommand {
)]
api_key: Option<String>,
#[arg(long = "device-auth")]
use_device_code: bool,
/// EXPERIMENTAL: Use custom OAuth issuer base URL (advanced)
/// Override the OAuth issuer base URL (advanced)
#[arg(long = "experimental_issuer", value_name = "URL", hide = true)]
issuer_base_url: Option<String>,
/// EXPERIMENTAL: Use custom OAuth client ID (advanced)
#[arg(long = "experimental_client-id", value_name = "CLIENT_ID", hide = true)]
client_id: Option<String>,
#[command(subcommand)]
action: Option<LoginSubcommand>,
}
@@ -547,9 +522,6 @@ struct AppServerCommand {
#[command(flatten)]
startup_config: codex_app_server::StartupConfigArgs,
/// Load frozen cloud skills from a JSON snapshot instead of a live skill service.
#[arg(long, value_name = "PATH")]
cloud_skills_snapshot: Option<PathBuf>,
/// Omit to run the app server; specify a subcommand for tooling.
#[command(subcommand)]
subcommand: Option<AppServerSubcommand>,
@@ -1185,7 +1157,6 @@ async fn dispatch_cli(
Some(Subcommand::AppServer(app_server_cli)) => {
let AppServerCommand {
startup_config,
cloud_skills_snapshot,
subcommand,
code_mode_host,
strict_config: app_server_strict_config,
@@ -1234,7 +1205,6 @@ async fn dispatch_cli(
let _ = codex_app_server_daemon::maintain_stderr_log();
}
let runtime_options = codex_app_server::AppServerRuntimeOptions {
cloud_skills_snapshot,
code_mode_host_transport: code_mode_host.into(),
managed_daemon,
// aKode: remote control (chatgpt.com relay) is never started.
@@ -1543,19 +1513,7 @@ async fn dispatch_cli(
run_login_status(login_cli.config_overrides).await;
}
None => {
if login_cli.with_api_key && login_cli.with_access_token {
eprintln!(
"Choose one login credential source: --with-api-key or --with-access-token."
);
std::process::exit(1);
} else if login_cli.use_device_code {
run_login_with_device_code(
login_cli.config_overrides,
login_cli.issuer_base_url,
login_cli.client_id,
)
.await;
} else if login_cli.api_key.is_some() {
if login_cli.api_key.is_some() {
eprintln!(
"The --api-key flag is no longer supported. Pipe the key instead, e.g. `printenv OPENAI_API_KEY | codex login --with-api-key`."
);
@@ -1563,11 +1521,11 @@ async fn dispatch_cli(
} else if login_cli.with_api_key {
let api_key = read_api_key_from_stdin();
run_login_with_api_key(login_cli.config_overrides, api_key).await;
} else if login_cli.with_access_token {
let access_token = read_access_token_from_stdin();
run_login_with_access_token(login_cli.config_overrides, access_token).await;
} else {
run_login_with_browser(login_cli.config_overrides).await;
eprintln!(
"Only API key login is supported. Pipe the key on stdin, e.g. `printenv OPENAI_API_KEY | codex login --with-api-key`."
);
std::process::exit(1);
}
}
}
@@ -1768,7 +1726,7 @@ async fn dispatch_cli(
}
let config =
cloud_config::load_config(&root_config_overrides, LoaderOverrides::default())
local_config::load_config(&root_config_overrides, LoaderOverrides::default())
.await?;
let mut rows = Vec::with_capacity(FEATURES.len());
let mut name_width = 0;
@@ -2003,7 +1961,6 @@ async fn run_debug_prompt_input_command(
.enabled(codex_features::Feature::OmitSkillDescriptions),
max_context_tokens: config.skill_max_context_tokens,
bundled_skills_enabled: config.bundled_skills_enabled(),
cloud_skill_enabled: config.cloud_skill_enabled,
shadow_selection_enabled: config
.features
.enabled(codex_features::Feature::SkillSearch),
@@ -2038,21 +1995,7 @@ async fn run_debug_models_command(
.await?;
let auth_manager =
AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ true).await?;
let runtime_auth = if config.model_catalog.is_none()
&& config
.features
.enabled(codex_features::Feature::RuntimeAgentInstances)
{
let installation_id = codex_core::resolve_installation_id(&config.codex_home).await?;
codex_core::build_runtime_auth_manager(
&config,
Arc::clone(&auth_manager),
&installation_id,
)
} else {
None
};
let models_manager = build_models_manager(&config, auth_manager, runtime_auth);
let models_manager = build_models_manager(&config, auth_manager);
models_manager
.raw_model_catalog(
RefreshStrategy::OnlineIfUncached,
@@ -4157,7 +4100,6 @@ enabled = true
"--name",
"forwarded",
"--strict-config",
"--use-agent-identity-auth",
])
.expect("parse forward");
assert!(cli.remote.remote.is_none());

View File

@@ -24,7 +24,7 @@ use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
use crate::cloud_config;
use crate::local_config;
use crate::plugin_cmd::JsonMarketplaceSource;
use crate::plugin_cmd::configured_marketplace_snapshot_issues;
use crate::plugin_cmd::configured_marketplace_sources;
@@ -129,7 +129,7 @@ impl MarketplaceCli {
subcommand,
} = self;
let builder = cloud_config::config_builder(
let builder = local_config::config_builder(
&config_overrides,
LoaderOverrides::default(),
ConfigOverrides::default(),

View File

@@ -29,7 +29,6 @@ use codex_mcp::McpRuntimeContext;
use codex_mcp::apply_http_headers_helper;
use codex_mcp::compute_auth_statuses;
use codex_mcp::discover_supported_scopes;
use codex_mcp::ema_auth_scope;
use codex_mcp::oauth_login_support;
use codex_mcp::resolve_oauth_callback;
use codex_mcp::resolve_oauth_scopes;
@@ -38,14 +37,13 @@ use codex_rmcp_client::McpOAuthCallbackMode;
use codex_rmcp_client::McpOAuthClientRegistration;
use codex_rmcp_client::OAuthDiscoveryTimeout;
use codex_rmcp_client::StreamableHttpRedirectMode;
use codex_rmcp_client::delete_enterprise_oauth_tokens;
use codex_rmcp_client::delete_oauth_tokens;
use codex_rmcp_client::resolve_mcp_oauth_callback_url;
use codex_utils_cli::CliConfigOverrides;
use codex_utils_cli::format_env_display;
use codex_utils_redacted_string::RedactedString;
use crate::cloud_config;
use crate::local_config;
use crate::mcp_login::McpLoginMode;
use crate::mcp_login::perform_oauth_login_retry_without_scopes;
@@ -249,26 +247,26 @@ impl McpCli {
match subcommand {
McpSubcommand::List(args) => {
let config = cloud_config::load_config(&config_overrides, loader_overrides).await?;
let config = local_config::load_config(&config_overrides, loader_overrides).await?;
run_list(&config, args).await?;
}
McpSubcommand::Get(args) => {
let config = cloud_config::load_config(&config_overrides, loader_overrides).await?;
let config = local_config::load_config(&config_overrides, loader_overrides).await?;
run_get(&config, args).await?;
}
McpSubcommand::Add(args) => {
let config = cloud_config::load_config(&config_overrides, loader_overrides).await?;
let config = local_config::load_config(&config_overrides, loader_overrides).await?;
run_add(&config, args).await?;
}
McpSubcommand::Remove(args) => {
run_remove(&config_overrides, args).await?;
}
McpSubcommand::Login(args) => {
let config = cloud_config::load_config(&config_overrides, loader_overrides).await?;
let config = local_config::load_config(&config_overrides, loader_overrides).await?;
run_login(&config, args).await?;
}
McpSubcommand::Logout(args) => {
let config = cloud_config::load_config(&config_overrides, loader_overrides).await?;
let config = local_config::load_config(&config_overrides, loader_overrides).await?;
run_logout(&config, args).await?;
}
}
@@ -558,9 +556,7 @@ async fn run_login(config: &Config, login_args: LoginArgs) -> Result<()> {
};
if matches!(server.auth, codex_config::types::McpServerAuth::EmaAuth) {
bail!(
"Enterprise MCP authorization is managed by Codex account sign-in. Open Codex to sign in."
);
bail!("Enterprise-managed MCP authorization (`auth = \"ema_auth\"`) is not supported.");
}
let (url, http_headers, env_http_headers) = match &server.transport {
@@ -635,33 +631,7 @@ async fn run_logout(config: &Config, logout_args: LogoutArgs) -> Result<()> {
.ok_or_else(|| anyhow!("No MCP server named '{name}' found in configuration."))?;
if matches!(server.auth, McpServerAuth::EmaAuth) {
let auth_manager =
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ true).await?;
let auth = auth_manager.auth().await;
let scope = ema_auth_scope(auth.as_ref())
.context("Sign in to your Codex account before removing enterprise authorization")?;
// Cleanup must remain available even when this server is no longer eligible
// for EMA (for example, after disabling the feature or changing its transport).
let profile = config
.mcp_enterprise_managed_auth
.as_ref()
.context("EMA logout requires a trusted enterprise IdP profile")?;
let idp = &profile.idp;
let credential_name = idp.credential_name(&scope);
match delete_enterprise_oauth_tokens(
&credential_name,
&idp.issuer,
config.auth_keyring_backend_kind(),
)
.await
{
Ok(true) => println!(
"Removed the shared enterprise authorization used by EMA MCP servers (selected via '{name}')."
),
Ok(false) => println!("No shared enterprise authorization is stored."),
Err(_) => return Err(anyhow!("failed to delete enterprise authorization")),
}
return Ok(());
bail!("Enterprise-managed MCP authorization (`auth = \"ema_auth\"`) is not supported.");
}
let url = match &server.transport {
@@ -710,8 +680,6 @@ async fn run_list(config: &Config, list_args: ListArgs) -> Result<()> {
config.mcp_oauth_credentials_store_mode,
config.auth_keyring_backend_kind(),
auth.as_ref(),
Some(&auth_manager),
&runtime_config.ema_state,
&runtime_context,
)
.await;

View File

@@ -120,7 +120,7 @@ async fn config_with_application_network(
)?;
let requirements_path = home.join("requirements.toml");
std::fs::write(&requirements_path, requirements)?;
crate::cloud_config::load_config(
crate::local_config::load_config(
&codex_utils_cli::CliConfigOverrides::default(),
codex_core::config::LoaderOverrides {
system_config_path: Some(home.join("absent-system-config.toml")),

View File

@@ -1,21 +1,16 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use anyhow::ensure;
use clap::Parser;
use codex_app_server_protocol::PluginAuthPolicy;
use codex_app_server_protocol::PluginInstallPolicy;
use codex_core::config::Config;
use codex_core::config::find_codex_home;
use codex_core::plugins_manager_for_config;
use codex_core::plugins_manager_for_config_with_runtime;
use codex_core_plugins::ConfiguredMarketplace;
use codex_core_plugins::OPENAI_BUNDLED_MARKETPLACE_NAME;
use codex_core_plugins::PluginInstallOutcome;
use codex_core_plugins::PluginInstallRequest;
use codex_core_plugins::PluginsConfigInput;
use codex_core_plugins::PluginsManager;
use codex_core_plugins::RemotePluginInstallRequest;
use codex_core_plugins::allowed_configured_marketplace_names;
use codex_core_plugins::installed_marketplaces::marketplace_install_root;
use codex_core_plugins::installed_marketplaces::resolve_configured_marketplace_root;
@@ -24,14 +19,7 @@ use codex_core_plugins::marketplace::MarketplacePluginAuthPolicy;
use codex_core_plugins::marketplace::MarketplacePluginInstallPolicy;
use codex_core_plugins::marketplace::MarketplacePluginSource;
use codex_core_plugins::marketplace::find_marketplace_manifest_path;
use codex_core_plugins::remote;
use codex_core_plugins::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
use codex_core_plugins::remote::RemoteMarketplace;
use codex_core_plugins::remote::RemoteMarketplaceSource;
use codex_core_plugins::remote::RemotePluginCatalogCacheMode;
use codex_core_plugins::remote::RemotePluginSummary;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_plugin::PluginId;
use codex_plugin::validate_plugin_segment;
use codex_utils_absolute_path::AbsolutePathBuf;
@@ -61,13 +49,13 @@ pub struct PluginCli {
#[derive(Debug, clap::Subcommand)]
pub enum PluginSubcommand {
/// Install a plugin from a configured or remote marketplace.
/// Install a plugin from a configured marketplace.
///
/// Pass either `PLUGIN@MARKETPLACE` or pass `PLUGIN` with
/// `--marketplace MARKETPLACE`.
Add(AddPluginArgs),
/// List plugins available from configured and remote marketplaces.
/// List plugins available from configured marketplaces.
List(ListPluginsArgs),
/// Add, list, upgrade, or remove configured plugin marketplaces.
@@ -147,63 +135,24 @@ pub async fn run_plugin_add(
json,
} = args;
let selection = parse_plugin_selection(plugin, marketplace_name)?;
let context = load_plugin_command_context(overrides, Some(&selection.marketplace_name)).await?;
let outcome = if selection.marketplace_name == REMOTE_GLOBAL_MARKETPLACE_NAME {
let mut listing = fetch_remote_marketplaces(
&context,
Some(&selection.marketplace_name),
RemotePluginCatalogCacheMode::PreferFreshCache,
let context = load_plugin_command_context(overrides).await?;
let marketplace = find_marketplace_for_plugin(
&context.manager,
context.codex_home.as_path(),
&context.plugins_input,
&selection.marketplace_name,
&selection.plugin_name,
)?;
let outcome = context
.manager
.install_plugin(
&context.plugins_input.config_layer_stack,
PluginInstallRequest {
plugin_name: selection.plugin_name,
marketplace_path: marketplace.path,
},
)
.await?;
// A newly published plugin may be missing from an otherwise fresh catalog cache.
if listing.catalog_cache_used
&& !listing
.marketplaces
.iter()
.flat_map(|marketplace| &marketplace.plugins)
.any(|plugin| plugin.name == selection.plugin_name)
{
listing = fetch_remote_marketplaces(
&context,
Some(&selection.marketplace_name),
RemotePluginCatalogCacheMode::ForceRefetch,
)
.await?;
}
let plugin = resolve_remote_plugin(listing.marketplaces, &selection)?;
context
.manager
.install_remote_plugin(
&context.plugins_input,
context.auth.as_ref(),
RemotePluginInstallRequest {
marketplace_name: selection.marketplace_name,
remote_plugin_id: plugin.remote_plugin_id,
install_attempt_id: None,
},
/*on_effective_plugins_changed*/ None,
)
.await?
.installed
} else {
let marketplace = find_marketplace_for_plugin(
&context.manager,
context.codex_home.as_path(),
&context.plugins_input,
&selection.marketplace_name,
&selection.plugin_name,
)?;
context
.manager
.install_plugin(
&context.plugins_input.config_layer_stack,
PluginInstallRequest {
plugin_name: selection.plugin_name,
marketplace_path: marketplace.path,
},
)
.await?
};
let output = JsonPluginAddOutput::from_outcome(outcome);
if json {
@@ -248,13 +197,7 @@ pub async fn run_plugin_list(
overrides: Vec<(String, toml::Value)>,
args: ListPluginsArgs,
) -> Result<()> {
let context = load_plugin_command_context(overrides, args.marketplace_name.as_deref()).await?;
let remote_listing = fetch_remote_marketplaces(
&context,
args.marketplace_name.as_deref(),
RemotePluginCatalogCacheMode::PreferFreshCache,
)
.await?;
let context = load_plugin_command_context(overrides).await?;
let PluginCommandContext {
codex_home,
plugins_input,
@@ -262,11 +205,7 @@ pub async fn run_plugin_list(
..
} = context;
let outcome = manager
.list_marketplaces_for_config(
&plugins_input,
&[],
/*include_openai_curated*/ !remote_listing.uses_global_catalog,
)
.list_marketplaces_for_config(&plugins_input, &[], /*include_openai_curated*/ true)
.context("failed to list marketplace plugins")?;
ensure_configured_marketplace_snapshots_loaded(
codex_home.as_path(),
@@ -294,15 +233,9 @@ pub async fn run_plugin_list(
})
.collect(),
name: marketplace.name,
path: Some(marketplace.path),
path: marketplace.path,
}
})
.chain(
remote_listing
.marketplaces
.into_iter()
.map(PluginListMarketplace::from),
)
.filter(|marketplace| {
args.marketplace_name
.as_ref()
@@ -371,7 +304,6 @@ fn render_plugin_list(
};
let installed_version = plugin.display_version.clone().unwrap_or_default();
let path = match &plugin.source {
JsonPluginSource::Remote { id } => id.clone(),
JsonPluginSource::Local { path } => path.clone(),
JsonPluginSource::Git { url, ref_name, sha }
| JsonPluginSource::GitSubdir {
@@ -414,11 +346,7 @@ fn render_plugin_list(
writeln!(writer)?;
}
writeln!(writer, "Marketplace `{}`", marketplace.name)?;
if let Some(path) = &marketplace.path {
writeln!(writer, "{}", path.display())?;
} else {
writeln!(writer, "Remote catalog")?;
}
writeln!(writer, "{}", marketplace.path.display())?;
writeln!(writer)?;
writeln!(
writer,
@@ -439,48 +367,10 @@ fn render_plugin_list(
struct PluginListMarketplace {
name: String,
path: Option<AbsolutePathBuf>,
path: AbsolutePathBuf,
plugins: Vec<PluginListEntry>,
}
impl From<RemoteMarketplace> for PluginListMarketplace {
fn from(marketplace: RemoteMarketplace) -> Self {
Self {
plugins: marketplace
.plugins
.into_iter()
.map(|plugin| {
let version = plugin.local_version.or(plugin.version);
PluginListEntry {
plugin_id: plugin.id,
name: plugin.name,
marketplace_name: marketplace.name.clone(),
display_version: version.clone(),
version,
installed: plugin.installed,
enabled: plugin.enabled,
source: JsonPluginSource::Remote {
id: plugin.remote_plugin_id,
},
marketplace_source: None,
install_policy: match plugin.install_policy {
PluginInstallPolicy::NotAvailable => "NOT_AVAILABLE",
PluginInstallPolicy::Available => "AVAILABLE",
PluginInstallPolicy::InstalledByDefault => "INSTALLED_BY_DEFAULT",
},
auth_policy: match plugin.auth_policy {
PluginAuthPolicy::OnInstall => "ON_INSTALL",
PluginAuthPolicy::OnUse => "ON_USE",
},
}
})
.collect(),
name: marketplace.name,
path: None,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonPluginListOutput {
@@ -558,9 +448,6 @@ impl PluginListEntry {
#[derive(Debug, Serialize)]
#[serde(tag = "source", rename_all = "kebab-case")]
enum JsonPluginSource {
Remote {
id: String,
},
Local {
path: String,
},
@@ -689,43 +576,12 @@ pub async fn run_plugin_remove(
json,
} = args;
let selection = parse_plugin_selection(plugin, marketplace_name)?;
let context = load_plugin_command_context(overrides, Some(&selection.marketplace_name)).await?;
let context = load_plugin_command_context(overrides).await?;
if selection.marketplace_name == REMOTE_GLOBAL_MARKETPLACE_NAME {
ensure!(
context.plugins_input.plugins_enabled,
"remote plugins are not enabled"
);
let auth = context.auth.as_ref();
// Installed plugins may no longer appear in the directory or curated collection.
let marketplaces = context
.manager
.build_and_cache_remote_installed_plugin_marketplaces(
&context.plugins_input,
auth,
&[REMOTE_GLOBAL_MARKETPLACE_NAME],
/*on_effective_plugins_changed*/ None,
)
.await?;
let plugin = resolve_remote_plugin(marketplaces, &selection)?;
let outcome = context
.manager
.uninstall_remote_plugin(
&context.plugins_input,
auth,
&plugin.remote_plugin_id,
/*on_effective_plugins_changed*/ None,
)
.await?;
if let Some(err) = outcome.cache_removal_error {
return Err(err.into());
}
} else {
context
.manager
.uninstall_plugin(selection.plugin_key.clone())
.await?;
}
context
.manager
.uninstall_plugin(selection.plugin_key.clone())
.await?;
if json {
let output = JsonPluginRemoveOutput::from_selection(selection);
println!("{}", serde_json::to_string_pretty(&output)?);
@@ -762,12 +618,10 @@ struct PluginCommandContext {
codex_home: PathBuf,
plugins_input: PluginsConfigInput,
manager: Arc<PluginsManager>,
auth: Option<CodexAuth>,
}
async fn load_plugin_command_context(
overrides: Vec<(String, toml::Value)>,
marketplace_name: Option<&str>,
) -> Result<PluginCommandContext> {
let codex_home = find_codex_home().context("failed to resolve CODEX_HOME")?;
let config = Config::load_with_cli_overrides(overrides)
@@ -775,20 +629,11 @@ async fn load_plugin_command_context(
.context("failed to load configuration")?;
let plugins_input = config.plugins_config_input();
let auth_manager = load_cli_auth_manager(&config).await?;
let auth = auth_manager.auth().await;
let uses_remote_catalog = plugins_input.plugins_enabled
&& auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)
&& marketplace_name.is_none_or(|name| name == REMOTE_GLOBAL_MARKETPLACE_NAME);
let manager = Arc::new(if uses_remote_catalog {
plugins_manager_for_config_with_runtime(&config, Arc::clone(&auth_manager)).await?
} else {
plugins_manager_for_config(&config, Arc::clone(&auth_manager))
});
let manager = Arc::new(plugins_manager_for_config(&config, auth_manager));
Ok(PluginCommandContext {
codex_home: codex_home.to_path_buf(),
plugins_input,
manager,
auth,
})
}
@@ -840,98 +685,6 @@ fn parse_plugin_selection(
}
}
#[derive(Default)]
struct RemoteMarketplaceListing {
marketplaces: Vec<RemoteMarketplace>,
// A successful global catalog replaces the local curated catalog even when it is empty.
uses_global_catalog: bool,
catalog_cache_used: bool,
}
async fn fetch_remote_marketplaces(
context: &PluginCommandContext,
marketplace_name: Option<&str>,
cache_mode: RemotePluginCatalogCacheMode,
) -> Result<RemoteMarketplaceListing> {
if marketplace_name.is_some_and(|name| name != REMOTE_GLOBAL_MARKETPLACE_NAME) {
return Ok(RemoteMarketplaceListing::default());
}
if !context.plugins_input.plugins_enabled {
ensure!(marketplace_name.is_none(), "remote plugins are not enabled");
return Ok(RemoteMarketplaceListing::default());
}
let auth = context.auth.as_ref();
if !auth.is_some_and(CodexAuth::uses_codex_backend) {
ensure!(
marketplace_name.is_none(),
"chatgpt authentication required for remote plugin catalog"
);
return Ok(RemoteMarketplaceListing::default());
}
let service = context
.manager
.remote_plugin_service_config(&context.plugins_input);
let result = if context.plugins_input.remote_plugin_enabled {
remote::fetch_remote_marketplaces(
&service,
auth,
&[RemoteMarketplaceSource::Global],
/*catalog_cache_root*/ Some(context.codex_home.as_path()),
cache_mode,
)
.await
.map(|outcome| RemoteMarketplaceListing {
marketplaces: outcome.marketplaces,
uses_global_catalog: true,
catalog_cache_used: outcome.catalog_cache_used,
})
} else {
remote::fetch_openai_curated_remote_collection_marketplace(
&service,
auth,
/*catalog_cache_root*/ Some(context.codex_home.as_path()),
cache_mode,
)
.await
.map(|outcome| RemoteMarketplaceListing {
marketplaces: outcome.marketplace.into_iter().collect(),
uses_global_catalog: false,
catalog_cache_used: outcome.catalog_cache_used,
})
};
match result {
Ok(listing) => Ok(listing),
Err(err) if marketplace_name.is_none() => {
eprintln!("Warning: failed to list remote marketplace plugins: {err}");
Ok(RemoteMarketplaceListing::default())
}
Err(err) => Err(err).context("failed to list remote marketplace plugins"),
}
}
fn resolve_remote_plugin(
marketplaces: Vec<RemoteMarketplace>,
selection: &PluginSelection,
) -> Result<RemotePluginSummary> {
let matches = marketplaces
.into_iter()
.flat_map(|marketplace| marketplace.plugins)
.filter(|plugin| plugin.name == selection.plugin_name)
.collect::<Vec<_>>();
match matches.as_slice() {
[plugin] => Ok(plugin.clone()),
[] => bail!(
"plugin `{}` was not found in remote marketplace `{}`",
selection.plugin_name,
selection.marketplace_name
),
_ => bail!(
"plugin `{}` matched multiple remote plugins",
selection.plugin_key
),
}
}
fn find_marketplace_for_plugin(
manager: &PluginsManager,
codex_home: &std::path::Path,

View File

@@ -95,10 +95,6 @@ Options:
--name <NAME>
Human-readable environment name
--use-agent-identity-auth
Use Agent Identity auth from CODEX_ACCESS_TOKEN for remote
registration
--registration-bearer-stdin
Read one registration bearer from stdin
@@ -106,12 +102,6 @@ Options:
Read rotating executor credentials from stdin; exit when the pipe
closes
--chatgpt-token-stdin
Read a ChatGPT access token from stdin for HTTPS registration
--chatgpt-account-id <ID>
ChatGPT account ID. Must match the token's account claim when present
--aws-sigv4
Sign Direct registration and WebSocket handshake requests with AWS
SigV4

View File

@@ -1,7 +1,7 @@
---
source: cli/src/login_storage_tests.rs
assertion_line: 47
assertion_line: 52
expression: "logs.replace(home.path().join(\"secrets\").to_str().unwrap(),\n\"[SECRETS_PATH]\").replace(&cause, \"[OS_ERROR]\")"
---
WARN codex_login::auth::storage: failed to save auth to keyring, falling back to file storage: failed to write OAuth tokens to encrypted auth storage: failed to create secrets dir [SECRETS_PATH]: [OS_ERROR]
WARN codex_login::auth::storage: failed to save auth to keyring, falling back to file storage: failed to write CLI auth to encrypted auth storage: failed to create secrets dir [SECRETS_PATH]: [OS_ERROR]
WARN codex_otel::auth_storage: credential storage file fallback completed credential_kind="codex" store_mode="auto" selected_store="secrets" actual_store="file" operation="save" secure_outcome="error" outcome="success" fallback_reason="secure_error" secure_error="other" storage_phase="policy" originator="none"

View File

@@ -1,6 +1,6 @@
---
source: cli/src/login_storage_tests.rs
assertion_line: 58
assertion_line: 81
expression: "message.replace(secrets_path.to_str().unwrap(),\n\"[SECRETS_PATH]\").replace(&cause, \"[OS_ERROR]\")"
---
failed to write OAuth tokens to encrypted auth storage: failed to create secrets dir [SECRETS_PATH]: [OS_ERROR]
failed to write CLI auth to encrypted auth storage: failed to create secrets dir [SECRETS_PATH]: [OS_ERROR]

View File

@@ -242,28 +242,6 @@ fn print_startup_config_preserves_project_login_restrictions() -> Result<()> {
Ok(())
}
#[test]
fn print_startup_config_rejects_sign_out_with_environment_access_token() -> Result<()> {
let home = TempDir::new()?;
let auth_path = home.path().join("auth.json");
let saved_auth = br#"{"OPENAI_API_KEY":"saved-test-key"}"#;
std::fs::write(&auth_path, saved_auth)?;
for token in ["at-test-token", "header.payload.signature"] {
let output = codex_command(home.path())?
.env("CODEX_ACCESS_TOKEN", token)
.args(["app-server", "--print-startup-config", "--startup-sign-out"])
.assert()
.failure();
let value: serde_json::Value = serde_json::from_slice(&output.get_output().stdout)?;
assert_eq!(
value["error"]["message"],
"Configured external authentication is owned by the app-server host and cannot be changed during startup recovery."
);
assert_eq!(std::fs::read(&auth_path)?, saved_auth);
}
Ok(())
}
#[test]
fn print_startup_config_validates_configuration() -> Result<()> {
let home = TempDir::new()?;

View File

@@ -1,688 +0,0 @@
use std::process::Output;
use std::process::Stdio;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::ConfigLoadOptions;
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::config::load_config_toml_with_layer_stack;
use codex_core::config::load_global_mcp_servers;
use codex_core_plugins::installed_marketplaces::marketplace_install_root;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::net::TcpStream;
use tokio::process::Command;
use tokio::time::timeout;
use url::Url;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_string_contains;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
const MANAGED_SERVER_NAME: &str = "managed-slack";
const MANAGED_CLIENT_ID: &str = "managed-oauth-client";
const MANAGED_SCOPE: &str = "managed.read";
const MOCK_ACCESS_TOKEN: &str = "mock-managed-access-token";
const MOCK_REFRESH_TOKEN: &str = "mock-managed-refresh-token";
struct CloudManagedConfigFixture {
server: MockServer,
codex_home: TempDir,
user_config: String,
mcp_url: String,
}
impl CloudManagedConfigFixture {
async fn for_backend() -> Result<Option<Self>> {
let server = MockServer::start().await;
let chatgpt_base_url = format!("{}/backend-api", server.uri());
let codex_home = TempDir::new()?;
let user_config = format!(
"cli_auth_credentials_store = \"file\"\nchatgpt_base_url = \"{chatgpt_base_url}\"\n"
);
std::fs::write(codex_home.path().join("config.toml"), &user_config)?;
let bootstrap_config = load_config_toml_with_layer_stack(
codex_home.path(),
Some(&AbsolutePathBuf::from_absolute_path(codex_home.path())?),
Vec::new(),
ConfigLoadOptions::default(),
)
.await?;
if bootstrap_config.config_toml.cli_auth_credentials_store
!= Some(AuthCredentialsStoreMode::File)
|| bootstrap_config.config_toml.chatgpt_base_url.as_deref()
!= Some(chatgpt_base_url.as_str())
{
eprintln!(
"skipping cloud-managed subprocess: host-managed authentication or backend routing prevents isolated mock credentials"
);
return Ok(None);
}
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("workspace-123")
.chatgpt_account_id("workspace-123")
.chatgpt_user_id("user-123")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
let mcp_url = format!("{}/mcp", server.uri());
Ok(Some(Self {
server,
codex_home,
user_config,
mcp_url,
}))
}
async fn new() -> Result<Option<Self>> {
let Some(fixture) = Self::for_backend().await? else {
return Ok(None);
};
let mcp_url = &fixture.mcp_url;
let managed_config = format!(
"mcp_oauth_credentials_store = \"file\"\n\n\
[mcp_servers.{MANAGED_SERVER_NAME}]\n\
url = \"{mcp_url}\"\n\
auth = \"oauth\"\n\
scopes = [\"{MANAGED_SCOPE}\"]\n\n\
[mcp_servers.{MANAGED_SERVER_NAME}.oauth]\n\
client_id = \"{MANAGED_CLIENT_ID}\"\n\n\
[marketplaces.managed]\n\
source_type = \"git\"\n\
source = \"https://github.com/owner/repo.git\"\n"
);
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "workspace-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"config_toml": {
"enterprise_managed": [{
"id": "managed-config",
"name": "Managed resources",
"contents": managed_config,
}],
},
})))
.expect(1)
.mount(&fixture.server)
.await;
Ok(Some(fixture))
}
fn command(&self, args: &[&str]) -> Result<Command> {
let mut command = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
command
.kill_on_drop(true)
.current_dir(self.codex_home.path())
.env("CODEX_HOME", self.codex_home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("OPENAI_FEDERATION_RULE_ID")
.env_remove("OPENAI_IDENTITY_TOKEN_FILE")
.env_remove("OPENAI_WORKLOAD_IDENTITY_CONTEXT")
.args(args);
Ok(command)
}
async fn output(&self, args: &[&str]) -> Result<Output> {
let output = self.command(args)?.output().await?;
ensure!(
output.status.success(),
"codex {} failed with status {}: stdout={}; stderr={}",
args.join(" "),
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
Ok(output)
}
fn assert_user_config_unchanged(&self) -> Result<()> {
assert_eq!(
std::fs::read_to_string(self.codex_home.path().join("config.toml"))?,
self.user_config
);
Ok(())
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn list_and_get_resolve_cloud_managed_mcp_without_writing_user_config() -> Result<()> {
let Some(fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
let output = fixture.output(&["mcp", "list", "--json"]).await?;
let entries: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(entries[0]["name"], MANAGED_SERVER_NAME);
assert_eq!(entries[0]["transport"]["type"], "streamable_http");
assert_eq!(entries[0]["transport"]["url"], fixture.mcp_url);
let output = fixture
.output(&["mcp", "get", MANAGED_SERVER_NAME, "--json"])
.await?;
let entry: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(entry["name"], MANAGED_SERVER_NAME);
assert_eq!(entry["transport"]["url"], fixture.mcp_url);
assert!(
fixture
.codex_home
.path()
.join("cloud-config-bundle-cache.json")
.exists()
);
fixture.assert_user_config_unchanged()?;
fixture.server.verify().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn login_and_logout_persist_only_cloud_managed_mcp_oauth_credentials() -> Result<()> {
let Some(fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
let challenge = format!(
"Bearer resource_metadata=\"{}/oauth-resource\"",
fixture.server.uri()
);
Mock::given(method("GET"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(401).insert_header("WWW-Authenticate", challenge))
.mount(&fixture.server)
.await;
Mock::given(method("GET"))
.and(path("/oauth-resource"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"resource": fixture.mcp_url,
"authorization_servers": [fixture.server.uri()],
})))
.mount(&fixture.server)
.await;
let oauth_metadata = json!({
"issuer": fixture.server.uri(),
"authorization_endpoint": format!("{}/oauth/authorize", fixture.server.uri()),
"token_endpoint": format!("{}/oauth/token", fixture.server.uri()),
"response_types_supported": ["code"],
"code_challenge_methods_supported": ["S256"],
"scopes_supported": [MANAGED_SCOPE],
});
for metadata_path in [
"/.well-known/oauth-authorization-server",
"/.well-known/oauth-authorization-server/mcp",
] {
Mock::given(method("GET"))
.and(path(metadata_path))
.respond_with(ResponseTemplate::new(200).set_body_json(oauth_metadata.clone()))
.mount(&fixture.server)
.await;
}
Mock::given(method("POST"))
.and(path("/oauth/token"))
.and(body_string_contains(format!(
"client_id={MANAGED_CLIENT_ID}"
)))
.and(body_string_contains("grant_type=authorization_code"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token": MOCK_ACCESS_TOKEN,
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": MOCK_REFRESH_TOKEN,
"scope": MANAGED_SCOPE,
})))
.expect(1)
.mount(&fixture.server)
.await;
let mut command = fixture.command(&["mcp", "login", MANAGED_SERVER_NAME, "--no-browser"])?;
command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit());
let mut child = command.spawn()?;
// Keep input open through child.wait() so the HTTP callback cannot race EOF.
let _stdin = child
.stdin
.take()
.context("MCP login did not provide stdin")?;
let stdout = child
.stdout
.take()
.context("MCP login did not provide captured stdout")?;
let mut lines = BufReader::new(stdout).lines();
let authorization_url = timeout(Duration::from_secs(30), async {
while let Some(line) = lines.next_line().await? {
if line.starts_with("http://") || line.starts_with("https://") {
return Ok::<_, anyhow::Error>(Url::parse(line.trim())?);
}
}
anyhow::bail!("MCP login exited before printing its OAuth authorization URL")
})
.await
.context("timed out waiting for the managed MCP authorization URL")??;
let query_pairs: Vec<_> = authorization_url.query_pairs().into_owned().collect();
let state = query_pairs
.iter()
.find(|(name, _)| name == "state")
.map(|(_, value)| value.as_str())
.context("managed MCP authorization URL did not contain OAuth state")?;
assert_eq!(
query_pairs
.iter()
.find(|(name, _)| name == "client_id")
.map(|(_, value)| value.as_str()),
Some(MANAGED_CLIENT_ID)
);
assert_eq!(
query_pairs
.iter()
.find(|(name, _)| name == "scope")
.map(|(_, value)| value.as_str()),
Some(MANAGED_SCOPE)
);
let redirect_uri = query_pairs
.iter()
.find(|(name, _)| name == "redirect_uri")
.map(|(_, value)| value.as_str())
.context("managed MCP authorization URL did not contain a callback")?;
let mut callback_url = Url::parse(redirect_uri)?;
callback_url
.query_pairs_mut()
.append_pair("code", "mock-managed-authorization-code")
.append_pair("state", state);
let callback_host = callback_url
.host_str()
.context("managed MCP callback did not contain a host")?;
let callback_port = callback_url
.port_or_known_default()
.context("managed MCP callback did not contain a port")?;
let callback_path = match callback_url.query() {
Some(query) => format!("{}?{query}", callback_url.path()),
None => callback_url.path().to_string(),
};
let callback_response = timeout(Duration::from_secs(30), async {
let mut callback = TcpStream::connect((callback_host, callback_port)).await?;
callback
.write_all(
format!(
"GET {callback_path} HTTP/1.1\r\nHost: {callback_host}:{callback_port}\r\nConnection: close\r\n\r\n"
)
.as_bytes(),
)
.await?;
let mut response_lines = BufReader::new(callback).lines();
response_lines
.next_line()
.await?
.context("managed MCP OAuth callback returned an empty HTTP response")
})
.await
.context("timed out waiting for the managed MCP OAuth callback response")??;
ensure!(
callback_response.starts_with("HTTP/1.1 200")
|| callback_response.starts_with("HTTP/1.0 200"),
"managed MCP OAuth callback failed: {callback_response}"
);
let login_status = timeout(Duration::from_secs(30), child.wait())
.await
.context("timed out waiting for managed MCP login")??;
ensure!(
login_status.success(),
"managed MCP login failed: status={login_status}"
);
timeout(Duration::from_secs(30), async {
while let Some(line) = lines.next_line().await? {
if line.contains("Successfully logged in to MCP server 'managed-slack'.") {
return Ok::<_, anyhow::Error>(());
}
}
anyhow::bail!("managed MCP login exited before printing its success message")
})
.await
.context("timed out waiting for the managed MCP login success message")??;
let credentials_path = fixture.codex_home.path().join(".credentials.json");
let credentials: Value = serde_json::from_slice(&std::fs::read(&credentials_path)?)?;
let entries = credentials
.as_object()
.context("MCP credentials should be a JSON object")?;
assert_eq!(entries.len(), 1);
let credential = entries
.values()
.next()
.context("managed MCP OAuth credentials were not persisted")?;
assert_eq!(credential["server_name"], MANAGED_SERVER_NAME);
assert_eq!(credential["server_url"], fixture.mcp_url);
assert_eq!(credential["client_id"], MANAGED_CLIENT_ID);
assert_eq!(credential["access_token"], MOCK_ACCESS_TOKEN);
assert_eq!(credential["refresh_token"], MOCK_REFRESH_TOKEN);
assert_eq!(credential["scopes"], json!([MANAGED_SCOPE]));
fixture.assert_user_config_unchanged()?;
let list_output = fixture.output(&["mcp", "list", "--json"]).await?;
let entries: Value = serde_json::from_slice(&list_output.stdout)?;
assert_eq!(entries[0]["name"], MANAGED_SERVER_NAME);
assert_eq!(entries[0]["auth_status"], "o_auth");
let logout_output = fixture
.output(&["mcp", "logout", MANAGED_SERVER_NAME])
.await?;
assert!(
String::from_utf8(logout_output.stdout)?
.contains("Removed OAuth credentials for 'managed-slack'.")
);
assert!(!credentials_path.exists());
fixture.assert_user_config_unchanged()?;
fixture.server.verify().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn add_and_remove_preserve_cloud_managed_resources() -> Result<()> {
let Some(fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
let installed_root = marketplace_install_root(fixture.codex_home.path()).join("managed");
std::fs::create_dir_all(&installed_root)?;
let marker = installed_root.join("marker.txt");
std::fs::write(&marker, "installed")?;
// Exercise both the initial fetch and the cached bundle without a user entry.
for _ in 0..2 {
let output = fixture
.command(&["plugin", "marketplace", "remove", "managed"])?
.output()
.await?;
assert!(!output.status.success());
assert!(String::from_utf8(output.stderr)?.contains(
"marketplace `managed` is configured in enterprise-managed (Managed resources, managed-config); remove it from that configuration source instead"
));
fixture.assert_user_config_unchanged()?;
assert_eq!(std::fs::read_to_string(&marker)?, "installed");
}
fixture
.output(&["mcp", "get", MANAGED_SERVER_NAME, "--json"])
.await?;
fixture
.output(&["mcp", "add", "local-docs", "--", "echo", "hello"])
.await?;
let local_servers = load_global_mcp_servers(fixture.codex_home.path()).await?;
assert!(local_servers.contains_key("local-docs"));
assert!(!local_servers.contains_key(MANAGED_SERVER_NAME));
let output = fixture
.output(&["mcp", "remove", MANAGED_SERVER_NAME])
.await?;
assert!(
String::from_utf8(output.stdout)?.contains("No MCP server named 'managed-slack' found.")
);
let local_servers = load_global_mcp_servers(fixture.codex_home.path()).await?;
assert!(local_servers.contains_key("local-docs"));
assert!(!local_servers.contains_key(MANAGED_SERVER_NAME));
fixture.output(&["mcp", "remove", "local-docs"]).await?;
assert!(
load_global_mcp_servers(fixture.codex_home.path())
.await?
.is_empty()
);
fixture
.output(&["mcp", "get", MANAGED_SERVER_NAME, "--json"])
.await?;
fixture.server.verify().await;
Ok(())
}
async fn mock_startup_bundle(server: &MockServer, status: u16, config: &str, requirements: &str) {
server.reset().await;
let layer = |contents: &str| {
json!({
"enterprise_managed": [{"id": "startup", "name": "Startup policy", "contents": contents}]
})
};
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.and(header("authorization", "Bearer chatgpt-token"))
.respond_with(ResponseTemplate::new(status).set_body_json(json!({
"config_toml": layer(config), "requirements_toml": layer(requirements),
})))
.expect(1..)
.mount(server)
.await;
}
async fn successful_json(command: &mut Command) -> Result<Value> {
let output = command.output().await?;
ensure!(output.status.success(), "{output:?}");
Ok(serde_json::from_slice(&output.stdout)?)
}
#[tokio::test]
async fn startup_config_loads_managed_policy_or_reports_cloud_failure() -> Result<()> {
for status in [200, 401, 503] {
let Some(fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
mock_startup_bundle(
&fixture.server,
status,
"forced_login_method = 'api'\n",
"[application.network.domains]\n'127.0.0.1' = 'allow'\n'example.com' = 'allow'\n",
)
.await;
let sqlite_home = TempDir::new()?;
let history_path = sqlite_home.path().join("state_5.sqlite");
std::fs::write(&history_path, b"history must not be repaired")?;
let output = fixture
.command(&["app-server", "--print-startup-config"])?
.env("CODEX_SQLITE_HOME", sqlite_home.path())
.env(
"CODEX_REFRESH_TOKEN_URL_OVERRIDE",
format!("{}/refresh", fixture.server.uri()),
)
.output()
.await?;
let value: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(output.status.success(), status == 200, "{value}");
if status == 200 {
let requirements = &value["configRequirements"]["requirements"];
assert_eq!(requirements["allowedLoginMethods"], json!(["api"]));
assert_eq!(
requirements["application"]["network"]["domains"]["example.com"],
"allow"
);
} else {
assert_eq!(value["error"]["data"]["reason"], "cloudConfigBundle");
assert!(value.get("configRequirements").is_none());
}
assert_eq!(
std::fs::read(&history_path)?,
b"history must not be repaired"
);
assert_eq!(std::fs::read_dir(sqlite_home.path())?.count(), 1);
fixture.server.verify().await;
}
Ok(())
}
#[tokio::test]
async fn startup_config_sign_out_reloads_policy_without_starting_runtime() -> Result<()> {
for (status, provider) in [(200, None), (503, None), (503, Some("amazon-bedrock"))] {
let Some(mut fixture) = CloudManagedConfigFixture::new().await? else {
return Ok(());
};
if let Some(provider) = provider {
fixture
.user_config
.push_str(&format!("model_provider = \"{provider}\"\n"));
}
std::fs::write(
fixture.codex_home.path().join("config.toml"),
&fixture.user_config,
)?;
mock_startup_bundle(
&fixture.server, status, "forced_login_method = 'api'\n",
"cli_auth_credentials_store = 'ephemeral'\nenforce_residency = 'us'\n[application.network.domains]\n'127.0.0.1' = 'allow'\n[windows]\nrequire_mxc = true\n",
).await;
let mut revoke = Mock::given(method("POST")).and(path("/revoke"));
if status == 200 {
revoke = revoke.and(header("x-openai-internal-codex-residency", "us"));
}
revoke
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&fixture.server)
.await;
let signed_out_home = TempDir::new()?;
std::fs::write(
signed_out_home.path().join("config.toml"),
&fixture.user_config,
)?;
let baseline = successful_json(
fixture
.command(&["app-server", "--print-startup-config"])?
.env("CODEX_HOME", signed_out_home.path()),
)
.await?;
let sqlite_home = TempDir::new()?;
let value = successful_json(
fixture
.command(&["app-server", "--print-startup-config", "--startup-sign-out"])?
.env("CODEX_SQLITE_HOME", sqlite_home.path())
.env(
"CODEX_REVOKE_TOKEN_URL_OVERRIDE",
format!("{}/revoke", fixture.server.uri()),
),
)
.await?;
assert_eq!(value["configRequirements"], baseline["configRequirements"]);
assert_eq!(std::fs::read_dir(sqlite_home.path())?.count(), 0);
let user_config: toml::Value = toml::from_str(&std::fs::read_to_string(
fixture.codex_home.path().join("config.toml"),
)?)?;
assert!(user_config.get("model_provider").is_none());
let status = fixture.command(&["login", "status"])?.output().await?;
assert!(!status.status.success());
fixture.server.verify().await;
}
Ok(())
}
const BUNDLE: &str = "/backend-api/wham/config/bundle";
const REGISTER: &str = "/cloud/environment/test/register";
const REGISTRATION_REACHED: &str = "registration reached";
#[tokio::test]
async fn remote_exec_server_loads_cloud_provider_with_chatgpt_auth() -> Result<()> {
check_registration(
"forced_login_method = 'chatgpt'\nmodel_provider = 'cloud-provider'",
Some((
"[model_providers.cloud-provider]\nname = 'Cloud provider'\nwire_api = 'responses'",
"",
)),
"Bearer chatgpt-token",
REGISTRATION_REACHED,
&[BUNDLE, REGISTER],
)
.await
}
#[tokio::test]
async fn remote_exec_server_api_key_skips_chatgpt_cloud_config() -> Result<()> {
check_registration(
"",
/*bundle*/ None,
"Bearer test-api-key",
REGISTRATION_REACHED,
&[REGISTER],
)
.await
}
#[tokio::test]
async fn remote_exec_server_cloud_policy_denies_registration() -> Result<()> {
check_registration(
"forced_login_method = 'chatgpt'",
Some(("", "[application.network]\nenabled = true\n[application.network.domains]\n'gateway.example.com' = 'allow'")),
"Bearer chatgpt-token",
"destination denied by application network policy",
&[BUNDLE],
)
.await
}
async fn check_registration(
config: &str,
bundle: Option<(&str, &str)>,
registration_auth: &str,
expected_error: &str,
expected_paths: &[&str],
) -> Result<()> {
let fixture = CloudManagedConfigFixture::for_backend()
.await?
.context("remote registration test requires isolated mock credentials")?;
let server = &fixture.server;
if let Some((config, requirements)) = bundle {
mock_startup_bundle(server, /*status*/ 200, config, requirements).await;
}
Mock::given(method("POST"))
.and(path(REGISTER))
.and(header("authorization", registration_auth))
.respond_with(ResponseTemplate::new(400).set_body_string(REGISTRATION_REACHED))
.mount(server)
.await;
std::fs::write(
fixture.codex_home.path().join("config.toml"),
format!("{}{config}\n", fixture.user_config),
)?;
let mut command = fixture.command(&[
"exec-server",
"--remote",
&server.uri(),
"--environment-id",
"test",
])?;
command.env("CODEX_API_KEY", "test-api-key");
let output = timeout(Duration::from_secs(30), command.output()).await??;
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!output.status.success() && stderr.contains(expected_error),
"{stderr}"
);
let requests = server
.received_requests()
.await
.context("mock request log")?;
let paths: Vec<_> = requests.iter().map(|request| request.url.path()).collect();
assert_eq!(paths, expected_paths);
Ok(())
}

View File

@@ -5,9 +5,6 @@ use std::process::Stdio;
use anyhow::Context as _;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::types::AuthCredentialsStoreMode;
use codex_state::SqliteConfig;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
@@ -170,7 +167,7 @@ async fn network_only_reports_recoverable_config_warnings_and_effective_config()
},
"config": {
"summary": "config loaded",
"scope": "invocation config, including cloud-managed policy",
"scope": "invocation config, including managed policy",
"provider": "local",
"startupWarnings": baseline_warning_count + 1,
"startupWarning": "Ignoring invalid `otel.span_attributes` config: configured span attribute key must not be empty",
@@ -247,124 +244,6 @@ async fn network_only_config_failure_human_output() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn doctor_reports_cloud_filesystem_policy_and_rejects_invalid_requirements() -> Result<()> {
for valid_requirements in [true, false] {
let server = MockServer::start().await;
let codex_home = TempDir::new()?;
let workspace = TempDir::new()?;
let workspace_key = serde_json::to_string(workspace.path())?;
let private_path = workspace.path().join("private-doctor-control");
let glob = format!("{}/**/*.doctor-secret", workspace.path().display());
let requirements = if valid_requirements {
format!("[permissions.filesystem]\ndeny_read = [{private_path:?}, {glob:?}]\n")
} else {
"[permissions.filesystem]\ndeny_read = false\n".to_string()
};
std::fs::write(
codex_home.path().join("config.toml"),
format!(
r#"
cli_auth_credentials_store = "ephemeral"
chatgpt_base_url = "{}/backend-api"
model_provider = "local"
[model_providers.local]
name = "local"
base_url = "{}/v1"
wire_api = "responses"
[windows]
sandbox = "elevated"
[projects.{workspace_key}]
trust_level = "trusted"
"#,
server.uri(),
server.uri(),
),
)?;
// Cloud authentication must use the project selected by --cd.
std::fs::create_dir(workspace.path().join(".codex"))?;
std::fs::write(
workspace.path().join(".codex/config.toml"),
"cli_auth_credentials_store = \"file\"\n",
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("doctor-test-token")
.account_id("doctor-workspace")
.chatgpt_account_id("doctor-workspace")
.chatgpt_user_id("doctor-user")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"requirements_toml": {
"enterprise_managed": [{
"id": "doctor-policy",
"name": "Doctor policy fixture",
"contents": requirements,
}],
},
})))
.expect(1)
.mount(&server)
.await;
let output = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
.current_dir(codex_home.path())
.env("CODEX_HOME", codex_home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.arg("--cd")
.arg(workspace.path())
.args(["doctor", "--json"])
.stdin(Stdio::null())
.output()?;
let report: Value = serde_json::from_slice(&output.stdout)?;
if valid_requirements {
let config = &report["checks"]["config.load"];
let sandbox = &report["checks"]["sandbox.helpers"]["details"];
assert_eq!(config["status"], "ok", "{config:#}");
assert_eq!(
config["details"]["cwd"],
workspace.path().display().to_string()
);
insta::assert_snapshot!(
serde_json::to_string_pretty(&json!({
"scope": config["details"]["configuration scope"],
"activeThreadOverrides": config["details"]["active thread overrides"],
"denyRules": sandbox["denied-read rules"],
"denyGlobs": sandbox["denied-read glob rules"],
"scanDepth": sandbox["glob scan max depth"],
"managedFilesystemSource": sandbox["managed filesystem source"],
}))?,
@r#"
{
"scope": "invocation config, including cloud-managed policy",
"activeThreadOverrides": "not inspected",
"denyRules": "2",
"denyGlobs": "1",
"scanDepth": "unbounded",
"managedFilesystemSource": "cloud"
}
"#
);
let stdout = String::from_utf8(output.stdout)?;
assert!(!stdout.contains("doctor-secret"));
assert!(!stdout.contains("private-doctor-control"));
} else {
assert_eq!(report["checks"]["config.load"]["status"], "fail");
assert!(report["checks"].get("sandbox.helpers").is_none());
}
server.verify().await;
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn invalid_custom_ca_falls_back_to_system_roots() -> Result<()> {
let server = MockServer::start().await;

View File

@@ -2,9 +2,6 @@
#[path = "exec_server/pid_namespace_tests.rs"]
mod pid_namespace_tests;
#[path = "exec_server/auth_refresh_tests.rs"]
mod auth_refresh_tests;
use std::collections::HashMap;
#[cfg(unix)]
use std::io::BufRead as _;
@@ -206,250 +203,6 @@ fn local_exec_server_allows_disabled_parent_lifetime_environment_variable() -> R
Ok(())
}
enum PatCredentialChange {
Rotate,
SwitchAccount,
Logout,
Unchanged,
UnavailableReplacement,
SlowReplacement,
}
async fn assert_pat_registry_reload(change: PatCredentialChange) -> Result<()> {
let home = TempDir::new()?;
let config_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.and(header("authorization", "Bearer at-synthetic-executor-pat"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"config_toml": {"enterprise_managed": []},
"requirements_toml": {"enterprise_managed": []},
})))
.expect(1)
.mount(&config_server)
.await;
std::fs::write(
home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = 'file'\nchatgpt_base_url = '{}/backend-api'\n",
config_server.uri(),
),
)?;
let auth_path = home.path().join("auth.json");
std::fs::write(
&auth_path,
serde_json::to_vec(&serde_json::json!({
"personal_access_token": "at-synthetic-executor-pat",
}))?,
)?;
let auth_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/v1/user-auth-credential/whoami"))
.and(header("authorization", "Bearer at-synthetic-executor-pat"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"chatgpt_user_id": "user-pat-test",
"chatgpt_account_id": "account-pat-test",
"chatgpt_plan_type": "enterprise",
"chatgpt_account_is_fedramp": false,
})))
// Cloud-config bootstrap and executor startup each hydrate once.
// Later registry requests must reuse metadata for the unchanged PAT.
.with_priority(1)
.up_to_n_times(2)
.expect(2)
.mount(&auth_server)
.await;
Mock::given(method("GET"))
.and(path("/v1/user-auth-credential/whoami"))
.respond_with(ResponseTemplate::new(503))
.with_priority(10)
.expect(0)
.mount(&auth_server)
.await;
if !matches!(
change,
PatCredentialChange::Logout | PatCredentialChange::Unchanged
) {
let account = match change {
PatCredentialChange::Rotate
| PatCredentialChange::UnavailableReplacement
| PatCredentialChange::SlowReplacement => "account-pat-test",
PatCredentialChange::SwitchAccount => "another-account",
PatCredentialChange::Logout | PatCredentialChange::Unchanged => unreachable!(),
};
if matches!(change, PatCredentialChange::UnavailableReplacement) {
Mock::given(method("GET"))
.and(path("/v1/user-auth-credential/whoami"))
.and(header(
"authorization",
"Bearer at-synthetic-replacement-pat",
))
.respond_with(ResponseTemplate::new(503))
.with_priority(1)
.up_to_n_times(1)
.expect(1)
.mount(&auth_server)
.await;
}
let response = ResponseTemplate::new(200).set_body_json(serde_json::json!({
"chatgpt_user_id": "user-pat-test",
"chatgpt_account_id": account,
"chatgpt_plan_type": "enterprise",
"chatgpt_account_is_fedramp": false,
}));
// Exceed registration's 10-second deadline while the detached auth
// resolution can still finish within its own 30-second budget.
let response = if matches!(change, PatCredentialChange::SlowReplacement) {
response.set_delay(Duration::from_secs(11))
} else {
response
};
Mock::given(method("GET"))
.and(path("/v1/user-auth-credential/whoami"))
.and(header(
"authorization",
"Bearer at-synthetic-replacement-pat",
))
.respond_with(response)
.with_priority(2)
.expect(1)
.mount(&auth_server)
.await;
}
let expected_registry_requests = match change {
PatCredentialChange::Rotate
| PatCredentialChange::Unchanged
| PatCredentialChange::UnavailableReplacement
| PatCredentialChange::SlowReplacement => 2,
PatCredentialChange::SwitchAccount | PatCredentialChange::Logout => 1,
};
let second_bearer = if matches!(change, PatCredentialChange::Unchanged) {
"Bearer at-synthetic-executor-pat"
} else {
"Bearer at-synthetic-replacement-pat"
};
let registry = MockServer::start().await;
let registration_path = "/cloud/environment/environment-pat-test/register";
let (credential_change_tx, mut credential_change_rx) = tokio::sync::mpsc::unbounded_channel();
Mock::given(method("POST"))
.and(path(registration_path))
.and(header("authorization", "Bearer at-synthetic-executor-pat"))
.and(header("chatgpt-account-id", "account-pat-test"))
.respond_with(move |_: &wiremock::Request| {
let result = match change {
PatCredentialChange::Rotate
| PatCredentialChange::SwitchAccount
| PatCredentialChange::UnavailableReplacement
| PatCredentialChange::SlowReplacement => std::fs::write(
&auth_path,
r#"{"personal_access_token":"at-synthetic-replacement-pat"}"#,
),
PatCredentialChange::Logout => std::fs::remove_file(&auth_path),
PatCredentialChange::Unchanged => Ok(()),
};
let _ = credential_change_tx.send(result);
ResponseTemplate::new(502).set_body_json(serde_json::json!({
"detail": {"code": "authentication_service_unavailable"},
}))
})
.with_priority(1)
.up_to_n_times(1)
.expect(1)
.mount(&registry)
.await;
Mock::given(method("POST"))
.and(path(registration_path))
.and(header("authorization", second_bearer))
.and(header("chatgpt-account-id", "account-pat-test"))
.respond_with(ResponseTemplate::new(403))
.with_priority(2)
.expect(expected_registry_requests - 1)
.mount(&registry)
.await;
let mut command = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
command
.current_dir(home.path())
.env("CODEX_HOME", home.path())
.env_remove("CODEX_ACCESS_TOKEN")
.env("CODEX_AUTHAPI_BASE_URL", auth_server.uri())
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"exec-server",
"--remote",
&registry.uri(),
"--environment-id",
"environment-pat-test",
])
.kill_on_drop(true);
// A same-owner replacement reaches the second registry request, whose denial
// stops the executor. Logout or a different owner must fail before that request.
let result = tokio::time::timeout(Duration::from_secs(30), command.output()).await;
assert!(
result.is_ok(),
"executor timed out (AuthAPI request count: {:?})",
auth_server
.received_requests()
.await
.map(|requests| requests.len()),
);
let output = result??;
let credential_update = credential_change_rx.try_recv();
assert!(
credential_update.is_ok(),
"registration did not update the credential fixture ({}): {}",
output.status,
String::from_utf8_lossy(&output.stderr),
);
credential_update?.context("update the stored PAT fixture")?;
assert!(!output.status.success());
registry.verify().await;
auth_server.verify().await;
config_server.verify().await;
assert_eq!(
registry
.received_requests()
.await
.context("registry request recording is disabled")?
.len(),
expected_registry_requests as usize
);
Ok(())
}
#[tokio::test]
async fn remote_exec_server_pat_follows_stored_rotation() -> Result<()> {
assert_pat_registry_reload(PatCredentialChange::Rotate).await
}
#[tokio::test]
async fn remote_exec_server_pat_rejects_account_switch() -> Result<()> {
assert_pat_registry_reload(PatCredentialChange::SwitchAccount).await
}
#[tokio::test]
async fn remote_exec_server_pat_stops_using_removed_credentials() -> Result<()> {
assert_pat_registry_reload(PatCredentialChange::Logout).await
}
#[tokio::test]
async fn remote_exec_server_pat_reuses_metadata_during_authapi_outage() -> Result<()> {
assert_pat_registry_reload(PatCredentialChange::Unchanged).await
}
#[tokio::test]
async fn remote_exec_server_pat_recovers_after_replacement_metadata_outage() -> Result<()> {
assert_pat_registry_reload(PatCredentialChange::UnavailableReplacement).await
}
#[tokio::test]
async fn remote_exec_server_pat_recovers_after_replacement_metadata_timeout() -> Result<()> {
assert_pat_registry_reload(PatCredentialChange::SlowReplacement).await
}
#[tokio::test]
async fn remote_exec_server_gracefully_stops_when_parent_stdin_closes() -> Result<()> {
const ENVIRONMENT_ID: &str = "environment-parent-lifetime";
@@ -1121,3 +874,55 @@ async fn wait_for_response(
}
}
}
/// API-key registration authenticates directly and never fetches account-managed
/// cloud configuration before registering.
#[tokio::test]
async fn remote_exec_server_api_key_registers_without_cloud_config() -> Result<()> {
const REGISTER: &str = "/cloud/environment/test/register";
const REGISTRATION_REACHED: &str = "registration reached";
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path(REGISTER))
.and(header("authorization", "Bearer test-api-key"))
.respond_with(ResponseTemplate::new(400).set_body_string(REGISTRATION_REACHED))
.mount(&server)
.await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
"cli_auth_credentials_store = \"file\"\n",
)?;
let output = tokio::time::timeout(
Duration::from_secs(30),
tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
.kill_on_drop(true)
.current_dir(home.path())
.env("CODEX_HOME", home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("OPENAI_API_KEY")
.env("CODEX_API_KEY", "test-api-key")
.args([
"exec-server",
"--remote",
&server.uri(),
"--environment-id",
"test",
])
.output(),
)
.await??;
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!output.status.success() && stderr.contains(REGISTRATION_REACHED),
"{stderr}"
);
let requests = server
.received_requests()
.await
.context("mock request log")?;
let paths: Vec<_> = requests.iter().map(|request| request.url.path()).collect();
assert_eq!(paths, vec![REGISTER]);
Ok(())
}

View File

@@ -1,178 +0,0 @@
//! Verify authentication updates across the running CLI executor process.
use std::process::Stdio;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_login::AuthCredentialsStoreMode;
use tempfile::TempDir;
use tokio::net::TcpListener;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::accept_hdr_async;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::path;
#[tokio::test]
async fn executor_startup_rejects_agent_identity_before_cloud_config() -> Result<()> {
let home = TempDir::new()?;
let server = MockServer::start().await;
Mock::given(wiremock::matchers::any())
.respond_with(ResponseTemplate::new(503))
.expect(0)
.mount(&server)
.await;
let manager = codex_login::test_support::auth_manager_with_agent_identity().await?;
let Some(codex_login::CodexAuth::AgentIdentity(agent)) = manager.auth_cached() else {
anyhow::bail!("expected Agent Identity fixture");
};
let mut record = agent.record().clone();
record.task_id = None;
std::fs::write(
home.path().join("auth.json"),
serde_json::to_vec(&serde_json::json!({
"auth_mode": codex_protocol::auth::AuthMode::AgentIdentity,
"agent_identity": record,
}))?,
)?;
std::fs::write(
home.path().join("config.toml"),
"cli_auth_credentials_store = 'file'\n",
)?;
let mut command = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
command
.current_dir(home.path())
.env("CODEX_HOME", home.path())
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("CODEX_ACCESS_TOKEN")
.env("CODEX_AGENT_IDENTITY_AUTHAPI_BASE_URL", server.uri())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"exec-server",
"--remote",
&server.uri(),
"--environment-id",
"env",
])
.kill_on_drop(true);
let output =
tokio::time::timeout(std::time::Duration::from_secs(20), command.output()).await??;
assert!(!output.status.success());
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("requires ChatGPT authentication or API key authentication"),
"{stderr}"
);
server.verify().await;
Ok(())
}
#[tokio::test]
async fn noise_executor_refreshes_on_401_and_reloads_rotated_credentials() -> Result<()> {
let home = TempDir::new()?;
let registry = MockServer::start().await;
let listener = TcpListener::bind("127.0.0.1:0").await?;
std::fs::write(
home.path().join("config.toml"),
"cli_auth_credentials_store = 'file'\n",
)?;
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("old-token")
.account_id("account")
.chatgpt_user_id("user"),
AuthCredentialsStoreMode::File,
)?;
Mock::given(path("/refresh"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"access_token": "refreshed-token", "refresh_token": "new-refresh-token",
})))
.expect(1)
.mount(&registry)
.await;
Mock::given(path("/cloud/environment/env/register"))
.and(header("authorization", "Bearer old-token"))
.respond_with(ResponseTemplate::new(401))
.expect(1)
.mount(&registry)
.await;
for token in ["refreshed-token", "rotated-token"] {
Mock::given(path("/cloud/environment/env/register"))
.and(header("authorization", format!("Bearer {token}")))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"environment_id": "env", "url": format!("ws://{}", listener.local_addr()?),
"executor_registration_id": "registration", "security_profile": "noise_hybrid_ik_v1",
})))
.with_priority(1)
.up_to_n_times(1)
.expect(1)
.mount(&registry)
.await;
}
// The later registration sees the stored rotation before sending a stale
// request. The initial 401 above still exercises bounded auth recovery.
Mock::given(path("/cloud/environment/env/register"))
.and(header("authorization", "Bearer refreshed-token"))
.respond_with(ResponseTemplate::new(401))
.expect(0)
.mount(&registry)
.await;
let mut child = tokio::process::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
.current_dir(home.path())
.env("CODEX_HOME", home.path())
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove("CODEX_ACCESS_TOKEN")
.env(
"CODEX_REFRESH_TOKEN_URL_OVERRIDE",
format!("{}/refresh", registry.uri()),
)
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args([
"exec-server",
"--remote",
&registry.uri(),
"--environment-id",
"env",
"--exit-on-stdin-close",
])
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()?;
let stdin = child.stdin.take();
let (socket, _) = listener.accept().await?;
let mut websocket = accept_async(socket).await?;
// Update storage while the executor is alive, then force a new registration.
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("rotated-token")
.account_id("account")
.chatgpt_user_id("user"),
AuthCredentialsStoreMode::File,
)?;
websocket.close(None).await?;
drop(websocket);
let (socket, _) = listener.accept().await?;
let rejected = accept_hdr_async(socket, |_: &_, _: _| {
Err(http::Response::builder().status(401).body(None).unwrap())
})
.await;
assert!(rejected.is_err());
let (socket, _) = listener.accept().await?;
let _websocket = accept_async(socket).await?;
drop(stdin);
let output = child.wait_with_output().await?;
anyhow::ensure!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
Ok(())
}

View File

@@ -1,23 +1,9 @@
use std::path::Path;
use anyhow::Context;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::ConfigLoadOptions;
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::config::load_config_toml_with_layer_stack;
use codex_utils_absolute_path::AbsolutePathBuf;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
@@ -234,101 +220,6 @@ async fn features_list_is_sorted_alphabetically_by_feature_name() -> Result<()>
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn features_list_honors_cloud_managed_feature_requirements() -> Result<()> {
let server = MockServer::start().await;
let chatgpt_base_url = format!("{}/backend-api", server.uri());
let codex_home = TempDir::new()?;
let user_config = format!(
"cli_auth_credentials_store = \"file\"\nchatgpt_base_url = \"{chatgpt_base_url}\"\n\n[features]\nfast_mode = true\nin_app_voice = true\n"
);
std::fs::write(codex_home.path().join("config.toml"), &user_config)?;
let bootstrap_config = load_config_toml_with_layer_stack(
codex_home.path(),
Some(&AbsolutePathBuf::from_absolute_path(codex_home.path())?),
Vec::new(),
ConfigLoadOptions::default(),
)
.await?;
if bootstrap_config.config_toml.cli_auth_credentials_store
!= Some(AuthCredentialsStoreMode::File)
|| bootstrap_config.config_toml.chatgpt_base_url.as_deref()
!= Some(chatgpt_base_url.as_str())
{
eprintln!(
"skipping cloud-managed feature subprocess: host-managed authentication or backend routing prevents isolated mock credentials"
);
return Ok(());
}
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("workspace-123")
.chatgpt_account_id("workspace-123")
.chatgpt_user_id("user-123")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "workspace-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"requirements_toml": {
"enterprise_managed": [{
"id": "managed-feature-requirements",
"name": "Managed feature requirements",
"contents": "[features]\nfast_mode = false\nin_app_voice = false\n",
}],
},
})))
.expect(1)
.mount(&server)
.await;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd
.current_dir(codex_home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.args(["features", "list"])
.assert()
.success()
.get_output()
.stdout
.clone();
let stdout = String::from_utf8(output)?;
let fast_mode = stdout
.lines()
.find(|line| line.starts_with("fast_mode "))
.context("feature list should include fast_mode")?;
assert_eq!(
fast_mode.split_whitespace().collect::<Vec<_>>(),
["fast_mode", "stable", "false"]
);
let in_app_voice = stdout
.lines()
.find(|line| line.starts_with("in_app_voice "))
.context("feature list should include in_app_voice")?;
insta::assert_snapshot!(
in_app_voice.split_whitespace().collect::<Vec<_>>().join(" "),
@"in_app_voice stable false"
);
assert_eq!(
std::fs::read_to_string(codex_home.path().join("config.toml"))?,
user_config
);
server.verify().await;
Ok(())
}
#[test]
fn remote_start_rejects_add_dir_before_connecting() -> Result<()> {
let home = TempDir::new()?;

View File

@@ -1,31 +1,14 @@
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use anyhow::Context;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::types::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::CLIENT_ID;
use codex_login::CODEX_ACCESS_TOKEN_ENV_VAR;
use codex_login::REVOKE_TOKEN_URL_OVERRIDE_ENV_VAR;
use codex_login::login_with_bedrock_access_keys;
use codex_protocol::shell_environment::OPENAI_FEDERATION_RULE_ID_ENV_VAR;
use codex_protocol::shell_environment::OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
@@ -73,9 +56,6 @@ fn login_with_api_key_reads_stdin_and_writes_auth_json() -> Result<()> {
assert!(auth.get("agent_identity").is_none());
let status = codex_command(codex_home.path())?
.env_remove(CODEX_ACCESS_TOKEN_ENV_VAR)
.env_remove(OPENAI_FEDERATION_RULE_ID_ENV_VAR)
.env_remove(OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR)
.args(["login", "status"])
.assert()
.success();
@@ -84,13 +64,19 @@ fn login_with_api_key_reads_stdin_and_writes_auth_json() -> Result<()> {
Authentication is checked when you send a request.
");
for args in [vec!["login"], vec!["login", "--device-auth"]] {
codex_command(codex_home.path())?
.args(["-c", "forced_login_method=\"api\"", "login"])
.assert()
.failure()
.stderr(contains("Only API key login is supported"));
assert_eq!(read_auth_json(codex_home.path())?, auth);
for removed_flag in ["--device-auth", "--with-access-token"] {
codex_command(codex_home.path())?
.args(["-c", "forced_login_method=\"api\""])
.args(args)
.args(["login", removed_flag])
.write_stdin("token\n")
.assert()
.failure()
.stderr(contains("ChatGPT login is disabled"));
.stderr(contains("unexpected argument"));
assert_eq!(read_auth_json(codex_home.path())?, auth);
}
@@ -150,29 +136,35 @@ fn login_status_reports_auth_storage_errors() -> Result<()> {
}
#[test]
fn login_status_validates_configured_workload_identity() -> Result<()> {
fn legacy_chatgpt_auth_is_reported_as_not_logged_in_and_logout_removes_it() -> Result<()> {
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
let missing_assertion = codex_home.path().join("missing-identity-token");
std::fs::write(
codex_home.path().join("auth.json"),
serde_json::to_vec(&json!({
"auth_mode": "chatgpt",
"OPENAI_API_KEY": null,
"tokens": {
"id_token": "eyJhbGciOiJub25lIn0.e30.c2ln",
"access_token": "old-access",
"refresh_token": "old-refresh",
},
}))?,
)?;
for login_method in ["chatgpt", "api"] {
let mut command = codex_command(codex_home.path())?;
command
.env_remove(CODEX_ACCESS_TOKEN_ENV_VAR)
.env(OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR, &missing_assertion)
.env(OPENAI_FEDERATION_RULE_ID_ENV_VAR, "rule-test")
.args([
"-c",
&format!("forced_login_method=\"{login_method}\""),
"login",
"status",
]);
command
.assert()
.failure()
.stderr(contains("could not read workload identity assertion file"));
}
codex_command(codex_home.path())?
.env_remove("CODEX_API_KEY")
.args(["login", "status"])
.assert()
.failure()
.stderr(contains("Not logged in"));
codex_command(codex_home.path())?
.arg("logout")
.assert()
.success()
.stderr(contains("Successfully logged out"));
assert!(!codex_home.path().join("auth.json").exists());
Ok(())
}
@@ -239,7 +231,6 @@ fn logout_clears_only_the_selected_bedrock_provider() -> Result<()> {
};
codex_command(codex_home.path())?
.env_remove(CODEX_ACCESS_TOKEN_ENV_VAR)
.env("AWS_ACCESS_KEY_ID", "environment-access-key-id")
.env("AWS_SECRET_ACCESS_KEY", "environment-secret-access-key")
.args(["logout"])
@@ -254,242 +245,3 @@ fn logout_clears_only_the_selected_bedrock_provider() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn logout_survives_enterprise_cleanup_failure_with_xaa_disabled() -> Result<()> {
let server = MockServer::start().await;
Mock::given(path("/backend-api/wham/config/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"config_toml": {"enterprise_managed": []},
"requirements_toml": {"enterprise_managed": []},
})))
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/oauth/revoke"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&server)
.await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = \"file\"\nchatgpt_base_url = \"{}/backend-api\"\n[features]\nuse_xaa = false\n[mcp_enterprise_managed_auth.idp]\nissuer = \"https://idp.example\"\nclient_id = \"enterprise-client\"\n[mcp_servers.enterprise]\nurl = \"https://resource.example/mcp\"\nauth = \"ema_auth\"\nbearer_token_env_var = \"UNUSED_TOKEN\"\n",
server.uri()
),
)?;
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("account-access")
.account_id("workspace")
.chatgpt_user_id("user"),
AuthCredentialsStoreMode::File,
)?;
// Fail before touching the real keyring; the subprocess owns this isolated home.
std::fs::write(home.path().join("mcp-oauth-locks"), "not a directory")?;
for enabled in [false, true] {
codex_command(home.path())?
.current_dir(home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove(CODEX_ACCESS_TOKEN_ENV_VAR)
.args([
"-c",
&format!("features.use_xaa={enabled}"),
"mcp",
"logout",
"enterprise",
])
.assert()
.failure()
.stderr(contains("failed to delete enterprise authorization"));
assert!(home.path().join("auth.json").exists());
}
codex_command(home.path())?
.current_dir(home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env(
REVOKE_TOKEN_URL_OVERRIDE_ENV_VAR,
format!("{}/oauth/revoke", server.uri()),
)
.env_remove("CODEX_API_KEY")
.env_remove("OPENAI_API_KEY")
.env_remove(CODEX_ACCESS_TOKEN_ENV_VAR)
.args(["logout"])
.assert()
.success()
.stderr(contains("continuing account logout"))
.stderr(contains("Successfully logged out"));
assert!(!home.path().join("auth.json").exists());
Ok(())
}
#[test]
fn login_with_access_token_rejects_invalid_jwt() -> Result<()> {
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
let mut cmd = codex_command(codex_home.path())?;
cmd.args(["login", "--with-access-token"])
.write_stdin("not-a-jwt\n")
.assert()
.failure()
.stderr(contains("Error logging in with access token"));
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn debug_prompt_input_follows_authenticated_attribution_setting() -> Result<()> {
let server = MockServer::start().await;
let request_count = Arc::new(AtomicUsize::new(0));
Mock::given(method("GET"))
.and(path("/backend-api/wham/settings/user"))
.and(header("chatgpt-account-id", "workspace-123"))
.respond_with(move |_request: &wiremock::Request| {
ResponseTemplate::new(200).set_body_json(json!({
"commit_attribution_enabled": request_count.fetch_add(1, Ordering::SeqCst) == 0,
}))
})
.expect(2)
.mount(&server)
.await;
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = \"file\"\nchatgpt_base_url = \"{}/backend-api\"\n",
server.uri()
),
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("workspace-123")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
for enabled in [true, false] {
let output = codex_command(codex_home.path())?
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("OPENAI_API_KEY")
.args(["debug", "prompt-input"])
.output()?;
assert!(output.status.success());
let prompt = String::from_utf8(output.stdout)?;
assert_eq!(
prompt.contains("Co-authored-by: Codex <noreply@openai.com>"),
enabled
);
assert!(!prompt.contains("attribution is disabled for the current workspace"));
}
server.verify().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn device_login_revokes_existing_auth_before_requesting_new_tokens() -> Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/oauth/revoke"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/api/accounts/deviceauth/usercode"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"device_auth_id": "device-auth-123",
"user_code": "CODE-12345",
"interval": "0",
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/api/accounts/deviceauth/token"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"authorization_code": "authorization-code-123",
"code_challenge": "code-challenge-123",
"code_verifier": "code-verifier-123",
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/oauth/token"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id_token": "eyJhbGciOiJub25lIn0.e30.c2ln",
"access_token": "new-access",
"refresh_token": "new-refresh",
})))
.expect(1)
.mount(&server)
.await;
let codex_home = TempDir::new()?;
write_file_auth_config(codex_home.path())?;
std::fs::write(
codex_home.path().join("auth.json"),
serde_json::to_vec(&json!({
"auth_mode": "chatgpt",
"OPENAI_API_KEY": null,
"tokens": {
"id_token": "eyJhbGciOiJub25lIn0.e30.c2ln",
"access_token": "old-access",
"refresh_token": "old-refresh",
"account_id": "old-account",
},
}))?,
)?;
let issuer = server.uri();
let mut cmd = codex_command(codex_home.path())?;
cmd.env(
REVOKE_TOKEN_URL_OVERRIDE_ENV_VAR,
format!("{issuer}/oauth/revoke"),
)
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("OPENAI_API_KEY")
.args(["login", "--device-auth", "--experimental_issuer", &issuer])
.assert()
.success()
.stderr(contains("Successfully logged in"));
let requests = server
.received_requests()
.await
.context("failed to read mock OAuth requests")?;
let paths: Vec<&str> = requests.iter().map(|request| request.url.path()).collect();
assert_eq!(
paths,
vec![
"/oauth/revoke",
"/api/accounts/deviceauth/usercode",
"/api/accounts/deviceauth/token",
"/oauth/token",
]
);
assert_eq!(
requests[0]
.body_json::<Value>()
.context("revoke request should be JSON")?,
json!({
"token": "old-refresh",
"token_type_hint": "refresh_token",
"client_id": CLIENT_ID,
})
);
let auth = read_auth_json(codex_home.path())?;
assert_eq!(auth["tokens"]["refresh_token"], "new-refresh");
Ok(())
}

View File

@@ -1,36 +1,18 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::CONFIG_TOML_FILE;
use codex_config::MarketplaceConfigUpdate;
use codex_config::record_user_marketplace;
use codex_config::types::AuthCredentialsStoreMode;
use codex_utils_absolute_path::canonicalize_existing_preserving_symlinks;
use flate2::Compression;
use flate2::write::GzEncoder;
use predicates::prelude::PredicateBooleanExt;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::path::Path;
use std::process::Output;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use tempfile::TempDir;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
const MARKETPLACE_HEADER: &str = "MARKETPLACE";
const MARKETPLACE_LIST_HEADER: &str = "MARKETPLACE ROOT";
@@ -1186,753 +1168,3 @@ async fn plugin_add_rejects_cached_plugins_without_authorizing_marketplace_snaps
Ok(())
}
const REMOTE_ID: &str = "b1234567-89ab-4cde-8f01-234567890abc";
const MARKETPLACE: &str = "openai-curated-remote";
const PLUGIN_KEY: &str = "sample@openai-curated-remote";
fn sample_remote_plugin_bundle() -> Result<Vec<u8>> {
let mut archive = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::default()));
for (path, contents) in [
(
".codex-plugin/plugin.json",
r#"{"name":"sample","version":"1.2.3"}"#,
),
(
"skills/sample/SKILL.md",
"---\nname: sample\ndescription: Sample remote skill\n---\nSample instructions.\n",
),
] {
let mut header = tar::Header::new_gnu();
header.set_size(contents.len() as u64);
header.set_mode(/*mode*/ 0o644);
header.set_cksum();
archive.append_data(&mut header, path, contents.as_bytes())?;
}
Ok(archive.into_inner()?.finish()?)
}
struct RemoteMarketplaceFixture {
home: TempDir,
server: MockServer,
plugin: Value,
}
impl RemoteMarketplaceFixture {
async fn new() -> Result<Self> {
let home = TempDir::new()?;
let server = MockServer::start().await;
std::fs::write(
home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = 'file'\nchatgpt_base_url = '{}/backend-api'\n[features]\nplugins = true\nremote_plugin = true\n",
server.uri()
),
)?;
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
let plugin = json!({
"id": REMOTE_ID, "name": "sample", "scope": "GLOBAL",
"installation_policy": "AVAILABLE", "authentication_policy": "ON_USE",
"release": {"version": "1.2.3", "display_name": "Sample", "description": "Remote sample",
"interface": {}, "bundle_download_url": format!("{}/bundle.tar.gz", server.uri())}
});
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/list"))
.and(query_param("scope", "GLOBAL"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(
json!({"plugins": [plugin.clone()], "pagination": {"next_page_token": null}}),
))
.mount(&server)
.await;
Ok(Self {
home,
server,
plugin,
})
}
fn write_local_curated_marketplace(&self) -> Result<Value> {
let source = canonicalize_existing_preserving_symlinks(self.home.path())?
.join(".tmp")
.join("plugins");
let mut manifest = json!({
"name": "openai-curated",
"plugins": [{
"name": "sample",
"source": {"source": "local", "path": "./plugins/sample"}
}]
});
write_marketplace_source_with_manifest(&source, &manifest.to_string())?;
std::fs::write(
self.home.path().join(".tmp").join("plugins.sha"),
"local-curated",
)?;
manifest["name"] = json!("openai-api-curated");
std::fs::write(
source
.join(".agents")
.join("plugins")
.join("api_marketplace.json"),
manifest.to_string(),
)?;
Ok(json!({
"pluginId": "sample@openai-curated", "name": "sample",
"marketplaceName": "openai-curated", "version": "1.2.3",
"installed": false, "enabled": false,
"source": {"source": "local", "path": source.join("plugins").join("sample")},
"installPolicy": "AVAILABLE", "authPolicy": "ON_INSTALL"
}))
}
async fn run(&self, args: &[&str]) -> Result<Output> {
Ok(Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
.current_dir(self.home.path())
.env("CODEX_HOME", self.home.path())
.env("HOME", self.home.path())
.env_remove("OPENAI_API_KEY")
.env_remove("CODEX_API_KEY")
.env_remove("CODEX_ACCESS_TOKEN")
.env("CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS", "1")
.args(args)
.output()
.await?)
}
async fn success(&self, args: &[&str]) -> Result<String> {
let output = self.run(args).await?;
ensure!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
Ok(String::from_utf8(output.stdout)?)
}
}
#[tokio::test]
async fn remote_plugin_listing_replaces_local_curated_catalog() -> Result<()> {
let fixture = RemoteMarketplaceFixture::new().await?;
let mut local_plugin = fixture.write_local_curated_marketplace()?;
fixture
.success(&["plugin", "add", "sample@openai-curated"])
.await?;
local_plugin["installed"] = json!(true);
local_plugin["enabled"] = json!(true);
local_plugin["version"] = json!("local-curated");
let mut installed_plugin = fixture.plugin.clone();
installed_plugin["enabled"] = json!(true);
Mock::given(path("/backend-api/ps/plugins/installed"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [installed_plugin], "pagination": {"next_page_token": null}
})))
.mount(&fixture.server)
.await;
let listed = fixture
.success(&["plugin", "list", "--available", "--json"])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [{
"pluginId": PLUGIN_KEY, "name": "sample", "marketplaceName": MARKETPLACE,
"version": "1.2.3", "installed": true, "enabled": true,
"source": {"source": "remote", "id": REMOTE_ID},
"installPolicy": "AVAILABLE", "authPolicy": "ON_USE"
}], "available": []})
);
let table = fixture.success(&["plugin", "list"]).await?;
insta::assert_snapshot!(table, @r"
Marketplace `openai-curated-remote`
Remote catalog
PLUGIN STATUS VERSION SOURCE
sample@openai-curated-remote installed, enabled 1.2.3 b1234567-89ab-4cde-8f01-234567890abc
");
fixture.server.reset().await;
let listed = fixture
.success(&["plugin", "list", "-m", "openai-curated", "--json"])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [local_plugin], "available": []})
);
assert!(fixture.server.received_requests().await.unwrap().is_empty());
Ok(())
}
#[tokio::test]
async fn remote_plugin_listing_preserves_local_curated_only_when_fetch_fails() -> Result<()> {
for status in [200, 403] {
let fixture = RemoteMarketplaceFixture::new().await?;
fixture.server.reset().await;
let local_plugin = fixture.write_local_curated_marketplace()?;
let response = ResponseTemplate::new(status).set_body_json(json!({
"plugins": [], "pagination": {"next_page_token": null}
}));
let _catalog = Mock::given(path("/backend-api/ps/plugins/list"))
.respond_with(response)
.mount_as_scoped(&fixture.server)
.await;
Mock::given(path("/backend-api/ps/plugins/installed"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [], "pagination": {"next_page_token": null}
})))
.mount(&fixture.server)
.await;
let listed = fixture
.success(&["plugin", "list", "--available", "--json"])
.await?;
let available = if status == 200 {
Vec::new()
} else {
vec![local_plugin]
};
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [], "available": available}),
"catalog response status: {status}"
);
}
Ok(())
}
#[tokio::test]
async fn remote_plugin_add_list_and_remove() -> Result<()> {
let fixture = RemoteMarketplaceFixture::new().await?;
let installed = Arc::new(AtomicBool::new(false));
let installed_for_list = Arc::clone(&installed);
let mut installed_plugin = fixture.plugin.clone();
installed_plugin["enabled"] = json!(true);
Mock::given(path("/backend-api/ps/plugins/installed"))
.respond_with(move |_: &wiremock::Request| {
let plugins = if installed_for_list.load(Ordering::SeqCst) {
vec![installed_plugin.clone()]
} else {
Vec::new()
};
ResponseTemplate::new(200)
.set_body_json(json!({"plugins": plugins, "pagination": {"next_page_token": null}}))
})
.mount(&fixture.server)
.await;
Mock::given(path(format!("/backend-api/ps/plugins/{REMOTE_ID}")))
.respond_with(ResponseTemplate::new(200).set_body_json(&fixture.plugin))
.mount(&fixture.server)
.await;
Mock::given(path("/bundle.tar.gz"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(sample_remote_plugin_bundle()?))
.expect(1)
.mount(&fixture.server)
.await;
let installed_root = canonicalize_existing_preserving_symlinks(fixture.home.path())?
.join("plugins")
.join("cache")
.join(MARKETPLACE)
.join("sample")
.join("1.2.3");
let manifest = installed_root.join(".codex-plugin/plugin.json");
let installed_for_add = Arc::clone(&installed);
Mock::given(method("POST"))
.and(path(format!("/backend-api/ps/plugins/{REMOTE_ID}/install")))
.and(query_param("includeAppsNeedingAuth", "true"))
.and(header("authorization", "Bearer chatgpt-token"))
.respond_with(move |_: &wiremock::Request| {
assert!(
manifest.is_file(),
"cache must exist before backend install"
);
installed_for_add.store(true, Ordering::SeqCst);
ResponseTemplate::new(200).set_body_json(json!({"id": REMOTE_ID, "enabled": true}))
})
.expect(1)
.mount(&fixture.server)
.await;
Mock::given(method("POST"))
.and(path(format!(
"/backend-api/ps/plugins/{REMOTE_ID}/uninstall"
)))
.and(header("authorization", "Bearer chatgpt-token"))
.respond_with(move |_: &wiremock::Request| {
installed.store(false, Ordering::SeqCst);
ResponseTemplate::new(200).set_body_json(json!({"id": REMOTE_ID, "enabled": false}))
})
.expect(1)
.mount(&fixture.server)
.await;
let available = json!({
"pluginId": PLUGIN_KEY, "name": "sample", "marketplaceName": MARKETPLACE,
"version": "1.2.3", "installed": false, "enabled": false,
"source": {"source": "remote", "id": REMOTE_ID}, "installPolicy": "AVAILABLE", "authPolicy": "ON_USE"
});
let listed = fixture
.success(&["plugin", "list", "--available", "--json"])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [], "available": [available.clone()]})
);
let table = fixture
.success(&["plugin", "list", "-m", MARKETPLACE])
.await?;
insta::assert_snapshot!(table, @r"
Marketplace `openai-curated-remote`
Remote catalog
PLUGIN STATUS VERSION SOURCE
sample@openai-curated-remote not installed 1.2.3 b1234567-89ab-4cde-8f01-234567890abc
");
let added = fixture
.success(&["plugin", "add", PLUGIN_KEY, "--json"])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&added)?,
json!({
"pluginId": PLUGIN_KEY, "name": "sample", "marketplaceName": MARKETPLACE,
"version": "1.2.3", "installedPath": installed_root, "authPolicy": "ON_USE"
})
);
assert_eq!(
fixture
.server
.received_requests()
.await
.unwrap()
.iter()
.filter(|request| request.url.path() == "/backend-api/ps/plugins/list")
.count(),
1,
"installing a cached name must not refetch the catalog"
);
assert!(installed_root.join("skills/sample/SKILL.md").is_file());
let mut expected = available;
expected["installed"] = json!(true);
expected["enabled"] = json!(true);
let listed = fixture
.success(&["plugin", "list", "-m", MARKETPLACE, "--json"])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [expected], "available": []})
);
let _delisted = Mock::given(path("/backend-api/ps/plugins/list"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(json!({"plugins": [], "pagination": {"next_page_token": null}})),
)
.mount_as_scoped(&fixture.server)
.await;
let removed = fixture
.success(&[
"-c",
"features.remote_plugin=false",
"plugin",
"remove",
"sample",
"-m",
MARKETPLACE,
"--json",
])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&removed)?,
json!({"pluginId": PLUGIN_KEY, "name": "sample", "marketplaceName": MARKETPLACE})
);
assert!(!installed_root.exists());
let listed = fixture.success(&["plugin", "list", "--json"]).await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [], "available": []})
);
Ok(())
}
#[tokio::test]
async fn remote_plugin_add_refreshes_cached_catalog_on_name_miss() -> Result<()> {
for (remote_plugin_config, collection) in [
("features.remote_plugin=true", None),
("features.remote_plugin=false", Some("vertical")),
] {
let fixture = RemoteMarketplaceFixture::new().await?;
fixture.server.reset().await;
let published = Arc::new(AtomicBool::new(false));
let published_for_list = Arc::clone(&published);
let plugin = fixture.plugin.clone();
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/list"))
.and(query_param("scope", "GLOBAL"))
.respond_with(move |_: &wiremock::Request| {
let plugins = if published_for_list.load(Ordering::SeqCst) {
vec![plugin.clone()]
} else {
Vec::new()
};
ResponseTemplate::new(200).set_body_json(json!({
"plugins": plugins, "pagination": {"next_page_token": null}
}))
})
.expect(2)
.mount(&fixture.server)
.await;
Mock::given(path("/backend-api/ps/plugins/installed"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [], "pagination": {"next_page_token": null}
})))
.mount(&fixture.server)
.await;
Mock::given(path(format!("/backend-api/ps/plugins/{REMOTE_ID}")))
.respond_with(ResponseTemplate::new(200).set_body_json(&fixture.plugin))
.expect(1)
.mount(&fixture.server)
.await;
Mock::given(path("/bundle.tar.gz"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(sample_remote_plugin_bundle()?))
.expect(1)
.mount(&fixture.server)
.await;
Mock::given(method("POST"))
.and(path(format!("/backend-api/ps/plugins/{REMOTE_ID}/install")))
.respond_with(
ResponseTemplate::new(200).set_body_json(json!({"id": REMOTE_ID, "enabled": true})),
)
.expect(1)
.mount(&fixture.server)
.await;
for is_published in [false, true] {
published.store(is_published, Ordering::SeqCst);
let listed = fixture
.success(&[
"-c",
remote_plugin_config,
"plugin",
"list",
"-m",
MARKETPLACE,
"--available",
"--json",
])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [], "available": []}),
"normal listing must keep using the fresh catalog cache"
);
}
let added = fixture
.success(&[
"-c",
remote_plugin_config,
"plugin",
"add",
PLUGIN_KEY,
"--json",
])
.await?;
let installed_root = canonicalize_existing_preserving_symlinks(fixture.home.path())?
.join("plugins")
.join("cache")
.join(MARKETPLACE)
.join("sample")
.join("1.2.3");
assert_eq!(
serde_json::from_str::<Value>(&added)?,
json!({
"pluginId": PLUGIN_KEY, "name": "sample", "marketplaceName": MARKETPLACE,
"version": "1.2.3", "installedPath": installed_root, "authPolicy": "ON_USE"
})
);
assert!(
installed_root
.join("skills")
.join("sample")
.join("SKILL.md")
.is_file()
);
let requests = fixture.server.received_requests().await.unwrap();
let catalog_collections = requests
.iter()
.filter(|request| request.url.path() == "/backend-api/ps/plugins/list")
.map(|request| {
request
.url
.query_pairs()
.find_map(|(key, value)| (key == "collection").then(|| value.into_owned()))
})
.collect::<Vec<_>>();
assert_eq!(catalog_collections, vec![collection.map(str::to_owned); 2]);
}
Ok(())
}
#[tokio::test]
async fn remote_plugin_add_limits_catalog_refresh_without_mutation() -> Result<()> {
enum CatalogCache {
Missing,
Fresh,
Expired,
}
for (remote_plugin_config, collection) in [
("features.remote_plugin=true", None),
("features.remote_plugin=false", Some("vertical")),
] {
for (cache, plugin_count, status, catalog_fetches, error) in [
(
CatalogCache::Missing,
0,
200,
1,
"was not found in remote marketplace",
),
(
CatalogCache::Fresh,
0,
200,
2,
"was not found in remote marketplace",
),
(
CatalogCache::Expired,
0,
200,
2,
"was not found in remote marketplace",
),
(
CatalogCache::Missing,
2,
200,
1,
"matched multiple remote plugins",
),
(
CatalogCache::Missing,
0,
403,
1,
"failed to list remote marketplace plugins",
),
] {
let fixture = RemoteMarketplaceFixture::new().await?;
fixture.server.reset().await;
let mut duplicate = fixture.plugin.clone();
duplicate["id"] = json!("c1234567-89ab-4cde-8f01-234567890abc");
let plugins = [fixture.plugin.clone(), duplicate]
.into_iter()
.take(plugin_count)
.collect::<Vec<_>>();
Mock::given(path("/backend-api/ps/plugins/list"))
.and(query_param("scope", "GLOBAL"))
.respond_with(ResponseTemplate::new(status).set_body_json(json!({
"plugins": plugins, "pagination": {"next_page_token": null}
})))
.expect(catalog_fetches)
.mount(&fixture.server)
.await;
Mock::given(path("/backend-api/ps/plugins/installed"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [], "pagination": {"next_page_token": null}
})))
.mount(&fixture.server)
.await;
if !matches!(cache, CatalogCache::Missing) {
let listed = fixture
.success(&[
"-c",
remote_plugin_config,
"plugin",
"list",
"-m",
MARKETPLACE,
"--available",
"--json",
])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [], "available": []})
);
}
if matches!(cache, CatalogCache::Expired) {
let cache_paths = std::fs::read_dir(
fixture
.home
.path()
.join("cache")
.join("remote_plugin_catalog"),
)?
.map(|entry| entry.map(|entry| entry.path()))
.collect::<std::io::Result<Vec<_>>>()?;
assert_eq!(cache_paths.len(), 1);
let cache_path = &cache_paths[0];
let mut cached_catalog: Value =
serde_json::from_slice(&std::fs::read(cache_path)?)?;
cached_catalog["fetched_at"] = json!("2000-01-01T00:00:00Z");
std::fs::write(cache_path, serde_json::to_vec(&cached_catalog)?)?;
}
let output = fixture
.run(&["-c", remote_plugin_config, "plugin", "add", PLUGIN_KEY])
.await?;
assert!(!output.status.success());
let stderr = String::from_utf8(output.stderr)?;
assert!(stderr.contains(error), "{stderr}");
let requests = fixture.server.received_requests().await.unwrap();
let catalog_collections = requests
.iter()
.filter(|request| request.url.path() == "/backend-api/ps/plugins/list")
.map(|request| {
request
.url
.query_pairs()
.find_map(|(key, value)| (key == "collection").then(|| value.into_owned()))
})
.collect::<Vec<_>>();
assert_eq!(
catalog_collections,
vec![collection.map(str::to_owned); catalog_fetches as usize]
);
assert!(requests.iter().all(|request| {
request.method == "GET"
&& matches!(
request.url.path(),
"/backend-api/ps/plugins/list" | "/backend-api/ps/plugins/installed"
)
}));
assert!(
!fixture
.home
.path()
.join("plugins")
.join("cache")
.join(MARKETPLACE)
.exists()
);
}
}
Ok(())
}
#[tokio::test]
async fn remote_plugin_install_checks_policy_and_bundle_before_mutation() -> Result<()> {
let fixture = RemoteMarketplaceFixture::new().await?;
Mock::given(path("/backend-api/ps/plugins/installed"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(json!({"plugins": [], "pagination": {"next_page_token": null}})),
)
.mount(&fixture.server)
.await;
for (field, value, error) in [
("status", "DISABLED_BY_ADMIN", "disabled by admin"),
(
"installation_policy",
"NOT_AVAILABLE",
"not available for install",
),
("status", "ENABLED", "failed to read plugin bundle tar"),
] {
let mut plugin = fixture.plugin.clone();
plugin[field] = json!(value);
let _detail = Mock::given(path(format!("/backend-api/ps/plugins/{REMOTE_ID}")))
.respond_with(ResponseTemplate::new(200).set_body_json(plugin))
.mount_as_scoped(&fixture.server)
.await;
let _bundle = Mock::given(path("/bundle.tar.gz"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"bad gzip"))
.mount_as_scoped(&fixture.server)
.await;
let output = fixture
.run(&["plugin", "add", "sample", "-m", MARKETPLACE])
.await?;
assert!(!output.status.success());
let stderr = String::from_utf8(output.stderr)?;
assert!(stderr.contains(error), "{stderr}");
}
let requests = fixture.server.received_requests().await.unwrap();
assert!(requests.iter().all(|request| request.method != "POST"));
assert_eq!(
requests
.iter()
.filter(|request| request.url.path() == "/backend-api/ps/plugins/list")
.count(),
1,
"installation policy and bundle failures must not refetch the catalog"
);
Ok(())
}
#[tokio::test]
async fn remote_plugin_listing_uses_collection_when_remote_catalog_is_disabled() -> Result<()> {
let fixture = RemoteMarketplaceFixture::new().await?;
let mut local_plugin = fixture.write_local_curated_marketplace()?;
Mock::given(path("/backend-api/ps/plugins/installed"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(json!({"plugins": [], "pagination": {"next_page_token": null}})),
)
.mount(&fixture.server)
.await;
let listed = fixture
.success(&[
"-c",
"features.remote_plugin=false",
"plugin",
"list",
"--available",
"--json",
])
.await?;
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [], "available": [local_plugin.clone(), {
"pluginId": PLUGIN_KEY, "name": "sample", "marketplaceName": MARKETPLACE,
"version": "1.2.3", "installed": false, "enabled": false,
"source": {"source": "remote", "id": REMOTE_ID},
"installPolicy": "AVAILABLE", "authPolicy": "ON_USE"
}]})
);
let requests = fixture.server.received_requests().await.unwrap();
let listing = requests
.iter()
.find(|request| request.url.path().ends_with("/list"))
.unwrap();
assert!(
listing
.url
.query_pairs()
.any(|(key, value)| key == "collection" && value == "vertical")
);
fixture.server.reset().await;
fixture
.success(&["-c", "features.plugins=false", "plugin", "list"])
.await?;
fixture
.success(&["plugin", "list", "-m", "local-only"])
.await?;
assert!(fixture.server.received_requests().await.unwrap().is_empty());
std::fs::remove_file(fixture.home.path().join("auth.json"))?;
let output = fixture.run(&["plugin", "list", "-m", MARKETPLACE]).await?;
assert!(!output.status.success());
assert!(String::from_utf8(output.stderr)?.contains("chatgpt authentication required"));
let listed = fixture
.success(&["plugin", "list", "--available", "--json"])
.await?;
local_plugin["pluginId"] = json!("sample@openai-api-curated");
local_plugin["marketplaceName"] = json!("openai-api-curated");
assert_eq!(
serde_json::from_str::<Value>(&listed)?,
json!({"installed": [], "available": [local_plugin]})
);
Ok(())
}

View File

@@ -1,184 +0,0 @@
use std::process::Command;
use anyhow::Context;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::ConfigLoadOptions;
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::config::load_config_toml_with_layer_stack;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
const CLOUD_MANAGED_PERMISSION_PROFILE_REQUIREMENTS: &str = r#"
default_permissions = "managed-cloud"
[allowed_permission_profiles]
managed-cloud = true
[permissions.managed-cloud]
extends = ":workspace"
[permissions.managed-cloud.network]
enabled = true
"#;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn sandbox_fetches_and_enforces_cloud_managed_permission_profile() -> Result<()> {
let requirements = json!({"enterprise_managed": [{
"id": "req-managed-cloud", "name": "Managed permissions",
"contents": CLOUD_MANAGED_PERMISSION_PROFILE_REQUIREMENTS,
}]});
let Some(codex_home) = run_cloud_sandbox(
&["-P", "managed-cloud", "--include-managed-config"],
json!({"requirements_toml": requirements}),
)
.await?
else {
return Ok(());
};
let cache: Value = serde_json::from_slice(&std::fs::read(
codex_home.path().join("cloud-config-bundle-cache.json"),
)?)?;
let payload = &cache["signed_payload"];
assert_eq!(payload["chatgpt_user_id"], "user-123");
assert_eq!(payload["account_id"], "workspace-123");
assert_eq!(payload["bundle"]["requirements_toml"], requirements);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn sandbox_loads_cloud_provider_for_cua_style_invocation() -> Result<()> {
run_cloud_sandbox(
&[
"-c",
"model_provider='cloud-provider'",
"-c",
"default_permissions='cua'",
"-c",
"permissions.cua={extends=':workspace',network={enabled=true}}",
"-c",
"approval_policy='never'",
],
json!({"config_toml": {"enterprise_managed": [{
"id": "cloud-provider", "name": "Cloud provider",
"contents": "[model_providers.cloud-provider]\nname = 'Cloud provider'\nwire_api = 'responses'",
}]}}),
)
.await?;
Ok(())
}
async fn run_cloud_sandbox(args: &[&str], bundle: Value) -> Result<Option<TempDir>> {
let server = MockServer::start().await;
let chatgpt_base_url = format!("{}/backend-api", server.uri());
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = \"file\"\nchatgpt_base_url = \"{chatgpt_base_url}\"\n",
),
)?;
let bootstrap_config = load_config_toml_with_layer_stack(
codex_home.path(),
Some(&AbsolutePathBuf::from_absolute_path(codex_home.path())?),
vec![
(
"cli_auth_credentials_store".to_string(),
toml::Value::String("file".to_string()),
),
(
"chatgpt_base_url".to_string(),
toml::Value::String(chatgpt_base_url.clone()),
),
],
ConfigLoadOptions::default(),
)
.await?;
if bootstrap_config.config_toml.cli_auth_credentials_store
!= Some(AuthCredentialsStoreMode::File)
|| bootstrap_config.config_toml.chatgpt_base_url.as_deref()
!= Some(chatgpt_base_url.as_str())
{
eprintln!(
"skipping cloud-managed sandbox subprocess: host-managed authentication or backend routing prevents isolated mock credentials"
);
return Ok(None);
}
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("workspace-123")
.chatgpt_account_id("workspace-123")
.chatgpt_user_id("user-123")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "workspace-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(bundle))
.expect(1)
.mount(&server)
.await;
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
let chatgpt_base_url_override = format!("chatgpt_base_url=\"{chatgpt_base_url}\"");
let output = Command::new(&codex)
.current_dir(codex_home.path())
.env("CODEX_HOME", codex_home.path())
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.env_remove("CODEX_ACCESS_TOKEN")
.env_remove("OPENAI_API_KEY")
.env_remove("OPENAI_FEDERATION_RULE_ID")
.env_remove("OPENAI_IDENTITY_TOKEN_FILE")
.env_remove("OPENAI_WORKLOAD_IDENTITY_CONTEXT")
.args(["-c", "cli_auth_credentials_store=\"file\""])
.args(["-c", chatgpt_base_url_override.as_str()])
.arg("sandbox")
.args(args)
.arg("--")
.arg(&codex)
.arg("--version")
.output()?;
let cloud_bundle_request_paths: Vec<_> = server
.received_requests()
.await
.context("failed to read mock cloud configuration requests")?
.into_iter()
.map(|request| request.url.path().to_string())
.collect();
let stderr = String::from_utf8_lossy(&output.stderr);
let nested_macos_sandbox_unavailable = cfg!(target_os = "macos")
&& output.status.code() == Some(71)
&& stderr.contains("sandbox-exec: sandbox_apply: Operation not permitted");
assert!(
output.status.success() || nested_macos_sandbox_unavailable,
"cloud-managed sandbox profile was not enforced: status={:?}; stdout={}; stderr={}; cloud bundle requests={cloud_bundle_request_paths:?}",
output.status.code(),
String::from_utf8_lossy(&output.stdout),
stderr,
);
if !nested_macos_sandbox_unavailable {
assert!(
String::from_utf8(output.stdout)?.starts_with("codex"),
"expected the sandboxed Codex version command to run",
);
}
server.verify().await;
Ok(Some(codex_home))
}

View File

@@ -223,14 +223,11 @@ trust_level = "trusted"
source.join(".codex/config.toml"),
"model = \"source-model\"\n",
)?;
app_test_support::write_chatgpt_auth(
codex_login::login_with_api_key(
&home,
app_test_support::ChatGptAuthFixture::new("test-token")
.account_id("workspace-123")
.chatgpt_account_id("workspace-123")
.chatgpt_user_id("user-123")
.plan_type("enterprise"),
"sk-test-token",
codex_config::types::AuthCredentialsStoreMode::File,
codex_login::AuthKeyringBackendKind::default(),
)?;
let program = codex_utils_cargo_bin::cargo_bin("codex")?;
// Keep cold Rosetta translation outside the timed startup assertions.