Rimossi i provider integrati OpenAI, Bedrock e GCP e ogni fallback a OpenAI (B)

Parte "sicurezza" della fase 3 di aKode (e39aae00), senza le funzioni di imeAI:

- via i provider integrati openai, amazon-bedrock, amazon-bedrock-runtime e gcp
  (crate model-provider: moduli amazon_bedrock, gcp, chatgpt_base_url; login Bedrock;
  onboarding Bedrock/GCP; richieste app-server di setup cloud);
- nessun URL predefinito verso api.openai.com / chatgpt.com: un provider senza
  base_url non viene mai contattato; senza model_provider configurato exec e TUI
  mostrano come scriverne uno in config.toml (NO_MODEL_PROVIDER_CONFIGURED_ERROR);
- via la skill openai-docs, la sample skill-installer (scaricava da github.com/openai/skills),
  request_plugin_install, AppsInstructions, URL predefiniti di realtime e updater;
- test di sicurezza adattati (provider "mock" al posto di quello integrato), non cancellati.

Restano fuori da questo commit (categoria F/D/E, non portate): chiave per provider nel
portachiavi, modelli da /models, unione dei messaggi di sistema, crate web-tools e
SearXNG, header @@ in apply_patch, modello ausiliario, tool function per apply_patch.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:31:29 +01:00
parent 22a79feba1
commit 2f8b6a3e16
481 changed files with 4319 additions and 25142 deletions

View File

