WIP fase 2b-2: rimosso login ChatGPT/OAuth/device code, agent/workload identity, backend-client; resta solo chiave API (test non tutti verdi)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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;
|
||||
@@ -1235,7 +1233,6 @@ fn auth_check(config: &Config) -> DoctorCheck {
|
||||
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))
|
||||
@@ -1264,11 +1261,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 +1288,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 +1308,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 +1379,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 +1408,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 +1426,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 +2305,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 +2495,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 +2567,6 @@ struct ReachabilityEndpoint {
|
||||
enum ProviderAuthReachabilityMode {
|
||||
NotRequired,
|
||||
ApiKey,
|
||||
Chatgpt,
|
||||
}
|
||||
|
||||
impl ProviderAuthReachabilityMode {
|
||||
@@ -2649,7 +2574,6 @@ impl ProviderAuthReachabilityMode {
|
||||
match self {
|
||||
Self::NotRequired => "provider auth",
|
||||
Self::ApiKey => "API key auth",
|
||||
Self::Chatgpt => "ChatGPT auth",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2716,21 +2640,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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3776,10 +3690,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 +3702,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 +3749,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 +3760,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 +3770,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 +3780,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 +3816,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 +3878,7 @@ mod tests {
|
||||
"https://chatgpt.com/backend-api/",
|
||||
] {
|
||||
let plan = provider_reachability_plan_from_parts(
|
||||
ProviderAuthReachabilityMode::Chatgpt,
|
||||
ProviderAuthReachabilityMode::NotRequired,
|
||||
"openai",
|
||||
"OpenAI",
|
||||
Some(base_url),
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -8,13 +8,9 @@ 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::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;
|
||||
@@ -498,12 +494,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 +504,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>,
|
||||
}
|
||||
@@ -1543,19 +1521,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 +1529,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2038,21 +2004,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 +4109,6 @@ enabled = true
|
||||
"--name",
|
||||
"forwarded",
|
||||
"--strict-config",
|
||||
"--use-agent-identity-auth",
|
||||
])
|
||||
.expect("parse forward");
|
||||
assert!(cli.remote.remote.is_none());
|
||||
|
||||
@@ -638,8 +638,9 @@ async fn run_logout(config: &Config, logout_args: LogoutArgs) -> Result<()> {
|
||||
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")?;
|
||||
let scope = ema_auth_scope(auth.as_ref()).context(
|
||||
"Enterprise MCP authorization requires an account sign-in, which this build does not support",
|
||||
)?;
|
||||
// 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
|
||||
@@ -710,8 +711,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;
|
||||
|
||||
@@ -8,7 +8,6 @@ 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;
|
||||
@@ -147,7 +146,7 @@ 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 context = load_plugin_command_context(overrides).await?;
|
||||
let outcome = if selection.marketplace_name == REMOTE_GLOBAL_MARKETPLACE_NAME {
|
||||
let mut listing = fetch_remote_marketplaces(
|
||||
&context,
|
||||
@@ -248,7 +247,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 context = load_plugin_command_context(overrides).await?;
|
||||
let remote_listing = fetch_remote_marketplaces(
|
||||
&context,
|
||||
args.marketplace_name.as_deref(),
|
||||
@@ -689,7 +688,7 @@ 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!(
|
||||
@@ -767,7 +766,6 @@ struct PluginCommandContext {
|
||||
|
||||
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)
|
||||
@@ -776,14 +774,7 @@ async fn load_plugin_command_context(
|
||||
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, Arc::clone(&auth_manager)));
|
||||
Ok(PluginCommandContext {
|
||||
codex_home: codex_home.to_path_buf(),
|
||||
plugins_input,
|
||||
@@ -861,10 +852,10 @@ async fn fetch_remote_marketplaces(
|
||||
return Ok(RemoteMarketplaceListing::default());
|
||||
}
|
||||
let auth = context.auth.as_ref();
|
||||
if !auth.is_some_and(CodexAuth::uses_codex_backend) {
|
||||
if !codex_core_plugins::apps_route_available(auth.map(CodexAuth::auth_mode)) {
|
||||
ensure!(
|
||||
marketplace_name.is_none(),
|
||||
"chatgpt authentication required for remote plugin catalog"
|
||||
"remote plugin catalogs are not available"
|
||||
);
|
||||
return Ok(RemoteMarketplaceListing::default());
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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()?;
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
|
||||
@@ -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(®istry)
|
||||
.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(®istry)
|
||||
.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",
|
||||
®istry.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(())
|
||||
}
|
||||
|
||||
@@ -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(®istry)
|
||||
.await;
|
||||
Mock::given(path("/cloud/environment/env/register"))
|
||||
.and(header("authorization", "Bearer old-token"))
|
||||
.respond_with(ResponseTemplate::new(401))
|
||||
.expect(1)
|
||||
.mount(®istry)
|
||||
.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(®istry)
|
||||
.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(®istry)
|
||||
.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",
|
||||
®istry.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(())
|
||||
}
|
||||
@@ -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()?;
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user