diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 97697beb..3f3e35b3 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -3225,7 +3225,6 @@ dependencies = [ "flate2", "futures", "http 1.4.0", - "libc", "pretty_assertions", "regex", "serde", @@ -3244,7 +3243,6 @@ dependencies = [ "url", "uuid", "wiremock", - "zip", ] [[package]] diff --git a/codex-rs/analytics/src/client_runtime_auth_tests.rs b/codex-rs/analytics/src/client_runtime_auth_tests.rs index cf2f25f8..86857adc 100644 --- a/codex-rs/analytics/src/client_runtime_auth_tests.rs +++ b/codex-rs/analytics/src/client_runtime_auth_tests.rs @@ -122,13 +122,14 @@ async fn runtime_delivery_signs_each_batch_and_strips_cross_origin_auth() { } } +// aKode: the analytics client never creates a delivery queue, so nothing is sent. #[tokio::test] -async fn custom_analytics_destination_does_not_initialize_runtime_auth() { +async fn analytics_client_never_sends_events() { for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { let server = MockServer::start().await; Mock::given(path("/codex/analytics-events/events")) .respond_with(ResponseTemplate::new(200)) - .expect(1) + .expect(0) .mount(&server) .await; let client = AnalyticsEventsClient::new_with_runtime( @@ -139,10 +140,7 @@ async fn custom_analytics_destination_does_not_initialize_runtime_auth() { /*api_key_headers*/ Default::default(), ); emit(&client, "custom").await; - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 1); - assert_eq!(requests[0].headers["authorization"], "Bearer key-a"); - assert!(!requests[0].headers.contains_key("x-openai-agent-assertion")); + assert!(server.received_requests().await.unwrap().is_empty()); server.verify().await; } } diff --git a/codex-rs/app-server/src/request_processors/account_processor.rs b/codex-rs/app-server/src/request_processors/account_processor.rs index 38bdda42..6795600b 100644 --- a/codex-rs/app-server/src/request_processors/account_processor.rs +++ b/codex-rs/app-server/src/request_processors/account_processor.rs @@ -309,12 +309,7 @@ impl AccountRequestProcessor { refresh_config_manager.clone(), ); }); - thread_manager - .plugins_manager() - .maybe_start_curated_repo_sync_for_config( - &plugins_config, - Some(Arc::clone(&on_effective_plugins_changed)), - ); + // aKode: no curated marketplace sync after account changes. if let Err(err) = runtime_auth { warn!("failed to initialize runtime auth for remote plugin refresh: {err}"); return; diff --git a/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs b/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs index 1f395396..15ca3986 100644 --- a/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs +++ b/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs @@ -539,8 +539,9 @@ fn assert_dynamic_status(response: &ListMcpServerStatusResponse, process_label: } #[tokio::test] -async fn oauth_login_automatically_selects_callback_specific_cimd_without_metadata_issuer() --> Result<()> { +// aKode: CIMD (a ChatGPT-hosted client metadata document) is never offered; automatic +// registration uses DCR even when the server advertises CIMD. +async fn oauth_login_uses_dcr_even_when_cimd_is_advertised() -> Result<()> { let responses_server = create_mock_responses_server_sequence_unchecked(Vec::new()).await; let listener = TcpListener::bind("127.0.0.1:0").await?; let base_url = format!("http://{}", listener.local_addr()?); @@ -596,11 +597,16 @@ async fn oauth_login_automatically_selects_callback_specific_cimd_without_metada ) .route( "/register", - post(move || { + post(move |body: Bytes| { let registrations = Arc::clone(®istration_count); async move { registrations.fetch_add(1, Ordering::SeqCst); - Json(json!({"client_id": "unexpected-dcr-client"})) + let registration: serde_json::Value = + serde_json::from_slice(&body).unwrap_or_default(); + Json(json!({ + "client_id": "dcr-client", + "redirect_uris": registration["redirect_uris"], + })) } }), ) @@ -660,14 +666,15 @@ async fn oauth_login_automatically_selects_callback_specific_cimd_without_metada let callback_id = callback_url .path() .strip_prefix("/callback/") - .expect("issuerless CIMD should use a resource-specific callback"); - let client_id = format!("https://chatgpt.com/oauth/codex/{callback_id}/client.json"); + .expect("issuerless servers should use a resource-specific callback"); + assert!(!callback_id.is_empty()); + let client_id = "dcr-client".to_string(); assert_eq!(parameters.get("client_id"), Some(&client_id)); assert_eq!( parameters.get("code_challenge_method").map(String::as_str), Some("S256") ); - assert_eq!(registrations.load(Ordering::SeqCst), 0); + assert_eq!(registrations.load(Ordering::SeqCst), 1); callback_url .query_pairs_mut() @@ -682,7 +689,7 @@ async fn oauth_login_automatically_selects_callback_specific_cimd_without_metada let (token_request, token_authorization) = timeout(DEFAULT_READ_TIMEOUT, token_request_rx.recv()) .await? - .expect("CIMD authorization should exchange its authorization code"); + .expect("DCR authorization should exchange its authorization code"); let token_parameters = url::form_urlencoded::parse(token_request.as_bytes()) .into_owned() .collect::>(); @@ -714,7 +721,7 @@ async fn oauth_login_automatically_selects_callback_specific_cimd_without_metada error: None, } ); - assert_eq!(registrations.load(Ordering::SeqCst), 0); + assert_eq!(registrations.load(Ordering::SeqCst), 1); let request_id = app_server .send_raw_request("config/mcpServer/reload", /*params*/ None) @@ -742,7 +749,7 @@ async fn oauth_login_automatically_selects_callback_specific_cimd_without_metada .expect("MCP startup should use the access token"), "Bearer cimd-access-token" ); - assert_eq!(registrations.load(Ordering::SeqCst), 0); + assert_eq!(registrations.load(Ordering::SeqCst), 1); oauth_server_handle.abort(); let _ = oauth_server_handle.await; diff --git a/codex-rs/core-plugins/Cargo.toml b/codex-rs/core-plugins/Cargo.toml index 2c190c07..747dec9b 100644 --- a/codex-rs/core-plugins/Cargo.toml +++ b/codex-rs/core-plugins/Cargo.toml @@ -59,13 +59,11 @@ toml = { workspace = true } tracing = { workspace = true } url = { workspace = true } uuid = { workspace = true, features = ["v4"] } -zip = { workspace = true } [dev-dependencies] base64 = { workspace = true } codex-exec-server-test-support = { workspace = true } codex-utils-cargo-bin = { workspace = true } -libc = { workspace = true } pretty_assertions = { workspace = true } tempfile = { workspace = true } tokio = { workspace = true, features = ["test-util"] } diff --git a/codex-rs/core-plugins/src/manager.rs b/codex-rs/core-plugins/src/manager.rs index a0845699..d25ef052 100644 --- a/codex-rs/core-plugins/src/manager.rs +++ b/codex-rs/core-plugins/src/manager.rs @@ -30,7 +30,6 @@ use crate::loaded_cache_metrics; use crate::loaded_cache_metrics::RequestOutcome; use crate::loader::PluginHookLoadOutcome; use crate::loader::TargetCuratedMarketplace; -use crate::loader::configured_curated_plugin_ids_from_codex_home; use crate::loader::curated_plugin_cache_version; use crate::loader::load_plugin_apps_from_manifest; use crate::loader::load_plugin_hooks; @@ -42,7 +41,6 @@ use crate::loader::log_plugin_load_errors; use crate::loader::materialize_marketplace_plugin_source; use crate::loader::plugin_capability_summary_from_root; use crate::loader::plugin_is_eligible_for_target_marketplace; -use crate::loader::refresh_curated_plugin_cache; use crate::loader::refresh_non_curated_plugin_cache_detailed; use crate::loader::refresh_non_curated_plugin_cache_force_reinstall_detailed; use crate::loader::remote_installed_plugins_to_config; @@ -86,11 +84,9 @@ use crate::remote_plugin_id_resolver::RemoteInstalledPluginsSnapshot; use crate::remote_plugin_id_resolver::RemotePluginIdResolver; use crate::remote_plugin_id_resolver::persisted_remote_plugin_id_for_installation; use crate::skill_snapshots::new_plugin_skill_snapshots; -use crate::startup_sync::OPENAI_PLUGINS_GIT_URL; use crate::startup_sync::curated_plugins_api_marketplace_path; use crate::startup_sync::curated_plugins_repo_path; use crate::startup_sync::read_curated_plugins_sha; -use crate::startup_sync::sync_openai_plugins_repo; use crate::store::PluginInstallResult as StorePluginInstallResult; use crate::store::PluginStore; use crate::store::PluginStoreError; @@ -146,8 +142,6 @@ use std::sync::Arc; use std::sync::Mutex; use std::sync::OnceLock; use std::sync::RwLock; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering; use std::time::Duration; use std::time::Instant; use tokio::sync::OnceCell; @@ -158,7 +152,6 @@ use tokio::sync::watch; use tracing::instrument; use tracing::warn; -static CURATED_REPO_SYNC_STARTED: AtomicBool = AtomicBool::new(false); const FEATURED_PLUGIN_IDS_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(60 * 60 * 3); const REMOTE_INSTALLED_PLUGIN_SYNC_WAIT_TIMEOUT: Duration = Duration::from_secs(120); @@ -828,25 +821,6 @@ impl PluginsManager { config.remote_plugin_enabled && self.auth_mode().is_some_and(AuthMode::uses_codex_backend) } - /// Starts the local curated marketplace sync when the remote catalog is unavailable. - pub fn maybe_start_curated_repo_sync_for_config( - self: &Arc, - config: &PluginsConfigInput, - on_effective_plugins_changed: Option, - ) { - if config.plugins_enabled - && !self.remote_global_catalog_active(config) - && MarketplacePolicy::from_requirements(config.config_layer_stack.requirements()) - .validate_git_source(OPENAI_PLUGINS_GIT_URL, /*ref_name*/ None) - .is_ok() - { - self.start_curated_repo_sync( - config.http_client_factory.clone(), - on_effective_plugins_changed, - ); - } - } - pub fn set_analytics_events_client(&self, analytics_events_client: AnalyticsEventsClient) { let mut stored_client = match self.analytics_events_client.write() { Ok(client_guard) => client_guard, @@ -2947,10 +2921,7 @@ impl PluginsManager { upgrade_warnings: mpsc::UnboundedSender, ) { if config.plugins_enabled { - self.maybe_start_curated_repo_sync_for_config( - config, - on_effective_plugins_changed.clone(), - ); + // aKode: the OpenAI curated marketplace is never synced at startup. let should_spawn_marketplace_auto_upgrade = { let mut state = match self.configured_marketplace_upgrade_state.write() { Ok(state) => state, @@ -3384,66 +3355,6 @@ impl PluginsManager { } } - fn start_curated_repo_sync( - self: &Arc, - http_client_factory: HttpClientFactory, - on_effective_plugins_changed: Option, - ) { - if CURATED_REPO_SYNC_STARTED.swap(true, Ordering::SeqCst) { - return; - } - let on_effective_plugins_changed = - on_effective_plugins_changed.map(|on_effective_plugins_changed| { - let Ok(runtime) = tokio::runtime::Handle::try_current() else { - return on_effective_plugins_changed; - }; - let callback: EffectivePluginsChangedCallback = Arc::new(move |change| { - let on_effective_plugins_changed = Arc::clone(&on_effective_plugins_changed); - runtime.spawn(async move { - on_effective_plugins_changed(change); - }); - }); - callback - }); - let manager = Arc::clone(self); - let codex_home = self.codex_home.clone(); - if let Err(err) = std::thread::Builder::new() - .name("plugins-curated-repo-sync".to_string()) - .spawn(move || { - match sync_openai_plugins_repo(codex_home.as_path(), http_client_factory) { - Ok(curated_plugin_version) => { - let configured_curated_plugin_ids = - configured_curated_plugin_ids_from_codex_home(codex_home.as_path()); - match refresh_curated_plugin_cache( - codex_home.as_path(), - &curated_plugin_version, - &configured_curated_plugin_ids, - ) { - Ok(cache_refreshed) => { - manager.clear_caches_after_marketplace_source_refresh( - cache_refreshed, - on_effective_plugins_changed.as_ref(), - ); - } - Err(err) => { - manager.clear_cache(); - CURATED_REPO_SYNC_STARTED.store(false, Ordering::SeqCst); - warn!("failed to refresh curated plugin cache after sync: {err}"); - } - } - } - Err(err) => { - CURATED_REPO_SYNC_STARTED.store(false, Ordering::SeqCst); - warn!("failed to sync curated plugins repo: {err}"); - } - } - }) - { - CURATED_REPO_SYNC_STARTED.store(false, Ordering::SeqCst); - warn!("failed to start curated plugins repo sync task: {err}"); - } - } - async fn run_remote_installed_plugins_cache_refresh_loop(self: Arc) { loop { let request = { diff --git a/codex-rs/core-plugins/src/manager_tests.rs b/codex-rs/core-plugins/src/manager_tests.rs index c4189fde..6bd2482b 100644 --- a/codex-rs/core-plugins/src/manager_tests.rs +++ b/codex-rs/core-plugins/src/manager_tests.rs @@ -6,9 +6,11 @@ use crate::PluginLoadOutcome; use crate::ToolSuggestDiscoverablePlugin; use crate::ToolSuggestPluginDiscoveryInput; use crate::installed_marketplaces::marketplace_install_root; +use crate::loader::configured_curated_plugin_ids_from_codex_home; use crate::loader::load_plugin_skill_inventory; use crate::loader::load_plugins_from_layer_stack; use crate::loader::plugin_capability_summary_from_root; +use crate::loader::refresh_curated_plugin_cache; use crate::loader::refresh_non_curated_plugin_cache; use crate::loader::refresh_non_curated_plugin_cache_force_reinstall; use crate::marketplace::MarketplacePluginInstallPolicy; @@ -160,33 +162,6 @@ async fn plugins_manager_reads_auth_mode_from_auth_manager() { assert_eq!(manager_with_auth.auth_mode(), Some(AuthMode::Chatgpt)); } -#[test] -fn curated_repo_sync_stays_deferred_for_remote_chatgpt_catalog() { - CURATED_REPO_SYNC_STARTED.store(false, std::sync::atomic::Ordering::SeqCst); - let tmp = TempDir::new().unwrap(); - let config = PluginsConfigInput::new( - unrestricted_config_layer_stack(), - Default::default(), - "openai".to_string(), - /*plugins_enabled*/ true, - /*remote_plugin_enabled*/ true, - "https://chatgpt.com".to_string(), - test_http_client_factory(), - /*product_sku*/ None, - ); - let manager = Arc::new(test_plugins_manager_with_options( - tmp.path().to_path_buf(), - Some(Product::Codex), - Some(AuthMode::Chatgpt), - )); - - manager.maybe_start_curated_repo_sync_for_config( - &config, /*on_effective_plugins_changed*/ None, - ); - - assert!(!CURATED_REPO_SYNC_STARTED.load(std::sync::atomic::Ordering::SeqCst)); -} - #[test] fn marketplace_source_refresh_notifies_only_after_installed_cache_changes() { let tmp = TempDir::new().unwrap(); diff --git a/codex-rs/core-plugins/src/marketplace_policy/curated_loading_tests.rs b/codex-rs/core-plugins/src/marketplace_policy/curated_loading_tests.rs index 841ebf1d..de8e9973 100644 --- a/codex-rs/core-plugins/src/marketplace_policy/curated_loading_tests.rs +++ b/codex-rs/core-plugins/src/marketplace_policy/curated_loading_tests.rs @@ -88,10 +88,6 @@ host_pattern = '^github[.]com$' permitted ); } - manager.maybe_start_curated_repo_sync_for_config( - &blocked, /*on_effective_plugins_changed*/ None, - ); - assert!(!CURATED_REPO_SYNC_STARTED.load(std::sync::atomic::Ordering::SeqCst)); } } diff --git a/codex-rs/core-plugins/src/startup_sync.rs b/codex-rs/core-plugins/src/startup_sync.rs index ee91e3ef..9b43f414 100644 --- a/codex-rs/core-plugins/src/startup_sync.rs +++ b/codex-rs/core-plugins/src/startup_sync.rs @@ -1,62 +1,18 @@ -use std::fs::File; +//! Paths of the local curated plugins snapshot. +//! +//! aKode: the upstream startup sync (git clone of github.com/openai/plugins, GitHub API +//! zipball download and the ChatGPT plugins export fallback) was removed. Only the on-disk +//! layout helpers remain, so an existing local snapshot keeps working and is never refreshed +//! from the network. + use std::path::Path; use std::path::PathBuf; -use std::process::Command; -use std::process::Output; -use std::process::Stdio; -use std::time::Duration; -use self::http_client::StartupSyncHttpClient; -use codex_http_client::HttpClientFactory; -use codex_http_client::RequestBuilder; -use codex_login::default_client::default_headers; -use codex_otel::CURATED_PLUGINS_STARTUP_SYNC_FINAL_METRIC; -use codex_otel::CURATED_PLUGINS_STARTUP_SYNC_METRIC; -use http::Method; -use serde::Deserialize; -use tempfile::TempDir; -use tracing::warn; -use zip::ZipArchive; - -mod http_client; - -const GITHUB_API_BASE_URL: &str = "https://api.github.com"; -const GITHUB_API_ACCEPT_HEADER: &str = "application/vnd.github+json"; -const GITHUB_API_VERSION_HEADER: &str = "2022-11-28"; -const CURATED_PLUGINS_BACKUP_ARCHIVE_API_URL: &str = - "https://chatgpt.com/backend-api/plugins/export/curated"; -const OPENAI_PLUGINS_OWNER: &str = "openai"; -const OPENAI_PLUGINS_REPO: &str = "plugins"; +/// Git source identifier of the upstream curated marketplace. aKode: used only to match +/// marketplace policy rules; nothing is ever fetched from it. pub(crate) const OPENAI_PLUGINS_GIT_URL: &str = "https://github.com/openai/plugins.git"; -const CURATED_PLUGINS_FETCH_REF: &str = "refs/codex/curated-sync"; const CURATED_PLUGINS_RELATIVE_DIR: &str = ".tmp/plugins"; const CURATED_PLUGINS_SHA_FILE: &str = ".tmp/plugins.sha"; -const CURATED_PLUGINS_SYNC_LOCK_FILE: &str = ".tmp/plugins.sync.lock"; -const CURATED_PLUGINS_BACKUP_ARCHIVE_FALLBACK_VERSION: &str = "export-backup"; -const CURATED_PLUGINS_GIT_TIMEOUT: Duration = Duration::from_secs(30); -const CURATED_PLUGINS_HTTP_TIMEOUT: Duration = Duration::from_secs(30); -const CURATED_PLUGINS_BACKUP_ARCHIVE_TIMEOUT: Duration = Duration::from_secs(30); -// Keep this comfortably above a normal sync attempt so we do not race another Codex process. -const CURATED_PLUGINS_STALE_TEMP_DIR_MAX_AGE: Duration = Duration::from_secs(10 * 60); -#[derive(Debug, Deserialize)] -struct GitHubRepositorySummary { - default_branch: String, -} - -#[derive(Debug, Deserialize)] -struct GitHubGitRefSummary { - object: GitHubGitRefObject, -} - -#[derive(Debug, Deserialize)] -struct GitHubGitRefObject { - sha: String, -} - -#[derive(Debug, Deserialize)] -struct CuratedPluginsBackupArchiveResponse { - download_url: String, -} pub fn curated_plugins_repo_path(codex_home: &Path) -> PathBuf { codex_home.join(CURATED_PLUGINS_RELATIVE_DIR) @@ -67,1059 +23,36 @@ pub fn curated_plugins_api_marketplace_path(codex_home: &Path) -> PathBuf { } pub fn read_curated_plugins_sha(codex_home: &Path) -> Option { - read_sha_file(curated_plugins_sha_path(codex_home).as_path()) -} - -fn curated_plugins_sha_path(codex_home: &Path) -> PathBuf { - codex_home.join(CURATED_PLUGINS_SHA_FILE) -} - -pub fn sync_openai_plugins_repo( - codex_home: &Path, - http_client_factory: HttpClientFactory, -) -> Result { - // Keep Git-only egress working without trusting workspace PATH entries. - let git_binary = codex_utils_path::system_executable("git"); - // Apple's /usr/bin/git is an installer shim when developer tools are absent. - // The resolver prefers the real CLT/Xcode executable when installed. - #[cfg(target_os = "macos")] - let git_binary = git_binary.filter(|path| path != Path::new("/usr/bin/git")); - sync_openai_plugins_repo_with_transport_overrides( - codex_home, - git_binary.as_deref(), - GITHUB_API_BASE_URL, - CURATED_PLUGINS_BACKUP_ARCHIVE_API_URL, - &http_client_factory, - ) -} - -fn sync_openai_plugins_repo_with_transport_overrides( - codex_home: &Path, - git_binary: Option<&Path>, - api_base_url: &str, - backup_archive_api_url: &str, - http_client_factory: &HttpClientFactory, -) -> Result { - let _file_guard = lock_curated_plugins_startup_sync(codex_home)?; - - let git_sync_result = match git_binary { - Some(git_binary) => sync_openai_plugins_repo_via_git(codex_home, git_binary), - None => Err("no Git executable found in trusted installation directories".to_string()), - }; - - match git_sync_result { - Ok(remote_sha) => { - emit_curated_plugins_startup_sync_metric("git", "success"); - emit_curated_plugins_startup_sync_final_metric("git", "success"); - Ok(remote_sha) - } - Err(err) => { - if git_binary.is_some() { - emit_curated_plugins_startup_sync_metric("git", "failure"); - warn!( - error = %err, - "git sync failed for curated plugin sync; falling back to GitHub HTTP" - ); - } - match sync_openai_plugins_repo_via_http(codex_home, api_base_url, http_client_factory) { - Ok(remote_sha) => { - emit_curated_plugins_startup_sync_metric("http", "success"); - emit_curated_plugins_startup_sync_final_metric("http", "success"); - Ok(remote_sha) - } - Err(http_err) => { - emit_curated_plugins_startup_sync_metric("http", "failure"); - if has_local_curated_plugins_snapshot(codex_home) { - emit_curated_plugins_startup_sync_final_metric("http", "failure"); - warn!( - error = %http_err, - "GitHub HTTP sync failed for curated plugin sync; skipping export archive fallback because a local curated plugins snapshot already exists" - ); - Err(format!( - "git sync failed for curated plugin sync: {err}; GitHub HTTP sync failed for curated plugin sync: {http_err}; export archive fallback skipped because a local curated plugins snapshot already exists" - )) - } else { - // The export archive is a lagging backup path. Only use it to bootstrap a - // missing local curated snapshot, never to refresh an existing one. - warn!( - error = %http_err, - backup_archive_api_url, - "GitHub HTTP sync failed for curated plugin sync; falling back to export archive" - ); - let result = sync_openai_plugins_repo_via_backup_archive( - codex_home, - backup_archive_api_url, - http_client_factory, - ); - let status = if result.is_ok() { "success" } else { "failure" }; - emit_curated_plugins_startup_sync_metric("export_archive", status); - emit_curated_plugins_startup_sync_final_metric("export_archive", status); - result.map_err(|export_err| { - format!( - "git sync failed for curated plugin sync: {err}; GitHub HTTP sync failed for curated plugin sync: {http_err}; export archive sync failed for curated plugin sync: {export_err}" - ) - }) - } - } - } - } - } -} - -fn lock_curated_plugins_startup_sync(codex_home: &Path) -> Result { - let lock_path = codex_home.join(CURATED_PLUGINS_SYNC_LOCK_FILE); - std::fs::create_dir_all(codex_home.join(".tmp")) - .map_err(|err| format!("failed to create curated plugins sync directory: {err}"))?; - let lock_file = File::options() - .write(true) - .create(true) - .truncate(false) - .open(&lock_path) - .map_err(|err| format!("failed to open curated plugins sync lock: {err}"))?; - lock_file - .lock() - .map_err(|err| format!("failed to lock curated plugins sync: {err}"))?; - Ok(lock_file) -} - -fn sync_openai_plugins_repo_via_git( - codex_home: &Path, - git_binary: &Path, -) -> Result { - let repo_path = curated_plugins_repo_path(codex_home); - let sha_path = codex_home.join(CURATED_PLUGINS_SHA_FILE); - let remote_sha = git_ls_remote_head_sha(codex_home, git_binary)?; - let local_sha = read_local_git_or_sha_file(&repo_path, &sha_path, git_binary); - - if local_sha.as_deref() == Some(remote_sha.as_str()) && repo_path.join(".git").is_dir() { - return Ok(remote_sha); - } - - let staged_repo_dir = prepare_curated_repo_parent_and_temp_dir(&repo_path)?; - run_git_in_repo( - staged_repo_dir.path(), - git_binary, - &["init"], - "git init curated plugins repo", - )?; - - if repo_path.join(".git").is_dir() { - fetch_curated_plugins_commit(&repo_path, &remote_sha, git_binary)?; - fetch_curated_plugins_commit_from_source( - staged_repo_dir.path(), - &repo_path, - CURATED_PLUGINS_FETCH_REF, - git_binary, - )?; - } else { - fetch_curated_plugins_commit(staged_repo_dir.path(), &remote_sha, git_binary)?; - } - - reset_curated_plugins_checkout(staged_repo_dir.path(), git_binary)?; - let fetched_sha = git_head_sha(staged_repo_dir.path(), git_binary)?; - if fetched_sha != remote_sha { - return Err(format!( - "curated plugins fetch HEAD mismatch: expected {remote_sha}, got {fetched_sha}" - )); - } - - ensure_marketplace_manifest_exists(staged_repo_dir.path())?; - activate_curated_repo(&repo_path, staged_repo_dir)?; - write_curated_plugins_sha(&sha_path, &remote_sha)?; - Ok(remote_sha) -} - -fn fetch_curated_plugins_commit( - repo_path: &Path, - remote_sha: &str, - git_binary: &Path, -) -> Result<(), String> { - fetch_curated_plugins_commit_from( - repo_path, - OPENAI_PLUGINS_GIT_URL.as_ref(), - remote_sha, - git_binary, - "git fetch curated plugins repo", - ) -} - -fn fetch_curated_plugins_commit_from_source( - repo_path: &Path, - source_repo_path: &Path, - remote_sha: &str, - git_binary: &Path, -) -> Result<(), String> { - fetch_curated_plugins_commit_from( - repo_path, - source_repo_path, - remote_sha, - git_binary, - "git copy fetched curated plugins commit", - ) -} - -fn fetch_curated_plugins_commit_from( - repo_path: &Path, - source: &Path, - source_revision: &str, - git_binary: &Path, - context: &str, -) -> Result<(), String> { - let fetch_refspec = format!("+{source_revision}:{CURATED_PLUGINS_FETCH_REF}"); - let mut command = git_command(git_binary)?; - command - .arg("-C") - .arg(repo_path) - .args(["fetch", "--depth", "1", "--no-tags"]) - .arg(source) - .arg(fetch_refspec); - let output = run_git_command_with_timeout(&mut command, context, CURATED_PLUGINS_GIT_TIMEOUT)?; - ensure_git_success(&output, context) -} - -fn reset_curated_plugins_checkout(repo_path: &Path, git_binary: &Path) -> Result<(), String> { - run_git_in_repo( - repo_path, - git_binary, - &["reset", "--hard", CURATED_PLUGINS_FETCH_REF], - "git reset curated plugins repo", - )?; - run_git_in_repo( - repo_path, - git_binary, - &["clean", "-fdx"], - "git clean curated plugins repo", - ) -} - -fn run_git_in_repo( - repo_path: &Path, - git_binary: &Path, - args: &[&str], - context: &str, -) -> Result<(), String> { - let mut command = git_command(git_binary)?; - command.arg("-C").arg(repo_path).args(args); - let output = run_git_command_with_timeout(&mut command, context, CURATED_PLUGINS_GIT_TIMEOUT)?; - ensure_git_success(&output, context) -} - -fn sync_openai_plugins_repo_via_http( - codex_home: &Path, - api_base_url: &str, - http_client_factory: &HttpClientFactory, -) -> Result { - let repo_path = curated_plugins_repo_path(codex_home); - let sha_path = codex_home.join(CURATED_PLUGINS_SHA_FILE); - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .map_err(|err| format!("failed to create curated plugins sync runtime: {err}"))?; - let http_clients = StartupSyncHttpClient::new(http_client_factory); - let remote_sha = - runtime.block_on(fetch_curated_repo_remote_sha(&http_clients, api_base_url))?; - let local_sha = read_sha_file(&sha_path); - - if local_sha.as_deref() == Some(remote_sha.as_str()) && repo_path.is_dir() { - return Ok(remote_sha); - } - - let staged_repo_dir = prepare_curated_repo_parent_and_temp_dir(&repo_path)?; - let zipball_bytes = runtime.block_on(fetch_curated_repo_zipball( - &http_clients, - api_base_url, - &remote_sha, - ))?; - extract_zipball_to_dir(&zipball_bytes, staged_repo_dir.path())?; - ensure_marketplace_manifest_exists(staged_repo_dir.path())?; - activate_curated_repo(&repo_path, staged_repo_dir)?; - write_curated_plugins_sha(&sha_path, &remote_sha)?; - Ok(remote_sha) -} - -fn sync_openai_plugins_repo_via_backup_archive( - codex_home: &Path, - backup_archive_api_url: &str, - http_client_factory: &HttpClientFactory, -) -> Result { - let repo_path = curated_plugins_repo_path(codex_home); - let sha_path = curated_plugins_sha_path(codex_home); - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .map_err(|err| format!("failed to create curated plugins sync runtime: {err}"))?; - let staged_repo_dir = prepare_curated_repo_parent_and_temp_dir(&repo_path)?; - let http_clients = StartupSyncHttpClient::new(http_client_factory); - let zipball_bytes = runtime.block_on(fetch_curated_repo_backup_archive_zip( - &http_clients, - backup_archive_api_url, - ))?; - extract_zipball_to_dir(&zipball_bytes, staged_repo_dir.path())?; - ensure_marketplace_manifest_exists(staged_repo_dir.path())?; - let export_version = read_extracted_backup_archive_git_sha(staged_repo_dir.path())? - .unwrap_or_else(|| CURATED_PLUGINS_BACKUP_ARCHIVE_FALLBACK_VERSION.to_string()); - activate_curated_repo(&repo_path, staged_repo_dir)?; - write_curated_plugins_sha(&sha_path, &export_version)?; - Ok(export_version) -} - -pub fn has_local_curated_plugins_snapshot(codex_home: &Path) -> bool { - curated_plugins_repo_path(codex_home) - .join(".agents/plugins/marketplace.json") - .is_file() - && codex_home.join(CURATED_PLUGINS_SHA_FILE).is_file() -} - -fn prepare_curated_repo_parent_and_temp_dir(repo_path: &Path) -> Result { - let Some(parent) = repo_path.parent() else { - return Err(format!( - "failed to determine curated plugins parent directory for {}", - repo_path.display() - )); - }; - std::fs::create_dir_all(parent).map_err(|err| { - format!( - "failed to create curated plugins parent directory {}: {err}", - parent.display() - ) - })?; - remove_stale_curated_repo_temp_dirs(parent, CURATED_PLUGINS_STALE_TEMP_DIR_MAX_AGE); - - let clone_dir = tempfile::Builder::new() - .prefix("plugins-clone-") - .tempdir_in(parent) - .map_err(|err| { - format!( - "failed to create temporary curated plugins directory in {}: {err}", - parent.display() - ) - })?; - Ok(clone_dir) -} - -fn remove_stale_curated_repo_temp_dirs(parent: &Path, max_age: Duration) { - let entries = match std::fs::read_dir(parent) { - Ok(entries) => entries, - Err(err) => { - warn!( - error = %err, - parent = %parent.display(), - "failed to list curated plugins temp directory parent for stale cleanup" - ); - return; - } - }; - - for entry in entries.flatten() { - let file_type = match entry.file_type() { - Ok(file_type) => file_type, - Err(err) => { - warn!( - error = %err, - path = %entry.path().display(), - "failed to inspect curated plugins temp directory entry" - ); - continue; - } - }; - if !file_type.is_dir() { - continue; - } - - let path = entry.path(); - let is_plugins_clone_dir = path - .file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.starts_with("plugins-clone-")); - if !is_plugins_clone_dir { - continue; - } - - let metadata = match entry.metadata() { - Ok(metadata) => metadata, - Err(err) => { - warn!( - error = %err, - path = %path.display(), - "failed to read curated plugins temp directory metadata" - ); - continue; - } - }; - let modified = match metadata.modified() { - Ok(modified) => modified, - Err(err) => { - warn!( - error = %err, - path = %path.display(), - "failed to read curated plugins temp directory modification time" - ); - continue; - } - }; - let age = match modified.elapsed() { - Ok(age) => age, - Err(err) => { - warn!( - error = %err, - path = %path.display(), - "failed to compute curated plugins temp directory age" - ); - continue; - } - }; - if age < max_age { - continue; - } - - if let Err(err) = std::fs::remove_dir_all(&path) { - warn!( - error = %err, - path = %path.display(), - "failed to remove stale curated plugins temp directory" - ); - } - } -} - -fn emit_curated_plugins_startup_sync_metric(transport: &'static str, status: &'static str) { - emit_curated_plugins_startup_sync_counter( - CURATED_PLUGINS_STARTUP_SYNC_METRIC, - transport, - status, - ); -} - -fn emit_curated_plugins_startup_sync_final_metric(transport: &'static str, status: &'static str) { - emit_curated_plugins_startup_sync_counter( - CURATED_PLUGINS_STARTUP_SYNC_FINAL_METRIC, - transport, - status, - ); -} - -fn emit_curated_plugins_startup_sync_counter( - metric_name: &str, - transport: &'static str, - status: &'static str, -) { - let Some(metrics) = codex_otel::global() else { - return; - }; - let tags = [("transport", transport), ("status", status)]; - let _ = metrics.counter(metric_name, /*inc*/ 1, &tags); -} - -fn ensure_marketplace_manifest_exists(repo_path: &Path) -> Result<(), String> { - if repo_path.join(".agents/plugins/marketplace.json").is_file() { - return Ok(()); - } - Err(format!( - "curated plugins archive missing marketplace manifest at {}", - repo_path.join(".agents/plugins/marketplace.json").display() - )) -} - -fn activate_curated_repo(repo_path: &Path, staged_repo_dir: TempDir) -> Result<(), String> { - let staged_repo_path = staged_repo_dir.path(); - if repo_path.exists() { - let parent = repo_path.parent().ok_or_else(|| { - format!( - "failed to determine curated plugins parent directory for {}", - repo_path.display() - ) - })?; - let backup_dir = tempfile::Builder::new() - .prefix("plugins-backup-") - .tempdir_in(parent) - .map_err(|err| { - format!( - "failed to create curated plugins backup directory in {}: {err}", - parent.display() - ) - })?; - let backup_repo_path = backup_dir.path().join("repo"); - - std::fs::rename(repo_path, &backup_repo_path).map_err(|err| { - format!( - "failed to move previous curated plugins repo out of the way at {}: {err}", - repo_path.display() - ) - })?; - - if let Err(err) = std::fs::rename(staged_repo_path, repo_path) { - let rollback_result = std::fs::rename(&backup_repo_path, repo_path); - return match rollback_result { - Ok(()) => Err(format!( - "failed to activate new curated plugins repo at {}: {err}", - repo_path.display() - )), - Err(rollback_err) => { - let backup_path = backup_dir.keep().join("repo"); - Err(format!( - "failed to activate new curated plugins repo at {}: {err}; failed to restore previous repo (left at {}): {rollback_err}", - repo_path.display(), - backup_path.display() - )) - } - }; - } - } else { - std::fs::rename(staged_repo_path, repo_path).map_err(|err| { - format!( - "failed to activate curated plugins repo at {}: {err}", - repo_path.display() - ) - })?; - } - - Ok(()) -} - -fn write_curated_plugins_sha(sha_path: &Path, remote_sha: &str) -> Result<(), String> { - if let Some(parent) = sha_path.parent() { - std::fs::create_dir_all(parent).map_err(|err| { - format!( - "failed to create curated plugins sha directory {}: {err}", - parent.display() - ) - })?; - } - std::fs::write(sha_path, format!("{remote_sha}\n")).map_err(|err| { - format!( - "failed to write curated plugins sha file {}: {err}", - sha_path.display() - ) - }) -} - -fn read_local_git_or_sha_file( - repo_path: &Path, - sha_path: &Path, - git_binary: &Path, -) -> Option { - if repo_path.join(".git").is_dir() - && let Ok(sha) = git_head_sha(repo_path, git_binary) - { - return Some(sha); - } - - read_sha_file(sha_path) -} - -fn git_ls_remote_head_sha(codex_home: &Path, git_binary: &Path) -> Result { - let mut command = git_command(git_binary)?; - let _trusted_repository = crate::configure_trusted_git_repository(&mut command, codex_home)?; - command - .current_dir(codex_home) - .arg("ls-remote") - .arg(OPENAI_PLUGINS_GIT_URL) - .arg("HEAD"); - let output = run_git_command_with_timeout( - &mut command, - "git ls-remote curated plugins repo", - CURATED_PLUGINS_GIT_TIMEOUT, - )?; - ensure_git_success(&output, "git ls-remote curated plugins repo")?; - - let stdout = String::from_utf8_lossy(&output.stdout); - let Some(first_line) = stdout.lines().next() else { - return Err("git ls-remote returned empty output for curated plugins repo".to_string()); - }; - let Some((sha, _)) = first_line.split_once('\t') else { - return Err(format!( - "unexpected git ls-remote output for curated plugins repo: {first_line}" - )); - }; - if sha.is_empty() { - return Err("git ls-remote returned empty sha for curated plugins repo".to_string()); - } - Ok(sha.to_string()) -} - -fn git_head_sha(repo_path: &Path, git_binary: &Path) -> Result { - let output = git_command(git_binary)? - .arg("-C") - .arg(repo_path) - .arg("rev-parse") - .arg("HEAD") - .output() - .map_err(|err| { - format!( - "failed to run git rev-parse HEAD in {}: {err}", - repo_path.display() - ) - })?; - ensure_git_success(&output, "git rev-parse HEAD")?; - - let sha = String::from_utf8_lossy(&output.stdout).trim().to_string(); - if sha.is_empty() { - return Err(format!( - "git rev-parse HEAD returned empty output in {}", - repo_path.display() - )); - } - Ok(sha) -} - -fn git_command(git_binary: &Path) -> Result { - let mut command = crate::PluginGitMode::Automatic.command(git_binary); - // Git launches transports and credential helpers too. Selecting a trusted - // main executable alone does not prevent a workspace PATH helper from running. - command - .env( - "PATH", - codex_utils_path::system_path() - .map_err(|err| format!("failed to construct trusted Git PATH: {err}"))?, - ) - .env_remove("GIT_EXEC_PATH") - .env_remove("GIT_TEMPLATE_DIR") - .env_remove("DEVELOPER_DIR") - .env("GIT_TERMINAL_PROMPT", "0") - .env("NoDefaultCurrentDirectoryInExePath", "1"); - Ok(command) -} - -fn run_git_command_with_timeout( - command: &mut Command, - context: &str, - timeout: Duration, -) -> Result { - let mut child = command - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .map_err(|err| format!("failed to run {context}: {err}"))?; - - let start = std::time::Instant::now(); - loop { - match child.try_wait() { - Ok(Some(_)) => { - return child - .wait_with_output() - .map_err(|err| format!("failed to wait for {context}: {err}")); - } - Ok(None) => {} - Err(err) => return Err(format!("failed to poll {context}: {err}")), - } - - if start.elapsed() >= timeout { - match child.try_wait() { - Ok(Some(_)) => { - return child - .wait_with_output() - .map_err(|err| format!("failed to wait for {context}: {err}")); - } - Ok(None) => {} - Err(err) => return Err(format!("failed to poll {context}: {err}")), - } - - let _ = child.kill(); - let output = child - .wait_with_output() - .map_err(|err| format!("failed to wait for {context} after timeout: {err}"))?; - let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); - return if stderr.is_empty() { - Err(format!("{context} timed out after {}s", timeout.as_secs())) - } else { - Err(format!( - "{context} timed out after {}s: {stderr}", - timeout.as_secs() - )) - }; - } - - std::thread::sleep(Duration::from_millis(100)); - } -} - -fn ensure_git_success(output: &Output, context: &str) -> Result<(), String> { - if output.status.success() { - return Ok(()); - } - let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); - if stderr.is_empty() { - Err(format!("{context} failed with status {}", output.status)) - } else { - Err(format!( - "{context} failed with status {}: {stderr}", - output.status - )) - } -} - -async fn fetch_curated_repo_remote_sha( - http_clients: &StartupSyncHttpClient, - api_base_url: &str, -) -> Result { - let api_base_url = api_base_url.trim_end_matches('/'); - let repo_url = format!("{api_base_url}/repos/{OPENAI_PLUGINS_OWNER}/{OPENAI_PLUGINS_REPO}"); - let repo_body = - fetch_github_text(http_clients, &repo_url, "get curated plugins repository").await?; - let repo_summary: GitHubRepositorySummary = - serde_json::from_str(&repo_body).map_err(|err| { - format!("failed to parse curated plugins repository response from {repo_url}: {err}") - })?; - if repo_summary.default_branch.is_empty() { - return Err(format!( - "curated plugins repository response from {repo_url} did not include a default branch" - )); - } - - let git_ref_url = format!("{repo_url}/git/ref/heads/{}", repo_summary.default_branch); - let git_ref_body = - fetch_github_text(http_clients, &git_ref_url, "get curated plugins HEAD ref").await?; - let git_ref: GitHubGitRefSummary = serde_json::from_str(&git_ref_body).map_err(|err| { - format!("failed to parse curated plugins ref response from {git_ref_url}: {err}") - })?; - if git_ref.object.sha.is_empty() { - return Err(format!( - "curated plugins ref response from {git_ref_url} did not include a HEAD sha" - )); - } - - Ok(git_ref.object.sha) -} - -async fn fetch_curated_repo_zipball( - http_clients: &StartupSyncHttpClient, - api_base_url: &str, - remote_sha: &str, -) -> Result, String> { - let api_base_url = api_base_url.trim_end_matches('/'); - let repo_url = format!("{api_base_url}/repos/{OPENAI_PLUGINS_OWNER}/{OPENAI_PLUGINS_REPO}"); - let zipball_url = format!("{repo_url}/zipball/{remote_sha}"); - fetch_github_bytes( - http_clients, - &zipball_url, - "download curated plugins archive", - ) - .await -} - -async fn fetch_curated_repo_backup_archive_zip( - http_clients: &StartupSyncHttpClient, - backup_archive_api_url: &str, -) -> Result, String> { - let export_body = fetch_public_text( - http_clients, - backup_archive_api_url, - "get curated plugins export archive metadata", - ) - .await?; - let export_response: CuratedPluginsBackupArchiveResponse = serde_json::from_str(&export_body) - .map_err(|err| { - format!( - "failed to parse curated plugins backup archive response from {backup_archive_api_url}: {err}" - ) - })?; - if export_response.download_url.is_empty() { - return Err(format!( - "curated plugins backup archive response from {backup_archive_api_url} did not include a download URL" - )); - } - - fetch_public_bytes( - http_clients, - &export_response.download_url, - "download curated plugins export archive", - ) - .await -} - -fn read_extracted_backup_archive_git_sha(repo_path: &Path) -> Result, String> { - let git_dir = repo_path.join(".git"); - if !git_dir.is_dir() { - return Ok(None); - } - - let head_path = git_dir.join("HEAD"); - let head = std::fs::read_to_string(&head_path).map_err(|err| { - format!( - "failed to read curated plugins backup archive git HEAD {}: {err}", - head_path.display() - ) - })?; - let head = head.trim(); - if head.is_empty() { - return Err(format!( - "curated plugins backup archive git HEAD is empty at {}", - head_path.display() - )); - } - - if let Some(reference) = head.strip_prefix("ref: ") { - let reference = validate_backup_archive_git_ref(reference.trim())?; - return read_git_ref_sha(&git_dir, reference).map(Some); - } - - Ok(Some(head.to_string())) -} - -fn validate_backup_archive_git_ref(reference: &str) -> Result<&str, String> { - if !reference.starts_with("refs/") { - return Err(format!( - "curated plugins backup archive git ref must stay under refs/: {reference}" - )); - } - - let path = Path::new(reference); - if path.is_absolute() { - return Err(format!( - "curated plugins backup archive git ref must be relative: {reference}" - )); - } - - for component in path.components() { - match component { - std::path::Component::Normal(_) => {} - _ => { - return Err(format!( - "curated plugins backup archive git ref contains invalid path components: {reference}" - )); - } - } - } - - Ok(reference) -} - -fn read_git_ref_sha(git_dir: &Path, reference: &str) -> Result { - let ref_path = git_dir.join(reference); - if let Ok(sha) = std::fs::read_to_string(&ref_path) { - let sha = sha.trim(); - if sha.is_empty() { - return Err(format!( - "curated plugins backup archive git ref {reference} is empty at {}", - ref_path.display() - )); - } - return Ok(sha.to_string()); - } - - let packed_refs_path = git_dir.join("packed-refs"); - if let Ok(packed_refs) = std::fs::read_to_string(&packed_refs_path) - && let Some(sha) = packed_refs.lines().find_map(|line| { - let trimmed = line.trim(); - if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('^') { - return None; - } - let (sha, candidate_ref) = trimmed.split_once(' ')?; - (candidate_ref == reference).then_some(sha.to_string()) - }) - { - return Ok(sha); - } - - Err(format!( - "failed to resolve curated plugins backup archive git ref {reference} from {}", - git_dir.display() - )) -} - -async fn fetch_github_text( - http_clients: &StartupSyncHttpClient, - url: &str, - context: &str, -) -> Result { - let response = github_request(http_clients, url) - .send() - .await - .map_err(|err| format!("failed to {context} from {url}: {err}"))?; - let status = response.status(); - let body = response - .text() - .await - .map_err(|err| format!("failed to {context} from {url}: {err}"))?; - if !status.is_success() { - return Err(format!( - "{context} from {url} failed with status {status}: {body}" - )); - } - Ok(body) -} - -async fn fetch_github_bytes( - http_clients: &StartupSyncHttpClient, - url: &str, - context: &str, -) -> Result, String> { - let response = github_request(http_clients, url) - .send() - .await - .map_err(|err| format!("failed to {context} from {url}: {err}"))?; - let status = response.status(); - let body = response - .bytes() - .await - .map_err(|err| format!("failed to read {context} response from {url}: {err}"))?; - if !status.is_success() { - let body_text = String::from_utf8_lossy(&body); - return Err(format!( - "{context} from {url} failed with status {status}: {body_text}" - )); - } - Ok(body.to_vec()) -} - -async fn fetch_public_text( - http_clients: &StartupSyncHttpClient, - url: &str, - context: &str, -) -> Result { - let response = startup_sync_request(http_clients, url) - .timeout(CURATED_PLUGINS_BACKUP_ARCHIVE_TIMEOUT) - .send() - .await - .map_err(|err| format!("failed to {context} from {url}: {err}"))?; - let status = response.status(); - let body = response - .text() - .await - .map_err(|err| format!("failed to {context} from {url}: {err}"))?; - if !status.is_success() { - return Err(format!( - "{context} from {url} failed with status {status}: {body}" - )); - } - Ok(body) -} - -async fn fetch_public_bytes( - http_clients: &StartupSyncHttpClient, - url: &str, - context: &str, -) -> Result, String> { - let response = startup_sync_request(http_clients, url) - .timeout(CURATED_PLUGINS_BACKUP_ARCHIVE_TIMEOUT) - .send() - .await - .map_err(|err| format!("failed to {context} from {url}: {err}"))?; - let status = response.status(); - let body = response - .bytes() - .await - .map_err(|err| format!("failed to read {context} response from {url}: {err}"))?; - if !status.is_success() { - let body_text = String::from_utf8_lossy(&body); - return Err(format!( - "{context} from {url} failed with status {status}: {body_text}" - )); - } - Ok(body.to_vec()) -} - -fn github_request(http_clients: &StartupSyncHttpClient, url: &str) -> RequestBuilder { - startup_sync_request(http_clients, url) - .timeout(CURATED_PLUGINS_HTTP_TIMEOUT) - .header("accept", GITHUB_API_ACCEPT_HEADER) - .header("x-github-api-version", GITHUB_API_VERSION_HEADER) -} - -fn startup_sync_request(http_clients: &StartupSyncHttpClient, url: &str) -> RequestBuilder { - http_clients - .request(Method::GET, url) - .headers(default_headers()) -} - -fn read_sha_file(sha_path: &Path) -> Option { - std::fs::read_to_string(sha_path) + std::fs::read_to_string(codex_home.join(CURATED_PLUGINS_SHA_FILE)) .ok() .map(|sha| sha.trim().to_string()) .filter(|sha| !sha.is_empty()) } -fn extract_zipball_to_dir(bytes: &[u8], destination: &Path) -> Result<(), String> { - std::fs::create_dir_all(destination).map_err(|err| { - format!( - "failed to create curated plugins extraction directory {}: {err}", - destination.display() - ) - })?; +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use tempfile::tempdir; - let cursor = std::io::Cursor::new(bytes); - let mut archive = ZipArchive::new(cursor) - .map_err(|err| format!("failed to open curated plugins zip archive: {err}"))?; - - for index in 0..archive.len() { - let mut entry = archive - .by_index(index) - .map_err(|err| format!("failed to read curated plugins zip entry: {err}"))?; - let Some(relative_path) = entry.enclosed_name() else { - let name = entry - .name() - .map_err(|err| format!("invalid curated plugins zip entry {index}: {err}"))?; - return Err(format!( - "curated plugins zip entry `{name}` escapes extraction root" - )); - }; - - let mut components = relative_path.components(); - let Some(std::path::Component::Normal(_)) = components.next() else { - continue; - }; - - let output_relative = components.fold(PathBuf::new(), |mut path, component| { - if let std::path::Component::Normal(segment) = component { - path.push(segment); - } - path - }); - if output_relative.as_os_str().is_empty() { - continue; - } - - let output_path = destination.join(&output_relative); - if entry.is_dir() { - std::fs::create_dir_all(&output_path).map_err(|err| { - format!( - "failed to create curated plugins directory {}: {err}", - output_path.display() - ) - })?; - continue; - } - - if let Some(parent) = output_path.parent() { - std::fs::create_dir_all(parent).map_err(|err| { - format!( - "failed to create curated plugins directory {}: {err}", - parent.display() - ) - })?; - } - let mut output = std::fs::File::create(&output_path).map_err(|err| { - format!( - "failed to create curated plugins file {}: {err}", - output_path.display() - ) - })?; - std::io::copy(&mut entry, &mut output).map_err(|err| { - format!( - "failed to write curated plugins file {}: {err}", - output_path.display() - ) - })?; - #[cfg(unix)] - if let Some(mode) = entry.unix_mode() { - use std::os::unix::fs::PermissionsExt; - - // zip strips setuid, setgid, and sticky bits from the archive's Unix mode. - output - .set_permissions(std::fs::Permissions::from_mode(mode)) - .map_err(|err| { - format!( - "failed to set permissions on curated plugins file {}: {err}", - output_path.display() - ) - })?; - } + #[test] + fn curated_plugins_repo_path_uses_codex_home_tmp_dir() { + let tmp = tempdir().expect("tempdir"); + assert_eq!( + curated_plugins_repo_path(tmp.path()), + tmp.path().join(".tmp/plugins") + ); } - Ok(()) -} + #[test] + fn read_curated_plugins_sha_reads_trimmed_sha_file() { + let tmp = tempdir().expect("tempdir"); + std::fs::create_dir_all(tmp.path().join(".tmp")).expect("create tmp"); + std::fs::write(tmp.path().join(".tmp/plugins.sha"), "abc123\n").expect("write sha"); -#[cfg(test)] -#[path = "startup_sync_tests.rs"] -mod tests; + assert_eq!( + read_curated_plugins_sha(tmp.path()).as_deref(), + Some("abc123") + ); + } +} diff --git a/codex-rs/core-plugins/src/startup_sync/http_client.rs b/codex-rs/core-plugins/src/startup_sync/http_client.rs deleted file mode 100644 index 3debe0cd..00000000 --- a/codex-rs/core-plugins/src/startup_sync/http_client.rs +++ /dev/null @@ -1,37 +0,0 @@ -//! HTTP transport for curated plugin startup sync. -//! -//! Both proxy modes retain the supplied application network policy. The default proxy mode also -//! keeps the legacy fallback for invalid custom CA configuration; system-proxy mode fails closed. -//! Startup-sync request helpers apply the standard Codex headers. - -use std::sync::Arc; - -use crate::http_client_selector::HttpClientSelector; -use codex_http_client::ClientRouteClass; -use codex_http_client::HttpClientFactory; -use codex_http_client::RequestBuilder; -use codex_http_client::RouteAwareClientPool; -use http::Method; - -pub(super) struct StartupSyncHttpClient(Arc); - -impl StartupSyncHttpClient { - pub(super) fn new(http_client_factory: &HttpClientFactory) -> Self { - let http_clients = - RouteAwareClientPool::with_chatgpt_cloudflare_cookies_without_request_logging( - http_client_factory.clone(), - ClientRouteClass::Api, - ) - .with_legacy_custom_ca_fallback(); - Self(Arc::new(http_clients)) - } - - #[cfg(test)] - pub(super) fn route_aware(http_clients: Arc) -> Self { - Self(http_clients) - } - - pub(super) fn request(&self, method: Method, url: &str) -> RequestBuilder { - self.0.request(method, url) - } -} diff --git a/codex-rs/core-plugins/src/startup_sync_tests.rs b/codex-rs/core-plugins/src/startup_sync_tests.rs deleted file mode 100644 index 8df59b15..00000000 --- a/codex-rs/core-plugins/src/startup_sync_tests.rs +++ /dev/null @@ -1,1487 +0,0 @@ -use super::*; -use crate::git_policy::REPOSITORY_LOCAL_GIT_ENVIRONMENT_VARIABLES; -use crate::test_support::RecordingHttpClientSelector; -use crate::test_support::recorded_http_client_urls; -use codex_http_client::DestinationPolicy::Restricted; -use codex_http_client::NetworkPolicyDenied::Destination; -use codex_http_client::RouteAwareRequestError::Policy; -use pretty_assertions::assert_eq; -use std::ffi::OsStr; -use std::io::Write; -use std::path::Path; -use std::path::PathBuf; -#[cfg(unix)] -use std::sync::Barrier; -use tempfile::tempdir; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header_exists; -use wiremock::matchers::method; -use wiremock::matchers::path; -use zip::ZipWriter; -use zip::write::SimpleFileOptions; - -const TEST_CURATED_PLUGIN_SHA: &str = "0123456789abcdef0123456789abcdef01234567"; - -#[cfg(unix)] -#[test] -fn pretrust_startup_sync_uses_installed_git_with_hostile_path() { - const CHILD_HOME: &str = "CODEX_TEST_CURATED_SYNC_HOME"; - if let Some(home) = std::env::var_os(CHILD_HOME) { - // Call the public entry point, synchronously. The parent joins this - // process before checking the marker, so no detached work can escape it. - sync_openai_plugins_repo( - Path::new(&home), - crate::test_support::test_http_client_factory(), - ) - .expect("Git-only startup sync should succeed"); - return; - } - let fixture = tempdir().expect("fixture"); - let source = fixture.path().join("remote"); - let home = fixture.path().join("home"); - let workspace = fixture.path().join("workspace"); - let bin = workspace.join("node_modules/.bin"); - let marker = fixture.path().join("helper-ran"); - std::fs::create_dir_all(&source).unwrap(); - std::fs::create_dir_all(&bin).unwrap(); - std::fs::create_dir(&home).unwrap(); - run_git(&source, &["init", "--quiet"]); - for name in ["git", "git-upload-pack", "git-remote-https"] { - write_executable_script( - &bin.join(name), - &format!("#!/bin/sh\nprintf ran > '{}'\nexit 1\n", marker.display()), - ); - } - let config = fixture.path().join("gitconfig"); - std::fs::write( - &config, - format!( - "[url \"file://{}\"]\n insteadOf = {OPENAI_PLUGINS_GIT_URL}\n", - source.display() - ), - ) - .unwrap(); - - for plugins in [vec!["gmail"], vec!["gmail", "linear"]] { - write_openai_curated_marketplace(&source, &plugins); - run_git(&source, &["add", "."]); - run_git( - &source, - &[ - "-c", - "user.name=Test", - "-c", - "user.email=test@example.com", - "commit", - "-qm", - "update", - ], - ); - let expected_sha = run_git(&source, &["rev-parse", "HEAD"]); - let output = Command::new(std::env::current_exe().unwrap()) - .args([ - "--exact", - "startup_sync::tests::pretrust_startup_sync_uses_installed_git_with_hostile_path", - "--nocapture", - ]) - .current_dir(&workspace) - .env(CHILD_HOME, &home) - .env("PATH", &bin) - .env("GIT_EXEC_PATH", &bin) - .env("GIT_CONFIG_GLOBAL", &config) - .env("GIT_CONFIG_SYSTEM", "/dev/null") - .env("HTTP_PROXY", "http://127.0.0.1:9") - .env("HTTPS_PROXY", "http://127.0.0.1:9") - .env("http_proxy", "http://127.0.0.1:9") - .env("https_proxy", "http://127.0.0.1:9") - .output() - .expect("join sync subprocess"); - assert!( - output.status.success(), - "{}\n{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); - assert_eq!( - read_curated_plugins_sha(&home), - Some( - String::from_utf8(expected_sha.stdout) - .unwrap() - .trim() - .to_string() - ) - ); - assert!(!marker.exists(), "sync executed a workspace helper"); - for plugin in plugins { - assert!( - curated_plugins_repo_path(&home) - .join(format!("plugins/{plugin}/.codex-plugin/plugin.json")) - .is_file() - ); - } - } -} - -#[tokio::test] -async fn github_http_routes_repository_ref_and_zipball_urls() { - let server = MockServer::start().await; - let sha = TEST_CURATED_PLUGIN_SHA; - let zipball = b"archive".to_vec(); - mount_github_repo_and_ref(&server, sha).await; - mount_github_zipball(&server, sha, zipball.clone()).await; - let api_base_url = server.uri(); - let repo_url = format!("{api_base_url}/repos/openai/plugins"); - let ref_url = format!("{repo_url}/git/ref/heads/main"); - let zipball_url = format!("{repo_url}/zipball/{sha}"); - let (http_clients, selected_urls) = RecordingHttpClientSelector::new(); - let http_clients = StartupSyncHttpClient::route_aware(http_clients); - - let remote_sha = fetch_curated_repo_remote_sha(&http_clients, &api_base_url) - .await - .expect("remote SHA request should succeed"); - let downloaded_zipball = fetch_curated_repo_zipball(&http_clients, &api_base_url, &remote_sha) - .await - .expect("zipball request should succeed"); - - assert_eq!(remote_sha, sha); - assert_eq!(downloaded_zipball, zipball); - assert_eq!( - recorded_http_client_urls(&selected_urls), - vec![repo_url, ref_url, zipball_url] - ); -} - -#[tokio::test] -async fn backup_archive_routes_metadata_and_backend_supplied_download_urls() { - let metadata_server = MockServer::start().await; - let download_server = MockServer::start().await; - let download_url = format!( - "{}/files/curated-plugins.zip?sig=signed", - download_server.uri() - ); - Mock::given(method("GET")) - .and(path("/backend-api/plugins/export/curated")) - .respond_with( - ResponseTemplate::new(200) - .set_body_json(serde_json::json!({"download_url": download_url.clone()})), - ) - .expect(1) - .mount(&metadata_server) - .await; - Mock::given(method("GET")) - .and(path("/files/curated-plugins.zip")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(b"archive".to_vec())) - .expect(1) - .mount(&download_server) - .await; - let metadata_url = format!( - "{}/backend-api/plugins/export/curated", - metadata_server.uri() - ); - let (http_clients, selected_urls) = RecordingHttpClientSelector::new(); - let http_clients = StartupSyncHttpClient::route_aware(http_clients); - - let body = fetch_curated_repo_backup_archive_zip(&http_clients, &metadata_url) - .await - .expect("backup archive download should succeed"); - - assert_eq!(body, b"archive"); - let controller = codex_http_client::NetworkPolicyController::default(); - let policy = controller.policy(); - let allowed_hosts = Default::default(); - controller.publish(policy.revision(), Restricted { allowed_hosts }); - let factory = crate::test_support::test_http_client_factory().with_network_policy(policy); - let clients = StartupSyncHttpClient::new(&factory); - for url in [&metadata_url, &download_url] { - let result = clients.request(Method::GET, url).send().await; - assert!(matches!(result, Err(Policy(Destination)))); - } - assert_eq!( - recorded_http_client_urls(&selected_urls), - vec![metadata_url, download_url] - ); -} - -#[test] -fn git_command_sanitizes_ambient_repository_environment() { - let command = git_command(Path::new("git")).expect("trusted Git command"); - - assert_eq!( - command.get_args().collect::>(), - [ - OsStr::new("-c"), - OsStr::new(codex_git_utils::SAFE_BARE_REPOSITORY_CONFIG), - ] - ); - - for name in REPOSITORY_LOCAL_GIT_ENVIRONMENT_VARIABLES { - assert_eq!( - command - .get_envs() - .find(|(key, _)| *key == OsStr::new(name)) - .map(|(_, value)| value), - Some(None), - "{name} should be removed from startup sync Git commands" - ); - } -} - -#[cfg(unix)] -#[test] -fn pretrust_git_sync_ignores_repository_local_transport_config() { - let fixture = tempdir().expect("tempdir"); - let codex_home = fixture.path().join("codex-home"); - let repository = fixture.path().join("untrusted-project"); - let marker = fixture.path().join("transport-config-ran"); - std::fs::create_dir_all(&codex_home).expect("create Codex home"); - std::fs::create_dir_all(&repository).expect("create repository"); - run_git(&repository, &["init", "--quiet"]); - - let transport = repository.join("synthetic-transport.sh"); - write_executable_script( - &transport, - &format!( - "#!/bin/sh\nprintf ran > '{}'\nprintf '{}\\tHEAD\\n'\n", - marker.display(), - TEST_CURATED_PLUGIN_SHA - ), - ); - run_git( - &repository, - &["config", "--local", "protocol.ext.allow", "always"], - ); - let rewrite_key = format!("url.ext::{} %S .insteadOf", transport.display()); - run_git( - &repository, - &["config", "--local", &rewrite_key, OPENAI_PLUGINS_GIT_URL], - ); - - let global_config = fixture.path().join("global-gitconfig"); - std::fs::write( - &global_config, - format!( - "[url \"file://{}/\"]\n\tinsteadOf = https://github.com/\n", - fixture.path().join("missing-remotes").display() - ), - ) - .expect("write global Git config"); - let git_wrapper = fixture.path().join("git-from-untrusted-repository.sh"); - write_executable_script( - &git_wrapper, - &format!( - "#!/bin/sh\ncd '{}' || exit 1\nGIT_CONFIG_GLOBAL='{}' GIT_CONFIG_SYSTEM=/dev/null GIT_TERMINAL_PROMPT=0 exec git \"$@\"\n", - repository.display(), - global_config.display() - ), - ); - - let err = sync_openai_plugins_repo_via_git(&codex_home, &git_wrapper) - .expect_err("isolated probe should use the missing global-config remote"); - - assert!(err.contains("git ls-remote curated plugins repo")); - assert!( - !marker.exists(), - "pre-trust sync must not execute repository-local transport configuration" - ); -} - -#[tokio::test] -async fn ordinary_clone_rejects_tracked_embedded_bare_repository() { - let temp_dir = tempdir().expect("create temporary directory"); - let source = temp_dir.path().join("source"); - let clone = temp_dir.path().join("clone"); - let nested_source = source.join("nested"); - std::fs::create_dir_all(nested_source.join("objects")).expect("create nested object directory"); - std::fs::create_dir_all(nested_source.join("refs")) - .expect("create nested references directory"); - - let run_setup_git = |cwd: &Path, args: &[&str]| { - let output = Command::new("git") - .args(args) - .current_dir(cwd) - .output() - .expect("run repository setup Git command"); - assert!( - output.status.success(), - "git {args:?} failed: {}", - String::from_utf8_lossy(&output.stderr) - ); - }; - - run_setup_git(&source, &["init", "--quiet"]); - std::fs::write(nested_source.join("HEAD"), "ref: refs/heads/main\n") - .expect("write tracked nested HEAD"); - std::fs::write( - nested_source.join("config"), - "[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tworktree = .\n\tfsmonitor = ./payload.sh\n", - ) - .expect("write tracked nested Git configuration"); - std::fs::write(nested_source.join("objects/.keep"), "").expect("track nested object directory"); - std::fs::write(nested_source.join("refs/.keep"), "") - .expect("track nested references directory"); - std::fs::write( - nested_source.join("payload.sh"), - "#!/bin/sh\nprintf ran > \"$0.ran\"\n", - ) - .expect("write tracked filesystem monitor"); - - run_setup_git(&source, &["add", "--all"]); - run_setup_git(&source, &["add", "--chmod=+x", "nested/payload.sh"]); - run_setup_git( - &source, - &[ - "-c", - "user.name=Codex Tests", - "-c", - "user.email=codex-tests@example.com", - "commit", - "--quiet", - "-m", - "track embedded Git repository", - ], - ); - let clone_output = Command::new("git") - .arg("clone") - .arg(&source) - .arg(&clone) - .output() - .expect("clone repository normally"); - assert!( - clone_output.status.success(), - "ordinary git clone failed: {}", - String::from_utf8_lossy(&clone_output.stderr) - ); - - let nested = clone.join("nested"); - let marker = nested.join("payload.sh.ran"); - let vulnerable = Command::new("git") - .args(["status", "--short"]) - .current_dir(&nested) - .output() - .expect("run unguarded Git against tracked embedded repository"); - assert!( - vulnerable.status.success(), - "unguarded Git should discover the tracked embedded repository: {}", - String::from_utf8_lossy(&vulnerable.stderr) - ); - assert!( - marker.exists(), - "unguarded Git should execute the tracked helper" - ); - std::fs::remove_file(&marker).expect("remove unguarded execution marker"); - - let guarded = git_command(Path::new("git")) - .expect("trusted Git command") - .args(["status", "--short"]) - .current_dir(&nested) - .output() - .expect("run guarded startup Git against tracked embedded repository"); - assert!( - !guarded.status.success(), - "startup Git should reject the repository" - ); - assert!( - !marker.exists(), - "startup Git must reject the repository before executing its helper" - ); - - let apply_error = codex_git_utils::apply_git_patch(&codex_git_utils::ApplyGitRequest { - cwd: nested.clone(), - diff: String::new(), - revert: false, - preflight: true, - }) - .expect_err("patch root discovery should reject the tracked embedded repository"); - assert!(apply_error.to_string().contains("not a git repository")); - assert!(codex_git_utils::collect_git_info(&nested).await.is_none()); - assert!(codex_git_utils::git_diff_to_remote(&nested).await.is_none()); - assert!( - !marker.exists(), - "Rust-owned Git inspection must not execute the tracked helper" - ); - - let explicit_git_dir = git_command(Path::new("git")) - .expect("trusted Git command") - .arg("--git-dir") - .arg(&nested) - .args(["rev-parse", "--git-dir"]) - .current_dir(&clone) - .output() - .expect("run Git with an explicitly selected bare repository"); - assert!( - explicit_git_dir.status.success(), - "--git-dir must continue to permit an explicitly selected repository: {}", - String::from_utf8_lossy(&explicit_git_dir.stderr) - ); - - let explicit_environment = Command::new("git") - .args(["-c", codex_git_utils::SAFE_BARE_REPOSITORY_CONFIG]) - .args(["rev-parse", "--git-dir"]) - .env("GIT_DIR", &nested) - .current_dir(&clone) - .output() - .expect("run Git with explicitly selected GIT_DIR"); - assert!( - explicit_environment.status.success(), - "GIT_DIR must continue to permit an explicitly selected repository: {}", - String::from_utf8_lossy(&explicit_environment.stderr) - ); -} - -fn write_file(path: &Path, contents: &str) { - std::fs::create_dir_all(path.parent().expect("file should have a parent")).unwrap(); - std::fs::write(path, contents).unwrap(); -} - -fn write_curated_plugin(root: &Path, plugin_name: &str) { - let plugin_root = root.join("plugins").join(plugin_name); - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - &format!(r#"{{"name":"{plugin_name}"}}"#), - ); -} - -fn write_openai_curated_marketplace(root: &Path, plugin_names: &[&str]) { - let plugins = plugin_names - .iter() - .map(|plugin_name| { - format!( - r#"{{ - "name": "{plugin_name}", - "source": {{ - "source": "local", - "path": "./plugins/{plugin_name}" - }} - }}"# - ) - }) - .collect::>() - .join(",\n"); - write_file( - &root.join(".agents/plugins/marketplace.json"), - &format!( - r#"{{ - "name": "openai-curated", - "plugins": [ -{plugins} - ] -}}"# - ), - ); - for plugin_name in plugin_names { - write_curated_plugin(root, plugin_name); - } -} - -fn write_curated_plugin_sha(codex_home: &Path) { - write_file( - &codex_home.join(".tmp/plugins.sha"), - &format!("{TEST_CURATED_PLUGIN_SHA}\n"), - ); -} - -fn has_plugins_clone_dirs(codex_home: &Path) -> bool { - let Ok(entries) = std::fs::read_dir(codex_home.join(".tmp")) else { - return false; - }; - - entries.flatten().any(|entry| { - let path = entry.path(); - path.is_dir() - && path - .file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.starts_with("plugins-clone-")) - }) -} - -#[cfg(unix)] -fn write_executable_script(path: &Path, contents: &str) { - codex_utils_cargo_bin::write_executable(path, contents).expect("write script"); -} - -#[cfg(unix)] -fn run_git(repo: &Path, args: &[&str]) -> std::process::Output { - let output = Command::new("git") - .arg("-C") - .arg(repo) - .args(args) - .output() - .expect("run git"); - assert!( - output.status.success(), - "git {args:?} failed: {}", - String::from_utf8_lossy(&output.stderr) - ); - output -} - -async fn mount_github_repo_and_ref(server: &MockServer, sha: &str) { - Mock::given(method("GET")) - .and(path("/repos/openai/plugins")) - .and(header_exists("user-agent")) - .and(header_exists("originator")) - .respond_with(ResponseTemplate::new(200).set_body_string(r#"{"default_branch":"main"}"#)) - .mount(server) - .await; - Mock::given(method("GET")) - .and(path("/repos/openai/plugins/git/ref/heads/main")) - .and(header_exists("user-agent")) - .and(header_exists("originator")) - .respond_with( - ResponseTemplate::new(200) - .set_body_string(format!(r#"{{"object":{{"sha":"{sha}"}}}}"#)), - ) - .mount(server) - .await; -} - -async fn mount_github_zipball(server: &MockServer, sha: &str, bytes: Vec) { - Mock::given(method("GET")) - .and(path(format!("/repos/openai/plugins/zipball/{sha}"))) - .and(header_exists("user-agent")) - .and(header_exists("originator")) - .respond_with( - ResponseTemplate::new(200) - .insert_header("content-type", "application/zip") - .set_body_bytes(bytes), - ) - .mount(server) - .await; -} - -async fn mount_export_archive(server: &MockServer, bytes: Vec) -> String { - let export_api_url = format!("{}/backend-api/plugins/export/curated", server.uri()); - Mock::given(method("GET")) - .and(path("/backend-api/plugins/export/curated")) - .and(header_exists("user-agent")) - .and(header_exists("originator")) - .respond_with(ResponseTemplate::new(200).set_body_string(format!( - r#"{{"download_url":"{}/files/curated-plugins.zip"}}"#, - server.uri() - ))) - .mount(server) - .await; - Mock::given(method("GET")) - .and(path("/files/curated-plugins.zip")) - .and(header_exists("user-agent")) - .and(header_exists("originator")) - .respond_with( - ResponseTemplate::new(200) - .insert_header("content-type", "application/zip") - .set_body_bytes(bytes), - ) - .mount(server) - .await; - export_api_url -} - -async fn run_sync_with_transport_overrides( - codex_home: PathBuf, - git_binary: impl Into, - api_base_url: impl Into, - backup_archive_api_url: impl Into, -) -> Result { - let git_binary = git_binary.into(); - let api_base_url = api_base_url.into(); - let backup_archive_api_url = backup_archive_api_url.into(); - tokio::task::spawn_blocking(move || { - let git_binary = PathBuf::from(git_binary); - sync_openai_plugins_repo_with_transport_overrides( - codex_home.as_path(), - Some(git_binary.as_path()), - &api_base_url, - &backup_archive_api_url, - &crate::test_support::test_http_client_factory(), - ) - }) - .await - .expect("sync task should join") -} - -async fn run_sync_without_git( - codex_home: PathBuf, - api_base_url: impl Into, - backup_archive_api_url: impl Into, -) -> Result { - let api_base_url = api_base_url.into(); - let backup_archive_api_url = backup_archive_api_url.into(); - tokio::task::spawn_blocking(move || { - sync_openai_plugins_repo_with_transport_overrides( - codex_home.as_path(), - /*git_binary*/ None, - &api_base_url, - &backup_archive_api_url, - &crate::test_support::test_http_client_factory(), - ) - }) - .await - .expect("sync task should join") -} - -async fn run_http_sync( - codex_home: PathBuf, - api_base_url: impl Into, -) -> Result { - let api_base_url = api_base_url.into(); - tokio::task::spawn_blocking(move || { - sync_openai_plugins_repo_via_http( - codex_home.as_path(), - &api_base_url, - &crate::test_support::test_http_client_factory(), - ) - }) - .await - .expect("sync task should join") -} - -fn assert_curated_gmail_repo(repo_path: &Path) { - assert!(repo_path.join(".agents/plugins/marketplace.json").is_file()); - assert!( - repo_path - .join("plugins/gmail/.codex-plugin/plugin.json") - .is_file() - ); -} - -#[test] -fn curated_plugins_repo_path_uses_codex_home_tmp_dir() { - let tmp = tempdir().expect("tempdir"); - assert_eq!( - curated_plugins_repo_path(tmp.path()), - tmp.path().join(".tmp/plugins") - ); -} - -#[test] -fn read_curated_plugins_sha_reads_trimmed_sha_file() { - let tmp = tempdir().expect("tempdir"); - std::fs::create_dir_all(tmp.path().join(".tmp")).expect("create tmp"); - std::fs::write(tmp.path().join(".tmp/plugins.sha"), "abc123\n").expect("write sha"); - - assert_eq!( - read_curated_plugins_sha(tmp.path()).as_deref(), - Some("abc123") - ); -} - -#[cfg(unix)] -#[test] -fn remove_stale_curated_repo_temp_dirs_removes_only_matching_directories() { - use std::os::unix::ffi::OsStrExt; - use std::time::SystemTime; - - fn set_dir_mtime(path: &Path, age: Duration) -> Result<(), Box> { - let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?; - let modified_at = now.saturating_sub(age); - let tv_sec = i64::try_from(modified_at.as_secs())?; - let ts = libc::timespec { tv_sec, tv_nsec: 0 }; - let times = [ts, ts]; - let c_path = std::ffi::CString::new(path.as_os_str().as_bytes())?; - let result = unsafe { libc::utimensat(libc::AT_FDCWD, c_path.as_ptr(), times.as_ptr(), 0) }; - if result != 0 { - return Err(std::io::Error::last_os_error().into()); - } - Ok(()) - } - - let tmp = tempdir().expect("tempdir"); - let parent = tmp.path().join(".tmp"); - let stale_clone_dir = parent.join("plugins-clone-stale"); - let fresh_clone_dir = parent.join("plugins-clone-fresh"); - let unrelated_dir = parent.join("plugins-cache"); - - std::fs::create_dir_all(&stale_clone_dir).expect("create stale clone dir"); - std::fs::create_dir_all(&fresh_clone_dir).expect("create fresh clone dir"); - std::fs::create_dir_all(&unrelated_dir).expect("create unrelated dir"); - set_dir_mtime( - &stale_clone_dir, - CURATED_PLUGINS_STALE_TEMP_DIR_MAX_AGE + Duration::from_secs(60), - ) - .expect("age stale clone dir"); - set_dir_mtime(&fresh_clone_dir, Duration::ZERO).expect("age fresh clone dir"); - - remove_stale_curated_repo_temp_dirs(&parent, CURATED_PLUGINS_STALE_TEMP_DIR_MAX_AGE); - - assert!(!stale_clone_dir.exists()); - assert!(fresh_clone_dir.is_dir()); - assert!(unrelated_dir.is_dir()); -} - -#[cfg(unix)] -#[test] -fn concurrent_syncs_serialize_fetches_without_skipping_remote_checks() { - let tmp = tempdir().expect("tempdir"); - let bin_dir = tempfile::Builder::new() - .prefix("fake-git-") - .tempdir() - .expect("tempdir"); - let git_path = bin_dir.path().join("git"); - let invocation_log = bin_dir.path().join("invocations.log"); - let sha = "0123456789abcdef0123456789abcdef01234567"; - - write_executable_script( - &git_path, - &format!( - r#"#!/bin/sh -if [ "$1" = "-c" ] && [ "$2" = "safe.bareRepository=explicit" ]; then shift 2; fi -printf '%s\n' "$*" >> '{}' -if [ "$1" = "ls-remote" ]; then - sleep 1 - printf '%s\tHEAD\n' "{sha}" - exit 0 -fi -if [ "$1" = "-C" ] && [ "$3" = "init" ]; then - mkdir -p "$2/.git" - exit 0 -fi -if [ "$1" = "-C" ] && [ "$3" = "fetch" ]; then - exit 0 -fi -if [ "$1" = "-C" ] && [ "$3" = "reset" ]; then - mkdir -p "$2/.agents/plugins" "$2/plugins/gmail/.codex-plugin" - cat > "$2/.agents/plugins/marketplace.json" <<'EOF' -{{"name":"openai-curated","plugins":[{{"name":"gmail","source":{{"source":"local","path":"./plugins/gmail"}}}}]}} -EOF - printf '%s\n' '{{"name":"gmail"}}' > "$2/plugins/gmail/.codex-plugin/plugin.json" - exit 0 -fi -if [ "$1" = "-C" ] && [ "$3" = "clean" ]; then - exit 0 -fi -if [ "$1" = "-C" ] && [ "$3" = "rev-parse" ] && [ "$4" = "HEAD" ]; then - printf '%s\n' "{sha}" - exit 0 -fi -echo "unexpected git invocation: $@" >&2 -exit 1 -"#, - invocation_log.display() - ), - ); - - let barrier = Barrier::new(2); - let results = std::thread::scope(|scope| { - let run_sync = || { - barrier.wait(); - sync_openai_plugins_repo_with_transport_overrides( - tmp.path(), - Some(git_path.as_path()), - "http://127.0.0.1:9", - "http://127.0.0.1:9/backend-api/plugins/export/curated", - &crate::test_support::test_http_client_factory(), - ) - }; - let first = scope.spawn(run_sync); - let second = scope.spawn(run_sync); - [ - first.join().expect("first sync thread"), - second.join().expect("second sync thread"), - ] - }); - - assert_eq!(results, [Ok(sha.to_string()), Ok(sha.to_string())]); - let repo_path = curated_plugins_repo_path(tmp.path()); - assert!(repo_path.join(".git").is_dir()); - assert_curated_gmail_repo(&repo_path); - assert_eq!(read_curated_plugins_sha(tmp.path()).as_deref(), Some(sha)); - let invocations = std::fs::read_to_string(invocation_log).expect("read invocation log"); - assert_eq!( - invocations - .lines() - .filter(|invocation| invocation.starts_with("ls-remote ")) - .count(), - 2 - ); - assert_eq!( - invocations - .lines() - .filter(|invocation| invocation.contains(" fetch --depth 1 --no-tags ")) - .count(), - 1 - ); - assert!( - !invocations - .lines() - .any(|invocation| invocation.split_whitespace().any(|arg| arg == "clone")) - ); -} - -#[cfg(unix)] -#[test] -fn sync_openai_plugins_repo_via_git_succeeds_with_local_rewritten_remote() { - let tmp = tempdir().expect("tempdir"); - let repo_root = tempfile::Builder::new() - .prefix("curated-repo-success-") - .tempdir() - .expect("tempdir"); - let work_repo = repo_root.path().join("work/plugins"); - let remote_repo = repo_root.path().join("remotes/openai/plugins.git"); - std::fs::create_dir_all(work_repo.join(".agents/plugins")).expect("create marketplace dir"); - std::fs::create_dir_all(work_repo.join("plugins/gmail/.codex-plugin")) - .expect("create plugin dir"); - std::fs::write( - work_repo.join(".agents/plugins/marketplace.json"), - r#"{"name":"openai-curated","plugins":[{"name":"gmail","source":{"source":"local","path":"./plugins/gmail"}}]}"#, - ) - .expect("write marketplace"); - std::fs::write( - work_repo.join("plugins/gmail/.codex-plugin/plugin.json"), - r#"{"name":"gmail"}"#, - ) - .expect("write plugin manifest"); - - run_git(&work_repo, &["init"]); - run_git(&work_repo, &["add", "."]); - run_git( - &work_repo, - &[ - "-c", - "user.name=Codex Test", - "-c", - "user.email=codex@example.com", - "commit", - "-m", - "init", - ], - ); - - std::fs::create_dir_all(remote_repo.parent().expect("remote parent")) - .expect("create remote parent"); - let clone_status = Command::new("git") - .arg("clone") - .arg("--bare") - .arg(&work_repo) - .arg(&remote_repo) - .status() - .expect("run git clone --bare"); - assert!(clone_status.success()); - - let sha_output = run_git(&work_repo, &["rev-parse", "HEAD"]); - let sha = String::from_utf8_lossy(&sha_output.stdout) - .trim() - .to_string(); - - let git_config_path = repo_root.path().join("git-rewrite.conf"); - std::fs::write( - &git_config_path, - format!( - "[url \"file://{}/\"]\n insteadOf = https://github.com/\n", - repo_root.path().join("remotes").display() - ), - ) - .expect("write git config"); - - let bin_dir = tempfile::Builder::new() - .prefix("git-rewrite-wrapper-") - .tempdir() - .expect("tempdir"); - let git_wrapper = bin_dir.path().join("git"); - let invocation_log = bin_dir.path().join("invocations.log"); - write_executable_script( - &git_wrapper, - &format!( - "#!/bin/sh\nprintf '%s\\n' \"$*\" >> '{}'\nGIT_CONFIG_GLOBAL='{}' exec git \"$@\"\n", - invocation_log.display(), - git_config_path.display() - ), - ); - - let synced_sha = sync_openai_plugins_repo_via_git(tmp.path(), &git_wrapper) - .expect("git sync should succeed"); - - assert_eq!(synced_sha, sha); - assert_curated_gmail_repo(&curated_plugins_repo_path(tmp.path())); - assert_eq!( - read_curated_plugins_sha(tmp.path()).as_deref(), - Some(sha.as_str()) - ); - assert!(!has_plugins_clone_dirs(tmp.path())); - - let first_sync_invocation_count = std::fs::read_to_string(&invocation_log) - .expect("read first sync invocations") - .lines() - .count(); - let first_sync_invocations = - std::fs::read_to_string(&invocation_log).expect("read first sync invocations"); - assert!( - first_sync_invocations - .lines() - .any(|invocation| invocation.contains(" fetch --depth 1 --no-tags ")) - ); - assert!( - !first_sync_invocations - .lines() - .any(|invocation| invocation.split_whitespace().any(|arg| arg == "clone")) - ); - write_openai_curated_marketplace(&work_repo, &["gmail", "linear"]); - run_git(&work_repo, &["add", "."]); - run_git( - &work_repo, - &[ - "-c", - "user.name=Codex Test", - "-c", - "user.email=codex@example.com", - "commit", - "-m", - "update", - ], - ); - let branch_output = run_git(&work_repo, &["symbolic-ref", "--short", "HEAD"]); - let branch = String::from_utf8_lossy(&branch_output.stdout) - .trim() - .to_string(); - let remote_repo = remote_repo.to_str().expect("utf8 remote repo"); - let push_ref = format!("HEAD:refs/heads/{branch}"); - run_git(&work_repo, &["push", remote_repo, &push_ref]); - let updated_sha_output = run_git(&work_repo, &["rev-parse", "HEAD"]); - let updated_sha = String::from_utf8_lossy(&updated_sha_output.stdout) - .trim() - .to_string(); - - let synced_sha = sync_openai_plugins_repo_via_git(tmp.path(), &git_wrapper) - .expect("incremental git sync should succeed"); - - assert_eq!(synced_sha, updated_sha); - assert!( - curated_plugins_repo_path(tmp.path()) - .join("plugins/linear/.codex-plugin/plugin.json") - .is_file() - ); - assert_eq!( - read_curated_plugins_sha(tmp.path()).as_deref(), - Some(updated_sha.as_str()) - ); - assert!( - !curated_plugins_repo_path(tmp.path()) - .join(".git/objects/info/alternates") - .exists() - ); - let invocation_log_contents = - std::fs::read_to_string(&invocation_log).expect("read sync invocations"); - let incremental_sync_invocations = invocation_log_contents - .lines() - .skip(first_sync_invocation_count) - .collect::>(); - let curated_repo_path = curated_plugins_repo_path(tmp.path()); - assert!(incremental_sync_invocations.iter().any(|invocation| { - invocation.contains(&format!(" -C {} fetch ", curated_repo_path.display())) - && invocation.contains(" https://github.com/openai/plugins.git ") - && invocation.contains(updated_sha.as_str()) - && invocation.ends_with(CURATED_PLUGINS_FETCH_REF) - })); - assert!(incremental_sync_invocations.iter().any(|invocation| { - invocation.contains(" fetch --depth 1 --no-tags ") - && invocation.contains(&format!(" {} ", curated_repo_path.display())) - && invocation.ends_with(&format!( - "{CURATED_PLUGINS_FETCH_REF}:{CURATED_PLUGINS_FETCH_REF}" - )) - })); - assert!( - incremental_sync_invocations - .iter() - .any(|invocation| invocation.ends_with(" init")) - ); - assert!( - !incremental_sync_invocations - .iter() - .any(|invocation| invocation.split_whitespace().any(|arg| arg == "clone")) - ); - assert!(!incremental_sync_invocations.iter().any(|invocation| { - invocation.contains(&format!(" -C {} reset ", curated_repo_path.display())) - || invocation.contains(&format!(" -C {} clean ", curated_repo_path.display())) - })); - assert!(!has_plugins_clone_dirs(tmp.path())); - - let unchanged_sync_invocation_count = invocation_log_contents.lines().count(); - let synced_sha = sync_openai_plugins_repo_via_git(tmp.path(), &git_wrapper) - .expect("unchanged git sync should succeed"); - - assert_eq!(synced_sha, updated_sha); - let invocation_log = std::fs::read_to_string(&invocation_log).expect("read sync invocations"); - let unchanged_sync_invocations = invocation_log - .lines() - .skip(unchanged_sync_invocation_count) - .collect::>(); - assert!( - unchanged_sync_invocations - .iter() - .any(|invocation| invocation.contains(" ls-remote ")) - ); - assert!( - !unchanged_sync_invocations - .iter() - .any(|invocation| invocation.contains(" fetch ")) - ); -} - -#[tokio::test] -async fn sync_openai_plugins_repo_falls_back_to_http_when_git_is_unavailable() { - let tmp = tempdir().expect("tempdir"); - let server = MockServer::start().await; - let sha = "0123456789abcdef0123456789abcdef01234567"; - - mount_github_repo_and_ref(&server, sha).await; - mount_github_zipball(&server, sha, curated_repo_zipball_bytes(sha)).await; - - let synced_sha = run_sync_with_transport_overrides( - tmp.path().to_path_buf(), - "missing-git-for-test", - server.uri(), - "http://127.0.0.1:9/backend-api/plugins/export/curated", - ) - .await - .expect("fallback sync should succeed"); - - let repo_path = curated_plugins_repo_path(tmp.path()); - assert_eq!(synced_sha, sha); - assert_curated_gmail_repo(&repo_path); - assert_eq!(read_curated_plugins_sha(tmp.path()).as_deref(), Some(sha)); -} - -#[tokio::test] -async fn sync_openai_plugins_repo_uses_http_without_git_transport() { - let tmp = tempdir().expect("tempdir"); - let server = MockServer::start().await; - let sha = "0123456789abcdef0123456789abcdef01234567"; - - mount_github_repo_and_ref(&server, sha).await; - mount_github_zipball(&server, sha, curated_repo_zipball_bytes(sha)).await; - - let synced_sha = run_sync_without_git( - tmp.path().to_path_buf(), - server.uri(), - "http://127.0.0.1:9/backend-api/plugins/export/curated", - ) - .await - .expect("HTTP sync should succeed"); - - assert_eq!(synced_sha, sha); - assert_curated_gmail_repo(&curated_plugins_repo_path(tmp.path())); -} - -#[cfg(unix)] -#[tokio::test] -async fn sync_openai_plugins_repo_falls_back_to_http_when_git_sync_fails() { - let tmp = tempdir().expect("tempdir"); - let bin_dir = tempfile::Builder::new() - .prefix("fake-git-fail-") - .tempdir() - .expect("tempdir"); - let git_path = bin_dir.path().join("git"); - let sha = "0123456789abcdef0123456789abcdef01234567"; - - write_executable_script( - &git_path, - r#"#!/bin/sh -echo "simulated git failure" >&2 -exit 1 -"#, - ); - - let server = MockServer::start().await; - mount_github_repo_and_ref(&server, sha).await; - mount_github_zipball(&server, sha, curated_repo_zipball_bytes(sha)).await; - - let synced_sha = run_sync_with_transport_overrides( - tmp.path().to_path_buf(), - git_path.to_str().expect("utf8 path"), - server.uri(), - "http://127.0.0.1:9/backend-api/plugins/export/curated", - ) - .await - .expect("fallback sync should succeed"); - - let repo_path = curated_plugins_repo_path(tmp.path()); - assert_eq!(synced_sha, sha); - assert_curated_gmail_repo(&repo_path); - assert_eq!(read_curated_plugins_sha(tmp.path()).as_deref(), Some(sha)); -} - -#[cfg(unix)] -#[test] -fn sync_openai_plugins_repo_via_git_cleans_up_staged_dir_on_fetch_failure() { - let tmp = tempdir().expect("tempdir"); - let bin_dir = tempfile::Builder::new() - .prefix("fake-git-partial-fail-") - .tempdir() - .expect("tempdir"); - let git_path = bin_dir.path().join("git"); - let sha = "0123456789abcdef0123456789abcdef01234567"; - - write_executable_script( - &git_path, - &format!( - r#"#!/bin/sh -if [ "$1" = "-c" ] && [ "$2" = "safe.bareRepository=explicit" ]; then shift 2; fi -if [ "$1" = "ls-remote" ]; then - printf '%s\tHEAD\n' "{sha}" - exit 0 -fi -if [ "$1" = "-C" ] && [ "$3" = "init" ]; then - mkdir -p "$2/.git" - exit 0 -fi -if [ "$1" = "-C" ] && [ "$3" = "fetch" ]; then - echo "fatal: early EOF" >&2 - exit 128 -fi -echo "unexpected git invocation: $@" >&2 -exit 1 -"# - ), - ); - - let err = - sync_openai_plugins_repo_via_git(tmp.path(), &git_path).expect_err("git sync should fail"); - - assert!(err.contains("fatal: early EOF")); - assert!(!has_plugins_clone_dirs(tmp.path())); -} - -#[cfg(unix)] -#[test] -fn sync_openai_plugins_repo_via_git_preserves_existing_snapshot_on_validation_failure() { - let tmp = tempdir().expect("tempdir"); - let repo_path = curated_plugins_repo_path(tmp.path()); - write_openai_curated_marketplace(&repo_path, &["gmail"]); - std::fs::create_dir_all(repo_path.join(".git")).expect("create git dir"); - write_curated_plugin_sha(tmp.path()); - - let bin_dir = tempfile::Builder::new() - .prefix("fake-git-invalid-update-") - .tempdir() - .expect("tempdir"); - let git_path = bin_dir.path().join("git"); - let remote_sha = "fedcba9876543210fedcba9876543210fedcba98"; - - write_executable_script( - &git_path, - &format!( - r#"#!/bin/sh -if [ "$1" = "-c" ] && [ "$2" = "safe.bareRepository=explicit" ]; then shift 2; fi -if [ "$1" = "ls-remote" ]; then - printf '%s\tHEAD\n' "{remote_sha}" - exit 0 -fi -if [ "$1" = "-C" ] && [ "$2" = "{}" ] && [ "$3" = "rev-parse" ]; then - printf '%s\n' "{TEST_CURATED_PLUGIN_SHA}" - exit 0 -fi -if [ "$1" = "-C" ] && [ "$2" = "{}" ] && [ "$3" = "fetch" ]; then - exit 0 -fi -if [ "$1" = "-C" ] && [ "$3" = "init" ]; then - mkdir -p "$2/.git" - exit 0 -fi -if [ "$1" = "-C" ] && [ "$3" = "fetch" ]; then - exit 0 -fi -if [ "$1" = "-C" ] && [ "$3" = "reset" ]; then - mkdir -p "$2/plugins/linear/.codex-plugin" - printf '%s\n' '{{"name":"linear"}}' > "$2/plugins/linear/.codex-plugin/plugin.json" - exit 0 -fi -if [ "$1" = "-C" ] && [ "$3" = "clean" ]; then - exit 0 -fi -if [ "$1" = "-C" ] && [ "$3" = "rev-parse" ]; then - printf '%s\n' "{remote_sha}" - exit 0 -fi -echo "unexpected git invocation: $@" >&2 -exit 1 -"#, - repo_path.display(), - repo_path.display(), - ), - ); - - let err = sync_openai_plugins_repo_via_git(tmp.path(), &git_path) - .expect_err("invalid staged checkout should fail"); - - assert!(err.contains("curated plugins archive missing marketplace manifest")); - assert_curated_gmail_repo(&repo_path); - assert!(!repo_path.join("plugins/linear").exists()); - assert_eq!( - read_curated_plugins_sha(tmp.path()).as_deref(), - Some(TEST_CURATED_PLUGIN_SHA) - ); - assert!(!has_plugins_clone_dirs(tmp.path())); -} - -#[tokio::test] -async fn sync_openai_plugins_repo_via_http_cleans_up_staged_dir_on_extract_failure() { - let tmp = tempdir().expect("tempdir"); - let server = MockServer::start().await; - let sha = "0123456789abcdef0123456789abcdef01234567"; - - mount_github_repo_and_ref(&server, sha).await; - mount_github_zipball(&server, sha, b"not a zip archive".to_vec()).await; - - let err = run_http_sync(tmp.path().to_path_buf(), server.uri()) - .await - .expect_err("http sync should fail"); - - assert!(err.contains("failed to open curated plugins zip archive")); - assert!(!has_plugins_clone_dirs(tmp.path())); -} - -/// Plugin executables keep their access permissions, but not setuid, setgid, or sticky bits. -#[cfg(unix)] -#[test] -fn extract_zipball_preserves_only_unix_access_permissions() { - use std::io::Cursor; - use std::os::unix::fs::PermissionsExt; - - let destination = tempdir().expect("tempdir"); - let mut archive = ZipWriter::new(Cursor::new(Vec::new())); - // unix_permissions() strips special bits on write; encode the untrusted mode directly. - let options = SimpleFileOptions::default().external_attributes(0o107755 << 16); - archive - .start_file("repo/script", options) - .expect("add script"); - let bytes = archive.finish().expect("finish archive").into_inner(); - - extract_zipball_to_dir(&bytes, destination.path()).expect("extract archive"); - - let script = std::fs::metadata(destination.path().join("script")).expect("script metadata"); - assert_eq!(script.permissions().mode() & 0o7777, 0o755); -} - -#[tokio::test] -async fn sync_openai_plugins_repo_skips_archive_download_when_sha_matches() { - let tmp = tempdir().expect("tempdir"); - let repo_path = curated_plugins_repo_path(tmp.path()); - std::fs::create_dir_all(repo_path.join(".agents/plugins")).expect("create repo"); - std::fs::write( - repo_path.join(".agents/plugins/marketplace.json"), - r#"{"name":"openai-curated","plugins":[]}"#, - ) - .expect("write marketplace"); - std::fs::create_dir_all(tmp.path().join(".tmp")).expect("create tmp"); - let sha = "fedcba9876543210fedcba9876543210fedcba98"; - std::fs::write(tmp.path().join(".tmp/plugins.sha"), format!("{sha}\n")).expect("write sha"); - - let server = MockServer::start().await; - mount_github_repo_and_ref(&server, sha).await; - - run_sync_with_transport_overrides( - tmp.path().to_path_buf(), - "missing-git-for-test", - server.uri(), - "http://127.0.0.1:9/backend-api/plugins/export/curated", - ) - .await - .expect("sync should succeed"); - - assert_eq!(read_curated_plugins_sha(tmp.path()).as_deref(), Some(sha)); - assert!(repo_path.join(".agents/plugins/marketplace.json").is_file()); -} - -#[tokio::test] -async fn sync_openai_plugins_repo_falls_back_to_export_archive_when_no_snapshot_exists() { - let tmp = tempdir().expect("tempdir"); - let server = MockServer::start().await; - let export_sha = "1111111111111111111111111111111111111111"; - - Mock::given(method("GET")) - .and(path("/repos/openai/plugins")) - .respond_with(ResponseTemplate::new(500).set_body_string("github repo lookup failed")) - .mount(&server) - .await; - let export_api_url = - mount_export_archive(&server, curated_repo_backup_archive_zip_bytes(export_sha)).await; - - let synced_sha = run_sync_with_transport_overrides( - tmp.path().to_path_buf(), - "missing-git-for-test", - server.uri(), - export_api_url, - ) - .await - .expect("export fallback sync should succeed"); - - let repo_path = curated_plugins_repo_path(tmp.path()); - assert_eq!(synced_sha, export_sha); - assert_curated_gmail_repo(&repo_path); - assert_eq!( - read_curated_plugins_sha(tmp.path()).as_deref(), - Some(export_sha) - ); -} - -#[tokio::test] -async fn sync_openai_plugins_repo_skips_export_archive_when_snapshot_exists() { - let tmp = tempdir().expect("tempdir"); - let curated_root = curated_plugins_repo_path(tmp.path()); - write_openai_curated_marketplace(&curated_root, &["linear"]); - write_curated_plugin_sha(tmp.path()); - - let plugin_manifest_path = curated_root.join("plugins/linear/.codex-plugin/plugin.json"); - let original_manifest = - std::fs::read_to_string(&plugin_manifest_path).expect("read existing plugin manifest"); - - let server = MockServer::start().await; - - Mock::given(method("GET")) - .and(path("/repos/openai/plugins")) - .respond_with(ResponseTemplate::new(500).set_body_string("github repo lookup failed")) - .mount(&server) - .await; - let export_api_url = mount_export_archive( - &server, - curated_repo_backup_archive_zip_bytes("2222222222222222222222222222222222222222"), - ) - .await; - - let err = run_sync_with_transport_overrides( - tmp.path().to_path_buf(), - "missing-git-for-test", - server.uri(), - export_api_url, - ) - .await - .expect_err("existing snapshot should suppress export fallback"); - - assert!(err.contains("export archive fallback skipped")); - assert_eq!( - std::fs::read_to_string(&plugin_manifest_path).expect("read plugin manifest after sync"), - original_manifest - ); - assert_eq!( - read_curated_plugins_sha(tmp.path()).as_deref(), - Some(TEST_CURATED_PLUGIN_SHA) - ); -} - -#[test] -fn read_extracted_backup_archive_git_sha_reads_head_ref_from_extracted_repo() { - let tmp = tempdir().expect("tempdir"); - let git_dir = tmp.path().join(".git/refs/heads"); - std::fs::create_dir_all(&git_dir).expect("create git ref dir"); - std::fs::write(tmp.path().join(".git/HEAD"), "ref: refs/heads/main\n").expect("write HEAD"); - std::fs::write( - git_dir.join("main"), - "3333333333333333333333333333333333333333\n", - ) - .expect("write main ref"); - - assert_eq!( - read_extracted_backup_archive_git_sha(tmp.path()) - .expect("read extracted backup archive git sha"), - Some("3333333333333333333333333333333333333333".to_string()) - ); -} - -#[test] -fn read_extracted_backup_archive_git_sha_rejects_non_refs_head_target() { - let tmp = tempdir().expect("tempdir"); - std::fs::create_dir_all(tmp.path().join(".git")).expect("create git dir"); - std::fs::write(tmp.path().join(".git/HEAD"), "ref: HEAD\n").expect("write HEAD"); - - let err = read_extracted_backup_archive_git_sha(tmp.path()) - .expect_err("non-refs target should be rejected"); - - assert!(err.contains("must stay under refs/")); -} - -#[test] -fn read_extracted_backup_archive_git_sha_rejects_path_traversal_ref() { - let tmp = tempdir().expect("tempdir"); - std::fs::create_dir_all(tmp.path().join(".git")).expect("create git dir"); - std::fs::write(tmp.path().join(".git/HEAD"), "ref: refs/heads/../../evil\n") - .expect("write HEAD"); - - let err = read_extracted_backup_archive_git_sha(tmp.path()) - .expect_err("path traversal ref should be rejected"); - - assert!(err.contains("invalid path components")); -} - -fn curated_repo_zipball_bytes(sha: &str) -> Vec { - let cursor = std::io::Cursor::new(Vec::new()); - let mut writer = ZipWriter::new(cursor); - let options = SimpleFileOptions::default(); - let root = format!("openai-plugins-{sha}"); - writer - .start_file(format!("{root}/.agents/plugins/marketplace.json"), options) - .expect("start marketplace entry"); - writer - .write_all( - br#"{ - "name": "openai-curated", - "plugins": [ - { - "name": "gmail", - "source": { - "source": "local", - "path": "./plugins/gmail" - } - } - ] -}"#, - ) - .expect("write marketplace"); - writer - .start_file( - format!("{root}/plugins/gmail/.codex-plugin/plugin.json"), - options, - ) - .expect("start plugin manifest entry"); - writer - .write_all(br#"{"name":"gmail"}"#) - .expect("write plugin manifest"); - - writer.finish().expect("finish zip writer").into_inner() -} - -fn curated_repo_backup_archive_zip_bytes(sha: &str) -> Vec { - let cursor = std::io::Cursor::new(Vec::new()); - let mut writer = ZipWriter::new(cursor); - let options = SimpleFileOptions::default(); - - writer - .start_file("plugins/.git/HEAD", options) - .expect("start HEAD entry"); - writer - .write_all(b"ref: refs/heads/main\n") - .expect("write HEAD"); - writer - .start_file("plugins/.git/refs/heads/main", options) - .expect("start main ref entry"); - writer - .write_all(format!("{sha}\n").as_bytes()) - .expect("write main ref"); - writer - .start_file("plugins/.agents/plugins/marketplace.json", options) - .expect("start marketplace entry"); - writer - .write_all( - br#"{ - "name": "openai-curated", - "plugins": [ - { - "name": "gmail", - "source": { - "source": "local", - "path": "./plugins/gmail" - } - } - ] -}"#, - ) - .expect("write marketplace"); - writer - .start_file("plugins/plugins/gmail/.codex-plugin/plugin.json", options) - .expect("start plugin manifest entry"); - writer - .write_all(br#"{"name":"gmail"}"#) - .expect("write plugin manifest"); - - writer.finish().expect("finish zip writer").into_inner() -} diff --git a/codex-rs/feedback/src/feedback_event_tests.rs b/codex-rs/feedback/src/feedback_event_tests.rs index 49bf41cd..393201e8 100644 --- a/codex-rs/feedback/src/feedback_event_tests.rs +++ b/codex-rs/feedback/src/feedback_event_tests.rs @@ -1,28 +1,11 @@ //! Feedback event contracts for titles, report grouping, and lossless comment bodies. use crate::CodexFeedback; -use crate::FeedbackUploadOptions; -use crate::UPLOAD_TIMEOUT; -use codex_http_client::HttpClientFactory; -use codex_http_client::OutboundProxyPolicy; -use flate2::read::GzDecoder; -use http::StatusCode; use pretty_assertions::assert_eq; use sentry::protocol::Event; use sentry::protocol::Exception; use sentry::protocol::Level; -use sentry::protocol::Value; -use sentry::protocol::Values; -use sentry::protocol::value::to_value; use std::collections::BTreeMap; -use std::io::Read; -use std::time::Instant; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; #[test] fn custom_titles_preserve_comments_and_keep_submissions_separate() { @@ -178,79 +161,3 @@ fn reason_tag_previews_preserve_full_comments_in_the_exception() { ); } } - -#[tokio::test] -async fn feedback_upload_sends_safe_reason_tag_and_full_comment() { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/42/envelope/")) - .and(header("Content-Encoding", "gzip")) - .respond_with(ResponseTemplate::new(StatusCode::OK)) - .expect(/*r*/ 1) - .mount(&server) - .await; - - let snapshot = CodexFeedback::new().snapshot(/*session_id*/ None); - let reason = format!("first\r\nsecond\n{}tail", "界🌍".repeat(120)); - let tags = BTreeMap::from([("reason".to_string(), "caller override\n".to_string())]); - snapshot - .upload_feedback_with_dsn( - FeedbackUploadOptions { - classification: "bug", - reason: Some(&reason), - tags: Some(&tags), - include_logs: false, - extra_attachments: Vec::new(), - extra_attachment_paths: &[], - session_source: None, - logs_override: None, - }, - &HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - &format!("http://public@{}/42", server.address()), - Instant::now() + UPLOAD_TIMEOUT, - ) - .await - .unwrap(); - - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 1); - let mut decoded = Vec::new(); - GzDecoder::new(requests[0].body.as_slice()) - .read_to_end(&mut decoded) - .unwrap(); - // The first two envelope lines are its header and the event item header. - let payload = std::str::from_utf8(&decoded) - .unwrap() - .splitn(/*n*/ 3, '\n') - .nth(/*n*/ 2) - .unwrap(); - let event: Value = payload.parse().unwrap(); - assert_eq!( - event["tags"]["reason"].as_str().unwrap().chars().count(), - 200 - ); - let title = format!("[Bug]: Codex session {}", snapshot.thread_id); - let expected_tags = to_value(BTreeMap::from([ - ("thread_id".to_string(), snapshot.thread_id), - ("classification".to_string(), "bug".to_string()), - ( - "cli_version".to_string(), - env!("CARGO_PKG_VERSION").to_string(), - ), - ( - "reason".to_string(), - format!("first second {}", "界🌍".repeat(93)), - ), - ])) - .unwrap(); - let expected_exception = to_value(Values::from(vec![Exception { - ty: title, - value: Some(reason), - ..Default::default() - }])) - .unwrap(); - assert_eq!( - (&event["tags"], &event["exception"]), - (&expected_tags, &expected_exception) - ); -} diff --git a/codex-rs/feedback/src/lib_tests.rs b/codex-rs/feedback/src/lib_tests.rs index 9e21368d..f11620fa 100644 --- a/codex-rs/feedback/src/lib_tests.rs +++ b/codex-rs/feedback/src/lib_tests.rs @@ -4,27 +4,14 @@ use std::ffi::OsStr; use std::fs; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; -use std::time::Duration; use super::*; use crate::FeedbackDiagnostic; use codex_http_client::OutboundProxyPolicy; -use flate2::Compression; -use flate2::read::GzDecoder; -use flate2::write::GzEncoder; -use http::StatusCode; use pretty_assertions::assert_eq; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; -use wiremock::Mock; use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::header_exists; -use wiremock::matchers::method; -use wiremock::matchers::path; #[test] fn ring_buffer_drops_front_when_full() { @@ -133,462 +120,17 @@ async fn upload_test_feedback( .await } +// aKode: feedback is never uploaded; the upload path fails without sending any request. #[tokio::test] -async fn feedback_upload_allows_slow_reports() { +async fn feedback_upload_is_disabled_and_sends_nothing() { let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/42/envelope/")) - .respond_with( - ResponseTemplate::new(StatusCode::OK).set_delay(Duration::from_secs(/*secs*/ 4)), - ) - .expect(/*r*/ 3) - .mount(&server) - .await; - - let dsn = format!("http://public@{}/42", server.address()); - let attachment = FeedbackAttachment { - filename: "later.txt".to_string(), - content_type: None, - buffer: b"later diagnostic".to_vec(), - }; - upload_test_feedback(&CodexFeedback::new(), &dsn, vec![attachment]) - .await - .expect("all three envelopes should finish across twelve seconds of network waits"); -} - -#[tokio::test] -async fn feedback_upload_deadline_stops_retries_and_later_attachments() { - let server = MockServer::start().await; - let attempt = AtomicUsize::default(); - Mock::given(method("POST")) - .and(path("/api/42/envelope/")) - .respond_with(move |_: &wiremock::Request| { - match attempt.fetch_add(/*val*/ 1, Ordering::SeqCst) { - 0 | 2 => ResponseTemplate::new(StatusCode::OK) - .set_delay(Duration::from_secs(/*secs*/ 1)), - 1 => ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE) - .set_delay(Duration::from_secs(/*secs*/ 1)), - _ => ResponseTemplate::new(StatusCode::OK) - .set_delay(Duration::from_secs(/*secs*/ 20)), - } - }) - .expect(/*r*/ 4) - .mount(&server) - .await; - - let dsn = format!("http://public@{}/42", server.address()); - let attachments = ["stalled.txt", "later.txt"].map(|filename| FeedbackAttachment { - filename: filename.to_string(), - content_type: None, - buffer: filename.as_bytes().to_vec(), - }); - let snapshot = CodexFeedback::new() - .snapshot(/*session_id*/ None) - .with_feedback_diagnostics(FeedbackDiagnostics::default()); - let error = tokio::time::timeout( - Duration::from_secs(/*secs*/ 10), - snapshot.upload_feedback_with_dsn( - FeedbackUploadOptions { - classification: "bug", - reason: None, - tags: None, - include_logs: true, - extra_attachments: attachments.into(), - extra_attachment_paths: &[], - session_source: Some(SessionSource::Cli), - logs_override: Some(b"log contents".to_vec()), - }, - &HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - &dsn, - Instant::now() + Duration::from_secs(/*secs*/ 8), - ), - ) - .await - .expect("each request must use only the time left in the report deadline") - .expect_err("the accepted report must report incomplete attachments"); - assert_eq!( - error.to_string(), - "feedback report was accepted, but some attachments failed to upload" - ); - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 4); - assert_eq!(requests[1].body, requests[2].body); -} - -#[tokio::test] -async fn feedback_upload_retries_diagnostics_without_replaying_core() { - let server = MockServer::start().await; - let attempt = AtomicUsize::default(); - Mock::given(method("POST")) - .and(path("/api/42/envelope/")) - .and(header_exists("X-Sentry-Auth")) - .and(header("Content-Encoding", "gzip")) - .respond_with(move |_: &wiremock::Request| { - match attempt.fetch_add(/*val*/ 1, Ordering::SeqCst) { - // Accept the core once; accept logs only on their second attempt. - 0 => ResponseTemplate::new(StatusCode::OK).insert_header( - "X-Sentry-Rate-Limits", - "0:attachment:project,60:transaction:project", - ), - 2 => ResponseTemplate::new(StatusCode::OK).insert_header("Retry-After", "0"), - 6 => ResponseTemplate::new(StatusCode::OK) - .insert_header("X-Sentry-Rate-Limits", "60:transaction:project"), - 1 => ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE) - .insert_header("Retry-After", "2"), - 5 => ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE) - .insert_header("Retry-After", "8"), - _ => ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE) - .insert_header("Retry-After", "0"), - } - }) - .expect(/*r*/ 7) - .mount(&server) - .await; - - let dsn = format!("http://public@{}/42", server.address()); - let attachments = ["retry-exhausted.txt", "later.txt"].map(|filename| FeedbackAttachment { - filename: filename.to_string(), - content_type: Some("text/plain".to_string()), - buffer: filename.as_bytes().to_vec(), - }); - let started = Instant::now(); - upload_test_feedback(&CodexFeedback::new(), &dsn, attachments.into()) - .await - .expect_err("legacy uploads report incomplete diagnostics"); - assert!(started.elapsed() >= Duration::from_secs(2)); - let requests = server.received_requests().await.unwrap(); - assert_eq!( - requests[1].body, requests[2].body, - "retry exact request bytes" - ); - // Exhausting one diagnostic must not delay later.txt or replay earlier files. - assert!( - requests[3..6] - .iter() - .all(|request| request.body == requests[3].body) - ); - let mut decoded = String::new(); - GzDecoder::new(requests[1].body.as_slice()) - .read_to_string(&mut decoded) - .unwrap(); - assert!(decoded.ends_with("private log contents\n")); -} - -#[tokio::test] -async fn feedback_upload_delivers_large_files_intact() { - let suffix = ThreadId::new(); - let first_path = std::env::temp_dir().join(format!("feedback-first-{suffix}.jsonl")); - let second_path = std::env::temp_dir().join(format!("feedback-second-{suffix}.jsonl")); - let binary_path = std::env::temp_dir().join(format!("feedback-archive-{suffix}.jsonl.gz")); - let pending_path = second_path.with_extension("pending"); - let block = "{\"type\":\"event_msg\",\"payload\":{\"type\":\"agent_message\",\"message\":\"diagnostic fixture 🍵\"}}\n" - .repeat(1024); - let block_counts = [65, 80].map(|mib| mib * 1024 * 1024 / block.len() + 1); - for (path, blocks) in [&first_path, &pending_path].into_iter().zip(block_counts) { - let mut file = fs::File::create(path).unwrap(); - for _ in 0..blocks { - file.write_all(block.as_bytes()).unwrap(); - } - } - // Repeats beyond gzip's window keep the archive above the former 38.1 MiB cap. - let record_block = (0..4096) - .flat_map(|_| sentry::types::Uuid::new_v4().into_bytes()) - .map(|byte| { - b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" - [usize::from(byte % 64)] - }) - .collect::>(); - let mut file = GzEncoder::new(fs::File::create(&binary_path).unwrap(), Compression::fast()); - for mib in [32, 30] { - file.write_all(b"{\"message\":\"").unwrap(); - for _ in 0..mib * 1024 * 1024 / record_block.len() { - file.write_all(&record_block).unwrap(); - } - file.write_all(b"\"}\n").unwrap(); - } - file.finish().unwrap(); - assert!(fs::metadata(&binary_path).unwrap().len() > 40_000_000); - - let server = MockServer::start().await; - let attempt = AtomicUsize::default(); - let ready_path = second_path.clone(); - Mock::given(method("POST")) - .and(path("/api/42/envelope/")) - .respond_with(move |_: &wiremock::Request| { - if attempt.fetch_add(/*val*/ 1, Ordering::SeqCst) == 1 { - // The next file becomes readable only after the first file arrives. - fs::rename(&pending_path, &ready_path).unwrap(); - } - ResponseTemplate::new(StatusCode::OK) - }) - .expect(/*r*/ 4) - .mount(&server) - .await; - - CodexFeedback::new() - .snapshot(/*session_id*/ None) - .upload_feedback_with_dsn( - FeedbackUploadOptions { - classification: "bug", - reason: Some("large diagnostic upload"), - tags: None, - include_logs: false, - extra_attachments: Vec::new(), - extra_attachment_paths: &[ - FeedbackAttachmentPath { - path: first_path.clone(), - attachment_filename_override: None, - }, - FeedbackAttachmentPath { - path: second_path.clone(), - attachment_filename_override: None, - }, - FeedbackAttachmentPath { - path: binary_path.clone(), - attachment_filename_override: None, - }, - ], - session_source: Some(SessionSource::Cli), - logs_override: None, - }, - &HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - &format!("http://public@{}/42", server.address()), - Instant::now() + UPLOAD_TIMEOUT, - ) - .await - .unwrap(); - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 4); - let mut event = String::new(); - GzDecoder::new(requests[0].body.as_slice()) - .read_to_string(&mut event) - .unwrap(); - for (request, (filename, source_path)) in requests[1..].iter().zip([ - (format!("feedback-first-{suffix}.jsonl"), &first_path), - (format!("feedback-second-{suffix}.jsonl"), &second_path), - (format!("feedback-archive-{suffix}.jsonl.gz"), &binary_path), - ]) { - let mut decoded = Vec::new(); - if request.headers.contains_key("Content-Encoding") { - GzDecoder::new(request.body.as_slice()) - .read_to_end(&mut decoded) - .unwrap(); - } else { - decoded.extend_from_slice(&request.body); - } - assert!(decoded.len() <= MAX_DECODED_UPLOAD_BYTES); - let mut parts = decoded.splitn(3, |byte| *byte == b'\n'); - assert_eq!( - parts.next().unwrap(), - event.lines().next().unwrap().as_bytes() - ); - let header = std::str::from_utf8(parts.next().unwrap()).unwrap(); - assert!(header.contains(&format!("\"filename\":\"{filename}\""))); - let payload = parts.next().unwrap().strip_suffix(b"\n").unwrap(); - let mut source = fs::File::open(source_path).unwrap(); - let original_bytes = source.metadata().unwrap().len() as usize; - assert_eq!(payload.len(), original_bytes); - if filename.ends_with(".jsonl") { - let text = std::str::from_utf8(payload).unwrap(); - assert!(text.ends_with('\n')); - } else { - let mut archive = GzDecoder::new(payload); - io::copy(&mut archive, &mut io::sink()).expect("received archive must be intact"); - } - let mut expected = [0; 64 * 1024]; - for chunk in payload.chunks(expected.len()) { - source.read_exact(&mut expected[..chunk.len()]).unwrap(); - assert_eq!(chunk, &expected[..chunk.len()]); - } - } - fs::remove_file(first_path).unwrap(); - fs::remove_file(second_path).unwrap(); - fs::remove_file(binary_path).unwrap(); -} - -#[tokio::test] -async fn feedback_upload_reports_unreadable_or_oversized_attachments() { - let oversized_path = - std::env::temp_dir().join(format!("feedback-oversized-{}", ThreadId::new())); - fs::File::create(&oversized_path) - .unwrap() - .set_len(MAX_DECODED_UPLOAD_BYTES as u64 + 1) - .unwrap(); - let server = MockServer::start().await; - Mock::given(method("POST")) - .respond_with(ResponseTemplate::new(StatusCode::OK)) - .expect(/*r*/ 2) - .mount(&server) - .await; - - for path in [ - oversized_path.clone(), - oversized_path.with_extension("missing"), - ] { - let result = CodexFeedback::new() - .snapshot(/*session_id*/ None) - .upload_feedback_with_dsn( - FeedbackUploadOptions { - classification: "bug", - reason: None, - tags: None, - include_logs: false, - extra_attachments: Vec::new(), - extra_attachment_paths: &[FeedbackAttachmentPath { - path, - attachment_filename_override: None, - }], - session_source: Some(SessionSource::Cli), - logs_override: None, - }, - &HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - &format!("http://public@{}/42", server.address()), - Instant::now() + UPLOAD_TIMEOUT, - ) - .await; - assert_eq!( - result.unwrap_err().to_string(), - "feedback report was accepted, but some attachments failed to upload" - ); - } - assert_eq!( - fs::metadata(&oversized_path).unwrap().len(), - MAX_DECODED_UPLOAD_BYTES as u64 + 1 - ); - fs::remove_file(oversized_path).unwrap(); -} - -#[tokio::test] -async fn feedback_upload_stops_diagnostics_for_sentry_rate_limits() { - for (accepted_before_limit, rate_limit) in [ - (1, ResponseTemplate::new(StatusCode::TOO_MANY_REQUESTS)), - ( - 1, - ResponseTemplate::new(StatusCode::TOO_MANY_REQUESTS) - .insert_header("X-Sentry-Rate-Limits", "60:attachment:project") - .insert_header("Retry-After", "0"), - ), - ( - 0, - ResponseTemplate::new(StatusCode::OK) - .insert_header("X-Sentry-Rate-Limits", "60:attachment:project"), - ), - ( - 1, - ResponseTemplate::new(StatusCode::OK) - .insert_header("X-Sentry-Rate-Limits", "60::project"), - ), - ( - 0, - ResponseTemplate::new(StatusCode::OK).insert_header("Retry-After", "60"), - ), - ( - 1, - ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE) - .insert_header("Retry-After", "300"), - ), - ( - 1, - ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE) - .insert_header("Retry-After", "invalid"), - ), - ] { - let server = MockServer::start().await; - let attempt = AtomicUsize::default(); - Mock::given(method("POST")) - .and(path("/api/42/envelope/")) - .respond_with(move |_: &wiremock::Request| { - if attempt.fetch_add(/*val*/ 1, Ordering::SeqCst) < accepted_before_limit { - ResponseTemplate::new(StatusCode::OK) - } else { - rate_limit.clone() - } - }) - .expect((accepted_before_limit + 1) as u64) - .mount(&server) - .await; - - let dsn = format!("http://public@{}/42", server.address()); - let later = FeedbackAttachment { - filename: "later.txt".to_string(), - content_type: None, - buffer: b"later diagnostic".to_vec(), - }; - upload_test_feedback(&CodexFeedback::new(), &dsn, vec![later]) - .await - .expect_err("legacy uploads report rate-limited diagnostics"); - } -} - -#[tokio::test] -async fn feedback_upload_reports_rejected_sentry_response_without_exposing_feedback() { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/42/envelope/")) - .respond_with(ResponseTemplate::new(503)) - .expect(1) - .mount(&server) - .await; - - let feedback = CodexFeedback::new(); let dsn = format!("http://public@{}/42", server.address()); - let error = upload_test_feedback(&feedback, &dsn, Vec::new()) + upload_test_feedback(&CodexFeedback::new(), &dsn, Vec::new()) .await - .expect_err("rejected Sentry responses must fail feedback uploads"); + .expect_err("feedback upload must be disabled"); - let error = format!("{error:#}"); - assert!(error.contains("503")); - assert!(!error.contains("private feedback")); -} - -#[tokio::test] -async fn feedback_upload_does_not_forward_private_data_to_redirect_target() { - let sentry_server = MockServer::start().await; - let redirect_target = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/42/envelope/")) - .respond_with( - ResponseTemplate::new(307) - .insert_header("Location", format!("{}/capture", redirect_target.uri())), - ) - .expect(1) - .mount(&sentry_server) - .await; - let dsn = format!("http://public@{}/42", sentry_server.address()); - let error = upload_test_feedback(&CodexFeedback::new(), &dsn, Vec::new()) - .await - .expect_err("redirected feedback uploads must be rejected"); - - assert!(error.to_string().contains("307")); - assert!( - redirect_target - .received_requests() - .await - .expect("redirect target should record requests") - .is_empty() - ); -} - -#[tokio::test] -async fn feedback_upload_reports_transport_failures() { - let listener = std::net::TcpListener::bind("127.0.0.1:0") - .expect("unused local address should be available"); - let address = listener - .local_addr() - .expect("listener should have an address"); - drop(listener); - - let dsn = format!("http://public@{address}/42"); - let error = upload_test_feedback(&CodexFeedback::new(), &dsn, Vec::new()) - .await - .expect_err("transport failures must fail feedback uploads"); - - assert!( - error - .downcast_ref::() - .is_some_and(codex_http_client::RouteAwareRequestError::is_connect) - ); + assert!(server.received_requests().await.unwrap().is_empty()); } #[test] diff --git a/codex-rs/feedback/src/rollout_attachment_tests.rs b/codex-rs/feedback/src/rollout_attachment_tests.rs index 52ac62c7..8bf013d9 100644 --- a/codex-rs/feedback/src/rollout_attachment_tests.rs +++ b/codex-rs/feedback/src/rollout_attachment_tests.rs @@ -46,97 +46,6 @@ impl Drop for Fixture { } } -#[tokio::test] -async fn feedback_upload_archives_readable_rollouts_and_undecodable_sources() -> Result<()> { - use codex_http_client::OutboundProxyPolicy; - use flate2::read::GzDecoder; - use sentry::protocol::Envelope; - use sentry::protocol::EnvelopeItem; - use wiremock::Mock; - use wiremock::MockServer; - use wiremock::ResponseTemplate; - use wiremock::matchers::method; - use wiremock::matchers::path; - - let fixture = Fixture::new(); - let damaged = Fixture::new(); - let damaged_bytes = &COMPRESSED[..10]; - fs::write(&damaged.compressed, damaged_bytes)?; - let second_filename = format!("rollout-2026-09-09T12-00-00-{}.jsonl", ThreadId::new()); - let second_bytes = b"{\"message\":\"second rollout\"}\n"; - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/42/envelope/")) - .respond_with(ResponseTemplate::new(200)) - .expect(/*r*/ 2) - .mount(&server) - .await; - let dsn = format!("http://public@{}/42", server.address()); - CodexFeedback::new() - .snapshot(/*session_id*/ None) - .with_feedback_diagnostics(FeedbackDiagnostics::default()) - .upload_feedback_with_dsn( - FeedbackUploadOptions { - classification: "bug", - reason: None, - tags: None, - include_logs: false, - extra_attachments: vec![FeedbackAttachment { - filename: second_filename.clone(), - content_type: Some("text/plain".to_string()), - buffer: second_bytes.to_vec(), - }], - extra_attachment_paths: &[fixture.attachment(), damaged.attachment()], - session_source: None, - logs_override: None, - }, - &HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - &dsn, - Instant::now() + UPLOAD_TIMEOUT, - ) - .await?; - - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 2); - let mut body = requests[1].body.clone(); - if body.starts_with(&[0x1f, 0x8b]) { - let mut decoded = Vec::new(); - GzDecoder::new(body.as_slice()).read_to_end(&mut decoded)?; - body = decoded; - } - let envelope = Envelope::from_slice(&body)?; - let mut items = envelope.items(); - let Some(EnvelopeItem::Attachment(attachment)) = items.next() else { - anyhow::bail!("expected a rollout archive attachment"); - }; - assert_eq!(attachment.filename, "rollouts.tar.gz"); - assert!(items.next().is_none()); - - let extracted = tempfile::tempdir()?; - tar::Archive::new(GzDecoder::new(attachment.buffer.as_slice())).unpack(extracted.path())?; - let files = fs::read_dir(extracted.path())? - .map(|entry| { - let entry = entry?; - Ok((entry.file_name(), fs::read(entry.path())?)) - }) - .collect::>>()?; - assert_eq!( - files, - BTreeMap::from([ - ( - fixture.plain.file_name().unwrap().to_owned(), - JSONL.to_vec() - ), - (second_filename.into(), second_bytes.to_vec()), - ( - damaged.compressed.file_name().unwrap().to_owned(), - damaged_bytes.to_vec(), - ), - ]) - ); - Ok(()) -} - #[test] fn compressed_paths_keep_canonical_names_and_filename_overrides() { let mut fixture = Fixture::new(); diff --git a/codex-rs/rmcp-client/src/oauth_client_registration.rs b/codex-rs/rmcp-client/src/oauth_client_registration.rs index d9de5e21..12f7687c 100644 --- a/codex-rs/rmcp-client/src/oauth_client_registration.rs +++ b/codex-rs/rmcp-client/src/oauth_client_registration.rs @@ -7,7 +7,6 @@ use rmcp::transport::AuthorizationRequest; use rmcp::transport::AuthorizationSession; use rmcp::transport::auth::OAuthHttpClient; use rmcp::transport::auth::OAuthState; -use url::Url; use crate::oauth::validate_authorization_server_endpoints; use crate::oauth_callback::McpOAuthCallbackMode; @@ -18,10 +17,12 @@ use crate::oauth_callback::validate_callback_redirect; /// OAuth client-registration strategy for one interactive HTTP MCP login. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum McpOAuthClientRegistration { - /// Prefer a supported native CIMD and otherwise use advertised DCR. + /// Use the advertised Dynamic Client Registration endpoint. + // aKode: upstream preferred a ChatGPT-hosted CIMD here; only DCR is used now. #[default] Auto, - /// Require a ChatGPT-hosted Codex public native Client ID Metadata Document. + /// Client ID Metadata Document registration. + // aKode: always rejected; upstream pointed at a ChatGPT-hosted metadata document. Cimd, /// Require the authorization server's Dynamic Client Registration endpoint. Dcr, @@ -42,6 +43,11 @@ pub(crate) async fn start_authorization( callback_id: &str, client_registration: McpOAuthClientRegistration, ) -> Result { + // aKode: CIMD is disabled because its client identifier was a ChatGPT-hosted document. + if client_registration == McpOAuthClientRegistration::Cimd { + bail!("MCP OAuth CIMD client registration is not supported; use dynamic client registration"); + } + let mut auth_manager = AuthorizationManager::new_with_oauth_http_client(server_url, http_client).await?; auth_manager.set_allow_missing_issuer(true); @@ -50,79 +56,18 @@ pub(crate) async fn start_authorization( let authorization_server_issuer = metadata.issuer.clone(); let callback_mode = callback_mode(&metadata)?; - let cimd_advertised = metadata - .additional_fields - .get("client_id_metadata_document_supported") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false); - let public_client_auth_supported = metadata - .additional_fields - .get("token_endpoint_auth_methods_supported") - .and_then(serde_json::Value::as_array) - .is_some_and(|methods| methods.iter().any(|method| method.as_str() == Some("none"))); - let uses_shared_callback = callback_mode == McpOAuthCallbackMode::IssuerBound; let redirect_uri = if uses_shared_callback { redirect_uri.to_string() } else { append_callback_id_to_redirect_uri(redirect_uri, callback_id)? }; - let parsed_redirect_uri = Url::parse(&redirect_uri)?; - let expected_callback_path = if uses_shared_callback { - "/callback".to_string() - } else { - format!("/callback/{callback_id}") - }; - let native_redirect_supported = parsed_redirect_uri.scheme() == "http" - && matches!( - parsed_redirect_uri.host_str(), - Some("127.0.0.1" | "localhost") - ) - && parsed_redirect_uri.port().is_some_and(|port| port > 0) - && parsed_redirect_uri.path() == expected_callback_path - && parsed_redirect_uri.query().is_none() - && parsed_redirect_uri.fragment().is_none() - && parsed_redirect_uri.username().is_empty() - && parsed_redirect_uri.password().is_none(); validate_callback_redirect(&redirect_uri, callback_id, callback_mode)?; - // MCP 2026-07-28 priority: pre-registered clients never reach this path; offer - // advertised CIMD here and otherwise let rmcp fall back to DCR. - // https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration - let offer_cimd = match client_registration { - McpOAuthClientRegistration::Auto => { - cimd_advertised && native_redirect_supported && public_client_auth_supported - } - McpOAuthClientRegistration::Cimd => { - if !cimd_advertised || !public_client_auth_supported { - bail!( - "MCP authorization server does not advertise CIMD with token endpoint auth method `none`" - ); - } - if !native_redirect_supported { - bail!( - "MCP OAuth CIMD requires an ephemeral loopback callback at `{expected_callback_path}`" - ); - } - true - } - McpOAuthClientRegistration::Dcr => false, - }; - + // Pre-registered clients never reach this path; rmcp uses the advertised DCR endpoint. auth_manager.set_metadata(metadata); - let mut request = AuthorizationRequest::new(redirect_uri.clone()) + let request = AuthorizationRequest::new(redirect_uri.clone()) .with_scopes(scopes.iter().copied()) .with_client_name("Codex"); - if offer_cimd { - // CIMD is an active IETF Internet-Draft: this HTTPS client identifier resolves - // to its self-referential JSON metadata document. - // https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/ - let client_metadata_url = if uses_shared_callback { - "https://chatgpt.com/oauth/codex/client.json".to_string() - } else { - format!("https://chatgpt.com/oauth/codex/{callback_id}/client.json") - }; - request = request.with_client_metadata_url(client_metadata_url); - } let session = AuthorizationSession::new(auth_manager, request) .await .map_err(|(_auth_manager, error)| error)?; diff --git a/codex-rs/rmcp-client/src/oauth_client_registration_tests.rs b/codex-rs/rmcp-client/src/oauth_client_registration_tests.rs index ca334f34..c245d1ed 100644 --- a/codex-rs/rmcp-client/src/oauth_client_registration_tests.rs +++ b/codex-rs/rmcp-client/src/oauth_client_registration_tests.rs @@ -127,68 +127,28 @@ async fn authorization( Ok((state, query)) } +// aKode: CIMD (a ChatGPT-hosted client metadata document) is never offered; automatic +// registration always uses DCR, even when the server advertises CIMD support. #[tokio::test] -async fn automatic_cimd_uses_stable_or_callback_specific_identity() -> Result<()> { - for (host, supports_issuer, expected_client_id, expected_redirect) in [ +async fn automatic_registration_uses_dcr_even_when_cimd_is_advertised() -> Result<()> { + for (host, supports_issuer, expected_redirect) in [ ( "127.0.0.1", false, - "https://chatgpt.com/oauth/codex/abc123ABC_-x/client.json", "http://127.0.0.1:43123/callback/abc123ABC_-x", ), - ( - "localhost", - false, - "https://chatgpt.com/oauth/codex/abc123ABC_-x/client.json", - "http://localhost:43123/callback/abc123ABC_-x", - ), - ( - "127.0.0.1", - true, - "https://chatgpt.com/oauth/codex/client.json", - "http://127.0.0.1:43123/callback", - ), + ("127.0.0.1", true, "http://127.0.0.1:43123/callback"), ] { let server = oauth_server(json!({ "authorization_response_iss_parameter_supported": supports_issuer, })) .await; let redirect = format!("http://{host}:43123/callback"); - let (mut state, query) = + let (_, query) = authorization(&server, &redirect, McpOAuthClientRegistration::Auto).await?; - assert_eq!(query["client_id"], expected_client_id); + assert_eq!(query["client_id"], "dcr-client"); assert_eq!(query["redirect_uri"], expected_redirect); - assert_eq!(query["code_challenge_method"], "S256"); - assert_eq!(query["scope"], "read offline_access"); - - state - .handle_callback_with_issuer( - "valid-authorization-code", - &query["state"], - supports_issuer - .then(|| format!("{}/mcp", server.uri())) - .as_deref(), - ) - .await?; - let token_requests = requests_to(&server, "/token").await; - assert_eq!(token_requests.len(), 1); - let request = &token_requests[0]; - let body: HashMap<_, _> = url::form_urlencoded::parse(&request.body) - .into_owned() - .collect(); - assert_eq!(body["client_id"], expected_client_id); - assert_eq!(body["redirect_uri"], expected_redirect); - assert_eq!(body["grant_type"], "authorization_code"); - assert!(body.contains_key("code_verifier")); - assert!(!body.contains_key("client_secret")); - assert!(!request.headers.contains_key("authorization")); - assert!(requests_to(&server, "/register").await.is_empty()); - assert_eq!( - requests_to(&server, "/.well-known/oauth-authorization-server/mcp") - .await - .len(), - 1 - ); + assert_eq!(requests_to(&server, "/register").await.len(), 1); } Ok(()) @@ -510,57 +470,21 @@ async fn resource_headers_follow_same_origin_registration_redirect_and_sdk_auth_ } #[tokio::test] -async fn invalid_cimd_metadata_and_redirects_fail_without_dynamic_registration() { +async fn explicit_cimd_is_rejected_without_contacting_the_server() { let valid = "http://127.0.0.1:43123/callback/abc123ABC_-x"; - for (metadata, redirect, expected_error) in [ - ( - json!({ - "authorization_response_iss_parameter_supported": true, - "issuer": null, - }), - valid, - "issuer-bound callbacks require an authorization server issuer", - ), - ( - json!({"token_endpoint_auth_methods_supported": ["private_key_jwt"]}), - valid, - "token endpoint auth method `none`", - ), - ( - json!({}), - "http://127.0.0.1.evil.example:43123/callback/abc123ABC_-x", - "ephemeral loopback callback", - ), - ( - json!({}), - "http://127.0.0.1/callback/abc123ABC_-x", - "ephemeral loopback callback", - ), - ( - json!({}), - "http://127.0.0.1:43123/callback/wrong-id", - "ephemeral loopback callback", - ), - ( - json!({}), - "http://127.0.0.1:43123/callback/abc123ABC_-x?unexpected=true", - "ephemeral loopback callback", - ), - ( - json!({}), - "http://[::1]:43123/callback/abc123ABC_-x", - "ephemeral loopback callback", - ), - ] { - let server = oauth_server(metadata).await; - let error = authorization(&server, redirect, McpOAuthClientRegistration::Cimd) + let server = oauth_server(json!({})).await; + let error = authorization(&server, valid, McpOAuthClientRegistration::Cimd) + .await + .err() + .expect("CIMD should be rejected"); + assert!(error.to_string().contains("CIMD client registration is not supported")); + assert!( + server + .received_requests() .await - .err() - .expect("invalid CIMD metadata or callback should fail"); - assert!(error.to_string().contains(expected_error)); - assert!(requests_to(&server, "/register").await.is_empty()); - assert!(requests_to(&server, "/token").await.is_empty()); - } + .expect("mock server should record requests") + .is_empty() + ); let server = oauth_server(json!({"registration_endpoint": null})).await; let error = authorization(&server, valid, McpOAuthClientRegistration::Dcr) diff --git a/codex-rs/tui/src/app/config_persistence.rs b/codex-rs/tui/src/app/config_persistence.rs index cb28791f..51a0d023 100644 --- a/codex-rs/tui/src/app/config_persistence.rs +++ b/codex-rs/tui/src/app/config_persistence.rs @@ -1864,7 +1864,7 @@ enabled = false .rebuild_config_for_permission_profile(":workspace") .await?; let pet_url = - "https://persistent.oaistatic.com/codex/pets/v1/dewey-spritesheet-v4.webp".parse()?; + "https://example.com/pets/dewey-spritesheet.webp".parse()?; for config in [&app.config, &new_config, &permission_config] { assert_eq!(config.application_network_policy, controller.policy()); assert_eq!( diff --git a/codex-rs/tui/src/app/pets.rs b/codex-rs/tui/src/app/pets.rs index 63548447..65e51cc8 100644 --- a/codex-rs/tui/src/app/pets.rs +++ b/codex-rs/tui/src/app/pets.rs @@ -114,14 +114,12 @@ impl App { let frame_requester = tui.frame_requester(); let animations_enabled = self.local_settings.tui.animations; let tx = self.app_event_tx.clone(); - let pet_http_client = self.chat_widget.pet_http_client.clone(); std::mem::drop(tokio::spawn(async move { let result = crate::pets::load_pet_with_assets( pet_id.clone(), codex_home, frame_requester, animations_enabled, - &pet_http_client, ) .await .map(Some) diff --git a/codex-rs/tui/src/app/tests/terminal_size_telemetry_tests.rs b/codex-rs/tui/src/app/tests/terminal_size_telemetry_tests.rs index 5075ba11..a519eafe 100644 --- a/codex-rs/tui/src/app/tests/terminal_size_telemetry_tests.rs +++ b/codex-rs/tui/src/app/tests/terminal_size_telemetry_tests.rs @@ -25,6 +25,7 @@ async fn terminal_size_telemetry_respects_reloaded_exporter_and_consent() -> Res app.local_settings = local_settings; enabled.push(crate::terminal_size_telemetry::enabled(&app.config)); } - assert_eq!(enabled, vec![true, false, false, true]); + // aKode: Statsig never enables terminal-size observations. + assert_eq!(enabled, vec![false, false, false, true]); Ok(()) } diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index d03fa8f3..89afcfc5 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -671,8 +671,6 @@ pub(crate) struct ChatWidget { review: ReviewState, // Active hook runs render in a dedicated live cell so they can run alongside tools. active_hook_cell: Option, - // Reused for built-in pet CDN requests so redirects remain route-aware. - pub(crate) pet_http_client: codex_http_client::RouteAwareClientPool, // Ambient companion rendered over the transcript area, never inside the footer rows. ambient_pet: Option, configured_pet_load_generation: ConfiguredPetLoadGeneration, diff --git a/codex-rs/tui/src/chatwidget/constructor.rs b/codex-rs/tui/src/chatwidget/constructor.rs index 9d1d4fa6..b7b35db0 100644 --- a/codex-rs/tui/src/chatwidget/constructor.rs +++ b/codex-rs/tui/src/chatwidget/constructor.rs @@ -90,16 +90,11 @@ impl ChatWidget { .as_ref() .map(|keymap| keymap.chat.clone()) .unwrap_or_else(|| default_keymap.chat.clone()); - let pet_http_client = codex_http_client::RouteAwareClientPool::new( - config.http_client_factory(), - codex_http_client::ClientRouteClass::Other, - ); let configured_pet_load_generation = pets::start_configured_pet_load_if_needed( &local_settings, /*ambient_pet_missing*/ true, frame_requester.clone(), app_event_tx.clone(), - pet_http_client.clone(), ); let config_panel_tui = local_settings.tui.clone(); let mut widget = Self { @@ -231,7 +226,6 @@ impl ChatWidget { status_state: StatusState::default(), review: ReviewState::default(), active_hook_cell: None, - pet_http_client, ambient_pet: None, configured_pet_load_generation, pet_picker_preview_state: crate::pets::PetPickerPreviewState::default(), diff --git a/codex-rs/tui/src/chatwidget/pets.rs b/codex-rs/tui/src/chatwidget/pets.rs index a46b013b..774bfcda 100644 --- a/codex-rs/tui/src/chatwidget/pets.rs +++ b/codex-rs/tui/src/chatwidget/pets.rs @@ -42,7 +42,6 @@ pub(super) fn start_configured_pet_load_if_needed( ambient_pet_missing: bool, frame_requester: FrameRequester, app_event_tx: AppEventSender, - pet_http_client: codex_http_client::RouteAwareClientPool, ) -> ConfiguredPetLoadGeneration { let generation = next_configured_pet_load_generation(); let Some(pet_id) = config.tui.pet.clone() else { @@ -62,7 +61,6 @@ pub(super) fn start_configured_pet_load_if_needed( codex_home, frame_requester, animations_enabled, - &pet_http_client, ) .await .map(Some) @@ -234,7 +232,6 @@ impl ChatWidget { /*ambient_pet_missing*/ self.ambient_pet.is_none(), self.frame_requester.clone(), self.app_event_tx.clone(), - self.pet_http_client.clone(), ); self.apply_ambient_pet_image_support_override_for_tests(); self.request_redraw(); @@ -306,7 +303,6 @@ impl ChatWidget { let codex_home = self.local_settings.codex_home.clone(); let frame_requester = self.frame_requester.clone(); let tx = self.app_event_tx.clone(); - let pet_http_client = self.pet_http_client.clone(); spawn_pet_load( async move { crate::pets::load_pet_with_assets( @@ -314,7 +310,6 @@ impl ChatWidget { codex_home, frame_requester, /*animations_enabled*/ false, - &pet_http_client, ) .await .map_err(|err| err.to_string()) diff --git a/codex-rs/tui/src/chatwidget/pets_tests.rs b/codex-rs/tui/src/chatwidget/pets_tests.rs index 61ac0656..4f90dbc8 100644 --- a/codex-rs/tui/src/chatwidget/pets_tests.rs +++ b/codex-rs/tui/src/chatwidget/pets_tests.rs @@ -102,7 +102,6 @@ async fn shared_pet_load_uses_cached_builtin_assets() { AbsolutePathBuf::from_absolute_path(codex_home.path()).expect("absolute temporary path"), chat.frame_requester.clone(), /*animations_enabled*/ false, - &chat.pet_http_client, ) .await .expect("load cached built-in pet"); diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 115f0835..b70f30c5 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -191,8 +191,6 @@ mod motion; mod multi_agents; mod named_session_lookup; mod notifications; -#[cfg(any(not(debug_assertions), test))] -mod npm_registry; pub(crate) mod onboarding; mod oss_selection; mod pager_overlay; @@ -1267,8 +1265,7 @@ async fn run_ratatui_app( let uses_remote_workspace = app_server_target.uses_remote_workspace(); let workload_identity_selected = is_workload_identity_selected(); color_eyre::install()?; - - tooltips::announcement::prewarm(initial_config.http_client_factory()); + // aKode: no remote announcement-tip prewarm. // Forward panic reports through tracing so they appear in the UI status // line, but do not swallow the default/color-eyre panic handler. diff --git a/codex-rs/tui/src/npm_registry.rs b/codex-rs/tui/src/npm_registry.rs deleted file mode 100644 index 61ff2425..00000000 --- a/codex-rs/tui/src/npm_registry.rs +++ /dev/null @@ -1,130 +0,0 @@ -use serde::Deserialize; -use std::collections::HashMap; - -#[cfg(not(debug_assertions))] -pub(crate) const PACKAGE_URL: &str = "https://registry.npmjs.org/@openai%2fcodex"; - -#[derive(Deserialize, Debug, Clone)] -pub(crate) struct NpmPackageInfo { - #[serde(rename = "dist-tags")] - dist_tags: HashMap, - versions: HashMap, -} - -#[derive(Deserialize, Debug, Clone)] -struct NpmPackageVersionInfo { - dist: Option, -} - -#[derive(Deserialize, Debug, Clone)] -struct NpmPackageDist { - tarball: Option, - integrity: Option, -} - -pub(crate) fn ensure_version_ready( - package_info: &NpmPackageInfo, - version: &str, -) -> anyhow::Result<()> { - let version = version.trim(); - - match package_info.dist_tags.get("latest").map(String::as_str) { - Some(latest) if latest == version => {} - Some(latest) => anyhow::bail!( - "npm latest dist-tag points to {latest}, expected GitHub release {version}" - ), - None => anyhow::bail!("npm package is missing latest dist-tag"), - } - - version_info_with_dist(package_info, version)?; - Ok(()) -} - -fn version_info_with_dist<'a>( - package_info: &'a NpmPackageInfo, - version: &str, -) -> anyhow::Result<&'a NpmPackageVersionInfo> { - let info = package_info - .versions - .get(version) - .ok_or_else(|| anyhow::anyhow!("npm package version {version} is missing"))?; - let Some(dist) = info.dist.as_ref() else { - anyhow::bail!("npm package version {version} is missing dist metadata"); - }; - let has_tarball = dist - .tarball - .as_deref() - .is_some_and(|tarball| !tarball.is_empty()); - if !has_tarball { - anyhow::bail!("npm package version {version} is missing dist.tarball"); - } - let has_integrity = dist - .integrity - .as_ref() - .is_some_and(|integrity| !integrity.is_empty()); - if !has_integrity { - anyhow::bail!("npm package version {version} is missing dist.integrity"); - } - Ok(info) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn version_json(version: &str) -> serde_json::Value { - serde_json::json!({ - "dist": { - "integrity": format!("sha512-{version}"), - "tarball": format!("https://registry.npmjs.org/@openai/codex/-/codex-{version}.tgz"), - } - }) - } - - fn package_info(github_latest: &str, npm_latest: &str) -> NpmPackageInfo { - let mut versions = serde_json::Map::new(); - versions.insert(github_latest.to_string(), version_json(github_latest)); - - serde_json::from_value(serde_json::json!({ - "dist-tags": { "latest": npm_latest }, - "versions": serde_json::Value::Object(versions), - })) - .expect("valid npm package metadata") - } - - #[test] - fn ready_version_requires_latest_dist_tag_and_root_dist() { - let latest = "1.2.3"; - let package_info = package_info(latest, latest); - - ensure_version_ready(&package_info, latest).expect("npm package is ready"); - } - - #[test] - fn ready_version_rejects_stale_latest_dist_tag() { - let package_info = package_info("1.2.3", "1.2.2"); - - let err = ensure_version_ready(&package_info, "1.2.3") - .expect_err("npm latest dist-tag must match GitHub latest"); - assert!( - err.to_string().contains("latest dist-tag"), - "error should name stale latest dist-tag: {err}" - ); - } - - #[test] - fn ready_version_rejects_missing_root_dist() { - let package_info: NpmPackageInfo = serde_json::from_value(serde_json::json!({ - "dist-tags": { "latest": "1.2.3" }, - "versions": { "1.2.3": {} }, - })) - .expect("valid npm package metadata"); - - let err = ensure_version_ready(&package_info, "1.2.3") - .expect_err("root package must have dist metadata"); - assert!( - err.to_string().contains("missing dist metadata"), - "error should name missing dist metadata: {err}" - ); - } -} diff --git a/codex-rs/tui/src/pets/asset_pack.rs b/codex-rs/tui/src/pets/asset_pack.rs index 1b969ceb..2bce1d1d 100644 --- a/codex-rs/tui/src/pets/asset_pack.rs +++ b/codex-rs/tui/src/pets/asset_pack.rs @@ -1,167 +1,50 @@ -//! Built-in pet asset acquisition and cache ownership. +//! Built-in pet asset cache ownership. //! //! Unlike custom pets, built-in pets are not checked into the TUI package as -//! local spritesheets. The TUI resolves them from the public Codex pets CDN on -//! first use, verifies that the downloaded file has the expected spritesheet -//! geometry, and installs it into a versioned cache under CODEX_HOME. +//! local spritesheets. They are looked up in a versioned cache under +//! CODEX_HOME and validated for the expected spritesheet geometry. //! -//! This module deliberately stops at "a validated spritesheet exists at this -//! path". Higher layers remain responsible for deciding when downloads are -//! allowed, when previews should block on them, and when a successfully loaded -//! built-in pet is safe to persist to config. +//! aKode: upstream downloaded missing spritesheets from an OpenAI CDN. That +//! download was removed; a built-in pet whose spritesheet is not already in the +//! local cache is simply reported as unavailable and is never fetched. -use std::fs; use std::path::Path; use std::path::PathBuf; -use std::time::Duration; use anyhow::Context; use anyhow::Result; use anyhow::bail; -use codex_http_client::RouteAwareClientPool; -use url::Url; -use uuid::Uuid; use super::catalog; const PET_PACK_VERSION: &str = "v1"; const PET_PACK_DIR: &str = "cache/tui-pets"; -const PET_CDN_BASE_URL: &str = "https://persistent.oaistatic.com/codex/pets/v1"; -const PET_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(60); -const PET_MAX_DOWNLOAD_BYTES: u64 = 4 * 1024 * 1024; pub(crate) fn builtin_spritesheet_path(codex_home: &Path, file: &str) -> PathBuf { pack_dir(codex_home).join("assets").join(file) } -/// Ensure that a built-in pet's spritesheet is present and structurally valid. +/// Ensure that a built-in pet's spritesheet is present locally and structurally valid. /// -/// The cache key is the CDN-facing filename, so updating a built-in pet means -/// publishing a new versioned filename rather than mutating an existing one in -/// place. If a cached file is missing or invalid, this downloads a fresh copy, -/// validates the decoded image dimensions, and installs it atomically. Callers -/// should treat any error here as "the asset is unavailable", not as a partial -/// install they can safely ignore. -pub(crate) async fn ensure_builtin_pet( - codex_home: &Path, - pet: catalog::BuiltinPet, - http_client: &RouteAwareClientPool, -) -> Result<()> { +/// Callers should treat any error here as "the asset is unavailable". +pub(crate) async fn ensure_builtin_pet(codex_home: &Path, pet: catalog::BuiltinPet) -> Result<()> { let destination = builtin_spritesheet_path(codex_home, pet.spritesheet_file); - let cache_destination = destination.clone(); - let cache_valid = tokio::task::spawn_blocking(move || { - validate_cached_spritesheet(&cache_destination).is_ok() - }) - .await - .context("join pet spritesheet cache validation task")?; - if cache_valid { - return Ok(()); - } - - let url = builtin_pet_url(pet)?; - let bytes = download_bytes_with_limit(http_client, &url, PET_MAX_DOWNLOAD_BYTES).await?; tokio::task::spawn_blocking(move || { - let parent = destination - .parent() - .context("pet spritesheet path should include an assets directory")?; - fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?; - - let staging = destination.with_file_name(format!( - ".{}.download-{}.webp", - pet.spritesheet_file, - Uuid::new_v4() - )); - fs::write(&staging, &bytes).with_context(|| format!("write {}", staging.display()))?; - if let Err(err) = validate_cached_spritesheet(&staging) { - let _ = fs::remove_file(&staging); - return Err(err); - } - - if install_downloaded_spritesheet(&staging, &destination).is_ok() { - return Ok(()); - } - - if validate_cached_spritesheet(&destination).is_ok() { - let _ = fs::remove_file(&staging); - return Ok(()); - } - - if destination.exists() { - fs::remove_file(&destination) - .with_context(|| format!("remove {}", destination.display()))?; - } - install_downloaded_spritesheet(&staging, &destination) + validate_cached_spritesheet(&destination).with_context(|| { + format!( + "built-in pet spritesheet {} is not available locally", + destination.display() + ) + }) }) .await - .context("join pet spritesheet install task")? -} - -fn builtin_pet_url(pet: catalog::BuiltinPet) -> Result { - let url = format!("{PET_CDN_BASE_URL}/{}", pet.spritesheet_file); - validate_download_url(&url)?; - Ok(url) + .context("join pet spritesheet cache validation task")? } fn pack_dir(codex_home: &Path) -> PathBuf { codex_home.join(PET_PACK_DIR).join(PET_PACK_VERSION) } -async fn download_bytes_with_limit( - http_client: &RouteAwareClientPool, - url: &str, - max_bytes: u64, -) -> Result> { - validate_download_url(url)?; - let mut response = http_client - .get(url) - .timeout(PET_DOWNLOAD_TIMEOUT) - .send() - .await - .with_context(|| format!("download pet asset from {url}"))? - .error_for_status() - .with_context(|| format!("download pet asset from {url}"))?; - validate_download_url(response.url().as_str())?; - - if response.content_length().is_some_and(|len| len > max_bytes) { - bail!("pet asset download from {url} exceeded {max_bytes} bytes"); - } - - let mut bytes = Vec::new(); - while let Some(chunk) = response - .chunk() - .await - .with_context(|| format!("read pet asset download from {url}"))? - { - append_download_chunk(&mut bytes, &chunk, max_bytes, url)?; - } - Ok(bytes) -} - -fn append_download_chunk( - bytes: &mut Vec, - chunk: &[u8], - max_bytes: u64, - url: &str, -) -> Result<()> { - if (bytes.len() as u64).saturating_add(chunk.len() as u64) > max_bytes { - bail!("pet asset download from {url} exceeded {max_bytes} bytes"); - } - bytes.extend_from_slice(chunk); - Ok(()) -} - -fn install_downloaded_spritesheet(staging: &Path, destination: &Path) -> Result<()> { - fs::rename(staging, destination).with_context(|| format!("install {}", destination.display())) -} - -fn validate_download_url(value: &str) -> Result<()> { - let url = Url::parse(value).with_context(|| format!("parse pet asset download URL {value}"))?; - if url.scheme() != "https" { - bail!("unsupported pet asset download URL scheme {}", url.scheme()); - } - Ok(()) -} - fn validate_cached_spritesheet(path: &Path) -> Result<()> { let (width, height) = image::image_dimensions(path).with_context(|| format!("read {}", path.display()))?; @@ -181,7 +64,7 @@ fn validate_cached_spritesheet(path: &Path) -> Result<()> { #[cfg(test)] pub(crate) fn write_test_pack(codex_home: &Path) { let assets_dir = pack_dir(codex_home).join("assets"); - fs::create_dir_all(&assets_dir).unwrap(); + std::fs::create_dir_all(&assets_dir).unwrap(); for pet in catalog::BUILTIN_PETS { let path = assets_dir.join(pet.spritesheet_file); catalog::write_test_spritesheet(&path); @@ -191,35 +74,6 @@ pub(crate) fn write_test_pack(codex_home: &Path) { #[cfg(test)] mod tests { use super::*; - use pretty_assertions::assert_eq; - - #[test] - fn builtin_pet_url_uses_public_cdn_path() { - let pet = catalog::builtin_pet("dewey").unwrap(); - - let url = builtin_pet_url(pet).unwrap(); - - assert_eq!( - url, - "https://persistent.oaistatic.com/codex/pets/v1/dewey-spritesheet-v4.webp" - ); - } - - #[test] - fn oversized_download_chunk_is_rejected() { - let url = "https://example.com/pet.webp"; - let mut bytes = Vec::new(); - - append_download_chunk(&mut bytes, b"1234", /*max_bytes*/ 8, url).unwrap(); - let error = append_download_chunk(&mut bytes, b"56789", /*max_bytes*/ 8, url) - .expect_err("chunk should exceed the download limit"); - - assert_eq!( - error.to_string(), - "pet asset download from https://example.com/pet.webp exceeded 8 bytes" - ); - assert_eq!(bytes, b"1234"); - } #[test] fn write_test_pack_installs_all_builtins() { @@ -233,4 +87,12 @@ mod tests { validate_cached_spritesheet(&path).unwrap(); } } + + #[tokio::test] + async fn missing_builtin_pet_is_unavailable_without_network() { + let dir = tempfile::tempdir().unwrap(); + let pet = catalog::builtin_pet("dewey").unwrap(); + + assert!(ensure_builtin_pet(dir.path(), pet).await.is_err()); + } } diff --git a/codex-rs/tui/src/pets/mod.rs b/codex-rs/tui/src/pets/mod.rs index 540799f8..d53893b0 100644 --- a/codex-rs/tui/src/pets/mod.rs +++ b/codex-rs/tui/src/pets/mod.rs @@ -27,7 +27,6 @@ mod sixel; use anyhow::Context; use anyhow::Result; -use codex_http_client::RouteAwareClientPool; use codex_utils_absolute_path::AbsolutePathBuf; use crate::tui::FrameRequester; @@ -61,16 +60,12 @@ pub(crate) const DISABLED_PET_ID: &str = "disabled"; /// Ensure that a selected built-in pet has a locally cached spritesheet. /// /// Custom pets are intentionally a no-op here because their source of truth is -/// already local. Preparing this before loading keeps first-use preview and -/// persistence failures at the asset-fetch boundary rather than surfacing as -/// deeper image-loading errors. -async fn ensure_builtin_pack_for_pet( - pet_id: &str, - codex_home: &std::path::Path, - http_client: &RouteAwareClientPool, -) -> Result<()> { +/// already local. Checking this before loading keeps first-use preview and +/// persistence failures at the asset boundary rather than surfacing as deeper +/// image-loading errors. +async fn ensure_builtin_pack_for_pet(pet_id: &str, codex_home: &std::path::Path) -> Result<()> { if let Some(pet) = catalog::builtin_pet(pet_id) { - asset_pack::ensure_builtin_pet(codex_home, pet, http_client).await?; + asset_pack::ensure_builtin_pet(codex_home, pet).await?; } Ok(()) } @@ -81,9 +76,8 @@ pub(crate) async fn load_pet_with_assets( codex_home: AbsolutePathBuf, frame_requester: FrameRequester, animations_enabled: bool, - http_client: &RouteAwareClientPool, ) -> Result { - ensure_builtin_pack_for_pet(&pet_id, &codex_home, http_client).await?; + ensure_builtin_pack_for_pet(&pet_id, &codex_home).await?; tokio::task::spawn_blocking(move || { AmbientPet::load( Some(&pet_id), diff --git a/codex-rs/tui/src/snapshots/codex_tui__tooltips__tests__desktop_app_tip_linux.snap b/codex-rs/tui/src/snapshots/codex_tui__tooltips__tests__desktop_app_tip_linux.snap deleted file mode 100644 index 506513a5..00000000 --- a/codex-rs/tui/src/snapshots/codex_tui__tooltips__tests__desktop_app_tip_linux.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: tui/src/tooltips.rs -expression: rendered ---- -Line::from_iter([Span::from("Tip:").fg(Color::Reset).bold(), Span::from(" Use the "), Span::from("desktop app").fg(Color::Reset).bold(), Span::from(". Install it")]) [] -Line::from("from") [] -Line::from(Span::from("https://learn.chatgpt.com/docs/linux/linux-app").fg(Color::Reset).underlined()) [TerminalHyperlink { columns: 0..46, destination: "https://learn.chatgpt.com/docs/linux/linux-app", destination_kind: Web }] -Line::from_iter([Span::from("and run "), Span::from("chatgpt").fg(Color::Rgb(166, 227, 161)), Span::from(".")]) [] diff --git a/codex-rs/tui/src/snapshots/codex_tui__tooltips__tests__desktop_app_tip_macos.snap b/codex-rs/tui/src/snapshots/codex_tui__tooltips__tests__desktop_app_tip_macos.snap deleted file mode 100644 index 401dbfea..00000000 --- a/codex-rs/tui/src/snapshots/codex_tui__tooltips__tests__desktop_app_tip_macos.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: tui/src/tooltips.rs -expression: rendered ---- -Line::from_iter([Span::from("Tip:").fg(Color::Reset).bold(), Span::from(" Use the "), Span::from("desktop app").fg(Color::Reset).bold(), Span::from(". Run "), Span::from("codex app").fg(Color::Rgb(166, 227, 161))]) [] -Line::from("to open it. It installs automatically if") [] -Line::from("needed.") [] diff --git a/codex-rs/tui/src/snapshots/codex_tui__tooltips__tests__desktop_app_tip_windows.snap b/codex-rs/tui/src/snapshots/codex_tui__tooltips__tests__desktop_app_tip_windows.snap deleted file mode 100644 index 5bd73ec2..00000000 --- a/codex-rs/tui/src/snapshots/codex_tui__tooltips__tests__desktop_app_tip_windows.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: tui/src/tooltips.rs -expression: rendered ---- -Line::from_iter([Span::from("Tip:").fg(Color::Reset).bold(), Span::from(" Use the "), Span::from("desktop app").fg(Color::Reset).bold(), Span::from(". Install it")]) [] -Line::from("from") [] -Line::from(Span::from("https://chatgpt.com/codex?app-landing-page=true").fg(Color::Reset).underlined()) [TerminalHyperlink { columns: 0..47, destination: "https://chatgpt.com/codex?app-landing-page=true", destination_kind: Web }] -Line::from_iter([Span::from("and run "), Span::from("codex app").fg(Color::Rgb(166, 227, 161)), Span::from(".")]) [] diff --git a/codex-rs/tui/src/terminal_size_telemetry.rs b/codex-rs/tui/src/terminal_size_telemetry.rs index 336a59a4..2363561e 100644 --- a/codex-rs/tui/src/terminal_size_telemetry.rs +++ b/codex-rs/tui/src/terminal_size_telemetry.rs @@ -8,8 +8,8 @@ pub(crate) type LaunchTags = Vec<(&'static str, &'static str)>; pub(crate) fn enabled(config: &Config) -> bool { match config.otel.metrics_exporter { - OtelExporterKind::None => false, - OtelExporterKind::Statsig => config.analytics_enabled != Some(false), + // aKode: Statsig export is disabled; only user-configured OTLP exporters observe sizes. + OtelExporterKind::None | OtelExporterKind::Statsig => false, OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. } => true, } } diff --git a/codex-rs/tui/src/tooltips.rs b/codex-rs/tui/src/tooltips.rs index eacb007d..a88ff019 100644 --- a/codex-rs/tui/src/tooltips.rs +++ b/codex-rs/tui/src/tooltips.rs @@ -13,17 +13,6 @@ use std::path::Path; #[path = "tooltips/keybinding_tests.rs"] mod keybinding_tests; -const ANNOUNCEMENT_TIP_URL: &str = - "https://raw.githubusercontent.com/openai/codex/main/announcement_tip.toml"; - -const IS_MACOS: bool = cfg!(target_os = "macos"); -const IS_WINDOWS: bool = cfg!(target_os = "windows"); - -const WINDOWS_APP_TOOLTIP: &str = "Use the **desktop app**. Install it from https://chatgpt.com/codex?app-landing-page=true and run `codex app`."; -const MACOS_APP_TOOLTIP: &str = - "Use the **desktop app**. Run `codex app` to open it. It installs automatically if needed."; -const LINUX_APP_TOOLTIP: &str = "Use the **desktop app**. Install it from https://learn.chatgpt.com/docs/linux/linux-app and run `chatgpt`."; - const RAW_TOOLTIPS: &str = include_str!("../assets/tooltips.txt"); lazy_static! { @@ -31,7 +20,6 @@ lazy_static! { .lines() .map(str::trim) .filter(|line| !line.is_empty() && !line.starts_with('#')) - .chain(app_tooltip()) .collect(); static ref ALL_TOOLTIPS: Vec<&'static str> = { let mut tips = Vec::new(); @@ -46,62 +34,10 @@ lazy_static! { } /// Pick a random tooltip to show to the user when starting Codex. -pub(crate) fn get_tooltip(plan: Option, keymap: &TuiKeymap) -> Option { +// aKode: remote announcement tips and desktop-app promotions were removed; only local tips remain. +pub(crate) fn get_tooltip(_plan: Option, keymap: &TuiKeymap) -> Option { let mut rng = rand::rng(); - preferred_tooltip(&mut rng, plan).or_else(|| pick_tooltip(&mut rng, keymap)) -} - -/// Apply the shared announcement and promotion policy before falling back to local tips. -/// The announcement lookup only reads the prewarmed cache. -pub(crate) fn preferred_tooltip( - rng: &mut R, - plan: Option, -) -> Option { - if let Some(announcement) = announcement::fetch_announcement_tip(plan) { - return Some(announcement); - } - - // Leave small chance for a random tooltip to be shown. - if rng.random_ratio(/*numerator*/ 8, /*denominator*/ 10) { - return app_tooltip().map(str::to_string); - } - - None -} - -struct LinuxDesktopSession { - has_display: bool, - is_wsl: bool, -} - -impl LinuxDesktopSession { - fn current() -> Self { - #[cfg(target_os = "linux")] - { - Self { - has_display: std::env::var_os("DISPLAY").is_some_and(|value| !value.is_empty()) - || std::env::var_os("WAYLAND_DISPLAY").is_some_and(|value| !value.is_empty()), - is_wsl: crate::clipboard_paste::is_probably_wsl(), - } - } - - #[cfg(not(target_os = "linux"))] - { - Self { - has_display: false, - is_wsl: false, - } - } - } -} - -fn linux_app_tooltip(session: LinuxDesktopSession) -> Option<&'static str> { - (session.has_display && !session.is_wsl).then_some(LINUX_APP_TOOLTIP) -} - -fn app_tooltip() -> Option<&'static str> { - // aKode: no desktop-app promotion. - None + pick_tooltip(&mut rng, keymap) } fn pick_tooltip(rng: &mut R, keymap: &TuiKeymap) -> Option { @@ -155,210 +91,9 @@ pub(crate) fn render_tooltip(mut template: &str, keymap: Option<&RuntimeKeymap>) Some(rendered) } -pub(crate) mod announcement { - use crate::tooltips::ANNOUNCEMENT_TIP_URL; - use crate::version::CODEX_CLI_VERSION; - use chrono::NaiveDate; - use chrono::Utc; - use codex_http_client::ClientRouteClass; - use codex_http_client::HttpClientFactory; - use codex_http_client::RouteAwareClientPool; - use codex_protocol::account::PlanType; - use regex_lite::Regex; - use serde::Deserialize; - use std::sync::OnceLock; - use std::time::Duration; - - static ANNOUNCEMENT_TIP: OnceLock> = OnceLock::new(); - const CURRENT_OS: TargetOs = TargetOs::current(); - - /// Prewarm the cache of the announcement tip. - pub(crate) fn prewarm(http_client_factory: HttpClientFactory) { - // aKode: announcement tips are never fetched from the network. - let _ = http_client_factory; - let _ = ANNOUNCEMENT_TIP.set(None); - } - - /// Fetch the announcement tip, return None if the prewarm is not done yet. - pub(crate) fn fetch_announcement_tip(plan: Option) -> Option { - ANNOUNCEMENT_TIP - .get() - .and_then(Option::as_ref) - .and_then(|tips| tips.select(plan)) - } - - #[derive(Debug, Deserialize)] - struct AnnouncementTipRaw { - content: String, - from_date: Option, - to_date: Option, - version_regex: Option, - target_app: Option, - target_plan_types: Option>, - target_oses: Option>, - } - - #[derive(Debug, Deserialize)] - struct AnnouncementTipDocument { - announcements: Vec, - } - - #[derive(Debug)] - struct AnnouncementTip { - content: String, - from_date: Option, - to_date: Option, - version_regex: Option, - target_app: String, - target_plan_types: Option>, - target_oses: Option>, - } - - #[derive(Debug, Deserialize, Copy, Clone, PartialEq, Eq)] - #[serde(rename_all = "lowercase")] - enum TargetOs { - Linux, - Macos, - Windows, - #[serde(other)] - Unknown, - } - - impl TargetOs { - const fn current() -> Self { - if cfg!(target_os = "macos") { - Self::Macos - } else if cfg!(target_os = "windows") { - Self::Windows - } else { - // Codex currently publishes CLI builds for macOS, Windows, and Linux. - Self::Linux - } - } - } - - async fn fetch_announcement_tip_text(http_client_factory: HttpClientFactory) -> Option { - let client = RouteAwareClientPool::new(http_client_factory, ClientRouteClass::Other); - let response = client - .get(ANNOUNCEMENT_TIP_URL) - .timeout(Duration::from_millis(2000)) - .send() - .await - .ok()?; - response.error_for_status().ok()?.text().await.ok() - } - - /// Parsed once during prewarming; eligibility stays current across redraws and account changes. - pub(super) struct AnnouncementTips(Vec); - - impl AnnouncementTips { - pub(super) fn parse(text: &str) -> Option { - let announcements = toml::from_str::(text) - .map(|doc| doc.announcements) - .or_else(|_| toml::from_str::>(text)) - .ok()?; - Some(Self( - announcements - .into_iter() - .filter_map(AnnouncementTip::from_raw) - .collect(), - )) - } - - pub(super) fn select(&self, plan: Option) -> Option { - let today = Utc::now().date_naive(); - self.0 - .iter() - .rev() - .find(|tip| { - let plan_matches = tip.target_plan_types.as_ref().is_none_or(|target_plans| { - plan.is_some_and(|plan| target_plans.contains(&plan)) - }); - let os_matches = tip - .target_oses - .as_ref() - .is_none_or(|target_oses| target_oses.contains(&CURRENT_OS)); - tip.version_matches(CODEX_CLI_VERSION) - && tip.date_matches(today) - && tip.target_app == "cli" - && plan_matches - && os_matches - }) - .map(|tip| tip.content.clone()) - } - } - - impl AnnouncementTip { - fn from_raw(raw: AnnouncementTipRaw) -> Option { - let content = raw.content.trim(); - if content.is_empty() { - return None; - } - - let from_date = match raw.from_date { - Some(date) => Some(NaiveDate::parse_from_str(&date, "%Y-%m-%d").ok()?), - None => None, - }; - let to_date = match raw.to_date { - Some(date) => Some(NaiveDate::parse_from_str(&date, "%Y-%m-%d").ok()?), - None => None, - }; - let version_regex = match raw.version_regex { - Some(pattern) => Some(Regex::new(&pattern).ok()?), - None => None, - }; - let target_plan_types = raw.target_plan_types; - if target_plan_types - .as_ref() - .is_some_and(|plans| plans.contains(&PlanType::Unknown)) - { - return None; - } - let target_oses = raw.target_oses; - if target_oses - .as_ref() - .is_some_and(|oses| oses.contains(&TargetOs::Unknown)) - { - return None; - } - - Some(Self { - content: content.to_string(), - from_date, - to_date, - version_regex, - target_app: raw.target_app.unwrap_or("cli".to_string()).to_lowercase(), - target_plan_types, - target_oses, - }) - } - - fn version_matches(&self, version: &str) -> bool { - self.version_regex - .as_ref() - .is_none_or(|regex| regex.is_match(version)) - } - - fn date_matches(&self, today: NaiveDate) -> bool { - if let Some(from) = self.from_date - && today < from - { - return false; - } - if let Some(to) = self.to_date - && today >= to - { - return false; - } - true - } - } -} - #[cfg(test)] mod tests { use super::*; - use crate::tooltips::announcement::AnnouncementTips; use pretty_assertions::assert_eq; use rand::SeedableRng; use rand::rngs::StdRng; @@ -379,292 +114,4 @@ mod tests { let mut rng = StdRng::seed_from_u64(7); assert_eq!(expected, pick_tooltip(&mut rng, &TuiKeymap::default())); } - - #[test] - fn desktop_app_tips_render_at_narrow_width() { - let cwd = std::env::current_dir().unwrap(); - for (platform, tip) in [ - ("macos", MACOS_APP_TOOLTIP), - ("windows", WINDOWS_APP_TOOLTIP), - ("linux", LINUX_APP_TOOLTIP), - ] { - let rendered = render_tooltip_lines(tip, /*width*/ 40, &cwd) - .iter() - .map(|line| format!("{:?} {:?}", line.line, line.hyperlinks)) - .collect::>() - .join("\n"); - insta::assert_snapshot!(format!("desktop_app_tip_{platform}"), rendered); - } - } - - #[test] - fn desktop_app_tooltip_uses_supported_platform_launcher() { - let tooltip = TOOLTIPS - .iter() - .copied() - .find(|tip| tip.contains("desktop app")); - - if linux_app_tooltip(LinuxDesktopSession::current()).is_some() { - let tooltip = tooltip.expect("Linux should advertise the desktop app"); - assert_eq!(app_tooltip(), Some(tooltip)); - } else if IS_MACOS { - let tooltip = tooltip.expect("macOS should advertise the desktop app"); - assert_eq!(app_tooltip(), Some(tooltip)); - } else if IS_WINDOWS { - let tooltip = tooltip.expect("Windows should advertise the desktop app"); - assert_eq!(app_tooltip(), Some(tooltip)); - } else { - assert_eq!(tooltip, None); - assert_eq!(app_tooltip(), None); - } - } - - #[test] - fn linux_desktop_app_tooltip_requires_graphical_native_session() { - assert_eq!( - linux_app_tooltip(LinuxDesktopSession { - has_display: true, - is_wsl: false, - }), - Some(LINUX_APP_TOOLTIP) - ); - - assert_eq!( - linux_app_tooltip(LinuxDesktopSession { - has_display: false, - is_wsl: false, - }), - None - ); - assert_eq!( - linux_app_tooltip(LinuxDesktopSession { - has_display: true, - is_wsl: true, - }), - None - ); - } - - #[test] - fn plans_use_platform_app_tip() { - for plan in [ - Some(PlanType::Free), - Some(PlanType::Go), - Some(PlanType::Plus), - Some(PlanType::Pro), - None, - ] { - let mut seen = std::collections::BTreeSet::new(); - for seed in 0..32 { - let mut rng = StdRng::seed_from_u64(seed); - seen.insert(preferred_tooltip(&mut rng, plan)); - } - assert_eq!( - seen, - std::collections::BTreeSet::from([None, app_tooltip().map(str::to_string)]) - ); - } - } - - #[test] - fn announcement_tip_toml_picks_last_matching() { - let toml = r#" -[[announcements]] -content = "first" -from_date = "2000-01-01" - -[[announcements]] -content = "latest match" -version_regex = ".*" -target_app = "cli" - -[[announcements]] -content = "should not match" -to_date = "2000-01-01" - "#; - - assert_eq!( - Some("latest match".to_string()), - AnnouncementTips::parse(toml).and_then(|tips| tips.select(/*plan*/ None)) - ); - - let toml = r#" -[[announcements]] -content = "first" -from_date = "2000-01-01" -target_app = "cli" - -[[announcements]] -content = "latest match" -version_regex = ".*" - -[[announcements]] -content = "should not match" -to_date = "2000-01-01" - "#; - - assert_eq!( - Some("latest match".to_string()), - AnnouncementTips::parse(toml).and_then(|tips| tips.select(/*plan*/ None)) - ); - } - - #[test] - fn announcement_tip_toml_picks_no_match() { - let toml = r#" -[[announcements]] -content = "first" -from_date = "2000-01-01" -to_date = "2000-01-05" - -[[announcements]] -content = "latest match" -version_regex = "invalid_version_name" - -[[announcements]] -content = "should not match either " -target_app = "vsce" - "#; - - assert_eq!( - None, - AnnouncementTips::parse(toml).and_then(|tips| tips.select(/*plan*/ None)) - ); - } - - #[test] - fn announcement_tip_toml_bad_deserialization() { - let toml = r#" -[[announcements]] -content = 123 -from_date = "2000-01-01" - "#; - - assert_eq!( - None, - AnnouncementTips::parse(toml).and_then(|tips| tips.select(/*plan*/ None)) - ); - } - - #[test] - fn announcement_tip_toml_parse_comments() { - let toml = r#" -# Example announcement tips for Codex TUI. -# Each [[announcements]] entry is evaluated in order; the last matching one is shown. -# Dates are UTC, formatted as YYYY-MM-DD. The from_date is inclusive and the to_date is exclusive. -# version_regex matches against the CLI version (env!("CARGO_PKG_VERSION")); omit to apply to all versions. -# target_app specify which app should display the announcement (cli, vsce, ...). -# target_plan_types optionally restricts the announcement to plan types like ["plus", "pro"]. -# target_oses optionally restricts the announcement to operating systems like ["macos", "windows"]. - -[[announcements]] -content = "Welcome to Codex! Check out the new onboarding flow." -from_date = "2024-10-01" -to_date = "2024-10-15" -target_app = "cli" -version_regex = "^0\\.0\\.0$" - -[[announcements]] -content = "This is a test announcement" - "#; - - assert_eq!( - Some("This is a test announcement".to_string()), - AnnouncementTips::parse(toml).and_then(|tips| tips.select(/*plan*/ None)) - ); - } - - #[test] - fn announcement_tip_toml_matches_target_plan_type() { - let toml = r#" -[[announcements]] -content = "all plans" - -[[announcements]] -content = "pro announcement" -target_plan_types = ["pro", "enterprise"] - -[[announcements]] -content = "free announcement" -target_plan_types = ["free"] - "#; - - let tips = AnnouncementTips::parse(toml).unwrap(); - assert_eq!( - Some("pro announcement".to_string()), - tips.select(Some(PlanType::Pro)) - ); - assert_eq!( - Some("free announcement".to_string()), - tips.select(Some(PlanType::Free)) - ); - assert_eq!( - Some("all plans".to_string()), - tips.select(Some(PlanType::Plus)) - ); - assert_eq!(Some("all plans".to_string()), tips.select(/*plan*/ None)); - } - - #[test] - fn announcement_tip_toml_rejects_unknown_target_plan_type() { - let toml = r#" -[[announcements]] -content = "all plans" - -[[announcements]] -content = "typo announcement" -target_plan_types = ["prp"] - "#; - - assert_eq!( - Some("all plans".to_string()), - AnnouncementTips::parse(toml).and_then(|tips| tips.select(Some(PlanType::Unknown))) - ); - } - - #[test] - fn announcement_tip_toml_matches_target_os() { - let toml = r#" -[[announcements]] -content = "linux announcement" -target_oses = ["linux"] - -[[announcements]] -content = "macos announcement" -target_oses = ["macos"] - -[[announcements]] -content = "windows announcement" -target_oses = ["windows"] - "#; - - let expected = if cfg!(target_os = "macos") { - "macos announcement" - } else if cfg!(target_os = "windows") { - "windows announcement" - } else { - "linux announcement" - }; - assert_eq!( - Some(expected.to_string()), - AnnouncementTips::parse(toml).and_then(|tips| tips.select(/*plan*/ None)) - ); - } - - #[test] - fn announcement_tip_toml_rejects_unknown_target_os() { - let toml = r#" -[[announcements]] -content = "all operating systems" - -[[announcements]] -content = "typo announcement" -target_oses = ["amiga"] - "#; - - assert_eq!( - Some("all operating systems".to_string()), - AnnouncementTips::parse(toml).and_then(|tips| tips.select(/*plan*/ None)) - ); - } } diff --git a/codex-rs/tui/src/update_versions.rs b/codex-rs/tui/src/update_versions.rs index b0aa3deb..02728de5 100644 --- a/codex-rs/tui/src/update_versions.rs +++ b/codex-rs/tui/src/update_versions.rs @@ -1,24 +1,4 @@ -#[cfg(any(not(debug_assertions), test))] -pub(crate) fn is_newer(latest: &str, current: &str) -> Option { - match (parse_version(latest), parse_version(current)) { - (Some(l), Some(c)) => Some(l > c), - _ => None, - } -} - -#[cfg(any(not(debug_assertions), test))] -pub(crate) fn extract_version_from_latest_tag(latest_tag_name: &str) -> anyhow::Result { - latest_tag_name - .strip_prefix("rust-v") - .map(str::to_owned) - .ok_or_else(|| anyhow::anyhow!("Failed to parse latest tag name '{latest_tag_name}'")) -} - -#[cfg(any(not(debug_assertions), test))] -pub(crate) fn is_source_build_version(version: &str) -> bool { - parse_version(version) == Some((0, 0, 0)) -} - +// aKode: release-tag and npm version helpers were removed with the remote update checks. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum ServerVersionNoticeKind { Older, @@ -43,59 +23,11 @@ pub(crate) fn server_version_notice_kind( .then_some(ServerVersionNoticeKind::Older) } -#[cfg(any(not(debug_assertions), test))] -fn parse_version(v: &str) -> Option<(u64, u64, u64)> { - let mut iter = v.trim().split('.'); - let maj = iter.next()?.parse::().ok()?; - let min = iter.next()?.parse::().ok()?; - let pat = iter.next()?.parse::().ok()?; - Some((maj, min, pat)) -} - #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; - #[test] - fn extracts_version_from_latest_tag() { - assert_eq!( - extract_version_from_latest_tag("rust-v1.5.0").expect("failed to parse version"), - "1.5.0" - ); - } - - #[test] - fn latest_tag_without_prefix_is_invalid() { - assert!(extract_version_from_latest_tag("v1.5.0").is_err()); - } - - #[test] - fn prerelease_version_is_not_considered_newer() { - assert_eq!(is_newer("0.11.0-beta.1", "0.11.0"), None); - assert_eq!(is_newer("1.0.0-rc.1", "1.0.0"), None); - } - - #[test] - fn plain_semver_comparisons_work() { - assert_eq!(is_newer("0.11.1", "0.11.0"), Some(true)); - assert_eq!(is_newer("0.11.0", "0.11.1"), Some(false)); - assert_eq!(is_newer("1.0.0", "0.9.9"), Some(true)); - assert_eq!(is_newer("0.9.9", "1.0.0"), Some(false)); - } - - #[test] - fn source_build_version_is_not_checked() { - assert!(is_source_build_version("0.0.0")); - assert!(!is_source_build_version("0.1.0")); - } - - #[test] - fn whitespace_is_ignored() { - assert_eq!(parse_version(" 1.2.3 \n"), Some((1, 2, 3))); - assert_eq!(is_newer(" 1.2.3 ", "1.2.2"), Some(true)); - } - #[test] fn stable_clients_only_warn_for_older_releases() { for (client, server, expected) in [ diff --git a/codex-rs/tui/src/updates.rs b/codex-rs/tui/src/updates.rs index ff1744ff..23cbddcf 100644 --- a/codex-rs/tui/src/updates.rs +++ b/codex-rs/tui/src/updates.rs @@ -1,26 +1,6 @@ #![cfg(not(debug_assertions))] use crate::legacy_core::config::Config; -use crate::npm_registry; -use crate::npm_registry::NpmPackageInfo; -use crate::update_action; -use crate::update_action::UpdateAction; -use crate::update_versions::extract_version_from_latest_tag; -use crate::update_versions::is_newer; -use crate::update_versions::is_source_build_version; -use crate::updates_cache::VersionInfo; -use crate::updates_cache::read_version_info; -use crate::updates_cache::version_filepath; -use chrono::Duration; -use chrono::Utc; -use codex_http_client::ClientRouteClass; -use codex_http_client::HttpClientFactory; -use codex_http_client::RouteAwareClientPool; -use codex_login::default_client::default_headers; -use serde::Deserialize; -use std::path::Path; - -use crate::version::CODEX_CLI_VERSION; pub(crate) use crate::updates_cache::dismiss_version; @@ -30,96 +10,6 @@ pub fn get_upgrade_version(config: &Config) -> Option { None } -// We use the latest version from the cask if installation is via homebrew - homebrew does not immediately pick up the latest release and can lag behind. -const HOMEBREW_CASK_API_URL: &str = "https://formulae.brew.sh/api/cask/codex.json"; -const LATEST_RELEASE_URL: &str = "https://api.github.com/repos/openai/codex/releases/latest"; - -#[derive(Deserialize, Debug, Clone)] -struct ReleaseInfo { - tag_name: String, -} - -#[derive(Deserialize, Debug, Clone)] -struct HomebrewCaskInfo { - version: String, -} - -async fn check_for_update( - version_file: &Path, - action: Option, - http_client_factory: HttpClientFactory, -) -> anyhow::Result<()> { - let client_pool = RouteAwareClientPool::with_chatgpt_cloudflare_cookies( - http_client_factory, - ClientRouteClass::Other, - ) - .with_legacy_custom_ca_fallback(); - let latest_version = match action { - Some(UpdateAction::Daemon(_)) => return Ok(()), - Some(UpdateAction::BrewUpgrade) => { - let HomebrewCaskInfo { version } = client_pool - .get(HOMEBREW_CASK_API_URL) - .headers(default_headers()) - .send() - .await? - .error_for_status()? - .json::() - .await?; - version - } - Some(UpdateAction::NpmGlobalLatest) - | Some(UpdateAction::BunGlobalLatest) - | Some(UpdateAction::VitePlusGlobalLatest) - | Some(UpdateAction::PnpmGlobalLatest) => { - let latest_version = fetch_latest_github_release_version(&client_pool).await?; - let package_info = client_pool - .get(npm_registry::PACKAGE_URL) - .headers(default_headers()) - .send() - .await? - .error_for_status()? - .json::() - .await?; - npm_registry::ensure_version_ready(&package_info, &latest_version)?; - latest_version - } - Some(UpdateAction::StandaloneUnix) | Some(UpdateAction::StandaloneWindows) | None => { - fetch_latest_github_release_version(&client_pool).await? - } - }; - - // Preserve any previously dismissed version if present. - let prev_info = read_version_info(version_file).ok(); - let info = VersionInfo { - latest_version, - last_checked_at: Utc::now(), - dismissed_version: prev_info.and_then(|p| p.dismissed_version), - }; - - let json_line = format!("{}\n", serde_json::to_string(&info)?); - if let Some(parent) = version_file.parent() { - tokio::fs::create_dir_all(parent).await?; - } - tokio::fs::write(version_file, json_line).await?; - Ok(()) -} - -async fn fetch_latest_github_release_version( - client_pool: &RouteAwareClientPool, -) -> anyhow::Result { - let ReleaseInfo { - tag_name: latest_tag_name, - } = client_pool - .get(LATEST_RELEASE_URL) - .headers(default_headers()) - .send() - .await? - .error_for_status()? - .json::() - .await?; - extract_version_from_latest_tag(&latest_tag_name) -} - /// Returns the latest version to show in a popup, if it should be shown. /// This respects the user's dismissal choice for the current latest version. pub fn get_upgrade_version_for_popup(config: &Config) -> Option {