@@ -1124,8 +1124,7 @@ enabled = true
}
#[tokio::test]
async fn debug_sandbox_honors_explicit_managed_permission_profile() -> anyhow::Result<()>
{
async fn debug_sandbox_honors_explicit_managed_permission_profile() -> anyhow::Result<()> {
let codex_home = TempDir::new()?;
let config = load_debug_sandbox_config_with_codex_home(
@@ -1159,17 +1158,14 @@ enabled = true
);
assert_eq!(
config.config_layer_stack.requirements_toml(),
&toml::from_str::<ConfigRequirementsToml>(
MANAGED_PERMISSION_PROFILE_REQUIREMENTS,
)?,
&toml::from_str::<ConfigRequirementsToml>(MANAGED_PERMISSION_PROFILE_REQUIREMENTS,)?,
);
Ok(())
}
#[tokio::test]
async fn debug_sandbox_ignores_managed_permission_profiles_by_default()
-> anyhow::Result<()> {
async fn debug_sandbox_ignores_managed_permission_profiles_by_default() -> anyhow::Result<()> {
let codex_home = TempDir::new()?;
let config = load_debug_sandbox_config_with_codex_home(

View File

@@ -1116,8 +1116,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 managed policy".to_string());
details.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()));
@@ -1327,7 +1326,7 @@ fn provider_specific_auth_check(
env_var_present: impl Fn(&str) -> bool,
) -> Option<DoctorCheck> {
details.push(format!(
"model provider requires OpenAI auth: {requires_openai_auth}"
"model provider uses the stored API key: {requires_openai_auth}"
));
if requires_openai_auth {
return None;
@@ -1367,7 +1366,7 @@ fn provider_specific_auth_check(
"auth.credentials",
"auth",
CheckStatus::Ok,
"OpenAI auth is not required for the active model provider",
"the stored API key is not used by the active model provider",
)
.details(details),
),
@@ -1378,8 +1377,6 @@ fn stored_auth_mode(auth: &codex_login::AuthDotJson) -> &'static str {
match stored_auth_mode_value(auth) {
Some(AuthMode::ApiKey) => "api_key",
Some(AuthMode::Headers) => "headers",
Some(AuthMode::BedrockApiKey) => "bedrock_api_key",
Some(AuthMode::BedrockAccessKeys) => "bedrock_access_keys",
None => "unsupported",
}
}
@@ -1389,11 +1386,7 @@ fn stored_auth_mode_value(auth: &AuthDotJson) -> Option<AuthMode> {
if let Some(mode) = auth.auth_mode {
return Some(mode);
}
if auth.bedrock_api_key.is_some() {
Some(AuthMode::BedrockApiKey)
} else if auth.bedrock_access_keys.is_some() {
Some(AuthMode::BedrockAccessKeys)
} else if auth.openai_api_key.is_some() {
if auth.openai_api_key.is_some() {
Some(AuthMode::ApiKey)
} else {
None
@@ -1426,22 +1419,6 @@ fn stored_auth_issues(
AuthMode::Headers => {
issues.push("header auth cannot be loaded from auth storage");
}
AuthMode::BedrockApiKey => {
if auth.bedrock_api_key.is_none() {
issues.push("Bedrock API key auth is missing a Bedrock API key");
}
}
AuthMode::BedrockAccessKeys => match auth.bedrock_access_keys.as_ref() {
Some(access_keys) => {
if access_keys.access_key_id.trim().is_empty() {
issues.push("Bedrock access key auth is missing an access key ID");
}
if access_keys.secret_access_key.trim().is_empty() {
issues.push("Bedrock access key auth is missing a secret access key");
}
}
None => issues.push("Bedrock access key auth is missing AWS access keys"),
},
}
issues
}
@@ -2493,8 +2470,6 @@ fn auth_mode_name(auth: &CodexAuth) -> &'static str {
match auth.auth_mode() {
AuthMode::ApiKey => "api_key",
AuthMode::Headers => "headers",
AuthMode::BedrockApiKey => "bedrock_api_key",
AuthMode::BedrockAccessKeys => "bedrock_access_keys",
}
}
@@ -2602,7 +2577,6 @@ fn provider_reachability_plan(config: &Config) -> ReachabilityPlan {
&config.model_provider.name,
config.model_provider.base_url.as_deref(),
query_params.as_ref(),
config.model_provider.is_amazon_bedrock(),
);
plan.http_client_factory = config.http_client_factory();
plan
@@ -2616,7 +2590,6 @@ fn default_reachability_plan() -> ReachabilityPlan {
"unknown",
/*provider_base_url*/ None,
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
)
}
@@ -2638,9 +2611,7 @@ fn provider_auth_reachability_mode_from_auth(
return ProviderAuthReachabilityMode::ApiKey;
}
match stored_auth.and_then(stored_auth_mode_value) {
Some(AuthMode::ApiKey | AuthMode::BedrockApiKey | AuthMode::BedrockAccessKeys) => {
ProviderAuthReachabilityMode::ApiKey
}
Some(AuthMode::ApiKey) => ProviderAuthReachabilityMode::ApiKey,
Some(AuthMode::Headers) | None => ProviderAuthReachabilityMode::NotRequired,
}
}
@@ -2651,7 +2622,6 @@ fn provider_reachability_plan_from_parts(
provider_name: &str,
provider_base_url: Option<&str>,
provider_query_params: Option<&HashMap<String, String>>,
is_amazon_bedrock: bool,
) -> ReachabilityPlan {
// aKode: only an explicitly configured base URL outside OpenAI/ChatGPT is probed. The
// implicit chatgpt.com and api.openai.com endpoints are never contacted.
@@ -2661,7 +2631,7 @@ fn provider_reachability_plan_from_parts(
label: format!("{provider_id} API"),
url: provider_url_for_path(base_url, "responses", provider_query_params),
required: true,
route_probe_url: should_probe_models_route(provider_name, base_url, is_amazon_bedrock)
route_probe_url: should_probe_models_route(provider_name, base_url)
.then(|| provider_url_for_path(base_url, "models", provider_query_params)),
})
.into_iter()
@@ -2673,8 +2643,8 @@ fn provider_reachability_plan_from_parts(
}
}
fn should_probe_models_route(provider_name: &str, base_url: &str, is_amazon_bedrock: bool) -> bool {
!is_amazon_bedrock && !is_azure_responses_provider(provider_name, Some(base_url))
fn should_probe_models_route(provider_name: &str, base_url: &str) -> bool {
!is_azure_responses_provider(provider_name, Some(base_url))
}
fn provider_url_for_path(
@@ -3656,7 +3626,7 @@ mod tests {
assert_eq!(check.status, CheckStatus::Ok);
assert_eq!(
check.summary,
"OpenAI auth is not required for the active model provider"
"the stored API key is not used by the active model provider"
);
}
@@ -3687,8 +3657,6 @@ mod tests {
let auth = AuthDotJson {
auth_mode: Some(AuthMode::ApiKey),
openai_api_key: None,
bedrock_api_key: None,
bedrock_access_keys: None,
};
assert_eq!(
@@ -3721,8 +3689,6 @@ mod tests {
let api_key_auth = AuthDotJson {
auth_mode: Some(AuthMode::ApiKey),
openai_api_key: Some("sk-test".to_string()),
bedrock_api_key: None,
bedrock_access_keys: None,
};
assert_eq!(
@@ -3792,7 +3758,6 @@ mod tests {
"azure",
Some("https://example.openai.azure.com/openai/v1"),
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
),
ReachabilityPlan {
description: "provider auth".to_string(),
@@ -3822,7 +3787,6 @@ mod tests {
"Custom",
Some("https://example.com/openai/v1/"),
Some(&query_params),
/*is_amazon_bedrock*/ false,
),
ReachabilityPlan {
description: description.to_string(),
@@ -3844,20 +3808,6 @@ mod tests {
}
}
#[test]
fn provider_reachability_skips_route_probe_for_bedrock() {
let plan = provider_reachability_plan_from_parts(
ProviderAuthReachabilityMode::NotRequired,
"amazon-bedrock",
"Amazon Bedrock",
Some("https://bedrock-runtime.us-east-1.amazonaws.com/openai/v1"),
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ true,
);
assert_eq!(plan.endpoints[0].route_probe_url, None);
}
#[test]
fn provider_reachability_never_infers_openai_endpoints() {
let plan = provider_reachability_plan_from_parts(
@@ -3866,7 +3816,6 @@ mod tests {
"OpenAI",
/*provider_base_url*/ None,
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
);
assert_eq!(plan.endpoints, Vec::new());
@@ -3880,7 +3829,6 @@ mod tests {
"OpenAI",
Some(base_url),
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
);
assert_eq!(plan.endpoints, Vec::new(), "{base_url}");
}
@@ -3929,7 +3877,6 @@ mod tests {
"OpenAI",
Some(&format!("http://{addr}/xxxx")),
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
);
let check = provider_reachability_check(plan).await;
@@ -3969,7 +3916,6 @@ mod tests {
"OpenAI",
Some(&format!("http://{addr}/v1")),
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
);
let check = provider_reachability_check(plan).await;

View File

@@ -85,8 +85,7 @@ pub(super) fn check(config: Option<&Config>) -> DoctorCheck {
{
let request_url = config
.and_then(|config| config.model_provider.base_url.as_deref())
.or_else(|| config.map(|config| config.chatgpt_base_url.as_str()))
.unwrap_or("https://chatgpt.com/backend-api/");
.unwrap_or("http://localhost/");
let configuration = match macos_system_proxy_configuration(request_url) {
MacosSystemProxyConfiguration::Automatic => "automatic (PAC)",
MacosSystemProxyConfiguration::Manual => "manual",

View File

@@ -22,7 +22,6 @@ async fn provider_reachability_rejects_proxy_authentication_challenges() {
"Local",
Some(&format!("{}/v1", proxy.uri())),
/*provider_query_params*/ None,
/*is_amazon_bedrock*/ false,
);
let check = provider_reachability_check(plan).await;

View File

@@ -1,6 +1,6 @@
pub mod local_config;
pub(crate) mod debug_sandbox;
mod exit_status;
pub mod local_config;
pub(crate) mod login;
use clap::Args;

View File

@@ -8,8 +8,6 @@
//! support can request from users.
use codex_core::config::Config;
use codex_core::config::edit::ConfigEdit;
use codex_core::config::edit::ConfigEditsBuilder;
use codex_login::login_with_api_key;
use codex_protocol::auth::AuthMode;
use codex_protocol::config_types::ForcedLoginMethod;
@@ -210,14 +208,6 @@ pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
AuthMode::Headers => {
unreachable!("header auth cannot be loaded from auth storage")
}
AuthMode::BedrockApiKey => {
eprintln!("Logged in using Amazon Bedrock API key");
std::process::exit(0);
}
AuthMode::BedrockAccessKeys => {
eprintln!("Logged in using Amazon Bedrock AWS access keys");
std::process::exit(0);
}
},
Ok(None) => {
eprintln!("Not logged in");
@@ -244,25 +234,7 @@ pub async fn run_logout(cli_config_overrides: CliConfigOverrides) -> ! {
}
};
let cleared_bedrock_config =
if let Some(paths) = ConfigEditsBuilder::bedrock_provider_config_paths_to_clear(&config) {
let edits = paths
.into_iter()
.map(|segments| ConfigEdit::ClearPath { segments });
if let Err(err) = ConfigEditsBuilder::for_config(&config)
.with_edits(edits)
.apply()
.await
{
eprintln!("Error clearing Amazon Bedrock configuration after logout: {err}");
std::process::exit(1);
}
true
} else {
false
};
if logged_out || cleared_bedrock_config {
if logged_out {
eprintln!("Successfully logged out");
} else {
eprintln!("Not logged in");

View File

@@ -487,7 +487,7 @@ struct LoginCommand {
#[arg(
long = "with-api-key",
help = "Read the API key from stdin (e.g. `printenv OPENAI_API_KEY | codex login --with-api-key`)"
help = "Read the API key from stdin (e.g. `printenv MY_KEY | codex login --with-api-key`)"
)]
with_api_key: bool,
@@ -1515,7 +1515,7 @@ async fn dispatch_cli(
None => {
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`."
"The --api-key flag is no longer supported. Pipe the key instead, e.g. `printenv MY_KEY | codex login --with-api-key`."
);
std::process::exit(1);
} else if login_cli.with_api_key {
@@ -1523,7 +1523,7 @@ async fn dispatch_cli(
run_login_with_api_key(login_cli.config_overrides, api_key).await;
} else {
eprintln!(
"Only API key login is supported. Pipe the key on stdin, e.g. `printenv OPENAI_API_KEY | codex login --with-api-key`."
"Only API key login is supported. Pipe the key on stdin, e.g. `printenv MY_KEY | codex login --with-api-key`."
);
std::process::exit(1);
}

View File

@@ -193,7 +193,11 @@ fn packaged_daemon_launch(action: &str, initial: InitialDaemon) -> Result<()> {
assert_eq!(standalone.join("current").canonicalize()?, cli_selection);
}
if action == "bootstrap" {
assert_eq!(output["autoUpdateEnabled"], false);
// Only stable release versions follow automatic updates; local builds versioned
// 0.0.0 do not. aKode builds carry a release version (0.1.0).
let stable_build =
env!("CARGO_PKG_VERSION") != "0.0.0" && !env!("CARGO_PKG_VERSION").contains(['-', '+']);
assert_eq!(output["autoUpdateEnabled"], stable_build);
}
Ok(())
}

View File

@@ -78,11 +78,6 @@ async fn daemon_exclusion_survives_fork_picker() -> Result<()> {
daemon_startup("fork").await
}
#[tokio::test]
async fn daemon_auto_start_preserves_bedrock_onboarding() -> Result<()> {
daemon_startup("bedrock").await
}
#[tokio::test]
#[cfg(windows)]
async fn elevated_local_tui_uses_embedded_without_starting_daemon() -> Result<()> {
@@ -146,12 +141,6 @@ async fn restrictive_launcher_uses_embedded_if_daemon_cannot_start() -> Result<(
daemon_startup("restrictive-job").await
}
#[tokio::test]
#[cfg(unix)]
async fn bedrock_onboarding_discovers_credentials_on_the_running_daemon() -> Result<()> {
daemon_startup("bedrock-running").await
}
async fn daemon_startup(command: &str) -> Result<()> {
#[cfg(windows)]
let elevated = codex_app_server_daemon::is_elevated()?;
@@ -177,17 +166,24 @@ async fn daemon_startup(command: &str) -> Result<()> {
"failed to prepare CLI test executable"
);
let bedrock_onboarding = matches!(command, "bedrock" | "bedrock-running");
// aKode has no built-in catalog for providers without a catalog URL; keep the bundled one.
let catalog = home.path().join("test-models.json");
fs::write(&catalog, include_str!("../../models-manager/models.json"))?;
fs::write(
home.path().join("config.toml"),
format!(
"model = \"gpt-5.6-terra\"\n\
model_provider = \"mock\"\n\
model_catalog_json = {}\n\
cli_auth_credentials_store = \"file\"\n\
suppress_unstable_features_warning = true\n\
windows.sandbox = \"unelevated\"\n\
tui.disable_paste_burst = true\n\
{}\n\
notice.model_migrations.\"gpt-5.6-terra\" = \"gpt-6-sol\"\n\
[model_providers.mock]\nname = \"mock\"\nbase_url = \"http://127.0.0.1:9/v1\"\nrequires_openai_auth = true\n\
[projects.{}]\ntrust_level = \"{}\"\n",
serde_json::to_string(&catalog.display().to_string())?,
if command == "discovered" {
"tui.status_line=[\"model\",\"thread-id\",\"thread-name\"]\nfeatures.daemon_auto_start=false"
} else if bedrock_onboarding {
@@ -380,7 +376,7 @@ async fn daemon_startup(command: &str) -> Result<()> {
"session_id": thread_id, "id": thread_id,
"timestamp": "2025-01-05T12:00:00Z", "cwd": workspace_path,
"originator": "codex", "cli_version": "0.0.0",
"source": "cli", "model_provider": "openai"
"source": "cli", "model_provider": "mock"
}
});
let message = serde_json::json!({

View File

@@ -25,7 +25,7 @@ fn debug_models_bundled_prints_json() -> Result<()> {
}
#[test]
fn debug_models_default_prints_json_without_auth() -> Result<()> {
fn debug_models_default_prints_empty_json_without_provider() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd.args(["debug", "models"]).output()?;
@@ -34,7 +34,8 @@ fn debug_models_default_prints_json_without_auth() -> Result<()> {
let stdout = String::from_utf8(output.stdout)?;
let value: serde_json::Value = serde_json::from_str(&stdout)?;
assert!(value["models"].is_array());
assert!(!value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
// aKode has no default provider and no built-in catalog: nothing to list, no network.
assert!(value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
Ok(())
}

View File

@@ -121,7 +121,9 @@ async fn network_only_reports_recoverable_config_warnings_and_effective_config()
let config = std::fs::read_to_string(&config_path)?;
std::fs::write(
config_path,
format!("{config}\n[otel.span_attributes]\n\"\" = \"missing-key\"\n"),
// OTEL exporters were removed (otel settings are ignored without warnings); use another
// recoverable, warning-only setting.
format!("{config}\n[features.guardianv2]\nasync_classifier_mode = \"conversation\"\n"),
)?;
let output = local_command(&home)?
.args(["doctor", "--network-only", "--json"])
@@ -137,8 +139,8 @@ async fn network_only_reports_recoverable_config_warnings_and_effective_config()
let startup_warning = std::iter::once(warnings)
.chain(warnings.as_array().into_iter().flatten())
.filter_map(Value::as_str)
.find(|warning| warning.starts_with("Ignoring invalid `otel.span_attributes` config"))
.context("missing recoverable OTEL config warning")?;
.find(|warning| warning.starts_with("`[features.guardianv2].async_classifier_mode`"))
.context("missing recoverable config warning")?;
let check_statuses = report["checks"]
.as_object()
.unwrap()
@@ -170,7 +172,7 @@ async fn network_only_reports_recoverable_config_warnings_and_effective_config()
"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",
"startupWarning": "`[features.guardianv2].async_classifier_mode` is deprecated and ignored. Async classification always uses conversations; remove this setting from config.toml or profile configuration files.",
},
})
);

View File

@@ -371,8 +371,10 @@ fn doctor_reports_only_safe_config_error_metadata() -> Result<()> {
"model_provider = \"doctor-test-credential\"",
),
),
// A type error in a known key reports its location (file/line/column) but never
// the offending value.
(
"doctor_config_invalid_data",
"doctor_config_invalid_type",
user_config_file.clone(),
original.replace(
"wire_api = \"responses\"",

View File

@@ -47,7 +47,7 @@ fn mcp_list_reports_invalid_keybinding_reason() -> Result<()> {
.get_output()
.stderr
.clone();
let output = String::from_utf8(output)?;
let output = normalize_config_location(&String::from_utf8(output)?);
insta::allow_duplicates! {
insta::assert_snapshot!(output);
}
@@ -304,3 +304,23 @@ fn no_daemon_rejects_queue_and_explicit_remote_targets() -> Result<()> {
}
Ok(())
}
/// Replaces `<temp home>/config.toml:<line>:<column>` with a stable placeholder.
fn normalize_config_location(output: &str) -> String {
output
.lines()
.map(|line| match line.find("/config.toml:") {
Some(index) => {
let start = line[..index].rfind(' ').map_or(0, |space| space + 1);
let rest = &line[index + "/config.toml:".len()..];
let after_location = rest.splitn(3, ':').nth(2).unwrap_or_default();
format!(
"{}[CODEX_HOME]/config.toml:<line>:<column>:{after_location}",
&line[..start]
)
}
None => line.to_string(),
})
.collect::<Vec<_>>()
.join("\n")
}

View File

@@ -1,9 +1,6 @@
use std::path::Path;
use anyhow::Result;
use codex_config::types::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::login_with_bedrock_access_keys;
use predicates::str::contains;
use pretty_assertions::assert_eq;
use serde_json::Value;
@@ -169,79 +166,68 @@ fn legacy_chatgpt_auth_is_reported_as_not_logged_in_and_logout_removes_it() -> R
}
#[test]
fn logout_clears_only_the_selected_bedrock_provider() -> Result<()> {
for (model_provider_id, managed_bedrock_auth, model) in [
("amazon-bedrock", true, "openai.gpt-5.6-sol"),
("amazon-bedrock-runtime", true, "global.openai.gpt-5.6-sol"),
("openai", true, "gpt-5.6-sol"),
("amazon-bedrock", false, "gpt-5.6-sol"),
("amazon-bedrock-runtime", false, "us.openai.gpt-5.6-sol"),
("openai", false, "gpt-5.6-sol"),
] {
let codex_home = TempDir::new()?;
let config_path = codex_home.path().join("config.toml");
std::fs::write(
&config_path,
format!(
"cli_auth_credentials_store = \"file\"\n\
model_provider = \"{model_provider_id}\"\n\
model = \"{model}\"\n\
model_reasoning_effort = \"high\"\n\
[model_providers.amazon-bedrock]\n\
base_url = \"https://mantle.example.com/v1\"\n\
[model_providers.amazon-bedrock.aws]\n\
profile = \"mantle-profile\"\n\
region = \"us-west-2\"\n\
auth_refresh = {{ command = \"aws\", args = [\"sso\", \"login\"] }}\n\
[model_providers.amazon-bedrock-runtime]\n\
base_url = \"https://runtime.example.com/v1\"\n\
[model_providers.amazon-bedrock-runtime.aws]\n\
profile = \"runtime-profile\"\n\
region = \"us-east-1\"\n\
auth_refresh = {{ command = \"aws\", args = [\"login\"] }}\n"
),
)?;
if managed_bedrock_auth {
login_with_bedrock_access_keys(
codex_home.path(),
"managed-access-key-id",
"managed-secret-access-key",
Some("managed-session-token"),
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?;
}
let mut expected_config: toml::Value =
toml::from_str(&std::fs::read_to_string(&config_path)?)?;
if model_provider_id != "openai" {
let expected_root = expected_config
.as_table_mut()
.expect("config should be a table");
expected_root.remove("model_provider");
expected_root.remove("model");
expected_root["model_providers"][model_provider_id]
.as_table_mut()
.expect("selected Bedrock provider should be a table")
.remove("aws");
}
let expected_message = if managed_bedrock_auth || model_provider_id != "openai" {
"Successfully logged out"
} else {
"Not logged in"
};
fn provider_api_key_login_uses_private_file_store_and_never_prints_the_key() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
"provider_api_key_store = \"file\"\n\
model_provider = \"imeai\"\n\
[model_providers.imeai]\n\
name = \"imeAI\"\n\
base_url = \"http://127.0.0.1:9/v1\"\n\
api_key = \"keyring\"\n",
)?;
let secret = "sk-provider-secret-0123456789";
codex_command(codex_home.path())?
.env("AWS_ACCESS_KEY_ID", "environment-access-key-id")
.env("AWS_SECRET_ACCESS_KEY", "environment-secret-access-key")
.args(["logout"])
.assert()
.success()
.stderr(contains(expected_message));
let login = codex_command(codex_home.path())?
.args(["login", "--provider", "imeai", "--with-api-key"])
.write_stdin(format!("{secret}\n"))
.assert()
.success();
let stderr = String::from_utf8_lossy(&login.get_output().stderr).to_string();
assert!(
stderr.contains("API key for `imeai` saved in file"),
"{stderr}"
);
assert!(!stderr.contains(secret), "{stderr}");
assert!(!codex_home.path().join("auth.json").exists());
let actual_config: toml::Value = toml::from_str(&std::fs::read_to_string(&config_path)?)?;
assert_eq!(actual_config, expected_config);
let path = codex_home.path().join("provider_api_keys.json");
let stored: Value = serde_json::from_str(&std::fs::read_to_string(&path)?)?;
assert_eq!(stored, json!({ "imeai": secret }));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&path)?.permissions().mode() & 0o777,
0o600
);
}
// The shared stored key is untouched.
assert!(!codex_home.path().join("auth.json").exists());
let status = codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.success();
let stderr = String::from_utf8_lossy(&status.get_output().stderr).to_string();
assert!(
stderr.contains("Provider `imeai`: API key stored in file"),
"{stderr}"
);
assert!(!stderr.contains(secret), "{stderr}");
codex_command(codex_home.path())?
.args(["logout", "--provider", "imeai"])
.assert()
.success()
.stderr(contains("Removed the stored API key for `imeai`"));
assert!(!path.exists());
codex_command(codex_home.path())?
.args(["login", "status"])
.assert()
.failure()
.stderr(contains(
"Provider `imeai`: no API key stored (codex login --provider imeai --with-api-key)",
));
Ok(())
}

View File

@@ -2,9 +2,11 @@
source: cli/tests/features.rs
expression: output
---
Error: failed to load bootstrap configuration
Error: failed to load configuration
Caused by:
unknown key `backslash` in keybinding `backslash`. Use a printable character (for example `a`), function keys (`f1`-`f24`), or one of: enter, tab, backspace, esc, delete, arrows, home/end, page-up/page-down, space, minus.
See the Codex keymap documentation for supported actions and examples.
in `tui.keymap.editor.insert_newline`
0: [CODEX_HOME]/config.toml:<line>:<column>: unknown key `backslash` in keybinding `backslash`. Use a printable character (for example `a`), function keys (`f1`-`f24`), or one of: enter, tab, backspace, esc, delete, arrows, home/end, page-up/page-down, space, minus.
See the Codex keymap documentation for supported actions and examples.
1: unknown key `backslash` in keybinding `backslash`. Use a printable character (for example `a`), function keys (`f1`-`f24`), or one of: enter, tab, backspace, esc, delete, arrows, home/end, page-up/page-down, space, minus.
See the Codex keymap documentation for supported actions and examples.
in `tui.keymap.editor.insert_newline`

View File

@@ -312,7 +312,8 @@ trust_level = "trusted"
if auth_failure {
fs::write(
source.join(".codex/config.toml"),
"forced_login_method = \"api\"\n",
// The stored API key satisfies `api`; require a login method it cannot satisfy.
"forced_login_method = \"chatgpt\"\n",
)?;
git(
&source,
@@ -330,16 +331,6 @@ trust_level = "trusted"
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
.mount(&server)
.await;
Mock::given(wiremock::matchers::method("GET"))
.and(wiremock::matchers::path(
"/source/backend-api/wham/config/bundle",
))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"config_toml": { "enterprise_managed": [{ "id": "test", "name": "test",
"contents": "developer_instructions = \"managed cloud instructions\"" }] }
})))
.mount(&server)
.await;
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let response = app_test_support::create_final_assistant_message_sse_response("done")?;
let observed_source = source.clone();
@@ -456,7 +447,7 @@ trust_level = "trusted"
let bytes = bytes.context("TUI exited before model request")?;
let text = String::from_utf8_lossy(&bytes);
output.push_str(&text);
if auth_failure && output.contains("API key login is required") && output.contains("Do not use --force.") {
if auth_failure && output.contains("API key login is not permitted") && output.contains("Do not use --force.") {
anyhow::bail!("observed required API login rejection");
}
let replies = queries.feed(&bytes);
@@ -470,7 +461,10 @@ trust_level = "trusted"
let exit =
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), spawned.exit_rx).await??;
assert_ne!(exit, 0);
assert!(output.contains("API key login is required"), "{output}");
assert!(
output.contains("API key login is not permitted"),
"{output}"
);
assert!(!home.join("auth.json").exists());
assert!(output.contains("The checkout was kept"), "{output}");
continue;
@@ -646,7 +640,7 @@ trust_level = "trusted"
);
}
assert_eq!(body["model"], "destination-model");
assert!(context.contains("managed cloud instructions"), "{context}");
// Managed cloud configuration (ChatGPT config bundles) was removed in aKode.
if previous.is_empty() {
// A legacy summary still says launcher A, but persisted turns use checkout B.
let sqlite = codex_state::SqliteConfig::new_for_testing(
@@ -659,26 +653,9 @@ trust_level = "trusted"
.execute(&db)
.await?;
db.close().await;
// B inherits trust from its primary repository; no exact trusted entry masks cloud distrust.
let home_config = home.join("config.toml");
let launcher_config = fs::read_to_string(&home_config)?;
fs::write(
&home_config,
launcher_config.replace(
"cli_auth_credentials_store = \"file\"",
"cli_auth_credentials_store = \"ephemeral\"",
),
)?;
let cache = home.join("cloud-config-bundle-cache.json");
if cache.exists() {
fs::remove_file(&cache)?;
}
let request_count = server.received_requests().await.context("requests")?.len();
Mock::given(wiremock::matchers::path("/source/backend-api/wham/config/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"config_toml": {"enterprise_managed": [{"id":"distrust", "name":"distrust",
"contents": format!("[projects.{}]\ntrust_level = \"untrusted\"\n", serde_json::to_string(&codex_config::loader::project_trust_key(Path::new(&checkout)))?)}]}
}))).with_priority(/*priority*/ 1).mount(&server).await;
// B inherits trust from its primary repository; an explicit distrust entry for B
// (formerly delivered by a managed cloud bundle, now a config override) still
// rejects the fork before any checkout is created.
let before = git(&source, &["worktree", "list", "--porcelain"])?;
rejected_start(
&program,
@@ -687,6 +664,13 @@ trust_level = "trusted"
"--enable".into(),
"worktrees".into(),
"--no-alt-screen".into(),
"-c".into(),
format!(
"projects={{{}={{trust_level=\"untrusted\"}}}}",
serde_json::to_string(&codex_config::loader::project_trust_key(
Path::new(&checkout)
))?
),
"fork".into(),
next_owner.clone(),
],
@@ -695,70 +679,7 @@ trust_level = "trusted"
"cannot create a checkout from an explicitly untrusted source",
)
.await?;
assert!(
server
.received_requests()
.await
.context("requests")?
.iter()
.skip(request_count)
.any(|request| request.url.path() == "/source/backend-api/wham/config/bundle")
);
assert_eq!(git(&source, &["worktree", "list", "--porcelain"])?, before);
server.reset().await;
if cache.exists() {
fs::remove_file(&cache)?;
}
let count = server.received_requests().await.context("requests")?.len();
Mock::given(wiremock::matchers::path("/source/backend-api/wham/config/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"config_toml": {"enterprise_managed": [{"id":"distrust-source", "name":"distrust-source",
"contents": format!("[projects.{}]\ntrust_level = \"untrusted\"\n", serde_json::to_string(&codex_config::loader::project_trust_key(&source.join(".codex")))?)}]}
}))).mount(&server).await;
let output = rejected_start(
&program,
&[
"--worktree".into(),
"--enable".into(),
"worktrees".into(),
"--no-alt-screen".into(),
"--cd".into(),
source.join(".codex").display().to_string(),
],
&launcher,
&env,
"cannot create a checkout from an explicitly untrusted source",
)
.await?;
let requests = server.received_requests().await.context("requests")?;
let paths = requests
.iter()
.skip(count)
.map(|r| r.url.path())
.collect::<Vec<_>>();
assert!(paths.contains(&"/source/backend-api/wham/config/bundle"));
assert!(!paths.contains(&"/v1/responses"));
let after = git(&source, &["worktree", "list", "--porcelain"])?;
let retained = after
.lines()
.filter_map(|line| line.strip_prefix("worktree "))
.find(|path| {
!before
.lines()
.any(|line| line.strip_prefix("worktree ") == Some(*path))
})
.context("retained untrusted checkout")?;
assert!(output.contains("The checkout was kept"), "{output}");
let metadata = git(
Path::new(retained),
&["rev-parse", "--git-path", "codex-thread.json"],
)?;
assert!(!Path::new(retained).join(metadata).exists());
previous.push(retained.to_owned());
fs::write(&home_config, launcher_config)?;
if cache.exists() {
fs::remove_file(&cache)?;
}
}
previous.push(checkout);
owner = Some(next_owner);