From e4209e2755c306e18a68d065df7fa838c28ab327 Mon Sep 17 00:00:00 2001 From: Andrea Date: Mon, 9 Nov 2026 13:55:36 +0100 Subject: [PATCH] aKode fase 2b-1 (WIP): rimossi cloud-config, apps MCP ChatGPT, upload file, connectors-extension, rate limits backend; plugin remoti in corso (test non ancora compilanti) --- codex-rs/Cargo.lock | 59 - codex-rs/Cargo.toml | 4 - codex-rs/app-server/Cargo.toml | 1 - codex-rs/app-server/src/app_info.rs | 175 -- .../src/application_network_tests.rs | 29 +- .../src/chatgpt_connectors/chatgpt_client.rs | 243 --- .../chatgpt_client_runtime_auth_tests.rs | 321 --- .../app-server/src/chatgpt_connectors/mod.rs | 525 ----- codex-rs/app-server/src/config_manager.rs | 34 +- codex-rs/app-server/src/extensions.rs | 13 +- .../app-server/src/in_process_bootstrap.rs | 29 - .../src/in_process_bootstrap_tests.rs | 129 -- codex-rs/app-server/src/lib.rs | 3 - codex-rs/app-server/src/mcp_refresh.rs | 2 - codex-rs/app-server/src/message_processor.rs | 75 +- codex-rs/app-server/src/request_processors.rs | 44 - .../request_processors/account_processor.rs | 508 ----- .../account_processor/backend_client.rs | 31 - .../account_processor/rate_limit_resets.rs | 169 -- .../src/request_processors/apps_processor.rs | 497 ----- .../apps_processor/installed.rs | 293 --- .../apps_processor/installed_tests.rs | 149 -- .../request_processors/apps_processor/read.rs | 108 - .../src/request_processors/plugins.rs | 156 +- .../request_processors/thread_lifecycle.rs | 12 - .../thread_listener_shutdown_tests.rs | 1 - .../request_processors/thread_processor.rs | 5 - .../src/request_processors/turn_processor.rs | 4 - codex-rs/app-server/src/turn_cost_worker.rs | 555 ----- .../src/turn_cost_worker_chatgpt.rs | 86 - .../src/turn_cost_worker_chatgpt_tests.rs | 73 - .../turn_cost_worker_runtime_auth_tests.rs | 124 -- .../app-server/src/turn_cost_worker_tests.rs | 507 ----- .../tests/suite/v2/app_installed.rs | 641 ------ .../app-server/tests/suite/v2/app_list.rs | 1764 ---------------- .../app-server/tests/suite/v2/app_read.rs | 941 --------- .../tests/suite/v2/git_attribution.rs | 539 ----- codex-rs/app-server/tests/suite/v2/mod.rs | 11 - .../tests/suite/v2/plugin_install.rs | 3 - .../tests/suite/v2/plugin_reconcile.rs | 332 --- .../tests/suite/v2/plugin_runtime_auth.rs | 194 -- .../app-server/tests/suite/v2/plugin_share.rs | 1550 -------------- .../suite/v2/rate_limit_reset_credits.rs | 354 ---- .../app-server/tests/suite/v2/rate_limits.rs | 1095 ---------- .../suite/v2/rate_limits_identity_tests.rs | 236 --- .../tests/suite/v2/recommended_plugins.rs | 225 -- .../suite/v2/selected_capability_stack.rs | 426 ---- codex-rs/cli/Cargo.toml | 1 - codex-rs/cli/src/cloud_config.rs | 31 +- codex-rs/cli/src/debug_sandbox.rs | 11 +- .../cli/src/debug_sandbox/cloud_config.rs | 57 - .../src/debug_sandbox/cloud_config_tests.rs | 185 -- codex-rs/cli/src/login.rs | 54 +- codex-rs/cli/src/main.rs | 9 +- codex-rs/cloud-config/BUILD.bazel | 6 - codex-rs/cloud-config/Cargo.toml | 38 - codex-rs/cloud-config/src/backend.rs | 166 -- codex-rs/cloud-config/src/bundle_loader.rs | 261 --- codex-rs/cloud-config/src/cache.rs | 292 --- codex-rs/cloud-config/src/cache_tests.rs | 212 -- codex-rs/cloud-config/src/chatgpt.rs | 103 - codex-rs/cloud-config/src/config_server.rs | 274 --- .../cloud-config/src/config_server_tests.rs | 209 -- codex-rs/cloud-config/src/config_source.rs | 43 - codex-rs/cloud-config/src/lib.rs | 25 - codex-rs/cloud-config/src/metrics.rs | 95 - codex-rs/cloud-config/src/service.rs | 521 ----- codex-rs/cloud-config/src/service_tests.rs | 1832 ----------------- codex-rs/cloud-config/src/validation.rs | 48 - codex-rs/cloud-config/src/validation_tests.rs | 78 - codex-rs/codex-api/src/files.rs | 937 --------- codex-rs/codex-api/src/files_retry_tests.rs | 234 --- codex-rs/codex-api/src/lib.rs | 4 - codex-rs/codex-mcp/src/binding_tests.rs | 1 - codex-rs/codex-mcp/src/codex_apps.rs | 5 - .../codex-mcp/src/codex_apps/file_params.rs | 219 -- .../src/codex_apps/file_params_tests.rs | 284 --- .../codex-mcp/src/connection_manager_tests.rs | 1 - codex-rs/codex-mcp/src/lib.rs | 4 - codex-rs/codex-mcp/src/mcp/mod.rs | 108 +- codex-rs/codex-mcp/src/rmcp_client.rs | 8 +- codex-rs/codex-mcp/src/tools.rs | 5 - .../core-plugins/src/discoverable_tests.rs | 244 --- .../core-plugins/src/http_client_selector.rs | 23 - codex-rs/core-plugins/src/lib.rs | 3 - codex-rs/core-plugins/src/manager_errors.rs | 1 + codex-rs/core-plugins/src/manager_tests.rs | 843 -------- .../core-plugins/src/plugin_bundle_archive.rs | 157 -- .../src/plugin_bundle_archive_tests.rs | 41 - .../src/plugin_measurement_catalog.rs | 63 - .../src/plugin_measurement_references.rs | 244 --- .../plugin_measurement_references_tests.rs | 775 ------- .../src/plugins_config_input_tests.rs | 76 - codex-rs/core-plugins/src/remote.rs | 511 +---- .../src/remote/plugin_capabilities_tests.rs | 100 - .../remote/remote_installed_plugin_sync.rs | 299 --- codex-rs/core-plugins/src/remote/search.rs | 57 +- .../core-plugins/src/remote/search_tests.rs | 490 ----- codex-rs/core-plugins/src/remote/share.rs | 403 +--- .../src/remote/share/local_paths.rs | 10 - .../core-plugins/src/remote/share/tests.rs | 824 -------- codex-rs/core-plugins/src/remote_bundle.rs | 173 +- .../src/remote_bundle_runtime_auth_tests.rs | 55 - codex-rs/core-plugins/src/remote_legacy.rs | 125 +- codex-rs/core-plugins/src/remote_mutations.rs | 3 - .../src/remote_mutations_tests.rs | 473 ----- .../src/remote_runtime_auth_tests.rs | 307 --- codex-rs/core-plugins/src/remote_tests.rs | 1009 --------- .../core-plugins/src/script_attribution.rs | 25 - codex-rs/core-plugins/src/test_support.rs | 86 - codex-rs/core/Cargo.toml | 1 - codex-rs/core/src/connectors.rs | 5 +- codex-rs/core/src/connectors_tests.rs | 3 - codex-rs/core/src/lib.rs | 1 - codex-rs/core/src/mcp.rs | 36 +- codex-rs/core/src/mcp_openai_file.rs | 718 ------- codex-rs/core/src/mcp_tool_call.rs | 43 +- codex-rs/core/src/mcp_tool_call_tests.rs | 26 - codex-rs/core/src/mcp_tool_exposure_test.rs | 1 - codex-rs/core/src/session/session.rs | 20 - codex-rs/core/src/session/tests.rs | 8 - codex-rs/core/src/state/service.rs | 2 - codex-rs/core/src/tools/handlers/mcp.rs | 1 - .../src/tools/handlers/mcp_search_tests.rs | 1 - .../core/src/tools/handlers/tool_search.rs | 1 - codex-rs/core/src/tools/router_tests.rs | 1 - codex-rs/core/src/tools/spec_plan_tests.rs | 1 - .../tests/suite/analytics_runtime_auth.rs | 142 -- codex-rs/core/tests/suite/mod.rs | 4 - codex-rs/core/tests/suite/openai_file_mcp.rs | 442 ---- .../tests/suite/request_plugin_install.rs | 3 - .../request_plugin_install_runtime_auth.rs | 248 --- codex-rs/core/tests/suite/runtime_auth.rs | 1157 ----------- .../core/tests/suite/runtime_auth_denials.rs | 215 -- codex-rs/exec-server-cli/Cargo.toml | 1 - codex-rs/exec-server-cli/src/command.rs | 12 - codex-rs/exec-server-cli/src/config.rs | 56 +- .../src/exec_server_args_tests.rs | 6 +- codex-rs/exec/Cargo.toml | 1 - codex-rs/exec/src/lib.rs | 32 +- codex-rs/ext/connectors/BUILD.bazel | 6 - codex-rs/ext/connectors/Cargo.toml | 24 - codex-rs/ext/connectors/src/lib.rs | 6 - codex-rs/ext/connectors/src/plugin_app.rs | 68 - codex-rs/ext/git-attribution/Cargo.toml | 11 - .../src/git_attribution_tests.rs | 236 --- codex-rs/ext/git-attribution/src/lib.rs | 100 +- codex-rs/ext/git-attribution/src/policy.rs | 122 -- codex-rs/ext/mcp/Cargo.toml | 1 - codex-rs/ext/mcp/src/lib.rs | 46 - codex-rs/ext/mcp/src/lib_tests.rs | 61 - codex-rs/ext/mcp/src/plugin.rs | 24 +- codex-rs/ext/mcp/tests/hosted_apps_mcp.rs | 233 --- codex-rs/memories/write/Cargo.toml | 1 - codex-rs/memories/write/src/guard.rs | 83 - codex-rs/memories/write/src/guard_tests.rs | 81 - codex-rs/memories/write/src/lib.rs | 5 - codex-rs/memories/write/src/metrics.rs | 1 - codex-rs/memories/write/src/start.rs | 11 - codex-rs/memories/write/src/startup_tests.rs | 173 -- .../src/manager_tests.rs | 87 - codex-rs/tui/Cargo.toml | 1 - codex-rs/tui/src/lib.rs | 34 +- codex-rs/tui/src/startup_orchestration.rs | 28 +- codex-rs/windows-sandbox-service/Cargo.toml | 1 - .../src/machine_policy.rs | 25 +- 166 files changed, 155 insertions(+), 31558 deletions(-) delete mode 100644 codex-rs/app-server/src/app_info.rs delete mode 100644 codex-rs/app-server/src/chatgpt_connectors/chatgpt_client.rs delete mode 100644 codex-rs/app-server/src/chatgpt_connectors/chatgpt_client_runtime_auth_tests.rs delete mode 100644 codex-rs/app-server/src/chatgpt_connectors/mod.rs delete mode 100644 codex-rs/app-server/src/request_processors/account_processor/backend_client.rs delete mode 100644 codex-rs/app-server/src/request_processors/account_processor/rate_limit_resets.rs delete mode 100644 codex-rs/app-server/src/request_processors/apps_processor.rs delete mode 100644 codex-rs/app-server/src/request_processors/apps_processor/installed.rs delete mode 100644 codex-rs/app-server/src/request_processors/apps_processor/installed_tests.rs delete mode 100644 codex-rs/app-server/src/request_processors/apps_processor/read.rs delete mode 100644 codex-rs/app-server/src/turn_cost_worker.rs delete mode 100644 codex-rs/app-server/src/turn_cost_worker_chatgpt.rs delete mode 100644 codex-rs/app-server/src/turn_cost_worker_chatgpt_tests.rs delete mode 100644 codex-rs/app-server/src/turn_cost_worker_runtime_auth_tests.rs delete mode 100644 codex-rs/app-server/src/turn_cost_worker_tests.rs delete mode 100644 codex-rs/app-server/tests/suite/v2/app_installed.rs delete mode 100644 codex-rs/app-server/tests/suite/v2/app_list.rs delete mode 100644 codex-rs/app-server/tests/suite/v2/app_read.rs delete mode 100644 codex-rs/app-server/tests/suite/v2/git_attribution.rs delete mode 100644 codex-rs/app-server/tests/suite/v2/plugin_reconcile.rs delete mode 100644 codex-rs/app-server/tests/suite/v2/plugin_runtime_auth.rs delete mode 100644 codex-rs/app-server/tests/suite/v2/plugin_share.rs delete mode 100644 codex-rs/app-server/tests/suite/v2/rate_limit_reset_credits.rs delete mode 100644 codex-rs/app-server/tests/suite/v2/rate_limits.rs delete mode 100644 codex-rs/app-server/tests/suite/v2/rate_limits_identity_tests.rs delete mode 100644 codex-rs/app-server/tests/suite/v2/recommended_plugins.rs delete mode 100644 codex-rs/cli/src/debug_sandbox/cloud_config.rs delete mode 100644 codex-rs/cli/src/debug_sandbox/cloud_config_tests.rs delete mode 100644 codex-rs/cloud-config/BUILD.bazel delete mode 100644 codex-rs/cloud-config/Cargo.toml delete mode 100644 codex-rs/cloud-config/src/backend.rs delete mode 100644 codex-rs/cloud-config/src/bundle_loader.rs delete mode 100644 codex-rs/cloud-config/src/cache.rs delete mode 100644 codex-rs/cloud-config/src/cache_tests.rs delete mode 100644 codex-rs/cloud-config/src/chatgpt.rs delete mode 100644 codex-rs/cloud-config/src/config_server.rs delete mode 100644 codex-rs/cloud-config/src/config_server_tests.rs delete mode 100644 codex-rs/cloud-config/src/config_source.rs delete mode 100644 codex-rs/cloud-config/src/lib.rs delete mode 100644 codex-rs/cloud-config/src/metrics.rs delete mode 100644 codex-rs/cloud-config/src/service.rs delete mode 100644 codex-rs/cloud-config/src/service_tests.rs delete mode 100644 codex-rs/cloud-config/src/validation.rs delete mode 100644 codex-rs/cloud-config/src/validation_tests.rs delete mode 100644 codex-rs/codex-api/src/files.rs delete mode 100644 codex-rs/codex-api/src/files_retry_tests.rs delete mode 100644 codex-rs/codex-mcp/src/codex_apps/file_params.rs delete mode 100644 codex-rs/codex-mcp/src/codex_apps/file_params_tests.rs delete mode 100644 codex-rs/core-plugins/src/plugin_bundle_archive_tests.rs delete mode 100644 codex-rs/core-plugins/src/plugin_measurement_catalog.rs delete mode 100644 codex-rs/core-plugins/src/plugin_measurement_references.rs delete mode 100644 codex-rs/core-plugins/src/plugin_measurement_references_tests.rs delete mode 100644 codex-rs/core-plugins/src/remote/search_tests.rs delete mode 100644 codex-rs/core-plugins/src/remote/share/tests.rs delete mode 100644 codex-rs/core-plugins/src/remote_bundle_runtime_auth_tests.rs delete mode 100644 codex-rs/core-plugins/src/remote_mutations_tests.rs delete mode 100644 codex-rs/core-plugins/src/remote_runtime_auth_tests.rs delete mode 100644 codex-rs/core-plugins/src/remote_tests.rs delete mode 100644 codex-rs/core/src/mcp_openai_file.rs delete mode 100644 codex-rs/core/tests/suite/analytics_runtime_auth.rs delete mode 100644 codex-rs/core/tests/suite/openai_file_mcp.rs delete mode 100644 codex-rs/core/tests/suite/request_plugin_install_runtime_auth.rs delete mode 100644 codex-rs/core/tests/suite/runtime_auth.rs delete mode 100644 codex-rs/core/tests/suite/runtime_auth_denials.rs delete mode 100644 codex-rs/ext/connectors/BUILD.bazel delete mode 100644 codex-rs/ext/connectors/Cargo.toml delete mode 100644 codex-rs/ext/connectors/src/lib.rs delete mode 100644 codex-rs/ext/connectors/src/plugin_app.rs delete mode 100644 codex-rs/ext/git-attribution/src/git_attribution_tests.rs delete mode 100644 codex-rs/ext/git-attribution/src/policy.rs delete mode 100644 codex-rs/ext/mcp/src/lib_tests.rs delete mode 100644 codex-rs/ext/mcp/tests/hosted_apps_mcp.rs delete mode 100644 codex-rs/memories/write/src/guard.rs delete mode 100644 codex-rs/memories/write/src/guard_tests.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index e187f365..cb6222ba 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2100,7 +2100,6 @@ dependencies = [ "codex-arg0", "codex-aws-auth", "codex-backend-client", - "codex-cloud-config", "codex-code-mode", "codex-config", "codex-connectors", @@ -2539,7 +2538,6 @@ dependencies = [ "codex-app-server-test-client", "codex-arg0", "codex-build-info", - "codex-cloud-config", "codex-config", "codex-core", "codex-core-plugins", @@ -2635,34 +2633,6 @@ dependencies = [ "url", ] -[[package]] -name = "codex-cloud-config" -version = "0.0.0" -dependencies = [ - "base64 0.22.1", - "chrono", - "codex-agent-identity", - "codex-async-utils", - "codex-backend-client", - "codex-config", - "codex-core", - "codex-http-client", - "codex-keyring-store", - "codex-login", - "codex-otel", - "codex-protocol", - "hmac 0.12.1", - "pretty_assertions", - "serde", - "serde_json", - "sha2 0.10.9", - "tempfile", - "thiserror 2.0.18", - "tokio", - "tracing", - "wiremock", -] - [[package]] name = "codex-code-mode" version = "0.0.0" @@ -2847,20 +2817,6 @@ dependencies = [ "urlencoding", ] -[[package]] -name = "codex-connectors-extension" -version = "0.0.0" -dependencies = [ - "codex-connectors", - "codex-core-plugins", - "codex-file-system", - "codex-plugin", - "codex-utils-path-uri", - "serde_json", - "thiserror 2.0.18", - "tracing", -] - [[package]] name = "codex-context-fragments" version = "0.0.0" @@ -2893,7 +2849,6 @@ dependencies = [ "codex-apply-patch", "codex-async-utils", "codex-attachment-store", - "codex-backend-client", "codex-client", "codex-code-mode", "codex-config", @@ -3150,7 +3105,6 @@ dependencies = [ "codex-app-server-protocol", "codex-apply-patch", "codex-arg0", - "codex-cloud-config", "codex-config", "codex-core", "codex-exec-server", @@ -3278,7 +3232,6 @@ dependencies = [ "codex-arg0", "codex-aws-auth", "codex-build-info", - "codex-cloud-config", "codex-config", "codex-core", "codex-exec-server", @@ -3524,16 +3477,8 @@ dependencies = [ name = "codex-git-attribution" version = "0.0.0" dependencies = [ - "codex-backend-client", "codex-extension-api", - "codex-features", - "codex-http-client", - "codex-login", - "codex-model-provider", - "codex-runtime-agent-instance", "serde_json", - "tokio", - "wiremock", ] [[package]] @@ -4041,7 +3986,6 @@ dependencies = [ "axum", "codex-config", "codex-connectors", - "codex-connectors-extension", "codex-core", "codex-core-plugins", "codex-exec-server", @@ -4105,7 +4049,6 @@ dependencies = [ "anyhow", "base64 0.22.1", "chrono", - "codex-backend-client", "codex-config", "codex-core", "codex-features", @@ -5046,7 +4989,6 @@ dependencies = [ "codex-arg0", "codex-backend-client", "codex-build-info", - "codex-cloud-config", "codex-config", "codex-connectors", "codex-context-fragments", @@ -5626,7 +5568,6 @@ name = "codex-windows-sandbox-service" version = "0.0.0" dependencies = [ "anyhow", - "codex-cloud-config", "codex-config", "codex-core", "codex-windows-sandbox", diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index bbe8364a..18fd7e02 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -32,7 +32,6 @@ members = [ "code-mode-runtime", "plugin-host", "codex-home", - "cloud-config", "cli", "collaboration-mode-templates", "connectors", @@ -61,7 +60,6 @@ members = [ "execpolicy", "ext/agent", "ext/agent-message-board", - "ext/connectors", "ext/extension-api", "ext/multi-env-copy-file", "ext/goal", @@ -201,7 +199,6 @@ codex-backend-client = { path = "backend-client" } codex-build-info = { path = "build-info" } codex-client = { path = "codex-client" } codex-collaboration-mode-templates = { path = "collaboration-mode-templates" } -codex-cloud-config = { path = "cloud-config" } codex-code-mode = { path = "code-mode" } codex-code-mode-protocol = { path = "code-mode-protocol" } codex-code-mode-runtime = { path = "code-mode-runtime" } @@ -217,7 +214,6 @@ codex-agent-message-board-extension = { path = "ext/agent-message-board" } codex-agent-message-board-host = { path = "agent-message-board-host" } codex-message-board = { path = "message-board" } codex-message-board-mcp = { path = "message-board-mcp" } -codex-connectors-extension = { path = "ext/connectors" } codex-context-fragments = { path = "context-fragments" } codex-core = { path = "core" } codex-core-api = { path = "core-api" } diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index a10f823a..cd4bba01 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -39,7 +39,6 @@ codex-analytics = { workspace = true } codex-app-server-daemon = { workspace = true } codex-arg0 = { workspace = true } codex-aws-auth = { workspace = true } -codex-cloud-config = { workspace = true } codex-code-mode = { workspace = true } codex-config = { workspace = true } codex-network-proxy = { workspace = true } diff --git a/codex-rs/app-server/src/app_info.rs b/codex-rs/app-server/src/app_info.rs deleted file mode 100644 index 4752d5fb..00000000 --- a/codex-rs/app-server/src/app_info.rs +++ /dev/null @@ -1,175 +0,0 @@ -use codex_app_server_protocol::AppBranding as ApiAppBranding; -use codex_app_server_protocol::AppInfo as ApiAppInfo; -use codex_app_server_protocol::AppMetadata as ApiAppMetadata; -use codex_app_server_protocol::AppReview as ApiAppReview; -use codex_app_server_protocol::AppScreenshot as ApiAppScreenshot; -use codex_app_server_protocol::AppToolSummary as ApiAppToolSummary; -use codex_app_server_protocol::ConnectorMetadata as ApiConnectorMetadata; -use codex_connectors::AppBranding; -use codex_connectors::AppInfo; -use codex_connectors::AppMetadata; -use codex_connectors::AppReview; -use codex_connectors::AppScreenshot; -use codex_connectors::ConnectorMetadata; -use codex_connectors::ConnectorToolSummary; -use codex_connectors::metadata::connector_install_url; - -/// Converts connector-domain app metadata owned by `codex-connectors` into the app-server wire -/// type owned by `codex-app-server-protocol`. -/// -/// The types stay separate so app-server protocol ownership does not leak into the connector -/// domain crate. Because this crate owns neither type, Rust's orphan rules require an explicit -/// conversion function instead of a `From` implementation. -pub(crate) fn app_info_to_api(app: AppInfo) -> ApiAppInfo { - let AppInfo { - id, - name, - description, - logo_url, - logo_url_dark, - icon_assets, - icon_dark_assets, - distribution_channel, - branding, - app_metadata, - labels, - install_url, - is_accessible, - is_enabled, - plugin_display_names, - } = app; - ApiAppInfo { - id, - name, - description, - logo_url, - logo_url_dark, - icon_assets, - icon_dark_assets, - distribution_channel, - branding: branding.map(app_branding_to_api), - app_metadata: app_metadata.map(app_metadata_to_api), - labels, - install_url, - is_accessible, - is_enabled, - plugin_display_names, - } -} - -/// Converts metadata-only connector data into the app-server wire type. -/// -/// Keeping this separate from app_info_to_api makes it impossible for app/read to accidentally -/// expose full runtime tool state from the broader app/list path. -pub(crate) fn connector_metadata_to_api(metadata: ConnectorMetadata) -> ApiConnectorMetadata { - let ConnectorMetadata { - id, - name, - description, - icon_url, - icon_url_dark, - distribution_channel, - tool_summaries, - } = metadata; - let install_url = Some(connector_install_url(&name, &id)); - ApiConnectorMetadata { - id, - name, - description, - icon_url, - icon_url_dark, - distribution_channel, - install_url, - plugin_display_names: Vec::new(), - tool_summaries: tool_summaries.map(|tools| { - tools - .into_iter() - .map(|tool| { - let ConnectorToolSummary { - name, - title, - description, - is_enabled, - disabled_reason, - is_read_only, - } = tool; - ApiAppToolSummary { - name, - title, - description, - is_enabled, - disabled_reason, - is_read_only, - } - }) - .collect() - }), - } -} - -fn app_branding_to_api(branding: AppBranding) -> ApiAppBranding { - let AppBranding { - category, - developer, - website, - privacy_policy, - terms_of_service, - is_discoverable_app, - } = branding; - ApiAppBranding { - category, - developer, - website, - privacy_policy, - terms_of_service, - is_discoverable_app, - } -} - -fn app_review_to_api(review: AppReview) -> ApiAppReview { - let AppReview { status } = review; - ApiAppReview { status } -} - -fn app_screenshot_to_api(screenshot: AppScreenshot) -> ApiAppScreenshot { - let AppScreenshot { - url, - file_id, - user_prompt, - } = screenshot; - ApiAppScreenshot { - url, - file_id, - user_prompt, - } -} - -fn app_metadata_to_api(metadata: AppMetadata) -> ApiAppMetadata { - let AppMetadata { - review, - categories, - sub_categories, - seo_description, - screenshots, - developer, - version, - version_id, - version_notes, - first_party_requires_install, - show_in_composer_when_unlinked, - } = metadata; - ApiAppMetadata { - review: review.map(app_review_to_api), - categories, - sub_categories, - seo_description, - screenshots: screenshots - .map(|screenshots| screenshots.into_iter().map(app_screenshot_to_api).collect()), - developer, - version, - version_id, - version_notes, - first_party_requires_install, - show_in_composer_when_unlinked, - } -} diff --git a/codex-rs/app-server/src/application_network_tests.rs b/codex-rs/app-server/src/application_network_tests.rs index 20a63a2d..8360ab40 100644 --- a/codex-rs/app-server/src/application_network_tests.rs +++ b/codex-rs/app-server/src/application_network_tests.rs @@ -28,7 +28,7 @@ async fn embedded_transports_stay_blocked_until_the_same_policy_is_published() - let server = MockServer::start().await; Mock::given(method("GET")) .respond_with(ResponseTemplate::new(200)) - .expect(2) + .expect(1) .mount(&server) .await; let home = tempdir()?; @@ -44,28 +44,15 @@ async fn embedded_transports_stay_blocked_until_the_same_policy_is_published() - .build() .await?; config.chatgpt_base_url = server.uri(); - let cloud_endpoint = format!("{}/api/codex/config/bundle", server.uri()); let policy = EmbeddedNetworkPolicy::load(&overrides).await; - let bootstrap_auth = policy.bind_bootstrap_auth(config.auth_config()); - let bootstrap = bootstrap_auth - .auth_route_config - .http_client_factory() - .build_client(&cloud_endpoint, ClientRouteClass::Auth)?; let application = policy .bind(config.http_client_factory()) .build_client(&server.uri(), ClientRouteClass::Other)?; - assert!(bootstrap.get(&cloud_endpoint).send().await.is_err()); assert!(application.get(server.uri()).send().await.is_err()); policy.activate(&mut config); let caller_factory = config.http_client_factory(); let caller_client = caller_factory.build_client(&server.uri(), ClientRouteClass::Other)?; - let worktree_bootstrap = policy.clone().bind_bootstrap_auth(config.auth_config()); - let worktree_client = worktree_bootstrap - .auth_route_config - .http_client_factory() - .build_client(&cloud_endpoint, ClientRouteClass::Auth)?; assert!(caller_client.get(server.uri()).send().await.is_err()); - assert!(worktree_client.get(&cloud_endpoint).send().await.is_err()); assert!( caller_factory .network_policy() @@ -86,29 +73,17 @@ async fn embedded_transports_stay_blocked_until_the_same_policy_is_published() - std::fs::remove_file(&requirements)?; let unrestricted = manager.refresh_application_network_policy().await?; - let unrelated_endpoint = format!("{}/not-the-config-endpoint", server.uri()).parse()?; - assert_eq!( - bootstrap_auth - .auth_route_config - .http_client_factory() - .network_policy() - .acquire(&unrelated_endpoint) - .map(|_| ()), - Err(NetworkPolicyDenied::Destination), - ); caller_client.get(server.uri()).send().await?; - worktree_client.get(&cloud_endpoint).send().await?; assert!( caller_factory .network_policy() .acquire_for_unsupported_sdk() .is_ok() ); - assert_eq!(server.received_requests().await.unwrap().len(), 2); + assert_eq!(server.received_requests().await.unwrap().len(), 1); std::fs::write(&requirements, "[malformed")?; assert!(manager.refresh_application_network_policy().await.is_err()); assert!(caller_client.get(server.uri()).send().await.is_err()); - assert!(worktree_client.get(&cloud_endpoint).send().await.is_err()); assert!( caller_factory .network_policy() diff --git a/codex-rs/app-server/src/chatgpt_connectors/chatgpt_client.rs b/codex-rs/app-server/src/chatgpt_connectors/chatgpt_client.rs deleted file mode 100644 index a88e22d7..00000000 --- a/codex-rs/app-server/src/chatgpt_connectors/chatgpt_client.rs +++ /dev/null @@ -1,243 +0,0 @@ -use codex_core::config::Config; -use codex_features::Feature; -use codex_features::RuntimeAuthMode; -use codex_http_client::HttpClient; -use codex_http_client::HttpClientFactory; -use codex_login::AuthManager; -use codex_login::CodexAuth; -use codex_login::default_client::RESIDENCY_HEADER_NAME; -use codex_login::default_client::create_client_with_chatgpt_cookies; -use codex_login::default_client::default_headers; -use codex_runtime_agent_instance::RuntimeAuthManager; -use std::sync::Arc; - -use anyhow::Context; -use serde::Serialize; -use serde::de::DeserializeOwned; -use std::sync::LazyLock; -use std::sync::Mutex; -use std::time::Duration; - -const OAI_PRODUCT_SKU_HEADER: &str = "OAI-Product-Sku"; -const CODEX_PRODUCT_SKU: &str = "codex"; - -struct CachedChatGptClient { - factory: HttpClientFactory, - residency: Option>, - client: HttpClient, -} - -static CHATGPT_CLIENT: LazyLock>> = - LazyLock::new(|| Mutex::new(None)); - -/// Reuse the client and cookies without changing the caller's captured account policy. -fn chatgpt_client(factory: HttpClientFactory) -> HttpClient { - let residency = default_headers() - .get(RESIDENCY_HEADER_NAME) - .map(|value| value.as_bytes().to_vec()); - let mut cached = CHATGPT_CLIENT - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some(cached_client) = cached.as_ref() - && cached_client.factory == factory - && cached_client.residency == residency - { - return cached_client.client.clone(); - } - - let client = create_client_with_chatgpt_cookies(&factory); - *cached = Some(CachedChatGptClient { - factory, - residency, - client: client.clone(), - }); - client -} - -/// Make a GET request to the ChatGPT backend API. -#[cfg(test)] -pub(crate) async fn chatgpt_get_request( - config: &Config, - path: String, -) -> anyhow::Result { - let mut config = config.clone(); - let (auth, runtime) = standalone_auth(&mut config).await?; - chatgpt_get_request_with_timeout( - &config, - &auth, - runtime.as_ref(), - path, - /*timeout*/ None, - ) - .await -} - -pub(crate) async fn standalone_auth( - config: &mut Config, -) -> anyhow::Result<( - CodexAuth, - Option<(Arc, RuntimeAuthMode)>, -)> { - // Standalone commands create one owner. Freeze the caller's account policy before loading - // credentials; this temporary manager does not own later account changes. - config.application_network_policy = config - .application_network_policy - .clone() - .for_current_account(); - if config.features.enabled(Feature::RuntimeAgentInstances) { - codex_model_provider::validate_runtime_destination(Some(&config.chatgpt_base_url))?; - } - let auth_manager = - AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await?; - let runtime = if config.features.enabled(Feature::RuntimeAgentInstances) - && codex_runtime_agent_instance::is_openai_api_url(&config.chatgpt_base_url) - { - let installation_id = codex_core::resolve_installation_id(&config.codex_home).await?; - codex_core::build_runtime_auth_manager(config, auth_manager.clone(), &installation_id) - .map(|runtime| (runtime, config.runtime_auth_mode)) - } else { - None - }; - let auth = auth_manager - .auth() - .await - .ok_or_else(|| anyhow::anyhow!("ChatGPT auth not available"))?; - Ok((auth, runtime)) -} - -pub(crate) async fn chatgpt_get_request_with_timeout( - config: &Config, - auth: &CodexAuth, - runtime: Option<&(Arc, RuntimeAuthMode)>, - path: String, - timeout: Option, -) -> anyhow::Result { - let chatgpt_base_url = &config.chatgpt_base_url; - anyhow::ensure!( - auth.uses_codex_backend(), - "ChatGPT backend requests require Codex backend auth" - ); - anyhow::ensure!( - auth.get_account_id().is_some(), - "ChatGPT account ID not available, please re-run `codex login`" - ); - let url = format!( - "{}/{}", - chatgpt_base_url.trim_end_matches('/'), - path.trim_start_matches('/') - ); - - let (client, request_auth) = prepare_client_auth(config, auth, runtime, &url).await?; - let mut request = client - .get(&url) - .headers(default_headers()) - .headers( - request_auth - .auth - .apply_auth_headers(Default::default()) - .await?, - ) - .header(OAI_PRODUCT_SKU_HEADER, CODEX_PRODUCT_SKU) - .header("Content-Type", "application/json"); - if let Some(timeout) = timeout { - request = request.timeout(timeout); - } - let response = request.send().await.context("Failed to send request")?; - - if response.status().is_success() { - let result: T = response - .json() - .await - .context("Failed to parse JSON response")?; - Ok(result) - } else { - let status = response.status(); - let body = response.text().await.unwrap_or_default(); - anyhow::bail!("Request failed with status {status}: {body}") - } -} - -/// Make a POST request to the ChatGPT backend API with an already-captured auth identity. -/// -/// Callers must capture `auth` and `config.application_network_policy` together and preserve -/// that snapshot rather than reacquiring either while the request is in flight. -pub(crate) async fn chatgpt_post_request_with_timeout< - TResponse: DeserializeOwned, - TRequest: Serialize + ?Sized, ->( - config: &Config, - auth: &CodexAuth, - path: String, - body: &TRequest, - timeout: Duration, - product_sku: &str, - runtime: Option<&(Arc, RuntimeAuthMode)>, -) -> anyhow::Result { - anyhow::ensure!( - auth.uses_codex_backend(), - "ChatGPT backend requests require Codex backend auth" - ); - anyhow::ensure!( - auth.get_account_id().is_some(), - "ChatGPT account ID not available, please re-run codex login" - ); - - let url = format!( - "{}/{}", - config.chatgpt_base_url.trim_end_matches('/'), - path.trim_start_matches('/') - ); - let (client, request_auth) = prepare_client_auth(config, auth, runtime, &url).await?; - let response = client - .post(&url) - .headers(default_headers()) - .headers( - request_auth - .auth - .apply_auth_headers(Default::default()) - .await?, - ) - .header(OAI_PRODUCT_SKU_HEADER, product_sku) - .header("Content-Type", "application/json") - .timeout(timeout) - .json(body) - .send() - .await - .context("Failed to send request")?; - - if response.status().is_success() { - response - .json() - .await - .context("Failed to parse JSON response") - } else { - let status = response.status(); - let body = response.text().await.unwrap_or_default(); - anyhow::bail!("Request failed with status {status}: {body}") - } -} - -/// Keep request credentials and the transport bound to the same account snapshot. -async fn prepare_client_auth( - config: &Config, - auth: &CodexAuth, - runtime: Option<&(Arc, RuntimeAuthMode)>, - url: &str, -) -> anyhow::Result<(HttpClient, codex_model_provider::ResolvedProviderAuth)> { - if runtime.is_some() { - codex_model_provider::validate_runtime_destination(Some(url))?; - } - let resolved = codex_model_provider::auth_provider_for_request( - auth, - runtime, - /*headers*/ &Default::default(), - ) - .await?; - let factory = resolved.bind_http_client_factory(config.http_client_factory())?; - let client = chatgpt_client(factory); - Ok((client, resolved)) -} - -#[cfg(test)] -#[path = "chatgpt_client_runtime_auth_tests.rs"] -mod runtime_auth_tests; diff --git a/codex-rs/app-server/src/chatgpt_connectors/chatgpt_client_runtime_auth_tests.rs b/codex-rs/app-server/src/chatgpt_connectors/chatgpt_client_runtime_auth_tests.rs deleted file mode 100644 index b3e11c97..00000000 --- a/codex-rs/app-server/src/chatgpt_connectors/chatgpt_client_runtime_auth_tests.rs +++ /dev/null @@ -1,321 +0,0 @@ -//! Test captured ChatGPT credentials and runtime proofs on helper requests. - -use super::*; -use base64::Engine; -use codex_features::RuntimeAuthMode; -use codex_runtime_agent_instance::AgentHostAuthorization; -use codex_runtime_agent_instance::RuntimeAuthManager; -use codex_runtime_agent_instance::RuntimeRegistrationMetadata; -use codex_runtime_agent_instance::RuntimeRole; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::collections::HashSet; -use std::sync::Arc; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::path; - -#[tokio::test] -async fn helpers_use_captured_auth_and_strip_cross_origin_proofs() { - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - let server = MockServer::start().await; - let redirected = MockServer::start().await; - Mock::given(path("/")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true}))) - .expect(1) - .mount(&redirected) - .await; - Mock::given(path("/agent/register")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "runtime_agent_instance_id": "runtime-chatgpt", "agent_host_id": "host-a", - "actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "workspace-a"}, - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(path("/data")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true}))) - .expect(2) - .mount(&server) - .await; - Mock::given(path("/redirect")) - .respond_with(ResponseTemplate::new(307).insert_header("location", redirected.uri())) - .expect(1) - .mount(&server) - .await; - Mock::given(path("/ps/apps/batch")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "apps": [{"id": "calendar", "name": "Calendar", "description": "Calendar metadata"}], - }))) - .expect(1).mount(&server).await; - let home = tempfile::TempDir::new().unwrap(); - let mut config = codex_core::config::ConfigBuilder::default() - .codex_home(home.path().to_path_buf()) - .build() - .await - .unwrap(); - config.chatgpt_base_url = server.uri(); - let token = actor_token(); - let auth = CodexAuth::from_external_chatgpt_tokens( - &token, - "workspace-a", - /*chatgpt_plan_type*/ None, - ) - .unwrap(); - let runtime = ( - Arc::new(RuntimeAuthManager::new( - AuthManager::from_auth_for_testing(auth.clone()), - AgentHostAuthorization::InstallationId { - installation_id: uuid::Uuid::nil(), - }, - RuntimeRegistrationMetadata { - harness: Some("codex".into()), - harness_version: None, - role: RuntimeRole::Orchestrator, - }, - format!("{}/agent/register", server.uri()).parse().unwrap(), - )), - mode, - ); - // No saved auth exists: these helpers must use the supplied snapshot, not reload auth. - let get: serde_json::Value = chatgpt_get_request_with_timeout( - &config, - &auth, - Some(&runtime), - "data".into(), - /*timeout*/ None, - ) - .await - .unwrap(); - let post: serde_json::Value = chatgpt_post_request_with_timeout( - &config, - &auth, - "data".into(), - &json!({}), - Duration::from_secs(10), - "codex", - Some(&runtime), - ) - .await - .unwrap(); - let metadata = crate::chatgpt_connectors::read_connector_metadata( - &config, - &auth, - Some(&runtime), - &["calendar".into()], - /*include_tools*/ false, - ) - .await - .unwrap(); - assert_eq!(metadata.apps.len(), 1); - assert_eq!(metadata.apps[0].name, "Calendar"); - assert!(metadata.missing_app_ids.is_empty()); - assert_eq!(get, json!({"ok": true})); - assert_eq!(post, get); - let redirected_result = chatgpt_get_request_with_timeout::( - &config, - &auth, - Some(&runtime), - "redirect".into(), - /*timeout*/ None, - ) - .await - .unwrap(); - assert_eq!(redirected_result, get); - let forwarded = redirected.received_requests().await.unwrap(); - assert_eq!(forwarded.len(), 1); - assert!(!forwarded[0].headers.contains_key("authorization")); - assert!( - !forwarded[0] - .headers - .contains_key("x-openai-agent-assertion") - ); - redirected.verify().await; - let requests = server.received_requests().await.unwrap(); - let metadata_request = requests - .iter() - .find(|request| request.url.path() == "/ps/apps/batch") - .unwrap(); - assert_eq!( - metadata_request.headers["authorization"], - format!("Bearer {token}") - ); - assert!( - !metadata_request - .headers - .contains_key("x-openai-agent-assertion") - ); - let proofs: HashSet<_> = requests - .iter() - .filter(|r| !matches!(r.url.path(), "/agent/register" | "/ps/apps/batch")) - .map(|r| { - assert_eq!(r.headers["chatgpt-account-id"], "workspace-a"); - let authorization = r.headers["authorization"].to_str().unwrap(); - match mode { - RuntimeAuthMode::DualHeader => { - assert_eq!(authorization, format!("Bearer {token}")); - r.headers["x-openai-agent-assertion"].to_str().unwrap() - } - RuntimeAuthMode::AssertionOnly => { - assert!(!r.headers.contains_key("x-openai-agent-assertion")); - authorization.strip_prefix("AgentAssertion ").unwrap() - } - } - }) - .collect(); - assert_eq!(proofs.len(), 3); - server.verify().await; - } -} - -fn actor_token() -> String { - let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json!({ - "iss": "https://auth.openai.com/", "session_id": "login-a", - "https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "workspace-a"}, - }).to_string()); - format!("header.{claims}.signature") -} - -#[tokio::test] -async fn standalone_apply_keeps_custom_backend_auth_when_runtime_feature_is_enabled() { - let server = MockServer::start().await; - let token = actor_token(); - Mock::given(path("/task")) - .and(wiremock::matchers::header( - "authorization", - format!("Bearer {token}"), - )) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true}))) - .expect(1) - .mount(&server) - .await; - let home = tempfile::TempDir::new().unwrap(); - codex_login::auth::login_with_chatgpt_auth_tokens( - home.path(), - &token, - "workspace-a", - /*chatgpt_plan_type*/ None, - ) - .unwrap(); - let mut config = codex_core::config::ConfigBuilder::default() - .codex_home(home.path().to_path_buf()) - .build() - .await - .unwrap(); - config.chatgpt_base_url = server.uri(); - config - .features - .enable(Feature::RuntimeAgentInstances) - .unwrap(); - let response: serde_json::Value = chatgpt_get_request(&config, "task".into()).await.unwrap(); - assert_eq!(response, json!({"ok": true})); - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 1); - assert!(!requests[0].headers.contains_key("x-openai-agent-assertion")); - server.verify().await; -} - -#[tokio::test] -async fn connector_requests_reject_unsupported_openai_destinations() { - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - for base_url in [ - "http://chatgpt.com", - "https://future.openai.com/backend-api", - ] { - let home = tempfile::TempDir::new().unwrap(); - let mut config = codex_core::config::ConfigBuilder::default() - .codex_home(home.path().to_path_buf()) - .build() - .await - .unwrap(); - config.chatgpt_base_url = base_url.to_string(); - config.features.enable(Feature::Apps).unwrap(); - let auth = CodexAuth::from_external_chatgpt_tokens( - &actor_token(), - "workspace-a", - /*chatgpt_plan_type*/ None, - ) - .unwrap(); - let runtime = ( - Arc::new(RuntimeAuthManager::for_chatgpt( - AuthManager::from_auth_for_testing(auth.clone()), - uuid::Uuid::nil().to_string(), - base_url.to_string(), - RuntimeRegistrationMetadata { - harness: Some("codex".to_string()), - harness_version: None, - role: RuntimeRole::Orchestrator, - }, - )), - mode, - ); - - // Keep a broken validation path from sending the test credential to the network. - let controller = codex_http_client::NetworkPolicyController::default(); - config.application_network_policy = controller.policy(); - assert!(controller.publish( - config.application_network_policy.revision(), - codex_http_client::DestinationPolicy::Restricted { - allowed_hosts: Default::default(), - }, - )); - - let directory_error = crate::chatgpt_connectors::list_all_connectors_with_options( - &config, - Some(&auth), - Some(&runtime), - /*force_refetch*/ true, - &[], - ) - .await - .expect_err("reject unsupported directory destination"); - let metadata_error = crate::chatgpt_connectors::read_connector_metadata( - &config, - &auth, - Some(&runtime), - &["calendar".to_string()], - /*include_tools*/ false, - ) - .await - .err() - .expect("reject unsupported metadata destination"); - for error in [directory_error, metadata_error] { - assert!( - matches!( - error - .downcast_ref::() - .map(codex_protocol::error::CodexErr::details), - Some(codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_)) - ), - "{base_url} ({mode:?}): {error:#}", - ); - } - } - } -} - -#[tokio::test] -async fn standalone_apply_rejects_unsupported_openai_destination() { - let home = tempfile::TempDir::new().unwrap(); - let mut config = codex_core::config::ConfigBuilder::default() - .codex_home(home.path().to_path_buf()) - .build() - .await - .unwrap(); - config.chatgpt_base_url = "https://future.openai.com/backend-api".into(); - config - .features - .enable(Feature::RuntimeAgentInstances) - .unwrap(); - - let error = chatgpt_get_request::(&config, "task".into()) - .await - .unwrap_err(); - assert!(matches!( - error - .downcast_ref::() - .map(codex_protocol::error::CodexErr::details), - Some(codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_)) - )); -} diff --git a/codex-rs/app-server/src/chatgpt_connectors/mod.rs b/codex-rs/app-server/src/chatgpt_connectors/mod.rs deleted file mode 100644 index bf37c2a4..00000000 --- a/codex-rs/app-server/src/chatgpt_connectors/mod.rs +++ /dev/null @@ -1,525 +0,0 @@ -use std::collections::HashMap; -use std::collections::HashSet; -use std::time::Duration; - -mod chatgpt_client; - -use self::chatgpt_client::chatgpt_get_request_with_timeout; -use self::chatgpt_client::chatgpt_post_request_with_timeout; - -use codex_connectors::AppInfo; -use codex_connectors::AppToolPolicyEvaluator; -use codex_connectors::ConnectorDirectoryCacheContext; -use codex_connectors::ConnectorDirectoryCacheKey; -use codex_connectors::ConnectorMetadata; -use codex_connectors::ConnectorMetadataStore; -use codex_connectors::ConnectorToolSummary; -use codex_connectors::DirectoryListResponse; -use codex_connectors::merge::merge_connectors; -use codex_connectors::merge::merge_plugin_connectors; -use codex_core::config::Config; -pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools; -pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_environment_manager; -pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager; -pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options; -pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options_and_status; -pub use codex_core::connectors::list_cached_accessible_connectors_from_mcp_tools; -use codex_features::RuntimeAuthMode; -use codex_login::AuthManager; -use codex_login::CodexAuth; -use codex_plugin::AppConnectorId; -use codex_runtime_agent_instance::RuntimeAuthManager; -use serde::Deserialize; -use serde::Serialize; -use std::sync::Arc; - -const DIRECTORY_CONNECTORS_TIMEOUT: Duration = Duration::from_secs(60); -const CONNECTOR_METADATA_TIMEOUT: Duration = Duration::from_secs(60); -const DEFAULT_APPS_PRODUCT_SKU: &str = "codex"; - -async fn apps_enabled(config: &Config) -> anyhow::Result { - let auth_manager = - AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await?; - let auth = auth_manager.auth().await; - Ok(config - .features - .apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend))) -} - -pub async fn list_connectors(config: &Config) -> anyhow::Result> { - if !apps_enabled(config).await? { - return Ok(Vec::new()); - } - let (connectors_result, accessible_result) = tokio::join!( - list_all_connectors(config), - list_accessible_connectors_from_mcp_tools(config), - ); - let connectors = connectors_result?; - let accessible = accessible_result?; - Ok( - AppToolPolicyEvaluator::new(&config.config_layer_stack).apply_app_enabled_state( - merge_connectors_with_accessible( - connectors, accessible, /*all_connectors_loaded*/ true, - ), - ), - ) -} - -pub async fn list_all_connectors(config: &Config) -> anyhow::Result> { - if !apps_enabled(config).await? { - return Ok(Vec::new()); - } - let mut config = config.clone(); - let (auth, runtime) = self::chatgpt_client::standalone_auth(&mut config).await?; - list_all_connectors_with_options( - &config, - Some(&auth), - runtime.as_ref(), - /*force_refetch*/ false, - &[], - ) - .await -} - -pub fn list_cached_all_connectors( - config: &Config, - auth: Option<&CodexAuth>, - plugin_apps: &[AppConnectorId], -) -> Option> { - if !config - .features - .apps_enabled_for_auth(auth.is_some_and(CodexAuth::uses_codex_backend)) - { - return Some(Vec::new()); - } - - let auth = auth?; - let cache_context = connector_directory_cache_context(config, auth); - let connectors = codex_connectors::cached_directory_connectors(&cache_context)?; - Some(merge_directory_and_plugin_connectors( - connectors.to_vec(), - plugin_apps, - )) -} - -pub async fn list_all_connectors_with_options( - config: &Config, - auth: Option<&CodexAuth>, - runtime: Option<&(Arc, RuntimeAuthMode)>, - force_refetch: bool, - plugin_apps: &[AppConnectorId], -) -> anyhow::Result> { - if !config - .features - .apps_enabled_for_auth(auth.is_some_and(CodexAuth::uses_codex_backend)) - { - return Ok(Vec::new()); - } - let auth = auth.ok_or_else(|| anyhow::anyhow!("ChatGPT auth not available"))?; - let runtime = codex_model_provider::runtime_auth_for_url(runtime, &config.chatgpt_base_url)?; - let cache_context = connector_directory_cache_context(config, auth); - let connectors = codex_connectors::list_all_connectors_with_options( - cache_context, - auth.is_workspace_account(), - force_refetch, - |path| async move { - chatgpt_get_request_with_timeout::( - config, - auth, - runtime, - path, - Some(DIRECTORY_CONNECTORS_TIMEOUT), - ) - .await - }, - ) - .await?; - Ok(merge_directory_and_plugin_connectors( - connectors, - plugin_apps, - )) -} - -pub struct ConnectorMetadataReadResult { - pub apps: Vec, - pub missing_app_ids: Vec, -} - -/// Reads display metadata without loading MCP connector tools or runtime state. -/// -/// The store is created before awaiting the backend request, so a response that arrives after an -/// account or backend change can only commit to the scope under which it was requested. -/// Capture `auth` and `config.application_network_policy` together using -/// `AuthManager::auth_with_http_client_factory` so the request retains that account's policy. -pub async fn read_connector_metadata( - config: &Config, - auth: &CodexAuth, - runtime: Option<&(Arc, RuntimeAuthMode)>, - app_ids: &[String], - include_tools: bool, -) -> anyhow::Result { - anyhow::ensure!( - auth.uses_codex_backend(), - "ChatGPT backend requests require Codex backend auth" - ); - anyhow::ensure!( - auth.get_account_id().is_some(), - "ChatGPT account ID not available, please re-run codex login" - ); - - let runtime = codex_model_provider::runtime_auth_for_url(runtime, &config.chatgpt_base_url)?; - let store = ConnectorMetadataStore::new( - config.chatgpt_base_url.clone(), - auth.get_account_id(), - auth.get_chatgpt_user_id(), - auth.is_workspace_account(), - ); - let mut metadata_by_id = store.fresh_records(app_ids, include_tools); - let missing_ids = app_ids - .iter() - .filter(|app_id| !metadata_by_id.contains_key(app_id.as_str())) - .cloned() - .collect::>(); - - if !missing_ids.is_empty() { - let product_sku = config - .apps_mcp_product_sku - .as_deref() - .unwrap_or(DEFAULT_APPS_PRODUCT_SKU); - let response: GetAppsResponse = chatgpt_post_request_with_timeout( - config, - auth, - "/ps/apps/batch".to_string(), - &GetAppsRequest { - app_ids: &missing_ids, - include_tools, - }, - CONNECTOR_METADATA_TIMEOUT, - product_sku, - runtime, - ) - .await?; - let mut requested_ids = missing_ids.iter().cloned().collect::>(); - let fetched = response - .apps - .into_iter() - .map(batch_app_to_metadata) - .filter(|metadata| requested_ids.remove(&metadata.id)) - .collect::>(); - store.commit(&fetched); - metadata_by_id.extend( - fetched - .into_iter() - .map(|metadata| (metadata.id.clone(), metadata)), - ); - } - - let mut apps = Vec::new(); - let mut missing_app_ids = Vec::new(); - for app_id in app_ids { - if let Some(mut metadata) = metadata_by_id.remove(app_id) { - if !include_tools { - metadata.tool_summaries = None; - } - apps.push(metadata); - } else { - missing_app_ids.push(app_id.clone()); - } - } - - Ok(ConnectorMetadataReadResult { - apps, - missing_app_ids, - }) -} - -#[derive(Serialize)] -struct GetAppsRequest<'a> { - app_ids: &'a [String], - include_tools: bool, -} - -#[derive(Deserialize)] -struct GetAppsResponse { - apps: Vec, -} - -/// The explicit metadata-only projection of Plugin Service's public app response. -/// -/// Serde ignores all other backend fields, including full actions, model descriptions, and -/// runtime state. -#[derive(Deserialize)] -struct BatchApp { - id: String, - name: String, - description: Option, - icon_url: Option, - #[serde(default, rename = "icon_dark_url", alias = "icon_url_dark")] - icon_url_dark: Option, - #[serde(default)] - distribution_channel: Option, - #[serde(default)] - tools: Option>, -} - -#[derive(Deserialize)] -struct BatchAppToolSummary { - name: String, - title: Option, - description: String, - #[serde(default)] - is_enabled: Option, - #[serde(default)] - disabled_reason: Option, - #[serde(default)] - is_read_only: bool, -} - -fn batch_app_to_metadata(app: BatchApp) -> ConnectorMetadata { - let BatchApp { - id, - name, - description, - icon_url, - icon_url_dark, - distribution_channel, - tools, - } = app; - ConnectorMetadata { - id, - name, - description, - icon_url, - icon_url_dark, - distribution_channel, - tool_summaries: tools.map(|tools| { - tools - .into_iter() - .map(|tool| { - let BatchAppToolSummary { - name, - title, - description, - is_enabled, - disabled_reason, - is_read_only, - } = tool; - ConnectorToolSummary { - name, - title, - description, - is_enabled: is_enabled.unwrap_or(true), - disabled_reason, - is_read_only, - } - }) - .collect() - }), - } -} - -fn connector_directory_cache_context( - config: &Config, - auth: &CodexAuth, -) -> ConnectorDirectoryCacheContext { - ConnectorDirectoryCacheContext::new( - config.codex_home.to_path_buf(), - ConnectorDirectoryCacheKey::new( - config.chatgpt_base_url.clone(), - auth.get_account_id(), - auth.get_chatgpt_user_id(), - auth.is_workspace_account(), - ), - ) -} - -fn merge_directory_and_plugin_connectors( - connectors: Vec, - plugin_apps: &[AppConnectorId], -) -> Vec { - merge_plugin_connectors( - connectors, - plugin_apps - .iter() - .map(|connector_id| connector_id.0.clone()), - ) -} - -pub fn connectors_for_plugin_apps( - connectors: Vec, - plugin_apps: &[AppConnectorId], -) -> Vec { - let connectors = merge_plugin_connectors( - connectors, - plugin_apps - .iter() - .map(|connector_id| connector_id.0.clone()), - ); - let mut connectors_by_id = connectors - .into_iter() - .map(|connector| (connector.id.clone(), connector)) - .collect::>(); - - plugin_apps - .iter() - .filter_map(|connector_id| connectors_by_id.remove(connector_id.0.as_str())) - .collect() -} - -pub fn merge_connectors_with_accessible( - connectors: Vec, - accessible_connectors: Vec, - all_connectors_loaded: bool, -) -> Vec { - let accessible_connectors = if all_connectors_loaded { - let connector_ids: HashSet<&str> = connectors - .iter() - .map(|connector| connector.id.as_str()) - .collect(); - accessible_connectors - .into_iter() - .filter(|connector| connector_ids.contains(connector.id.as_str())) - .collect() - } else { - accessible_connectors - }; - merge_connectors(connectors, accessible_connectors) -} - -#[cfg(test)] -mod tests { - use super::*; - use codex_connectors::metadata::connector_install_url; - use codex_plugin::AppConnectorId; - use pretty_assertions::assert_eq; - use serde_json::json; - - #[test] - fn batch_app_accepts_missing_optional_metadata() { - let app = serde_json::from_value::(json!({ - "id": "alpha", - "name": "Alpha", - "description": "Alpha description", - "icon_url": null, - "tools": [{ - "name": "search", - "title": "Search", - "description": "Search Alpha", - }], - })) - .expect("valid legacy batch app"); - - assert_eq!( - batch_app_to_metadata(app), - ConnectorMetadata { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha description".to_string()), - icon_url: None, - icon_url_dark: None, - distribution_channel: None, - tool_summaries: Some(vec![ConnectorToolSummary { - name: "search".to_string(), - title: Some("Search".to_string()), - description: "Search Alpha".to_string(), - is_enabled: true, - disabled_reason: None, - is_read_only: false, - }]), - } - ); - } - - fn app(id: &str) -> AppInfo { - AppInfo { - id: id.to_string(), - name: id.to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - } - } - - fn merged_app(id: &str, is_accessible: bool) -> AppInfo { - AppInfo { - id: id.to_string(), - name: id.to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some(connector_install_url(id, id)), - is_accessible, - is_enabled: true, - plugin_display_names: Vec::new(), - } - } - - #[test] - fn excludes_accessible_connectors_not_in_all_when_all_loaded() { - let merged = merge_connectors_with_accessible( - vec![app("alpha")], - vec![app("alpha"), app("beta")], - /*all_connectors_loaded*/ true, - ); - assert_eq!(merged, vec![merged_app("alpha", /*is_accessible*/ true)]); - } - - #[test] - fn keeps_accessible_connectors_not_in_all_while_all_loading() { - let merged = merge_connectors_with_accessible( - vec![app("alpha")], - vec![app("alpha"), app("beta")], - /*all_connectors_loaded*/ false, - ); - assert_eq!( - merged, - vec![ - merged_app("alpha", /*is_accessible*/ true), - merged_app("beta", /*is_accessible*/ true) - ] - ); - } - - #[test] - fn connectors_for_plugin_apps_returns_only_requested_plugin_apps() { - let connectors = connectors_for_plugin_apps( - vec![app("alpha"), app("beta")], - &[ - AppConnectorId("gmail".to_string()), - AppConnectorId("alpha".to_string()), - AppConnectorId("gmail".to_string()), - ], - ); - assert_eq!( - connectors, - vec![merged_app("gmail", /*is_accessible*/ false), app("alpha")] - ); - } - - #[test] - fn connectors_for_plugin_apps_preserves_formerly_disallowed_plugin_apps() { - let connector_id = "asdk_app_6938a94a61d881918ef32cb999ff937c"; - let connectors = - connectors_for_plugin_apps(Vec::new(), &[AppConnectorId(connector_id.to_string())]); - assert_eq!( - connectors, - vec![merged_app(connector_id, /*is_accessible*/ false)] - ); - } -} diff --git a/codex-rs/app-server/src/config_manager.rs b/codex-rs/app-server/src/config_manager.rs index 3495e6c3..df47a85b 100644 --- a/codex-rs/app-server/src/config_manager.rs +++ b/codex-rs/app-server/src/config_manager.rs @@ -1,6 +1,5 @@ use codex_app_server_protocol::ModelProviderError; use codex_arg0::Arg0DispatchPaths; -use codex_cloud_config::managed_config_bundle_loader; use codex_config::CloudConfigBundleLoader; use codex_config::ConfigLayerStack; use codex_config::LoaderOverrides; @@ -191,37 +190,14 @@ impl ConfigManager { Ok(()) } + /// aKode never fetches managed config bundles from a remote service, so an + /// auth change only resets any previously installed loader. pub(crate) fn update_managed_config_loader( &self, - auth_manager: Arc, - config: &Config, + _auth_manager: Arc, + _config: &Config, ) { - // Keep config-server settings and their refresh worker when only - // ChatGPT/API-key credentials change. - if self - .current_managed_config_loader() - .config_server() - .is_some() - { - self.revoke_mcp_ema(); - return; - } - let loader = managed_config_bundle_loader( - auth_manager, - config.chatgpt_base_url.clone(), - self.codex_home.clone(), - config - .http_client_factory() - .with_network_policy(self.local_network_policy.policy()), - config.config_layer_stack.requirements_toml(), - ); - if let Ok(mut guard) = self.cloud_config_bundle.write() { - guard.retire_ema_policy(); - *guard = loader; - } else { - warn!("failed to update cloud config bundle loader"); - } - self.revoke_mcp_ema(); + self.clear_chatgpt_config_loader(); } pub(crate) fn clear_chatgpt_config_loader(&self) { diff --git a/codex-rs/app-server/src/extensions.rs b/codex-rs/app-server/src/extensions.rs index a5e884f2..20bba426 100644 --- a/codex-rs/app-server/src/extensions.rs +++ b/codex-rs/app-server/src/extensions.rs @@ -18,7 +18,6 @@ use codex_extension_api::ExtensionWarning; use codex_extension_api::TurnStartAdmission; use codex_goal_extension::GoalExtensionConfig; use codex_goal_extension::GoalService; -use codex_http_client::HttpClientFactory; use codex_login::AuthManager; use codex_protocol::ThreadId; use codex_protocol::protocol::Event; @@ -42,8 +41,6 @@ pub(crate) struct ThreadExtensionDependencies { pub(crate) environment_manager: Arc, pub(crate) executor_skill_provider: Arc, pub(crate) cloud_skill_provider: Option>, - pub(crate) git_attribution_base_url: String, - pub(crate) http_client_factory: HttpClientFactory, /// Process-scoped queue shared by idle dispatch and app-server requests. pub(crate) queue_service: Option>, pub(crate) turn_start_admission: Option>, @@ -64,8 +61,6 @@ pub(crate) fn thread_extensions( environment_manager, executor_skill_provider, cloud_skill_provider, - git_attribution_base_url, - http_client_factory, queue_service, turn_start_admission, } = dependencies; @@ -98,15 +93,9 @@ pub(crate) fn thread_extensions( }, ); } - codex_git_attribution::install( - &mut builder, - auth_manager.clone(), - git_attribution_base_url, - http_client_factory, - ); + codex_git_attribution::install(&mut builder); codex_guardian_v2::install(&mut builder, thread_manager); codex_memories_extension::install(&mut builder, codex_otel::global()); - codex_mcp_extension::install(&mut builder); codex_mcp_extension::install_plugins(&mut builder, environment_manager); codex_web_search_extension::install(&mut builder, auth_manager.clone()); codex_image_generation_extension::install(&mut builder, auth_manager, |config: &Config| { diff --git a/codex-rs/app-server/src/in_process_bootstrap.rs b/codex-rs/app-server/src/in_process_bootstrap.rs index 84234626..b7151137 100644 --- a/codex-rs/app-server/src/in_process_bootstrap.rs +++ b/codex-rs/app-server/src/in_process_bootstrap.rs @@ -67,35 +67,6 @@ impl EmbeddedNetworkPolicy { pub fn bind_config(&self, config: &mut Config) { config.application_network_policy = self.effective.policy(); } - - /// Limits cloud discovery and each authentication request to their exact local-policy endpoints. - pub fn bind_bootstrap_auth( - &self, - mut auth: codex_login::AuthConfig, - ) -> codex_login::AuthConfig { - let factory = auth - .auth_route_config - .http_client_factory() - .clone() - .with_network_policy(self.local.policy()); - let endpoint = codex_backend_client::Client::new( - auth.chatgpt_base_url - .as_deref() - .unwrap_or("https://chatgpt.com/backend-api/"), - factory.clone(), - ) - .config_bundle_url(); - auth.auth_route_config = codex_login::AuthRouteConfig::from_http_client_factory( - factory.clone().with_network_policy( - self.local - .policy() - .restrict_to_endpoints(endpoint.parse().into_iter().collect()), - ), - ) - .with_local_bootstrap_factory(factory) - .with_application_network_policy(self.effective.policy()); - auth - } } pub(super) async fn configure( diff --git a/codex-rs/app-server/src/in_process_bootstrap_tests.rs b/codex-rs/app-server/src/in_process_bootstrap_tests.rs index 9d7ec83b..4049a25a 100644 --- a/codex-rs/app-server/src/in_process_bootstrap_tests.rs +++ b/codex-rs/app-server/src/in_process_bootstrap_tests.rs @@ -1,10 +1,7 @@ //! Embedded startup preserves caller configuration and bootstrap access across authentication. -use super::EmbeddedNetworkPolicy; use super::configure; use crate::config_manager::ConfigManager; -use base64::Engine; -use base64::engine::general_purpose::URL_SAFE_NO_PAD; use codex_arg0::Arg0DispatchPaths; use codex_config::CloudConfigBundleLoader; use codex_config::LoaderOverrides; @@ -12,138 +9,12 @@ use codex_config::NoopThreadConfigLoader; use codex_core::config::ConfigBuilder; use codex_core::config::ConfigOverrides; use codex_core::config::set_project_trust_level; -use codex_http_client::DestinationPolicy; -use codex_http_client::HttpClientFactory; -use codex_http_client::NetworkPermit; -use codex_http_client::NetworkPolicyDenied; -use codex_login::AuthCredentialsStoreMode; -use codex_login::AuthKeyringBackendKind; -use codex_login::AuthManager; use codex_login::CodexAuth; -use codex_login::ExternalAuth; -use codex_login::ExternalAuthFuture; -use codex_login::ExternalAuthRefreshContext; use codex_model_provider::DEFAULT_CHATGPT_BASE_URL; use codex_protocol::config_types::TrustLevel; use pretty_assertions::assert_eq; use std::sync::Arc; -struct BootstrapExternalAuth(CodexAuth); - -impl ExternalAuth for BootstrapExternalAuth { - fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> { - Box::pin(async { Ok(self.0.clone()) }) - } - - fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> { - self.resolve() - } -} - -#[tokio::test] -async fn bootstrap_discovery_survives_identity_installation_but_account_access_is_revoked() --> anyhow::Result<()> { - let home = tempfile::tempdir()?; - let overrides = LoaderOverrides::without_managed_config_for_tests(); - let config = ConfigBuilder::default() - .codex_home(home.path().to_path_buf()) - .loader_overrides(overrides.clone()) - .build() - .await?; - let policy = EmbeddedNetworkPolicy::load(&overrides).await; - let auth_config = policy.bind_bootstrap_auth(config.auth_config()); - let bootstrap = auth_config.auth_route_config.http_client_factory().clone(); - let bundle_url = - codex_backend_client::Client::new(config.chatgpt_base_url.clone(), bootstrap.clone()) - .config_bundle_url() - .parse()?; - let content_url = "https://chatgpt.com/backend-api/codex/responses".parse()?; - let manager = AuthManager::new( - home.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::Ephemeral, - /*forced_chatgpt_workspace_id*/ None, - Some(config.chatgpt_base_url.clone()), - AuthKeyringBackendKind::default(), - auth_config.auth_route_config, - ) - .await; - assert!(manager.auth_cached().is_none()); - - bootstrap.network_policy().acquire(&bundle_url)?; - let mut previous_access: Option<(HttpClientFactory, NetworkPermit)> = None; - for identity in ["bootstrap-account-one", "bootstrap-account-two"] { - let token = format!( - "e30.{}.signature", - URL_SAFE_NO_PAD.encode(serde_json::to_vec(&serde_json::json!({ - "sub": "bootstrap-user", - "https://api.openai.com/auth": { - "chatgpt_user_id": "bootstrap-user", - "chatgpt_account_id": identity, - }, - }))?), - ); - let auth = CodexAuth::from_external_chatgpt_tokens(&token, identity, Some("enterprise"))?; - manager - .set_external_auth(Arc::new(BootstrapExternalAuth(auth))) - .await?; - - if let Some((client, permit)) = previous_access.take() { - assert_eq!(permit.check(), Err(NetworkPolicyDenied::Revoked)); - assert_eq!( - client.network_policy().acquire(&content_url).err(), - Some(NetworkPolicyDenied::Revoked) - ); - } - - // Discovery must remain possible after both initial login and a workspace change. - bootstrap.network_policy().acquire(&bundle_url)?; - assert_eq!( - bootstrap.network_policy().acquire(&content_url).err(), - Some(NetworkPolicyDenied::Destination) - ); - assert_eq!( - manager - .application_network_policy() - .acquire(&content_url) - .err(), - Some(NetworkPolicyDenied::Unavailable) - ); - - assert!(policy.effective.publish( - policy.effective.policy().revision(), - DestinationPolicy::Unrestricted, - )); - let client = manager.http_client_factory(); - let permit = client.network_policy().acquire(&content_url)?; - previous_access = Some((client, permit)); - } - - let (client, permit) = previous_access.expect("the last identity has active account access"); - manager.clear_external_auth(); - assert_eq!(permit.check(), Err(NetworkPolicyDenied::Revoked)); - assert_eq!( - client.network_policy().acquire(&content_url).err(), - Some(NetworkPolicyDenied::Revoked) - ); - assert_eq!( - manager - .application_network_policy() - .acquire(&content_url) - .err(), - Some(NetworkPolicyDenied::Unavailable) - ); - bootstrap.network_policy().acquire(&bundle_url)?; - - // Losing local requirements must still close the bootstrap route. - policy.local.unavailable(policy.local.policy().revision()); - assert_eq!( - bootstrap.network_policy().acquire(&bundle_url).err(), - Some(NetworkPolicyDenied::Unavailable) - ); - Ok(()) -} - #[tokio::test] async fn startup_reloads_the_callers_selected_project() -> anyhow::Result<()> { let temp = tempfile::tempdir()?; diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index a7aef89d..882e3b9b 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -99,13 +99,11 @@ pub use codex_agent_message_board_host::delete_agent_message_boards; pub use codex_agent_message_board_host::install_agent_message_board; mod analytics_utils; -mod app_info; mod app_server_tracing; mod attestation; mod auth_mode; mod bespoke_event_handling; #[doc(hidden)] -pub mod chatgpt_connectors; mod code_mode_host; mod codex_home_metrics; mod command_exec; @@ -155,7 +153,6 @@ mod thread_state; mod thread_status; mod transport; mod turn_admission; -mod turn_cost_worker; mod user_verification; mod user_verification_response; diff --git a/codex-rs/app-server/src/mcp_refresh.rs b/codex-rs/app-server/src/mcp_refresh.rs index 4a6e7daa..64325f25 100644 --- a/codex-rs/app-server/src/mcp_refresh.rs +++ b/codex-rs/app-server/src/mcp_refresh.rs @@ -560,8 +560,6 @@ enabled = false goal_service: Arc::new(codex_goal_extension::GoalService::new()), environment_manager: Arc::clone(&environment_manager), executor_skill_provider: Arc::clone(&executor_skill_provider), - git_attribution_base_url: good_config.chatgpt_base_url.clone(), - http_client_factory: good_config.http_client_factory(), queue_service: None, turn_start_admission: None, }, diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 309d5794..119b6457 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -26,7 +26,6 @@ use crate::outgoing_message::RequestContext; use crate::plugin_config_reload; use crate::plugin_config_reload::PluginStartupConfig; use crate::request_processors::AccountRequestProcessor; -use crate::request_processors::AppsRequestProcessor; use crate::request_processors::CatalogRequestProcessor; use crate::request_processors::CommandExecRequestProcessor; use crate::request_processors::ConfigRequestProcessor; @@ -61,7 +60,6 @@ use crate::thread_state::ConnectionCapabilities; use crate::thread_state::ThreadStateManager; use crate::transport::AppServerTransport; use crate::transport::RemoteControlHandle; -use crate::turn_cost_worker::TurnCostWorker; use codex_analytics::AnalyticsEventsClient; use codex_analytics::AppServerRpcTransport; use codex_app_server_protocol::ClientNotification; @@ -155,10 +153,8 @@ pub(crate) struct MessageProcessor { outgoing: Arc, startup_warnings: StartupWarnings, models_refresh_worker: ModelsRefreshWorker, - turn_cost_worker: Option, skills_watcher: Arc, account_processor: Arc, - apps_processor: AppsRequestProcessor, catalog_processor: CatalogRequestProcessor, command_exec_processor: CommandExecRequestProcessor, process_exec_processor: ProcessExecRequestProcessor, @@ -400,8 +396,6 @@ impl MessageProcessor { environment_manager: Arc::clone(&environment_manager_for_extensions), executor_skill_provider: Arc::clone(&executor_skill_provider), cloud_skill_provider: cloud_skill_provider.clone(), - git_attribution_base_url: config.chatgpt_base_url.clone(), - http_client_factory: config.http_client_factory(), queue_service: queue_service.clone(), turn_start_admission: Some(Arc::clone(&turn_start_admission)), }, @@ -440,11 +434,6 @@ impl MessageProcessor { Arc::clone(&thread_manager), )); let models_refresh_worker = crate::models_refresh_worker::spawn(&model_catalog); - let turn_cost_worker = TurnCostWorker::spawn( - Arc::clone(&config), - Arc::clone(&auth_manager), - runtime_auth.map(|runtime| (runtime, config.runtime_auth_mode)), - ); thread_manager .plugins_manager() .set_analytics_events_client(analytics_events_client.clone()); @@ -458,7 +447,6 @@ impl MessageProcessor { let thread_watch_manager = crate::thread_status::ThreadWatchManager::new_with_outgoing(outgoing.clone()); let thread_list_state_permit = Arc::new(Semaphore::new(/*permits*/ 1)); - let app_list_shutdown_token = CancellationToken::new(); let request_serialization_queues = RequestSerializationQueues::default(); let config_processor = ConfigRequestProcessor::new( outgoing.clone(), @@ -483,12 +471,6 @@ impl MessageProcessor { config_manager.clone(), Arc::clone(&model_catalog), ); - let apps_processor = AppsRequestProcessor::new( - Arc::clone(&thread_manager), - outgoing.clone(), - config_manager.clone(), - app_list_shutdown_token, - ); let catalog_processor = CatalogRequestProcessor::new( outgoing.clone(), Arc::clone(&skills_watcher), @@ -574,7 +556,6 @@ impl MessageProcessor { state_db.clone(), log_db, Arc::clone(&skills_watcher), - turn_cost_worker.as_ref().map(TurnCostWorker::handle), config_warnings.clone(), sample_responses, ); @@ -588,7 +569,6 @@ impl MessageProcessor { thread_state_manager, thread_watch_manager, Arc::clone(&skills_watcher), - turn_cost_worker.as_ref().map(TurnCostWorker::handle), ); if let Some(startup_config) = plugin_startup_tasks { let reload_config = match startup_config { @@ -650,10 +630,8 @@ impl MessageProcessor { config: config_warnings, }, models_refresh_worker, - turn_cost_worker, skills_watcher, account_processor, - apps_processor, catalog_processor, command_exec_processor, process_exec_processor, @@ -681,7 +659,6 @@ impl MessageProcessor { pub(crate) fn clear_runtime_references(&self) { self.account_processor.clear_external_auth(); - self.apps_processor.shutdown(); self.models_refresh_worker.shutdown(); self.skills_watcher.shutdown(); } @@ -915,9 +892,6 @@ impl MessageProcessor { pub(crate) async fn drain_background_tasks(&self) { self.models_refresh_worker.shutdown(); - if let Some(worker) = &self.turn_cost_worker { - worker.shutdown(); - } self.thread_processor.drain_background_tasks().await; } @@ -1706,15 +1680,22 @@ impl MessageProcessor { ClientRequest::PluginShareDelete { params, .. } => { self.plugin_processor.plugin_share_delete(params).await } - ClientRequest::AppsRead { params, .. } => self.apps_processor.apps_read(params).await, - ClientRequest::AppsList { params, .. } => { - self.apps_processor.apps_list(&request_id, params).await + // ChatGPT apps/connectors are not available in aKode. + ClientRequest::AppsRead { .. } => Err(method_not_found( + "ChatGPT apps are not available in aKode", + )), + ClientRequest::AppsList { .. } => Ok(Some( + codex_app_server_protocol::AppsListResponse { + data: Vec::new(), + next_cursor: None, + } + .into(), + )), + ClientRequest::AppsInstalled { .. } => { + Ok(Some( + codex_app_server_protocol::AppsInstalledResponse { apps: Vec::new() }.into(), + )) } - ClientRequest::AppsInstalled { params, .. } => self - .apps_processor - .apps_installed(params) - .await - .map(|response| Some(response.into())), ClientRequest::SkillsConfigWrite { params, .. } => { self.catalog_processor.skills_config_write(params).await } @@ -1948,25 +1929,13 @@ impl MessageProcessor { .await .into(), )), - ClientRequest::GetAccountRateLimits { params, .. } => { - self.account_processor.get_account_rate_limits(params).await - } - ClientRequest::ConsumeAccountRateLimitResetCredit { params, .. } => { - self.account_processor - .consume_account_rate_limit_reset_credit(params) - .await - } - ClientRequest::GetAccountTokenUsage { params, .. } => { - self.account_processor.get_account_token_usage(params).await - } - ClientRequest::GetWorkspaceMessages { .. } => { - self.account_processor.get_workspace_messages().await - } - ClientRequest::SendAddCreditsNudgeEmail { params, .. } => { - self.account_processor - .send_add_credits_nudge_email(params) - .await - } + ClientRequest::GetAccountRateLimits { .. } + | ClientRequest::ConsumeAccountRateLimitResetCredit { .. } + | ClientRequest::GetAccountTokenUsage { .. } + | ClientRequest::GetWorkspaceMessages { .. } + | ClientRequest::SendAddCreditsNudgeEmail { .. } => Err(method_not_found( + "ChatGPT usage, credits and workspace messages are not available in aKode", + )), ClientRequest::GitDiffToRemote { params, .. } => { self.git_processor.git_diff_to_remote(params).await } diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index b67e17ac..7b5a9544 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -1,5 +1,4 @@ use crate::bespoke_event_handling::apply_bespoke_event_handling; -use crate::chatgpt_connectors as connectors; use crate::command_exec::CommandExecManager; use crate::command_exec::StartCommandExecParams; use crate::config_manager::ConfigManager; @@ -22,23 +21,12 @@ use codex_analytics::InputError; use codex_analytics::TurnSteerRequestError; use codex_app_server_protocol::Account; use codex_app_server_protocol::AccountLoginCompletedNotification; -use codex_app_server_protocol::AccountTokenUsageDailyBucket; -use codex_app_server_protocol::AccountTokenUsageSummary; use codex_app_server_protocol::AccountUpdatedNotification; -use codex_app_server_protocol::AddCreditsNudgeCreditType; -use codex_app_server_protocol::AddCreditsNudgeEmailStatus; use codex_app_server_protocol::AdditionalContextEntry; use codex_app_server_protocol::AdditionalContextKind; -use codex_app_server_protocol::AppListUpdatedNotification; use codex_app_server_protocol::AppSummary; use codex_app_server_protocol::AppTemplateSummary; use codex_app_server_protocol::AppTemplateUnavailableReason; -use codex_app_server_protocol::AppsInstalledParams; -use codex_app_server_protocol::AppsInstalledResponse; -use codex_app_server_protocol::AppsListParams; -use codex_app_server_protocol::AppsListResponse; -use codex_app_server_protocol::AppsReadParams; -use codex_app_server_protocol::AppsReadResponse; use codex_app_server_protocol::AskForApproval; use codex_app_server_protocol::AuthMode; use codex_app_server_protocol::CancelLoginAccountParams; @@ -55,9 +43,6 @@ use codex_app_server_protocol::CommandExecResizeParams; use codex_app_server_protocol::CommandExecTerminateParams; use codex_app_server_protocol::CommandExecWriteParams; use codex_app_server_protocol::ConfigWarningNotification; -use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditOutcome; -use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditParams; -use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse; use codex_app_server_protocol::ConversationGitInfo; use codex_app_server_protocol::ConversationSummary; use codex_app_server_protocol::DeprecationNoticeNotification; @@ -79,15 +64,11 @@ use codex_app_server_protocol::ExperimentalFeatureStage as ApiExperimentalFeatur use codex_app_server_protocol::FeedbackUploadParams; use codex_app_server_protocol::FeedbackUploadResponse; use codex_app_server_protocol::GetAccountParams; -use codex_app_server_protocol::GetAccountRateLimitsResponse; use codex_app_server_protocol::GetAccountResponse; -use codex_app_server_protocol::GetAccountTokenUsageParams; -use codex_app_server_protocol::GetAccountTokenUsageResponse; use codex_app_server_protocol::GetAuthStatusParams; use codex_app_server_protocol::GetAuthStatusResponse; use codex_app_server_protocol::GetConversationSummaryParams; use codex_app_server_protocol::GetConversationSummaryResponse; -use codex_app_server_protocol::GetWorkspaceMessagesResponse; use codex_app_server_protocol::GitDiffToRemoteParams; use codex_app_server_protocol::GitDiffToRemoteResponse; use codex_app_server_protocol::GitInfo as ApiGitInfo; @@ -97,7 +78,6 @@ use codex_app_server_protocol::HooksListParams; use codex_app_server_protocol::HooksListResponse; use codex_app_server_protocol::InitializeParams; use codex_app_server_protocol::InitializeResponse; -use codex_app_server_protocol::InstalledApp; use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::ListMcpServerStatusParams; use codex_app_server_protocol::ListMcpServerStatusResponse; @@ -169,17 +149,11 @@ use codex_app_server_protocol::PluginSource; use codex_app_server_protocol::PluginSummary; use codex_app_server_protocol::PluginUninstallParams; use codex_app_server_protocol::PluginUninstallResponse; -use codex_app_server_protocol::RateLimitResetCredit; -use codex_app_server_protocol::RateLimitResetCreditStatus; -use codex_app_server_protocol::RateLimitResetCreditsSummary; -use codex_app_server_protocol::RateLimitResetType; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ReviewStartParams; use codex_app_server_protocol::ReviewStartResponse; use codex_app_server_protocol::ReviewTarget as ApiReviewTarget; use codex_app_server_protocol::SandboxMode; -use codex_app_server_protocol::SendAddCreditsNudgeEmailParams; -use codex_app_server_protocol::SendAddCreditsNudgeEmailResponse; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::SkillSummary; use codex_app_server_protocol::SkillsConfigWriteParams; @@ -316,29 +290,16 @@ use codex_app_server_protocol::WindowsSandboxSetupCompletedNotification; use codex_app_server_protocol::WindowsSandboxSetupMode; use codex_app_server_protocol::WindowsSandboxSetupStartParams; use codex_app_server_protocol::WindowsSandboxSetupStartResponse; -use codex_app_server_protocol::WorkspaceMessage; -use codex_app_server_protocol::WorkspaceMessageType; use codex_arg0::Arg0DispatchPaths; -use codex_backend_client::AddCreditsNudgeCreditType as BackendAddCreditsNudgeCreditType; use codex_backend_client::Client as BackendClient; -use codex_backend_client::CodexWorkspaceMessage as BackendWorkspaceMessage; -use codex_backend_client::CodexWorkspaceMessageType as BackendWorkspaceMessageType; -use codex_backend_client::CodexWorkspaceMessagesResponse as BackendWorkspaceMessagesResponse; -use codex_backend_client::ConsumeRateLimitResetCreditCode as BackendConsumeRateLimitResetCreditCode; -use codex_backend_client::RateLimitResetCreditDetails as BackendRateLimitResetCreditDetails; -use codex_backend_client::RateLimitResetCreditsDetails as BackendRateLimitResetCreditsDetails; -use codex_backend_client::RequestError as BackendRequestError; -use codex_backend_client::TokenUsageProfile; use codex_config::CloudConfigBundleLoadError; use codex_config::CloudConfigBundleLoadErrorCode; use codex_config::ConfigLayerStack; use codex_config::loader::project_trust_key; use codex_config::types::McpServerTransportConfig; -use codex_connectors::AppInfo; use codex_core::CodexThread; use codex_core::CodexThreadSettingsOverrides; use codex_core::ForkSnapshot; -use codex_core::McpManager; use codex_core::NewThread; use codex_core::NotSubmittedReason; #[cfg(test)] @@ -356,7 +317,6 @@ use codex_core::config::ConfigOverrides; use codex_core::config::NetworkProxyAuditMetadata; use codex_core::config::edit::ConfigEdit; use codex_core::config::edit::ConfigEditsBuilder; -use codex_core::connectors::AccessibleConnectorsStatus; use codex_core::exec::ExecCapturePolicy; use codex_core::exec::ExecExpiration; use codex_core::exec::ExecParams; @@ -376,7 +336,6 @@ use codex_core_plugins::PluginInstallError as CorePluginInstallError; use codex_core_plugins::PluginInstallRequest; use codex_core_plugins::PluginReadRequest; use codex_core_plugins::PluginUninstallError as CorePluginUninstallError; -use codex_core_plugins::PluginsManager; use codex_core_plugins::loader::load_plugin_apps; use codex_core_plugins::manifest::PluginManifestInterface; use codex_core_plugins::marketplace::MarketplaceError; @@ -525,7 +484,6 @@ use tokio::sync::broadcast; use tokio::sync::oneshot; use tokio::sync::watch; use tokio_util::sync::CancellationToken; -use tokio_util::sync::DropGuard; use tokio_util::task::TaskTracker; use toml::Value as TomlValue; use tracing::Instrument; @@ -538,7 +496,6 @@ use uuid::Uuid; use codex_app_server_protocol::ServerRequest; pub(crate) mod account_processor; -mod apps_processor; mod bedrock_auth; mod catalog_processor; mod command_exec_processor; @@ -580,7 +537,6 @@ mod turn_processor; mod windows_sandbox_processor; pub(crate) use account_processor::AccountRequestProcessor; -pub(crate) use apps_processor::AppsRequestProcessor; pub(crate) use catalog_processor::CatalogRequestProcessor; pub(crate) use command_exec_processor::CommandExecRequestProcessor; pub(crate) use config_processor::ConfigRequestProcessor; 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 6795600b..a6b92ab1 100644 --- a/codex-rs/app-server/src/request_processors/account_processor.rs +++ b/codex-rs/app-server/src/request_processors/account_processor.rs @@ -7,9 +7,7 @@ use crate::auth_mode::auth_mode_to_api; use crate::external_auth::ExternalAuthBridge; use crate::model_catalog::ModelCatalog; use crate::outgoing_message::AccountNotification; -use chrono::DateTime; use codex_app_server_protocol::DesktopOnboardingEntrypoint; -use codex_app_server_protocol::GetAccountRateLimitsParams; use codex_login::LoginOnboardingEntrypoint; use codex_login::login_with_bedrock_access_keys; use codex_mcp::ema_auth_scope; @@ -17,13 +15,11 @@ use codex_model_provider::is_supported_amazon_bedrock_region; use codex_otel::auth_storage::AuthStorageOriginator; use codex_rmcp_client::EnterpriseOAuthCredentialGuard; -mod backend_client; mod bedrock_gov_cloud; mod bedrock_setup; mod enterprise_login; mod gateway_oauth; mod gcp_setup; -mod rate_limit_resets; mod security_setup; mod workspace_routing; mod workspace_switching; @@ -34,10 +30,6 @@ pub(crate) use gcp_setup::handle_gcp_setup; // Duration before a browser ChatGPT login attempt is abandoned. const LOGIN_CHATGPT_TIMEOUT: Duration = Duration::from_secs(10 * 60); -const ACCOUNT_TOKEN_USAGE_FETCH_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10); -const THREAD_USAGE_FETCH_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 60); -const ACCOUNT_WORKSPACE_MESSAGES_FETCH_TIMEOUT: Duration = - Duration::from_millis(/*millis*/ 1000); // Packaged clients use this together with the OAuth client ID override for staging login. const LOGIN_ISSUER_OVERRIDE_ENV_VAR: &str = "CODEX_APP_SERVER_LOGIN_ISSUER"; // The development success-page redirect remains debug-only. @@ -205,41 +197,6 @@ impl AccountRequestProcessor { .map(|response| Some(response.into())) } - pub(crate) async fn get_account_rate_limits( - &self, - params: Option, - ) -> Result, JSONRPCErrorError> { - self.get_account_rate_limits_response(params.unwrap_or_default()) - .await - .map(|response| Some(response.into())) - } - - pub(crate) async fn get_account_token_usage( - &self, - params: Option, - ) -> Result, JSONRPCErrorError> { - self.get_account_token_usage_response(params) - .await - .map(|response| Some(response.into())) - } - - pub(crate) async fn get_workspace_messages( - &self, - ) -> Result, JSONRPCErrorError> { - self.get_workspace_messages_response() - .await - .map(|response| Some(response.into())) - } - - pub(crate) async fn send_add_credits_nudge_email( - &self, - params: SendAddCreditsNudgeEmailParams, - ) -> Result, JSONRPCErrorError> { - self.send_add_credits_nudge_email_response(params) - .await - .map(|response| Some(response.into())) - } - pub(crate) async fn cancel_active_login(&self) { self.cancel_gateway_login(); self.enterprise_login.cancel(/*login_id*/ None).await; @@ -1169,376 +1126,6 @@ impl AccountRequestProcessor { Ok(response) } - - async fn get_account_rate_limits_response( - &self, - params: GetAccountRateLimitsParams, - ) -> Result { - let Some((auth, http_client_factory)) = - self.auth_manager.auth_with_http_client_factory().await - else { - return Err(invalid_request( - "codex account authentication required to read rate limits", - )); - }; - - if !auth.uses_codex_backend() { - return Err(invalid_request( - "chatgpt authentication required to read rate limits", - )); - } - - let client = self.backend_client(&auth, http_client_factory).await?; - - let usage_request = async { - if params.supports_luna_reserve - && auth.auth_mode() == codex_protocol::auth::AuthMode::Chatgpt - && !auth.is_fedramp_account() - { - client.get_rate_limits_with_luna_reserve().await - } else { - client.get_rate_limits_with_reset_credits().await - } - }; - let (response, detailed_rate_limit_reset_credits) = tokio::join!(usage_request, async { - if params.exclude_reset_credit_details { - None - } else { - Self::detailed_rate_limit_reset_credits(&client).await - } - },); - let response = response - .map_err(|err| internal_error(format!("failed to fetch codex rate limits: {err}")))?; - if response.rate_limits.is_empty() { - return Err(internal_error( - "failed to fetch codex rate limits: no snapshots returned", - )); - } - - let rate_limits_by_limit_id: HashMap<_, _> = response - .rate_limits - .iter() - .cloned() - .map(|snapshot| { - let limit_id = snapshot - .limit_id - .clone() - .unwrap_or_else(|| "codex".to_string()); - (limit_id, snapshot) - }) - .collect(); - let rate_limits = response - .rate_limits - .iter() - .find(|snapshot| snapshot.limit_id.as_deref() == Some("codex")) - .cloned() - .unwrap_or_else(|| response.rate_limits[0].clone()); - - let rate_limit_reset_credits = detailed_rate_limit_reset_credits.or_else(|| { - response - .rate_limit_reset_credits - .map(|summary| RateLimitResetCreditsSummary { - available_count: summary.available_count, - credits: None, - }) - }); - - // Match desktop's account readiness check before exposing account-bound CTA content. - // Normal rate limits remain available when older backends omit identity or banner data. - // Login can change while the backend read is in flight. - let active_auth = self.auth_manager.auth().await; - let matches_active_account = active_auth.is_some_and(|auth| { - !auth.is_fedramp_account() - && response.account_id.is_some() - && response.account_id == auth.get_account_id() - && response.user_id.is_some() - && response.user_id == auth.get_chatgpt_user_id() - }); - let rate_limit_upsell = response - .rate_limit_upsell - .filter(|_| matches_active_account); - - Ok(GetAccountRateLimitsResponse { - ordinary_usage_allowed: response - .ordinary_usage_allowed - .filter(|_| matches_active_account), - rate_limits: rate_limits.into(), - rate_limits_by_limit_id: Some( - rate_limits_by_limit_id - .into_iter() - .map(|(limit_id, snapshot)| (limit_id, snapshot.into())) - .collect(), - ), - rate_limit_reset_credits, - account_id: response.account_id, - rate_limit_upsell, - }) - } - - async fn get_account_token_usage_response( - &self, - params: Option, - ) -> Result { - let thread_id = params - .and_then(|params| params.thread_id) - .map(|thread_id| { - ThreadId::from_string(&thread_id) - .map_err(|err| invalid_request(format!("invalid thread id: {err}"))) - }) - .transpose()?; - - let Some((auth, http_client_factory)) = - self.auth_manager.auth_with_http_client_factory().await - else { - return Err(invalid_request( - "codex account authentication required to read token usage", - )); - }; - - if !auth.uses_codex_backend() { - return Err(invalid_request( - "chatgpt authentication required to read token usage", - )); - } - - let client = self.backend_client(&auth, http_client_factory).await?; - if let Some(thread_id) = thread_id { - let thread_id = thread_id.to_string(); - let usage = tokio::time::timeout( - THREAD_USAGE_FETCH_TIMEOUT, - client.get_thread_usage(&thread_id), - ) - .await - .map_err(|_| internal_error("thread usage fetch timed out"))?; - let thread_usage = match usage { - Ok(usage) => Some(codex_app_server_protocol::ThreadUsage { - thread_id: usage.thread_id, - estimated_usage_credits_micros: usage.estimated_usage_credits_micros, - estimated_usage_usd_micros: usage.estimated_usage_usd_micros, - native_usage_usd_micros: usage.native_usage_usd_micros, - groups: usage - .groups - .into_iter() - .map( - |group| codex_app_server_protocol::ThreadUsageBreakdownGroup { - model: group.model, - reasoning_effort: group.reasoning_effort, - speed: group.speed, - estimated_usage_credits_micros: group - .estimated_usage_credits_micros, - net_new_input_tokens: group.net_new_input_tokens, - cached_input_tokens: group.cached_input_tokens, - input_tokens: group.input_tokens, - output_tokens: group.output_tokens, - total_tokens: group.total_tokens, - }, - ) - .collect(), - }), - Err(err) - if matches!(err.status().map(|status| status.as_u16()), Some(403 | 404)) => - { - None - } - Err(err) => { - return Err(internal_error(format!( - "failed to fetch thread usage: {err}" - ))); - } - }; - return Ok(GetAccountTokenUsageResponse { - summary: AccountTokenUsageSummary { - lifetime_tokens: None, - peak_daily_tokens: None, - longest_running_turn_sec: None, - current_streak_days: None, - longest_streak_days: None, - }, - daily_usage_buckets: None, - thread_usage, - }); - } - let profile = tokio::time::timeout( - ACCOUNT_TOKEN_USAGE_FETCH_TIMEOUT, - client.get_token_usage_profile(), - ) - .await - .map_err(|_| internal_error("token usage profile fetch timed out"))? - .map_err(|err| internal_error(format!("failed to fetch token usage profile: {err}")))?; - Ok(Self::account_token_usage_response(profile)) - } - - async fn get_workspace_messages_response( - &self, - ) -> Result { - let Some((auth, http_client_factory)) = - self.auth_manager.auth_with_http_client_factory().await - else { - return Err(invalid_request( - "codex account authentication required to read workspace messages", - )); - }; - - if !auth.uses_codex_backend() { - return Err(invalid_request( - "chatgpt authentication required to read workspace messages", - )); - } - - let client = self.backend_client(&auth, http_client_factory).await?; - let messages = tokio::time::timeout( - ACCOUNT_WORKSPACE_MESSAGES_FETCH_TIMEOUT, - client.list_workspace_messages(), - ) - .await - .map_err(|_| internal_error("workspace messages fetch timed out"))?; - - match messages { - Ok(messages) => { - Self::workspace_messages_response(messages, /*feature_enabled*/ true) - } - Err(err) if workspace_messages_feature_disabled(&err) => { - Self::workspace_messages_response( - BackendWorkspaceMessagesResponse { - messages: Vec::new(), - }, - /*feature_enabled*/ false, - ) - } - Err(err) => Err(internal_error(format!( - "failed to fetch workspace messages: {err}" - ))), - } - } - - fn account_token_usage_response(profile: TokenUsageProfile) -> GetAccountTokenUsageResponse { - let stats = profile.stats; - GetAccountTokenUsageResponse { - summary: AccountTokenUsageSummary { - lifetime_tokens: stats.lifetime_tokens, - peak_daily_tokens: stats.peak_daily_tokens, - longest_running_turn_sec: stats.longest_running_turn_sec, - current_streak_days: stats.current_streak_days, - longest_streak_days: stats.longest_streak_days, - }, - daily_usage_buckets: stats.daily_usage_buckets.map(|buckets| { - buckets - .into_iter() - .map(|bucket| AccountTokenUsageDailyBucket { - start_date: bucket.start_date, - tokens: bucket.tokens, - }) - .collect() - }), - thread_usage: None, - } - } - - fn workspace_messages_response( - messages: BackendWorkspaceMessagesResponse, - feature_enabled: bool, - ) -> Result { - Ok(GetWorkspaceMessagesResponse { - feature_enabled, - messages: messages - .messages - .into_iter() - .map(workspace_message_from_backend) - .collect::, _>>()?, - }) - } - - async fn send_add_credits_nudge_email_response( - &self, - params: SendAddCreditsNudgeEmailParams, - ) -> Result { - self.send_add_credits_nudge_email_inner(params) - .await - .map(|status| SendAddCreditsNudgeEmailResponse { status }) - } - - async fn send_add_credits_nudge_email_inner( - &self, - params: SendAddCreditsNudgeEmailParams, - ) -> Result { - let Some((auth, http_client_factory)) = - self.auth_manager.auth_with_http_client_factory().await - else { - return Err(invalid_request( - "codex account authentication required to notify workspace owner", - )); - }; - - if !auth.uses_codex_backend() { - return Err(invalid_request( - "chatgpt authentication required to notify workspace owner", - )); - } - - let client = self.backend_client(&auth, http_client_factory).await?; - - match client - .send_add_credits_nudge_email(Self::backend_credit_type(params.credit_type)) - .await - { - Ok(()) => Ok(AddCreditsNudgeEmailStatus::Sent), - Err(err) if err.status().is_some_and(|status| status.as_u16() == 429) => { - Ok(AddCreditsNudgeEmailStatus::CooldownActive) - } - Err(err) => Err(internal_error(format!( - "failed to notify workspace owner: {err}" - ))), - } - } - - fn backend_credit_type(value: AddCreditsNudgeCreditType) -> BackendAddCreditsNudgeCreditType { - match value { - AddCreditsNudgeCreditType::Credits => BackendAddCreditsNudgeCreditType::Credits, - AddCreditsNudgeCreditType::UsageLimit => BackendAddCreditsNudgeCreditType::UsageLimit, - } - } -} - -fn workspace_message_from_backend( - message: BackendWorkspaceMessage, -) -> Result { - Ok(WorkspaceMessage { - message_id: message.message_id, - message_type: workspace_message_type_from_backend(message.message_type), - message_body: message.message_body, - created_at: workspace_message_timestamp_from_backend(message.created_at)?, - archived_at: workspace_message_timestamp_from_backend(message.archived_at)?, - }) -} - -fn workspace_message_timestamp_from_backend( - timestamp: Option, -) -> Result, JSONRPCErrorError> { - timestamp - .map(|timestamp| { - DateTime::parse_from_rfc3339(×tamp) - .map(|timestamp| timestamp.timestamp()) - .map_err(|err| { - internal_error(format!( - "failed to parse workspace message timestamp `{timestamp}`: {err}" - )) - }) - }) - .transpose() -} - -fn workspace_message_type_from_backend( - message_type: BackendWorkspaceMessageType, -) -> WorkspaceMessageType { - match message_type { - BackendWorkspaceMessageType::Headline => WorkspaceMessageType::Headline, - BackendWorkspaceMessageType::Announcement => WorkspaceMessageType::Announcement, - BackendWorkspaceMessageType::Unknown => WorkspaceMessageType::Unknown, - } -} - -fn workspace_messages_feature_disabled(err: &BackendRequestError) -> bool { - err.status().is_some_and(|status| status.as_u16() == 404) } /// Remove account credentials using the current account's policy, even during startup recovery. @@ -1616,98 +1203,3 @@ pub(crate) async fn clear_account_configuration( Ok(()) } -#[cfg(test)] -mod tests { - use super::*; - use codex_backend_client::TokenUsageProfileDailyBucket; - use codex_backend_client::TokenUsageProfileStats; - use http::StatusCode; - use pretty_assertions::assert_eq; - - #[test] - fn account_token_usage_response_maps_profile_stats_and_daily_buckets() { - let response = AccountRequestProcessor::account_token_usage_response(TokenUsageProfile { - stats: TokenUsageProfileStats { - lifetime_tokens: Some(123), - peak_daily_tokens: Some(45), - longest_running_turn_sec: Some(67), - current_streak_days: Some(8), - longest_streak_days: Some(9), - daily_usage_buckets: Some(vec![TokenUsageProfileDailyBucket { - start_date: "2026-05-29".to_string(), - tokens: 10, - }]), - }, - }); - - assert_eq!( - response, - GetAccountTokenUsageResponse { - summary: AccountTokenUsageSummary { - lifetime_tokens: Some(123), - peak_daily_tokens: Some(45), - longest_running_turn_sec: Some(67), - current_streak_days: Some(8), - longest_streak_days: Some(9), - }, - daily_usage_buckets: Some(vec![AccountTokenUsageDailyBucket { - start_date: "2026-05-29".to_string(), - tokens: 10, - }]), - thread_usage: None, - } - ); - } - - #[test] - fn workspace_messages_response_maps_backend_messages() { - let response = AccountRequestProcessor::workspace_messages_response( - BackendWorkspaceMessagesResponse { - messages: vec![BackendWorkspaceMessage { - message_id: "headline-id".to_string(), - message_type: BackendWorkspaceMessageType::Headline, - message_body: "Headline body".to_string(), - created_at: Some("2026-06-14T00:00:00Z".to_string()), - archived_at: Some("2026-06-15T00:00:00Z".to_string()), - }], - }, - /*feature_enabled*/ true, - ) - .expect("workspace message timestamps should parse"); - - assert_eq!( - response, - GetWorkspaceMessagesResponse { - feature_enabled: true, - messages: vec![WorkspaceMessage { - message_id: "headline-id".to_string(), - message_type: WorkspaceMessageType::Headline, - message_body: "Headline body".to_string(), - created_at: Some(1_781_395_200), - archived_at: Some(1_781_481_600), - }], - } - ); - } - - #[test] - fn workspace_messages_feature_disabled_only_for_not_found() { - let cases = [ - (StatusCode::NOT_FOUND, true), - (StatusCode::UNAUTHORIZED, false), - (StatusCode::FORBIDDEN, false), - ]; - - for (status, expected) in cases { - let err = BackendRequestError::UnexpectedStatus { - method: "GET".to_string(), - url: "https://example.test/api/codex/workspace-messages".to_string(), - status, - content_type: "application/json".to_string(), - body: "{}".to_string(), - identity_error_code: None, - }; - assert_eq!(workspace_messages_feature_disabled(&err), expected); - } - } -} diff --git a/codex-rs/app-server/src/request_processors/account_processor/backend_client.rs b/codex-rs/app-server/src/request_processors/account_processor/backend_client.rs deleted file mode 100644 index 9e3967ac..00000000 --- a/codex-rs/app-server/src/request_processors/account_processor/backend_client.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! Build account API clients from the latest config and captured account authority. - -use super::*; -use futures::future::BoxFuture; - -impl AccountRequestProcessor { - // Keep config loading and runtime bootstrap out of request-handler future types. - #[inline(never)] - pub(super) fn backend_client<'a>( - &'a self, - auth: &'a CodexAuth, - http_client_factory: codex_http_client::HttpClientFactory, - ) -> BoxFuture<'a, Result> { - Box::pin(async move { - let config = self.load_latest_config().await; - let runtime = self - .thread_manager - .runtime_auth_for_config(&config) - .map_err(|error| internal_error(error.to_string()))?; - BackendClient::from_auth_with_runtime( - config.chatgpt_base_url.clone(), - auth, - http_client_factory, - runtime.as_ref(), - /*headers*/ &Default::default(), - ) - .await - .map_err(|error| internal_error(error.to_string())) - }) - } -} diff --git a/codex-rs/app-server/src/request_processors/account_processor/rate_limit_resets.rs b/codex-rs/app-server/src/request_processors/account_processor/rate_limit_resets.rs deleted file mode 100644 index 5a1ee4c0..00000000 --- a/codex-rs/app-server/src/request_processors/account_processor/rate_limit_resets.rs +++ /dev/null @@ -1,169 +0,0 @@ -use super::*; - -const RATE_LIMIT_RESET_REQUEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10); -const RATE_LIMIT_RESET_DETAILS_REQUEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 5); -#[cfg(debug_assertions)] -const RATE_LIMIT_RESET_REQUEST_TIMEOUT_ENV_VAR: &str = - "CODEX_TEST_RATE_LIMIT_RESET_REQUEST_TIMEOUT_MS"; - -impl AccountRequestProcessor { - pub(super) async fn detailed_rate_limit_reset_credits( - client: &BackendClient, - ) -> Option { - let details = match tokio::time::timeout( - RATE_LIMIT_RESET_DETAILS_REQUEST_TIMEOUT, - client.list_rate_limit_reset_credits(), - ) - .await - { - Ok(Ok(details)) => details, - Ok(Err(err)) => { - tracing::warn!( - "failed to fetch rate limit reset credit details; falling back to the usage response: {err}" - ); - return None; - } - Err(_) => { - tracing::warn!( - "rate limit reset credit detail request timed out; falling back to the usage response" - ); - return None; - } - }; - - match rate_limit_reset_credits_from_backend(details) { - Ok(summary) => Some(summary), - Err(err) => { - tracing::warn!( - "failed to parse rate limit reset credit details; falling back to the usage response: {err}" - ); - None - } - } - } - - pub(crate) async fn consume_account_rate_limit_reset_credit( - &self, - params: ConsumeAccountRateLimitResetCreditParams, - ) -> Result, JSONRPCErrorError> { - if params.idempotency_key.is_empty() { - return Err(invalid_request("idempotencyKey must not be empty")); - } - if params.credit_id.as_deref().is_some_and(str::is_empty) { - return Err(invalid_request("creditId must not be empty")); - } - - let client = self.rate_limit_reset_backend_client().await?; - let request_timeout = RATE_LIMIT_RESET_REQUEST_TIMEOUT; - #[cfg(debug_assertions)] - let request_timeout = std::env::var(RATE_LIMIT_RESET_REQUEST_TIMEOUT_ENV_VAR) - .ok() - .and_then(|value| value.parse::().ok()) - .map(Duration::from_millis) - .unwrap_or(request_timeout); - let response = tokio::time::timeout(request_timeout, async { - match params.credit_id.as_deref() { - Some(credit_id) => { - client - .consume_rate_limit_reset_credit_by_id(¶ms.idempotency_key, credit_id) - .await - } - None => { - client - .consume_rate_limit_reset_credit(¶ms.idempotency_key) - .await - } - } - }) - .await - .map_err(|_| internal_error("rate limit reset consume timed out"))? - .map_err(|err| internal_error(format!("failed to consume rate limit reset: {err}")))?; - let outcome = match response.code { - BackendConsumeRateLimitResetCreditCode::Reset => { - ConsumeAccountRateLimitResetCreditOutcome::Reset - } - BackendConsumeRateLimitResetCreditCode::NothingToReset => { - ConsumeAccountRateLimitResetCreditOutcome::NothingToReset - } - BackendConsumeRateLimitResetCreditCode::NoCredit => { - ConsumeAccountRateLimitResetCreditOutcome::NoCredit - } - BackendConsumeRateLimitResetCreditCode::AlreadyRedeemed => { - ConsumeAccountRateLimitResetCreditOutcome::AlreadyRedeemed - } - }; - Ok(Some( - ConsumeAccountRateLimitResetCreditResponse { outcome }.into(), - )) - } - - async fn rate_limit_reset_backend_client(&self) -> Result { - let Some((auth, http_client_factory)) = - self.auth_manager.auth_with_http_client_factory().await - else { - return Err(invalid_request( - "codex account authentication required for rate limit reset credits", - )); - }; - if !auth.uses_codex_backend() { - return Err(invalid_request( - "chatgpt authentication required for rate limit reset credits", - )); - } - - self.backend_client(&auth, http_client_factory).await - } -} - -fn rate_limit_reset_credits_from_backend( - details: BackendRateLimitResetCreditsDetails, -) -> Result { - let credits = details - .credits - .into_iter() - .map(rate_limit_reset_credit_from_backend) - .collect::, _>>()?; - Ok(RateLimitResetCreditsSummary { - available_count: details.available_count, - credits: Some(credits), - }) -} - -fn rate_limit_reset_credit_from_backend( - credit: BackendRateLimitResetCreditDetails, -) -> Result { - let reset_type = match credit.reset_type.as_str() { - "codex_rate_limits" => RateLimitResetType::CodexRateLimits, - _ => RateLimitResetType::Unknown, - }; - let status = match credit.status.as_str() { - "available" => RateLimitResetCreditStatus::Available, - "redeeming" => RateLimitResetCreditStatus::Redeeming, - "redeemed" => RateLimitResetCreditStatus::Redeemed, - _ => RateLimitResetCreditStatus::Unknown, - }; - let granted_at = rate_limit_reset_credit_timestamp(&credit.granted_at) - .map_err(|err| format!("invalid granted_at for credit `{}`: {err}", credit.id))?; - let expires_at = credit - .expires_at - .as_deref() - .map(rate_limit_reset_credit_timestamp) - .transpose() - .map_err(|err| format!("invalid expires_at for credit `{}`: {err}", credit.id))?; - - Ok(RateLimitResetCredit { - id: credit.id, - reset_type, - status, - granted_at, - expires_at, - title: credit.title, - description: credit.description, - }) -} - -fn rate_limit_reset_credit_timestamp(timestamp: &str) -> Result { - DateTime::parse_from_rfc3339(timestamp) - .map(|timestamp| timestamp.timestamp()) - .map_err(|err| format!("failed to parse timestamp `{timestamp}`: {err}")) -} diff --git a/codex-rs/app-server/src/request_processors/apps_processor.rs b/codex-rs/app-server/src/request_processors/apps_processor.rs deleted file mode 100644 index 3dc90593..00000000 --- a/codex-rs/app-server/src/request_processors/apps_processor.rs +++ /dev/null @@ -1,497 +0,0 @@ -use super::*; -use crate::app_info::app_info_to_api; -use codex_connectors::AppToolPolicyEvaluator; - -mod installed; -mod read; - -pub(super) use read::APP_READ_MAX_IDS; - -pub(crate) struct AppsRequestProcessor { - thread_manager: Arc, - outgoing: Arc, - config_manager: ConfigManager, - shutdown_token: CancellationToken, - _shutdown_drop_guard: DropGuard, -} - -impl AppsRequestProcessor { - pub(crate) fn new( - thread_manager: Arc, - outgoing: Arc, - config_manager: ConfigManager, - shutdown_token: CancellationToken, - ) -> Self { - let shutdown_drop_guard = shutdown_token.clone().drop_guard(); - Self { - thread_manager, - outgoing, - config_manager, - shutdown_token, - _shutdown_drop_guard: shutdown_drop_guard, - } - } - - pub(crate) async fn apps_list( - &self, - request_id: &ConnectionRequestId, - params: AppsListParams, - ) -> Result, JSONRPCErrorError> { - self.apps_list_inner(request_id, params) - .await - .map(|response| response.map(Into::into)) - } - - async fn apps_list_inner( - &self, - request_id: &ConnectionRequestId, - params: AppsListParams, - ) -> Result, JSONRPCErrorError> { - let installed_start = Instant::now(); - let reload = params.force_refetch; - let thread = if let Some(thread_id) = params.thread_id.as_deref() { - let (_, loaded_thread) = self.load_thread(thread_id).await?; - Some(loaded_thread) - } else { - None - }; - let fallback_cwd = match thread.as_ref() { - Some(thread) => Some(thread.config_snapshot().await.cwd().to_path_buf()), - None => None, - }; - let mut config = self.load_latest_config(fallback_cwd).await?; - - if let Some(thread) = thread.as_ref() { - let _ = config - .features - .set_enabled(Feature::Apps, thread.enabled(Feature::Apps)); - } - - let mcp_manager = thread - .as_ref() - .map(|thread| thread.mcp_manager()) - .unwrap_or_else(|| self.thread_manager.mcp_manager()); - self.thread_manager - .runtime_auth_for_mcp_manager(&config, &mcp_manager) - .map_err(|error| internal_error(error.to_string()))?; - let auth_manager = mcp_manager.auth_manager(); - if params.force_refetch && !auth_manager.has_external_auth() { - auth_manager - .reload_with_cached_auth() - .await - .map_err(|error| internal_error(error.to_string()))?; - } - let auth = auth_manager.auth().await; - if !config - .features - .apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)) - { - let response = AppsListResponse { - data: Vec::new(), - next_cursor: None, - }; - record_legacy_apps_installed_duration(installed_start, reload); - return Ok(Some(response)); - } - - let request = request_id.clone(); - let outgoing = Arc::clone(&self.outgoing); - let environment_manager = self.thread_manager.environment_manager(); - let plugins_manager = mcp_manager.plugins_manager(); - let shutdown_token = self.shutdown_token.child_token(); - tokio::spawn(async move { - tokio::select! { - _ = shutdown_token.cancelled() => {} - _ = Self::apps_list_task( - outgoing, - request, - params, - config, - environment_manager, - mcp_manager, - plugins_manager, - installed_start, - ) => {} - } - }); - Ok(None) - } - - pub(crate) fn shutdown(&self) { - self.shutdown_token.cancel(); - } - - #[allow(clippy::too_many_arguments)] - async fn apps_list_task( - outgoing: Arc, - request_id: ConnectionRequestId, - params: AppsListParams, - config: Config, - environment_manager: Arc, - mcp_manager: Arc, - plugins_manager: Arc, - installed_start: Instant, - ) { - let reload = params.force_refetch; - let retry_params = params.clone(); - let retry_config = config.clone(); - let retry_environment_manager = Arc::clone(&environment_manager); - let retry_mcp_manager = Arc::clone(&mcp_manager); - let retry_plugins_manager = Arc::clone(&plugins_manager); - let result = Self::apps_list_response( - &outgoing, - params, - config, - environment_manager, - mcp_manager, - plugins_manager, - ) - .await; - if result.is_ok() { - record_legacy_apps_installed_duration(installed_start, reload); - } - let should_retry = result - .as_ref() - .is_ok_and(|(_, codex_apps_ready)| !codex_apps_ready); - outgoing - .send_result(request_id, result.map(|(response, _)| response)) - .await; - - if should_retry && !retry_params.force_refetch { - let mut retry_params = retry_params; - retry_params.force_refetch = true; - if let Err(err) = Self::apps_list_response( - &outgoing, - retry_params, - retry_config, - retry_environment_manager, - retry_mcp_manager, - retry_plugins_manager, - ) - .await - { - warn!("failed to refresh app list after codex-apps readiness retry: {err:?}"); - } - } - } - - async fn apps_list_response( - outgoing: &Arc, - params: AppsListParams, - config: Config, - environment_manager: Arc, - mcp_manager: Arc, - plugins_manager: Arc, - ) -> Result<(AppsListResponse, bool), JSONRPCErrorError> { - let AppsListParams { - cursor, - limit, - thread_id: _, - force_refetch, - } = params; - let start = match cursor { - Some(cursor) => match cursor.parse::() { - Ok(idx) => idx, - Err(_) => return Err(invalid_request(format!("invalid cursor: {cursor}"))), - }, - None => 0, - }; - - let loaded_plugins = plugins_manager - .plugins_for_config(&config.plugins_config_input()) - .await; - let connector_snapshot = - codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries( - loaded_plugins.capability_summaries(), - ); - let plugin_apps = connector_snapshot.connector_ids().to_vec(); - let mut config = config; - let auth = match mcp_manager - .auth_manager() - .auth_with_http_client_factory() - .await - { - Some((auth, factory)) => { - config.application_network_policy = factory.network_policy().clone(); - Some(auth) - } - None => None, - }; - let runtime = mcp_manager - .runtime_auth_for_config(&config) - .map(|(slot, mode)| { - slot.get() - .cloned() - .map(|runtime| (runtime, mode)) - .ok_or_else(|| { - internal_error("runtime authentication is not initialized".to_string()) - }) - }) - .transpose()?; - let mut accessible_connectors = - connectors::list_cached_accessible_connectors_from_mcp_tools(&config, auth.as_ref()); - let mut all_connectors = - connectors::list_cached_all_connectors(&config, auth.as_ref(), &plugin_apps); - let cached_all_connectors = all_connectors.clone(); - - let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); - - let accessible_config = config.clone(); - let accessible_tx = tx.clone(); - tokio::spawn(async move { - let result = connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager( - &accessible_config, - force_refetch, - Arc::clone(&environment_manager), - mcp_manager, - ) - .await - .map_err(|err| format!("failed to load accessible apps: {err}")); - let _ = accessible_tx.send(AppListLoadResult::Accessible(result)); - }); - - let all_config = config.clone(); - let all_plugin_apps = plugin_apps.clone(); - tokio::spawn(async move { - let result = connectors::list_all_connectors_with_options( - &all_config, - auth.as_ref(), - runtime.as_ref(), - force_refetch, - &all_plugin_apps, - ) - .await - .map_err(|err| format!("failed to list apps: {err}")); - let _ = tx.send(AppListLoadResult::Directory(result)); - }); - - let app_list_deadline = tokio::time::Instant::now() + APP_LIST_LOAD_TIMEOUT; - let mut accessible_loaded = false; - let mut all_loaded = false; - let mut codex_apps_ready = true; - let mut last_notified_apps = None; - let mut sent_app_list_update = false; - let app_policy = AppToolPolicyEvaluator::new(&config.config_layer_stack); - - if accessible_connectors.is_some() || all_connectors.is_some() { - let merged = app_policy.apply_app_enabled_state(merge_loaded_apps( - all_connectors.as_deref(), - accessible_connectors.as_deref(), - )); - if !force_refetch { - last_notified_apps = Some(merged); - } else if should_send_app_list_updated_notification( - merged.as_slice(), - accessible_loaded, - all_loaded, - ) { - send_app_list_updated_notification(outgoing, merged.clone()).await; - last_notified_apps = Some(merged); - sent_app_list_update = true; - } - } - - loop { - let result = match tokio::time::timeout_at(app_list_deadline, rx.recv()).await { - Ok(Some(result)) => result, - Ok(None) => { - return Err(internal_error("failed to load app lists")); - } - Err(_) => { - let timeout_seconds = APP_LIST_LOAD_TIMEOUT.as_secs(); - return Err(internal_error(format!( - "timed out waiting for app lists after {timeout_seconds} seconds" - ))); - } - }; - - match result { - AppListLoadResult::Accessible(Ok(status)) => { - accessible_connectors = Some(status.connectors); - accessible_loaded = true; - codex_apps_ready = status.codex_apps_ready; - } - AppListLoadResult::Accessible(Err(err)) => { - return Err(internal_error(err)); - } - AppListLoadResult::Directory(Ok(connectors)) => { - all_connectors = Some(connectors); - all_loaded = true; - } - AppListLoadResult::Directory(Err(err)) => { - return Err(internal_error(err)); - } - } - - let showing_interim_force_refetch = force_refetch && !(accessible_loaded && all_loaded); - let all_connectors_for_update = - if showing_interim_force_refetch && cached_all_connectors.is_some() { - cached_all_connectors.as_deref() - } else { - all_connectors.as_deref() - }; - let accessible_connectors_for_update = - if showing_interim_force_refetch && !accessible_loaded { - None - } else { - accessible_connectors.as_deref() - }; - let merged = app_policy.apply_app_enabled_state(merge_loaded_apps( - all_connectors_for_update, - accessible_connectors_for_update, - )); - if should_send_app_list_updated_notification( - merged.as_slice(), - accessible_loaded, - all_loaded, - ) && (last_notified_apps.as_ref() != Some(&merged) - || (!force_refetch - && start == 0 - && accessible_loaded - && all_loaded - && !sent_app_list_update)) - { - send_app_list_updated_notification(outgoing, merged.clone()).await; - last_notified_apps = Some(merged.clone()); - sent_app_list_update = true; - } - - if accessible_loaded && all_loaded { - let response = paginate_apps(merged.as_slice(), start, limit)?; - return Ok((response, codex_apps_ready)); - } - } - } - - async fn load_thread( - &self, - thread_id: &str, - ) -> Result<(ThreadId, Arc), JSONRPCErrorError> { - let thread_id = ThreadId::from_string(thread_id) - .map_err(|err| invalid_request(format!("invalid thread id: {err}")))?; - - let thread = self - .thread_manager - .get_thread(thread_id) - .await - .map_err(|_| invalid_request(format!("thread not found: {thread_id}")))?; - - Ok((thread_id, thread)) - } - - async fn load_latest_config( - &self, - fallback_cwd: Option, - ) -> Result { - self.config_manager - .load_latest_config(fallback_cwd) - .await - .map_err(|err| internal_error(format!("failed to reload config: {err}"))) - } - - async fn load_apps_config( - &self, - thread_id: Option<&str>, - ) -> Result<(Config, Arc), JSONRPCErrorError> { - let Some(thread_id) = thread_id else { - let config = self.load_latest_config(/*fallback_cwd*/ None).await?; - self.thread_manager - .runtime_auth_for_config(&config) - .map_err(|error| internal_error(error.to_string()))?; - return Ok((config, self.thread_manager.mcp_manager())); - }; - let (_, thread) = self.load_thread(thread_id).await?; - let thread_config = thread.config().await; - let config = self - .config_manager - .load_latest_config_with_session_layers( - &thread_config.config_layer_stack, - &thread_config.cwd, - ) - .await - .map_err(|err| internal_error(format!("failed to reload config: {err}")))?; - let mcp_manager = thread.mcp_manager(); - self.thread_manager - .runtime_auth_for_mcp_manager(&config, &mcp_manager) - .map_err(|error| internal_error(error.to_string()))?; - Ok((config, mcp_manager)) - } -} - -const APP_LIST_LOAD_TIMEOUT: Duration = Duration::from_secs(90); -// `app/list` is the legacy request-path baseline for the `app/installed` endpoint; -// `path=legacy` keeps it separate from the new snapshot-backed implementation in dashboards. -const APPS_INSTALLED_DURATION_METRIC: &str = "codex.apps.installed.duration_ms"; - -fn record_legacy_apps_installed_duration(started_at: Instant, reload: bool) { - let reload = if reload { "true" } else { "false" }; - if let Some(metrics) = codex_otel::global() { - let _ = metrics.record_duration( - APPS_INSTALLED_DURATION_METRIC, - started_at.elapsed(), - &[("path", "legacy"), ("reload", reload)], - ); - } -} -enum AppListLoadResult { - Accessible(Result), - Directory(Result, String>), -} - -fn merge_loaded_apps( - all_connectors: Option<&[AppInfo]>, - accessible_connectors: Option<&[AppInfo]>, -) -> Vec { - let all_connectors_loaded = all_connectors.is_some(); - let all = all_connectors.map_or_else(Vec::new, <[AppInfo]>::to_vec); - let accessible = accessible_connectors.map_or_else(Vec::new, <[AppInfo]>::to_vec); - connectors::merge_connectors_with_accessible(all, accessible, all_connectors_loaded) -} - -fn should_send_app_list_updated_notification( - connectors: &[AppInfo], - accessible_loaded: bool, - all_loaded: bool, -) -> bool { - connectors.iter().any(|connector| connector.is_accessible) || (accessible_loaded && all_loaded) -} - -fn paginate_apps( - connectors: &[AppInfo], - start: usize, - limit: Option, -) -> Result { - let total = connectors.len(); - if start > total { - return Err(invalid_request(format!( - "cursor {start} exceeds total apps {total}" - ))); - } - - let effective_limit = limit.unwrap_or(total as u32).max(1) as usize; - let end = start.saturating_add(effective_limit).min(total); - let data = connectors[start..end] - .iter() - .cloned() - .map(app_info_to_api) - .collect(); - let next_cursor = if end < total { - Some(end.to_string()) - } else { - None - }; - - Ok(AppsListResponse { data, next_cursor }) -} - -async fn send_app_list_updated_notification( - outgoing: &Arc, - data: Vec, -) { - let data = data.into_iter().map(app_info_to_api).collect(); - outgoing - .send_server_notification(ServerNotification::AppListUpdated( - AppListUpdatedNotification { data }, - )) - .await; -} diff --git a/codex-rs/app-server/src/request_processors/apps_processor/installed.rs b/codex-rs/app-server/src/request_processors/apps_processor/installed.rs deleted file mode 100644 index ce6c1052..00000000 --- a/codex-rs/app-server/src/request_processors/apps_processor/installed.rs +++ /dev/null @@ -1,293 +0,0 @@ -use super::*; - -use codex_connectors::ConnectorRuntimeTool; -use codex_connectors::connector_runtime_context_key; -use codex_connectors::connector_tool_is_synthetic; -use codex_connectors::installed_connector_runtime; -use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; -use codex_mcp::MCP_TOOL_CODEX_APPS_META_KEY; -use codex_mcp::McpRuntime; -use codex_mcp::McpRuntimeInput; -use codex_mcp::McpStartupPolicy; -use codex_mcp::ToolInfo; -use codex_mcp::effective_mcp_servers; -use codex_mcp::host_owned_codex_apps_enabled; -use codex_mcp::tool_is_model_visible; -use codex_protocol::mcp::ClientMcpExtensions; - -#[cfg(test)] -#[path = "installed_tests.rs"] -mod tests; - -const CONNECTOR_RUNTIME_REFRESH_TIMEOUT: Duration = Duration::from_secs(30); -const APPS_INSTALLED_SUBMIT_ID: &str = "app-installed"; -const APPS_INSTALLED_RESPONSE_BYTES_METRIC: &str = "codex.apps.installed.response_bytes"; -const APPS_INSTALLED_CONNECTOR_COUNT_METRIC: &str = "codex.apps.installed.connector_count"; -const APPS_INSTALLED_TOOL_COUNT_METRIC: &str = "codex.apps.installed.tool_count"; -const APPS_SNAPSHOT_AGE_METRIC: &str = "codex.apps.snapshot.age_ms"; - -struct AppsInstalledSnapshotMetrics { - age: Option, - tool_count: usize, -} - -impl AppsRequestProcessor { - pub(crate) async fn apps_installed( - &self, - params: AppsInstalledParams, - ) -> Result { - let started_at = Instant::now(); - let force_refresh = params.force_refresh; - let mut retained_previous_snapshot = false; - let mut refresh_disposition = if force_refresh { - "not_started" - } else { - "not_requested" - }; - let mut snapshot_age = None; - let mut snapshot_tool_count = 0; - let result = async { - let (config, thread) = match params.thread_id.as_deref() { - Some(thread_id) => { - let (_, thread) = self.load_thread(thread_id).await?; - let config = thread.config().await; - (config.as_ref().clone(), Some(thread)) - } - None => ( - self.load_latest_config(/*fallback_cwd*/ None).await?, - None, - ), - }; - let mcp_manager = thread.as_ref().map(|thread| thread.mcp_manager()) - .unwrap_or_else(|| self.thread_manager.mcp_manager()); - let auth_manager = mcp_manager.auth_manager(); - let auth = auth_manager.auth().await; - let runtime_enabled = config - .features - .apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)); - - let cache_key = connector_runtime_context_key(auth.as_ref()); - let previous_snapshot = mcp_manager - .codex_apps_tools_cache() - .current_snapshot(config.codex_home.to_path_buf(), cache_key.clone()); - let mut model_visible_tool_names = None; - let tools = if force_refresh && runtime_enabled { - let refresh_result = async { - if let Some(thread) = thread { - let snapshot = thread.refresh_codex_apps_tools().await?; - model_visible_tool_names = Some(snapshot.model_visible_tool_names); - snapshot_age = Some(Duration::ZERO); - return Ok(snapshot.tools); - } - let mcp_config = mcp_manager.runtime_config(&config).await; - let mut mcp_servers = effective_mcp_servers(&mcp_config, auth.as_ref()); - mcp_servers.retain(|name, _| name == CODEX_APPS_MCP_SERVER_NAME); - let mcp_config = Arc::new(mcp_config.for_threadless_operations(&mcp_servers)); - anyhow::ensure!( - !mcp_servers.is_empty(), - "host-owned MCP server '{CODEX_APPS_MCP_SERVER_NAME}' is not enabled" - ); - let startup_timeout = mcp_servers - .get(CODEX_APPS_MCP_SERVER_NAME) - .and_then(|server| server.config().startup_timeout_sec) - .unwrap_or(CONNECTOR_RUNTIME_REFRESH_TIMEOUT); - let runtime_context = McpRuntimeContext::new( - self.thread_manager.environment_manager(), - config.cwd.to_path_buf(), - ); - let cancellation_token = CancellationToken::new(); - let codex_apps_auth_manager = - host_owned_codex_apps_enabled(&mcp_config, auth.as_ref()) - .then(|| Arc::clone(&auth_manager)); - self.thread_manager.runtime_auth_for_mcp_manager(&config, &mcp_manager)?; - let runtime = McpRuntime::new(McpRuntimeInput { - network_policy_metadata: None, - runtime_auth: mcp_manager.runtime_auth_for_config(&config), - startup_policy: McpStartupPolicy::Eager, - config: Arc::clone(&mcp_config), - plugins_available: false, - ready_selected_capability_roots: Vec::new(), - mcp_servers, - submit_id: APPS_INSTALLED_SUBMIT_ID.to_string(), - tx_event: None, - startup_cancellation_token: cancellation_token.clone(), - runtime_context, - codex_apps_tools_cache: mcp_manager.codex_apps_tools_cache(), - tool_catalog_cache: mcp_manager.tool_catalog_cache(), - codex_apps_tools_cache_key: cache_key.clone(), - client_mcp_extensions: ClientMcpExtensions::default(), - auth: auth.clone(), - auth_manager: codex_apps_auth_manager, - elicitation_reviewer: None, - elicitation_lifecycle: None, - }) - .await; - - let result = if runtime - .latest_wait_for_server_ready( - CODEX_APPS_MCP_SERVER_NAME, - startup_timeout, - ) - .await - { - mcp_manager - .codex_apps_tools_cache() - .current_snapshot(config.codex_home.to_path_buf(), cache_key.clone()) - .ok_or_else(|| { - anyhow::anyhow!( - "hosted connector refresh completed without publishing a snapshot" - ) - }) - } else { - Err(anyhow::anyhow!( - "failed to refresh tools for MCP server '{CODEX_APPS_MCP_SERVER_NAME}'" - )) - }; - cancellation_token.cancel(); - runtime.shutdown().await; - result.map(|snapshot| { - snapshot_age = Some(snapshot.age()); - snapshot.tools().to_vec() - }) - } - .await; - - match refresh_result { - Ok(tools) => { - refresh_disposition = "success"; - tools - } - Err(err) => { - refresh_disposition = "error"; - retained_previous_snapshot = previous_snapshot.is_some(); - return Err(internal_error(format!( - "failed to refresh installed connector runtime state: {err:#}" - ))); - } - } - } else { - if force_refresh { - refresh_disposition = "skipped_apps_disabled"; - retained_previous_snapshot = previous_snapshot.is_some(); - } - previous_snapshot.map_or_else(Vec::new, |snapshot| { - snapshot_age = Some(snapshot.age()); - snapshot.tools().to_vec() - }) - }; - - snapshot_tool_count = tools.len(); - let apps = installed_connector_runtime( - &config.config_layer_stack, - tools.iter().map(|tool| { - let mut runtime_tool = connector_runtime_tool(tool); - if let Some(names) = &model_visible_tool_names { - runtime_tool.model_visible &= names.contains(tool.tool.name.as_ref()); - } - runtime_tool - }), - ) - .into_iter() - .map(|app| InstalledApp { - id: app.id, - runtime_name: app.runtime_name, - enabled: runtime_enabled && app.enabled, - callable: runtime_enabled && app.callable, - }) - .collect(); - Ok(AppsInstalledResponse { apps }) - } - .await; - - if let Some(metrics) = codex_otel::global() { - record_apps_installed_metrics( - &metrics, - started_at, - force_refresh, - retained_previous_snapshot, - refresh_disposition, - AppsInstalledSnapshotMetrics { - age: snapshot_age, - tool_count: snapshot_tool_count, - }, - result.as_ref().ok(), - ); - } - result - } -} - -fn connector_runtime_tool(tool: &ToolInfo) -> ConnectorRuntimeTool<'_> { - let annotations = tool.tool.annotations.as_ref(); - ConnectorRuntimeTool { - connector_id: tool.connector_id.as_deref(), - connector_name: tool.connector_name.as_deref(), - tool_name: &tool.tool.name, - tool_title: tool.tool.title.as_deref(), - destructive_hint: annotations.and_then(|annotations| annotations.destructive_hint), - open_world_hint: annotations.and_then(|annotations| annotations.open_world_hint), - synthetic: connector_tool_is_synthetic( - tool.tool - .meta - .as_deref() - .and_then(|meta| meta.get(MCP_TOOL_CODEX_APPS_META_KEY)), - ), - model_visible: tool_is_model_visible(tool), - } -} - -fn record_apps_installed_metrics( - metrics: &codex_otel::MetricsClient, - started_at: Instant, - force_refresh: bool, - retained_previous_snapshot: bool, - refresh_disposition: &'static str, - snapshot_metrics: AppsInstalledSnapshotMetrics, - response: Option<&AppsInstalledResponse>, -) { - let Some(response) = response else { - return; - }; - let force_refresh = if force_refresh { "true" } else { "false" }; - let retained_previous_snapshot = if retained_previous_snapshot { - "true" - } else { - "false" - }; - let _ = metrics.record_duration( - APPS_INSTALLED_DURATION_METRIC, - started_at.elapsed(), - &[ - ("path", "installed"), - ("reload", force_refresh), - ("force_refresh", force_refresh), - ("refresh", refresh_disposition), - ("outcome", "success"), - ("retained_previous_snapshot", retained_previous_snapshot), - ], - ); - if let Ok(bytes) = serde_json::to_vec(response) { - let _ = metrics.histogram( - APPS_INSTALLED_RESPONSE_BYTES_METRIC, - i64::try_from(bytes.len()).unwrap_or(i64::MAX), - &[("path", "new")], - ); - } - let _ = metrics.histogram( - APPS_INSTALLED_CONNECTOR_COUNT_METRIC, - i64::try_from(response.apps.len()).unwrap_or(i64::MAX), - &[("path", "new")], - ); - let _ = metrics.histogram( - APPS_INSTALLED_TOOL_COUNT_METRIC, - i64::try_from(snapshot_metrics.tool_count).unwrap_or(i64::MAX), - &[("path", "new")], - ); - if let Some(snapshot_age) = snapshot_metrics.age { - let _ = metrics.record_duration( - APPS_SNAPSHOT_AGE_METRIC, - snapshot_age, - &[("path", "new"), ("observation", "installed")], - ); - } -} diff --git a/codex-rs/app-server/src/request_processors/apps_processor/installed_tests.rs b/codex-rs/app-server/src/request_processors/apps_processor/installed_tests.rs deleted file mode 100644 index 94f106fc..00000000 --- a/codex-rs/app-server/src/request_processors/apps_processor/installed_tests.rs +++ /dev/null @@ -1,149 +0,0 @@ -use super::APPS_INSTALLED_DURATION_METRIC; -use super::AppsInstalledSnapshotMetrics; -use super::record_apps_installed_metrics; -use anyhow::Result; -use codex_app_server_protocol::AppsInstalledResponse; -use codex_otel::MetricsClient; -use codex_otel::MetricsConfig; -use opentelemetry_sdk::metrics::InMemoryMetricExporter; -use opentelemetry_sdk::metrics::data::AggregatedMetrics; -use opentelemetry_sdk::metrics::data::MetricData; -use opentelemetry_sdk::metrics::data::ScopeMetrics; -use pretty_assertions::assert_eq; -use std::collections::BTreeMap; -use std::time::Instant; - -fn test_metrics() -> Result { - Ok(MetricsClient::new( - MetricsConfig::in_memory( - "test", - "codex-app-server", - env!("CARGO_PKG_VERSION"), - InMemoryMetricExporter::default(), - ) - .with_runtime_reader(), - )?) -} - -#[test] -fn installed_duration_records_one_sample_per_success_with_legacy_comparison_dimensions() --> Result<()> { - let metrics = test_metrics()?; - let response = AppsInstalledResponse { apps: Vec::new() }; - - record_apps_installed_metrics( - &metrics, - Instant::now(), - /*force_refresh*/ false, - /*retained_previous_snapshot*/ false, - "not_requested", - AppsInstalledSnapshotMetrics { - age: None, - tool_count: 0, - }, - Some(&response), - ); - record_apps_installed_metrics( - &metrics, - Instant::now(), - /*force_refresh*/ true, - /*retained_previous_snapshot*/ false, - "success", - AppsInstalledSnapshotMetrics { - age: None, - tool_count: 0, - }, - Some(&response), - ); - - let snapshot = metrics.snapshot()?; - let metric = snapshot - .scope_metrics() - .flat_map(ScopeMetrics::metrics) - .find(|metric| metric.name() == APPS_INSTALLED_DURATION_METRIC) - .expect("installed duration metric should be recorded"); - let mut points = match metric.data() { - AggregatedMetrics::F64(MetricData::Histogram(histogram)) => histogram - .data_points() - .map(|point| { - let attributes = point - .attributes() - .map(|attribute| { - ( - attribute.key.as_str().to_string(), - attribute.value.as_str().to_string(), - ) - }) - .collect::>(); - (attributes, point.count()) - }) - .collect::>(), - _ => panic!("installed duration should be a floating-point histogram"), - }; - points.sort_by(|(left, _), (right, _)| left.cmp(right)); - - assert_eq!( - points, - vec![ - ( - BTreeMap::from([ - ("force_refresh".to_string(), "false".to_string()), - ("outcome".to_string(), "success".to_string()), - ("path".to_string(), "installed".to_string()), - ("refresh".to_string(), "not_requested".to_string()), - ("reload".to_string(), "false".to_string()), - ( - "retained_previous_snapshot".to_string(), - "false".to_string() - ), - ]), - 1, - ), - ( - BTreeMap::from([ - ("force_refresh".to_string(), "true".to_string()), - ("outcome".to_string(), "success".to_string()), - ("path".to_string(), "installed".to_string()), - ("refresh".to_string(), "success".to_string()), - ("reload".to_string(), "true".to_string()), - ( - "retained_previous_snapshot".to_string(), - "false".to_string() - ), - ]), - 1, - ), - ] - ); - - Ok(()) -} - -#[test] -fn installed_duration_does_not_record_failed_requests() -> Result<()> { - let metrics = test_metrics()?; - - record_apps_installed_metrics( - &metrics, - Instant::now(), - /*force_refresh*/ true, - /*retained_previous_snapshot*/ true, - "error", - AppsInstalledSnapshotMetrics { - age: None, - tool_count: 0, - }, - /*response*/ None, - ); - - let snapshot = metrics.snapshot()?; - assert!( - snapshot - .scope_metrics() - .flat_map(ScopeMetrics::metrics) - .all(|metric| metric.name() != APPS_INSTALLED_DURATION_METRIC), - "failed installed requests must not record a successful duration sample", - ); - - Ok(()) -} diff --git a/codex-rs/app-server/src/request_processors/apps_processor/read.rs b/codex-rs/app-server/src/request_processors/apps_processor/read.rs deleted file mode 100644 index 4348613f..00000000 --- a/codex-rs/app-server/src/request_processors/apps_processor/read.rs +++ /dev/null @@ -1,108 +0,0 @@ -use super::*; -use crate::app_info::connector_metadata_to_api; - -pub(in crate::request_processors) const APP_READ_MAX_IDS: usize = 100; -const APPS_READ_DURATION_METRIC: &str = "codex.apps.read.duration_ms"; - -impl AppsRequestProcessor { - pub(crate) async fn apps_read( - &self, - params: AppsReadParams, - ) -> Result, JSONRPCErrorError> { - let started_at = Instant::now(); - let AppsReadParams { - app_ids, - thread_id, - include_tools, - } = params; - if app_ids.len() > APP_READ_MAX_IDS { - return Err(invalid_params(format!( - "app/read accepts at most {APP_READ_MAX_IDS} appIds" - ))); - } - - let mut seen_app_ids = HashSet::new(); - let app_ids = app_ids - .into_iter() - .filter(|app_id| seen_app_ids.insert(app_id.clone())) - .collect::>(); - let (mut config, mcp_manager) = self.load_apps_config(thread_id.as_deref()).await?; - let auth = match mcp_manager - .auth_manager() - .auth_with_http_client_factory() - .await - { - Some((auth, factory)) => { - config.application_network_policy = factory.network_policy().clone(); - Some(auth) - } - None => None, - }; - let runtime = self - .thread_manager - .runtime_auth_for_mcp_manager(&config, &mcp_manager) - .map_err(|error| internal_error(error.to_string()))?; - if !config - .features - .apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)) - { - let response = AppsReadResponse { - apps: Vec::new(), - missing_app_ids: app_ids, - }; - record_apps_read_duration(started_at, include_tools); - return Ok(Some(response.into())); - } - let auth = auth - .as_ref() - .ok_or_else(|| internal_error("app/read requires ChatGPT auth".to_string()))?; - - let connectors::ConnectorMetadataReadResult { - apps, - missing_app_ids, - } = connectors::read_connector_metadata( - &config, - auth, - runtime.as_ref(), - &app_ids, - include_tools, - ) - .await - .map_err(|err| internal_error(format!("failed to read app metadata: {err}")))?; - let loaded_plugins = mcp_manager - .plugins_manager() - .plugins_for_config(&config.plugins_config_input()) - .await; - let connector_snapshot = - codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries( - loaded_plugins.capability_summaries(), - ); - let apps = apps - .into_iter() - .map(|metadata| { - let mut app = connector_metadata_to_api(metadata); - app.plugin_display_names = connector_snapshot - .plugin_display_names_for_connector_id(app.id.as_str()) - .to_vec(); - app - }) - .collect(); - let response = AppsReadResponse { - apps, - missing_app_ids, - }; - record_apps_read_duration(started_at, include_tools); - Ok(Some(response.into())) - } -} - -fn record_apps_read_duration(started_at: Instant, include_tools: bool) { - let include_tools = if include_tools { "true" } else { "false" }; - if let Some(metrics) = codex_otel::global() { - let _ = metrics.record_duration( - APPS_READ_DURATION_METRIC, - started_at.elapsed(), - &[("include_tools", include_tools)], - ); - } -} diff --git a/codex-rs/app-server/src/request_processors/plugins.rs b/codex-rs/app-server/src/request_processors/plugins.rs index 141b8cc5..f6ee4327 100644 --- a/codex-rs/app-server/src/request_processors/plugins.rs +++ b/codex-rs/app-server/src/request_processors/plugins.rs @@ -1,8 +1,8 @@ -use super::apps_processor::APP_READ_MAX_IDS; use super::config_processor::reload_user_config; use super::*; use crate::error_code::internal_error; use crate::error_code::invalid_request; +use crate::error_code::method_not_found; use codex_analytics::PluginInstallSource; use codex_app_server_protocol::PluginAvailability; use codex_app_server_protocol::PluginSharePrincipalRole; @@ -1831,78 +1831,15 @@ impl PluginRequestProcessor { ); } + /// ChatGPT apps never need auth in aKode: the hosted apps MCP server is never used. async fn plugin_apps_needing_auth_for_install( &self, - config: &Config, - auth: Option<&CodexAuth>, - plugin_id: &str, - plugin_app_declarations: &[codex_plugin::AppDeclaration], + _config: &Config, + _auth: Option<&CodexAuth>, + _plugin_id: &str, + _plugin_app_declarations: &[codex_plugin::AppDeclaration], ) -> Vec { - if plugin_app_declarations.is_empty() - || !config - .features - .apps_enabled_for_auth(auth.is_some_and(CodexAuth::is_chatgpt_auth)) - { - return Vec::new(); - } - - let plugin_apps = - codex_plugin::app_connector_ids_from_declarations(plugin_app_declarations); - let app_category_by_id = plugin_app_declarations - .iter() - .filter_map(|app| { - app.category - .as_ref() - .map(|category| (app.connector_id.0.clone(), category.clone())) - }) - .collect(); - let environment_manager = self.thread_manager.environment_manager(); - let (app_summaries, accessible_connectors_result) = tokio::join!( - load_plugin_app_summaries( - &self.thread_manager, - config, - auth, - &plugin_apps, - &app_category_by_id - ), - connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager( - config, - /*force_refetch*/ true, - Arc::clone(&environment_manager), - self.thread_manager.mcp_manager(), - ), - ); - - let (accessible_connectors, codex_apps_ready) = match accessible_connectors_result { - Ok(status) => (status.connectors, status.codex_apps_ready), - Err(err) => { - warn!( - plugin = plugin_id, - "failed to load accessible apps after plugin install: {err:#}" - ); - ( - connectors::list_cached_accessible_connectors_from_mcp_tools(config, auth) - .unwrap_or_default(), - false, - ) - } - }; - if !codex_apps_ready { - warn!( - plugin = plugin_id, - "codex_apps MCP not ready after plugin install; skipping appsNeedingAuth check" - ); - return Vec::new(); - } - - let accessible_ids = accessible_connectors - .iter() - .map(|connector| connector.id.as_str()) - .collect::>(); - app_summaries - .into_iter() - .filter(|app| !accessible_ids.contains(app.id.as_str())) - .collect() + Vec::new() } async fn start_plugin_mcp_oauth_logins( @@ -2182,79 +2119,25 @@ impl PluginRequestProcessor { } } +/// Summarizes plugin app declarations locally; aKode never fetches ChatGPT app metadata. async fn load_plugin_app_summaries( - thread_manager: &ThreadManager, - config: &Config, - auth: Option<&CodexAuth>, + _thread_manager: &ThreadManager, + _config: &Config, + _auth: Option<&CodexAuth>, plugin_apps: &[codex_plugin::AppConnectorId], app_category_by_id: &HashMap, ) -> Vec { let mut seen_app_ids = HashSet::new(); - let app_ids = plugin_apps + plugin_apps .iter() .map(|app| app.0.clone()) .filter(|app_id| seen_app_ids.insert(app_id.clone())) - .collect::>(); - let mut metadata_by_id = HashMap::new(); - if let Some(auth) = auth.filter(|auth| { - config - .features - .apps_enabled_for_auth(auth.uses_codex_backend()) - }) { - metadata_by_id.extend( - codex_connectors::ConnectorMetadataStore::new( - config.chatgpt_base_url.clone(), - auth.get_account_id(), - auth.get_chatgpt_user_id(), - auth.is_workspace_account(), - ) - .fresh_records(&app_ids, /*include_tools*/ false), - ); - let runtime = thread_manager.runtime_auth_for_config(config); - for app_ids in app_ids.chunks(APP_READ_MAX_IDS) { - let runtime = match &runtime { - Ok(runtime) => runtime.as_ref(), - Err(error) => { - warn!("failed to initialize app metadata authentication: {error}"); - break; - } - }; - match connectors::read_connector_metadata( - config, auth, runtime, app_ids, /*include_tools*/ false, - ) - .await - { - Ok(result) => metadata_by_id.extend( - result - .apps - .into_iter() - .map(|metadata| (metadata.id.clone(), metadata)), - ), - Err(err) => { - warn!("failed to load app metadata for plugin: {err:#}"); - break; - } - } - } - } - - app_ids - .into_iter() - .map(|app_id| { - let (name, description) = metadata_by_id - .remove(&app_id) - .map(|metadata| (metadata.name, metadata.description)) - .unwrap_or_else(|| (app_id.clone(), None)); - let category = app_category_by_id.get(&app_id).cloned(); - AppSummary { - install_url: Some(codex_connectors::metadata::connector_install_url( - &name, &app_id, - )), - id: app_id, - name, - description, - category, - } + .map(|app_id| AppSummary { + install_url: None, + name: app_id.clone(), + description: None, + category: app_category_by_id.get(&app_id).cloned(), + id: app_id, }) .collect() } @@ -2425,6 +2308,7 @@ fn remote_plugin_detail_to_info( fn remote_plugin_catalog_error_type(err: &RemotePluginCatalogError) -> &'static str { match err { + RemotePluginCatalogError::Unavailable => "remote_catalog_unavailable", RemotePluginCatalogError::AuthRequired => "remote_catalog_auth_required", RemotePluginCatalogError::UnsupportedAuthMode => "remote_catalog_unsupported_auth_mode", RemotePluginCatalogError::AuthToken(_) => "remote_catalog_auth_token", @@ -2459,6 +2343,7 @@ fn remote_plugin_catalog_error_type(err: &RemotePluginCatalogError) -> &'static fn remote_plugin_bundle_install_error_type(err: &RemotePluginBundleInstallError) -> &'static str { match err { + RemotePluginBundleInstallError::Unavailable => "remote_bundle_unavailable", RemotePluginBundleInstallError::MissingReleaseVersion { .. } => { "remote_bundle_missing_release_version" } @@ -2499,6 +2384,7 @@ fn remote_plugin_catalog_error_to_jsonrpc( ) -> JSONRPCErrorError { let message = format!("{context}: {err}"); match &err { + RemotePluginCatalogError::Unavailable => method_not_found(message), RemotePluginCatalogError::AuthRequired | RemotePluginCatalogError::UnsupportedAuthMode => { invalid_request(message) } diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs index b9062d6e..70c292b4 100644 --- a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs @@ -26,7 +26,6 @@ pub(super) struct ListenerTaskContext { pub(super) thread_watch_manager: ThreadWatchManager, pub(super) codex_home: PathBuf, pub(super) skills_watcher: Arc, - pub(super) turn_cost_worker: Option, } struct UnloadingState { @@ -500,7 +499,6 @@ async fn start_listener( pending_thread_unloads, thread_watch_manager, codex_home, - turn_cost_worker, .. } = listener_task_context; let outgoing_for_task = Arc::clone(&outgoing); @@ -538,15 +536,6 @@ async fn start_listener( } }; - if let Some(worker) = &turn_cost_worker { - worker.observe_event( - conversation_id, - config.as_ref(), - &event, - || conversation.session_telemetry(), - ); - } - // Track the event before emitting any typed translations // so thread-local state such as raw event opt-in stays // synchronized with the conversation. @@ -751,7 +740,6 @@ async fn start_listener( drop(conversation); drop(config); drop(thread_manager); - drop(turn_cost_worker); if shutdown_complete { drained_tx.send_replace(true); diff --git a/codex-rs/app-server/src/request_processors/thread_listener_shutdown_tests.rs b/codex-rs/app-server/src/request_processors/thread_listener_shutdown_tests.rs index bbb872b3..116a0adc 100644 --- a/codex-rs/app-server/src/request_processors/thread_listener_shutdown_tests.rs +++ b/codex-rs/app-server/src/request_processors/thread_listener_shutdown_tests.rs @@ -90,7 +90,6 @@ async fn listener_shutdown_releases_runtime_and_preserves_other_subscribers( /*state_db*/ None, /*log_db*/ None, skills_watcher.clone(), - /*turn_cost_worker*/ None, Vec::new(), Arc::new(SampleResponseRegistry::default()), ); diff --git a/codex-rs/app-server/src/request_processors/thread_processor.rs b/codex-rs/app-server/src/request_processors/thread_processor.rs index 130bb85a..ce6eb92f 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor.rs @@ -518,7 +518,6 @@ pub(crate) struct ThreadRequestProcessor { pub(super) background_tasks: TaskTracker, pub(super) sample_responses: Arc, pub(super) skills_watcher: Arc, - pub(super) turn_cost_worker: Option, pub(super) initial_config_warnings: Arc>, } @@ -557,7 +556,6 @@ impl ThreadRequestProcessor { state_db: Option, log_db: Option, skills_watcher: Arc, - turn_cost_worker: Option, initial_config_warnings: Vec, sample_responses: Arc, ) -> Self { @@ -579,7 +577,6 @@ impl ThreadRequestProcessor { background_tasks: TaskTracker::new(), sample_responses, skills_watcher, - turn_cost_worker, initial_config_warnings: Arc::new(initial_config_warnings), } } @@ -1231,7 +1228,6 @@ impl ThreadRequestProcessor { thread_watch_manager: self.thread_watch_manager.clone(), codex_home: self.config.codex_home.to_path_buf(), skills_watcher: Arc::clone(&self.skills_watcher), - turn_cost_worker: self.turn_cost_worker.clone(), } } @@ -1361,7 +1357,6 @@ impl ThreadRequestProcessor { thread_watch_manager: self.thread_watch_manager.clone(), codex_home: self.config.codex_home.to_path_buf(), skills_watcher: Arc::clone(&self.skills_watcher), - turn_cost_worker: self.turn_cost_worker.clone(), }; let request_trace = request_context.request_trace(); let config_manager = self.config_manager.clone(); diff --git a/codex-rs/app-server/src/request_processors/turn_processor.rs b/codex-rs/app-server/src/request_processors/turn_processor.rs index 8fc7afa9..8967cafd 100644 --- a/codex-rs/app-server/src/request_processors/turn_processor.rs +++ b/codex-rs/app-server/src/request_processors/turn_processor.rs @@ -89,7 +89,6 @@ pub(crate) struct TurnRequestProcessor { thread_state_manager: ThreadStateManager, thread_watch_manager: ThreadWatchManager, skills_watcher: Arc, - turn_cost_worker: Option, } fn map_additional_context( @@ -147,7 +146,6 @@ impl TurnRequestProcessor { thread_state_manager: ThreadStateManager, thread_watch_manager: ThreadWatchManager, skills_watcher: Arc, - turn_cost_worker: Option, ) -> Self { Self { thread_manager, @@ -159,7 +157,6 @@ impl TurnRequestProcessor { thread_state_manager, thread_watch_manager, skills_watcher, - turn_cost_worker, } } @@ -1543,7 +1540,6 @@ impl TurnRequestProcessor { thread_watch_manager: self.thread_watch_manager.clone(), codex_home: self.config.codex_home.to_path_buf(), skills_watcher: Arc::clone(&self.skills_watcher), - turn_cost_worker: self.turn_cost_worker.clone(), } } diff --git a/codex-rs/app-server/src/turn_cost_worker.rs b/codex-rs/app-server/src/turn_cost_worker.rs deleted file mode 100644 index cdbaeae9..00000000 --- a/codex-rs/app-server/src/turn_cost_worker.rs +++ /dev/null @@ -1,555 +0,0 @@ -use codex_backend_client::ApiKeyTurnCost; -use codex_backend_client::ApiKeyTurnCostStatus; -use codex_backend_client::Client as BackendClient; -use codex_backend_client::RequestError; -use codex_config::types::OtelExporterKind; -use codex_core::config::Config; -use codex_features::RuntimeAuthMode; -use codex_login::AuthManager; -use codex_model_provider::SharedModelProvider; -use codex_otel::SessionTelemetry; -use codex_protocol::ThreadId; -use codex_protocol::auth::AuthMode; -use codex_protocol::protocol::Event; -use codex_protocol::protocol::EventMsg; -use codex_runtime_agent_instance::RuntimeAuthManager; -use std::collections::HashMap; -use std::collections::HashSet; -use std::sync::Arc; -use std::time::Duration; -use std::time::Instant; -use tokio::sync::mpsc; -use tokio::task::JoinHandle; -use tokio_util::sync::CancellationToken; -use tracing::warn; - -const POLL_INTERVAL: Duration = Duration::from_secs(150); -const REQUEST_TIMEOUT: Duration = Duration::from_secs(15); -const OBSERVATION_CHANNEL_CAPACITY: usize = 16_384; -const MAX_TRACKED_TURNS: usize = 4_096; -const MAX_QUERY_TURNS: usize = 100; -const MAX_TRACKED_RESPONSES_PER_TURN: usize = 4_096; -const MAX_STALLED_POLL_ATTEMPTS: u8 = 5; - -pub(crate) struct TurnCostWorker { - handle: TurnCostWorkerHandle, - shutdown: CancellationToken, - _task: JoinHandle<()>, -} - -#[derive(Clone)] -pub(crate) struct TurnCostWorkerHandle { - sender: mpsc::Sender, - backend: TurnCostBackend, - config: Arc, -} - -enum TurnCostObservationKind { - Started { - session_telemetry: Box, - }, - ResponseCompleted { - response_id: String, - }, - Finished { - interrupted: bool, - }, -} - -struct TurnCostObservation { - thread_id: ThreadId, - turn_id: String, - kind: TurnCostObservationKind, -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum TurnCostStatus { - Running, - Completed, - Interrupted, -} - -struct TurnCostEntry { - thread_id: ThreadId, - session_telemetry: SessionTelemetry, - expected_response_ids: HashSet, - status: TurnCostStatus, - next_poll_at: Instant, - attempt_count: u8, -} - -struct WorkerRuntime { - config: Arc, - backend: TurnCostBackend, - turns: HashMap, - runtime_auth: Option<(Arc, RuntimeAuthMode)>, -} - -#[derive(Clone)] -enum TurnCostBackend { - OpenAi(Arc), - ModelProvider(SharedModelProvider), -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum BackendAvailability { - AwaitingAuthChange, - RetryProbe, - Ready, - Disabled, -} - -impl TurnCostWorker { - pub(crate) fn spawn( - config: Arc, - auth_manager: Arc, - runtime_auth: Option<(Arc, RuntimeAuthMode)>, - ) -> Option { - let has_otel_log_exporter = matches!( - config.otel.exporter, - OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. } - ); - let has_otel_metrics_exporter = matches!( - config.otel.metrics_exporter, - OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. } - ); - if !(has_otel_log_exporter || has_otel_metrics_exporter) - || config.model_provider.is_amazon_bedrock() - { - return None; - } - let is_openai = config.model_provider.is_openai(); - let backend = if is_openai { - TurnCostBackend::OpenAi(Arc::clone(&auth_manager)) - } else { - TurnCostBackend::ModelProvider( - codex_model_provider::ProviderAuthContext { - credentials: Arc::clone(&auth_manager), - runtime_auth: runtime_auth.clone(), - } - .model_provider(config.model_provider.clone()), - ) - }; - let (sender, receiver) = mpsc::channel(OBSERVATION_CHANNEL_CAPACITY); - let shutdown = CancellationToken::new(); - let runtime = WorkerRuntime { - config: Arc::clone(&config), - backend: backend.clone(), - turns: HashMap::new(), - runtime_auth, - }; - let worker_shutdown = shutdown.clone(); - let task = tokio::spawn(async move { - runtime.run(receiver, worker_shutdown).await; - }); - Some(Self { - handle: TurnCostWorkerHandle { - sender, - backend, - config, - }, - shutdown, - _task: task, - }) - } - - pub(crate) fn handle(&self) -> TurnCostWorkerHandle { - self.handle.clone() - } - - pub(crate) fn shutdown(&self) { - self.shutdown.cancel(); - } -} - -impl Drop for TurnCostWorker { - fn drop(&mut self) { - self.shutdown(); - } -} - -impl TurnCostWorkerHandle { - pub(crate) fn observe_event( - &self, - thread_id: ThreadId, - thread_config: &Config, - event: &Event, - session_telemetry: impl FnOnce() -> SessionTelemetry, - ) { - if thread_config.model_provider != self.config.model_provider { - return; - } - if let TurnCostBackend::OpenAi(auth_manager) = &self.backend { - let Some(auth) = auth_manager.auth_cached() else { - return; - }; - if !auth.is_api_key_auth() && !auth.is_chatgpt_auth() { - return; - } - } - let kind = match &event.msg { - EventMsg::TurnStarted(_) => TurnCostObservationKind::Started { - session_telemetry: Box::new(session_telemetry()), - }, - EventMsg::RawResponseCompleted(event) => TurnCostObservationKind::ResponseCompleted { - response_id: event.response_id.clone(), - }, - EventMsg::TurnComplete(_) => TurnCostObservationKind::Finished { interrupted: false }, - EventMsg::TurnAborted(_) => TurnCostObservationKind::Finished { interrupted: true }, - _ => return, - }; - let _ = self.sender.try_send(TurnCostObservation { - thread_id, - turn_id: event.id.clone(), - kind, - }); - } -} - -impl WorkerRuntime { - async fn run(self, receiver: mpsc::Receiver, shutdown: CancellationToken) { - let auth_changes = match &self.backend { - TurnCostBackend::OpenAi(auth_manager) => Some(auth_manager.auth_change_receiver()), - TurnCostBackend::ModelProvider(_) => None, - }; - let backend_availability = self.probe_backend().await; - self.run_with_backend_availability(receiver, shutdown, auth_changes, backend_availability) - .await; - } - - async fn run_with_backend_availability( - mut self, - mut receiver: mpsc::Receiver, - shutdown: CancellationToken, - mut auth_changes: Option>, - mut backend_availability: BackendAvailability, - ) { - let mut ticker = tokio::time::interval(POLL_INTERVAL); - ticker.tick().await; - loop { - tokio::select! { - biased; - _ = shutdown.cancelled() => break, - changed = async { - match auth_changes.as_mut() { - Some(auth_changes) => auth_changes.changed().await, - None => std::future::pending().await, - } - } => { - if changed.is_err() { - break; - } - // Cost telemetry is best effort: auth changes may drop pending turns. - // Callers can query the cost API directly to reconcile missing telemetry. - self.turns.clear(); - while receiver.try_recv().is_ok() {} - backend_availability = self.probe_backend().await; - } - observation = receiver.recv() => { - let Some(observation) = observation else { - break; - }; - if !matches!( - backend_availability, - BackendAvailability::Ready | BackendAvailability::RetryProbe - ) { - continue; - } - self.record_observation(observation); - } - _ = ticker.tick() => { - match backend_availability { - BackendAvailability::Ready => self.poll_due().await, - BackendAvailability::RetryProbe => { - backend_availability = self.probe_backend().await; - } - BackendAvailability::AwaitingAuthChange - | BackendAvailability::Disabled => {} - } - } - } - } - } - - async fn probe_backend(&self) -> BackendAvailability { - let probe_turn_ids = [uuid::Uuid::new_v4().to_string()]; - match tokio::time::timeout(REQUEST_TIMEOUT, self.query_turn_costs(&probe_turn_ids)).await { - Ok(Ok(Some(_))) => BackendAvailability::Ready, - Ok(Ok(None)) => match self.backend { - TurnCostBackend::OpenAi(_) => BackendAvailability::AwaitingAuthChange, - TurnCostBackend::ModelProvider(_) => BackendAvailability::Disabled, - }, - Ok(Err(error)) => match error.status().map(|status| status.as_u16()) { - Some(401 | 403) if matches!(self.backend, TurnCostBackend::OpenAi(_)) => { - tracing::debug!( - status = error.status().map(|status| status.as_u16()), - "turn cost worker waiting for auth change after backend availability check" - ); - BackendAvailability::AwaitingAuthChange - } - Some(401 | 403 | 429) => BackendAvailability::RetryProbe, - Some(400..=499) => { - tracing::debug!( - status = error.status().map(|status| status.as_u16()), - "turn cost worker disabled by backend availability check" - ); - BackendAvailability::Disabled - } - _ => { - tracing::debug!( - status = error.status().map(|status| status.as_u16()), - "turn cost worker backend availability check failed temporarily" - ); - BackendAvailability::RetryProbe - } - }, - Err(_) => { - tracing::debug!( - "turn cost worker backend availability check timed out; will retry" - ); - BackendAvailability::RetryProbe - } - } - } - - fn record_observation(&mut self, observation: TurnCostObservation) { - match observation.kind { - TurnCostObservationKind::Started { session_telemetry } => { - if self.turns.len() < MAX_TRACKED_TURNS { - self.turns - .entry(observation.turn_id) - .or_insert(TurnCostEntry { - thread_id: observation.thread_id, - session_telemetry: *session_telemetry, - expected_response_ids: HashSet::new(), - status: TurnCostStatus::Running, - next_poll_at: Instant::now(), - attempt_count: 0, - }); - } - } - TurnCostObservationKind::ResponseCompleted { response_id } => { - if let Some(entry) = self.turns.get_mut(&observation.turn_id) - && entry.status == TurnCostStatus::Running - { - if entry.expected_response_ids.len() >= MAX_TRACKED_RESPONSES_PER_TURN { - self.turns.remove(&observation.turn_id); - return; - } - entry.expected_response_ids.insert(response_id); - } - } - TurnCostObservationKind::Finished { interrupted } => { - let Some(entry) = self.turns.get_mut(&observation.turn_id) else { - return; - }; - if entry.status != TurnCostStatus::Running { - return; - } - entry.status = if interrupted { - TurnCostStatus::Interrupted - } else { - TurnCostStatus::Completed - }; - entry.next_poll_at = Instant::now(); - } - } - } - - async fn poll_due(&mut self) { - let now = Instant::now(); - let due_turn_ids: Vec = self - .turns - .iter() - .filter(|(_, entry)| { - entry.status != TurnCostStatus::Running && entry.next_poll_at <= now - }) - .take(MAX_QUERY_TURNS) - .map(|(turn_id, _)| turn_id.clone()) - .collect(); - if !due_turn_ids.is_empty() { - self.poll_entries(&due_turn_ids).await; - } - } - - async fn poll_entries(&mut self, turn_ids: &[String]) { - let costs = - match tokio::time::timeout(REQUEST_TIMEOUT, self.query_turn_costs(turn_ids)).await { - Ok(Ok(Some(costs))) => costs, - Ok(Ok(None)) => return, - Ok(Err(error)) => { - warn!( - status = error.status().map(|status| status.as_u16()), - "failed to query turn costs" - ); - self.retry_entries(turn_ids); - return; - } - Err(_) => { - warn!("timed out querying turn costs"); - self.retry_entries(turn_ids); - return; - } - }; - let costs_by_turn: HashMap = costs - .into_iter() - .map(|cost| (cost.turn_id.clone(), cost)) - .collect(); - for turn_id in turn_ids { - let Some(cost) = costs_by_turn.get(turn_id) else { - self.retry_entry(turn_id); - continue; - }; - self.process_turn_cost(turn_id, cost); - } - } - - async fn query_turn_costs( - &self, - turn_ids: &[String], - ) -> Result>, RequestError> { - match &self.backend { - TurnCostBackend::OpenAi(auth_manager) => { - let Some((auth, captured_factory)) = - auth_manager.auth_with_http_client_factory().await - else { - return Ok(None); - }; - let http_client_factory = self - .config - .http_client_factory() - .with_network_policy(captured_factory.network_policy().clone()); - if auth.is_chatgpt_auth() { - return self - .query_chatgpt_turn_costs(&auth, http_client_factory, turn_ids) - .await - .map(Some); - } - if !auth.is_api_key_auth() { - return Ok(None); - } - let provider = self - .config - .model_provider - .to_api_provider(Some(AuthMode::ApiKey)) - .map_err(|error| RequestError::Other(error.into()))?; - let client = BackendClient::from_auth_with_runtime( - self.config.chatgpt_backend_url().resolve(&auth), - &auth, - http_client_factory, - self.runtime_auth.as_ref(), - &provider.headers, - ) - .await - .map_err(RequestError::Other)?; - client - .query_api_key_turn_costs(turn_ids, &provider.headers) - .await - .map(Some) - } - TurnCostBackend::ModelProvider(model_provider) => { - let http_client_factory = self.config.http_client_factory().with_network_policy( - self.config - .application_network_policy - .clone() - .for_current_account(), - ); - if model_provider.info().requires_openai_auth { - let Some(auth) = model_provider.auth().await else { - return Ok(None); - }; - if !auth.is_api_key_auth() { - return Ok(None); - } - } - let resolved = codex_model_provider::resolve_request( - model_provider.as_ref(), - /*scope*/ None, - /*routing*/ None, - http_client_factory, - ) - .await - .map_err(|error| RequestError::Other(error.into()))?; - let provider = resolved.api_provider; - let endpoint = provider.url_for_path("analytics/codex/turn-costs"); - let client = - BackendClient::new(provider.base_url.clone(), resolved.http_client_factory) - .with_auth_provider(resolved.api_auth) - .map_err(RequestError::Other)?; - client - .query_api_key_turn_costs_at(&endpoint, turn_ids, &provider.headers) - .await - .map(Some) - } - } - } - - fn process_turn_cost(&mut self, turn_id: &str, cost: &ApiKeyTurnCost) { - if cost.status != ApiKeyTurnCostStatus::Priced { - self.retry_entry(turn_id); - return; - } - let response_count = cost - .responses - .as_ref() - .map(|responses| responses.len() as u64) - .or(cost.event_count); - let (Some(total_usd), Some(response_count)) = (cost.total_usd.as_deref(), response_count) - else { - self.retry_entry(turn_id); - return; - }; - let Some(entry) = self.turns.get(turn_id) else { - return; - }; - if response_count < entry.expected_response_ids.len() as u64 { - self.retry_entry(turn_id); - return; - } - let mut session_telemetry = entry.session_telemetry.clone(); - if let Some(model) = cost.model.as_deref() { - session_telemetry = session_telemetry.with_model(model, model); - } - let Some(entry) = self.turns.remove(turn_id) else { - return; - }; - session_telemetry.record_turn_cost( - turn_id, - total_usd, - entry.status == TurnCostStatus::Interrupted, - cost.speed.as_deref(), - cost.reasoning_effort.as_deref(), - ); - } - - fn retry_entries(&mut self, turn_ids: &[String]) { - for turn_id in turn_ids { - self.retry_entry(turn_id); - } - } - - fn retry_entry(&mut self, turn_id: &str) { - let Some(entry) = self.turns.get_mut(turn_id) else { - return; - }; - entry.attempt_count = entry.attempt_count.saturating_add(1); - if entry.attempt_count >= MAX_STALLED_POLL_ATTEMPTS { - warn!( - thread_id = %entry.thread_id, - turn_id, - attempts = MAX_STALLED_POLL_ATTEMPTS, - "dropping turn cost event after repeated unsuccessful polls" - ); - self.turns.remove(turn_id); - return; - } - entry.next_poll_at = Instant::now() + POLL_INTERVAL; - } -} - -#[path = "turn_cost_worker_chatgpt.rs"] -mod chatgpt; - -#[cfg(test)] -#[path = "turn_cost_worker_tests.rs"] -mod tests; diff --git a/codex-rs/app-server/src/turn_cost_worker_chatgpt.rs b/codex-rs/app-server/src/turn_cost_worker_chatgpt.rs deleted file mode 100644 index b79fe314..00000000 --- a/codex-rs/app-server/src/turn_cost_worker_chatgpt.rs +++ /dev/null @@ -1,86 +0,0 @@ -//! Adapts workspace-visible SiWC estimates to the shared turn-cost emission path. -//! Emit only nonnegative, visible amounts covering every observed completed response; -//! missing amounts/settlement data must never be interpreted as a zero-cost turn. - -use super::ApiKeyTurnCost; -use super::ApiKeyTurnCostStatus; -use super::BackendClient; -use super::RequestError; -use super::WorkerRuntime; -use codex_login::CodexAuth; -use std::collections::BTreeMap; - -impl WorkerRuntime { - pub(super) async fn query_chatgpt_turn_costs( - &self, - auth: &CodexAuth, - http_client_factory: codex_http_client::HttpClientFactory, - turn_ids: &[String], - ) -> Result, RequestError> { - let mut threads: BTreeMap> = BTreeMap::new(); - for turn_id in turn_ids { - // Availability probes use an untracked, random thread/turn pair. - let thread_id = self - .turns - .get(turn_id) - .map(|entry| entry.thread_id) - .unwrap_or_default(); - threads - .entry(thread_id.to_string()) - .or_default() - .push(turn_id.clone()); - } - let client = BackendClient::from_auth_with_runtime( - self.config.chatgpt_base_url.clone(), - auth, - http_client_factory, - self.runtime_auth.as_ref(), - /*headers*/ &Default::default(), - ) - .await - .map_err(RequestError::Other)?; - let costs = client.query_chatgpt_turn_costs(&threads).await?; - let mut settled_costs = Vec::new(); - for thread in costs { - let Some(requested_turns) = threads.get(&thread.thread_id) else { - continue; - }; - for cost in thread.turns { - if !requested_turns.contains(&cost.turn_id) { - continue; - } - let Some(entry) = self.turns.get(&cost.turn_id) else { - continue; - }; - let (Some(micros), Some(settled_ids)) = - (cost.estimated_usage_usd_micros, cost.settled_response_ids) - else { - continue; - }; - // Missing/hidden dollars are not zero. A projection can appear before - // all responses settle, so require every locally observed response. - if micros < 0 - || entry.expected_response_ids.is_empty() - || !entry - .expected_response_ids - .iter() - .all(|id| settled_ids.contains(id)) - { - continue; - } - // Reuse the existing emission path without a floating-point conversion. - settled_costs.push(ApiKeyTurnCost { - turn_id: cost.turn_id, - status: ApiKeyTurnCostStatus::Priced, - total_usd: Some(format!("{}.{:06}", micros / 1_000_000, micros % 1_000_000)), - event_count: Some(settled_ids.len() as u64), - responses: None, - model: cost.model, - speed: None, - reasoning_effort: None, - }); - } - } - Ok(settled_costs) - } -} diff --git a/codex-rs/app-server/src/turn_cost_worker_chatgpt_tests.rs b/codex-rs/app-server/src/turn_cost_worker_chatgpt_tests.rs deleted file mode 100644 index 432641be..00000000 --- a/codex-rs/app-server/src/turn_cost_worker_chatgpt_tests.rs +++ /dev/null @@ -1,73 +0,0 @@ -//! Checks unusable SiWC estimates and exact conversion; public app-server/OTLP coverage lives in turn_cost_otel. - -use super::*; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use test_case::test_case; - -#[test_case(json!(null), json!(["resp-one", "resp-two"]), None; "hidden or incomplete amount")] -#[test_case(json!(-1), json!(["resp-one", "resp-two"]), None; "negative amount")] -#[test_case(json!(1), json!(null), None; "missing settlement")] -#[test_case(json!(1), json!([]), None; "unsettled")] -#[test_case(json!(1), json!(["unrelated"]), None; "wrong response")] -#[test_case(json!(1), json!(["resp-one"]), None; "only one response settled")] -#[test_case(json!(0), json!(["resp-one", "resp-two"]), Some("0.000000"); "zero")] -#[test_case(json!(i64::MAX), json!(["resp-one", "resp-two"]), Some("9223372036854.775807"); "integer precision")] -#[tokio::test] -async fn chatgpt_cost_requires_visible_amount_and_matching_settlement( - micros: Value, - settled_ids: Value, - expected: Option<&str>, -) { - let server = MockServer::start().await; - let mut runtime = test_runtime( - &server, - AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()), - ) - .await; - let thread_id = ThreadId::new(); - runtime.turns.insert( - "turn-1".to_string(), - TurnCostEntry { - thread_id, - session_telemetry: test_session_telemetry(thread_id), - expected_response_ids: HashSet::from(["resp-one".to_string(), "resp-two".to_string()]), - status: TurnCostStatus::Completed, - next_poll_at: Instant::now(), - attempt_count: 0, - }, - ); - Mock::given(method("POST")) - .and(path("/api/codex/usage/thread-estimates/query")) - .respond_with( - ResponseTemplate::new(200).set_body_json(json!({"threads": [{ - "thread_id": thread_id, "turns": [{"turn_id": "turn-1", - "estimated_usage_usd_micros": micros, "settled_response_ids": settled_ids}] - }]})), - ) - .expect(1) - .mount(&server) - .await; - let costs = runtime - .query_turn_costs(&["turn-1".to_string()]) - .await - .expect("query") - .expect("SiWC enabled"); - assert_eq!( - costs, - expected - .map(|amount| ApiKeyTurnCost { - turn_id: "turn-1".to_string(), - status: ApiKeyTurnCostStatus::Priced, - total_usd: Some(amount.to_string()), - event_count: Some(2), - responses: None, - model: None, - speed: None, - reasoning_effort: None, - }) - .into_iter() - .collect::>() - ); -} diff --git a/codex-rs/app-server/src/turn_cost_worker_runtime_auth_tests.rs b/codex-rs/app-server/src/turn_cost_worker_runtime_auth_tests.rs deleted file mode 100644 index b95c9e8c..00000000 --- a/codex-rs/app-server/src/turn_cost_worker_runtime_auth_tests.rs +++ /dev/null @@ -1,124 +0,0 @@ -//! Exercise runtime-authenticated turn-cost requests through OpenAI and provider aliases. - -use super::*; -use codex_features::RuntimeAuthMode; -use codex_runtime_agent_instance::AgentHostAuthorization; -use codex_runtime_agent_instance::RuntimeAuthManager; -use codex_runtime_agent_instance::RuntimeRegistrationMetadata; -use codex_runtime_agent_instance::RuntimeRole; -use pretty_assertions::assert_eq; -use test_case::test_case; -use wiremock::matchers::body_partial_json; - -#[test_case(false; "default OpenAI provider")] -#[test_case(true; "OpenAI alias")] -#[tokio::test] -async fn turn_costs_register_with_requested_organization(openai_alias: bool) { - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - let server = MockServer::start().await; - let registration = if openai_alias { - ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "runtime_agent_instance_id": "runtime-telemetry", "agent_host_id": "host-a", - "actor": {"kind": "platform", "user_id": "user-a", "organization_id": "org-a", "project_id": null}, - })) - } else { - // Inspect registration without sending a request to the real OpenAI destination. - ResponseTemplate::new(403) - }; - Mock::given(path("/agent/register")) - .and(body_partial_json(serde_json::json!({ - "actor_auth": {"organization_id": "org-a"}, - }))) - .respond_with(registration) - .expect(1) - .mount(&server) - .await; - Mock::given(path(TURN_COST_PATH)) - .and(header("openai-organization", "org-a")) - .respond_with( - ResponseTemplate::new(200).set_body_json(serde_json::json!({"turns": []})), - ) - .expect(if openai_alias { 2 } else { 0 }) - .mount(&server) - .await; - let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("key-a")); - let mut worker = test_runtime(&server, credentials.clone()).await; - let owner = Arc::new(RuntimeAuthManager::new( - credentials.clone(), - AgentHostAuthorization::InstallationId { - installation_id: uuid::Uuid::nil(), - }, - RuntimeRegistrationMetadata { - harness: Some("codex".into()), - harness_version: None, - role: RuntimeRole::Orchestrator, - }, - format!("{}/agent/register", server.uri()).parse().unwrap(), - )); - let mut info = codex_model_provider_info::ModelProviderInfo::create_openai_provider(Some( - format!("{}/v1", server.uri()), - )); - info.name = "OpenAI alias".to_string(); - info.http_headers = Some(HashMap::from([( - "OpenAI-Organization".to_string(), - "org-a".into(), - )])); - if openai_alias { - worker.backend = TurnCostBackend::ModelProvider( - codex_model_provider::test_support::runtime_model_provider( - info, - credentials, - (owner, mode), - ), - ); - } else { - let config = Arc::make_mut(&mut worker.config); - config.model_provider = info; - config.chatgpt_base_url = "https://chatgpt.com".to_string(); - worker.runtime_auth = Some((owner, mode)); - worker - .query_turn_costs(&[]) - .await - .expect_err("registration denial must stop the cost request"); - server.verify().await; - continue; - } - for _ in 0..2 { - assert!( - worker - .query_turn_costs(&[]) - .await - .unwrap() - .unwrap() - .is_empty() - ); - } - let requests = server.received_requests().await.unwrap(); - let proofs: Vec<_> = requests - .iter() - .filter(|r| r.url.path() != "/agent/register") - .map(|r| { - let authorization = r.headers["authorization"].to_str().unwrap(); - match mode { - RuntimeAuthMode::DualHeader => { - assert_eq!(authorization, "Bearer key-a"); - r.headers["x-openai-agent-assertion"] - .to_str() - .unwrap() - .to_owned() - } - RuntimeAuthMode::AssertionOnly => { - assert!(!r.headers.contains_key("x-openai-agent-assertion")); - authorization - .strip_prefix("AgentAssertion ") - .unwrap() - .to_owned() - } - } - }) - .collect(); - assert_eq!(proofs.len(), 2); - assert_eq!(proofs.iter().collect::>().len(), 2); - server.verify().await; - } -} diff --git a/codex-rs/app-server/src/turn_cost_worker_tests.rs b/codex-rs/app-server/src/turn_cost_worker_tests.rs deleted file mode 100644 index 6a5b4a06..00000000 --- a/codex-rs/app-server/src/turn_cost_worker_tests.rs +++ /dev/null @@ -1,507 +0,0 @@ -use super::*; -use codex_backend_client::ApiKeyResponseCost; -use codex_core::config::ConfigBuilder; -use codex_login::AuthCredentialsStoreMode; -use codex_login::AuthKeyringBackendKind; -use codex_login::CodexAuth; -use codex_login::login_with_api_key; -use codex_model_provider::create_model_provider; -use codex_model_provider_info::ModelProviderInfo; -use codex_otel::TelemetryAuthMode; -use codex_protocol::protocol::SessionSource; -use codex_protocol::protocol::TurnStartedEvent; -use pretty_assertions::assert_eq; -use tempfile::TempDir; -use test_case::test_case; -use tokio::time::timeout; -use tracing::instrument::WithSubscriber; -use tracing_subscriber::layer::SubscriberExt; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; - -const TURN_COST_PATH: &str = "/v1/analytics/codex/turn-costs"; - -#[path = "turn_cost_worker_chatgpt_tests.rs"] -mod chatgpt; - -#[tokio::test] -async fn worker_starts_with_otlp_metrics_exporter_without_log_exporter() { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path(TURN_COST_PATH)) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "turns": [] - }))) - .expect(1) - .mount(&server) - .await; - let codex_home = TempDir::new().expect("temporary Codex home"); - let mut config = ConfigBuilder::default() - .codex_home(codex_home.path().to_path_buf()) - .build() - .await - .expect("test config"); - config.chatgpt_base_url = server.uri(); - config.otel.exporter = OtelExporterKind::None; - config.otel.metrics_exporter = OtelExporterKind::OtlpGrpc { - endpoint: server.uri(), - headers: HashMap::new(), - tls: None, - }; - let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test")); - - let worker = TurnCostWorker::spawn(Arc::new(config), auth_manager, /*runtime_auth*/ None) - .expect("OTLP metrics exporter should enable turn-cost collection"); - wait_for_request_count(&server, /*expected*/ 1).await; - worker.shutdown(); - server.verify().await; -} - -#[tokio::test] -async fn handle_observes_only_matching_model_provider() { - let codex_home = TempDir::new().expect("temporary Codex home"); - let mut config = ConfigBuilder::default() - .codex_home(codex_home.path().to_path_buf()) - .build() - .await - .expect("test config"); - let model_provider = ModelProviderInfo { - name: "provider-a".to_string(), - base_url: Some("https://provider-a.example/v1".to_string()), - ..Default::default() - }; - config.model_provider = model_provider.clone(); - let config = Arc::new(config); - let (sender, mut receiver) = mpsc::channel(OBSERVATION_CHANNEL_CAPACITY); - let handle = TurnCostWorkerHandle { - sender, - backend: TurnCostBackend::ModelProvider(create_model_provider( - model_provider.clone(), - /*auth_manager*/ None, - )), - config: Arc::clone(&config), - }; - let thread_id = ThreadId::new(); - let event = Event { - id: "turn-1".to_string(), - msg: EventMsg::TurnStarted(TurnStartedEvent { - turn_attribution: None, - turn_id: "turn-1".to_string(), - root_turn_id: None, - trace_id: None, - started_at: None, - model_context_window: None, - collaboration_mode_kind: Default::default(), - }), - }; - let mut mismatched_config = config.as_ref().clone(); - mismatched_config.model_provider = ModelProviderInfo { - base_url: Some("https://provider-b.example/v1".to_string()), - ..model_provider - }; - - handle.observe_event(thread_id, &mismatched_config, &event, || { - panic!("telemetry should not be captured for a mismatched provider") - }); - assert!(receiver.try_recv().is_err()); - - handle.observe_event(thread_id, config.as_ref(), &event, || { - test_session_telemetry(thread_id) - }); - let observation = receiver.recv().await.expect("matching observation"); - assert_eq!(observation.thread_id, thread_id); - assert_eq!(observation.turn_id, "turn-1"); - assert!(matches!( - observation.kind, - TurnCostObservationKind::Started { .. } - )); -} - -#[tokio::test] -async fn worker_waits_for_late_api_key_login() { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path(TURN_COST_PATH)) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "turns": [] - }))) - .expect(1) - .mount(&server) - .await; - let auth_home = TempDir::new().expect("temporary auth home"); - let auth_manager = auth_manager_at(auth_home.path()).await; - let runtime = test_runtime(&server, Arc::clone(&auth_manager)).await; - let (_sender, receiver) = mpsc::channel(OBSERVATION_CHANNEL_CAPACITY); - let shutdown = CancellationToken::new(); - let mut task = tokio::spawn(runtime.run(receiver, shutdown.clone())); - - assert!( - timeout(Duration::from_millis(/*millis*/ 50), &mut task) - .await - .is_err(), - "worker exited while waiting for login" - ); - login_with_api_key( - auth_home.path(), - "sk-test", - AuthCredentialsStoreMode::File, - AuthKeyringBackendKind::default(), - ) - .expect("write API-key auth"); - assert!(auth_manager.reload().await); - wait_for_request_count(&server, /*expected*/ 1).await; - - shutdown.cancel(); - task.await.expect("worker task"); - server.verify().await; -} - -#[tokio::test] -async fn custom_provider_auth_failure_retries_without_auth_changes() { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/analytics/codex/turn-costs")) - .and(header("authorization", "Bearer sk-old")) - .respond_with(ResponseTemplate::new(401)) - .expect(1) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/analytics/codex/turn-costs")) - .and(header("authorization", "Bearer sk-new-token")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "turns": [] - }))) - .expect(1) - .mount(&server) - .await; - - let provider_auth_home = TempDir::new().expect("temporary provider auth home"); - login_with_api_key( - provider_auth_home.path(), - "sk-old", - AuthCredentialsStoreMode::File, - AuthKeyringBackendKind::default(), - ) - .expect("write initial provider auth"); - let provider_auth_manager = auth_manager_at(provider_auth_home.path()).await; - let codex_home = TempDir::new().expect("temporary Codex home"); - let mut config = ConfigBuilder::default() - .codex_home(codex_home.path().to_path_buf()) - .build() - .await - .expect("test config"); - config.model_provider = ModelProviderInfo { - name: "custom-provider".to_string(), - base_url: Some(server.uri()), - requires_openai_auth: true, - ..Default::default() - }; - let backend = TurnCostBackend::ModelProvider(create_model_provider( - config.model_provider.clone(), - Some(Arc::clone(&provider_auth_manager)), - )); - let runtime = WorkerRuntime { - config: Arc::new(config), - backend, - turns: HashMap::new(), - runtime_auth: None, - }; - assert_eq!( - runtime.probe_backend().await, - BackendAvailability::RetryProbe - ); - login_with_api_key( - provider_auth_home.path(), - "sk-new-token", - AuthCredentialsStoreMode::File, - AuthKeyringBackendKind::default(), - ) - .expect("update provider auth"); - provider_auth_manager.reload().await; - assert_eq!(runtime.probe_backend().await, BackendAvailability::Ready); - - server.verify().await; -} - -#[tokio::test] -async fn custom_provider_does_not_send_chatgpt_auth_for_turn_costs() { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/analytics/codex/turn-costs")) - .respond_with(ResponseTemplate::new(500)) - .mount(&server) - .await; - let auth_manager = - AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()); - let codex_home = TempDir::new().expect("temporary Codex home"); - let mut config = ConfigBuilder::default() - .codex_home(codex_home.path().to_path_buf()) - .build() - .await - .expect("test config"); - config.model_provider = ModelProviderInfo { - name: "custom-provider".to_string(), - base_url: Some(server.uri()), - requires_openai_auth: true, - ..Default::default() - }; - let backend = TurnCostBackend::ModelProvider(create_model_provider( - config.model_provider.clone(), - Some(Arc::clone(&auth_manager)), - )); - let runtime = WorkerRuntime { - config: Arc::new(config), - backend, - turns: HashMap::new(), - runtime_auth: None, - }; - - assert_eq!(runtime.probe_backend().await, BackendAvailability::Disabled); - let requests = server.received_requests().await.expect("received requests"); - assert!(requests.is_empty()); -} - -#[tokio::test] -async fn transient_probe_failure_keeps_worker_alive() { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path(TURN_COST_PATH)) - .respond_with(ResponseTemplate::new(500).set_body_string("temporary failure")) - .expect(1) - .mount(&server) - .await; - let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test")); - let runtime = test_runtime(&server, Arc::clone(&auth_manager)).await; - let backend_availability = runtime.probe_backend().await; - assert_eq!(backend_availability, BackendAvailability::RetryProbe); - let (_sender, receiver) = mpsc::channel(OBSERVATION_CHANNEL_CAPACITY); - let shutdown = CancellationToken::new(); - let auth_changes = Some(auth_manager.auth_change_receiver()); - let mut task = tokio::spawn(runtime.run_with_backend_availability( - receiver, - shutdown.clone(), - auth_changes, - backend_availability, - )); - - assert!( - timeout(Duration::from_millis(/*millis*/ 50), &mut task) - .await - .is_err(), - "worker exited after a transient probe failure" - ); - - shutdown.cancel(); - task.await.expect("worker task"); - server.verify().await; -} - -#[tokio::test] -async fn priced_cost_uses_telemetry_captured_before_thread_removal() { - let server = MockServer::start().await; - let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test")); - let mut runtime = test_runtime(&server, auth_manager).await; - let thread_id = ThreadId::new(); - let turn_id = "turn-1"; - - runtime.record_observation(TurnCostObservation { - thread_id, - turn_id: turn_id.to_string(), - kind: TurnCostObservationKind::Started { - session_telemetry: Box::new(test_session_telemetry(thread_id)), - }, - }); - runtime.record_observation(TurnCostObservation { - thread_id, - turn_id: turn_id.to_string(), - kind: TurnCostObservationKind::ResponseCompleted { - response_id: "resp-one".to_string(), - }, - }); - runtime.record_observation(TurnCostObservation { - thread_id, - turn_id: turn_id.to_string(), - kind: TurnCostObservationKind::Finished { interrupted: false }, - }); - - runtime.process_turn_cost( - turn_id, - &ApiKeyTurnCost { - turn_id: turn_id.to_string(), - status: ApiKeyTurnCostStatus::Priced, - total_usd: Some("1.25".to_string()), - event_count: Some(1), - responses: None, - model: Some("gpt-5.6".to_string()), - speed: Some("fast".to_string()), - reasoning_effort: Some("high".to_string()), - }, - ); - - assert_eq!(runtime.turns.len(), 0); -} - -#[tokio::test] -async fn priced_cost_waits_for_every_response_when_response_costs_are_available() { - let server = MockServer::start().await; - let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test")); - let mut runtime = test_runtime(&server, auth_manager).await; - let thread_id = ThreadId::new(); - let turn_id = "turn-1"; - - runtime.turns.insert( - turn_id.to_string(), - TurnCostEntry { - thread_id, - session_telemetry: test_session_telemetry(thread_id), - expected_response_ids: HashSet::from(["resp-one".to_string(), "resp-two".to_string()]), - status: TurnCostStatus::Completed, - next_poll_at: Instant::now(), - attempt_count: 0, - }, - ); - - let mut cost = ApiKeyTurnCost { - turn_id: turn_id.to_string(), - status: ApiKeyTurnCostStatus::Priced, - total_usd: Some("1.25".to_string()), - event_count: Some(2), - responses: Some(vec![ApiKeyResponseCost { - response_id: "resp-one".to_string(), - total_usd: "1.25".to_string(), - }]), - model: Some("gpt-5.6".to_string()), - speed: Some("fast".to_string()), - reasoning_effort: Some("high".to_string()), - }; - runtime.process_turn_cost(turn_id, &cost); - - let entry = runtime.turns.get(turn_id).expect("turn remains tracked"); - assert_eq!(entry.attempt_count, 1); - - cost.event_count = None; - cost.responses - .as_mut() - .expect("response costs") - .push(ApiKeyResponseCost { - response_id: "resp-two".to_string(), - total_usd: "0.50".to_string(), - }); - runtime.process_turn_cost(turn_id, &cost); - - assert_eq!(runtime.turns.len(), 0); -} - -async fn test_runtime(server: &MockServer, auth_manager: Arc) -> WorkerRuntime { - let codex_home = TempDir::new().expect("temporary Codex home"); - let mut config = ConfigBuilder::default() - .codex_home(codex_home.path().to_path_buf()) - .build() - .await - .expect("test config"); - config.chatgpt_base_url = server.uri(); - let backend = TurnCostBackend::OpenAi(Arc::clone(&auth_manager)); - WorkerRuntime { - config: Arc::new(config), - backend, - turns: HashMap::new(), - runtime_auth: None, - } -} - -async fn auth_manager_at(codex_home: &std::path::Path) -> Arc { - Arc::new( - AuthManager::new( - codex_home.to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::File, - /*forced_chatgpt_workspace_id*/ None, - /*chatgpt_base_url*/ None, - AuthKeyringBackendKind::default(), - codex_login::test_support::transport_default_auth_route_config(), - ) - .await, - ) -} - -fn test_session_telemetry(thread_id: ThreadId) -> SessionTelemetry { - SessionTelemetry::new( - thread_id, - "gpt-5.6", - "gpt-5.6", - /*account_id*/ None, - /*account_email*/ None, - Some(TelemetryAuthMode::ApiKey), - "test".to_string(), - /*log_user_prompts*/ false, - "test".to_string(), - SessionSource::Cli, - ) -} - -async fn wait_for_request_count(server: &MockServer, expected: usize) { - timeout(Duration::from_secs(/*secs*/ 15), async { - loop { - let requests = server.received_requests().await.unwrap_or_default(); - if requests.len() >= expected { - break; - } - tokio::task::yield_now().await; - } - }) - .await - .expect("timed out waiting for turn-cost request"); -} - -#[test_case(500; "HTTP failure")] -#[test_case(200; "decode failure")] -#[tokio::test] -async fn turn_cost_failures_do_not_log_response_bodies(status: u16) { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path(TURN_COST_PATH)) - .respond_with( - ResponseTemplate::new(status).set_body_string("private-workspace-response-marker"), - ) - .expect(2) - .mount(&server) - .await; - let mut runtime = test_runtime( - &server, - AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test")), - ) - .await; - let capture = tempfile::NamedTempFile::new().expect("log capture"); - let subscriber = tracing_subscriber::fmt() - .with_ansi(false) - .with_max_level(tracing::Level::DEBUG) - .with_writer(Arc::new(capture.reopen().expect("log writer"))) - .finish(); - // A parallel test can first register this callsite without a subscriber. - // Keep two dispatchers alive so it cannot globally disable our log capture. - let _parallel_dispatch = tracing::Dispatch::new( - tracing_subscriber::registry().with(tracing_subscriber::filter::LevelFilter::OFF), - ); - async { - assert_eq!( - runtime.probe_backend().await, - BackendAvailability::RetryProbe - ); - runtime.poll_entries(&["turn-1".to_string()]).await; - } - .with_subscriber(subscriber) - .await; - let logs = std::fs::read_to_string(capture.path()).expect("captured logs"); - assert!(logs.contains("backend availability check failed temporarily")); - assert!(logs.contains("failed to query turn costs")); - assert!(!logs.contains("private-workspace-response-marker")); - server.verify().await; -} - -#[path = "turn_cost_worker_runtime_auth_tests.rs"] -mod runtime_auth; diff --git a/codex-rs/app-server/tests/suite/v2/app_installed.rs b/codex-rs/app-server/tests/suite/v2/app_installed.rs deleted file mode 100644 index 9ff295ae..00000000 --- a/codex-rs/app-server/tests/suite/v2/app_installed.rs +++ /dev/null @@ -1,641 +0,0 @@ -use std::collections::HashMap; -use std::path::Path; -use std::sync::Arc; -use std::sync::Mutex; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; -use std::time::Duration; - -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::MockResponsesConfig; -use app_test_support::TestAppServer; -use app_test_support::write_chatgpt_auth; -use axum::Json; -use axum::Router; -use axum::extract::State; -use axum::routing::get; -use codex_app_server_protocol::AppsInstalledParams; -use codex_app_server_protocol::AppsInstalledResponse; -use codex_app_server_protocol::AppsListParams; -use codex_app_server_protocol::AppsListResponse; -use codex_app_server_protocol::InstalledApp; -use codex_app_server_protocol::JSONRPCError; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ThreadStartParams; -use codex_app_server_protocol::ThreadStartResponse; -use codex_app_server_protocol::TurnStartParams; -use codex_app_server_protocol::TurnStatus; -use codex_app_server_protocol::UserInput; -use codex_config::types::AuthCredentialsStoreMode; -use codex_features::Feature; -use core_test_support::responses; -use pretty_assertions::assert_eq; -use rmcp::handler::server::ServerHandler; -use rmcp::model::CallToolRequestParams; -use rmcp::model::CallToolResult; -use rmcp::model::ContentBlock; -use rmcp::model::ListToolsResult; -use rmcp::model::ServerCapabilities; -use rmcp::model::ServerConfig; -use rmcp::model::Tool; -use rmcp::transport::StreamableHttpServerConfig; -use rmcp::transport::StreamableHttpService; -use rmcp::transport::streamable_http_server::session::local::LocalSessionManager; -use serde_json::json; -use tempfile::TempDir; -use tokio::net::TcpListener; -use tokio::task::JoinHandle; -use tokio::time::timeout; - -use super::app_list::connector_tool; - -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60); - -#[tokio::test] -async fn installed_apps_force_refresh_only_refreshes_tools_snapshot() -> Result<()> { - let fixture = InstalledAppsFixture::start().await?; - let codex_home = configured_codex_home(fixture.base_url())?; - let mut app_server = start_app_server(codex_home.path()).await?; - - let initially_empty = send_installed_request(&mut app_server, /*force_refresh*/ false).await?; - assert_eq!(initially_empty, AppsInstalledResponse { apps: Vec::new() }); - assert_eq!(fixture.list_tools_calls(), 0); - - let refreshed = send_installed_request(&mut app_server, /*force_refresh*/ true).await?; - assert_eq!( - refreshed.apps, - vec![ - InstalledApp { - id: "alpha".to_string(), - runtime_name: Some("Alpha Tool Name".to_string()), - enabled: true, - callable: true, - }, - InstalledApp { - id: "blocked".to_string(), - runtime_name: Some("Policy Blocked Tool Name".to_string()), - enabled: true, - callable: false, - }, - InstalledApp { - id: "disabled".to_string(), - runtime_name: Some("Locally Disabled Tool Name".to_string()), - enabled: false, - callable: false, - }, - ] - ); - assert_eq!(fixture.list_tools_calls(), 1); - - let cached = send_installed_request(&mut app_server, /*force_refresh*/ false).await?; - assert_eq!(cached, refreshed); - assert_eq!(fixture.list_tools_calls(), 1); - - fixture.set_tools(Vec::new()); - let empty = send_installed_request(&mut app_server, /*force_refresh*/ true).await?; - assert_eq!(empty, AppsInstalledResponse { apps: Vec::new() }); - assert_eq!(fixture.list_tools_calls(), 2); - - let cached_empty = send_installed_request(&mut app_server, /*force_refresh*/ false).await?; - assert_eq!(cached_empty, empty); - assert_eq!(fixture.list_tools_calls(), 2); - assert_eq!(fixture.directory_calls(), 0); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn installed_apps_threadless_refresh_updates_existing_thread_tools() -> Result<()> { - let fixture = InstalledAppsFixture::start().await?; - fixture.set_tools(vec![connector_tool("alpha", "Alpha")?]); - let responses_server = responses::start_mock_server().await; - let codex_home = configured_codex_home(fixture.base_url())?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123") - .plan_type("sci_plus"), - AuthCredentialsStoreMode::File, - )?; - MockResponsesConfig::new(&responses_server.uri()) - .with_root_config(&format!( - "chatgpt_base_url = {:?}\nmcp_oauth_credentials_store = \"file\"", - fixture.base_url(), - )) - .enable_feature(Feature::Apps) - .disable_feature(Feature::CodeMode) - .disable_feature(Feature::CodeModeOnly) - .disable_feature(Feature::ToolSearch) - .write(codex_home.path())?; - let mut app_server = start_app_server(codex_home.path()).await?; - let ThreadStartResponse { thread, .. } = app_server - .start_thread(ThreadStartParams::default()) - .await?; - - for (index, (connector_id, connector_name)) in [("alpha", "Alpha"), ("beta", "Beta")] - .into_iter() - .enumerate() - { - if index > 0 { - fixture.set_tools(vec![connector_tool(connector_id, connector_name)?]); - send_installed_request(&mut app_server, /*force_refresh*/ true).await?; - } - let response_id = format!("response-{connector_id}"); - let response = responses::mount_sse_once( - &responses_server, - responses::sse(vec![ - responses::ev_response_created(&response_id), - responses::ev_assistant_message("message", "done"), - responses::ev_completed(&response_id), - ]), - ) - .await; - app_server - .start_turn_and_wait_for_completion(TurnStartParams { - thread_id: thread.id.clone(), - input: vec![UserInput::Text { - text: "Show the available apps".to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }) - .await?; - - let body = response.single_request().body_json(); - for candidate in ["alpha", "beta"] { - assert_eq!( - responses::namespace_child_tool( - &body, - &format!("mcp__codex_apps__{candidate}"), - &format!("connector_{candidate}"), - ) - .is_some(), - candidate == connector_id, - "the existing thread should expose the refreshed Apps catalog: {body}", - ); - } - assert_eq!(fixture.list_tools_calls(), index + 1); - } - let request_id = app_server - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: true, - }) - .await?; - let _: AppsListResponse = - timeout(DEFAULT_TIMEOUT, app_server.read_response(request_id)).await??; - assert_eq!(fixture.directory_calls(), 2); - Ok(()) -} - -#[tokio::test] -async fn installed_apps_global_disable_retains_tool_derived_identities() -> Result<()> { - let fixture = InstalledAppsFixture::start().await?; - let codex_home = configured_codex_home(fixture.base_url())?; - let committed = { - let mut app_server = start_app_server(codex_home.path()).await?; - send_installed_request(&mut app_server, /*force_refresh*/ true).await? - }; - let mut expected_disabled = committed; - for app in &mut expected_disabled.apps { - app.enabled = false; - app.callable = false; - } - - let config_path = codex_home.path().join("config.toml"); - let config = std::fs::read_to_string(&config_path)?; - std::fs::write(&config_path, config.replace("apps = true", "apps = false"))?; - let mut app_server = start_app_server(codex_home.path()).await?; - - let cached = send_installed_request(&mut app_server, /*force_refresh*/ false).await?; - assert_eq!(cached, expected_disabled); - let force_refresh = send_installed_request(&mut app_server, /*force_refresh*/ true).await?; - assert_eq!(force_refresh, cached); - assert_eq!(fixture.list_tools_calls(), 1); - - Ok(()) -} - -#[tokio::test] -async fn installed_apps_thread_id_uses_effective_thread_config() -> Result<()> { - let fixture = InstalledAppsFixture::start().await?; - let codex_home = configured_codex_home(fixture.base_url())?; - let mut app_server = start_app_server(codex_home.path()).await?; - let mut expected = send_installed_request(&mut app_server, /*force_refresh*/ true).await?; - - let request_id = app_server - .send_thread_start_request_with_auto_env(ThreadStartParams { - config: Some(HashMap::from([( - "apps.alpha.enabled".to_string(), - json!(false), - )])), - ..Default::default() - }) - .await?; - let ThreadStartResponse { thread, .. } = - timeout(DEFAULT_TIMEOUT, app_server.read_response(request_id)).await??; - - let alpha = expected - .apps - .iter_mut() - .find(|app| app.id == "alpha") - .expect("alpha app should be installed"); - alpha.enabled = false; - alpha.callable = false; - - for force_refresh in [false, true] { - let request_id = app_server - .send_apps_installed_request(AppsInstalledParams { - thread_id: Some(thread.id.clone()), - force_refresh, - }) - .await?; - let response: AppsInstalledResponse = - timeout(DEFAULT_TIMEOUT, app_server.read_response(request_id)).await??; - assert_eq!(response, expected); - } - - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn installed_apps_thread_refresh_updates_live_tools_and_retains_them_on_failure() -> Result<()> -{ - let fixture = InstalledAppsFixture::start().await?; - fixture.set_tools(vec![connector_tool("alpha", "Alpha")?]); - let responses_server = responses::start_mock_server().await; - let codex_home = configured_codex_home(fixture.base_url())?; - MockResponsesConfig::new(&responses_server.uri()) - .with_root_config(&format!( - "chatgpt_base_url = {:?}\nmcp_oauth_credentials_store = \"file\"", - fixture.base_url() - )) - .enable_feature(Feature::Apps) - .write(codex_home.path())?; - let mut app_server = start_app_server(codex_home.path()).await?; - let ThreadStartResponse { thread, .. } = app_server - .start_thread(ThreadStartParams::default()) - .await?; - - let initial_model_request = responses::mount_sse_once( - &responses_server, - responses::sse(vec![responses::ev_completed("before-refresh")]), - ) - .await; - let completed = timeout( - DEFAULT_TIMEOUT, - app_server.start_turn_and_wait_for_completion(TurnStartParams { - thread_id: thread.id.clone(), - input: vec![UserInput::Text { - text: "Which tools are available?".to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }), - ) - .await??; - assert_eq!(completed.turn.status, TurnStatus::Completed); - assert!( - initial_model_request - .single_request() - .tool_by_name("mcp__codex_apps__alpha", "connector_alpha") - .is_some() - ); - - fixture.set_tools(vec![connector_tool("beta", "Beta")?]); - let expected = AppsInstalledResponse { - apps: vec![InstalledApp { - id: "beta".to_string(), - runtime_name: Some("Beta".to_string()), - enabled: true, - callable: true, - }], - }; - - for (call_id, refresh_fails) in [("after-refresh", false), ("after-failed-refresh", true)] { - if refresh_fails { - fixture.fail_next_list_tools(); - } - let list_tools_calls = fixture.list_tools_calls(); - let mut request_id = app_server - .send_apps_installed_request(AppsInstalledParams { - thread_id: Some(thread.id.clone()), - force_refresh: true, - }) - .await?; - if refresh_fails { - let error = timeout( - DEFAULT_TIMEOUT, - app_server.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - assert_eq!(error.error.code, -32603); - request_id = app_server - .send_apps_installed_request(AppsInstalledParams { - thread_id: Some(thread.id.clone()), - force_refresh: false, - }) - .await?; - } - let installed: AppsInstalledResponse = - timeout(DEFAULT_TIMEOUT, app_server.read_response(request_id)).await??; - assert_eq!(installed, expected); - assert_eq!(fixture.list_tools_calls(), list_tools_calls + 1); - - let model_requests = responses::mount_sse_sequence( - &responses_server, - vec![ - responses::sse(vec![ - responses::ev_function_call_with_namespace( - call_id, - "mcp__codex_apps__beta", - "connector_beta", - "{}", - ), - responses::ev_completed(call_id), - ]), - responses::sse(vec![responses::ev_completed("done")]), - ], - ) - .await; - let completed = timeout( - DEFAULT_TIMEOUT, - app_server.start_turn_and_wait_for_completion(TurnStartParams { - thread_id: thread.id.clone(), - input: vec![UserInput::Text { - text: "Call Beta.".to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }), - ) - .await??; - assert_eq!(completed.turn.status, TurnStatus::Completed); - let requests = model_requests.requests(); - assert_eq!(requests.len(), 2); - assert!( - requests[0] - .tool_by_name("mcp__codex_apps__beta", "connector_beta") - .is_some() - ); - assert!( - requests[0] - .tool_by_name("mcp__codex_apps__alpha", "connector_alpha") - .is_none() - ); - assert_eq!( - requests[1].function_call_output(call_id)["output"][1], - json!({"type": "input_text", "text": "called connector_beta"}) - ); - assert_eq!(fixture.list_tools_calls(), list_tools_calls + 1); - } - Ok(()) -} - -#[tokio::test] -async fn installed_apps_failed_force_refresh_retains_previous_snapshot() -> Result<()> { - let fixture = InstalledAppsFixture::start().await?; - let codex_home = configured_codex_home(fixture.base_url())?; - let mut app_server = start_app_server(codex_home.path()).await?; - - let committed = send_installed_request(&mut app_server, /*force_refresh*/ true).await?; - fixture.fail_next_list_tools(); - let request_id = app_server - .send_apps_installed_request(AppsInstalledParams { - thread_id: None, - force_refresh: true, - }) - .await?; - let error: JSONRPCError = timeout( - DEFAULT_TIMEOUT, - app_server.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - assert_eq!(error.error.code, -32603); - - let retained = send_installed_request(&mut app_server, /*force_refresh*/ false).await?; - assert_eq!(retained, committed); - assert_eq!(fixture.list_tools_calls(), 2); - Ok(()) -} - -async fn start_app_server(codex_home: &Path) -> Result { - TestAppServer::builder() - .with_codex_home(codex_home) - .without_managed_config() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await -} - -async fn send_installed_request( - app_server: &mut TestAppServer, - force_refresh: bool, -) -> Result { - let request_id = app_server - .send_apps_installed_request(AppsInstalledParams { - thread_id: None, - force_refresh, - }) - .await?; - timeout(DEFAULT_TIMEOUT, app_server.read_response(request_id)).await? -} - -fn configured_codex_home(base_url: &str) -> Result { - let codex_home = TempDir::new()?; - std::fs::write( - codex_home.path().join("config.toml"), - format!( - r#" -chatgpt_base_url = "{base_url}" -mcp_oauth_credentials_store = "file" - -[features] -apps = true - -[apps.blocked] -default_tools_enabled = false - -[apps.disabled] -enabled = false -"#, - ), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123") - .plan_type("team"), - AuthCredentialsStoreMode::File, - )?; - Ok(codex_home) -} - -#[derive(Clone)] -struct InstalledAppsMcpServer { - state: Arc, -} - -impl ServerHandler for InstalledAppsMcpServer { - fn get_info(&self) -> ServerConfig { - ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) - } - - async fn call_tool( - &self, - request: CallToolRequestParams, - _context: rmcp::service::RequestContext, - ) -> Result { - Ok( - CallToolResult::success(vec![ContentBlock::text(format!("called {}", request.name))]) - .into(), - ) - } - - fn list_tools( - &self, - _request: Option, - _context: rmcp::service::RequestContext, - ) -> impl std::future::Future> + Send + '_ - { - let state = Arc::clone(&self.state); - async move { - state.list_tools_calls.fetch_add(1, Ordering::SeqCst); - let should_fail = state.fail_next.swap(false, Ordering::SeqCst); - if should_fail { - return Err(rmcp::ErrorData::internal_error( - "injected tools/list failure", - None, - )); - } - - Ok(ListToolsResult::with_all_items( - state - .tools - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone(), - )) - } - } -} - -struct InstalledAppsServerState { - tools: Mutex>, - list_tools_calls: AtomicUsize, - directory_calls: AtomicUsize, - fail_next: AtomicBool, -} - -struct InstalledAppsFixture { - base_url: String, - state: Arc, - handle: JoinHandle<()>, -} - -impl InstalledAppsFixture { - async fn start() -> Result { - let mut synthetic_link = connector_tool("link-only", "Link Only")?; - synthetic_link - .meta - .as_mut() - .expect("connector tool should have metadata") - .0 - .insert("_codex_apps".to_string(), json!({ "synthetic_link": true })); - let state = Arc::new(InstalledAppsServerState { - tools: Mutex::new(vec![ - connector_tool("alpha", "Alpha Tool Name")?, - connector_tool("blocked", "Policy Blocked Tool Name")?, - connector_tool("disabled", "Locally Disabled Tool Name")?, - connector_tool("alpha", "Duplicate Alpha Tool Name")?, - connector_tool("", "Empty Connector ID")?, - Tool::new( - "missing_connector_id", - "Missing connector id", - Arc::new(Default::default()), - ), - synthetic_link, - ]), - list_tools_calls: AtomicUsize::new(0), - directory_calls: AtomicUsize::new(0), - fail_next: AtomicBool::new(false), - }); - let listener = TcpListener::bind("127.0.0.1:0").await?; - let address = listener.local_addr()?; - let mcp_service = StreamableHttpService::new( - { - let state = Arc::clone(&state); - move || { - Ok(InstalledAppsMcpServer { - state: Arc::clone(&state), - }) - } - }, - Arc::new(LocalSessionManager::default()), - StreamableHttpServerConfig::default(), - ); - let router = Router::new() - .route( - "/api/codex/config/bundle", - get(|| async { Json(json!({})) }), - ) - .route("/connectors/directory/list", get(list_directory_apps)) - .route( - "/connectors/directory/list_workspace", - get(list_directory_apps), - ) - .nest_service("/api/codex/ps/mcp", mcp_service) - .with_state(Arc::clone(&state)); - let handle = tokio::spawn(async move { - let _ = axum::serve(listener, router).await; - }); - Ok(Self { - base_url: format!("http://{address}"), - state, - handle, - }) - } - - fn base_url(&self) -> &str { - &self.base_url - } - - fn list_tools_calls(&self) -> usize { - self.state.list_tools_calls.load(Ordering::SeqCst) - } - - fn set_tools(&self, tools: Vec) { - *self - .state - .tools - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = tools; - } - - fn directory_calls(&self) -> usize { - self.state.directory_calls.load(Ordering::SeqCst) - } - - fn fail_next_list_tools(&self) { - self.state.fail_next.store(true, Ordering::SeqCst); - } -} - -impl Drop for InstalledAppsFixture { - fn drop(&mut self) { - self.handle.abort(); - } -} - -async fn list_directory_apps( - State(state): State>, -) -> Json { - state.directory_calls.fetch_add(1, Ordering::SeqCst); - Json(json!({ "apps": [], "next_token": null })) -} diff --git a/codex-rs/app-server/tests/suite/v2/app_list.rs b/codex-rs/app-server/tests/suite/v2/app_list.rs deleted file mode 100644 index efef823c..00000000 --- a/codex-rs/app-server/tests/suite/v2/app_list.rs +++ /dev/null @@ -1,1764 +0,0 @@ -use std::borrow::Cow; -use std::collections::HashMap; -use std::path::Path; -use std::sync::Arc; -use std::sync::Mutex as StdMutex; -use std::time::Duration; - -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::ChatGptIdTokenClaims; -use app_test_support::TestAppServer; -use app_test_support::encode_id_token; -use app_test_support::write_chatgpt_auth; -use axum::Json; -use axum::Router; -use axum::extract::State; -use axum::http::HeaderMap; -use axum::http::StatusCode; -use axum::http::Uri; -use axum::http::header::AUTHORIZATION; -use axum::routing::get; -use codex_app_server_protocol::AppBranding; -use codex_app_server_protocol::AppInfo; -use codex_app_server_protocol::AppListUpdatedNotification; -use codex_app_server_protocol::AppMetadata; -use codex_app_server_protocol::AppReview; -use codex_app_server_protocol::AppScreenshot; -use codex_app_server_protocol::AppsListParams; -use codex_app_server_protocol::AppsListResponse; -use codex_app_server_protocol::GetAccountParams; -use codex_app_server_protocol::GetAccountResponse; -use codex_app_server_protocol::JSONRPCError; -use codex_app_server_protocol::LoginAccountResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ThreadStartParams; -use codex_app_server_protocol::ThreadStartResponse; -use codex_config::types::AuthCredentialsStoreMode; -use codex_login::AuthDotJson; -use codex_login::AuthKeyringBackendKind; -use codex_login::save_auth; -use codex_protocol::auth::AuthMode; -use pretty_assertions::assert_eq; -use rmcp::handler::server::ServerHandler; -use rmcp::model::JsonObject; -use rmcp::model::ListToolsResult; -use rmcp::model::MetaObject; -use rmcp::model::ServerCapabilities; -use rmcp::model::ServerConfig; -use rmcp::model::Tool; -use rmcp::model::ToolAnnotations; -use rmcp::transport::StreamableHttpServerConfig; -use rmcp::transport::StreamableHttpService; -use rmcp::transport::streamable_http_server::session::local::LocalSessionManager; -use serde_json::json; -use tempfile::TempDir; -use tokio::net::TcpListener; -use tokio::task::JoinHandle; -use tokio::time::timeout; - -// Bazel CI can spend tens of seconds starting app-server subprocesses or -// processing app-list RPCs under load. -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60); - -#[tokio::test] -async fn list_apps_returns_empty_when_connectors_disabled() -> Result<()> { - let codex_home = TempDir::new()?; - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: Some(50), - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - - let AppsListResponse { data, next_cursor } = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - - assert!(data.is_empty()); - assert!(next_cursor.is_none()); - Ok(()) -} - -#[tokio::test] -async fn list_apps_returns_empty_with_api_key_auth() -> Result<()> { - let connectors = vec![AppInfo { - id: "beta".to_string(), - name: "Beta".to_string(), - description: Some("Beta connector".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = - start_apps_server_with_delays(connectors, tools, Duration::ZERO, Duration::ZERO).await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - save_auth( - codex_home.path(), - &AuthDotJson { - auth_mode: Some(AuthMode::ApiKey), - openai_api_key: Some("test-api-key".to_string()), - tokens: None, - last_refresh: None, - agent_identity: None, - personal_access_token: None, - bedrock_api_key: None, - bedrock_access_keys: None, - }, - AuthCredentialsStoreMode::File, - AuthKeyringBackendKind::default(), - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: Some(50), - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - - let AppsListResponse { data, next_cursor } = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - assert!(data.is_empty()); - assert!(next_cursor.is_none()); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn list_apps_uses_external_chatgpt_auth() -> Result<()> { - let access_token = encode_id_token( - &ChatGptIdTokenClaims::new() - .email("external@example.com") - .plan_type("pro") - .chatgpt_account_id("account-123"), - )?; - let connectors = vec![AppInfo { - id: "beta".to_string(), - name: "Beta".to_string(), - description: Some("Beta connector".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle, _) = start_apps_server_with_delays_and_control_inner( - connectors, - tools, - Duration::ZERO, - Duration::ZERO, - &access_token, - ) - .await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - let login_id = mcp - .send_chatgpt_auth_tokens_login_request( - access_token, - "account-123".to_string(), - Some("pro".to_string()), - ) - .await?; - let login_response: LoginAccountResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(login_id)).await??; - assert_eq!(login_response, LoginAccountResponse::ChatgptAuthTokens {}); - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: true, - }) - .await?; - let AppsListResponse { data, next_cursor } = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - - assert_eq!(data.len(), 1); - assert_eq!(data[0].id, "beta"); - assert!(data[0].is_accessible); - assert!(next_cursor.is_none()); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn list_apps_includes_plugin_apps_for_chatgpt_auth() -> Result<()> { - let (server_url, server_handle) = - start_apps_server_with_delays(Vec::new(), Vec::new(), Duration::ZERO, Duration::ZERO) - .await?; - - let codex_home = TempDir::new()?; - write_connectors_and_plugins_config(codex_home.path(), &server_url)?; - write_plugin_app_fixture(codex_home.path(), "sample", "connector_sample")?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-plugin-apps") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - let AppsListResponse { data, next_cursor } = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - - assert!(data.iter().any(|app| app.id == "connector_sample")); - assert!(next_cursor.is_none()); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn list_apps_uses_thread_feature_flag_when_thread_id_is_provided() -> Result<()> { - let connectors = vec![AppInfo { - id: "beta".to_string(), - name: "Beta".to_string(), - description: Some("Beta connector".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = - start_apps_server_with_delays(connectors, tools, Duration::ZERO, Duration::ZERO).await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let start_request = mcp - .send_thread_start_request_with_auto_env(ThreadStartParams::default()) - .await?; - let ThreadStartResponse { thread, .. } = - timeout(DEFAULT_TIMEOUT, mcp.read_response(start_request)).await??; - - std::fs::write( - codex_home.path().join("config.toml"), - format!( - r#" -chatgpt_base_url = "{server_url}" -mcp_oauth_credentials_store = "file" - -[features] -connectors = false -"# - ), - )?; - - let global_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - let AppsListResponse { - data: global_data, - next_cursor: global_next_cursor, - } = timeout(DEFAULT_TIMEOUT, mcp.read_response(global_request)).await??; - assert!(global_data.is_empty()); - assert!(global_next_cursor.is_none()); - - let thread_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: Some(thread.id), - force_refetch: false, - }) - .await?; - let AppsListResponse { - data: thread_data, - next_cursor: thread_next_cursor, - } = timeout(DEFAULT_TIMEOUT, mcp.read_response(thread_request)).await??; - assert!(thread_data.iter().any(|app| app.id == "beta")); - assert!(thread_next_cursor.is_none()); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn list_apps_keeps_apps_with_app_only_tools_accessible() -> Result<()> { - let connector_id = "connector_2b0a9009c9c64bf9933a3dae3f2b1254"; - let connectors = vec![AppInfo { - id: connector_id.to_string(), - name: "Formerly Blocked".to_string(), - description: Some("Formerly blocked connector".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let mut app_only_tool = connector_tool(connector_id, "Formerly Blocked")?; - app_only_tool - .meta - .as_mut() - .expect("connector tool should include metadata") - .0 - .insert("ui".to_string(), json!({ "visibility": ["app"] })); - let tools = vec![app_only_tool]; - let (server_url, server_handle) = - start_apps_server_with_delays(connectors, tools, Duration::ZERO, Duration::ZERO).await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-app-only") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: true, - }) - .await?; - let AppsListResponse { data, next_cursor } = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - - assert_eq!(data.len(), 1); - assert_eq!(data[0].id, connector_id); - assert!(data[0].is_accessible); - assert!(next_cursor.is_none()); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn list_apps_reports_is_enabled_from_config() -> Result<()> { - let connectors = vec![AppInfo { - id: "beta".to_string(), - name: "Beta".to_string(), - description: Some("Beta connector".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = - start_apps_server_with_delays(connectors, tools, Duration::ZERO, Duration::ZERO).await?; - - let codex_home = TempDir::new()?; - std::fs::write( - codex_home.path().join("config.toml"), - format!( - r#" -chatgpt_base_url = "{server_url}" - -[features] -connectors = true - -[apps.beta] -enabled = false -"# - ), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - - let AppsListResponse { - data: response_data, - next_cursor, - } = timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - assert!(next_cursor.is_none()); - assert_eq!(response_data.len(), 1); - assert_eq!(response_data[0].id, "beta"); - assert!(!response_data[0].is_enabled); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn list_apps_emits_updates_and_returns_after_both_lists_load() -> Result<()> { - let alpha_branding = Some(AppBranding { - category: Some("PRODUCTIVITY".to_string()), - developer: Some("Acme".to_string()), - website: Some("https://acme.example".to_string()), - privacy_policy: Some("https://acme.example/privacy".to_string()), - terms_of_service: Some("https://acme.example/terms".to_string()), - is_discoverable_app: true, - }); - let alpha_app_metadata = Some(AppMetadata { - review: Some(AppReview { - status: "APPROVED".to_string(), - }), - categories: Some(vec!["PRODUCTIVITY".to_string()]), - sub_categories: Some(vec!["WRITING".to_string()]), - seo_description: Some("Alpha connector".to_string()), - screenshots: Some(vec![AppScreenshot { - url: Some("https://example.com/alpha-screenshot.png".to_string()), - file_id: Some("file_123".to_string()), - user_prompt: "Summarize this draft".to_string(), - }]), - developer: Some("Acme".to_string()), - version: Some("1.2.3".to_string()), - version_id: Some("version_123".to_string()), - version_notes: Some("Fixes and improvements".to_string()), - first_party_requires_install: Some(true), - show_in_composer_when_unlinked: Some(true), - }); - let alpha_labels = Some(HashMap::from([ - ("feature".to_string(), "beta".to_string()), - ("source".to_string(), "directory".to_string()), - ])); - - let connectors = vec![ - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: Some("https://example.com/alpha.png".to_string()), - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: alpha_branding.clone(), - app_metadata: alpha_app_metadata.clone(), - labels: alpha_labels.clone(), - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "beta".to_string(), - name: "beta".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ]; - - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = start_apps_server_with_delays( - connectors.clone(), - tools, - Duration::from_millis(300), - Duration::ZERO, - ) - .await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - - let expected_accessible = vec![AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta-app/beta".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - - let first_update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!(first_update.data, expected_accessible); - - let expected_merged = vec![ - AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta/beta".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: Some("https://example.com/alpha.png".to_string()), - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: alpha_branding, - app_metadata: alpha_app_metadata, - labels: alpha_labels, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ]; - - let second_update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!(second_update.data, expected_merged); - - let AppsListResponse { - data: response_data, - next_cursor, - } = timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - assert_eq!(response_data, expected_merged); - assert!(next_cursor.is_none()); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn list_apps_waits_for_accessible_data_before_emitting_directory_updates() -> Result<()> { - let connectors = vec![ - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: Some("https://example.com/alpha.png".to_string()), - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "beta".to_string(), - name: "beta".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ]; - - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = start_apps_server_with_delays( - connectors.clone(), - tools, - Duration::ZERO, - Duration::from_millis(300), - ) - .await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-directory-first") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - - let expected = vec![ - AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta/beta".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: Some("https://example.com/alpha.png".to_string()), - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ]; - - loop { - let update = read_app_list_updated_notification(&mut mcp).await?; - if update.data == expected { - break; - } - - assert!( - !update.data.is_empty() && update.data.iter().all(|connector| connector.is_accessible), - "unexpected directory-only app/list update before accessible apps loaded" - ); - } - - let AppsListResponse { data, next_cursor } = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - assert_eq!(data, expected); - assert!(next_cursor.is_none()); - - server_handle.abort(); - Ok(()) -} - -#[tokio::test] -async fn list_apps_does_not_emit_empty_interim_updates() -> Result<()> { - let connectors = vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let (server_url, server_handle) = start_apps_server_with_delays( - connectors.clone(), - Vec::new(), - Duration::from_millis(300), - Duration::ZERO, - ) - .await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-empty-interim") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - - let maybe_update = timeout( - Duration::from_millis(150), - read_app_list_updated_notification(&mut mcp), - ) - .await; - assert!( - maybe_update.is_err(), - "unexpected empty interim app/list update" - ); - - let expected = vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - - let update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!(update.data, expected); - - let AppsListResponse { data, next_cursor } = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - assert_eq!(data, expected); - assert!(next_cursor.is_none()); - - server_handle.abort(); - Ok(()) -} - -#[tokio::test] -async fn list_apps_paginates_results() -> Result<()> { - let connectors = vec![ - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "beta".to_string(), - name: "beta".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ]; - - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = start_apps_server_with_delays( - connectors.clone(), - tools, - Duration::ZERO, - Duration::from_millis(300), - ) - .await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let first_request = mcp - .send_apps_list_request(AppsListParams { - limit: Some(1), - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - let AppsListResponse { - data: first_page, - next_cursor: first_cursor, - } = timeout(DEFAULT_TIMEOUT, mcp.read_response(first_request)).await??; - - let expected_first = vec![AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta/beta".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - - assert_eq!(first_page, expected_first); - let next_cursor = first_cursor.ok_or_else(|| anyhow::anyhow!("missing cursor"))?; - - loop { - let update = read_app_list_updated_notification(&mut mcp).await?; - if update.data.len() == 2 && update.data.iter().any(|connector| connector.is_accessible) { - break; - } - } - mcp.clear_message_buffer(); - - let second_request = mcp - .send_apps_list_request(AppsListParams { - limit: Some(1), - cursor: Some(next_cursor), - thread_id: None, - force_refetch: false, - }) - .await?; - let AppsListResponse { - data: second_page, - next_cursor: second_cursor, - } = timeout(DEFAULT_TIMEOUT, mcp.read_response(second_request)).await??; - - let expected_second = vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - - assert_eq!(second_page, expected_second); - assert!(second_cursor.is_none()); - - let duplicate_update = timeout( - Duration::from_millis(150), - read_app_list_updated_notification(&mut mcp), - ) - .await; - assert!( - duplicate_update.is_err(), - "cached app/list page emitted a duplicate full-list update" - ); - - server_handle.abort(); - Ok(()) -} - -#[tokio::test] -async fn list_apps_force_refetch_preserves_previous_cache_on_failure() -> Result<()> { - let connectors = vec![AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: Some("Beta connector".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = - start_apps_server_with_delays(connectors, tools, Duration::ZERO, Duration::ZERO).await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let initial_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - let AppsListResponse { - data: initial_data, - next_cursor: initial_next_cursor, - } = timeout(DEFAULT_TIMEOUT, mcp.read_response(initial_request)).await??; - assert!(initial_next_cursor.is_none()); - assert_eq!(initial_data.len(), 1); - assert!(initial_data.iter().all(|app| app.is_accessible)); - - let account_request = mcp - .send_get_account_request(GetAccountParams { - refresh_token: false, - }) - .await?; - let initial_account: GetAccountResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(account_request)).await??; - assert!(initial_account.account.is_some()); - - let auth_path = codex_home.path().join("auth.json"); - std::fs::write(&auth_path, "")?; - let refetch_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: true, - }) - .await?; - let _: JSONRPCError = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(refetch_request)), - ) - .await??; - - let account_request = mcp - .send_get_account_request(GetAccountParams { - refresh_token: false, - }) - .await?; - let account: GetAccountResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(account_request)).await??; - assert_eq!(account, initial_account); - - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token-invalid") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let refetch_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: true, - }) - .await?; - let refetch_error: JSONRPCError = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(refetch_request)), - ) - .await??; - assert!(refetch_error.error.message.contains("failed to")); - - let cached_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - let AppsListResponse { - data: cached_data, - next_cursor: cached_next_cursor, - } = timeout(DEFAULT_TIMEOUT, mcp.read_response(cached_request)).await??; - - assert_eq!(cached_data, initial_data); - assert!(cached_next_cursor.is_none()); - server_handle.abort(); - Ok(()) -} - -#[tokio::test] -async fn list_apps_force_refetch_patches_updates_from_cached_snapshots() -> Result<()> { - let initial_connectors = vec![ - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha v1".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: Some("Beta v1".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ]; - let initial_tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle, server_control) = start_apps_server_with_delays_and_control( - initial_connectors, - initial_tools, - Duration::from_millis(300), - Duration::ZERO, - ) - .await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let warm_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - let warm_first_update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!( - warm_first_update.data, - vec![AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta-app/beta".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }] - ); - - let warm_second_update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!( - warm_second_update.data, - vec![ - AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: Some("Beta v1".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta-app/beta".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha v1".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ] - ); - - let AppsListResponse { - data: warm_data, - next_cursor: warm_next_cursor, - } = timeout(DEFAULT_TIMEOUT, mcp.read_response(warm_request)).await??; - assert_eq!(warm_data, warm_second_update.data); - assert!(warm_next_cursor.is_none()); - - server_control.set_connectors(vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha v2".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]); - server_control.set_tools(Vec::new()); - - let refetch_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: true, - }) - .await?; - - let first_update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!( - first_update.data, - vec![ - AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: Some("Beta v1".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta-app/beta".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha v1".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ] - ); - - let maybe_second_update = timeout( - Duration::from_millis(150), - read_app_list_updated_notification(&mut mcp), - ) - .await; - assert!( - maybe_second_update.is_err(), - "unexpected inaccessible-only app/list update during force refetch" - ); - - let expected_final = vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha v2".to_string()), - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let second_update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!(second_update.data, expected_final); - - let AppsListResponse { - data: refetch_data, - next_cursor: refetch_next_cursor, - } = timeout(DEFAULT_TIMEOUT, mcp.read_response(refetch_request)).await??; - assert_eq!(refetch_data, expected_final); - assert!(refetch_next_cursor.is_none()); - - mcp.clear_message_buffer(); - let cached_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - let AppsListResponse { - data: cached_data, - next_cursor: cached_next_cursor, - } = timeout(DEFAULT_TIMEOUT, mcp.read_response(cached_request)).await??; - assert_eq!(cached_data, expected_final); - assert!(cached_next_cursor.is_none()); - - let cached_update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!(cached_update.data, expected_final); - - let duplicate_update = timeout( - Duration::from_millis(150), - read_app_list_updated_notification(&mut mcp), - ) - .await; - assert!( - duplicate_update.is_err(), - "cached initial app/list emitted more than one full-list update" - ); - - server_handle.abort(); - Ok(()) -} - -async fn read_app_list_updated_notification( - mcp: &mut TestAppServer, -) -> Result { - timeout(DEFAULT_TIMEOUT, mcp.read_notification("app/list/updated")).await? -} - -#[derive(Clone)] -struct AppsServerState { - expected_bearer: String, - expected_account_id: String, - response: Arc>, - directory_delay: Duration, -} - -#[derive(Clone)] -struct AppListMcpServer { - tools: Arc>>, - tools_delay: Duration, -} - -impl AppListMcpServer { - fn new(tools: Arc>>, tools_delay: Duration) -> Self { - Self { tools, tools_delay } - } -} - -#[derive(Clone)] -struct AppsServerControl { - response: Arc>, - tools: Arc>>, -} - -impl AppsServerControl { - fn set_connectors(&self, connectors: Vec) { - let mut response_guard = self - .response - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - *response_guard = json!({ "apps": connectors, "next_token": null }); - } - - fn set_tools(&self, tools: Vec) { - let mut tools_guard = self - .tools - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - *tools_guard = tools; - } -} - -impl ServerHandler for AppListMcpServer { - fn get_info(&self) -> ServerConfig { - ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) - } - - fn list_tools( - &self, - _request: Option, - _context: rmcp::service::RequestContext, - ) -> impl std::future::Future> + Send + '_ - { - let tools = self.tools.clone(); - let tools_delay = self.tools_delay; - async move { - if tools_delay > Duration::ZERO { - tokio::time::sleep(tools_delay).await; - } - let tools = tools - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone(); - Ok(ListToolsResult::with_all_items(tools)) - } - } -} - -pub(super) async fn start_apps_server_with_delays( - connectors: Vec, - tools: Vec, - directory_delay: Duration, - tools_delay: Duration, -) -> Result<(String, JoinHandle<()>)> { - let (server_url, server_handle, _server_control) = - start_apps_server_with_delays_and_control(connectors, tools, directory_delay, tools_delay) - .await?; - Ok((server_url, server_handle)) -} - -async fn start_apps_server_with_delays_and_control( - connectors: Vec, - tools: Vec, - directory_delay: Duration, - tools_delay: Duration, -) -> Result<(String, JoinHandle<()>, AppsServerControl)> { - start_apps_server_with_delays_and_control_inner( - connectors, - tools, - directory_delay, - tools_delay, - "chatgpt-token", - ) - .await -} - -async fn start_apps_server_with_delays_and_control_inner( - connectors: Vec, - tools: Vec, - directory_delay: Duration, - tools_delay: Duration, - expected_bearer: &str, -) -> Result<(String, JoinHandle<()>, AppsServerControl)> { - let response = Arc::new(StdMutex::new( - json!({ "apps": connectors, "next_token": null }), - )); - let tools = Arc::new(StdMutex::new(tools)); - let state = AppsServerState { - expected_bearer: format!("Bearer {expected_bearer}"), - expected_account_id: "account-123".to_string(), - response: response.clone(), - directory_delay, - }; - let state = Arc::new(state); - let server_control = AppsServerControl { - response, - tools: tools.clone(), - }; - - let listener = TcpListener::bind("127.0.0.1:0").await?; - let addr = listener.local_addr()?; - - let mcp_service = StreamableHttpService::new( - { - let tools = tools.clone(); - move || Ok(AppListMcpServer::new(tools.clone(), tools_delay)) - }, - Arc::new(LocalSessionManager::default()), - StreamableHttpServerConfig::default(), - ); - - let router = Router::new() - .route( - "/api/codex/accounts/check", - get(|State(state): State>| async move { - Json(json!({ - "accounts": [{ - "id": state.expected_account_id, - "workspace_backend_origin": "https://chatgpt.com", - "account_routing_override": "NO_CONSTRAINT", - }], - })) - }), - ) - .route("/connectors/directory/list", get(list_directory_connectors)) - .route( - "/connectors/directory/list_workspace", - get(list_directory_connectors), - ) - .with_state(state) - .nest_service("/api/codex/ps/mcp", mcp_service); - - let handle = tokio::spawn(async move { - let _ = axum::serve(listener, router).await; - }); - - Ok((format!("http://{addr}"), handle, server_control)) -} - -async fn list_directory_connectors( - State(state): State>, - headers: HeaderMap, - uri: Uri, -) -> Result { - if state.directory_delay > Duration::ZERO { - tokio::time::sleep(state.directory_delay).await; - } - - let bearer_ok = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .is_some_and(|value| value == state.expected_bearer); - let account_ok = headers - .get("chatgpt-account-id") - .and_then(|value| value.to_str().ok()) - .is_some_and(|value| value == state.expected_account_id); - let external_logos_ok = uri - .query() - .is_some_and(|query| query.split('&').any(|pair| pair == "external_logos=true")); - - if !bearer_ok || !account_ok { - Err(StatusCode::UNAUTHORIZED) - } else if !external_logos_ok { - Err(StatusCode::BAD_REQUEST) - } else { - let response = state - .response - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone(); - Ok(Json(response)) - } -} - -pub(super) fn connector_tool(connector_id: &str, connector_name: &str) -> Result { - let schema: JsonObject = serde_json::from_value(json!({ - "type": "object", - "additionalProperties": false - }))?; - let mut tool = Tool::new( - Cow::Owned(format!("connector_{connector_id}")), - Cow::Borrowed("Connector test tool"), - Arc::new(schema), - ); - tool.annotations = Some(ToolAnnotations::new().read_only(true)); - - let mut meta = MetaObject::new(); - meta.0 - .insert("connector_id".to_string(), json!(connector_id)); - meta.0 - .insert("connector_name".to_string(), json!(connector_name)); - tool.meta = Some(meta); - Ok(tool) -} - -fn write_connectors_config(codex_home: &std::path::Path, base_url: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -chatgpt_base_url = "{base_url}" -mcp_oauth_credentials_store = "file" - -[features] -connectors = true -"# - ), - ) -} - -fn write_connectors_and_plugins_config(codex_home: &Path, base_url: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -chatgpt_base_url = "{base_url}" -mcp_oauth_credentials_store = "file" - -[features] -connectors = true -plugins = true - -[plugins."sample@test"] -enabled = true -"# - ), - ) -} - -fn write_plugin_app_fixture(codex_home: &Path, plugin_name: &str, app_id: &str) -> Result<()> { - let plugin_root = codex_home - .join("plugins/cache") - .join("test") - .join(plugin_name) - .join("local"); - std::fs::create_dir_all(plugin_root.join(".codex-plugin"))?; - std::fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - format!(r#"{{"name":"{plugin_name}"}}"#), - )?; - std::fs::write( - plugin_root.join(".app.json"), - serde_json::to_vec_pretty(&json!({ - "apps": { - plugin_name: { "id": app_id } - } - }))?, - )?; - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/v2/app_read.rs b/codex-rs/app-server/tests/suite/v2/app_read.rs deleted file mode 100644 index 409d693f..00000000 --- a/codex-rs/app-server/tests/suite/v2/app_read.rs +++ /dev/null @@ -1,941 +0,0 @@ -use std::collections::HashMap; -use std::path::Path; -use std::sync::Arc; -use std::sync::Mutex as StdMutex; -use std::time::Duration; - -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::ChatGptIdTokenClaims; -use app_test_support::TestAppServer; -use app_test_support::encode_id_token; -use app_test_support::write_chatgpt_auth; -use axum::Json; -use axum::Router; -use axum::extract::State; -use axum::http::HeaderMap; -use axum::http::StatusCode; -use axum::http::header::AUTHORIZATION; -use axum::routing::any; -use axum::routing::post; -use codex_app_server::chatgpt_connectors as connectors; -use codex_app_server_protocol::AppsReadParams; -use codex_app_server_protocol::AppsReadResponse; -use codex_app_server_protocol::ConnectorMetadata; -use codex_app_server_protocol::JSONRPCError; -use codex_app_server_protocol::LoginAccountResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ThreadStartParams; -use codex_app_server_protocol::ThreadStartResponse; -use codex_config::LoaderOverrides; -use codex_config::types::AuthCredentialsStoreMode; -use codex_core::config::ConfigBuilder; -use codex_http_client::DestinationPolicy; -use codex_http_client::HttpError; -use codex_http_client::NetworkPolicyController; -use codex_http_client::NetworkPolicyDenied; -use codex_login::AuthManager; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use tempfile::TempDir; -use tokio::net::TcpListener; -use tokio::task::JoinHandle; -use tokio::time::timeout; - -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30); - -#[test] -fn app_read_deserializes_legacy_tool_summaries() -> Result<()> { - let response: AppsReadResponse = serde_json::from_value(json!({ - "apps": [{ - "id": "alpha", - "name": "Alpha", - "description": null, - "iconUrl": null, - "iconUrlDark": null, - "distributionChannel": null, - "installUrl": null, - "pluginDisplayNames": [], - "toolSummaries": [{ - "name": "search", - "title": "Search", - "description": "Search Alpha", - }], - }], - "missingAppIds": [], - }))?; - - assert_eq!( - serde_json::to_value(response)?, - json!({ - "apps": [{ - "id": "alpha", - "name": "Alpha", - "description": null, - "iconUrl": null, - "iconUrlDark": null, - "distributionChannel": null, - "installUrl": null, - "pluginDisplayNames": [], - "toolSummaries": [{ - "name": "search", - "title": "Search", - "description": "Search Alpha", - "isEnabled": true, - "disabledReason": null, - "isReadOnly": false, - }], - }], - "missingAppIds": [], - }) - ); - Ok(()) -} - -#[tokio::test] -async fn connector_requests_preserve_account_policy() -> Result<()> { - let state = BatchServerState::new(json!({ "apps": [] }), "chatgpt-token", "codex"); - let (server_url, server_handle) = start_batch_server(state.clone()).await?; - let home = TempDir::new()?; - write_apps_config(home.path(), &server_url, /*apps_mcp_product_sku*/ None)?; - write_auth(home.path())?; - let mut config = ConfigBuilder::default() - .codex_home(home.path().to_path_buf()) - .fallback_cwd(Some(home.path().to_path_buf())) - .loader_overrides(LoaderOverrides::without_managed_config_for_tests()) - .build() - .await?; - let controller = NetworkPolicyController::default(); - let policy = controller.policy(); - controller.publish(policy.revision(), DestinationPolicy::Unrestricted); - config.application_network_policy = policy.clone(); - let manager = - AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await?; - let (auth, factory) = manager.auth_with_http_client_factory().await.unwrap(); - config.application_network_policy = factory.network_policy().clone(); - let app_ids = vec!["alpha".to_string()]; - connectors::read_connector_metadata( - &config, &auth, /*runtime*/ None, &app_ids, /*include_tools*/ false, - ) - .await?; - assert_eq!(state.requests().len(), 1); - - policy.invalidate(); - controller.publish(policy.revision(), DestinationPolicy::Unrestricted); - let error = timeout( - DEFAULT_TIMEOUT, - connectors::read_connector_metadata( - &config, &auth, /*runtime*/ None, &app_ids, /*include_tools*/ false, - ), - ) - .await? - .err() - .expect("old credentials must retain their revoked policy"); - assert!(matches!( - error.downcast_ref::(), - Some(HttpError::Policy(NetworkPolicyDenied::Revoked)) - )); - assert_eq!(state.requests().len(), 1); - - controller.publish( - policy.revision(), - DestinationPolicy::Restricted { - allowed_hosts: Default::default(), - }, - ); - let (auth, factory) = manager.auth_with_http_client_factory().await.unwrap(); - config.application_network_policy = factory.network_policy().clone(); - let error = timeout( - DEFAULT_TIMEOUT, - connectors::list_all_connectors_with_options( - &config, - Some(&auth), - /*runtime*/ None, - /*force_refetch*/ true, - &[], - ), - ) - .await? - .unwrap_err(); - assert!(matches!( - error.downcast_ref::(), - Some(HttpError::Policy(NetworkPolicyDenied::Destination)) - )); - server_handle.abort(); - Ok(()) -} - -#[tokio::test] -async fn app_read_applies_network_policy_to_cached_client_after_reload() -> Result<()> { - let state = BatchServerState::new(json!({ "apps": [] }), "chatgpt-token", "codex"); - let (server_url, server_handle) = start_batch_server(state.clone()).await?; - let home = TempDir::new()?; - write_apps_config(home.path(), &server_url, /*apps_mcp_product_sku*/ None)?; - write_auth(home.path())?; - let mut app = TestAppServer::builder() - .with_codex_home(home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - read_apps(&mut app, vec!["alpha"], /*include_tools*/ false).await?; - assert_eq!(state.requests().len(), 1); - - std::fs::write( - home.path().join("requirements.toml"), - "[application.network]", - )?; - let reload_id = app.send_request("config/read", Some(json!({}))).await?; - let _: Value = timeout(DEFAULT_TIMEOUT, app.read_response(reload_id)).await??; - let request_id = app - .send_apps_read_request(AppsReadParams { - app_ids: vec!["alpha".to_string()], - thread_id: None, - include_tools: false, - }) - .await?; - let error = timeout( - DEFAULT_TIMEOUT, - app.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - assert_eq!( - error.error.message, - "failed to read app metadata: Failed to send request" - ); - assert_eq!(state.requests().len(), 1); - server_handle.abort(); - Ok(()) -} - -#[tokio::test] -async fn app_read_deduplicates_orders_partial_misses_and_reuses_cached_metadata() -> Result<()> { - let access_token = encode_id_token( - &ChatGptIdTokenClaims::new() - .email("external@example.com") - .plan_type("plus") - .chatgpt_account_id("account-123"), - )?; - let mut beta_response = app_response( - "beta", - "Beta", - Some("https://files.openai.com/content?id=beta"), - ); - let beta_icon_dark_url = beta_response - .as_object_mut() - .expect("app response is an object") - .remove("icon_dark_url") - .expect("app response contains icon_dark_url"); - beta_response["icon_url_dark"] = beta_icon_dark_url; - let state = BatchServerState::new( - json!({ - "apps": [ - app_response("alpha", "Alpha", Some("https://files.openai.com/content?id=alpha")), - beta_response, - ] - }), - &access_token, - "tpp", - ); - let (server_url, server_handle) = start_batch_server(state.clone()).await?; - let codex_home = TempDir::new()?; - write_apps_config(codex_home.path(), &server_url, Some("tpp"))?; - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .without_managed_config() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - let login_id = mcp - .send_chatgpt_auth_tokens_login_request( - access_token, - "account-123".to_string(), - Some("plus".to_string()), - ) - .await?; - let login_response: LoginAccountResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(login_id)).await??; - assert_eq!(login_response, LoginAccountResponse::ChatgptAuthTokens {}); - - let raw_response = read_apps_raw( - &mut mcp, - vec!["beta", "missing", "alpha", "beta", "forbidden"], - /*include_tools*/ true, - ) - .await?; - assert_eq!( - raw_response, - json!({ - "apps": [ - metadata_json("beta", "Beta", Some("https://files.openai.com/content?id=beta")), - metadata_json("alpha", "Alpha", Some("https://files.openai.com/content?id=alpha")), - ], - "missingAppIds": ["missing", "forbidden"], - }) - ); - let response: AppsReadResponse = serde_json::from_value(raw_response)?; - assert_eq!( - response, - AppsReadResponse { - apps: vec![ - metadata( - "beta", - "Beta", - Some("https://files.openai.com/content?id=beta") - ), - metadata( - "alpha", - "Alpha", - Some("https://files.openai.com/content?id=alpha") - ), - ], - missing_app_ids: vec!["missing".to_string(), "forbidden".to_string()], - } - ); - assert_eq!( - state.requests(), - vec![json!({ - "app_ids": ["beta", "missing", "alpha", "forbidden"], - "include_tools": true, - })] - ); - - let cached_response = - read_apps(&mut mcp, vec!["alpha", "beta"], /*include_tools*/ true).await?; - assert_eq!( - cached_response, - AppsReadResponse { - apps: vec![ - metadata( - "alpha", - "Alpha", - Some("https://files.openai.com/content?id=alpha") - ), - metadata( - "beta", - "Beta", - Some("https://files.openai.com/content?id=beta") - ), - ], - missing_app_ids: Vec::new(), - } - ); - assert_eq!(state.requests().len(), 1); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn app_read_refetches_metadata_only_cache_entries_when_tools_are_requested() -> Result<()> { - let state = BatchServerState::new( - json!({ - "apps": [app_response("cached", "Cached", /*icon_url*/ None)] - }), - "chatgpt-token", - "codex", - ); - let (server_url, server_handle) = start_batch_server(state.clone()).await?; - let codex_home = TempDir::new()?; - write_apps_config( - codex_home.path(), - &server_url, - /*apps_mcp_product_sku*/ None, - )?; - write_auth(codex_home.path())?; - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .without_managed_config() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - assert_eq!( - read_apps(&mut mcp, vec!["cached"], /*include_tools*/ false).await?, - AppsReadResponse { - apps: vec![metadata_without_tools( - "cached", "Cached", /*icon_url*/ None - )], - missing_app_ids: Vec::new(), - } - ); - assert_eq!( - state.requests(), - vec![json!({ - "app_ids": ["cached"], - "include_tools": false, - })] - ); - - assert_eq!( - read_apps(&mut mcp, vec!["cached"], /*include_tools*/ true).await?, - AppsReadResponse { - apps: vec![metadata("cached", "Cached", /*icon_url*/ None)], - missing_app_ids: Vec::new(), - } - ); - assert_eq!( - state.requests(), - vec![ - json!({ - "app_ids": ["cached"], - "include_tools": false, - }), - json!({ - "app_ids": ["cached"], - "include_tools": true, - }), - ] - ); - - assert_eq!( - read_apps(&mut mcp, vec!["cached"], /*include_tools*/ false).await?, - AppsReadResponse { - apps: vec![metadata_without_tools( - "cached", "Cached", /*icon_url*/ None - )], - missing_app_ids: Vec::new(), - } - ); - assert_eq!( - read_apps(&mut mcp, vec!["cached"], /*include_tools*/ true).await?, - AppsReadResponse { - apps: vec![metadata("cached", "Cached", /*icon_url*/ None)], - missing_app_ids: Vec::new(), - } - ); - assert_eq!(state.requests().len(), 2); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn app_read_thread_id_uses_effective_thread_config() -> Result<()> { - let state = BatchServerState::new( - json!({ - "apps": [app_response("alpha", "Alpha", /*icon_url*/ None)] - }), - "chatgpt-token", - "codex", - ); - let (server_url, server_handle) = start_batch_server(state.clone()).await?; - let codex_home = TempDir::new()?; - write_apps_config( - codex_home.path(), - &server_url, - /*apps_mcp_product_sku*/ None, - )?; - write_auth(codex_home.path())?; - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_managed_config() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - assert_eq!( - read_apps(&mut mcp, vec!["alpha"], /*include_tools*/ false).await?, - AppsReadResponse { - apps: vec![metadata_without_tools( - "alpha", "Alpha", /*icon_url*/ None - )], - missing_app_ids: Vec::new(), - } - ); - - let request_id = mcp - .send_thread_start_request_with_auto_env(ThreadStartParams { - config: Some(HashMap::from([( - "features.connectors".to_string(), - json!(false), - )])), - ..Default::default() - }) - .await?; - let ThreadStartResponse { thread, .. } = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - let request_id = mcp - .send_apps_read_request(AppsReadParams { - app_ids: vec!["alpha".to_string()], - thread_id: Some(thread.id), - include_tools: false, - }) - .await?; - let response: AppsReadResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - assert_eq!( - response, - AppsReadResponse { - apps: Vec::new(), - missing_app_ids: vec!["alpha".to_string()], - } - ); - assert_eq!(state.requests().len(), 1); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn app_read_backend_failure_preserves_fresh_cached_records() -> Result<()> { - let state = BatchServerState::new( - json!({ - "apps": [app_response("cached", "Cached", /*icon_url*/ None)] - }), - "chatgpt-token", - "codex", - ); - let (server_url, server_handle) = start_batch_server(state.clone()).await?; - let codex_home = TempDir::new()?; - write_apps_config( - codex_home.path(), - &server_url, - /*apps_mcp_product_sku*/ None, - )?; - write_auth(codex_home.path())?; - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .without_managed_config() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - assert_eq!( - read_apps(&mut mcp, vec!["cached"], /*include_tools*/ true).await?, - AppsReadResponse { - apps: vec![metadata("cached", "Cached", /*icon_url*/ None)], - missing_app_ids: Vec::new(), - } - ); - state.set_status(StatusCode::INTERNAL_SERVER_ERROR); - - let request_id = mcp - .send_apps_read_request(AppsReadParams { - app_ids: vec!["cached".to_string(), "uncached".to_string()], - thread_id: None, - include_tools: true, - }) - .await?; - let error: JSONRPCError = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - assert!( - error.error.message.contains("failed to read app metadata"), - "unexpected error: {error:?}" - ); - - assert_eq!( - read_apps(&mut mcp, vec!["cached"], /*include_tools*/ true).await?, - AppsReadResponse { - apps: vec![metadata("cached", "Cached", /*icon_url*/ None)], - missing_app_ids: Vec::new(), - } - ); - assert_eq!(state.requests().len(), 2); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn app_read_adds_plugin_display_names_without_starting_mcp() -> Result<()> { - let state = BatchServerState::new( - json!({ - "apps": [ - app_response("alpha", "Alpha", /*icon_url*/ None), - app_response("unclaimed", "Unclaimed", /*icon_url*/ None), - ] - }), - "chatgpt-token", - "codex", - ); - let (server_url, server_handle) = start_batch_server(state.clone()).await?; - let codex_home = TempDir::new()?; - std::fs::write( - codex_home.path().join("config.toml"), - format!( - r#" -chatgpt_base_url = "{server_url}" - -[features] -connectors = true -plugins = true - -[plugins."alpha-z@test"] -enabled = true - -[plugins."alpha-a@test"] -enabled = true - -[plugins."disabled@test"] -enabled = false -"#, - ), - )?; - write_plugin_app(codex_home.path(), "alpha-z", "Alpha Z", "alpha")?; - write_plugin_app(codex_home.path(), "alpha-a", "Alpha A", "alpha")?; - write_plugin_app( - codex_home.path(), - "disabled", - "Disabled Plugin", - "unclaimed", - )?; - write_auth(codex_home.path())?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let response = read_apps( - &mut mcp, - vec!["alpha", "unclaimed"], - /*include_tools*/ false, - ) - .await?; - let mut alpha = metadata_without_tools("alpha", "Alpha", /*icon_url*/ None); - alpha.plugin_display_names = vec!["Alpha A".to_string(), "Alpha Z".to_string()]; - assert_eq!( - response, - AppsReadResponse { - apps: vec![ - alpha, - metadata_without_tools("unclaimed", "Unclaimed", /*icon_url*/ None), - ], - missing_app_ids: Vec::new(), - } - ); - assert_eq!( - state.requests(), - vec![json!({ - "app_ids": ["alpha", "unclaimed"], - "include_tools": false, - })] - ); - assert_eq!(state.mcp_requests(), 0); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn app_read_rejects_more_than_one_hundred_input_ids() -> Result<()> { - let codex_home = TempDir::new()?; - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let request_id = mcp - .send_apps_read_request(AppsReadParams { - app_ids: (0..101).map(|index| format!("app-{index}")).collect(), - thread_id: None, - include_tools: false, - }) - .await?; - let error: JSONRPCError = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.error.message, "app/read accepts at most 100 appIds"); - Ok(()) -} - -async fn read_apps( - mcp: &mut TestAppServer, - app_ids: Vec<&str>, - include_tools: bool, -) -> Result { - Ok(serde_json::from_value( - read_apps_raw(mcp, app_ids, include_tools).await?, - )?) -} - -async fn read_apps_raw( - mcp: &mut TestAppServer, - app_ids: Vec<&str>, - include_tools: bool, -) -> Result { - let request_id = mcp - .send_apps_read_request(AppsReadParams { - app_ids: app_ids.into_iter().map(str::to_string).collect(), - thread_id: None, - include_tools, - }) - .await?; - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await? -} - -fn metadata(id: &str, name: &str, icon_url: Option<&str>) -> ConnectorMetadata { - serde_json::from_value(metadata_json(id, name, icon_url)).expect("valid app metadata JSON") -} - -fn metadata_json(id: &str, name: &str, icon_url: Option<&str>) -> Value { - json!({ - "id": id, - "name": name, - "description": format!("{name} description"), - "iconUrl": icon_url, - "iconUrlDark": format!("https://files.openai.com/content?id={id}-dark"), - "distributionChannel": "ECOSYSTEM_DIRECTORY", - "installUrl": format!("https://chatgpt.com/apps/{}/{id}", name.to_ascii_lowercase()), - "pluginDisplayNames": [], - "toolSummaries": [{ - "name": format!("{id}_tool"), - "title": format!("{name} Tool"), - "description": format!("Use {name}"), - "isEnabled": false, - "disabledReason": "disabled_by_admin", - "isReadOnly": true, - }], - }) -} - -fn metadata_without_tools(id: &str, name: &str, icon_url: Option<&str>) -> ConnectorMetadata { - ConnectorMetadata { - tool_summaries: None, - ..metadata(id, name, icon_url) - } -} - -fn app_response(id: &str, name: &str, icon_url: Option<&str>) -> Value { - let mut response = json!({ - "id": id, - "name": name, - "description": format!("{name} description"), - "icon_url": null, - "icon_dark_url": format!("https://files.openai.com/content?id={id}-dark"), - "distribution_channel": "ECOSYSTEM_DIRECTORY", - "tools": [{ - "name": format!("{id}_tool"), - "title": format!("{name} Tool"), - "description": format!("Use {name}"), - "is_enabled": false, - "disabled_reason": "disabled_by_admin", - "is_read_only": true, - }], - "branding": { - "category": "PRODUCTIVITY", - "developer": "Test Developer", - "website": "https://example.com", - "privacy_policy": "https://example.com/privacy", - "terms_of_service": "https://example.com/terms", - "is_discoverable_app": true, - }, - "app_metadata": { - "review": { "status": "RELEASED" }, - "categories": ["PRODUCTIVITY"], - "sub_categories": ["CALENDAR"], - "seo_description": "Search description", - "screenshots": [{ - "url": "https://example.com/screenshot.png", - "cdn_url": "must-not-escape", - "file_id": "file-1", - "user_prompt": "Use this app", - }], - "developer": "Test Developer", - "version": "1.0.0", - "version_id": "version-1", - "version_notes": "Initial release", - "first_party_requires_install": true, - "show_in_composer_when_unlinked": true, - "subtitle": "must-not-escape", - "mcp_server_instructions": "must-not-escape", - }, - "labels": null, - "actions": [{ "name": "must_not_escape_metadata_boundary" }], - "model_description": "must not escape metadata boundary", - "icon_assets": { "256_square": "must-not-escape" }, - }); - if let Some(icon_url) = icon_url { - response["icon_url"] = json!(icon_url); - } - response -} - -fn write_plugin_app( - codex_home: &Path, - plugin_name: &str, - display_name: &str, - connector_id: &str, -) -> Result<()> { - let plugin_root = codex_home - .join("plugins/cache/test") - .join(plugin_name) - .join("local"); - std::fs::create_dir_all(plugin_root.join(".codex-plugin"))?; - std::fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - serde_json::to_vec(&json!({ - "name": plugin_name, - "interface": { "displayName": display_name }, - }))?, - )?; - std::fs::write( - plugin_root.join(".app.json"), - serde_json::to_vec(&json!({ - "apps": { "app": { "id": connector_id } } - }))?, - )?; - Ok(()) -} - -fn write_apps_config( - codex_home: &Path, - base_url: &str, - apps_mcp_product_sku: Option<&str>, -) -> std::io::Result<()> { - let apps_mcp_product_sku = apps_mcp_product_sku - .map(|product_sku| format!("apps_mcp_product_sku = \"{product_sku}\"\n")) - .unwrap_or_default(); - std::fs::write( - codex_home.join("config.toml"), - format!( - r#" -chatgpt_base_url = "{base_url}" -{apps_mcp_product_sku} - -[features] -connectors = true -"# - ), - ) -} - -fn write_auth(codex_home: &Path) -> Result<()> { - write_chatgpt_auth( - codex_home, - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123") - .plan_type("plus"), - AuthCredentialsStoreMode::File, - ) -} - -#[derive(Clone)] -struct BatchServerState { - requests: Arc>>, - mcp_requests: Arc>, - response: Arc>, - status: Arc>, - access_token: String, - expected_product_sku: String, -} - -impl BatchServerState { - fn new(response: Value, access_token: &str, expected_product_sku: &str) -> Self { - Self { - requests: Arc::new(StdMutex::new(Vec::new())), - mcp_requests: Arc::new(StdMutex::new(0)), - response: Arc::new(StdMutex::new(response)), - status: Arc::new(StdMutex::new(StatusCode::OK)), - access_token: access_token.to_string(), - expected_product_sku: expected_product_sku.to_string(), - } - } - - fn requests(&self) -> Vec { - self.requests - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone() - } - - fn set_status(&self, status: StatusCode) { - *self - .status - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = status; - } - - fn mcp_requests(&self) -> usize { - *self - .mcp_requests - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - } -} - -async fn start_batch_server(state: BatchServerState) -> Result<(String, JoinHandle<()>)> { - let listener = TcpListener::bind("127.0.0.1:0").await?; - let addr = listener.local_addr()?; - let router = Router::new() - .route("/ps/apps/batch", post(batch_apps)) - .route("/api/codex/ps/mcp", any(unexpected_mcp_request)) - .with_state(state); - let handle = tokio::spawn(async move { - let _ = axum::serve(listener, router).await; - }); - Ok((format!("http://{addr}"), handle)) -} - -async fn unexpected_mcp_request(State(state): State) -> StatusCode { - *state - .mcp_requests - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) += 1; - StatusCode::INTERNAL_SERVER_ERROR -} - -async fn batch_apps( - State(state): State, - headers: HeaderMap, - Json(body): Json, -) -> Result, StatusCode> { - let bearer_ok = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .is_some_and(|value| value == format!("Bearer {}", state.access_token)); - let account_ok = headers - .get("chatgpt-account-id") - .and_then(|value| value.to_str().ok()) - .is_some_and(|value| value == "account-123"); - // Rejecting a mismatch makes both the configured override and default fallback observable. - let product_sku_ok = headers - .get("oai-product-sku") - .and_then(|value| value.to_str().ok()) - .is_some_and(|value| value == state.expected_product_sku); - if !bearer_ok || !account_ok || !product_sku_ok { - return Err(StatusCode::UNAUTHORIZED); - } - - let include_tools = body - .get("include_tools") - .and_then(Value::as_bool) - .unwrap_or_default(); - state - .requests - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .push(body); - let status = *state - .status - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if status != StatusCode::OK { - return Err(status); - } - let mut response = state - .response - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone(); - if !include_tools && let Some(apps) = response.get_mut("apps").and_then(Value::as_array_mut) { - for app in apps { - app["tools"] = Value::Null; - } - } - Ok(Json(response)) -} diff --git a/codex-rs/app-server/tests/suite/v2/git_attribution.rs b/codex-rs/app-server/tests/suite/v2/git_attribution.rs deleted file mode 100644 index 73456974..00000000 --- a/codex-rs/app-server/tests/suite/v2/git_attribution.rs +++ /dev/null @@ -1,539 +0,0 @@ -use std::collections::HashMap; -use std::path::Path; -use std::sync::Arc; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; - -use anyhow::Context; -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::TestAppServer; -use app_test_support::create_final_assistant_message_sse_response; -use app_test_support::to_response; -use app_test_support::write_chatgpt_auth; -use app_test_support::write_mock_responses_config_toml_with_chatgpt_base_url; -use codex_app_server_protocol::LoginAccountResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ThreadHistoryMode; -use codex_app_server_protocol::ThreadResumeParams; -use codex_app_server_protocol::ThreadResumeResponse; -use codex_app_server_protocol::ThreadStartParams; -use codex_app_server_protocol::ThreadStartResponse; -use codex_app_server_protocol::TurnStartParams; -use codex_app_server_protocol::UserInput; -use codex_config::types::AuthCredentialsStoreMode; -use codex_protocol::models::ContentItem; -use codex_protocol::models::ResponseItem; -use codex_rollout::RolloutItem; -use core_test_support::responses; -use core_test_support::skip_if_no_network; -use pretty_assertions::assert_eq; -use serde::de::DeserializeOwned; -use serde_json::json; -use tempfile::TempDir; -use test_case::test_case; -use tokio::time::Duration; -use tokio::time::timeout; -use wiremock::Mock; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; - -// macOS and Windows Bazel CI can spend tens of seconds starting app-server -// subprocesses or processing test RPCs under load. -#[cfg(any(target_os = "macos", windows))] -const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(60); -#[cfg(not(any(target_os = "macos", windows)))] -const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10); -const COMMIT_ATTRIBUTION: &str = "Co-authored-by: Codex "; -const PR_ATTRIBUTION: &str = "Generated with [Codex](https://openai.com/codex/)."; -const ATTRIBUTION_DISABLED: &str = "attribution is disabled for the current workspace"; -const LEGACY_COMMIT_ATTRIBUTION_INSTRUCTIONS: &str = "\ -When you write or edit a git commit message, ensure the message ends with this trailer exactly once: -Co-authored-by: Codex - -Rules: -- Keep existing trailers and append this trailer at the end if missing. -- Do not duplicate this trailer if it already exists. -- Keep one blank line between the commit body and trailer block."; - -#[derive(Clone, Copy)] -enum LegacyAttribution { - CommitOnly, - UnlinkedPullRequest, -} - -#[test_case("dual_header", false; "dual_header")] -#[test_case("assertion_only", false; "assertion_only")] -#[test_case("dual_header", true; "dual_header_custom_destination")] -#[test_case("assertion_only", true; "assertion_only_custom_destination")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn git_attribution_runtime_auth_uses_request_destination( - mode: &str, - custom_destination: bool, -) -> Result<()> { - use base64::Engine; - use core_test_support::runtime_auth::PROBE_SERVER; - use core_test_support::runtime_auth::run_harness_through_proxy; - - skip_if_no_network!(Ok(())); - let token = format!( - "e30.{}.c2ln", - base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json!({ - "exp": chrono::Utc::now().timestamp() + 3600, - "session_id": "session-a", "iss": "https://auth.openai.com", - "https://api.openai.com/auth": { - "chatgpt_user_id": "user-123", "chatgpt_account_id": "workspace-enabled", - }, - }))?) - ); - if let Ok(server_url) = std::env::var(PROBE_SERVER) { - let home = TempDir::new()?; - let base_url = if custom_destination { - format!("{server_url}/backend-api") - } else { - "https://chatgpt.com/backend-api".into() - }; - write_mock_responses_config_toml_with_chatgpt_base_url( - home.path(), - &server_url, - &base_url, - )?; - let config_path = home.path().join("config.toml"); - let config = std::fs::read_to_string(&config_path)?; - std::fs::write( - config_path, - format!( - "{config}\n[features.runtime_agent_instances]\nenabled = {}\nmode = {mode:?}\n", - !custom_destination - ), - )?; - write_chatgpt_auth( - home.path(), - ChatGptAuthFixture::new(&token) - .account_id("workspace-enabled") - .chatgpt_user_id("user-123") - .plan_type("enterprise"), - AuthCredentialsStoreMode::File, - )?; - let mut app = TestAppServer::builder() - .with_codex_home(home.path()) - .with_env_overrides(&[("OPENAI_API_KEY", None), ("CODEX_ACCESS_TOKEN", None)]) - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - let id = app - .send_thread_start_request_with_auto_env(ThreadStartParams { - // Extensions retain the harness URL, even when a thread overrides it. - config: Some(HashMap::from([ - ( - "chatgpt_base_url".into(), - json!("https://chatgpt.com/backend-api"), - ), - ( - "features.runtime_agent_instances".into(), - json!({"enabled": true, "mode": mode}), - ), - ])), - ..Default::default() - }) - .await?; - let ThreadStartResponse { thread, .. } = read_response(&mut app, id).await?; - run_turn(&mut app, &thread.id, "Hello").await?; - return Ok(()); - } - - let server = responses::start_mock_server().await; - let response_mock = responses::mount_sse_sequence( - &server, - vec![create_final_assistant_message_sse_response("Done")?], - ) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/config/bundle")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({}))) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/agent/register")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "runtime_agent_instance_id": "runtime-a", "agent_host_id": "host-a", - "actor": {"kind": "chatgpt", "user_id": "user-123", "account_id": "workspace-enabled"}, - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/settings/user")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "commit_attribution_enabled": true, - }))) - .expect(1) - .mount(&server) - .await; - let case = if custom_destination { - format!("{mode}_custom_destination") - } else { - mode.into() - }; - run_harness_through_proxy( - &server, - &format!("suite::v2::git_attribution::git_attribution_runtime_auth_uses_request_destination::{case}"), - /*realtime_target*/ None, - ) - .await?; - - let requests = server - .received_requests() - .await - .context("captured requests")?; - let settings = requests - .iter() - .find(|request| request.url.path() == "/backend-api/wham/settings/user") - .context("git-attribution settings request")?; - let authorization = settings.headers["authorization"].to_str()?; - if custom_destination || mode == "dual_header" { - assert!(authorization.starts_with("Bearer e30.")); - } else { - assert!(authorization.starts_with("AgentAssertion 1.")); - } - assert_eq!( - settings.headers.contains_key("x-openai-agent-assertion"), - !custom_destination && mode == "dual_header", - ); - let model_requests = response_mock.requests(); - assert_eq!(model_requests.len(), 1); - assert!( - model_requests[0] - .message_input_texts("developer") - .join("\n") - .contains(COMMIT_ATTRIBUTION) - ); - server.verify().await; - Ok(()) -} - -#[tokio::test] -async fn git_attribution_follows_authenticated_workspace_policy() -> Result<()> { - skip_if_no_network!(Ok(())); - - let server = responses::start_mock_server().await; - let settings_server = responses::start_mock_server().await; - let response_mock = responses::mount_sse_sequence( - &server, - [ - "Unavailable", - "Recovered", - "Cached", - "After switch", - "After switching back", - ] - .into_iter() - .map(create_final_assistant_message_sse_response) - .collect::>>()?, - ) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/config/bundle")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({}))) - .mount(&server) - .await; - let enabled_settings_requests = Arc::new(AtomicUsize::new(0)); - Mock::given(method("GET")) - .and(path("/backend-api/wham/settings/user")) - .and(header("chatgpt-account-id", "workspace-enabled")) - .respond_with({ - let enabled_settings_requests = enabled_settings_requests.clone(); - move |_request: &wiremock::Request| { - if enabled_settings_requests.fetch_add(1, Ordering::SeqCst) == 0 { - ResponseTemplate::new(503) - } else { - ResponseTemplate::new(200).set_body_json(json!({ - "commit_attribution_enabled": true, - })) - } - } - }) - .expect(3) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/settings/user")) - .and(header("chatgpt-account-id", "workspace-disabled")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "commit_attribution_enabled": false, - }))) - .expect(1) - .mount(&server) - .await; - - let codex_home = TempDir::new()?; - write_mock_responses_config_toml_with_chatgpt_base_url( - codex_home.path(), - &server.uri(), - &format!("{}/backend-api", server.uri()), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("workspace-enabled") - .plan_type("enterprise"), - AuthCredentialsStoreMode::File, - )?; - - let mut app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .with_env_overrides(&[("OPENAI_API_KEY", None), ("CODEX_ACCESS_TOKEN", None)]) - .build() - .await?; - timeout(DEFAULT_READ_TIMEOUT, app_server.initialize()).await??; - - let request_id = app_server - .send_thread_start_request_with_auto_env(ThreadStartParams { - config: Some(HashMap::from([( - "chatgpt_base_url".to_string(), - json!(format!("{}/backend-api", settings_server.uri())), - )])), - history_mode: Some(ThreadHistoryMode::Legacy), - ..Default::default() - }) - .await?; - let ThreadStartResponse { thread, .. } = read_response(&mut app_server, request_id).await?; - run_turn(&mut app_server, &thread.id, "First turn").await?; - run_turn(&mut app_server, &thread.id, "Second turn").await?; - run_turn(&mut app_server, &thread.id, "Third turn").await?; - - let request_id = app_server - .send_chatgpt_auth_tokens_login_request( - "e30.e30.c2ln".to_string(), - "workspace-disabled".to_string(), - Some("enterprise".to_string()), - ) - .await?; - let _: LoginAccountResponse = read_response(&mut app_server, request_id).await?; - run_turn(&mut app_server, &thread.id, "Turn after workspace switch").await?; - - let request_id = app_server - .send_chatgpt_auth_tokens_login_request( - "e30.e30.c2ln".to_string(), - "workspace-enabled".to_string(), - Some("enterprise".to_string()), - ) - .await?; - let _: LoginAccountResponse = read_response(&mut app_server, request_id).await?; - run_turn(&mut app_server, &thread.id, "Turn after switching back").await?; - - let requests = response_mock.requests(); - assert_eq!(requests.len(), 5); - for (request, expected) in requests - .into_iter() - .zip([(0, 0), (1, 0), (1, 0), (1, 1), (2, 1)]) - { - let developer_text = request.message_input_texts("developer").join("\n"); - assert_eq!( - ( - developer_text.matches(COMMIT_ATTRIBUTION).count(), - developer_text.matches(PR_ATTRIBUTION).count(), - developer_text.matches(ATTRIBUTION_DISABLED).count(), - ), - (expected.0, expected.0, expected.1) - ); - } - server.verify().await; - assert!( - settings_server - .received_requests() - .await - .context("failed to fetch thread-override requests")? - .iter() - .all(|request| request.url.path() != "/backend-api/wham/settings/user"), - "attribution settings must use the process-level base URL" - ); - Ok(()) -} - -#[test_case(LegacyAttribution::CommitOnly; "commit_only")] -#[test_case(LegacyAttribution::UnlinkedPullRequest; "unlinked_pull_request")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn cold_resume_replaces_legacy_attribution_without_duplication( - legacy_attribution: LegacyAttribution, -) -> Result<()> { - skip_if_no_network!(Ok(())); - - let server = responses::start_mock_server().await; - let response_mock = responses::mount_sse_sequence( - &server, - ["Initial", "Resumed", "Resumed again"] - .into_iter() - .map(create_final_assistant_message_sse_response) - .collect::>>()?, - ) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/config/bundle")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({}))) - .mount(&server) - .await; - let settings_requests = Arc::new(AtomicUsize::new(0)); - Mock::given(method("GET")) - .and(path("/backend-api/wham/settings/user")) - .and(header("chatgpt-account-id", "workspace-resume")) - .respond_with({ - let settings_requests = Arc::clone(&settings_requests); - move |_request: &wiremock::Request| { - ResponseTemplate::new(200).set_body_json(json!({ - "commit_attribution_enabled": settings_requests - .fetch_add(1, Ordering::SeqCst) - == 0, - })) - } - }) - .expect(2) - .mount(&server) - .await; - - let codex_home = TempDir::new()?; - write_mock_responses_config_toml_with_chatgpt_base_url( - codex_home.path(), - &server.uri(), - &format!("{}/backend-api", server.uri()), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("workspace-resume") - .plan_type("enterprise"), - AuthCredentialsStoreMode::File, - )?; - - let mut app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .with_env_overrides(&[("OPENAI_API_KEY", None), ("CODEX_ACCESS_TOKEN", None)]) - .without_auto_env() - .build() - .await?; - timeout(DEFAULT_READ_TIMEOUT, app_server.initialize()).await??; - let request_id = app_server - .send_thread_start_request(ThreadStartParams::default()) - .await?; - let ThreadStartResponse { thread, .. } = read_response(&mut app_server, request_id).await?; - run_turn(&mut app_server, &thread.id, "persist enabled attribution").await?; - let rollout_path = thread - .path - .context("initial thread should have a rollout path")?; - let status = timeout(DEFAULT_READ_TIMEOUT, app_server.shutdown_gracefully()).await??; - anyhow::ensure!( - status.success(), - "initial app-server did not exit successfully" - ); - replace_attribution_fragment_with_legacy(&rollout_path, legacy_attribution)?; - - let mut app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .with_env_overrides(&[("OPENAI_API_KEY", None), ("CODEX_ACCESS_TOKEN", None)]) - .without_auto_env() - .build() - .await?; - timeout(DEFAULT_READ_TIMEOUT, app_server.initialize()).await??; - let request_id = app_server - .send_thread_resume_request(ThreadResumeParams { - thread_id: thread.id, - ..Default::default() - }) - .await?; - let ThreadResumeResponse { thread, .. } = read_response(&mut app_server, request_id).await?; - run_turn(&mut app_server, &thread.id, "resume disabled attribution").await?; - run_turn(&mut app_server, &thread.id, "continue disabled attribution").await?; - - let requests = response_mock.requests(); - assert_eq!(requests.len(), 3); - let initial_text = requests[0].message_input_texts("developer").join("\n"); - assert_eq!(initial_text.matches(COMMIT_ATTRIBUTION).count(), 1); - assert_eq!(initial_text.matches(PR_ATTRIBUTION).count(), 1); - assert_eq!(initial_text.matches(ATTRIBUTION_DISABLED).count(), 0); - for request in &requests[1..] { - let developer_text = request.message_input_texts("developer").join("\n"); - assert_eq!(developer_text.matches(COMMIT_ATTRIBUTION).count(), 1); - assert_eq!(developer_text.matches(PR_ATTRIBUTION).count(), 0); - assert_eq!(developer_text.matches(ATTRIBUTION_DISABLED).count(), 1); - } - server.verify().await; - Ok(()) -} - -fn replace_attribution_fragment_with_legacy( - rollout_path: &Path, - legacy_attribution: LegacyAttribution, -) -> Result<()> { - let rollout = std::fs::read_to_string(rollout_path)?; - let mut replaced = false; - let mut removed_saved_attribution = false; - let lines = rollout - .lines() - .filter(|line| !line.trim().is_empty()) - .map(|line| { - let mut line = codex_rollout::parse_rollout_line(line)?; - if let RolloutItem::ResponseItem(response_item) = &mut line.item - && let ResponseItem::Message { role, content, .. } = &mut response_item.item - && role == "developer" - { - for item in content { - if let ContentItem::InputText { text } = item - && text.contains("") - { - *text = match legacy_attribution { - LegacyAttribution::CommitOnly => { - LEGACY_COMMIT_ATTRIBUTION_INSTRUCTIONS.to_string() - } - LegacyAttribution::UnlinkedPullRequest => { - text.replace(PR_ATTRIBUTION, "Generated with Codex.") - } - }; - replaced = true; - } - } - } - if let RolloutItem::WorldState(world_state) = &mut line.item - && world_state.state.remove("git_attribution").is_some() - { - removed_saved_attribution = true; - } - serde_json::to_string(&line) - }) - .collect::, _>>()?; - anyhow::ensure!(replaced, "rollout did not contain git attribution context"); - anyhow::ensure!( - removed_saved_attribution, - "rollout did not contain saved git attribution state" - ); - std::fs::write(rollout_path, format!("{}\n", lines.join("\n")))?; - Ok(()) -} - -async fn read_response( - app_server: &mut TestAppServer, - request_id: i64, -) -> Result { - let response = timeout( - DEFAULT_READ_TIMEOUT, - app_server.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - to_response(response) -} - -async fn run_turn(app_server: &mut TestAppServer, thread_id: &str, text: &str) -> Result<()> { - timeout( - DEFAULT_READ_TIMEOUT, - app_server.start_turn_and_wait_for_completion(TurnStartParams { - thread_id: thread_id.to_string(), - input: vec![UserInput::Text { - text: text.to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }), - ) - .await??; - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/v2/mod.rs b/codex-rs/app-server/tests/suite/v2/mod.rs index bb3b8b68..6d76cb3d 100644 --- a/codex-rs/app-server/tests/suite/v2/mod.rs +++ b/codex-rs/app-server/tests/suite/v2/mod.rs @@ -6,9 +6,6 @@ mod account_gcp; mod account_thread_usage; mod agent_message_board; mod analytics; -mod app_installed; -mod app_list; -mod app_read; mod application_network; #[path = "attached_thread_tests.rs"] mod attached_thread; @@ -78,7 +75,6 @@ mod fs; mod gateway_oauth; #[path = "gcp_setup_tests.rs"] mod gcp_setup; -mod git_attribution; mod guardian_v2; mod history_notes_extension; mod hooks_list; @@ -118,18 +114,11 @@ mod plugin_install; mod plugin_list; mod plugin_manifest_cache; mod plugin_read; -mod plugin_reconcile; mod plugin_search; -mod plugin_share; mod plugin_uninstall; mod process_exec; mod projects; -mod rate_limit_reset_credits; -mod rate_limits; -#[path = "rate_limits_identity_tests.rs"] -mod rate_limits_identity; mod realtime_conversation; -mod recommended_plugins; #[cfg(debug_assertions)] mod remote_thread_store; mod request_permissions; diff --git a/codex-rs/app-server/tests/suite/v2/plugin_install.rs b/codex-rs/app-server/tests/suite/v2/plugin_install.rs index 0fafd9cc..19a4327b 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_install.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_install.rs @@ -77,9 +77,6 @@ use wiremock::matchers::method; use wiremock::matchers::path; use wiremock::matchers::query_param; -#[path = "plugin_runtime_auth.rs"] -mod runtime_auth_tests; - // Plugin install tests wait on connector discovery after the install response path // starts, which is noticeably slower on Windows CI. const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60); diff --git a/codex-rs/app-server/tests/suite/v2/plugin_reconcile.rs b/codex-rs/app-server/tests/suite/v2/plugin_reconcile.rs deleted file mode 100644 index 0b65e2b2..00000000 --- a/codex-rs/app-server/tests/suite/v2/plugin_reconcile.rs +++ /dev/null @@ -1,332 +0,0 @@ -//! Exercises blocking plugin reconciliation through the public JSON-RPC API. - -use std::time::Duration; - -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::MockResponsesConfig; -use app_test_support::TestAppServer; -use app_test_support::write_chatgpt_auth; -use codex_app_server_protocol::PluginReconcileChangedPlugin; -use codex_app_server_protocol::PluginReconcileResponse; -use codex_app_server_protocol::TurnStartParams; -use codex_app_server_protocol::TurnStatus; -use codex_app_server_protocol::UserInput; -use codex_config::types::AuthCredentialsStoreMode; -use codex_features::Feature; -use core_test_support::responses; -use flate2::Compression; -use flate2::write::GzEncoder; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use tempfile::TempDir; -use test_case::test_case; -use tokio::time::timeout; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; - -use super::analytics::wait_for_matching_analytics_event; - -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30); -const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_00000000000000000000000000000000"; - -#[test_case("WORKSPACE", "workspace-directory"; "workspace")] -#[test_case("GLOBAL", "openai-curated-remote"; "global")] -#[tokio::test] -async fn plugin_reconcile_syncs_bundles_and_reports_changes( - scope: &str, - marketplace: &str, -) -> Result<()> { - let server = MockServer::start().await; - // Both scopes must retain background-sync behavior with remote_plugin disabled. - let (mut app_server, codex_home) = start_app_server(&server).await?; - let thread = app_server.start_thread(Default::default()).await?.thread; - let bundle_url = format!("{}/bundle", server.uri()); - let plugin_id = format!("linear@{marketplace}"); - let first = PluginReconcileChangedPlugin { - id: plugin_id.clone(), - has_mcps: true, - has_apps: false, - has_hooks: true, - has_skills: true, - }; - let second = PluginReconcileChangedPlugin { - id: plugin_id.clone(), - has_mcps: false, - has_apps: true, - has_hooks: false, - has_skills: false, - }; - let updated = PluginReconcileChangedPlugin { - id: plugin_id, - has_mcps: true, - has_apps: true, - has_hooks: true, - has_skills: true, - }; - let failed_id = "plugins~Plugin_11111111111111111111111111111111"; - let mut missing_bundle = installed_plugin("1.0.0", &bundle_url, "WORKSPACE"); - missing_bundle["id"] = json!(failed_id); - missing_bundle["name"] = json!("missing-bundle"); - missing_bundle["release"]["bundle_download_url"] = Value::Null; - let mut first_pass_failure = Some(missing_bundle); - - // v1.1 drops hooks; v2 restores them and drops Apps. Both updates must report - // both sides, while uninstall below reports only v2's remaining capabilities. - // Enablement changes report cached capabilities without downloading the bundle again. - for (version, enabled, capabilities, expected_plugins, expected_downloads) in [ - ("1.0.0", true, &first, vec![first.clone()], 1), - ("1.0.0", true, &first, Vec::new(), 0), - ("1.0.0", false, &first, vec![first.clone()], 0), - ("1.0.0", true, &first, vec![first.clone()], 0), - ("1.1.0", true, &second, vec![updated.clone()], 1), - ("2.0.0", true, &first, vec![updated], 1), - ] { - let mut files = vec![( - ".codex-plugin/plugin.json", - json!({"name": "linear"}).to_string(), - )]; - if capabilities.has_mcps { - files.push(( - ".mcp.json", - json!({"mcpServers": {"example": {"command": "unused", "enabled": false}}}) - .to_string(), - )); - } - if capabilities.has_apps { - files.push(( - ".app.json", - json!({"apps": {"example": {"id": "connector_example"}}}).to_string(), - )); - } - if capabilities.has_hooks { - files.push(( - "hooks/hooks.json", - json!({"hooks": {"UserPromptSubmit": [{"hooks": [{ - "type": "command", "command": format!("echo hook {version}") - }]}]}}) - .to_string(), - )); - } - if capabilities.has_skills { - files.push(( - "skills/example/SKILL.md", - "---\nname: example\ndescription: Example skill\n---\nExample skill".to_string(), - )); - } - let mut archive = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::default())); - for (path, contents) in files { - let mut header = tar::Header::new_gnu(); - header.set_size(contents.len() as u64); - header.set_mode(/*mode*/ 0o644); - header.set_cksum(); - archive.append_data(&mut header, path, contents.as_bytes())?; - } - let bundle = archive.into_inner()?.finish()?; - let mut plugin = installed_plugin(version, &bundle_url, scope); - plugin["enabled"] = json!(enabled); - let mut plugins = vec![plugin]; - let mut failures = Vec::new(); - if let Some(failure) = first_pass_failure.take() { - plugins.push(failure); - failures.push(failed_id.to_string()); - } - let expected = PluginReconcileResponse { - changed_plugins: expected_plugins, - failed_remote_plugin_ids: failures.clone(), - failed_materialization_remote_plugin_ids: failures, - }; - let active_plugin_ids = if enabled { - vec![REMOTE_PLUGIN_ID.to_string()] - } else { - Vec::new() - }; - mount_installed_snapshot(&server, plugins).await; - Mock::given(method("GET")) - .and(path("/bundle")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(bundle)) - .expect(expected_downloads) - .mount(&server) - .await; - assert_eq!(reconcile(&mut app_server).await?, expected); - // A turn exercises the loaded registry, not fresh hooks/list discovery. Hooks run - // on the app-server host even when the thread uses a remote executor. - assert_eq!( - turn_hook_runs( - &mut app_server, - &server, - thread.id.clone(), - active_plugin_ids - ) - .await?, - usize::from(scope == "WORKSPACE" && enabled && capabilities.has_hooks), - ); - server.verify().await; - server.reset().await; - } - - // Uninstall must report removed capabilities and stop already-loaded hooks. - mount_installed_snapshot(&server, Vec::new()).await; - assert_eq!( - reconcile(&mut app_server).await?, - PluginReconcileResponse { - changed_plugins: vec![first], - ..Default::default() - } - ); - assert_eq!( - turn_hook_runs(&mut app_server, &server, thread.id.clone(), Vec::new()).await?, - 0 - ); - server.verify().await; - server.reset().await; - - // The next RPC must honor the latest config without contacting the plugin service. - let config_path = codex_home.path().join("config.toml"); - let config = std::fs::read_to_string(&config_path)?; - std::fs::write( - config_path, - config.replace("plugins = true", "plugins = false"), - )?; - assert_eq!( - reconcile(&mut app_server).await?, - PluginReconcileResponse::default() - ); - let requests = server.received_requests().await.expect("recorded requests"); - assert!(requests.iter().all(|request| { - !request.url.path().starts_with("/backend-api/ps/plugins/") - && request.url.path() != "/bundle" - })); - Ok(()) -} - -async fn turn_hook_runs( - app_server: &mut TestAppServer, - server: &MockServer, - thread_id: String, - active_plugin_ids: Vec, -) -> Result { - Mock::given(method("POST")) - .and(path("/backend-api/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(200)) - .mount(server) - .await; - let _response = responses::mount_sse_once( - server, - responses::sse(vec![ - responses::ev_response_created("response"), - responses::ev_completed("response"), - ]), - ) - .await; - app_server.clear_message_buffer(); - let completed = timeout( - DEFAULT_TIMEOUT, - app_server.start_turn_and_wait_for_completion(TurnStartParams { - thread_id: thread_id.clone(), - input: vec![UserInput::Text { - text: "run hooks".to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }), - ) - .await??; - assert_eq!(completed.turn.status, TurnStatus::Completed); - let event = wait_for_matching_analytics_event(server, DEFAULT_TIMEOUT, |event| { - event["event_type"] == "codex_turn_event" - && event["event_params"]["turn_id"] == completed.turn.id - }) - .await?; - assert_eq!(event["event_params"]["thread_id"], thread_id); - assert_eq!( - event["event_params"]["active_plugin_ids_at_turn_start"], - json!(active_plugin_ids) - ); - Ok(app_server - .pending_notification_methods() - .iter() - .filter(|method| method.as_str() == "hook/started") - .count()) -} - -async fn reconcile(app_server: &mut TestAppServer) -> Result { - let request = app_server - .send_raw_request( - "plugin/reconcile", - Some(json!({"reason": "tooling_changed"})), - ) - .await?; - timeout(DEFAULT_TIMEOUT, app_server.read_response(request)).await? -} - -async fn start_app_server(server: &MockServer) -> Result<(TestAppServer, TempDir)> { - let codex_home = TempDir::new()?; - let base_url = format!("{}/backend-api/", server.uri()); - MockResponsesConfig::new(&server.uri()) - .with_root_config(&format!("chatgpt_base_url = \"{base_url}\"")) - .disable_feature(Feature::Apps) - .enable_feature(Feature::Plugins) - .enable_feature(Feature::CodexHooks) - .disable_feature(Feature::RemotePlugin) - .disable_feature(Feature::PluginSharing) - .write(codex_home.path())?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - let app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_managed_config() - .with_env_overrides(&[( - "CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS", - Some("1"), - )]) - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - Ok((app_server, codex_home)) -} - -async fn mount_installed_snapshot(server: &MockServer, plugins: Vec) { - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("includeDownloadUrls", "true")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": plugins, - "pagination": { "limit": 200, "next_page_token": null }, - }))) - .expect(1) - .mount(server) - .await; -} - -fn installed_plugin(version: &str, bundle_url: &str, scope: &str) -> Value { - json!({ - "id": REMOTE_PLUGIN_ID, - "name": "linear", - "scope": scope, - "discoverability": (scope == "WORKSPACE").then_some("LISTED"), - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "release": { - "version": version, - "display_name": "Linear", - "description": "Track work in Linear", - "bundle_download_url": bundle_url, - "interface": {}, - }, - "enabled": true, - }) -} diff --git a/codex-rs/app-server/tests/suite/v2/plugin_runtime_auth.rs b/codex-rs/app-server/tests/suite/v2/plugin_runtime_auth.rs deleted file mode 100644 index 0732ffb6..00000000 --- a/codex-rs/app-server/tests/suite/v2/plugin_runtime_auth.rs +++ /dev/null @@ -1,194 +0,0 @@ -//! Cover direct plugin mutations when runtime authentication is enabled after startup. - -use super::*; -use anyhow::Context; -use base64::Engine; -use codex_app_server_protocol::PluginUninstallParams; -use codex_app_server_protocol::PluginUninstallResponse; -use core_test_support::runtime_auth::PROBE_SERVER; -use core_test_support::runtime_auth::run_harness_through_proxy; -use pretty_assertions::assert_eq; -use test_case::test_case; - -#[test_case("dual_header", "install"; "install_dual_header")] -#[test_case("assertion_only", "install"; "install_assertion_only")] -#[test_case("dual_header", "uninstall"; "uninstall_dual_header")] -#[test_case("assertion_only", "uninstall"; "uninstall_assertion_only")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn direct_mutation_initializes_runtime_after_config_reload( - mode: &str, - operation: &str, -) -> Result<()> { - core_test_support::skip_if_no_network!(Ok(())); - let token = format!( - "e30.{}.c2ln", - base64::engine::general_purpose::URL_SAFE_NO_PAD.encode( - json!({ - "exp": 4_102_444_800_u64, - "session_id": "session-a", - "iss": "https://auth.openai.com", - "https://api.openai.com/auth": { - "chatgpt_user_id": "user-123", "chatgpt_account_id": "account-123", - }, - }) - .to_string() - ) - ); - if std::env::var(PROBE_SERVER).is_ok() { - let home = TempDir::new()?; - write_chatgpt_auth( - home.path(), - ChatGptAuthFixture::new(&token) - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - write_remote_plugin_catalog_config(home.path(), "https://chatgpt.com/backend-api")?; - let config_path = home.path().join("config.toml"); - let initial = std::fs::read_to_string(&config_path)?; - std::fs::write( - &config_path, - format!( - "{initial}\n[features.runtime_agent_instances]\nenabled = false\nmode = {mode:?}\n" - ), - )?; - let mut app = TestAppServer::builder() - .with_codex_home(home.path()) - .without_auto_env() - .with_env_overrides(&[ - ("OPENAI_API_KEY", None), - ("CODEX_ACCESS_TOKEN", None), - (TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS, Some("1")), - ]) - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - std::fs::write( - &config_path, - format!( - "{initial}\n[features.runtime_agent_instances]\nenabled = true\nmode = {mode:?}\n" - ), - )?; - let cache = home - .path() - .join("plugins/cache/openai-curated-remote/linear"); - match operation { - "install" => { - let id = send_remote_plugin_install_request(&mut app, REMOTE_PLUGIN_ID).await?; - let response: PluginInstallResponse = - timeout(DEFAULT_TIMEOUT, app.read_response(id)).await??; - assert_eq!( - response, - PluginInstallResponse { - auth_policy: PluginAuthPolicy::OnUse, - apps_needing_auth: Vec::new(), - } - ); - assert!(cache.join("1.2.3/.codex-plugin/plugin.json").is_file()); - } - "uninstall" => { - std::fs::create_dir_all(cache.join("1.2.3/.codex-plugin"))?; - std::fs::write( - cache.join("1.2.3/.codex-plugin/plugin.json"), - r#"{"name":"linear","version":"1.2.3"}"#, - )?; - let id = app - .send_plugin_uninstall_request(PluginUninstallParams { - plugin_id: REMOTE_PLUGIN_ID.into(), - }) - .await?; - let response: PluginUninstallResponse = - timeout(DEFAULT_TIMEOUT, app.read_response(id)).await??; - assert_eq!(response, PluginUninstallResponse {}); - assert!(!cache.exists()); - } - _ => unreachable!("test operation"), - } - return Ok(()); - } - - let server = MockServer::start().await; - let bundle = mount_remote_plugin_bundle( - &server, - /*status_code*/ 200, - remote_plugin_bundle_tar_gz_bytes("linear")?, - ) - .await; - Mock::given(method("POST")) - .and(path("/agent/register")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "runtime_agent_instance_id": "runtime-a", "agent_host_id": "host-a", - "actor": {"kind": "chatgpt", "user_id": "user-123", "account_id": "account-123"}, - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path(format!("/backend-api/ps/plugins/{REMOTE_PLUGIN_ID}"))) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "id": REMOTE_PLUGIN_ID, "name": "linear", "scope": "GLOBAL", - "installation_policy": "AVAILABLE", "authentication_policy": "ON_USE", "status": "ENABLED", - "release": { - "version": "1.2.3", "bundle_download_url": bundle, "display_name": "Linear", - "description": "Track work in Linear.", - "app_ids": [], "interface": {}, "skills": [], - }, - }))) - .expect(1) - .mount(&server).await; - Mock::given(method("POST")) - .and(path(format!( - "/backend-api/ps/plugins/{REMOTE_PLUGIN_ID}/{operation}" - ))) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "id": REMOTE_PLUGIN_ID, "enabled": operation == "install", - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [], "pagination": {"limit": 50, "next_page_token": null}, - }))) - .mount(&server) - .await; - run_harness_through_proxy( - &server, - &format!("suite::v2::plugin_install::runtime_auth_tests::direct_mutation_initializes_runtime_after_config_reload::{operation}_{mode}"), - /*realtime_target*/ None, - ).await?; - let requests = server - .received_requests() - .await - .context("recorded requests")?; - let plugin_requests = requests - .iter() - .filter(|request| { - request - .url - .path() - .starts_with(&format!("/backend-api/ps/plugins/{REMOTE_PLUGIN_ID}")) - }) - .collect::>(); - assert_eq!(plugin_requests.len(), 2); - for request in plugin_requests { - let proof = if mode == "dual_header" { - assert_eq!(request.headers["authorization"], format!("Bearer {token}")); - request.headers["x-openai-agent-assertion"].to_str()? - } else { - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - request.headers["authorization"] - .to_str()? - .strip_prefix("AgentAssertion ") - .context("assertion auth")? - }; - let claims: serde_json::Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(proof.split('.').nth(2).context("assertion payload")?)?, - )?; - assert_eq!(claims["runtime_agent_instance"], "runtime-a"); - } - server.verify().await; - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/v2/plugin_share.rs b/codex-rs/app-server/tests/suite/v2/plugin_share.rs deleted file mode 100644 index 06ca0a58..00000000 --- a/codex-rs/app-server/tests/suite/v2/plugin_share.rs +++ /dev/null @@ -1,1550 +0,0 @@ -use std::path::Path; -use std::path::PathBuf; -use std::time::Duration; - -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::TestAppServer; -use app_test_support::write_chatgpt_auth; -use codex_app_server_protocol::JSONRPCError; -use codex_app_server_protocol::PluginAuthPolicy; -use codex_app_server_protocol::PluginInstallPolicy; -use codex_app_server_protocol::PluginInterface; -use codex_app_server_protocol::PluginListParams; -use codex_app_server_protocol::PluginListResponse; -use codex_app_server_protocol::PluginShareCheckoutResponse; -use codex_app_server_protocol::PluginShareContext; -use codex_app_server_protocol::PluginShareDeleteResponse; -use codex_app_server_protocol::PluginShareDiscoverability; -use codex_app_server_protocol::PluginShareListItem; -use codex_app_server_protocol::PluginShareListResponse; -use codex_app_server_protocol::PluginSharePrincipal; -use codex_app_server_protocol::PluginSharePrincipalRole; -use codex_app_server_protocol::PluginSharePrincipalType; -use codex_app_server_protocol::PluginShareSaveResponse; -use codex_app_server_protocol::PluginShareUpdateTargetsResponse; -use codex_app_server_protocol::PluginSource; -use codex_app_server_protocol::PluginSummary; -use codex_app_server_protocol::RequestId; -use codex_config::types::AuthCredentialsStoreMode; -use codex_utils_absolute_path::AbsolutePathBuf; -use flate2::Compression; -use flate2::write::GzEncoder; -use pretty_assertions::assert_eq; -use serde_json::json; -use tempfile::TempDir; -use tokio::time::timeout; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::body_json; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; - -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30); -const TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS: &str = - "CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS"; - -#[tokio::test] -async fn plugin_share_save_uploads_local_plugin() -> Result<()> { - let codex_home = TempDir::new()?; - let plugin_root = TempDir::new()?; - let plugin_path = write_test_plugin(plugin_root.path(), "demo-plugin")?; - let server = MockServer::start().await; - write_remote_plugin_config(codex_home.path(), &format!("{}/backend-api", server.uri()))?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - write_corrupt_plugin_share_local_path_mapping(codex_home.path())?; - - Mock::given(method("POST")) - .and(path("/backend-api/public/plugins/workspace/upload-url")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(201).set_body_json(json!({ - "file_id": "file_123", - "upload_url": format!("{}/upload/file_123", server.uri()), - "etag": "\"upload_etag_123\"", - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path("/upload/file_123")) - .and(header("x-ms-blob-type", "BlockBlob")) - .and(header("content-type", "application/gzip")) - .respond_with(ResponseTemplate::new(201).insert_header("etag", "\"blob_etag_123\"")) - .expect(1) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/backend-api/public/plugins/workspace")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .and(body_json(json!({ - "file_id": "file_123", - "etag": "\"upload_etag_123\"", - }))) - .respond_with(ResponseTemplate::new(201).set_body_json(json!({ - "plugin_id": "plugins_123", - "share_url": "https://chatgpt.example/plugins/share/share-key-1", - "can_publish_to_workspace": true, - }))) - .expect(1) - .mount(&server) - .await; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - let expected_plugin_path = AbsolutePathBuf::try_from(plugin_path.clone())?; - let request_id = mcp - .send_raw_request( - "plugin/share/save", - Some(json!({ - "pluginPath": expected_plugin_path.clone(), - })), - ) - .await?; - - let response: PluginShareSaveResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - - assert_eq!( - response, - PluginShareSaveResponse { - remote_plugin_id: "plugins_123".to_string(), - share_url: "https://chatgpt.example/plugins/share/share-key-1".to_string(), - can_publish_to_workspace: Some(true), - } - ); - - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/workspace/created")) - .and(query_param("limit", "200")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [remote_plugin_json("plugins_123")], - "pagination": empty_pagination_json(), - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("scope", "WORKSPACE")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [installed_remote_plugin_json("plugins_123")], - "pagination": empty_pagination_json(), - }))) - .expect(1) - .mount(&server) - .await; - - let request_id = mcp - .send_raw_request("plugin/share/list", Some(json!({}))) - .await?; - let response: PluginShareListResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - - assert_eq!( - response, - PluginShareListResponse { - data: vec![PluginShareListItem { - plugin: PluginSummary { - id: "demo-plugin@workspace-shared-with-me".to_string(), - remote_plugin_id: Some("plugins_123".to_string()), - version: Some("0.1.0".to_string()), - local_version: Some("0.1.0".to_string()), - name: "demo-plugin".to_string(), - share_context: Some(expected_share_context("plugins_123")), - source: PluginSource::Remote, - installed: true, - installed_at: None, - enabled: true, - install_policy: PluginInstallPolicy::Available, - install_policy_source: None, - must_show_installation_interstitial: Some(false), - auth_policy: PluginAuthPolicy::OnUse, - availability: codex_app_server_protocol::PluginAvailability::Available, - disabled_reason: None, - eligible_plan_types: None, - interface: Some(expected_plugin_interface()), - keywords: Vec::new(), - }, - local_plugin_path: Some(expected_plugin_path), - }], - } - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_share_save_forwards_access_policy() -> Result<()> { - let codex_home = TempDir::new()?; - let plugin_root = TempDir::new()?; - let plugin_path = write_test_plugin(plugin_root.path(), "demo-plugin")?; - let server = MockServer::start().await; - write_remote_plugin_config(codex_home.path(), &format!("{}/backend-api", server.uri()))?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - Mock::given(method("POST")) - .and(path("/backend-api/public/plugins/workspace/upload-url")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(201).set_body_json(json!({ - "file_id": "file_123", - "upload_url": format!("{}/upload/file_123", server.uri()), - "etag": "\"upload_etag_123\"", - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path("/upload/file_123")) - .respond_with(ResponseTemplate::new(201).insert_header("etag", "\"blob_etag_123\"")) - .expect(1) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/backend-api/public/plugins/workspace")) - .and(body_json(json!({ - "file_id": "file_123", - "etag": "\"upload_etag_123\"", - "discoverability": "UNLISTED", - "share_targets": [ - { - "principal_type": "user", - "principal_id": "user-1", - "role": "editor", - }, - { - "principal_type": "workspace", - "principal_id": "account-123", - "role": "reader", - }, - ], - }))) - .respond_with(ResponseTemplate::new(201).set_body_json(json!({ - "plugin_id": "plugins_123", - "share_url": "https://chatgpt.example/plugins/share/share-key-1", - }))) - .expect(1) - .mount(&server) - .await; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - let expected_plugin_path = AbsolutePathBuf::try_from(plugin_path)?; - let request_id = mcp - .send_raw_request( - "plugin/share/save", - Some(json!({ - "pluginPath": expected_plugin_path, - "discoverability": "UNLISTED", - "shareTargets": [ - { - "principalType": "user", - "principalId": "user-1", - "role": "editor", - }, - ], - })), - ) - .await?; - - let response: PluginShareSaveResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - - assert_eq!( - response, - PluginShareSaveResponse { - remote_plugin_id: "plugins_123".to_string(), - share_url: "https://chatgpt.example/plugins/share/share-key-1".to_string(), - can_publish_to_workspace: None, - } - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_share_save_rejects_listed_discoverability() -> Result<()> { - let codex_home = TempDir::new()?; - let plugin_root = TempDir::new()?; - let plugin_path = write_test_plugin(plugin_root.path(), "demo-plugin")?; - let server = MockServer::start().await; - write_remote_plugin_config(codex_home.path(), &format!("{}/backend-api", server.uri()))?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - let request_id = mcp - .send_raw_request( - "plugin/share/save", - Some(json!({ - "pluginPath": AbsolutePathBuf::try_from(plugin_path)?, - "discoverability": "LISTED", - })), - ) - .await?; - - let error: JSONRPCError = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.error.code, -32600); - assert_eq!( - error.error.message, - "discoverability LISTED is not supported for plugin/share/save; use UNLISTED or PRIVATE" - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_share_save_rejects_when_plugin_sharing_disabled() -> Result<()> { - let codex_home = TempDir::new()?; - let plugin_root = TempDir::new()?; - let plugin_path = write_test_plugin(plugin_root.path(), "demo-plugin")?; - let server = MockServer::start().await; - std::fs::write( - codex_home.path().join("config.toml"), - format!( - r#" -chatgpt_base_url = "{}/backend-api" - -[features] -plugins = true -plugin_sharing = false -"#, - server.uri() - ), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - let request_id = mcp - .send_raw_request( - "plugin/share/save", - Some(json!({ - "pluginPath": AbsolutePathBuf::try_from(plugin_path)?, - })), - ) - .await?; - - let error: JSONRPCError = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.error.code, -32600); - assert_eq!(error.error.message, "plugin sharing is disabled"); - assert!( - server - .received_requests() - .await - .expect("wiremock should record requests") - .iter() - .all(|request| request.url.path() == "/backend-api/wham/accounts/check") - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_share_rejects_workspace_targets_from_client() -> Result<()> { - let codex_home = TempDir::new()?; - let plugin_root = TempDir::new()?; - let plugin_path = write_test_plugin(plugin_root.path(), "demo-plugin")?; - let server = MockServer::start().await; - write_remote_plugin_config(codex_home.path(), &format!("{}/backend-api", server.uri()))?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - let request_id = mcp - .send_raw_request( - "plugin/share/save", - Some(json!({ - "pluginPath": AbsolutePathBuf::try_from(plugin_path)?, - "discoverability": "UNLISTED", - "shareTargets": [ - { - "principalType": "workspace", - "principalId": "account-123", - "role": "reader", - }, - ], - })), - ) - .await?; - - let error: JSONRPCError = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.error.code, -32600); - assert_eq!( - error.error.message, - "shareTargets cannot include workspace principals; use discoverability UNLISTED for workspace link access" - ); - - let request_id = mcp - .send_raw_request( - "plugin/share/updateTargets", - Some(json!({ - "remotePluginId": "plugins_123", - "discoverability": "UNLISTED", - "shareTargets": [ - { - "principalType": "workspace", - "principalId": "account-123", - "role": "reader", - }, - ], - })), - ) - .await?; - - let error: JSONRPCError = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.error.code, -32600); - assert_eq!( - error.error.message, - "shareTargets cannot include workspace principals; use discoverability UNLISTED for workspace link access" - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_share_save_rejects_access_policy_for_existing_plugin() -> Result<()> { - let codex_home = TempDir::new()?; - let plugin_root = TempDir::new()?; - let plugin_path = write_test_plugin(plugin_root.path(), "demo-plugin")?; - let server = MockServer::start().await; - write_remote_plugin_config(codex_home.path(), &format!("{}/backend-api", server.uri()))?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - let request_id = mcp - .send_raw_request( - "plugin/share/save", - Some(json!({ - "pluginPath": AbsolutePathBuf::try_from(plugin_path)?, - "remotePluginId": "plugins_123", - "discoverability": "PRIVATE", - "shareTargets": [ - { - "principalType": "user", - "principalId": "user-1", - "role": "reader", - }, - ], - })), - ) - .await?; - - let error: JSONRPCError = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.error.code, -32600); - assert_eq!( - error.error.message, - "discoverability and shareTargets are only supported when creating a plugin share; use plugin/share/updateTargets to update share settings" - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_share_list_returns_created_workspace_plugins() -> Result<()> { - let codex_home = TempDir::new()?; - let server = MockServer::start().await; - write_remote_plugin_config(codex_home.path(), &format!("{}/backend-api", server.uri()))?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/workspace/created")) - .and(query_param("limit", "200")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [remote_plugin_json("plugins_123")], - "pagination": empty_pagination_json(), - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("scope", "WORKSPACE")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [installed_remote_plugin_json("plugins_123")], - "pagination": empty_pagination_json(), - }))) - .expect(1) - .mount(&server) - .await; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - let request_id = mcp - .send_raw_request("plugin/share/list", Some(json!({}))) - .await?; - - let response: PluginShareListResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - - assert_eq!( - response, - PluginShareListResponse { - data: vec![PluginShareListItem { - plugin: PluginSummary { - id: "demo-plugin@workspace-shared-with-me".to_string(), - remote_plugin_id: Some("plugins_123".to_string()), - version: Some("0.1.0".to_string()), - local_version: Some("0.1.0".to_string()), - name: "demo-plugin".to_string(), - share_context: Some(expected_share_context("plugins_123")), - source: PluginSource::Remote, - installed: true, - installed_at: None, - enabled: true, - install_policy: PluginInstallPolicy::Available, - install_policy_source: None, - must_show_installation_interstitial: Some(false), - auth_policy: PluginAuthPolicy::OnUse, - availability: codex_app_server_protocol::PluginAvailability::Available, - disabled_reason: None, - eligible_plan_types: None, - interface: Some(expected_plugin_interface()), - keywords: Vec::new(), - }, - local_plugin_path: None, - }], - } - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_share_checkout_adds_personal_marketplace_entry() -> Result<()> { - let codex_home = TempDir::new()?; - let home = TempDir::new()?; - let server = MockServer::start().await; - write_remote_plugin_config(codex_home.path(), &format!("{}/backend-api", server.uri()))?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let bundle_url = mount_remote_plugin_bundle( - &server, - "demo-plugin", - remote_plugin_bundle_tar_gz_bytes("demo-plugin")?, - ) - .await; - mount_remote_plugin_detail_with_bundle( - &server, - "plugins_123", - "demo-plugin", - &bundle_url, - "WORKSPACE", - ) - .await; - mount_empty_remote_installed_plugins(&server, "WORKSPACE").await; - - let home_env = home.path().to_string_lossy().into_owned(); - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .with_env_overrides(&[ - ("HOME", Some(home_env.as_str())), - ("USERPROFILE", Some(home_env.as_str())), - (TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS, Some("1")), - ]) - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let request_id = mcp - .send_raw_request( - "plugin/share/checkout", - Some(json!({ - "remotePluginId": "plugins_123", - })), - ) - .await?; - let response: PluginShareCheckoutResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - - let plugin_path = AbsolutePathBuf::try_from(home.path().join("plugins/demo-plugin"))?; - let marketplace_path = - AbsolutePathBuf::try_from(home.path().join(".agents/plugins/marketplace.json"))?; - assert_eq!( - response, - PluginShareCheckoutResponse { - remote_plugin_id: "plugins_123".to_string(), - plugin_id: "demo-plugin@codex-curated".to_string(), - plugin_name: "demo-plugin".to_string(), - plugin_path: plugin_path.clone(), - marketplace_name: "codex-curated".to_string(), - marketplace_path: marketplace_path.clone(), - remote_version: Some("1.2.3".to_string()), - } - ); - assert!( - plugin_path - .as_path() - .join(".codex-plugin/plugin.json") - .is_file() - ); - - let marketplace: serde_json::Value = - serde_json::from_str(&std::fs::read_to_string(marketplace_path.as_path())?)?; - assert_eq!( - marketplace, - json!({ - "name": "codex-curated", - "interface": { - "displayName": "Personal", - }, - "plugins": [ - { - "name": "demo-plugin", - "source": { - "source": "local", - "path": "./plugins/demo-plugin", - }, - "policy": { - "installation": "AVAILABLE", - "authentication": "ON_USE", - }, - }, - ], - }) - ); - - let mapping: serde_json::Value = serde_json::from_str(&std::fs::read_to_string( - codex_home - .path() - .join(".tmp/plugin-share-local-paths-v1.json"), - )?)?; - assert_eq!( - mapping, - json!({ - "localPluginPathsByRemotePluginId": { - "plugins_123": plugin_path.clone(), - }, - }) - ); - - let request_id = mcp - .send_plugin_list_request(PluginListParams { - cwds: None, - marketplace_kinds: Some(vec![ - codex_app_server_protocol::PluginListMarketplaceKind::Local, - ]), - force_refetch: false, - }) - .await?; - let response: PluginListResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - assert_eq!(response.marketplaces.len(), 1); - assert_eq!(response.marketplaces[0].name, "codex-curated"); - assert_eq!(response.marketplaces[0].plugins[0].name, "demo-plugin"); - assert_eq!( - response.marketplaces[0].plugins[0] - .share_context - .as_ref() - .map(|context| context.remote_plugin_id.as_str()), - Some("plugins_123") - ); - - std::fs::write(plugin_path.as_path().join("local-edit.txt"), "keep")?; - let request_id = mcp - .send_raw_request( - "plugin/share/checkout", - Some(json!({ - "remotePluginId": "plugins_123", - })), - ) - .await?; - let response: PluginShareCheckoutResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - assert_eq!(response.plugin_path, plugin_path); - assert_eq!( - std::fs::read_to_string(plugin_path.as_path().join("local-edit.txt"))?, - "keep" - ); - - Ok(()) -} - -#[tokio::test] -async fn plugin_share_checkout_rejects_non_share_remote_plugin() -> Result<()> { - let codex_home = TempDir::new()?; - let home = TempDir::new()?; - let server = MockServer::start().await; - write_remote_plugin_config(codex_home.path(), &format!("{}/backend-api", server.uri()))?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let bundle_url = format!("{}/bundles/global-plugin.tar.gz", server.uri()); - mount_remote_plugin_detail_with_bundle( - &server, - "plugins_global", - "global-plugin", - &bundle_url, - "GLOBAL", - ) - .await; - mount_empty_remote_installed_plugins(&server, "GLOBAL").await; - - let home_env = home.path().to_string_lossy().into_owned(); - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .with_env_overrides(&[ - ("HOME", Some(home_env.as_str())), - ("USERPROFILE", Some(home_env.as_str())), - (TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS, Some("1")), - ]) - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let request_id = mcp - .send_raw_request( - "plugin/share/checkout", - Some(json!({ - "remotePluginId": "plugins_global", - })), - ) - .await?; - let error: JSONRPCError = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.error.code, -32600); - assert!( - error - .error - .message - .contains("not available for plugin/share/checkout") - ); - assert!(!home.path().join("plugins/global-plugin").exists()); - - Ok(()) -} - -#[tokio::test] -async fn plugin_share_checkout_cleans_up_path_when_marketplace_update_fails() -> Result<()> { - let codex_home = TempDir::new()?; - let home = TempDir::new()?; - let server = MockServer::start().await; - write_remote_plugin_config(codex_home.path(), &format!("{}/backend-api", server.uri()))?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let marketplace_path = home.path().join(".agents/plugins/marketplace.json"); - std::fs::create_dir_all( - marketplace_path - .parent() - .expect("marketplace path has parent"), - )?; - std::fs::write( - &marketplace_path, - serde_json::to_string_pretty(&json!({ - "name": "codex-curated", - "plugins": [ - { - "name": "demo-plugin", - "source": { - "source": "local", - "path": "./other/demo-plugin", - }, - }, - ], - }))?, - )?; - - let bundle_url = mount_remote_plugin_bundle( - &server, - "demo-plugin", - remote_plugin_bundle_tar_gz_bytes("demo-plugin")?, - ) - .await; - mount_remote_plugin_detail_with_bundle( - &server, - "plugins_123", - "demo-plugin", - &bundle_url, - "WORKSPACE", - ) - .await; - mount_empty_remote_installed_plugins(&server, "WORKSPACE").await; - - let home_env = home.path().to_string_lossy().into_owned(); - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .with_env_overrides(&[ - ("HOME", Some(home_env.as_str())), - ("USERPROFILE", Some(home_env.as_str())), - (TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS, Some("1")), - ]) - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - - let request_id = mcp - .send_raw_request( - "plugin/share/checkout", - Some(json!({ - "remotePluginId": "plugins_123", - })), - ) - .await?; - let error: JSONRPCError = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.error.code, -32600); - assert!( - error - .error - .message - .contains("marketplace already contains plugin `demo-plugin`") - ); - assert!(!home.path().join("plugins/demo-plugin").exists()); - assert!( - !codex_home - .path() - .join(".tmp/plugin-share-local-paths-v1.json") - .exists() - ); - - Ok(()) -} - -#[tokio::test] -async fn plugin_share_update_targets_updates_share_targets() -> Result<()> { - let codex_home = TempDir::new()?; - let server = MockServer::start().await; - write_remote_plugin_config(codex_home.path(), &format!("{}/backend-api", server.uri()))?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - Mock::given(method("PUT")) - .and(path("/backend-api/ps/plugins/plugins_123/shares")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .and(body_json(json!({ - "discoverability": "UNLISTED", - "targets": [ - { - "principal_type": "user", - "principal_id": "user-1", - "role": "editor", - }, - { - "principal_type": "workspace", - "principal_id": "account-123", - "role": "reader", - }, - ], - }))) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "principals": [ - { - "principal_type": "user", - "principal_id": "owner-1", - "role": "owner", - "name": "Owner", - }, - { - "principal_type": "user", - "principal_id": "user-1", - "role": "editor", - "name": "Gavin", - }, - { - "principal_type": "workspace", - "principal_id": "account-123", - "role": "reader", - "name": "Workspace", - }, - ], - "discoverability": "UNLISTED", - }))) - .expect(1) - .mount(&server) - .await; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - let request_id = mcp - .send_raw_request( - "plugin/share/updateTargets", - Some(json!({ - "remotePluginId": "plugins_123", - "discoverability": "UNLISTED", - "shareTargets": [ - { - "principalType": "user", - "principalId": "user-1", - "role": "editor", - }, - ], - })), - ) - .await?; - - let response: PluginShareUpdateTargetsResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - - assert_eq!( - response, - PluginShareUpdateTargetsResponse { - principals: vec![ - PluginSharePrincipal { - principal_type: PluginSharePrincipalType::User, - principal_id: "owner-1".to_string(), - role: PluginSharePrincipalRole::Owner, - name: "Owner".to_string(), - }, - PluginSharePrincipal { - principal_type: PluginSharePrincipalType::User, - principal_id: "user-1".to_string(), - role: PluginSharePrincipalRole::Editor, - name: "Gavin".to_string(), - }, - PluginSharePrincipal { - principal_type: PluginSharePrincipalType::Workspace, - principal_id: "account-123".to_string(), - role: PluginSharePrincipalRole::Reader, - name: "Workspace".to_string(), - }, - ], - discoverability: codex_app_server_protocol::PluginShareDiscoverability::Unlisted, - } - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_share_update_targets_publishes_workspace_plugin() -> Result<()> { - let codex_home = TempDir::new()?; - let server = MockServer::start().await; - write_remote_plugin_config(codex_home.path(), &format!("{}/backend-api", server.uri()))?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - Mock::given(method("PUT")) - .and(path("/backend-api/ps/plugins/plugins_123/shares")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .and(body_json(json!({ - "discoverability": "LISTED", - "targets": [], - }))) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "principals": [ - { - "principal_type": "user", - "principal_id": "owner-1", - "role": "owner", - "name": "Owner", - }, - ], - "discoverability": "LISTED", - }))) - .expect(1) - .mount(&server) - .await; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - let request_id = mcp - .send_raw_request( - "plugin/share/updateTargets", - Some(json!({ - "remotePluginId": "plugins_123", - "discoverability": "LISTED", - "shareTargets": [], - })), - ) - .await?; - - let response: PluginShareUpdateTargetsResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - - assert_eq!( - response, - PluginShareUpdateTargetsResponse { - principals: vec![PluginSharePrincipal { - principal_type: PluginSharePrincipalType::User, - principal_id: "owner-1".to_string(), - role: PluginSharePrincipalRole::Owner, - name: "Owner".to_string(), - }], - discoverability: codex_app_server_protocol::PluginShareDiscoverability::Listed, - } - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_share_update_targets_rejects_when_plugin_sharing_disabled() -> Result<()> { - let codex_home = TempDir::new()?; - let server = MockServer::start().await; - std::fs::write( - codex_home.path().join("config.toml"), - format!( - r#" -chatgpt_base_url = "{}/backend-api" - -[features] -plugins = true -plugin_sharing = false -"#, - server.uri() - ), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - let request_id = mcp - .send_raw_request( - "plugin/share/updateTargets", - Some(json!({ - "remotePluginId": "plugins_123", - "discoverability": "UNLISTED", - "shareTargets": [], - })), - ) - .await?; - - let error: JSONRPCError = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.error.code, -32600); - assert_eq!(error.error.message, "plugin sharing is disabled"); - Ok(()) -} - -#[tokio::test] -async fn plugin_share_delete_removes_created_workspace_plugin() -> Result<()> { - let codex_home = TempDir::new()?; - let server = MockServer::start().await; - write_remote_plugin_config(codex_home.path(), &format!("{}/backend-api", server.uri()))?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - let local_plugin_path = AbsolutePathBuf::try_from(codex_home.path().join("local-plugin"))?; - write_plugin_share_local_path_mapping(codex_home.path(), "plugins_123", &local_plugin_path)?; - - Mock::given(method("DELETE")) - .and(path("/backend-api/public/plugins/workspace/plugins_123")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(204)) - .expect(1) - .mount(&server) - .await; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_TIMEOUT) - .await?; - let request_id = mcp - .send_raw_request( - "plugin/share/delete", - Some(json!({ - "remotePluginId": "plugins_123", - })), - ) - .await?; - - let response: PluginShareDeleteResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - - assert_eq!(response, PluginShareDeleteResponse {}); - - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/workspace/created")) - .and(query_param("limit", "200")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [remote_plugin_json("plugins_123")], - "pagination": empty_pagination_json(), - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("scope", "WORKSPACE")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [installed_remote_plugin_json("plugins_123")], - "pagination": empty_pagination_json(), - }))) - .expect(1) - .mount(&server) - .await; - - let request_id = mcp - .send_raw_request("plugin/share/list", Some(json!({}))) - .await?; - let response: PluginShareListResponse = - timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??; - - assert_eq!( - response, - PluginShareListResponse { - data: vec![PluginShareListItem { - plugin: PluginSummary { - id: "demo-plugin@workspace-shared-with-me".to_string(), - remote_plugin_id: Some("plugins_123".to_string()), - version: Some("0.1.0".to_string()), - local_version: Some("0.1.0".to_string()), - name: "demo-plugin".to_string(), - share_context: Some(expected_share_context("plugins_123")), - source: PluginSource::Remote, - installed: true, - installed_at: None, - enabled: true, - install_policy: PluginInstallPolicy::Available, - install_policy_source: None, - must_show_installation_interstitial: Some(false), - auth_policy: PluginAuthPolicy::OnUse, - availability: codex_app_server_protocol::PluginAvailability::Available, - disabled_reason: None, - eligible_plan_types: None, - interface: Some(expected_plugin_interface()), - keywords: Vec::new(), - }, - local_plugin_path: None, - }], - } - ); - Ok(()) -} - -fn write_remote_plugin_config(codex_home: &Path, base_url: &str) -> std::io::Result<()> { - std::fs::write( - codex_home.join("config.toml"), - format!( - r#" -chatgpt_base_url = "{base_url}" - -[features] -plugins = true -"# - ), - ) -} - -async fn mount_remote_plugin_bundle( - server: &MockServer, - plugin_name: &str, - body: Vec, -) -> String { - let bundle_path = format!("/bundles/{plugin_name}.tar.gz"); - Mock::given(method("GET")) - .and(path(bundle_path.clone())) - .respond_with( - ResponseTemplate::new(200) - .insert_header("content-type", "application/gzip") - .set_body_bytes(body), - ) - .expect(1) - .mount(server) - .await; - format!("{}{}", server.uri(), bundle_path) -} - -async fn mount_remote_plugin_detail_with_bundle( - server: &MockServer, - remote_plugin_id: &str, - plugin_name: &str, - bundle_url: &str, - scope: &str, -) { - Mock::given(method("GET")) - .and(path(format!("/backend-api/ps/plugins/{remote_plugin_id}"))) - .and(query_param("includeDownloadUrls", "true")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "id": remote_plugin_id, - "name": plugin_name, - "scope": scope, - "discoverability": "PRIVATE", - "share_url": "https://chatgpt.example/plugins/share/share-key-1", - "share_principals": [ - { - "principal_type": "user", - "principal_id": "user-owner__account-123", - "role": "owner", - "name": "Owner", - }, - ], - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "release": { - "version": "1.2.3", - "bundle_download_url": bundle_url, - "display_name": "Demo Plugin", - "description": "Demo plugin description", - "interface": { - "short_description": "A demo plugin", - "capabilities": ["Read", "Write"], - }, - "skills": [], - }, - }))) - .mount(server) - .await; -} - -async fn mount_empty_remote_installed_plugins(server: &MockServer, scope: &str) { - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("scope", scope)) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [], - "pagination": { - "next_page_token": null, - }, - }))) - .mount(server) - .await; -} - -fn remote_plugin_json(plugin_id: &str) -> serde_json::Value { - json!({ - "id": plugin_id, - "name": "demo-plugin", - "scope": "WORKSPACE", - "discoverability": "PRIVATE", - "can_publish_to_workspace": true, - "share_url": "https://chatgpt.example/plugins/share/share-key-1", - "share_principals": [ - { - "principal_type": "user", - "principal_id": "user-owner__account-123", - "role": "owner", - "name": "Owner" - }, - { - "principal_type": "user", - "principal_id": "user-reader__account-123", - "role": "reader", - "name": "Reader" - } - ], - "installation_policy": "AVAILABLE", - "must_show_installation_interstitial": false, - "authentication_policy": "ON_USE", - "release": { - "version": "0.1.0", - "display_name": "Demo Plugin", - "description": "Demo plugin description", - "interface": { - "short_description": "A demo plugin", - "capabilities": ["Read", "Write"] - }, - "skills": [] - } - }) -} - -fn installed_remote_plugin_json(plugin_id: &str) -> serde_json::Value { - let mut plugin = remote_plugin_json(plugin_id); - let serde_json::Value::Object(fields) = &mut plugin else { - unreachable!("plugin json should be an object"); - }; - fields.insert("enabled".to_string(), json!(true)); - fields.insert("disabled_skill_names".to_string(), json!([])); - plugin -} - -fn empty_pagination_json() -> serde_json::Value { - json!({ - "next_page_token": null - }) -} - -fn expected_plugin_interface() -> PluginInterface { - PluginInterface { - display_name: Some("Demo Plugin".to_string()), - short_description: Some("A demo plugin".to_string()), - long_description: None, - developer_name: None, - category: None, - capabilities: vec!["Read".to_string(), "Write".to_string()], - website_url: None, - privacy_policy_url: None, - terms_of_service_url: None, - default_prompt: None, - brand_color: None, - composer_icon: None, - composer_icon_url: None, - logo: None, - logo_dark: None, - logo_url: None, - logo_url_dark: None, - screenshots: Vec::new(), - screenshot_urls: Vec::new(), - } -} - -fn expected_share_context(plugin_id: &str) -> PluginShareContext { - PluginShareContext { - remote_plugin_id: plugin_id.to_string(), - remote_version: Some("0.1.0".to_string()), - discoverability: Some(PluginShareDiscoverability::Private), - share_url: Some("https://chatgpt.example/plugins/share/share-key-1".to_string()), - creator_account_user_id: None, - creator_name: None, - share_principals: Some(vec![ - PluginSharePrincipal { - principal_type: PluginSharePrincipalType::User, - principal_id: "user-owner__account-123".to_string(), - role: PluginSharePrincipalRole::Owner, - name: "Owner".to_string(), - }, - PluginSharePrincipal { - principal_type: PluginSharePrincipalType::User, - principal_id: "user-reader__account-123".to_string(), - role: PluginSharePrincipalRole::Reader, - name: "Reader".to_string(), - }, - ]), - can_publish_to_workspace: Some(true), - } -} - -fn write_test_plugin(root: &Path, plugin_name: &str) -> std::io::Result { - let plugin_path = root.join(plugin_name); - write_file( - &plugin_path.join(".codex-plugin/plugin.json"), - &format!(r#"{{"name":"{plugin_name}"}}"#), - )?; - write_file( - &plugin_path.join("skills/example/SKILL.md"), - "# Example\n\nA test skill.\n", - )?; - Ok(plugin_path) -} - -fn remote_plugin_bundle_tar_gz_bytes(plugin_name: &str) -> Result> { - let manifest = format!(r#"{{"name":"{plugin_name}"}}"#); - let skill = "# Example\n\nA test skill.\n"; - let encoder = GzEncoder::new(Vec::new(), Compression::default()); - let mut tar = tar::Builder::new(encoder); - for (path, contents, mode) in [ - ( - ".codex-plugin/plugin.json", - manifest.as_bytes(), - /*mode*/ 0o644, - ), - ( - "skills/example/SKILL.md", - skill.as_bytes(), - /*mode*/ 0o644, - ), - ] { - let mut header = tar::Header::new_gnu(); - header.set_size(contents.len() as u64); - header.set_mode(mode); - header.set_cksum(); - tar.append_data(&mut header, path, contents)?; - } - Ok(tar.into_inner()?.finish()?) -} - -fn write_corrupt_plugin_share_local_path_mapping(codex_home: &Path) -> std::io::Result<()> { - write_file( - &codex_home.join(".tmp/plugin-share-local-paths-v1.json"), - "not-json", - ) -} - -fn write_plugin_share_local_path_mapping( - codex_home: &Path, - remote_plugin_id: &str, - plugin_path: &AbsolutePathBuf, -) -> std::io::Result<()> { - let mut local_plugin_paths_by_remote_plugin_id = serde_json::Map::new(); - local_plugin_paths_by_remote_plugin_id.insert( - remote_plugin_id.to_string(), - serde_json::to_value(plugin_path).map_err(std::io::Error::other)?, - ); - let contents = serde_json::to_string_pretty(&json!({ - "localPluginPathsByRemotePluginId": local_plugin_paths_by_remote_plugin_id, - })) - .map_err(std::io::Error::other)?; - write_file( - &codex_home.join(".tmp/plugin-share-local-paths-v1.json"), - &format!("{contents}\n"), - ) -} - -fn write_file(path: &Path, contents: &str) -> std::io::Result<()> { - let Some(parent) = path.parent() else { - return Err(std::io::Error::other(format!( - "file path `{}` should have a parent", - path.display() - ))); - }; - std::fs::create_dir_all(parent)?; - std::fs::write(path, contents) -} diff --git a/codex-rs/app-server/tests/suite/v2/rate_limit_reset_credits.rs b/codex-rs/app-server/tests/suite/v2/rate_limit_reset_credits.rs deleted file mode 100644 index 96ba01d6..00000000 --- a/codex-rs/app-server/tests/suite/v2/rate_limit_reset_credits.rs +++ /dev/null @@ -1,354 +0,0 @@ -use std::path::Path; - -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::TestAppServer; -use app_test_support::write_chatgpt_auth; -use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditOutcome; -use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditParams; -use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse; -use codex_app_server_protocol::GetAccountParams; -use codex_app_server_protocol::JSONRPCError; -use codex_app_server_protocol::LoginAccountResponse; -use codex_app_server_protocol::RequestId; -use codex_config::types::AuthCredentialsStoreMode; -use pretty_assertions::assert_eq; -use serde_json::json; -use tempfile::TempDir; -use tokio::time::timeout; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::body_json; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(/*secs*/ 10); -const RATE_LIMIT_RESET_REQUEST_TIMEOUT_ENV_VAR: &str = - "CODEX_TEST_RATE_LIMIT_RESET_REQUEST_TIMEOUT_MS"; -const SERVER_TIMEOUT_READ_TIMEOUT: std::time::Duration = - std::time::Duration::from_secs(/*secs*/ 15); -const INVALID_REQUEST_ERROR_CODE: i64 = -32600; -const INTERNAL_ERROR_CODE: i64 = -32603; - -#[tokio::test] -async fn consume_rate_limit_reset_credit_requires_chatgpt_auth() -> Result<()> { - let codex_home = TempDir::new()?; - let mut mcp = initialized_app_server(codex_home.path()).await?; - - let consume_id = mcp - .send_consume_account_rate_limit_reset_credit_request( - ConsumeAccountRateLimitResetCreditParams { - idempotency_key: "request-1".to_string(), - credit_id: None, - }, - ) - .await?; - let consume_error = read_error_response(&mut mcp, consume_id).await?; - assert_eq!(consume_error.error.code, INVALID_REQUEST_ERROR_CODE); - assert_eq!( - consume_error.error.message, - "codex account authentication required for rate limit reset credits" - ); - - login_with_api_key(&mut mcp, "sk-test-key").await?; - let consume_id = send_consume_reset_credit(&mut mcp, "request-2").await?; - let consume_error = read_error_response(&mut mcp, consume_id).await?; - assert_eq!(consume_error.error.code, INVALID_REQUEST_ERROR_CODE); - assert_eq!( - consume_error.error.message, - "chatgpt authentication required for rate limit reset credits" - ); - Ok(()) -} - -#[tokio::test] -async fn consume_account_rate_limit_reset_credit_maps_backend_outcomes() -> Result<()> { - let (codex_home, server) = chatgpt_test_context().await?; - let cases = [ - ( - "request-reset", - "reset", - ConsumeAccountRateLimitResetCreditOutcome::Reset, - 2, - ), - ( - "request-nothing", - "nothing_to_reset", - ConsumeAccountRateLimitResetCreditOutcome::NothingToReset, - 0, - ), - ( - "request-no-credit", - "no_credit", - ConsumeAccountRateLimitResetCreditOutcome::NoCredit, - 0, - ), - ( - "request-retry", - "already_redeemed", - ConsumeAccountRateLimitResetCreditOutcome::AlreadyRedeemed, - 0, - ), - ]; - for (idempotency_key, backend_code, _, windows_reset) in cases { - Mock::given(method("POST")) - .and(path("/api/codex/rate-limit-reset-credits/consume")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .and(body_json(json!({ "redeem_request_id": idempotency_key }))) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "code": backend_code, - "windows_reset": windows_reset - }))) - .mount(&server) - .await; - } - - let mut mcp = initialized_app_server(codex_home.path()).await?; - for (idempotency_key, _, expected_outcome, _) in cases { - assert_eq!( - consume_reset_credit(&mut mcp, idempotency_key).await?, - ConsumeAccountRateLimitResetCreditResponse { - outcome: expected_outcome, - } - ); - } - Ok(()) -} - -#[tokio::test] -async fn consume_account_rate_limit_reset_credit_forwards_selected_credit_id() -> Result<()> { - let (codex_home, server) = chatgpt_test_context().await?; - Mock::given(method("POST")) - .and(path("/api/codex/rate-limit-reset-credits/consume")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .and(body_json(json!({ - "redeem_request_id": "request-selected", - "credit_id": "credit-123", - }))) - .respond_with( - ResponseTemplate::new(200) - .set_body_json(json!({ "code": "reset", "windows_reset": 2 })), - ) - .expect(1) - .mount(&server) - .await; - - let mut mcp = initialized_app_server(codex_home.path()).await?; - let request_id = mcp - .send_consume_account_rate_limit_reset_credit_request( - ConsumeAccountRateLimitResetCreditParams { - idempotency_key: "request-selected".to_string(), - credit_id: Some("credit-123".to_string()), - }, - ) - .await?; - - assert_eq!( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_response::(request_id), - ) - .await??, - ConsumeAccountRateLimitResetCreditResponse { - outcome: ConsumeAccountRateLimitResetCreditOutcome::Reset, - } - ); - Ok(()) -} - -#[tokio::test] -async fn consume_account_rate_limit_reset_credit_rejects_empty_idempotency_key() -> Result<()> { - let (codex_home, _server) = chatgpt_test_context().await?; - let mut mcp = initialized_app_server(codex_home.path()).await?; - - let request_id = mcp - .send_consume_account_rate_limit_reset_credit_request( - ConsumeAccountRateLimitResetCreditParams { - idempotency_key: String::new(), - credit_id: None, - }, - ) - .await?; - let error = read_error_response(&mut mcp, request_id).await?; - - assert_eq!(error.error.code, INVALID_REQUEST_ERROR_CODE); - assert_eq!(error.error.message, "idempotencyKey must not be empty"); - Ok(()) -} - -#[tokio::test] -async fn consume_account_rate_limit_reset_credit_rejects_empty_credit_id() -> Result<()> { - let (codex_home, _server) = chatgpt_test_context().await?; - let mut mcp = initialized_app_server(codex_home.path()).await?; - - let request_id = mcp - .send_consume_account_rate_limit_reset_credit_request( - ConsumeAccountRateLimitResetCreditParams { - idempotency_key: "request-1".to_string(), - credit_id: Some(String::new()), - }, - ) - .await?; - let error = read_error_response(&mut mcp, request_id).await?; - - assert_eq!(error.error.code, INVALID_REQUEST_ERROR_CODE); - assert_eq!(error.error.message, "creditId must not be empty"); - Ok(()) -} - -#[tokio::test] -async fn consume_account_rate_limit_reset_credit_surfaces_backend_failure() -> Result<()> { - let (codex_home, server) = chatgpt_test_context().await?; - Mock::given(method("POST")) - .and(path("/api/codex/rate-limit-reset-credits/consume")) - .respond_with(ResponseTemplate::new(500).set_body_string("boom")) - .mount(&server) - .await; - - let mut mcp = initialized_app_server(codex_home.path()).await?; - let request_id = send_consume_reset_credit(&mut mcp, "request-1").await?; - let error = read_error_response(&mut mcp, request_id).await?; - - assert_eq!(error.error.code, INTERNAL_ERROR_CODE); - assert!( - error - .error - .message - .contains("failed to consume rate limit reset"), - "unexpected error message: {}", - error.error.message - ); - Ok(()) -} - -#[tokio::test] -async fn consume_timeout_releases_account_auth_queue() -> Result<()> { - let (codex_home, server) = chatgpt_test_context().await?; - Mock::given(method("GET")) - .and(path("/api/codex/accounts/check")) - .respond_with( - ResponseTemplate::new(200).set_body_json(json!({"accounts": [{ - "id": "account-123", "workspace_backend_origin": "https://chatgpt.com", - "account_routing_override": "NO_CONSTRAINT" - }]})), - ) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/api/codex/rate-limit-reset-credits/consume")) - .respond_with( - ResponseTemplate::new(200) - .set_delay(std::time::Duration::from_secs(/*secs*/ 1)) - .set_body_json(json!({ "code": "reset", "windows_reset": 2 })), - ) - .mount(&server) - .await; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .with_env_overrides(&[ - ("OPENAI_API_KEY", None), - (RATE_LIMIT_RESET_REQUEST_TIMEOUT_ENV_VAR, Some("100")), - ]) - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - let consume_id = send_consume_reset_credit(&mut mcp, "request-timeout").await?; - let account_id = mcp - .send_get_account_request(GetAccountParams { - refresh_token: false, - }) - .await?; - - let consume_error: JSONRPCError = timeout( - SERVER_TIMEOUT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(consume_id)), - ) - .await??; - assert_eq!(consume_error.error.code, INTERNAL_ERROR_CODE); - assert_eq!( - consume_error.error.message, - "rate limit reset consume timed out" - ); - - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(account_id)), - ) - .await??; - Ok(()) -} - -async fn chatgpt_test_context() -> Result<(TempDir, MockServer)> { - let codex_home = TempDir::new()?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .plan_type("pro"), - AuthCredentialsStoreMode::File, - )?; - let server = MockServer::start().await; - write_chatgpt_base_url(codex_home.path(), &server.uri())?; - Ok((codex_home, server)) -} - -async fn initialized_app_server(codex_home: &Path) -> Result { - TestAppServer::builder() - .with_codex_home(codex_home) - .without_auto_env() - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await -} - -async fn consume_reset_credit( - mcp: &mut TestAppServer, - idempotency_key: &str, -) -> Result { - let request_id = send_consume_reset_credit(mcp, idempotency_key).await?; - timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await? -} - -async fn send_consume_reset_credit(mcp: &mut TestAppServer, idempotency_key: &str) -> Result { - mcp.send_consume_account_rate_limit_reset_credit_request( - ConsumeAccountRateLimitResetCreditParams { - idempotency_key: idempotency_key.to_string(), - credit_id: None, - }, - ) - .await -} - -async fn read_error_response(mcp: &mut TestAppServer, request_id: i64) -> Result { - let error = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - Ok(error) -} - -async fn login_with_api_key(mcp: &mut TestAppServer, api_key: &str) -> Result<()> { - let request_id = mcp.send_login_account_api_key_request(api_key).await?; - assert_eq!( - timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_response::(request_id), - ) - .await??, - LoginAccountResponse::ApiKey {} - ); - Ok(()) -} - -fn write_chatgpt_base_url(codex_home: &Path, base_url: &str) -> std::io::Result<()> { - std::fs::write( - codex_home.join("config.toml"), - format!("chatgpt_base_url = \"{base_url}\"\n"), - ) -} diff --git a/codex-rs/app-server/tests/suite/v2/rate_limits.rs b/codex-rs/app-server/tests/suite/v2/rate_limits.rs deleted file mode 100644 index fa9c3413..00000000 --- a/codex-rs/app-server/tests/suite/v2/rate_limits.rs +++ /dev/null @@ -1,1095 +0,0 @@ -use anyhow::Context; -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::ChatGptIdTokenClaims; -use app_test_support::TestAppServer; -use app_test_support::write_chatgpt_auth; -use codex_app_server_protocol::AddCreditsNudgeCreditType; -use codex_app_server_protocol::AddCreditsNudgeEmailStatus; -use codex_app_server_protocol::GetAccountParams; -use codex_app_server_protocol::GetAccountRateLimitsResponse; -use codex_app_server_protocol::GetAccountResponse; -use codex_app_server_protocol::JSONRPCError; -use codex_app_server_protocol::LoginAccountResponse; -use codex_app_server_protocol::RateLimitReachedType; -use codex_app_server_protocol::RateLimitResetCredit; -use codex_app_server_protocol::RateLimitResetCreditStatus; -use codex_app_server_protocol::RateLimitResetCreditsSummary; -use codex_app_server_protocol::RateLimitResetType; -use codex_app_server_protocol::RateLimitSnapshot; -use codex_app_server_protocol::RateLimitWindow; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SendAddCreditsNudgeEmailParams; -use codex_app_server_protocol::SendAddCreditsNudgeEmailResponse; -use codex_app_server_protocol::SpendControlLimitSnapshot; -use codex_config::types::AuthCredentialsStoreMode; -use codex_protocol::account::PlanType as AccountPlanType; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::path::Path; -use tempfile::TempDir; -use test_case::test_case; -use tokio::time::timeout; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; - -const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); -const INVALID_REQUEST_ERROR_CODE: i64 = -32600; -const INTERNAL_ERROR_CODE: i64 = -32603; - -#[tokio::test] -async fn get_account_rate_limits_requires_auth() -> Result<()> { - let codex_home = TempDir::new()?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - - let request_id = mcp.send_get_account_rate_limits_request().await?; - - let error: JSONRPCError = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.id, RequestId::Integer(request_id)); - assert_eq!(error.error.code, INVALID_REQUEST_ERROR_CODE); - assert_eq!( - error.error.message, - "codex account authentication required to read rate limits" - ); - - Ok(()) -} - -#[tokio::test] -async fn get_account_rate_limits_requires_chatgpt_auth() -> Result<()> { - let codex_home = TempDir::new()?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - - login_with_api_key(&mut mcp, "sk-test-key").await?; - - let request_id = mcp.send_get_account_rate_limits_request().await?; - - let error: JSONRPCError = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.id, RequestId::Integer(request_id)); - assert_eq!(error.error.code, INVALID_REQUEST_ERROR_CODE); - assert_eq!( - error.error.message, - "chatgpt authentication required to read rate limits" - ); - - Ok(()) -} - -#[test_case("enterprise_cbp_automation", AccountPlanType::EnterpriseCbpAutomation; "enterprise_automation")] -#[test_case("promax", AccountPlanType::ProMax; "pro_max")] -#[test_case("edu_plus", AccountPlanType::EduPlus; "edu_plus")] -#[test_case("edu_pro", AccountPlanType::EduPro; "edu_pro")] -#[test_case("sci", AccountPlanType::Sci; "sci")] -#[test_case("sci_plus", AccountPlanType::SciPlus; "sci_plus")] -#[tokio::test] -async fn get_account_rate_limits_returns_snapshot( - plan_type: &str, - expected_plan: AccountPlanType, -) -> Result<()> { - let codex_home = TempDir::new()?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .plan_type("pro"), - AuthCredentialsStoreMode::File, - )?; - - let server = MockServer::start().await; - let server_url = server.uri(); - let startup_server = MockServer::start().await; - write_chatgpt_base_url(codex_home.path(), &startup_server.uri())?; - - let primary_reset_timestamp = chrono::DateTime::parse_from_rfc3339("2025-01-01T00:02:00Z") - .expect("parse primary reset timestamp") - .timestamp(); - let secondary_reset_timestamp = chrono::DateTime::parse_from_rfc3339("2025-01-01T01:00:00Z") - .expect("parse secondary reset timestamp") - .timestamp(); - let reset_credit_granted_at = chrono::DateTime::parse_from_rfc3339("2026-06-17T00:00:00Z") - .expect("parse reset credit grant timestamp") - .timestamp(); - let reset_credit_expires_at = chrono::DateTime::parse_from_rfc3339("2026-07-17T00:00:00Z") - .expect("parse reset credit expiry timestamp") - .timestamp(); - let second_reset_credit_granted_at = - chrono::DateTime::parse_from_rfc3339("2026-06-18T00:00:00Z") - .expect("parse second reset credit grant timestamp") - .timestamp(); - let banner = json!({ - "banner_type": "selected_model_limit_reached", - "title": "Usage limit reached", - "description": "View your usage.", - "ctas": [{"action": "view_usage", "label": "View usage"}] - }); - let response_body = json!({ - "account_id": "account-123", - "user_id": "user-123", - "rate_limit_upsell": banner, - - "plan_type": plan_type, - "rate_limit": { - "allowed": true, - "limit_reached": false, - "primary_window": { - "used_percent": 42, - "limit_window_seconds": 3600, - "reset_after_seconds": 120, - "reset_at": primary_reset_timestamp, - }, - "secondary_window": { - "used_percent": 5, - "limit_window_seconds": 86400, - "reset_after_seconds": 43200, - "reset_at": secondary_reset_timestamp, - } - }, - "rate_limit_reached_type": { - "type": "workspace_member_usage_limit_reached", - }, - "spend_control": { - "reached": false, - "individual_limit": { - "source": "workspace_spend_controls", - "limit": "25000", - "used": "8000", - "remaining": "17000", - "used_percent": 32, - "remaining_percent": 68, - "reset_after_seconds": 43200, - "reset_at": secondary_reset_timestamp, - } - }, - "additional_rate_limits": [ - { - "limit_name": "codex_other", - "metered_feature": "codex_other", - "rate_limit": { - "allowed": true, - "limit_reached": false, - "primary_window": { - "used_percent": 88, - "limit_window_seconds": 1800, - "reset_after_seconds": 600, - "reset_at": 1735693200 - } - } - } - ], - "rate_limit_reset_credits": { "available_count": 3 } - }); - - Mock::given(method("GET")) - .and(path("/api/codex/usage")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_json(response_body)) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/api/codex/rate-limit-reset-credits")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "credits": [ - { - "id": "credit-1", - "reset_type": "codex_rate_limits", - "status": "available", - "granted_at": "2026-06-17T00:00:00Z", - "expires_at": "2026-07-17T00:00:00Z", - "title": "Full reset (Weekly + 5 hr)", - "description": "Ready to redeem" - }, - { - "id": "credit-2", - "reset_type": "future_reset_type", - "status": "future_status", - "granted_at": "2026-06-18T00:00:00Z", - "expires_at": null - } - ], - "available_count": 2, - "total_earned_count": 4 - }))) - .expect(1) - .mount(&server) - .await; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - - // Account RPCs reload the effective config, but custom endpoints keep their original auth. - std::fs::write( - codex_home.path().join("config.toml"), - format!( - "chatgpt_base_url = {server_url:?}\n[features.runtime_agent_instances]\nenabled = true\nmode = \"assertion_only\"\n", - ), - )?; - - let request_id = mcp.send_get_account_rate_limits_request().await?; - - let received: GetAccountRateLimitsResponse = - timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??; - - let expected = GetAccountRateLimitsResponse { - ordinary_usage_allowed: Some(true), - account_id: Some("account-123".to_string()), - rate_limit_upsell: Some(banner), - rate_limits: RateLimitSnapshot { - limit_id: Some("codex".to_string()), - limit_name: None, - normal_model_slug: None, - primary: Some(RateLimitWindow { - used_percent: 42, - window_duration_mins: Some(60), - resets_at: Some(primary_reset_timestamp), - }), - secondary: Some(RateLimitWindow { - used_percent: 5, - window_duration_mins: Some(1440), - resets_at: Some(secondary_reset_timestamp), - }), - credits: None, - individual_limit: Some(SpendControlLimitSnapshot { - limit: "25000".to_string(), - used: "8000".to_string(), - remaining_percent: 68, - resets_at: secondary_reset_timestamp, - }), - spend_control_reached: Some(false), - plan_type: Some(expected_plan), - rate_limit_reached_type: Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached), - }, - rate_limits_by_limit_id: Some( - [ - ( - "codex".to_string(), - RateLimitSnapshot { - limit_id: Some("codex".to_string()), - limit_name: None, - normal_model_slug: None, - primary: Some(RateLimitWindow { - used_percent: 42, - window_duration_mins: Some(60), - resets_at: Some(primary_reset_timestamp), - }), - secondary: Some(RateLimitWindow { - used_percent: 5, - window_duration_mins: Some(1440), - resets_at: Some(secondary_reset_timestamp), - }), - credits: None, - individual_limit: Some(SpendControlLimitSnapshot { - limit: "25000".to_string(), - used: "8000".to_string(), - remaining_percent: 68, - resets_at: secondary_reset_timestamp, - }), - spend_control_reached: Some(false), - plan_type: Some(expected_plan), - rate_limit_reached_type: Some( - RateLimitReachedType::WorkspaceMemberUsageLimitReached, - ), - }, - ), - ( - "codex_other".to_string(), - RateLimitSnapshot { - limit_id: Some("codex_other".to_string()), - limit_name: Some("codex_other".to_string()), - normal_model_slug: None, - primary: Some(RateLimitWindow { - used_percent: 88, - window_duration_mins: Some(30), - resets_at: Some(1735693200), - }), - secondary: None, - credits: None, - individual_limit: None, - spend_control_reached: None, - plan_type: Some(expected_plan), - rate_limit_reached_type: None, - }, - ), - ] - .into_iter() - .collect(), - ), - rate_limit_reset_credits: Some(RateLimitResetCreditsSummary { - available_count: 2, - credits: Some(vec![ - RateLimitResetCredit { - id: "credit-1".to_string(), - reset_type: RateLimitResetType::CodexRateLimits, - status: RateLimitResetCreditStatus::Available, - granted_at: reset_credit_granted_at, - expires_at: Some(reset_credit_expires_at), - title: Some("Full reset (Weekly + 5 hr)".to_string()), - description: Some("Ready to redeem".to_string()), - }, - RateLimitResetCredit { - id: "credit-2".to_string(), - reset_type: RateLimitResetType::Unknown, - status: RateLimitResetCreditStatus::Unknown, - granted_at: second_reset_credit_granted_at, - expires_at: None, - title: None, - description: None, - }, - ]), - }), - }; - assert_eq!(received, expected); - - for request in server.received_requests().await.expect("recorded requests") { - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - } - Ok(()) -} - -#[test_case(Some("workspace-a"), Some("user-a"), /*restricted*/ false, /*permitted*/ true; "matching_identity")] -#[test_case(Some("workspace-b"), Some("user-a"), /*restricted*/ false, /*permitted*/ false; "account_mismatch")] -#[test_case(Some("workspace-a"), Some("user-b"), /*restricted*/ false, /*permitted*/ false; "user_mismatch")] -#[test_case(/*account*/ None, Some("user-a"), /*restricted*/ false, /*permitted*/ false; "missing_account")] -#[test_case(Some("workspace-a"), /*user*/ None, /*restricted*/ false, /*permitted*/ false; "missing_user")] -#[test_case(Some("workspace-a"), Some("user-a"), /*restricted*/ true, /*permitted*/ false; "restricted_account")] -#[tokio::test] -async fn get_account_rate_limits_filters_banner_by_identity( - account: Option<&str>, - user: Option<&str>, - restricted: bool, - permitted: bool, -) -> Result<()> { - let codex_home = TempDir::new()?; - let mut claims = ChatGptIdTokenClaims::new() - .plan_type("team") - .chatgpt_user_id("user-a"); - claims.chatgpt_account_is_fedramp = restricted; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("workspace-a") - .claims(claims), - AuthCredentialsStoreMode::File, - )?; - - let server = MockServer::start().await; - write_chatgpt_base_url(codex_home.path(), &server.uri())?; - let banner = json!({ - "banner_type": "selected_model_limit", "model_slug": "test-model-a", - "presentation": "inline", "title": "Usage limit reached", - "description": "Contact your owner.", - "ctas": [{"action": "notify_owner", "label": "Notify owner"}] - }); - Mock::given(method("GET")) - .and(path("/api/codex/usage")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "workspace-a")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "account_id": account, "user_id": user, "plan_type": "team", - "rate_limit": {"allowed": true, "limit_reached": false, - "primary_window": {"used_percent": 42, "limit_window_seconds": 3600, - "reset_after_seconds": 120, "reset_at": 2000000000}}, - "rate_limit_upsell": banner, "rate_limit_reset_credits": {"available_count": 0} - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/api/codex/rate-limit-reset-credits")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "available_count": 0, "credits": [] - }))) - .expect(1) - .mount(&server) - .await; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - let request_id = mcp.send_get_account_rate_limits_request().await?; - let received: GetAccountRateLimitsResponse = - timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??; - let snapshot = json!({ - "limitId": "codex", "planType": "team", - "primary": {"usedPercent": 42, "windowDurationMins": 60, "resetsAt": 2000000000} - }); - let expected: GetAccountRateLimitsResponse = serde_json::from_value(json!({ - "ordinaryUsageAllowed": if permitted { Some(true) } else { None }, - "accountId": account, "rateLimitUpsell": if permitted { Some(banner) } else { None }, - "rateLimits": snapshot, "rateLimitsByLimitId": {"codex": snapshot}, - "rateLimitResetCredits": {"availableCount": 0, "credits": []} - }))?; - assert_eq!(received, expected); - server.verify().await; - Ok(()) -} - -#[tokio::test] -async fn get_account_rate_limits_preserves_count_when_reset_credit_details_fail() -> Result<()> { - let codex_home = TempDir::new()?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .plan_type("pro"), - AuthCredentialsStoreMode::File, - )?; - - let server = MockServer::start().await; - write_chatgpt_base_url(codex_home.path(), &server.uri())?; - - Mock::given(method("GET")) - .and(path("/api/codex/usage")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plan_type": "pro", - "rate_limit": { - "allowed": true, - "limit_reached": false, - "primary_window": { - "used_percent": 42, - "limit_window_seconds": 3600, - "reset_after_seconds": 120, - "reset_at": 1735689720 - } - }, - "rate_limit_reset_credits": { "available_count": 3 } - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/api/codex/rate-limit-reset-credits")) - .respond_with(ResponseTemplate::new(500).set_body_string("boom")) - .expect(1) - .mount(&server) - .await; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - - let request_id = mcp.send_get_account_rate_limits_request().await?; - let received: GetAccountRateLimitsResponse = - timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??; - - assert_eq!( - received.rate_limit_reset_credits, - Some(RateLimitResetCreditsSummary { - available_count: 3, - credits: None, - }) - ); - - Ok(()) -} - -#[tokio::test] -async fn send_add_credits_nudge_email_requires_auth() -> Result<()> { - let codex_home = TempDir::new()?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - - let request_id = mcp - .send_add_credits_nudge_email_request(SendAddCreditsNudgeEmailParams { - credit_type: AddCreditsNudgeCreditType::Credits, - }) - .await?; - - let error: JSONRPCError = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.id, RequestId::Integer(request_id)); - assert_eq!(error.error.code, INVALID_REQUEST_ERROR_CODE); - assert_eq!( - error.error.message, - "codex account authentication required to notify workspace owner" - ); - - Ok(()) -} - -#[tokio::test] -async fn send_add_credits_nudge_email_requires_chatgpt_auth() -> Result<()> { - let codex_home = TempDir::new()?; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - - login_with_api_key(&mut mcp, "sk-test-key").await?; - - let request_id = mcp - .send_add_credits_nudge_email_request(SendAddCreditsNudgeEmailParams { - credit_type: AddCreditsNudgeCreditType::UsageLimit, - }) - .await?; - - let error: JSONRPCError = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.id, RequestId::Integer(request_id)); - assert_eq!(error.error.code, INVALID_REQUEST_ERROR_CODE); - assert_eq!( - error.error.message, - "chatgpt authentication required to notify workspace owner" - ); - - Ok(()) -} - -#[cfg_attr(target_os = "windows", ignore = "covered by Linux and macOS CI")] -#[tokio::test] -async fn send_add_credits_nudge_email_posts_expected_body() -> Result<()> { - let codex_home = TempDir::new()?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .plan_type("pro"), - AuthCredentialsStoreMode::File, - )?; - - let server = MockServer::start().await; - let server_url = server.uri(); - write_chatgpt_base_url(codex_home.path(), &server_url)?; - - Mock::given(method("POST")) - .and(path("/api/codex/accounts/send_add_credits_nudge_email")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .and(wiremock::matchers::body_json(json!({ - "credit_type": "usage_limit", - }))) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - - let request_id = mcp - .send_add_credits_nudge_email_request(SendAddCreditsNudgeEmailParams { - credit_type: AddCreditsNudgeCreditType::UsageLimit, - }) - .await?; - - let received: SendAddCreditsNudgeEmailResponse = - timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??; - - assert_eq!(received.status, AddCreditsNudgeEmailStatus::Sent); - - Ok(()) -} - -#[cfg_attr(target_os = "windows", ignore = "covered by Linux and macOS CI")] -#[tokio::test] -async fn send_add_credits_nudge_email_maps_cooldown() -> Result<()> { - let codex_home = TempDir::new()?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .plan_type("pro"), - AuthCredentialsStoreMode::File, - )?; - - let server = MockServer::start().await; - let server_url = server.uri(); - write_chatgpt_base_url(codex_home.path(), &server_url)?; - - Mock::given(method("POST")) - .and(path("/api/codex/accounts/send_add_credits_nudge_email")) - .respond_with(ResponseTemplate::new(429)) - .mount(&server) - .await; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - - let request_id = mcp - .send_add_credits_nudge_email_request(SendAddCreditsNudgeEmailParams { - credit_type: AddCreditsNudgeCreditType::Credits, - }) - .await?; - - let received: SendAddCreditsNudgeEmailResponse = - timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??; - - assert_eq!(received.status, AddCreditsNudgeEmailStatus::CooldownActive); - - Ok(()) -} - -#[cfg_attr(target_os = "windows", ignore = "covered by Linux and macOS CI")] -#[tokio::test] -async fn send_add_credits_nudge_email_surfaces_backend_failure() -> Result<()> { - let codex_home = TempDir::new()?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .plan_type("pro"), - AuthCredentialsStoreMode::File, - )?; - - let server = MockServer::start().await; - let server_url = server.uri(); - write_chatgpt_base_url(codex_home.path(), &server_url)?; - - Mock::given(method("POST")) - .and(path("/api/codex/accounts/send_add_credits_nudge_email")) - .respond_with(ResponseTemplate::new(500).set_body_string("boom")) - .mount(&server) - .await; - - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_auto_env() - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - - let request_id = mcp - .send_add_credits_nudge_email_request(SendAddCreditsNudgeEmailParams { - credit_type: AddCreditsNudgeCreditType::Credits, - }) - .await?; - - let error: JSONRPCError = timeout( - DEFAULT_READ_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(error.id, RequestId::Integer(request_id)); - assert_eq!(error.error.code, INTERNAL_ERROR_CODE); - assert!( - error - .error - .message - .contains("failed to notify workspace owner"), - "unexpected error message: {}", - error.error.message - ); - assert_eq!(error.error.data, None); - - Ok(()) -} - -async fn login_with_api_key(mcp: &mut TestAppServer, api_key: &str) -> Result<()> { - let request_id = mcp.send_login_account_api_key_request(api_key).await?; - let login: LoginAccountResponse = - timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??; - assert_eq!(login, LoginAccountResponse::ApiKey {}); - - Ok(()) -} - -fn write_chatgpt_base_url(codex_home: &Path, base_url: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write(config_toml, format!("chatgpt_base_url = \"{base_url}\"\n")) -} - -#[test_case("disabled"; "disabled")] -#[test_case("dual_header"; "dual_header")] -#[test_case("assertion_only"; "assertion_only")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn account_requests_share_runtime_and_rotate_on_restart(mode: &str) -> Result<()> { - use base64::Engine; - use core_test_support::runtime_auth::PROBE_SERVER; - use core_test_support::runtime_auth::run_harness_through_proxy; - use std::collections::BTreeSet; - use std::sync::atomic::AtomicUsize; - use std::sync::atomic::Ordering; - - let enabled = mode != "disabled"; - let token = format!("e30.{}.c2ln", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode( - serde_json::to_vec(&json!({ - "exp": chrono::Utc::now().timestamp() + 3600, - "session_id": "session-a", "iss": "https://auth.openai.com", - "https://api.openai.com/auth": {"chatgpt_user_id": "user-123", "chatgpt_account_id": "account-123"}, - }))? - )); - if std::env::var(PROBE_SERVER).is_ok() { - let home = TempDir::new()?; - write_chatgpt_auth( - home.path(), - ChatGptAuthFixture::new(&token) - .account_id("account-123") - .chatgpt_user_id("user-123") - .plan_type("pro"), - AuthCredentialsStoreMode::File, - )?; - let before = std::fs::read(home.path().join("auth.json"))?; - std::fs::write( - home.path().join("config.toml"), - format!( - "chatgpt_base_url = \"https://chatgpt.com/backend-api\"\nfeatures.connectors = true\n[features.runtime_agent_instances]\nenabled = {enabled}\nmode = {mode:?}\n", - mode = if enabled { mode } else { "dual_header" }, - ), - )?; - for _ in 0..2 { - let mut app = TestAppServer::builder() - .with_codex_home(home.path()) - .without_auto_env() - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - let id = app - .send_get_account_request(GetAccountParams { - refresh_token: false, - }) - .await?; - let account: GetAccountResponse = - timeout(DEFAULT_READ_TIMEOUT, app.read_response(id)).await??; - assert_eq!( - account - .workspace_routing - .context("workspace routing")? - .chatgpt_account_id, - "account-123" - ); - for _ in 0..2 { - let id = app.send_get_account_rate_limits_request().await?; - let result: GetAccountRateLimitsResponse = - timeout(DEFAULT_READ_TIMEOUT, app.read_response(id)).await??; - assert_eq!(result.rate_limits.plan_type, Some(AccountPlanType::Pro)); - assert_eq!( - result - .rate_limits - .primary - .context("primary rate limit")? - .used_percent, - 42 - ); - } - let id = app - .send_apps_list_request(codex_app_server_protocol::AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: true, - }) - .await?; - let apps: codex_app_server_protocol::AppsListResponse = - timeout(DEFAULT_READ_TIMEOUT, app.read_response(id)).await??; - assert!(!apps.data.is_empty(), "Apps list must return the mock app"); - let id = app - .send_apps_read_request(codex_app_server_protocol::AppsReadParams { - app_ids: vec!["details-only".into()], - thread_id: None, - include_tools: false, - }) - .await?; - let apps: codex_app_server_protocol::AppsReadResponse = - timeout(DEFAULT_READ_TIMEOUT, app.read_response(id)).await??; - assert_eq!(apps.apps[0].id, "details-only"); - let id = app - .send_request("account/securitySetup/read", /*params*/ None) - .await?; - let response: codex_app_server_protocol::GetAccountSecuritySetupResponse = - timeout(DEFAULT_READ_TIMEOUT, app.read_response(id)).await??; - assert_eq!( - response.notice, - Some(codex_app_server_protocol::AccountSecuritySetupNotice { - account_id: "account-123".into(), - user_id: "user-123".into(), - title: "Set up security".into(), - description: "Account security reminder".into(), - action: codex_app_server_protocol::AccountSecuritySetupAction { - label: "Settings".into(), - url: "https://chatgpt.com/cyber".into(), - }, - }) - ); - } - assert_eq!(std::fs::read(home.path().join("auth.json"))?, before); - return Ok(()); - } - - let server = MockServer::start().await; - app_test_support::mount_workspace_routing(&server).await; - core_test_support::apps_test_server::AppsTestServer::mount(&server).await?; - Mock::given(method("GET")).and(wiremock::matchers::path_regex(".*/connectors/directory/(list|list_workspace)$")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "apps": [{"id": "directory-app", "name": "Directory app", "description": "An app from the directory"}], - "nextToken": null, - }))).mount(&server).await; - Mock::given(method("POST")).and(wiremock::matchers::path_regex(".*/ps/apps/batch$")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({"apps": [{ - "id": "details-only", "name": "Details", "description": "An app read through the public RPC", - }]}))).expect(2).mount(&server).await; - let registrations = AtomicUsize::new(0); - Mock::given(method("POST")) - .and(path("/agent/register")) - .respond_with(move |_: &wiremock::Request| { - let id = registrations.fetch_add(1, Ordering::Relaxed) + 1; - ResponseTemplate::new(200).set_body_json(json!({ - "runtime_agent_instance_id": format!("runtime-{id}"), "agent_host_id": "host-a", - "actor": {"kind": "chatgpt", "user_id": "user-123", "account_id": "account-123"}, - })) - }) - .expect(if enabled { 2 } else { 0 }) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/usage")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "account_id": "account-123", "user_id": "user-123", "plan_type": "pro", - "rate_limit": {"allowed": true, "limit_reached": false, "primary_window": { - "used_percent": 42, "limit_window_seconds": 3600, - "reset_after_seconds": 120, "reset_at": 1900000000, - }}, - }))) - .expect(4) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/rate-limit-reset-credits")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "credits": [], "available_count": 0, "total_earned_count": 0, - }))) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/security-setup")) - .respond_with( - ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"notice": { - "title": "Set up security", "description": "Account security reminder", - "action": {"label": "Settings", "url": "https://chatgpt.com/cyber"}, - }})), - ) - .expect(/*r*/ 2) - .mount(&server) - .await; - run_harness_through_proxy( - &server, - &format!( - "suite::v2::rate_limits::account_requests_share_runtime_and_rotate_on_restart::{mode}" - ), - /*realtime_target*/ None, - ) - .await?; - - let requests = server - .received_requests() - .await - .context("captured requests")?; - let registrations: Vec<_> = requests - .iter() - .filter(|request| request.url.path() == "/agent/register") - .collect(); - if enabled { - let first: serde_json::Value = registrations[0].body_json()?; - let second: serde_json::Value = registrations[1].body_json()?; - assert_eq!(first["agent_host_auth"], second["agent_host_auth"]); - assert_ne!(first["public_key"], second["public_key"]); - assert_ne!( - registrations[0].headers["idempotency-key"], - registrations[1].headers["idempotency-key"] - ); - for request in registrations { - assert!(!request.headers.contains_key("authorization")); - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - } - } - let mut proofs = BTreeSet::new(); - let mut runtimes = BTreeSet::new(); - for request in requests.iter().filter(|request| { - let path = request.url.path(); - path.starts_with("/backend-api/wham/") - || path.contains("/connectors/") - || path.contains("/ps/") - }) { - assert_eq!(request.headers["chatgpt-account-id"], "account-123"); - let authorization = request.headers["authorization"].to_str()?; - let proof = if mode == "assertion_only" { - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - authorization - .strip_prefix("AgentAssertion ") - .with_context(|| { - format!( - "assertion-only authentication for {} {}", - request.method, - request.url.path() - ) - })? - } else { - assert!(authorization.starts_with("Bearer e30.")); - if !enabled { - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - continue; - } - request - .headers - .get("x-openai-agent-assertion") - .with_context(|| { - format!( - "runtime assertion for {} {}", - request.method, - request.url.path() - ) - })? - .to_str()? - }; - assert!( - proofs.insert(proof.to_string()), - "each request must get a fresh assertion" - ); - let payload: serde_json::Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(proof.split('.').nth(2).context("assertion payload")?)?, - )?; - runtimes.insert( - payload["runtime_agent_instance"] - .as_str() - .context("runtime ID")? - .to_string(), - ); - } - if enabled { - assert!(proofs.len() >= 4); - assert_eq!( - runtimes, - BTreeSet::from(["runtime-1".to_string(), "runtime-2".to_string()]) - ); - } - server.verify().await; - Ok(()) -} - -#[test_case("api_key")] -#[test_case("fedramp")] -#[test_case("external_token")] -#[test_case("signed_out")] -#[tokio::test] -async fn security_setup_requires_matching_saved_chatgpt_login(kind: &str) -> Result<()> { - use base64::Engine; - let token = format!("e30.{}.c2ln", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode( - json!({"exp": chrono::Utc::now().timestamp() + 3600, - "https://api.openai.com/auth": {"chatgpt_user_id": "user-123", "chatgpt_account_id": "account-123"}}).to_string())); - let home = TempDir::new()?; - let server = MockServer::start().await; - write_chatgpt_base_url(home.path(), &format!("{}/backend-api", server.uri()))?; - if kind != "signed_out" { - write_chatgpt_auth( - home.path(), - ChatGptAuthFixture::new(&token) - .account_id("account-123") - .claims(ChatGptIdTokenClaims { - chatgpt_account_id: Some("account-123".into()), - chatgpt_user_id: Some("user-123".into()), - chatgpt_account_is_fedramp: kind == "fedramp", - ..Default::default() - }), - AuthCredentialsStoreMode::File, - )?; - } - app_test_support::mount_workspace_routing(&server).await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/security-setup")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"notice": null}))) - .expect(/*r*/ 0) - .mount(&server) - .await; - let mut app = TestAppServer::builder() - .with_codex_home(home.path()) - .without_auto_env() - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT) - .await?; - if kind == "api_key" { - let id = app - .send_request( - "account/login/start", - Some(json!({ - "type": "apiKey", "apiKey": "selected-api-key", - })), - ) - .await?; - let response: serde_json::Value = - timeout(DEFAULT_READ_TIMEOUT, app.read_response(id)).await??; - assert_eq!(response["type"], "apiKey"); - } - if kind == "external_token" { - let id = app - .send_request( - "account/login/start", - Some(json!({ - "type": "chatgptAuthTokens", "accessToken": token, - "chatgptAccountId": "account-123", "chatgptPlanType": "pro", - })), - ) - .await?; - let response: serde_json::Value = - timeout(DEFAULT_READ_TIMEOUT, app.read_response(id)).await??; - assert_eq!(response["type"], "chatgptAuthTokens"); - } - let id = app - .send_request("account/securitySetup/read", /*params*/ None) - .await?; - let response: codex_app_server_protocol::GetAccountSecuritySetupResponse = - timeout(DEFAULT_READ_TIMEOUT, app.read_response(id)).await??; - assert_eq!(response.notice, None); - server.verify().await; - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/v2/rate_limits_identity_tests.rs b/codex-rs/app-server/tests/suite/v2/rate_limits_identity_tests.rs deleted file mode 100644 index f1125685..00000000 --- a/codex-rs/app-server/tests/suite/v2/rate_limits_identity_tests.rs +++ /dev/null @@ -1,236 +0,0 @@ -//! Account readiness is verified after an in-flight backend read, including concurrent login. - -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::ChatGptIdTokenClaims; -use app_test_support::TestAppServer; -use app_test_support::encode_id_token; -use app_test_support::write_chatgpt_auth; -use axum::Json; -use axum::Router; -use axum::http::HeaderMap; -use axum::routing::get; -use codex_app_server_protocol::GetAccountRateLimitsResponse; -use codex_app_server_protocol::LoginAccountResponse; -use codex_app_server_protocol::RequestId; -use codex_config::types::AuthCredentialsStoreMode; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::sync::Arc; -use std::time::Duration; -use tempfile::TempDir; -use test_case::test_case; -use tokio::net::TcpListener; -use tokio::sync::Notify; -use tokio::time::timeout; - -const READ_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10); - -#[test_case("workspace-a", "user-b", /*verified*/ false; "user_switch")] -#[test_case("workspace-b", "user-a", /*verified*/ false; "workspace_switch")] -#[test_case("workspace-a", "user-a", /*verified*/ true; "same_identity_token_refresh")] -#[tokio::test] -async fn identity_is_rechecked_after_backend_response( - account: &str, - user: &str, - verified: bool, -) -> Result<()> { - let old_token = encode_id_token( - &ChatGptIdTokenClaims::new() - .chatgpt_account_id("workspace-a") - .chatgpt_user_id("user-a"), - )?; - let home = TempDir::new()?; - write_chatgpt_auth( - home.path(), - ChatGptAuthFixture::new(&old_token) - .account_id("workspace-a") - .chatgpt_user_id("user-a") - .plan_type("team"), - AuthCredentialsStoreMode::File, - )?; - let entered = Arc::new(Notify::new()); - let release = Arc::new(Notify::new()); - let request_entered = Arc::clone(&entered); - let response_release = Arc::clone(&release); - let listener = TcpListener::bind("127.0.0.1:0").await?; - std::fs::write( - home.path().join("config.toml"), - format!("chatgpt_base_url = \"http://{}\"\n", listener.local_addr()?), - )?; - let expected_authorization = format!("Bearer {old_token}"); - let router = Router::new().route( - "/api/codex/usage", - get(move |headers: HeaderMap| { - let expected_authorization = expected_authorization.clone(); - let entered = Arc::clone(&request_entered); - let release = Arc::clone(&response_release); - async move { - assert_eq!(headers["authorization"], expected_authorization); - assert_eq!(headers["chatgpt-account-id"], "workspace-a"); - entered.notify_one(); - release.notified().await; - Json(json!({ - "account_id": "workspace-a", "user_id": "user-a", "plan_type": "team", - "rate_limit": {"allowed": true, "limit_reached": false, - "primary_window": {"used_percent": 42, "limit_window_seconds": 3600, - "reset_after_seconds": 120, "reset_at": 2000000000}} - })) - } - }), - ); - let server = tokio::spawn(async move { axum::serve(listener, router).await }); - let mut app = TestAppServer::builder() - .with_codex_home(home.path()) - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .build_initialized_with_timeout(READ_TIMEOUT) - .await?; - let initial_login = app - .send_chatgpt_auth_tokens_login_request( - old_token, - "workspace-a".into(), - Some("team".into()), - ) - .await?; - let _: LoginAccountResponse = app.read_response(initial_login).await?; - let request = app - .send_request( - "account/rateLimits/read", - Some(json!({"excludeResetCreditDetails": true})), - ) - .await?; - timeout(READ_TIMEOUT, entered.notified()).await?; - let token = encode_id_token( - &ChatGptIdTokenClaims::new() - .chatgpt_account_id(account) - .chatgpt_user_id(user) - .plan_type("team"), - )?; - let login = app - .send_chatgpt_auth_tokens_login_request(token, account.into(), Some("team".into())) - .await?; - let response: LoginAccountResponse = timeout(READ_TIMEOUT, app.read_response(login)).await??; - assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {}); - release.notify_one(); - if !verified { - let error = timeout( - READ_TIMEOUT, - app.read_stream_until_error_message(RequestId::Integer(request)), - ) - .await??; - server.abort(); - assert_eq!( - error.error.message, - "failed to fetch codex rate limits: application network permission was revoked" - ); - return Ok(()); - } - let response: GetAccountRateLimitsResponse = - timeout(READ_TIMEOUT, app.read_response(request)).await??; - server.abort(); - let snapshot = json!({ - "limitId": "codex", "planType": "team", - "primary": {"usedPercent": 42, "windowDurationMins": 60, "resetsAt": 2000000000} - }); - let expected: GetAccountRateLimitsResponse = serde_json::from_value(json!({ - "ordinaryUsageAllowed": if verified { Some(true) } else { None }, - "accountId": "workspace-a", - "rateLimits": snapshot, "rateLimitsByLimitId": {"codex": snapshot} - }))?; - assert_eq!(response, expected); - Ok(()) -} - -#[test_case(false; "same_login")] -#[test_case(true; "same_user_external_login")] -#[tokio::test] -async fn security_setup_rechecks_login_mode_after_backend_response( - change_login: bool, -) -> Result<()> { - use codex_app_server_protocol::GetAccountSecuritySetupResponse; - - let token = encode_id_token( - &ChatGptIdTokenClaims::new() - .chatgpt_account_id("workspace-a") - .chatgpt_user_id("user-a"), - )?; - let home = TempDir::new()?; - write_chatgpt_auth( - home.path(), - ChatGptAuthFixture::new(&token) - .account_id("workspace-a") - .chatgpt_user_id("user-a") - .plan_type("team"), - AuthCredentialsStoreMode::File, - )?; - let entered = Arc::new(Notify::new()); - let release = Arc::new(Notify::new()); - let request_entered = Arc::clone(&entered); - let response_release = Arc::clone(&release); - let listener = TcpListener::bind("127.0.0.1:0").await?; - std::fs::write( - home.path().join("config.toml"), - format!( - "chatgpt_base_url = \"http://{}/backend-api\"\n", - listener.local_addr()? - ), - )?; - let expected_authorization = format!("Bearer {token}"); - let router = Router::new().route( - "/backend-api/wham/security-setup", - get(move |headers: HeaderMap| { - let expected_authorization = expected_authorization.clone(); - let entered = Arc::clone(&request_entered); - let release = Arc::clone(&response_release); - async move { - assert_eq!(headers["authorization"], expected_authorization); - assert_eq!(headers["chatgpt-account-id"], "workspace-a"); - entered.notify_one(); - release.notified().await; - Json(json!({"notice": { - "title": "Set up security", - "description": "Account security reminder", - "action": {"label": "Settings", "url": "https://chatgpt.com/cyber"} - }})) - } - }), - ); - let server = tokio::spawn(async move { axum::serve(listener, router).await }); - let mut app = TestAppServer::builder() - .with_codex_home(home.path()) - .without_auto_env() - .with_env_overrides(&[("OPENAI_API_KEY", None)]) - .build_initialized_with_timeout(READ_TIMEOUT) - .await?; - let request = app - .send_request("account/securitySetup/read", /*params*/ None) - .await?; - timeout(READ_TIMEOUT, entered.notified()).await?; - if change_login { - let login = app - .send_chatgpt_auth_tokens_login_request( - token, - "workspace-a".into(), - Some("team".into()), - ) - .await?; - let response: LoginAccountResponse = - timeout(READ_TIMEOUT, app.read_response(login)).await??; - assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {}); - } - release.notify_one(); - let response: GetAccountSecuritySetupResponse = - timeout(READ_TIMEOUT, app.read_response(request)).await??; - server.abort(); - if change_login { - assert_eq!(response.notice, None); - } else { - let notice = response - .notice - .expect("unchanged saved login gets its notice"); - assert_eq!(notice.account_id, "workspace-a"); - assert_eq!(notice.user_id, "user-a"); - assert_eq!(notice.title, "Set up security"); - } - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/v2/recommended_plugins.rs b/codex-rs/app-server/tests/suite/v2/recommended_plugins.rs deleted file mode 100644 index 0d8ddf5a..00000000 --- a/codex-rs/app-server/tests/suite/v2/recommended_plugins.rs +++ /dev/null @@ -1,225 +0,0 @@ -use anyhow::Result; -use anyhow::bail; -use app_test_support::ChatGptIdTokenClaims; -use app_test_support::TestAppServer; -use app_test_support::encode_id_token; -use app_test_support::to_response; -use app_test_support::write_mock_responses_config_toml_with_chatgpt_base_url; -use codex_app_server_protocol::AccountLoginCompletedNotification; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::LoginAccountResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::ThreadStartParams; -use codex_app_server_protocol::ThreadStartResponse; -use codex_app_server_protocol::TurnStartParams; -use codex_app_server_protocol::UserInput; -use core_test_support::apps_test_server::AppsTestServer; -use core_test_support::responses; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use std::time::Duration; -use tempfile::TempDir; -use tokio::time::timeout; -use wiremock::Mock; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; - -const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(20); -const WORKSPACE_ID: &str = "123e4567-e89b-42d3-a456-426614174010"; - -enum ToolSuggestFeature { - Enabled, - Disabled, -} - -#[tokio::test] -async fn first_turn_after_external_login_waits_for_recommended_plugins() -> Result<()> { - recommended_plugins_after_external_login(ToolSuggestFeature::Enabled).await -} - -#[tokio::test] -async fn first_turn_after_external_login_waits_for_recommended_plugins_without_tool_suggest() --> Result<()> { - recommended_plugins_after_external_login(ToolSuggestFeature::Disabled).await -} - -async fn recommended_plugins_after_external_login( - tool_suggest_feature: ToolSuggestFeature, -) -> Result<()> { - let tool_suggest_enabled = matches!(tool_suggest_feature, ToolSuggestFeature::Enabled); - let recommended_plugins_config = if tool_suggest_enabled { - "" - } else { - "recommended_plugins = true\n" - }; - let server = responses::start_mock_server().await; - let apps_server = AppsTestServer::mount(&server).await?; - Mock::given(method("GET")) - .and(path("/ps/plugins/suggested/codex")) - .and(query_param("scope", "GLOBAL")) - .respond_with( - ResponseTemplate::new(200) - .set_delay(Duration::from_millis(250)) - .set_body_json(json!({ - "enabled": true, - "plugins": [{ - "id": "plugin_github", - "name": "github", - "display_name": "GitHub" - }] - })), - ) - .expect(1) - .mount(&server) - .await; - let response = responses::sse(vec![ - responses::ev_response_created("resp-1"), - responses::ev_assistant_message("msg-1", "done"), - responses::ev_completed("resp-1"), - ]); - let responses_mock = responses::mount_sse_once(&server, response).await; - - let codex_home = TempDir::new()?; - write_mock_responses_config_toml_with_chatgpt_base_url( - codex_home.path(), - &server.uri(), - &apps_server.chatgpt_base_url, - )?; - let config_path = codex_home.path().join("config.toml"); - let config = std::fs::read_to_string(&config_path)?; - std::fs::write( - config_path, - format!( - "{config}\n[features]\napps = true\nplugins = true\ntool_suggest = {tool_suggest_enabled}\n{recommended_plugins_config}" - ), - )?; - - let sqlite_home = codex_home.path().to_string_lossy(); - let mut app_server = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .without_managed_config() - .with_env_overrides(&[("CODEX_SQLITE_HOME", Some(sqlite_home.as_ref()))]) - .build() - .await?; - timeout(DEFAULT_READ_TIMEOUT, app_server.initialize()).await??; - - let access_token = encode_id_token( - &ChatGptIdTokenClaims::new() - .email("embedded@example.com") - .plan_type("pro") - .chatgpt_account_id(WORKSPACE_ID), - )?; - let login_id = app_server - .send_chatgpt_auth_tokens_login_request( - access_token, - WORKSPACE_ID.to_string(), - Some("pro".to_string()), - ) - .await?; - let login_response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - app_server.read_stream_until_response_message(RequestId::Integer(login_id)), - ) - .await??; - assert_eq!( - to_response::(login_response)?, - LoginAccountResponse::ChatgptAuthTokens {} - ); - - // Login clears the recommendation cache after its RPC response. Wait for completion so - // thread startup and the background refresh share the same cache generation. - let notification = timeout( - DEFAULT_READ_TIMEOUT, - app_server.read_stream_until_notification_message("account/login/completed"), - ) - .await??; - let ServerNotification::AccountLoginCompleted(payload) = notification.try_into()? else { - bail!("unexpected notification") - }; - assert_eq!( - payload, - AccountLoginCompletedNotification { - login_id: None, - success: true, - error: None, - onboarding_entrypoint: None, - } - ); - - let thread_id = app_server - .send_thread_start_request_with_auto_env(ThreadStartParams { - model: Some("mock-model".to_string()), - ..Default::default() - }) - .await?; - let thread_response: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - app_server.read_stream_until_response_message(RequestId::Integer(thread_id)), - ) - .await??; - let ThreadStartResponse { thread, .. } = to_response(thread_response)?; - - let turn_id = app_server - .send_turn_start_request(TurnStartParams { - thread_id: thread.id, - input: vec![UserInput::Text { - text: "suggest a plugin".to_string(), - text_elements: Vec::new(), - }], - ..Default::default() - }) - .await?; - let _: JSONRPCResponse = timeout( - DEFAULT_READ_TIMEOUT, - app_server.read_stream_until_response_message(RequestId::Integer(turn_id)), - ) - .await??; - timeout( - DEFAULT_READ_TIMEOUT, - app_server.read_stream_until_notification_message("turn/completed"), - ) - .await??; - - let requests = responses_mock.requests(); - let request = requests - .iter() - .find(|request| { - request - .message_input_texts("user") - .iter() - .any(|text| text.contains("suggest a plugin")) - }) - .expect("turn request"); - let recommendations = request - .message_input_texts("developer") - .into_iter() - .filter(|text| text.starts_with("")) - .collect::>(); - assert_eq!( - recommendations, - vec![concat!( - "\n", - "Here is a list of plugins that are available but not installed.\n\n", - "- GitHub (github@openai-curated-remote)\n", - "", - )] - ); - let body = request.body_json(); - let tool_names = body - .get("tools") - .and_then(Value::as_array) - .into_iter() - .flatten() - .filter_map(|tool| tool.get("name").and_then(Value::as_str)) - .collect::>(); - assert_eq!( - tool_names.contains(&"request_plugin_install"), - tool_suggest_enabled - ); - assert!(!tool_names.contains(&"list_available_plugins_to_install")); - Ok(()) -} diff --git a/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs b/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs index 13c983ab..90b318f0 100644 --- a/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs +++ b/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs @@ -9,14 +9,11 @@ use app_test_support::create_final_assistant_message_sse_response; use app_test_support::to_response; use app_test_support::write_chatgpt_auth; use app_test_support::write_mock_responses_config_toml_with_chatgpt_base_url; -use codex_app_server_protocol::AppInfo; use codex_app_server_protocol::CapabilityRootLocation; use codex_app_server_protocol::EnvironmentAddResponse; use codex_app_server_protocol::EnvironmentInfoResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SelectedCapabilityRoot; -use codex_app_server_protocol::ThreadResumeParams; -use codex_app_server_protocol::ThreadResumeResponse; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; use codex_app_server_protocol::TurnEnvironmentParams; @@ -25,7 +22,6 @@ use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::UserInput; use codex_config::types::AuthCredentialsStoreMode; use codex_exec_server::LOCAL_ENVIRONMENT_ID; -use codex_protocol::protocol::PLUGINS_INSTRUCTIONS_OPEN_TAG; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::PathUri; use core_test_support::process::wait_for_pid_file; @@ -33,7 +29,6 @@ use core_test_support::responses; use core_test_support::responses::ResponsesRequest; use core_test_support::stdio_server_bin; use pretty_assertions::assert_eq; -use pretty_assertions::assert_ne; use serde_json::json; use tempfile::TempDir; use test_case::test_case; @@ -45,8 +40,6 @@ use tokio::time::timeout; use super::analytics::mount_analytics_capture; use super::analytics::wait_for_matching_analytics_event; -use super::app_list::connector_tool; -use super::app_list::start_apps_server_with_delays; const READ_TIMEOUT: Duration = Duration::from_secs(20); const EXECUTOR_ID: &str = "executor-1"; @@ -62,7 +55,6 @@ const NO_SELECTED_SKILLS_MESSAGE: &str = "No selected-environment skills are cur const RESTORED_SELECTED_SKILLS_MESSAGE: &str = "The previously listed selected-environment skills are available again."; const MCP_SERVER_NAME: &str = "executor_probe"; -const MCP_CALL_ID: &str = "selected-executor-mcp-call"; const CONNECTOR_ID: &str = "calendar"; #[derive(Clone, Copy)] @@ -196,314 +188,6 @@ async fn selected_plugin_mcp_startup_respects_explicit_mentions( Ok(()) } -#[test_case(false; "direct selected root discovery")] -#[test_case(true; "batched executor capability discovery")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn managed_plugins_requirement_disables_selected_executor_plugin_capabilities( - executor_capability_discovery: bool, -) -> Result<()> { - let responses_server = responses::start_mock_server().await; - let (apps_url, apps_server_handle) = start_apps_server_with_delays( - vec![AppInfo { - id: CONNECTOR_ID.to_string(), - name: "Calendar".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }], - vec![connector_tool(CONNECTOR_ID, "Calendar")?], - Duration::ZERO, - Duration::ZERO, - ) - .await?; - let fixture = selected_capability_fixture(&responses_server.uri(), &apps_url)?; - let config_path = fixture.codex_home.path().join("config.toml"); - let config = std::fs::read_to_string(&config_path)?.replace( - "executor_capability_discovery = true", - &format!("executor_capability_discovery = {executor_capability_discovery}\nplugins = true"), - ); - std::fs::write(config_path, config)?; - std::fs::write( - fixture.codex_home.path().join("requirements.toml"), - "[features]\nplugins = false\n", - )?; - let response_mock = responses::mount_sse_once( - &responses_server, - responses::sse(vec![ - responses::ev_response_created("disabled-selected-plugin"), - responses::ev_assistant_message("disabled-selected-plugin-message", "Done"), - responses::ev_completed("disabled-selected-plugin"), - ]), - ) - .await; - - let mut app_server = TestAppServer::builder() - .with_codex_home(fixture.codex_home.path()) - .without_auto_env() - .build() - .await?; - timeout(READ_TIMEOUT, app_server.initialize()).await??; - let thread_id = start_thread( - &mut app_server, - fixture.selected_root, - fixture.environment_cwd.clone(), - ) - .await?; - let mut exec_server = - spawn_exec_server(fixture.codex_home.path(), &fixture.exec_server_url).await?; - add_environment(&mut app_server, &fixture.exec_server_url).await?; - - run_turn( - &mut app_server, - &thread_id, - "Inspect the disabled selected plugin capabilities", - fixture.environment_cwd, - &[LOCAL_ENVIRONMENT_ID, EXECUTOR_ID], - ) - .await?; - - assert!( - !fixture.pid_file.exists(), - "the disabled selected plugin MCP server must never start" - ); - assert_selected_capabilities_absent(&response_mock.single_request()); - - exec_server.kill().await?; - apps_server_handle.abort(); - let _ = apps_server_handle.await; - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn selected_capability_stack_tracks_environment_selection_and_resume() -> Result<()> { - let responses_server = responses::start_mock_server().await; - let (apps_url, apps_server_handle) = start_apps_server_with_delays( - vec![AppInfo { - id: CONNECTOR_ID.to_string(), - name: "Calendar".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - icon_assets: None, - icon_dark_assets: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }], - vec![connector_tool(CONNECTOR_ID, "Calendar")?], - Duration::ZERO, - Duration::ZERO, - ) - .await?; - let fixture = selected_capability_fixture(&responses_server.uri(), &apps_url)?; - - let response_mock = responses::mount_sse_sequence( - &responses_server, - vec![ - responses::sse(vec![ - responses::ev_response_created("environment-unavailable"), - responses::ev_assistant_message("unavailable-message", "Waiting"), - responses::ev_completed("environment-unavailable"), - ]), - responses::sse(vec![ - responses::ev_response_created("environment-available-call"), - responses::ev_function_call_with_namespace( - MCP_CALL_ID, - &format!("mcp__{MCP_SERVER_NAME}"), - "echo", - &json!({ - "message": "hello from the selected executor", - "env_var": EXECUTOR_ENV_NAME, - }) - .to_string(), - ), - responses::ev_completed("environment-available-call"), - ]), - responses::sse(vec![ - responses::ev_response_created("environment-available-done"), - responses::ev_assistant_message("available-message", "Done"), - responses::ev_completed("environment-available-done"), - ]), - responses::sse(vec![ - responses::ev_response_created("unchanged-step"), - responses::ev_assistant_message("unchanged-message", "Still ready"), - responses::ev_completed("unchanged-step"), - ]), - responses::sse(vec![ - responses::ev_response_created("resumed-unavailable-step"), - responses::ev_assistant_message( - "resumed-unavailable-message", - "Unavailable after resume", - ), - responses::ev_completed("resumed-unavailable-step"), - ]), - responses::sse(vec![ - responses::ev_response_created("reattached-step"), - responses::ev_assistant_message("reattached-message", "Ready after reattach"), - responses::ev_completed("reattached-step"), - ]), - ], - ) - .await; - - let mut app_server = TestAppServer::builder() - .with_codex_home(fixture.codex_home.path()) - // This fixture owns environments.toml and selects its environments explicitly. - .without_auto_env() - .build() - .await?; - timeout(READ_TIMEOUT, app_server.initialize()).await??; - let thread_id = start_thread( - &mut app_server, - fixture.selected_root.clone(), - fixture.environment_cwd.clone(), - ) - .await?; - - run_turn( - &mut app_server, - &thread_id, - "Inspect the current capabilities", - fixture.environment_cwd.clone(), - &[LOCAL_ENVIRONMENT_ID], - ) - .await?; - let initial_requests = response_mock.requests(); - assert_selected_capabilities_absent(&initial_requests[0]); - - let mut exec_server = - spawn_exec_server(fixture.codex_home.path(), &fixture.exec_server_url).await?; - add_environment(&mut app_server, &fixture.exec_server_url).await?; - - // The next turn selects the executor; its server mention waits for MCP startup. - run_turn( - &mut app_server, - &thread_id, - &format!("Use ${SKILL_NAME} and call [${MCP_SERVER_NAME}](mcp://{MCP_SERVER_NAME})"), - fixture.environment_cwd.clone(), - &[LOCAL_ENVIRONMENT_ID, EXECUTOR_ID], - ) - .await?; - let first_mcp_pid = wait_for_pid_file(&fixture.pid_file).await?; - - run_turn( - &mut app_server, - &thread_id, - "Continue with the same selected capabilities", - fixture.environment_cwd.clone(), - &[LOCAL_ENVIRONMENT_ID, EXECUTOR_ID], - ) - .await?; - assert_eq!(first_mcp_pid, wait_for_pid_file(&fixture.pid_file).await?); - - exec_server.kill().await?; - drop(app_server); - std::fs::remove_file(&fixture.pid_file)?; - - let mut app_server = TestAppServer::builder() - .with_codex_home(fixture.codex_home.path()) - // This fixture owns environments.toml and selects its environments explicitly. - .without_auto_env() - .build() - .await?; - timeout(READ_TIMEOUT, app_server.initialize()).await??; - let request_id = app_server - .send_thread_resume_request(ThreadResumeParams { - thread_id: thread_id.clone(), - ..Default::default() - }) - .await?; - let response = timeout( - READ_TIMEOUT, - app_server.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let ThreadResumeResponse { thread, .. } = to_response(response)?; - assert_eq!(thread_id, thread.id); - - run_turn( - &mut app_server, - &thread_id, - "Inspect capabilities while the selected executor is unavailable", - fixture.environment_cwd.clone(), - &[LOCAL_ENVIRONMENT_ID], - ) - .await?; - let requests = response_mock.requests(); - assert_eq!(5, requests.len()); - assert_selected_plugin_tools_absent(&requests[4]); - assert!( - latest_selected_skill_update(&requests[4]) - .is_some_and(|text| text.contains(NO_SELECTED_SKILLS_MESSAGE)) - ); - - exec_server = spawn_exec_server(fixture.codex_home.path(), &fixture.exec_server_url).await?; - add_environment(&mut app_server, &fixture.exec_server_url).await?; - - run_turn( - &mut app_server, - &thread_id, - &format!( - "Use ${SKILL_NAME} with [${MCP_SERVER_NAME}](mcp://{MCP_SERVER_NAME}) after reattaching the selected executor" - ), - fixture.environment_cwd, - &[LOCAL_ENVIRONMENT_ID, EXECUTOR_ID], - ) - .await?; - let resumed_mcp_pid = wait_for_pid_file(&fixture.pid_file).await?; - assert_ne!(first_mcp_pid, resumed_mcp_pid); - - let requests = response_mock.requests(); - assert_eq!(6, requests.len()); - for request in &requests[1..4] { - assert_selected_skill_is_injected(request, /*expected_count*/ 1); - assert_selected_plugin_tools(request); - assert_plugin_guidance_count(request, /*expected_count*/ 0); - } - assert_plugin_guidance_count(&requests[4], /*expected_count*/ 0); - assert_selected_skill_is_injected(&requests[5], /*expected_count*/ 2); - assert!( - latest_selected_skill_update(&requests[5]) - .is_some_and(|text| text.contains(RESTORED_SELECTED_SKILLS_MESSAGE)) - ); - assert_eq!( - 1, - requests[5] - .message_input_texts("developer") - .into_iter() - .filter(|text| text.contains(SKILL_DESCRIPTION)) - .count(), - "reattaching should retain the original catalog without repeating it" - ); - assert_selected_plugin_tools(&requests[5]); - let output = requests[2].function_call_output(MCP_CALL_ID); - let output = output["output"] - .as_str() - .expect("MCP function output should be text"); - assert!(output.contains("ECHOING: hello from the selected executor")); - assert!(output.contains(EXECUTOR_ENV_VALUE)); - - exec_server.kill().await?; - apps_server_handle.abort(); - let _ = apps_server_handle.await; - Ok(()) -} - struct SelectedCapabilityFixture { codex_home: TempDir, _plugin: TempDir, @@ -635,60 +319,6 @@ fn selected_capability_fixture( }) } -fn assert_selected_capabilities_absent(request: &ResponsesRequest) { - assert!( - request - .message_input_texts("developer") - .into_iter() - .all(|text| !text.contains(SKILL_DESCRIPTION)) - ); - assert_selected_plugin_tools_absent(request); - assert_plugin_guidance_count(request, /*expected_count*/ 0); -} - -fn assert_selected_plugin_tools_absent(request: &ResponsesRequest) { - assert!( - request - .tool_by_name(&format!("mcp__{MCP_SERVER_NAME}"), "echo") - .is_none() - ); - let connector = request - .tool_by_name("mcp__codex_apps__calendar", "connector_calendar") - .expect("host connector should remain model-visible"); - assert!( - connector["description"] - .as_str() - .is_some_and(|description| !description.contains(PLUGIN_DISPLAY_NAME)) - ); -} - -fn assert_plugin_guidance_count(request: &ResponsesRequest, expected_count: usize) { - assert_eq!( - expected_count, - request - .message_input_texts("developer") - .into_iter() - .filter(|text| text.starts_with(PLUGINS_INSTRUCTIONS_OPEN_TAG)) - .count() - ); -} - -fn assert_selected_skill_is_injected(request: &ResponsesRequest, expected_count: usize) { - assert_selected_skill_catalog_available(request); - - let skill_fragments = request - .message_input_texts("user") - .into_iter() - .filter(|text| text.starts_with("")) - .collect::>(); - assert_eq!(expected_count, skill_fragments.len()); - for fragment in skill_fragments { - assert!(fragment.contains(&format!("{SKILL_NAME}"))); - assert!(fragment.contains(SKILL_BODY_MARKER)); - assert!(!fragment.contains(LOCAL_SKILL_BODY_MARKER)); - } -} - fn assert_selected_skill_catalog_available(request: &ResponsesRequest) { let latest_update = latest_selected_skill_update(request) .expect("selected skill availability should be model-visible"); @@ -712,22 +342,6 @@ fn latest_selected_skill_update(request: &ResponsesRequest) -> Option { }) } -fn assert_selected_plugin_tools(request: &ResponsesRequest) { - assert!( - request - .tool_by_name(&format!("mcp__{MCP_SERVER_NAME}"), "echo") - .is_some() - ); - let connector = request - .tool_by_name("mcp__codex_apps__calendar", "connector_calendar") - .expect("selected connector should be model-visible"); - assert!( - connector["description"] - .as_str() - .is_some_and(|description| description.contains(PLUGIN_DISPLAY_NAME)) - ); -} - async fn start_thread( app_server: &mut TestAppServer, selected_root: SelectedCapabilityRoot, @@ -754,46 +368,6 @@ async fn start_thread( Ok(thread.id) } -async fn run_turn( - app_server: &mut TestAppServer, - thread_id: &str, - text: &str, - environment_cwd: AbsolutePathBuf, - environment_ids: &[&str], -) -> Result<()> { - let request_id = app_server - .send_turn_start_request(TurnStartParams { - thread_id: thread_id.to_string(), - input: vec![UserInput::Text { - text: text.to_string(), - text_elements: Vec::new(), - }], - environments: Some( - environment_ids - .iter() - .map(|environment_id| TurnEnvironmentParams { - environment_id: (*environment_id).to_string(), - cwd: environment_cwd.clone().into(), - runtime_workspace_roots: None, - }) - .collect(), - ), - ..Default::default() - }) - .await?; - timeout( - READ_TIMEOUT, - app_server.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - timeout( - READ_TIMEOUT, - app_server.read_stream_until_notification_message("turn/completed"), - ) - .await??; - Ok(()) -} - async fn add_environment(app_server: &mut TestAppServer, exec_server_url: &str) -> Result<()> { let request_id = app_server .send_raw_request( diff --git a/codex-rs/cli/Cargo.toml b/codex-rs/cli/Cargo.toml index adcc4c7c..c5dcc6bc 100644 --- a/codex-rs/cli/Cargo.toml +++ b/codex-rs/cli/Cargo.toml @@ -39,7 +39,6 @@ codex-app-server-test-client = { workspace = true } codex-arg0 = { workspace = true } codex-build-info = { workspace = true } codex-api = { workspace = true } -codex-cloud-config = { workspace = true } codex-utils-cli = { workspace = true } codex-config = { workspace = true } codex-core = { workspace = true } diff --git a/codex-rs/cli/src/cloud_config.rs b/codex-rs/cli/src/cloud_config.rs index 8a0f1f37..8be267a0 100644 --- a/codex-rs/cli/src/cloud_config.rs +++ b/codex-rs/cli/src/cloud_config.rs @@ -1,16 +1,11 @@ use anyhow::Context; use anyhow::Result; use codex_app_server::in_process::EmbeddedNetworkPolicy; -use codex_cloud_config::managed_config_bundle_loader_for_storage; -use codex_config::CloudConfigBundleLoader; -use codex_config::ConfigLoadOptions; use codex_core::config::Config; use codex_core::config::ConfigBuilder; use codex_core::config::ConfigOverrides; use codex_core::config::LoaderOverrides; -use codex_core::config::bootstrap_auth_config; use codex_core::config::find_codex_home; -use codex_core::config::load_config_toml_with_layer_stack; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_cli::CliConfigOverrides; @@ -32,12 +27,13 @@ pub async fn load_config( Ok(config) } +/// Builds a config from local files only; aKode never fetches managed config +/// bundles from a remote service. pub async fn config_builder( config_overrides: &CliConfigOverrides, loader_overrides: LoaderOverrides, harness_overrides: ConfigOverrides, ) -> Result { - let network_policy = EmbeddedNetworkPolicy::load(&loader_overrides).await; let cli_overrides = config_overrides .parse_overrides() .map_err(anyhow::Error::msg)?; @@ -47,34 +43,11 @@ pub async fn config_builder( None => AbsolutePathBuf::current_dir(), } .context("failed to resolve current directory")?; - let bootstrap_config = load_config_toml_with_layer_stack( - codex_home.as_path(), - Some(&cwd), - cli_overrides.clone(), - ConfigLoadOptions { - loader_overrides: loader_overrides.clone(), - strict_config: false, - cloud_config_bundle: CloudConfigBundleLoader::default(), - }, - ) - .await - .context("failed to load bootstrap configuration")?; - let cloud_config_bundle = managed_config_bundle_loader_for_storage( - network_policy.bind_bootstrap_auth( - bootstrap_auth_config(codex_home.as_path(), &bootstrap_config) - .context("failed to resolve cloud configuration authentication")?, - ), - bootstrap_config.config_layer_stack.requirements_toml(), - /*enable_codex_api_key_env*/ false, - ) - .await - .context("failed to initialize cloud configuration authentication")?; Ok(ConfigBuilder::default() .codex_home(codex_home.to_path_buf()) .cli_overrides(cli_overrides) .loader_overrides(loader_overrides) .harness_overrides(harness_overrides) - .cloud_config_bundle(cloud_config_bundle) .fallback_cwd(Some(cwd.to_path_buf()))) } diff --git a/codex-rs/cli/src/debug_sandbox.rs b/codex-rs/cli/src/debug_sandbox.rs index 04ebcf16..0ac491bd 100644 --- a/codex-rs/cli/src/debug_sandbox.rs +++ b/codex-rs/cli/src/debug_sandbox.rs @@ -1,4 +1,3 @@ -mod cloud_config; #[cfg(target_os = "macos")] mod pid_tracker; #[cfg(target_os = "macos")] @@ -663,20 +662,12 @@ async fn load_debug_sandbox_config( options: DebugSandboxConfigOptions, strict_config: bool, ) -> anyhow::Result { - let cloud_config_bundle = cloud_config::bootstrap_cloud_config_bundle( - &cli_overrides, - &options, - find_codex_home, - strict_config, - ) - .await?; - load_debug_sandbox_config_with_codex_home( cli_overrides, codex_linux_sandbox_exe, options, /*codex_home*/ None, - cloud_config_bundle, + CloudConfigBundleLoader::default(), strict_config, ) .await diff --git a/codex-rs/cli/src/debug_sandbox/cloud_config.rs b/codex-rs/cli/src/debug_sandbox/cloud_config.rs deleted file mode 100644 index 2cbc7445..00000000 --- a/codex-rs/cli/src/debug_sandbox/cloud_config.rs +++ /dev/null @@ -1,57 +0,0 @@ -use codex_app_server::in_process::EmbeddedNetworkPolicy; -use codex_cloud_config::chatgpt_config_bundle_loader_for_storage; -use codex_config::CloudConfigBundleLoader; -use codex_config::ConfigLoadOptions; -use codex_core::config::bootstrap_auth_config; -use codex_core::config::load_config_toml_with_layer_stack; -use codex_utils_absolute_path::AbsolutePathBuf; -use toml::Value as TomlValue; - -use super::DebugSandboxConfigOptions; -use super::ManagedRequirementsMode; - -pub(super) async fn bootstrap_cloud_config_bundle( - cli_overrides: &[(String, TomlValue)], - options: &DebugSandboxConfigOptions, - resolve_codex_home: impl FnOnce() -> std::io::Result, - strict_config: bool, -) -> anyhow::Result { - if options.sandbox_state.sandbox_state_json.is_some() - || !matches!( - options.managed_requirements_mode, - ManagedRequirementsMode::Include - ) - { - return Ok(CloudConfigBundleLoader::default()); - } - - let codex_home = resolve_codex_home()?; - let cwd = match options.cwd.as_deref() { - Some(cwd) => AbsolutePathBuf::relative_to_current_dir(cwd)?, - None => AbsolutePathBuf::current_dir()?, - }; - let network_policy = EmbeddedNetworkPolicy::load(&options.loader_overrides).await; - let bootstrap_config = load_config_toml_with_layer_stack( - codex_home.as_path(), - Some(&cwd), - cli_overrides.to_vec(), - ConfigLoadOptions { - loader_overrides: options.loader_overrides.clone(), - strict_config, - cloud_config_bundle: CloudConfigBundleLoader::default(), - }, - ) - .await?; - Ok(chatgpt_config_bundle_loader_for_storage( - network_policy.bind_bootstrap_auth(bootstrap_auth_config( - codex_home.as_path(), - &bootstrap_config, - )?), - /*enable_codex_api_key_env*/ false, - ) - .await?) -} - -#[cfg(test)] -#[path = "cloud_config_tests.rs"] -mod tests; diff --git a/codex-rs/cli/src/debug_sandbox/cloud_config_tests.rs b/codex-rs/cli/src/debug_sandbox/cloud_config_tests.rs deleted file mode 100644 index 4333375c..00000000 --- a/codex-rs/cli/src/debug_sandbox/cloud_config_tests.rs +++ /dev/null @@ -1,185 +0,0 @@ -use anyhow::Context; -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::write_chatgpt_auth; -use codex_config::ConfigRequirementsToml; -use codex_config::LoaderOverrides; -use codex_config::types::AuthCredentialsStoreMode; -use codex_protocol::permissions::NetworkSandboxPolicy; -use codex_utils_absolute_path::AbsolutePathBuf; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use tempfile::TempDir; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; - -use super::super::DebugSandboxConfigOptions; -use super::super::ManagedRequirementsMode; -use super::super::load_debug_sandbox_config_with_codex_home; -use super::bootstrap_cloud_config_bundle; - -const CLOUD_MANAGED_PERMISSION_PROFILE_REQUIREMENTS: &str = r#" -default_permissions = "managed-cloud" - -[allowed_permission_profiles] -managed-cloud = true - -[permissions.managed-cloud] -extends = ":workspace" - -[permissions.managed-cloud.network] -enabled = true -"#; - -#[tokio::test] -async fn sandbox_fetches_managed_profile_only_when_local_policy_allows_backend() -> Result<()> { - let server = MockServer::start().await; - let expected_requirements = json!([{ - "id": "req-managed-cloud", - "name": "Managed permissions", - "contents": CLOUD_MANAGED_PERMISSION_PROFILE_REQUIREMENTS, - }]); - Mock::given(method("GET")) - .and(path("/backend-api/wham/config/bundle")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "workspace-123")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "requirements_toml": { - "enterprise_managed": expected_requirements.clone(), - }, - }))) - .expect(1) - .mount(&server) - .await; - - let codex_home = TempDir::new()?; - std::fs::write( - codex_home.path().join("config.toml"), - format!( - "cli_auth_credentials_store = \"file\"\nchatgpt_base_url = \"{}/backend-api\"\n", - server.uri(), - ), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("workspace-123") - .chatgpt_account_id("workspace-123") - .chatgpt_user_id("user-123") - .plan_type("enterprise"), - AuthCredentialsStoreMode::File, - )?; - - let mut options = DebugSandboxConfigOptions { - sandbox_state: Default::default(), - permissions_profile: None, - cwd: Some(codex_home.path().to_path_buf()), - managed_requirements_mode: ManagedRequirementsMode::Include, - loader_overrides: LoaderOverrides::without_managed_config_for_tests(), - }; - let bootstrap = async |options: &DebugSandboxConfigOptions| { - bootstrap_cloud_config_bundle( - &[], - options, - || AbsolutePathBuf::from_absolute_path(codex_home.path()), - /*strict_config*/ false, - ) - .await - }; - let requirements = codex_home.path().join("requirements.toml"); - std::fs::write(&requirements, "[application.network]\nenabled = true\n")?; - options.loader_overrides.system_requirements_path = Some(requirements); - let denied = bootstrap(&options) - .await? - .get() - .await - .expect_err("local policy denies the bundle endpoint"); - assert_eq!( - denied.to_string(), - "destination denied by application network policy" - ); - assert!( - server - .received_requests() - .await - .context("mock request log")? - .is_empty() - ); - - options.permissions_profile = Some("managed-cloud".to_string()); - options.loader_overrides = LoaderOverrides::without_managed_config_for_tests(); - let cloud_config_bundle = bootstrap(&options).await?; - let config = load_debug_sandbox_config_with_codex_home( - Vec::new(), - /*codex_linux_sandbox_exe*/ None, - options, - Some(codex_home.path().to_path_buf()), - cloud_config_bundle, - /*strict_config*/ false, - ) - .await?; - - assert_eq!( - config - .permissions - .active_permission_profile() - .map(|profile| profile.id), - Some("managed-cloud".to_string()), - ); - assert_eq!( - config.permissions.network_sandbox_policy(), - NetworkSandboxPolicy::Enabled, - ); - assert_eq!( - config.config_layer_stack.requirements_toml(), - &toml::from_str::(CLOUD_MANAGED_PERMISSION_PROFILE_REQUIREMENTS,)?, - ); - - let cache: Value = serde_json::from_slice(&std::fs::read( - codex_home.path().join("cloud-config-bundle-cache.json"), - )?)?; - assert_eq!( - json!({ - "chatgpt_user_id": cache["signed_payload"]["chatgpt_user_id"], - "account_id": cache["signed_payload"]["account_id"], - "requirements_toml": cache["signed_payload"]["bundle"]["requirements_toml"], - }), - json!({ - "chatgpt_user_id": "user-123", - "account_id": "workspace-123", - "requirements_toml": { - "enterprise_managed": expected_requirements, - }, - }), - ); - server.verify().await; - - Ok(()) -} - -#[tokio::test] -async fn sandbox_state_skips_cloud_bootstrap() -> Result<()> { - let options = DebugSandboxConfigOptions { - sandbox_state: crate::SandboxStateArgs { - sandbox_state_json: Some("{}".into()), - ..Default::default() - }, - permissions_profile: None, - cwd: None, - managed_requirements_mode: ManagedRequirementsMode::Include, - loader_overrides: LoaderOverrides::without_managed_config_for_tests(), - }; - bootstrap_cloud_config_bundle( - &[], - &options, - || panic!("supplied state must skip CODEX_HOME resolution"), - /*strict_config*/ false, - ) - .await?; - Ok(()) -} diff --git a/codex-rs/cli/src/login.rs b/codex-rs/cli/src/login.rs index a471e8cd..ee2bba68 100644 --- a/codex-rs/cli/src/login.rs +++ b/codex-rs/cli/src/login.rs @@ -172,25 +172,16 @@ pub async fn login_with_chatgpt( server.block_until_done().await } -/// Signs into the config server if needed, then reloads configuration. +/// Remote managed configuration (config server / cloud bundles) is not +/// supported in aKode: requirements that demand it cannot be satisfied. async fn sign_in_to_config_server_and_reload_config( - config: &mut Config, - cli_config_overrides: &CliConfigOverrides, + _config: &mut Config, + _cli_config_overrides: &CliConfigOverrides, ) -> std::io::Result<()> { - let requirements = config.config_layer_stack.requirements_toml(); - let network = codex_app_server::in_process::EmbeddedNetworkPolicy::load( - &codex_config::LoaderOverrides::default(), - ) - .await; - let bootstrap_auth = network.bind_bootstrap_auth(config.auth_config()); - let auth_route_config = bootstrap_auth.auth_route_config.clone(); - codex_cloud_config::ensure_config_server_login(bootstrap_auth, requirements).await?; - *config = crate::cloud_config::load_config(cli_config_overrides, Default::default()) - .await - .map_err(|error| std::io::Error::other(format!("{error:#}")))?; - network.activate(config); - config.application_auth_route_config = Some(auth_route_config); - Ok(()) + Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "remote managed configuration is not supported in aKode", + )) } fn finish_login(result: std::io::Result<()>) -> ! { @@ -553,29 +544,9 @@ pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! { } } -async fn logout_config_server(config: &Config) -> std::io::Result { - match codex_cloud_config::managed_config_auth_manager( - config.auth_config(), - config.config_layer_stack.requirements_toml(), - )? { - Some(manager) => manager.logout().await, - None => Ok(false), - } -} - pub async fn run_logout(cli_config_overrides: CliConfigOverrides) -> ! { let config = load_config_or_exit(cli_config_overrides).await; let auth_route_config = config.auth_route_config(); - let config_server_logout = if config - .config_layer_stack - .requirements_toml() - .requires_remote_config() - { - logout_config_server(&config).await - } else { - Ok(false) - }; - // Cleanup is independent of the current feature gate. Retain the grant lock // through account removal so another process cannot commit a late login. let enterprise_guard = async { @@ -641,14 +612,7 @@ pub async fn run_logout(cli_config_overrides: CliConfigOverrides) -> ! { false }; - let config_server_logged_out = match config_server_logout { - Ok(removed) => removed, - Err(error) => { - eprintln!("Error logging out: {error}"); - std::process::exit(1); - } - }; - if logged_out || config_server_logged_out || cleared_bedrock_config { + if logged_out || cleared_bedrock_config { eprintln!("Successfully logged out"); } else { eprintln!("Not logged in"); diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index 9bfe70fd..dc45513a 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -2013,8 +2013,6 @@ async fn run_debug_prompt_input_command( let user_instructions_provider = Arc::new(CodexHomeUserInstructionsProvider::new( config.codex_home.clone(), )); - let auth_manager = - AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await?; let mut extensions = codex_extension_api::ExtensionRegistryBuilder::new(); // Debug prompt construction bypasses app-server and needs its own extension registry. if config @@ -2023,12 +2021,7 @@ async fn run_debug_prompt_input_command( { codex_multi_env_copy_file::install(&mut extensions); } - codex_git_attribution::install( - &mut extensions, - auth_manager, - config.chatgpt_base_url.clone(), - config.http_client_factory(), - ); + codex_git_attribution::install(&mut extensions); codex_skills_extension::install(&mut extensions, |config: &Config| { codex_skills_extension::SkillsExtensionConfig { include_instructions: config.include_skill_instructions, diff --git a/codex-rs/cloud-config/BUILD.bazel b/codex-rs/cloud-config/BUILD.bazel deleted file mode 100644 index b11ed2ca..00000000 --- a/codex-rs/cloud-config/BUILD.bazel +++ /dev/null @@ -1,6 +0,0 @@ -load("//:defs.bzl", "codex_rust_crate") - -codex_rust_crate( - name = "cloud-config", - crate_name = "codex_cloud_config", -) diff --git a/codex-rs/cloud-config/Cargo.toml b/codex-rs/cloud-config/Cargo.toml deleted file mode 100644 index ad8a7521..00000000 --- a/codex-rs/cloud-config/Cargo.toml +++ /dev/null @@ -1,38 +0,0 @@ -[package] -name = "codex-cloud-config" -version.workspace = true -edition.workspace = true -license.workspace = true - -[lints] -workspace = true - -[dependencies] -base64 = { workspace = true } -chrono = { workspace = true, features = ["serde"] } -codex-async-utils = { workspace = true } -codex-backend-client = { workspace = true } -codex-config = { workspace = true } -codex-http-client = { workspace = true } -codex-keyring-store = { workspace = true } -codex-login = { workspace = true } -codex-otel = { workspace = true } -codex-protocol = { workspace = true } -hmac = "0.12.1" -serde = { workspace = true, features = ["derive"] } -serde_json = { workspace = true } -sha2 = { workspace = true } -tempfile = { workspace = true } -thiserror = { workspace = true } -tokio = { workspace = true, features = ["fs", "rt", "sync", "time"] } -tracing = { workspace = true } - -[dev-dependencies] -wiremock = { workspace = true } -codex-agent-identity = { workspace = true } -codex-core = { workspace = true } -pretty_assertions = { workspace = true } -tokio = { workspace = true, features = ["macros", "rt", "test-util", "time"] } - -[lib] -doctest = false diff --git a/codex-rs/cloud-config/src/backend.rs b/codex-rs/cloud-config/src/backend.rs deleted file mode 100644 index 68f337d5..00000000 --- a/codex-rs/cloud-config/src/backend.rs +++ /dev/null @@ -1,166 +0,0 @@ -use codex_backend_client::Client as BackendClient; -use codex_backend_client::ConfigBundleResponse; -use codex_backend_client::DeliveredTomlFragment; -use codex_config::CloudConfigBundle; -use codex_config::CloudConfigFragment; -use codex_config::CloudConfigTomlBundle; -use codex_config::CloudRequirementsFragment; -use codex_config::CloudRequirementsTomlBundle; -use codex_http_client::HttpClientFactory; -use codex_login::CodexAuth; -use std::future::Future; - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub(crate) enum RetryableFailureKind { - Request { status_code: Option }, - AuthRecovery { status_code: Option }, -} - -impl RetryableFailureKind { - pub(crate) fn status_code(self) -> Option { - match self { - Self::Request { status_code } | Self::AuthRecovery { status_code } => status_code, - } - } -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub(crate) enum BundleRequestError { - Policy(codex_http_client::NetworkPolicyDenied), - Fatal { - error: codex_config::CloudConfigBundleLoadError, - metric_reason: Option<&'static str>, - }, - Retryable(RetryableFailureKind), - Unauthorized { - status_code: Option, - message: String, - }, -} - -impl BundleRequestError { - pub(crate) fn auth_failure( - status_code: Option, - message: impl Into, - metric_reason: Option<&'static str>, - ) -> Self { - Self::Fatal { - error: codex_config::CloudConfigBundleLoadError::new( - codex_config::CloudConfigBundleLoadErrorCode::Auth, - status_code, - message, - ), - metric_reason, - } - } -} - -/// Retrieves one cloud config bundle from the backend. -/// -/// Implementations should return the backend-selected bundle exactly as delivered and leave -/// validation, caching, and config/requirements parsing decisions to the service layer. -pub(crate) trait BundleClient: Send + Sync { - fn get_bundle( - &self, - auth: &CodexAuth, - ) -> impl Future> + Send; -} - -pub(crate) struct BackendBundleClient { - base_url: String, - http_client_factory: HttpClientFactory, -} - -impl BackendBundleClient { - pub(crate) fn new(base_url: String, http_client_factory: HttpClientFactory) -> Self { - Self { - base_url, - http_client_factory, - } - } -} - -impl BundleClient for BackendBundleClient { - async fn get_bundle(&self, auth: &CodexAuth) -> Result { - let client = BackendClient::from_auth( - self.base_url.clone(), - auth, - self.http_client_factory.clone(), - ); - - fetch_bundle(&client).await - } -} - -pub(crate) async fn fetch_bundle( - client: &BackendClient, -) -> Result { - client - .get_config_bundle() - .await - .map(bundle_from_response) - .map_err(bundle_request_error) -} - -fn bundle_request_error(error: codex_backend_client::RequestError) -> BundleRequestError { - if let codex_backend_client::RequestError::Policy(denied) = &error { - return BundleRequestError::Policy(*denied); - } - let status_code = error.status().map(|status| status.as_u16()); - if error.is_unauthorized() { - BundleRequestError::Unauthorized { - status_code, - message: "Managed configuration sign-in is required".into(), - } - } else { - BundleRequestError::Retryable(RetryableFailureKind::Request { status_code }) - } -} - -pub(crate) fn bundle_from_response(response: ConfigBundleResponse) -> CloudConfigBundle { - let config_toml = response - .config_toml - .flatten() - .map(|config_toml| *config_toml) - .and_then(|config_toml| config_toml.enterprise_managed.flatten()) - .unwrap_or_default() - .into_iter() - .map(config_fragment_from_delivered) - .collect(); - let requirements_toml = response - .requirements_toml - .flatten() - .map(|requirements_toml| *requirements_toml) - .and_then(|requirements_toml| requirements_toml.enterprise_managed.flatten()) - .unwrap_or_default() - .into_iter() - .map(requirements_fragment_from_delivered) - .collect(); - - CloudConfigBundle { - config_toml: CloudConfigTomlBundle { - enterprise_managed: config_toml, - }, - requirements_toml: CloudRequirementsTomlBundle { - enterprise_managed: requirements_toml, - }, - } -} - -fn config_fragment_from_delivered(fragment: DeliveredTomlFragment) -> CloudConfigFragment { - CloudConfigFragment { - id: fragment.id, - name: fragment.name, - contents: fragment.contents, - } -} - -fn requirements_fragment_from_delivered( - fragment: DeliveredTomlFragment, -) -> CloudRequirementsFragment { - CloudRequirementsFragment { - id: fragment.id, - name: fragment.name, - contents: fragment.contents, - } -} diff --git a/codex-rs/cloud-config/src/bundle_loader.rs b/codex-rs/cloud-config/src/bundle_loader.rs deleted file mode 100644 index 9fc34002..00000000 --- a/codex-rs/cloud-config/src/bundle_loader.rs +++ /dev/null @@ -1,261 +0,0 @@ -use crate::backend::BackendBundleClient; -use crate::chatgpt::ChatGptSource; -use crate::chatgpt::plan_requires_managed_config; -use crate::config_server::config_server_http_client_factory; -use crate::config_source::BundleSource; -use crate::service::CLOUD_CONFIG_BUNDLE_TIMEOUT; -use crate::service::CloudConfigBundleService; -use codex_config::CloudConfigBundleLoader; -use codex_config::ConfigRequirementsToml; -use codex_http_client::HttpClientFactory; -use codex_login::AuthConfig; -use codex_login::AuthManager; -use codex_login::CodexAuth; -use codex_protocol::account::PlanType; -use std::path::PathBuf; -use std::sync::Arc; -use tokio::task::AbortHandle; -use tokio::task::JoinHandle; - -pub fn managed_config_auth_manager( - auth: AuthConfig, - requirements: &ConfigRequirementsToml, -) -> std::io::Result> { - let Some(service_config) = requirements.config_server.as_ref() else { - return Ok(None); - }; - let factory = config_server_http_client_factory(service_config, &auth.auth_route_config); - crate::config_server_auth_manager(service_config, auth.codex_home, &factory) -} - -/// Existing grants are left to the loader's normal cache and refresh handling. -pub async fn ensure_config_server_login( - auth: AuthConfig, - requirements: &ConfigRequirementsToml, -) -> std::io::Result<()> { - let Some(manager) = managed_config_auth_manager(auth, requirements)? else { - return Ok(()); - }; - if let Err(error) = manager.authorization_id().await { - if error - .get_ref() - .and_then(|source| source.downcast_ref::()) - != Some(&codex_login::OAuthSessionError::LoginRequired) - { - return Err(error); - } - manager.login().await?; - } - Ok(()) -} - -pub fn managed_config_bundle_loader( - auth_manager: Arc, - chatgpt_base_url: String, - codex_home: PathBuf, - factory: HttpClientFactory, - requirements: &ConfigRequirementsToml, -) -> CloudConfigBundleLoader { - if let Some(service_config) = requirements.config_server.as_ref() { - let factory = config_server_http_client_factory( - service_config, - &codex_login::AuthRouteConfig::from_http_client_factory(factory), - ); - return crate::config_server_bundle_loader(service_config.clone(), codex_home, factory); - } - let endpoint = codex_backend_client::Client::new(chatgpt_base_url.clone(), factory.clone()) - .config_bundle_url(); - let policy = factory - .network_policy() - .clone() - .restrict_to_endpoints(endpoint.parse().into_iter().collect()); - chatgpt_config_bundle_loader( - auth_manager, - chatgpt_base_url, - codex_home, - factory.with_network_policy(policy), - ) -} - -pub async fn managed_config_bundle_loader_for_storage( - auth_config: AuthConfig, - requirements: &ConfigRequirementsToml, - enable_codex_api_key_env: bool, -) -> std::io::Result { - if let Some(service_config) = requirements.config_server.as_ref() { - let factory = - config_server_http_client_factory(service_config, &auth_config.auth_route_config); - return Ok(crate::config_server_bundle_loader( - service_config.clone(), - auth_config.codex_home, - factory, - )); - } - let service = - chatgpt_config_bundle_service_for_storage(auth_config, enable_codex_api_key_env).await?; - Ok(managed_config_bundle_loader_for_service(service).0) -} - -struct CloudConfigBundleLoaderLifetime { - service: Arc>, - refresh_task: AbortHandle, -} - -impl Drop for CloudConfigBundleLoaderLifetime { - fn drop(&mut self) { - self.refresh_task.abort(); - } -} - -pub fn chatgpt_config_bundle_loader( - auth_manager: Arc, - chatgpt_base_url: String, - codex_home: PathBuf, - http_client_factory: HttpClientFactory, -) -> CloudConfigBundleLoader { - let service = CloudConfigBundleService::new( - auth_manager, - Arc::new(BackendBundleClient::new( - chatgpt_base_url, - http_client_factory, - )), - codex_home, - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - let (loader, _) = managed_config_bundle_loader_for_service(service); - loader -} - -pub(crate) fn managed_config_bundle_loader_for_service( - service: CloudConfigBundleService, -) -> (CloudConfigBundleLoader, JoinHandle<()>) -where - C: BundleSource + 'static, -{ - let service = Arc::new(service); - let background_service = Arc::clone(&service); - let refresh_task = tokio::spawn(async move { - let _ = background_service.get_latest().await; - background_service.refresh_cache_in_background().await; - }); - let abort_handle = refresh_task.abort_handle(); - let lifetime = Arc::new(CloudConfigBundleLoaderLifetime { - service, - refresh_task: abort_handle, - }); - - let snapshot_lifetime = Arc::clone(&lifetime); - let policy = lifetime.service.policy.clone(); - let loader = CloudConfigBundleLoader::from_getter(move || { - let lifetime = Arc::clone(&lifetime); - async move { lifetime.service.get_latest().await } - }) - .with_ema_policy_snapshots(policy, move || { - let lifetime = Arc::clone(&snapshot_lifetime); - async move { lifetime.service.get_latest_snapshot().await } - }); - (loader, refresh_task) -} - -pub async fn chatgpt_config_bundle_loader_for_storage( - auth_config: AuthConfig, - enable_codex_api_key_env: bool, -) -> std::io::Result { - let service = - chatgpt_config_bundle_service_for_storage(auth_config, enable_codex_api_key_env).await?; - let (loader, _) = managed_config_bundle_loader_for_service(service); - Ok(loader) -} - -/// Use the configured policy server or the supplied account's ChatGPT policy when eligible. -pub async fn managed_config_bundle_loader_for_auth( - config: AuthConfig, - auth: &CodexAuth, - requirements: &ConfigRequirementsToml, -) -> std::io::Result { - if requirements.config_server.is_some() { - return managed_config_bundle_loader_for_storage( - config, - requirements, - /*enable_codex_api_key_env*/ false, - ) - .await; - } - // Only skip the policy lookup when the supplied account's plan is known. - if auth - .account_plan_type() - .is_some_and(|plan| plan != PlanType::Unknown && !plan_requires_managed_config(plan)) - { - return Ok(CloudConfigBundleLoader::default()); - } - - let base_url = config - .chatgpt_base_url - .as_deref() - .unwrap_or("https://chatgpt.com/backend-api/"); - codex_http_client::validate_https_endpoint_url(base_url, "ChatGPT policy endpoint") - .map_err(std::io::Error::other)?; - let mut client = codex_backend_client::Client::new_without_redirects( - base_url, - config.auth_route_config.http_client_factory().clone(), - ) - .with_user_agent(codex_login::default_client::get_codex_user_agent()) - .with_bearer_token(auth.get_token()?) - .map_err(std::io::Error::other)? - .with_chatgpt_account_id( - auth.get_account_id() - .ok_or_else(|| std::io::Error::other("missing ChatGPT account ID"))?, - ); - if auth.is_fedramp_account() { - client = client.with_fedramp_routing_header(); - } - let response = tokio::time::timeout(CLOUD_CONFIG_BUNDLE_TIMEOUT, client.get_config_bundle()) - .await - .map_err(|_| { - std::io::Error::new( - std::io::ErrorKind::TimedOut, - "timed out loading ChatGPT account policy", - ) - })? - .map_err(|_| std::io::Error::other("could not load ChatGPT account policy"))?; - let bundle = crate::backend::bundle_from_response(response); - Ok(CloudConfigBundleLoader::new( - async move { Ok(Some(bundle)) }, - )) -} - -/// Fetches directly from the network on each load, without reading or writing -/// the disk cache or starting a background refresher. -pub async fn chatgpt_config_bundle_loader_for_storage_without_cache( - auth_config: AuthConfig, - enable_codex_api_key_env: bool, -) -> std::io::Result { - let service = Arc::new( - chatgpt_config_bundle_service_for_storage(auth_config, enable_codex_api_key_env) - .await? - .without_cache(), - ); - Ok(CloudConfigBundleLoader::from_getter(move || { - let service = Arc::clone(&service); - async move { service.load_startup_bundle_with_timeout().await } - })) -} - -async fn chatgpt_config_bundle_service_for_storage( - auth_config: AuthConfig, - enable_codex_api_key_env: bool, -) -> std::io::Result>> { - let auth_manager = - AuthManager::shared_from_auth_config(auth_config.clone(), enable_codex_api_key_env).await?; - Ok(CloudConfigBundleService::new( - auth_manager, - Arc::new(BackendBundleClient::new( - auth_config - .chatgpt_base_url - .unwrap_or_else(|| "https://chatgpt.com/backend-api/".to_string()), - auth_config.auth_route_config.http_client_factory().clone(), - )), - auth_config.codex_home, - CLOUD_CONFIG_BUNDLE_TIMEOUT, - )) -} diff --git a/codex-rs/cloud-config/src/cache.rs b/codex-rs/cloud-config/src/cache.rs deleted file mode 100644 index a0857350..00000000 --- a/codex-rs/cloud-config/src/cache.rs +++ /dev/null @@ -1,292 +0,0 @@ -//! Signed on-disk cache for cloud config bundles. -//! -//! The cache is scoped to the authenticated ChatGPT user and account, has a -//! short TTL, and is HMAC-signed so malformed or edited files fail closed. - -use base64::Engine; -use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; -use chrono::DateTime; -use chrono::Duration as ChronoDuration; -use chrono::Utc; -use codex_config::AbsolutePathBuf; -use codex_config::CloudConfigBundle; -use codex_config::CloudConfigBundlePolicyRevision; -use hmac::Hmac; -use hmac::Mac; -use serde::Deserialize; -use serde::Serialize; -use sha2::Sha256; -use std::io::Write; -use std::path::Path; -use std::path::PathBuf; -use std::time::Duration; -use tempfile::NamedTempFile; -use thiserror::Error; -use tokio::fs; - -const CLOUD_CONFIG_BUNDLE_CACHE_VERSION: u32 = 1; -pub(super) const CLOUD_CONFIG_BUNDLE_CACHE_FILENAME: &str = "cloud-config-bundle-cache.json"; -const CLOUD_CONFIG_BUNDLE_CACHE_TTL: Duration = Duration::from_secs(60 * 60); -const CLOUD_CONFIG_BUNDLE_CACHE_WRITE_HMAC_KEY: &[u8] = - b"codex-cloud-config-bundle-cache-v1-6160ae70-bcfd-4ca8-a99b-40f73b3b072e"; -const CLOUD_CONFIG_BUNDLE_CACHE_READ_HMAC_KEYS: &[&[u8]] = - &[CLOUD_CONFIG_BUNDLE_CACHE_WRITE_HMAC_KEY]; - -type HmacSha256 = Hmac; - -#[derive(Clone)] -pub(super) struct CloudConfigBundleCache { - path: AbsolutePathBuf, -} - -impl CloudConfigBundleCache { - pub(super) fn new(codex_home: AbsolutePathBuf) -> Self { - Self { - path: codex_home.join(CLOUD_CONFIG_BUNDLE_CACHE_FILENAME), - } - } - - pub(super) fn for_source(codex_home: AbsolutePathBuf, namespace: &str) -> Self { - Self { - path: codex_home.join(format!("managed-config-{namespace}.json")), - } - } - - pub(super) fn path(&self) -> &Path { - &self.path - } - - pub(super) async fn load( - &self, - chatgpt_user_id: Option<&str>, - account_id: Option<&str>, - ) -> Result { - let (Some(chatgpt_user_id), Some(account_id)) = (chatgpt_user_id, account_id) else { - return Err(CacheLoadStatus::AuthIdentityIncomplete); - }; - - let bytes = match fs::read(&self.path).await { - Ok(bytes) => bytes, - Err(err) => { - if err.kind() != std::io::ErrorKind::NotFound { - return Err(CacheLoadStatus::CacheReadFailed(err.to_string())); - } - return Err(CacheLoadStatus::CacheFileNotFound); - } - }; - - let cache_file: CloudConfigBundleCacheFile = match serde_json::from_slice(&bytes) { - Ok(cache_file) => cache_file, - Err(err) => { - return Err(CacheLoadStatus::CacheParseFailed(err.to_string())); - } - }; - let payload_bytes = match cache_payload_bytes(&cache_file.signed_payload) { - Some(payload_bytes) => payload_bytes, - None => { - return Err(CacheLoadStatus::CacheParseFailed( - "failed to serialize cache payload".to_string(), - )); - } - }; - if !verify_cache_signature(&payload_bytes, &cache_file.signature) { - return Err(CacheLoadStatus::CacheSignatureInvalid); - } - if cache_file.signed_payload.version != CLOUD_CONFIG_BUNDLE_CACHE_VERSION { - return Err(CacheLoadStatus::CacheVersionUnsupported( - cache_file.signed_payload.version, - )); - } - - let (Some(cached_chatgpt_user_id), Some(cached_account_id)) = ( - cache_file.signed_payload.chatgpt_user_id.as_deref(), - cache_file.signed_payload.account_id.as_deref(), - ) else { - return Err(CacheLoadStatus::CacheIdentityIncomplete); - }; - - if cached_chatgpt_user_id != chatgpt_user_id || cached_account_id != account_id { - return Err(CacheLoadStatus::CacheIdentityMismatch); - } - - if cache_file.signed_payload.expires_at <= Utc::now() { - return Err(CacheLoadStatus::CacheExpired); - } - - Ok(cache_file.signed_payload) - } - - pub(super) fn log_load_status(&self, status: &CacheLoadStatus) { - if matches!(status, CacheLoadStatus::CacheFileNotFound) { - return; - } - - let warn = matches!( - status, - CacheLoadStatus::CacheReadFailed(_) - | CacheLoadStatus::CacheParseFailed(_) - | CacheLoadStatus::CacheSignatureInvalid - ); - - if warn { - tracing::warn!(path = %self.path.display(), "{status}"); - } else { - tracing::info!(path = %self.path.display(), "{status}"); - } - } - - pub(super) async fn prepare( - &self, - chatgpt_user_id: Option, - account_id: Option, - bundle: CloudConfigBundle, - ) -> Result { - let now = Utc::now(); - let expires_at = now - .checked_add_signed( - ChronoDuration::from_std(CLOUD_CONFIG_BUNDLE_CACHE_TTL) - .map_err(|_| CloudConfigBundleCacheError)?, - ) - .ok_or(CloudConfigBundleCacheError)?; - let signed_payload = CloudConfigBundleCacheSignedPayload { - version: CLOUD_CONFIG_BUNDLE_CACHE_VERSION, - cached_at: now, - expires_at, - chatgpt_user_id, - account_id, - bundle, - }; - let payload_bytes = - cache_payload_bytes(&signed_payload).ok_or(CloudConfigBundleCacheError)?; - let serialized = serde_json::to_vec_pretty(&CloudConfigBundleCacheFile { - signature: sign_cache_payload(&payload_bytes).ok_or(CloudConfigBundleCacheError)?, - signed_payload, - }) - .map_err(|_| CloudConfigBundleCacheError)?; - - let destination = self.path.to_path_buf(); - tokio::task::spawn_blocking(move || { - let parent = destination.parent().ok_or(CloudConfigBundleCacheError)?; - std::fs::create_dir_all(parent).map_err(|_| CloudConfigBundleCacheError)?; - let mut temporary = - NamedTempFile::new_in(parent).map_err(|_| CloudConfigBundleCacheError)?; - temporary - .write_all(&serialized) - .map_err(|_| CloudConfigBundleCacheError)?; - Ok(StagedCloudConfigBundleCache { - temporary, - destination, - }) - }) - .await - .map_err(|_| CloudConfigBundleCacheError)? - } -} - -pub(super) struct StagedCloudConfigBundleCache { - temporary: NamedTempFile, - destination: PathBuf, -} - -impl StagedCloudConfigBundleCache { - pub(super) async fn publish_if_current( - self, - revision: CloudConfigBundlePolicyRevision, - ) -> Result<(), CloudConfigBundleCacheError> { - tokio::task::spawn_blocking(move || { - revision.commit_if_current(|| { - self.temporary - .persist(self.destination) - .map(|_| ()) - .map_err(|_| CloudConfigBundleCacheError) - }) - }) - .await - .map_err(|_| CloudConfigBundleCacheError)? - } -} - -#[derive(Clone, Debug, Eq, Error, PartialEq)] -pub(super) enum CacheLoadStatus { - #[error("Skipping cloud config bundle cache read because auth identity is incomplete.")] - AuthIdentityIncomplete, - #[error("Cloud config bundle cache file not found.")] - CacheFileNotFound, - #[error("Failed to read cloud config bundle cache: {0}.")] - CacheReadFailed(String), - #[error("Failed to parse cloud config bundle cache: {0}.")] - CacheParseFailed(String), - #[error("Cloud config bundle cache failed signature verification.")] - CacheSignatureInvalid, - #[error("Ignoring cloud config bundle cache because cached identity is incomplete.")] - CacheIdentityIncomplete, - #[error("Ignoring cloud config bundle cache for different auth identity.")] - CacheIdentityMismatch, - #[error("Ignoring cloud config bundle cache with unsupported version {0}.")] - CacheVersionUnsupported(u32), - #[error("Cloud config bundle cache expired.")] - CacheExpired, - #[error("Ignoring cloud config bundle cache because the cached bundle is invalid.")] - CacheInvalidBundle, -} - -#[derive(Debug, Error)] -#[error("failed to write cloud config bundle cache")] -pub(super) struct CloudConfigBundleCacheError; - -#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] -pub(super) struct CloudConfigBundleCacheFile { - pub(super) signed_payload: CloudConfigBundleCacheSignedPayload, - pub(super) signature: String, -} - -#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] -pub(super) struct CloudConfigBundleCacheSignedPayload { - pub(super) version: u32, - pub(super) cached_at: DateTime, - pub(super) expires_at: DateTime, - pub(super) chatgpt_user_id: Option, - pub(super) account_id: Option, - pub(super) bundle: CloudConfigBundle, -} - -pub(super) fn cache_payload_bytes( - payload: &CloudConfigBundleCacheSignedPayload, -) -> Option> { - serde_json::to_vec(&payload).ok() -} - -pub(super) fn sign_cache_payload(payload_bytes: &[u8]) -> Option { - let mut mac = HmacSha256::new_from_slice(CLOUD_CONFIG_BUNDLE_CACHE_WRITE_HMAC_KEY).ok()?; - mac.update(payload_bytes); - let signature = mac.finalize().into_bytes(); - Some(BASE64_STANDARD.encode(signature)) -} - -pub(super) fn verify_cache_signature(payload_bytes: &[u8], signature: &str) -> bool { - let signature_bytes = match BASE64_STANDARD.decode(signature) { - Ok(signature_bytes) => signature_bytes, - Err(_) => return false, - }; - - CLOUD_CONFIG_BUNDLE_CACHE_READ_HMAC_KEYS - .iter() - .any(|key| verify_cache_signature_with_key(payload_bytes, &signature_bytes, key)) -} - -fn verify_cache_signature_with_key( - payload_bytes: &[u8], - signature_bytes: &[u8], - key: &[u8], -) -> bool { - let mut mac = match HmacSha256::new_from_slice(key) { - Ok(mac) => mac, - Err(_) => return false, - }; - mac.update(payload_bytes); - mac.verify_slice(signature_bytes).is_ok() -} - -#[cfg(test)] -#[path = "cache_tests.rs"] -mod tests; diff --git a/codex-rs/cloud-config/src/cache_tests.rs b/codex-rs/cloud-config/src/cache_tests.rs deleted file mode 100644 index 29d4a579..00000000 --- a/codex-rs/cloud-config/src/cache_tests.rs +++ /dev/null @@ -1,212 +0,0 @@ -use super::*; -use codex_config::AbsolutePathBuf; -use codex_config::CloudConfigFragment; -use codex_config::CloudConfigTomlBundle; -use codex_config::CloudRequirementsFragment; -use codex_config::CloudRequirementsTomlBundle; -use pretty_assertions::assert_eq; -use std::path::Path; -use tempfile::tempdir; - -fn test_bundle() -> CloudConfigBundle { - CloudConfigBundle { - config_toml: CloudConfigTomlBundle { - enterprise_managed: vec![CloudConfigFragment { - id: "cfg_1".to_string(), - name: "Base config".to_string(), - contents: "model = \"gpt-5\"".to_string(), - }], - }, - requirements_toml: CloudRequirementsTomlBundle { - enterprise_managed: vec![CloudRequirementsFragment { - id: "req_1".to_string(), - name: "Base requirements".to_string(), - contents: "allowed_approval_policies = [\"never\"]".to_string(), - }], - }, - } -} - -fn signed_cache_file( - signed_payload: CloudConfigBundleCacheSignedPayload, -) -> CloudConfigBundleCacheFile { - let payload_bytes = cache_payload_bytes(&signed_payload).expect("payload bytes"); - CloudConfigBundleCacheFile { - signature: sign_cache_payload(&payload_bytes).expect("signature"), - signed_payload, - } -} - -fn valid_signed_payload() -> CloudConfigBundleCacheSignedPayload { - let cached_at = Utc::now(); - CloudConfigBundleCacheSignedPayload { - version: CLOUD_CONFIG_BUNDLE_CACHE_VERSION, - cached_at, - expires_at: cached_at + ChronoDuration::minutes(30), - chatgpt_user_id: Some("user-12345".to_string()), - account_id: Some("account-12345".to_string()), - bundle: test_bundle(), - } -} - -fn write_cache_file(cache: &CloudConfigBundleCache, cache_file: &CloudConfigBundleCacheFile) { - std::fs::write( - cache.path(), - serde_json::to_vec_pretty(cache_file).expect("serialize cache"), - ) - .expect("write cache"); -} - -fn create_test_cache(codex_home: &Path) -> CloudConfigBundleCache { - CloudConfigBundleCache::new(AbsolutePathBuf::resolve_path_against_base(codex_home, "/")) -} - -#[tokio::test] -async fn save_writes_signed_payload_and_loads_for_matching_identity() { - let codex_home = tempdir().expect("tempdir"); - let cache = create_test_cache(codex_home.path()); - let bundle = test_bundle(); - - let revision = codex_config::CloudConfigBundlePolicy::default() - .observe_remote_bundle(&bundle) - .expect("cache revision"); - cache - .prepare( - Some("user-12345".to_string()), - Some("account-12345".to_string()), - bundle.clone(), - ) - .await - .expect("stage cache") - .publish_if_current(revision) - .await - .expect("save cache"); - - let cache_file: CloudConfigBundleCacheFile = - serde_json::from_slice(&std::fs::read(cache.path()).expect("read cache")) - .expect("parse cache"); - assert!( - cache_file.signed_payload.expires_at - <= cache_file.signed_payload.cached_at + ChronoDuration::minutes(60) - ); - assert!(cache_file.signed_payload.expires_at > cache_file.signed_payload.cached_at); - assert_eq!( - cache_file, - signed_cache_file(CloudConfigBundleCacheSignedPayload { - version: CLOUD_CONFIG_BUNDLE_CACHE_VERSION, - cached_at: cache_file.signed_payload.cached_at, - expires_at: cache_file.signed_payload.expires_at, - chatgpt_user_id: Some("user-12345".to_string()), - account_id: Some("account-12345".to_string()), - bundle, - }) - ); - - assert_eq!( - cache.load(Some("user-12345"), Some("account-12345")).await, - Ok(cache_file.signed_payload) - ); -} - -#[tokio::test] -async fn load_rejects_missing_request_identity_before_reading_cache_file() { - let codex_home = tempdir().expect("tempdir"); - let cache = create_test_cache(codex_home.path()); - - assert_eq!( - cache - .load(/*chatgpt_user_id*/ None, Some("account-12345")) - .await, - Err(CacheLoadStatus::AuthIdentityIncomplete) - ); - assert_eq!( - cache.load(Some("user-12345"), /*account_id*/ None).await, - Err(CacheLoadStatus::AuthIdentityIncomplete) - ); -} - -#[tokio::test] -async fn load_reports_missing_and_malformed_cache_files() { - let codex_home = tempdir().expect("tempdir"); - let cache = create_test_cache(codex_home.path()); - - assert_eq!( - cache.load(Some("user-12345"), Some("account-12345")).await, - Err(CacheLoadStatus::CacheFileNotFound) - ); - - std::fs::write(cache.path(), "{").expect("write malformed cache"); - assert!(matches!( - cache.load(Some("user-12345"), Some("account-12345")).await, - Err(CacheLoadStatus::CacheParseFailed(_)) - )); -} - -#[tokio::test] -async fn load_rejects_tampered_payload() { - let codex_home = tempdir().expect("tempdir"); - let cache = create_test_cache(codex_home.path()); - let mut cache_file = signed_cache_file(valid_signed_payload()); - cache_file - .signed_payload - .bundle - .requirements_toml - .enterprise_managed[0] - .contents = "allowed_approval_policies = [\"on-request\"]".to_string(); - write_cache_file(&cache, &cache_file); - - assert_eq!( - cache.load(Some("user-12345"), Some("account-12345")).await, - Err(CacheLoadStatus::CacheSignatureInvalid) - ); -} - -#[tokio::test] -async fn load_rejects_cache_for_incomplete_or_different_identity() { - let codex_home = tempdir().expect("tempdir"); - let cache = create_test_cache(codex_home.path()); - let cache_file = signed_cache_file(valid_signed_payload()); - write_cache_file(&cache, &cache_file); - - assert_eq!( - cache.load(Some("user-99999"), Some("account-12345")).await, - Err(CacheLoadStatus::CacheIdentityMismatch) - ); - - let mut signed_payload = valid_signed_payload(); - signed_payload.chatgpt_user_id = None; - write_cache_file(&cache, &signed_cache_file(signed_payload)); - - assert_eq!( - cache.load(Some("user-12345"), Some("account-12345")).await, - Err(CacheLoadStatus::CacheIdentityIncomplete) - ); -} - -#[tokio::test] -async fn load_rejects_expired_cache() { - let codex_home = tempdir().expect("tempdir"); - let cache = create_test_cache(codex_home.path()); - let mut signed_payload = valid_signed_payload(); - signed_payload.expires_at = Utc::now() - ChronoDuration::seconds(1); - write_cache_file(&cache, &signed_cache_file(signed_payload)); - - assert_eq!( - cache.load(Some("user-12345"), Some("account-12345")).await, - Err(CacheLoadStatus::CacheExpired) - ); -} - -#[tokio::test] -async fn load_rejects_unsupported_cache_version() { - let codex_home = tempdir().expect("tempdir"); - let cache = create_test_cache(codex_home.path()); - let mut signed_payload = valid_signed_payload(); - signed_payload.version = 2; - write_cache_file(&cache, &signed_cache_file(signed_payload)); - - assert_eq!( - cache.load(Some("user-12345"), Some("account-12345")).await, - Err(CacheLoadStatus::CacheVersionUnsupported(2)) - ); -} diff --git a/codex-rs/cloud-config/src/chatgpt.rs b/codex-rs/cloud-config/src/chatgpt.rs deleted file mode 100644 index 47a3b2cf..00000000 --- a/codex-rs/cloud-config/src/chatgpt.rs +++ /dev/null @@ -1,103 +0,0 @@ -//! ChatGPT eligibility, credentials, and account identity for managed configuration. - -use crate::backend::BundleClient; -use crate::backend::BundleRequestError; -use crate::backend::RetryableFailureKind; -use crate::config_source::BundleSource; -use codex_config::CloudConfigBundle; -use codex_config::CloudConfigBundleLoadError; -use codex_login::AuthManager; -use codex_login::CodexAuth; -use codex_login::RefreshTokenError; -use codex_login::UnauthorizedRecovery; -use codex_protocol::account::PlanType; -use std::sync::Arc; - -const CLOUD_CONFIG_BUNDLE_AUTH_RECOVERY_FAILED_MESSAGE: &str = concat!( - "Your authentication session could not be refreshed automatically. ", - "Please log out and sign in again." -); - -pub(super) fn plan_requires_managed_config(plan: PlanType) -> bool { - plan.is_business_like() - || plan.is_education_like() - || matches!( - plan, - PlanType::Enterprise | PlanType::Sci | PlanType::SciPlus - ) -} - -pub(crate) struct ChatGptSource { - pub(crate) auth_manager: Arc, - pub(crate) client: Arc, -} - -impl BundleSource for ChatGptSource { - type Auth = CodexAuth; - type FetchContext = UnauthorizedRecovery; - fn begin_fetch(&self) -> Self::FetchContext { - self.auth_manager.unauthorized_recovery() - } - - async fn auth(&self) -> Result, CloudConfigBundleLoadError> { - Ok(self.auth_manager.auth().await.filter(|auth| { - auth.uses_codex_backend() - && auth - .account_plan_type() - .is_some_and(plan_requires_managed_config) - })) - } - - fn identity(&self, auth: &CodexAuth) -> (Option, Option) { - (auth.get_chatgpt_user_id(), auth.get_account_id()) - } - - async fn get_bundle( - &self, - auth: &mut CodexAuth, - _context: &mut UnauthorizedRecovery, - ) -> Result { - self.client.get_bundle(auth).await - } - - async fn recover_auth( - &self, - auth: &mut CodexAuth, - recovery: &mut UnauthorizedRecovery, - status_code: Option, - _recovery_attempt: usize, - ) -> Result { - if !recovery.has_next() { - return Err(BundleRequestError::auth_failure( - status_code, - CLOUD_CONFIG_BUNDLE_AUTH_RECOVERY_FAILED_MESSAGE, - Some("auth_recovery_unavailable"), - )); - } - match recovery.next().await { - Ok(_) => { - *auth = self.auth_manager.auth().await.ok_or_else(|| { - BundleRequestError::auth_failure( - status_code, - CLOUD_CONFIG_BUNDLE_AUTH_RECOVERY_FAILED_MESSAGE, - Some("auth_recovery_missing_auth"), - ) - })?; - Ok(true) - } - Err(RefreshTokenError::Transient(_)) => Err(BundleRequestError::Retryable( - RetryableFailureKind::AuthRecovery { status_code }, - )), - Err(RefreshTokenError::Permanent(failed)) => Err(BundleRequestError::auth_failure( - status_code, - failed.message, - Some("auth_recovery_unrecoverable"), - )), - Err(RefreshTokenError::Policy(error)) => Err(BundleRequestError::auth_failure( - status_code, - error.to_string(), - /*metric_reason*/ None, - )), - } - } -} diff --git a/codex-rs/cloud-config/src/config_server.rs b/codex-rs/cloud-config/src/config_server.rs deleted file mode 100644 index 2dba54ad..00000000 --- a/codex-rs/cloud-config/src/config_server.rs +++ /dev/null @@ -1,274 +0,0 @@ -//! Fetch managed configuration from a custom config server. -//! Cache entries are scoped to the endpoint and the current OAuth sign-in. - -use crate::backend::BundleRequestError; -use crate::backend::RetryableFailureKind; -use crate::backend::fetch_bundle; -use crate::config_source::BundleSource; -use crate::service::CLOUD_CONFIG_BUNDLE_TIMEOUT; -use crate::service::CloudConfigBundleService; -use codex_backend_client::Client as BackendClient; -use codex_config::CloudConfigBundle; -use codex_config::CloudConfigBundleLoadError; -use codex_config::CloudConfigBundleLoadErrorCode; -use codex_config::CloudConfigBundleLoader; -use codex_config::ConfigServer; -use codex_http_client::HttpClientFactory; -use codex_keyring_store::DefaultKeyringStore; -use codex_login::AuthRouteConfig; -use codex_login::OAuthSessionConfig; -use codex_login::OAuthSessionError; -use codex_login::OAuthSessionManager; -use codex_login::OAuthSessionRequest; -use sha2::Digest; -use sha2::Sha256; -use std::path::PathBuf; -use std::sync::Arc; - -pub fn config_server_bundle_loader( - config: ConfigServer, - codex_home: PathBuf, - factory: HttpClientFactory, -) -> CloudConfigBundleLoader { - match ConfigServerSource::from_config_server(config.clone(), codex_home.clone(), factory) { - Ok(source) => { - let service = CloudConfigBundleService::from_source( - source, - codex_home, - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - crate::bundle_loader::managed_config_bundle_loader_for_service(service).0 - } - Err(error) => CloudConfigBundleLoader::new(std::future::ready(Err(error))), - } - .with_config_server(config) -} - -pub fn config_server_auth_manager( - service_config: &ConfigServer, - codex_home: PathBuf, - factory: &HttpClientFactory, -) -> std::io::Result> { - service_config - .validated_base_url() - .map_err(std::io::Error::other)?; - oauth_session_manager(service_config.oauth.as_deref(), codex_home, factory) -} - -pub(crate) fn config_server_http_client_factory( - config: &ConfigServer, - routes: &AuthRouteConfig, -) -> HttpClientFactory { - let endpoint = config.validated_base_url().ok().map(|base_url| { - BackendClient::for_config_endpoint(base_url, routes.http_client_factory().clone()) - .config_bundle_url() - }); - let endpoints = endpoint - .as_deref() - .into_iter() - .chain(config.oauth.as_ref().map(|oauth| oauth.token_url.as_str())) - .chain( - config - .oauth - .as_ref() - .and_then(|oauth| oauth.device_authorization_url.as_deref()), - ) - .filter_map(|endpoint| endpoint.parse().ok()); - routes.http_client_factory_for_bootstrap(endpoints) -} - -struct ConfigServerSource { - cache_namespace: String, - client: BackendClient, - auth: Option, -} - -fn oauth_session_manager( - oauth: Option<&OAuthSessionConfig>, - codex_home: PathBuf, - factory: &HttpClientFactory, -) -> std::io::Result> { - oauth - .map(|oauth| { - OAuthSessionManager::new( - oauth.clone(), - codex_home, - factory, - Arc::new(DefaultKeyringStore), - ) - .map(OAuthSessionManager::without_interactive_login) - }) - .transpose() -} - -impl ConfigServerSource { - fn from_config_server( - config: ConfigServer, - codex_home: PathBuf, - factory: HttpClientFactory, - ) -> Result { - let base_url = config.validated_base_url().map_err(|message| { - CloudConfigBundleLoadError::new( - CloudConfigBundleLoadErrorCode::Internal, - /*status_code*/ None, - message, - ) - })?; - Self::new( - base_url, - config.oauth.map(|oauth| *oauth), - codex_home, - factory, - ) - } - - fn new( - base_url: String, - oauth: Option, - codex_home: PathBuf, - factory: HttpClientFactory, - ) -> Result { - let auth = - oauth_session_manager(oauth.as_ref(), codex_home, &factory).map_err(auth_io_error)?; - let client = BackendClient::for_config_endpoint(base_url, factory); - // Reuse the OAuth session's issuer/client/audience/scope identity; the endpoint - // additionally separates policy authorities that share one OAuth grant. - let namespace = serde_json::to_vec(&( - client.config_bundle_url(), - auth.as_ref().map(OAuthSessionManager::credential_id), - )) - .map_err(|_| auth_failure())?; - Ok(Self { - client, - cache_namespace: format!("{:x}", Sha256::digest(namespace)), - auth, - }) - } -} - -impl BundleSource for ConfigServerSource { - type Auth = Option; - type FetchContext = Option; - fn begin_fetch(&self) -> Self::FetchContext { - self.auth.as_ref().map(OAuthSessionManager::begin_request) - } - - async fn auth(&self) -> Result, CloudConfigBundleLoadError> { - // Cache reads need the grant identity, not a refreshed access token. - Ok(Some(match &self.auth { - Some(auth) => Some(auth.authorization_id().await.map_err(auth_io_error)?), - None => None, - })) - } - - fn cache_namespace(&self) -> Option { - Some(self.cache_namespace.clone()) - } - - fn identity(&self, auth: &Self::Auth) -> (Option, Option) { - ( - Some(auth.clone().unwrap_or_else(|| "anonymous".into())), - self.cache_namespace(), - ) - } - - async fn get_bundle( - &self, - identity: &mut Self::Auth, - context: &mut Self::FetchContext, - ) -> Result { - let Some(request) = context else { - return fetch_bundle(&self.client).await; - }; - let credentials = request - .credentials() - .await - .map_err(|error| auth_request_error(error, request.is_recovering()))?; - if credentials.authorization_id.is_none() { - return Err(BundleRequestError::Fatal { - error: auth_failure(), - metric_reason: Some("auth"), - }); - } - *identity = credentials.authorization_id; - let client = self - .client - .clone() - .with_bearer_token(credentials.access_token) - .map_err(|_| BundleRequestError::Fatal { - error: auth_failure(), - metric_reason: Some("auth"), - })?; - fetch_bundle(&client).await - } - - async fn recover_auth( - &self, - _identity: &mut Self::Auth, - context: &mut Self::FetchContext, - status_code: Option, - recovery_attempt: usize, - ) -> Result { - let Some(auth) = context else { - return Ok(false); - }; - if status_code != Some(401) || recovery_attempt != 0 { - return Ok(false); - } - Ok(auth.reject_credentials()) - } -} - -fn auth_request_error(error: std::io::Error, recovering: bool) -> BundleRequestError { - if error - .get_ref() - .is_some_and(::is::) - || matches!( - error.kind(), - std::io::ErrorKind::PermissionDenied - | std::io::ErrorKind::InvalidInput - | std::io::ErrorKind::InvalidData - ) - { - BundleRequestError::Fatal { - error: auth_io_error(error), - metric_reason: Some("auth"), - } - } else { - BundleRequestError::Retryable(if recovering { - RetryableFailureKind::AuthRecovery { - status_code: Some(401), - } - } else { - RetryableFailureKind::Request { status_code: None } - }) - } -} - -fn auth_io_error(error: std::io::Error) -> CloudConfigBundleLoadError { - if error - .get_ref() - .and_then(|source| source.downcast_ref::()) - == Some(&OAuthSessionError::LoginRequired) - { - CloudConfigBundleLoadError::new( - CloudConfigBundleLoadErrorCode::Auth, - /*status_code*/ None, - "Sign in to the configuration server to load your organization's settings", - ) - } else { - auth_failure() - } -} - -fn auth_failure() -> CloudConfigBundleLoadError { - CloudConfigBundleLoadError::new( - CloudConfigBundleLoadErrorCode::Auth, - /*status_code*/ None, - "Could not authenticate with the configuration server", - ) -} - -#[cfg(test)] -#[path = "config_server_tests.rs"] -mod tests; diff --git a/codex-rs/cloud-config/src/config_server_tests.rs b/codex-rs/cloud-config/src/config_server_tests.rs deleted file mode 100644 index 57afe403..00000000 --- a/codex-rs/cloud-config/src/config_server_tests.rs +++ /dev/null @@ -1,209 +0,0 @@ -#![cfg(test)] - -use super::*; -use crate::bundle_loader::managed_config_bundle_loader_for_service; -use crate::service::CLOUD_CONFIG_BUNDLE_TIMEOUT; -use crate::service::CloudConfigBundleService; -use codex_config::CloudConfigBundleLoader; -use codex_config::ConfigServer; -use codex_config::test_support::CloudConfigBundleFixture; -use codex_keyring_store::tests::MockKeyringStore; -use codex_login::test_support::transport_default_auth_route_config; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; -use tempfile::tempdir; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; - -// HTTP fixtures exercise the same service while production enforces HTTPS at construction. -fn remote_loader(url: String, codex_home: PathBuf) -> CloudConfigBundleLoader { - let factory = transport_default_auth_route_config() - .http_client_factory() - .clone(); - let source = ConfigServerSource::new(url, /*oauth*/ None, codex_home.clone(), factory).unwrap(); - managed_config_bundle_loader_for_service(CloudConfigBundleService::from_source( - source, - codex_home, - CLOUD_CONFIG_BUNDLE_TIMEOUT, - )) - .0 -} - -fn oauth_config(base_url: &str) -> OAuthSessionConfig { - OAuthSessionConfig { - authorization_url: format!("{base_url}/authorize"), - token_url: format!("{base_url}/token"), - device_authorization_url: None, - client_id: "company-client".into(), - resource: None, - scopes: vec![], - redirect_port: None, - credentials_store: Default::default(), - } -} - -#[tokio::test] -async fn a_supplied_chatgpt_token_does_not_replace_config_server_sign_in() { - let server = MockServer::start().await; - let home = tempdir().unwrap(); - let endpoint = format!("https://{}", server.address()); - let mut config = codex_core::config::ConfigBuilder::default() - .codex_home(home.path().into()) - .build() - .await - .unwrap() - .auth_config(); - config.chatgpt_base_url = Some(server.uri()); - let requirements = codex_config::ConfigRequirementsToml { - config_server: Some(ConfigServer { - base_url: format!("{endpoint}/settings"), - oauth: Some(Box::new(oauth_config(&endpoint))), - }), - ..Default::default() - }; - let chatgpt = codex_login::CodexAuth::from_external_chatgpt_tokens( - "e30.e30.c2ln", - "endor", - /*chatgpt_plan_type*/ None, - ) - .unwrap(); - let loader = crate::managed_config_bundle_loader_for_auth(config, &chatgpt, &requirements) - .await - .unwrap(); - assert_eq!(loader.config_server(), requirements.config_server.as_ref()); - let error = loader.get().await.unwrap_err(); - assert_eq!(error.code(), CloudConfigBundleLoadErrorCode::Auth); - assert_eq!( - error.to_string(), - "Sign in to the configuration server to load your organization's settings" - ); - assert!(server.received_requests().await.unwrap().is_empty()); -} - -#[tokio::test] -async fn policy_fetch_uses_replacement_config_server_credentials() { - let server = MockServer::start().await; - let sign_in = AtomicUsize::new(0); - Mock::given(path("/token")) - .respond_with(move |_: &wiremock::Request| { - ResponseTemplate::new(200).set_body_json(json!({ - "access_token": format!("account-{}", sign_in.fetch_add(1, Ordering::Relaxed)), - "token_type": "Bearer", "expires_in": 3600, - })) - }) - .mount(&server) - .await; - let policies = ["never", "on-request"].map(|approval| { - CloudConfigBundleFixture::enterprise_requirement(format!( - "allowed_approval_policies = ['{approval}']" - )) - .into_bundle() - }); - for (account, policy) in policies.iter().enumerate() { - Mock::given(path("/settings/codex/config/bundle")) - .and(header("authorization", format!("Bearer account-{account}"))) - .respond_with(ResponseTemplate::new(200).set_body_json(policy)) - .mount(&server) - .await; - } - let home = tempdir().unwrap(); - let factory = transport_default_auth_route_config() - .http_client_factory() - .clone(); - let oauth = oauth_config(&server.uri()); - let keyring = Arc::new(MockKeyringStore::default()); - let manager = || { - OAuthSessionManager::new( - oauth.clone(), - home.path().to_path_buf(), - &factory, - keyring.clone(), - ) - .unwrap() - }; - let gateway = manager(); - gateway - .login_with_browser(std::future::pending(), complete_browser_authorization) - .await - .unwrap(); - let source = ConfigServerSource { - cache_namespace: "test".into(), - client: BackendClient::for_config_endpoint( - format!("{}/settings", server.uri()), - factory.clone(), - ), - auth: Some(manager().without_interactive_login()), - }; - let service = CloudConfigBundleService::from_source( - source, - home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - assert_eq!( - service.load_startup_bundle_with_timeout().await.unwrap(), - Some(policies[0].clone()) - ); - - gateway - .login_with_browser(std::future::pending(), complete_browser_authorization) - .await - .unwrap(); - // The old access token is still valid, so this must detect the changed grant. - assert_eq!( - service.load_startup_bundle_with_timeout().await.unwrap(), - Some(policies[1].clone()) - ); -} - -fn complete_browser_authorization(url: &wiremock::http::Url) { - let query = url - .query_pairs() - .collect::>(); - let callback = format!( - "{}?code=browser-authorization-code&state={}", - query["redirect_uri"], query["state"] - ); - tokio::spawn(async move { - codex_login::auth::default_client::create_client_without_request_logging() - .get(callback) - .send() - .await - .expect("OAuth callback"); - }); -} - -#[tokio::test] -async fn cached_policy_is_reused_only_for_the_same_endpoint() { - let server = MockServer::start().await; - let home = tempdir().unwrap(); - let endpoint = format!("{}/settings", server.uri()); - let loader = || remote_loader(endpoint.clone(), home.path().to_path_buf()); - let bundle = - CloudConfigBundleFixture::enterprise_requirement("allowed_approval_policies = ['never']") - .into_bundle(); - Mock::given(method("GET")) - .and(path("/settings/codex/config/bundle")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(&bundle)) - .mount(&server) - .await; - let first = loader(); - assert_eq!(first.get().await.unwrap(), Some(bundle.clone())); - drop(first); - server.reset().await; - Mock::given(method("GET")) - .respond_with(ResponseTemplate::new(/*s*/ 403)) - .mount(&server) - .await; - assert_eq!(loader().get().await.unwrap(), Some(bundle)); - let different = remote_loader( - format!("{}/different", server.uri()), - home.path().to_path_buf(), - ); - assert_eq!(different.get().await.unwrap_err().status_code(), Some(403)); -} diff --git a/codex-rs/cloud-config/src/config_source.rs b/codex-rs/cloud-config/src/config_source.rs deleted file mode 100644 index 523d8fc9..00000000 --- a/codex-rs/cloud-config/src/config_source.rs +++ /dev/null @@ -1,43 +0,0 @@ -//! Common interface for fetching managed configuration - -use crate::backend::BundleRequestError; -use codex_config::CloudConfigBundle; -use codex_config::CloudConfigBundleLoadError; -use std::future::Future; - -/// Supplies authentication and cache identity to the managed-config service. -/// Cache lookup and fetch must use the same authorization identity. -pub(crate) trait BundleSource: Send + Sync { - type Auth: Send + Sync; - type FetchContext: Send; - /// One context per load or refresh, retained across the service's retries. - fn begin_fetch(&self) -> Self::FetchContext; - - /// `None` means this source does not apply, such as an ineligible ChatGPT plan. - /// A required source returns `Some` even when its endpoint is unauthenticated. - fn auth( - &self, - ) -> impl Future, CloudConfigBundleLoadError>> + Send; - /// Stable subject and authority identifiers; missing values disable cache reads. - fn identity(&self, auth: &Self::Auth) -> (Option, Option); - /// Cache lookups do not call this operation or require a token refresh. - fn get_bundle( - &self, - auth: &mut Self::Auth, - context: &mut Self::FetchContext, - ) -> impl Future> + Send; - - /// Recover one unauthorized request. The service retries only when this returns true. - fn recover_auth( - &self, - auth: &mut Self::Auth, - context: &mut Self::FetchContext, - status_code: Option, - recovery_attempt: usize, - ) -> impl Future> + Send; - - /// The default preserves the existing ChatGPT cache location. - fn cache_namespace(&self) -> Option { - None - } -} diff --git a/codex-rs/cloud-config/src/lib.rs b/codex-rs/cloud-config/src/lib.rs deleted file mode 100644 index 3d0dab60..00000000 --- a/codex-rs/cloud-config/src/lib.rs +++ /dev/null @@ -1,25 +0,0 @@ -//! Cloud-hosted configuration data for Codex. -//! -//! This crate owns transport, caching, and refresh behavior for cloud-delivered -//! config data. Parsing and composition remain in `codex-config`. - -mod backend; -mod bundle_loader; -mod cache; -mod chatgpt; -mod config_server; -mod config_source; -mod metrics; -mod service; -mod validation; - -pub use bundle_loader::chatgpt_config_bundle_loader; -pub use bundle_loader::chatgpt_config_bundle_loader_for_storage; -pub use bundle_loader::chatgpt_config_bundle_loader_for_storage_without_cache; -pub use bundle_loader::ensure_config_server_login; -pub use bundle_loader::managed_config_auth_manager; -pub use bundle_loader::managed_config_bundle_loader; -pub use bundle_loader::managed_config_bundle_loader_for_auth; -pub use bundle_loader::managed_config_bundle_loader_for_storage; -pub use config_server::config_server_auth_manager; -pub use config_server::config_server_bundle_loader; diff --git a/codex-rs/cloud-config/src/metrics.rs b/codex-rs/cloud-config/src/metrics.rs deleted file mode 100644 index c1c02cce..00000000 --- a/codex-rs/cloud-config/src/metrics.rs +++ /dev/null @@ -1,95 +0,0 @@ -use codex_config::CloudConfigBundle; - -const CLOUD_CONFIG_BUNDLE_FETCH_ATTEMPT_METRIC: &str = "codex.cloud_config_bundle.fetch_attempt"; -const CLOUD_CONFIG_BUNDLE_FETCH_FINAL_METRIC: &str = "codex.cloud_config_bundle.fetch_final"; -const CLOUD_CONFIG_BUNDLE_LOAD_METRIC: &str = "codex.cloud_config_bundle.load"; - -pub(crate) fn emit_fetch_attempt_metric( - trigger: &str, - attempt: usize, - outcome: &str, - status_code: Option, -) { - let attempt_tag = attempt.to_string(); - let status_code_tag = status_code_tag(status_code); - emit_metric( - CLOUD_CONFIG_BUNDLE_FETCH_ATTEMPT_METRIC, - vec![ - ("trigger", trigger.to_string()), - ("attempt", attempt_tag), - ("outcome", outcome.to_string()), - ("status_code", status_code_tag), - ], - ); -} - -pub(crate) fn emit_fetch_final_metric( - trigger: &str, - outcome: &str, - reason: &str, - attempt_count: usize, - status_code: Option, - bundle: Option<&CloudConfigBundle>, -) { - let attempt_count_tag = attempt_count.to_string(); - let status_code_tag = status_code_tag(status_code); - emit_metric( - CLOUD_CONFIG_BUNDLE_FETCH_FINAL_METRIC, - vec![ - ("trigger", trigger.to_string()), - ("outcome", outcome.to_string()), - ("reason", reason.to_string()), - ("attempt_count", attempt_count_tag), - ("status_code", status_code_tag), - ("bundle_shape", bundle_shape_tag(bundle)), - ], - ); -} - -pub(crate) fn emit_load_metric(trigger: &str, outcome: &str, bundle: Option<&CloudConfigBundle>) { - emit_metric( - CLOUD_CONFIG_BUNDLE_LOAD_METRIC, - vec![ - ("trigger", trigger.to_string()), - ("outcome", outcome.to_string()), - ("bundle_shape", bundle_shape_tag(bundle)), - ], - ); -} - -pub(crate) fn bundle_shape_tag(bundle: Option<&CloudConfigBundle>) -> String { - let Some(bundle) = bundle else { - return "none".to_string(); - }; - - let mut sources = Vec::new(); - if !bundle.config_toml.enterprise_managed.is_empty() { - sources.push("enterprise_config"); - } - if !bundle.requirements_toml.enterprise_managed.is_empty() { - sources.push("enterprise_requirements"); - } - - if sources.is_empty() { - "empty".to_string() - } else { - sources.sort_unstable(); - sources.join(",") - } -} - -fn status_code_tag(status_code: Option) -> String { - status_code - .map(|status_code| status_code.to_string()) - .unwrap_or_else(|| "none".to_string()) -} - -fn emit_metric(metric_name: &str, tags: Vec<(&str, String)>) { - if let Some(metrics) = codex_otel::global() { - let tag_refs = tags - .iter() - .map(|(key, value)| (*key, value.as_str())) - .collect::>(); - let _ = metrics.counter(metric_name, /*inc*/ 1, &tag_refs); - } -} diff --git a/codex-rs/cloud-config/src/service.rs b/codex-rs/cloud-config/src/service.rs deleted file mode 100644 index 00c67c36..00000000 --- a/codex-rs/cloud-config/src/service.rs +++ /dev/null @@ -1,521 +0,0 @@ -//! Cloud config bundle lifecycle orchestration. -//! -//! Startup loads a shared bundle from cache or backend, and background refresh -//! updates both the on-disk cache and the bundle observed by future config loads. -//! One-shot network loads can disable disk-cache reads and writes. - -use crate::backend::BundleClient; -use crate::backend::BundleRequestError; -use crate::backend::RetryableFailureKind; -use crate::cache::CacheLoadStatus; -use crate::cache::CloudConfigBundleCache; -use crate::chatgpt::ChatGptSource; -use crate::config_source::BundleSource; -use crate::metrics::emit_fetch_attempt_metric; -use crate::metrics::emit_fetch_final_metric; -use crate::metrics::emit_load_metric; -use crate::validation::validate_bundle; -use codex_async_utils::backoff; -use codex_config::AbsolutePathBuf; -use codex_config::CloudConfigBundle; -use codex_config::CloudConfigBundleLoadError; -use codex_config::CloudConfigBundleLoadErrorCode; -use codex_config::CloudConfigBundlePolicy; -use codex_config::CloudConfigBundleSnapshot; -use codex_login::AuthManager; -use std::path::PathBuf; -use std::sync::Arc; -use std::time::Duration; -use std::time::Instant; -use tokio::sync::Mutex; -use tokio::sync::OnceCell; -use tokio::time::sleep; -use tokio::time::timeout; - -pub(crate) const CLOUD_CONFIG_BUNDLE_TIMEOUT: Duration = Duration::from_secs(20); -const CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS: usize = 5; -const CLOUD_CONFIG_BUNDLE_CACHE_REFRESH_INTERVAL: Duration = Duration::from_secs(15 * 60); -const CLOUD_CONFIG_BUNDLE_TIMEOUT_RETRY_INTERVAL: Duration = Duration::from_secs(5); -const CLOUD_CONFIG_BUNDLE_LOAD_FAILED_MESSAGE: &str = - "Failed to load cloud config bundle (workspace-managed policies)."; -fn optional_bundle(bundle: CloudConfigBundle) -> Option { - if bundle.is_empty() { - None - } else { - Some(bundle) - } -} - -enum CachedBundleLookup { - Hit(Option), - Miss, -} - -pub(crate) struct CloudConfigBundleService { - source: S, - cache: CloudConfigBundleCache, - cache_enabled: bool, - codex_home: AbsolutePathBuf, - timeout: Duration, - latest_bundle: OnceCell>, - pub(crate) policy: CloudConfigBundlePolicy, -} - -impl CloudConfigBundleService> { - pub(crate) fn new( - auth_manager: Arc, - client: Arc, - codex_home: PathBuf, - timeout: Duration, - ) -> Self { - Self::from_source( - ChatGptSource { - auth_manager, - client, - }, - codex_home, - timeout, - ) - } -} - -impl CloudConfigBundleService { - pub(crate) fn from_source(source: S, codex_home: PathBuf, timeout: Duration) -> Self { - let codex_home = AbsolutePathBuf::resolve_path_against_base(codex_home, "/"); - let cache = match source.cache_namespace() { - Some(namespace) => CloudConfigBundleCache::for_source(codex_home.clone(), &namespace), - None => CloudConfigBundleCache::new(codex_home.clone()), - }; - Self { - source, - cache, - cache_enabled: true, - codex_home, - timeout, - latest_bundle: OnceCell::new(), - policy: CloudConfigBundlePolicy::default(), - } - } - - pub(crate) fn without_cache(mut self) -> Self { - self.cache_enabled = false; - self - } - - pub(crate) async fn get_latest( - &self, - ) -> Result, CloudConfigBundleLoadError> { - self.get_latest_snapshot().await.bundle - } - - pub(crate) async fn get_latest_snapshot(&self) -> CloudConfigBundleSnapshot { - self.latest_snapshot().await.lock().await.clone() - } - - async fn latest_snapshot(&self) -> &Mutex { - self.latest_bundle - .get_or_init(|| async { - let mut snapshot = CloudConfigBundleSnapshot { - config_server: None, - bundle: self.load_startup_bundle_with_timeout().await, - binding: None, - }; - self.policy.publish_snapshot(&mut snapshot); - Mutex::new(snapshot) - }) - .await - } - - pub(crate) async fn load_startup_bundle_with_timeout( - &self, - ) -> Result, CloudConfigBundleLoadError> { - let _timer = - codex_otel::start_global_timer("codex.cloud_config_bundle.fetch.duration_ms", &[]); - let started_at = Instant::now(); - let load_result = timeout(self.timeout, self.load_startup_bundle()) - .await - .inspect_err(|_| { - let message = format!( - "Timed out waiting for cloud config bundle after {}s", - self.timeout.as_secs() - ); - tracing::error!("{message}"); - emit_load_metric("startup", "error", /*bundle*/ None); - }) - .map_err(|_| { - CloudConfigBundleLoadError::new( - CloudConfigBundleLoadErrorCode::Timeout, - /*status_code*/ None, - format!( - "timed out waiting for cloud config bundle after {}s", - self.timeout.as_secs() - ), - ) - })?; - - let result = match load_result { - Ok(result) => result, - Err(err) => { - emit_load_metric("startup", "error", /*bundle*/ None); - return Err(err); - } - }; - - match result.as_ref() { - Some(bundle) => { - tracing::info!( - elapsed_ms = started_at.elapsed().as_millis(), - config_fragments = bundle.config_toml.enterprise_managed.len(), - requirements_fragments = bundle.requirements_toml.enterprise_managed.len(), - "Cloud config bundle load completed" - ); - emit_load_metric("startup", "success", Some(bundle)); - } - None => { - tracing::info!( - elapsed_ms = started_at.elapsed().as_millis(), - "Cloud config bundle load completed (none)" - ); - emit_load_metric("startup", "success", /*bundle*/ None); - } - } - - Ok(result) - } - - async fn load_startup_bundle( - &self, - ) -> Result, CloudConfigBundleLoadError> { - let Some(auth) = self.source.auth().await? else { - return Ok(None); - }; - - if self.cache_enabled { - // Startup prefers a valid, identity-matched cache entry. The backend is - // only consulted on cache miss or invalid cache contents. - let (chatgpt_user_id, account_id) = self.source.identity(&auth); - match self - .load_valid_cached_bundle(chatgpt_user_id.as_deref(), account_id.as_deref()) - .await - { - CachedBundleLookup::Hit(bundle) => return Ok(bundle), - CachedBundleLookup::Miss => {} - } - } - - self.fetch_remote_bundle_and_update_cache_with_retries(auth, "startup") - .await - } - - async fn load_valid_cached_bundle( - &self, - chatgpt_user_id: Option<&str>, - account_id: Option<&str>, - ) -> CachedBundleLookup { - match self.cache.load(chatgpt_user_id, account_id).await { - Ok(signed_payload) => { - if let Err(err) = validate_bundle(&signed_payload.bundle, &self.codex_home) { - tracing::warn!( - path = %self.cache.path().display(), - error = %err, - "Ignoring invalid cached cloud config bundle" - ); - self.cache - .log_load_status(&CacheLoadStatus::CacheInvalidBundle); - CachedBundleLookup::Miss - } else { - tracing::info!( - path = %self.cache.path().display(), - "Using cached cloud config bundle" - ); - CachedBundleLookup::Hit(optional_bundle(signed_payload.bundle)) - } - } - Err(cache_load_status) => { - self.cache.log_load_status(&cache_load_status); - CachedBundleLookup::Miss - } - } - } - - async fn fetch_remote_bundle_and_update_cache_with_retries( - &self, - mut auth: S::Auth, - trigger: &'static str, - ) -> Result, CloudConfigBundleLoadError> { - let mut context = self.source.begin_fetch(); - let mut attempt = 1; - let mut last_status_code: Option = None; - - while attempt <= CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS { - match self - .fetch_with_auth_recovery(&mut auth, &mut context, trigger, attempt) - .await - { - Ok(bundle) => { - return self - .validate_and_cache_remote_bundle(&auth, trigger, attempt, bundle) - .await; - } - Err(BundleRequestError::Policy(denied)) => { - return Err(CloudConfigBundleLoadError::new( - CloudConfigBundleLoadErrorCode::RequestFailed, - /*status_code*/ None, - denied.to_string(), - )); - } - Err(BundleRequestError::Retryable(status)) => { - last_status_code = status.status_code(); - if self - .retry_after_request_failure(trigger, attempt, status) - .await - { - attempt += 1; - continue; - } - } - Err(BundleRequestError::Fatal { - error, - metric_reason, - }) => { - if let Some(reason) = metric_reason { - emit_fetch_final_metric( - trigger, - "error", - reason, - attempt, - error.status_code(), - /*bundle*/ None, - ); - } - return Err(error); - } - Err(BundleRequestError::Unauthorized { - status_code, - message, - }) => { - emit_fetch_final_metric( - trigger, - "error", - "auth", - attempt, - status_code, - /*bundle*/ None, - ); - return Err(CloudConfigBundleLoadError::new( - CloudConfigBundleLoadErrorCode::Auth, - status_code, - message, - )); - } - } - - break; - } - - emit_fetch_final_metric( - trigger, - "error", - "request_retry_exhausted", - CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS, - last_status_code, - /*bundle*/ None, - ); - tracing::error!( - path = %self.cache.path().display(), - "{CLOUD_CONFIG_BUNDLE_LOAD_FAILED_MESSAGE}" - ); - Err(CloudConfigBundleLoadError::new( - CloudConfigBundleLoadErrorCode::RequestFailed, - last_status_code, - CLOUD_CONFIG_BUNDLE_LOAD_FAILED_MESSAGE, - )) - } - - async fn fetch_with_auth_recovery( - &self, - auth: &mut S::Auth, - context: &mut S::FetchContext, - trigger: &'static str, - attempt: usize, - ) -> Result { - let mut recovery_attempt = 0; - loop { - let result = self.source.get_bundle(auth, context).await; - let Err(BundleRequestError::Unauthorized { status_code, .. }) = &result else { - return result; - }; - emit_fetch_attempt_metric(trigger, attempt, "unauthorized", *status_code); - if !self - .source - .recover_auth(auth, context, *status_code, recovery_attempt) - .await? - { - return result; - } - recovery_attempt += 1; - } - } - - async fn validate_and_cache_remote_bundle( - &self, - auth: &S::Auth, - trigger: &'static str, - attempt: usize, - bundle: CloudConfigBundle, - ) -> Result, CloudConfigBundleLoadError> { - emit_fetch_attempt_metric(trigger, attempt, "success", /*status_code*/ None); - let revision = self.policy.observe_remote_bundle(&bundle); - if let Err(err) = validate_bundle(&bundle, &self.codex_home) { - emit_fetch_final_metric( - trigger, - "error", - "invalid_bundle", - attempt, - /*status_code*/ None, - /*bundle*/ None, - ); - return Err(err); - } - - let (chatgpt_user_id, account_id) = self.source.identity(auth); - if self.cache_enabled - && let Some(revision) = revision - { - let result = match self - .cache - .prepare(chatgpt_user_id, account_id, bundle.clone()) - .await - { - Ok(staged) => staged.publish_if_current(revision).await, - Err(err) => Err(err), - }; - if let Err(err) = result { - tracing::warn!(error = %err, "Failed to write cloud config bundle cache"); - } - } - - emit_fetch_final_metric( - trigger, - "success", - "none", - attempt, - /*status_code*/ None, - Some(&bundle), - ); - Ok(optional_bundle(bundle)) - } - - async fn retry_after_request_failure( - &self, - trigger: &'static str, - attempt: usize, - status: RetryableFailureKind, - ) -> bool { - let status_code = status.status_code(); - if matches!(status, RetryableFailureKind::Request { .. }) { - emit_fetch_attempt_metric(trigger, attempt, "error", status_code); - } - if attempt < CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS { - tracing::warn!( - status = ?status, - attempt, - max_attempts = CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS, - "Failed to fetch cloud config bundle; retrying" - ); - sleep(backoff(attempt as u64)).await; - true - } else { - false - } - } - - pub(crate) async fn refresh_cache_in_background(&self) { - loop { - let mut refresh_interval = CLOUD_CONFIG_BUNDLE_CACHE_REFRESH_INTERVAL; - if let Some(latest_bundle) = self.latest_bundle.get() - && matches!( - &latest_bundle.lock().await.bundle, - Err(error) if error.code() == CloudConfigBundleLoadErrorCode::Timeout - ) - { - // Recover startup timeouts through this worker without making - // readers fetch concurrently or extending the startup deadline. - refresh_interval = CLOUD_CONFIG_BUNDLE_TIMEOUT_RETRY_INTERVAL; - } - sleep(refresh_interval).await; - match timeout(self.timeout, self.refresh_cache_once()).await { - Ok(true) => {} - Ok(false) => break, - Err(_) => { - tracing::error!( - "Timed out refreshing cloud config bundle cache from remote; keeping existing cache" - ); - emit_load_metric("refresh", "error", /*bundle*/ None); - self.publish_refresh_result(Err(CloudConfigBundleLoadError::new( - CloudConfigBundleLoadErrorCode::Timeout, - /*status_code*/ None, - "timed out refreshing cloud config bundle", - ))) - .await; - } - } - } - } - - async fn refresh_cache_once(&self) -> bool { - let auth = match self.source.auth().await { - Ok(Some(auth)) => auth, - Ok(None) => return false, - Err(error) => { - self.publish_refresh_result(Err(error)).await; - return true; - } - }; - - match self - .fetch_remote_bundle_and_update_cache_with_retries(auth, "refresh") - .await - { - Ok(bundle) => { - emit_load_metric("refresh", "success", bundle.as_ref()); - self.publish_refresh_result(Ok(bundle)).await; - } - Err(err) => { - tracing::error!( - path = %self.cache.path().display(), - error = %err, - "Failed to refresh cloud config bundle cache from remote" - ); - emit_load_metric("refresh", "error", /*bundle*/ None); - self.publish_refresh_result(Err(err)).await; - } - } - true - } - - async fn publish_refresh_result( - &self, - result: Result, CloudConfigBundleLoadError>, - ) { - let Some(latest) = self.latest_bundle.get() else { - return; - }; - let mut latest = latest.lock().await; - if result.is_ok() { - *latest = CloudConfigBundleSnapshot { - config_server: None, - bundle: result, - binding: None, - }; - self.policy.publish_snapshot(&mut latest); - } else if latest.bundle.is_err() { - latest.bundle = result; - latest.binding = None; - } - } -} - -#[cfg(test)] -#[path = "service_tests.rs"] -mod tests; diff --git a/codex-rs/cloud-config/src/service_tests.rs b/codex-rs/cloud-config/src/service_tests.rs deleted file mode 100644 index 70fd0a02..00000000 --- a/codex-rs/cloud-config/src/service_tests.rs +++ /dev/null @@ -1,1832 +0,0 @@ -use super::*; -use crate::backend::BundleClient; -use crate::backend::BundleRequestError; -use crate::backend::RetryableFailureKind; -use crate::backend::bundle_from_response; -use crate::cache::CLOUD_CONFIG_BUNDLE_CACHE_FILENAME; -use crate::cache::CloudConfigBundleCache; -use crate::metrics::bundle_shape_tag; -use base64::Engine; -use base64::engine::general_purpose::URL_SAFE_NO_PAD; -use codex_backend_client::ConfigBundleResponse; -use codex_backend_client::DeliveredTomlFragment; -use codex_config::AbsolutePathBuf; -use codex_config::CloudConfigBundleBindingStatus; -use codex_config::CloudConfigFragment; -use codex_config::CloudConfigTomlBundle; -use codex_config::CloudRequirementsFragment; -use codex_config::CloudRequirementsTomlBundle; -use codex_config::types::AuthCredentialsStoreMode; -use codex_core::config::ConfigBuilder; -use codex_login::AuthKeyringBackendKind; -use codex_login::CodexAuth; -use codex_login::auth::AgentIdentityAuth; -use codex_login::auth::AgentIdentityAuthRecord; -use codex_login::auth::ExternalAuth; -use codex_login::auth::ExternalAuthRefreshContext; -use codex_protocol::account::PlanType; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::collections::VecDeque; -use std::future::pending; -use std::path::Path; -use std::sync::RwLock; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; -use tempfile::tempdir; - -fn write_auth_json(codex_home: &Path, value: serde_json::Value) -> std::io::Result<()> { - std::fs::write(codex_home.join("auth.json"), serde_json::to_string(&value)?)?; - Ok(()) -} - -fn create_test_cache(codex_home: &Path) -> CloudConfigBundleCache { - CloudConfigBundleCache::new(AbsolutePathBuf::resolve_path_against_base(codex_home, "/")) -} - -async fn write_test_cache(cache: &CloudConfigBundleCache, bundle: CloudConfigBundle) { - let revision = CloudConfigBundlePolicy::default() - .observe_remote_bundle(&bundle) - .expect("fixture revision"); - cache - .prepare( - Some("user-12345".to_string()), - Some("account-12345".to_string()), - bundle, - ) - .await - .expect("stage test cache") - .publish_if_current(revision) - .await - .expect("write test cache"); -} - -async fn auth_manager_with_api_key() -> Arc { - let tmp = tempdir().expect("tempdir"); - let auth_json = json!({ - "OPENAI_API_KEY": "sk-test-key", - "tokens": null, - "last_refresh": null, - }); - write_auth_json(tmp.path(), auth_json).expect("write auth"); - Arc::new( - AuthManager::new( - tmp.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::File, - /*forced_chatgpt_workspace_id*/ None, - /*chatgpt_base_url*/ None, - AuthKeyringBackendKind::default(), - codex_login::test_support::transport_default_auth_route_config(), - ) - .await, - ) -} - -async fn auth_manager_with_plan_and_identity( - plan_type: &str, - chatgpt_user_id: Option<&str>, - account_id: Option<&str>, -) -> Arc { - let tmp = tempdir().expect("tempdir"); - write_auth_json( - tmp.path(), - chatgpt_auth_json( - plan_type, - chatgpt_user_id, - account_id, - "test-access-token", - "test-refresh-token", - ), - ) - .expect("write auth"); - Arc::new( - AuthManager::new( - tmp.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::File, - /*forced_chatgpt_workspace_id*/ None, - /*chatgpt_base_url*/ None, - AuthKeyringBackendKind::default(), - codex_login::test_support::transport_default_auth_route_config(), - ) - .await, - ) -} - -async fn auth_manager_with_plan(plan_type: &str) -> Arc { - auth_manager_with_plan_and_identity(plan_type, Some("user-12345"), Some("account-12345")).await -} - -async fn auth_manager_with_agent_identity_business_plan() -> Arc { - let key_material = - codex_agent_identity::generate_agent_key_material().expect("generate agent key material"); - AuthManager::from_auth_for_testing(CodexAuth::AgentIdentity( - AgentIdentityAuth::from_record( - AgentIdentityAuthRecord { - agent_runtime_id: "agent-runtime-123".to_string(), - agent_private_key: key_material.private_key_pkcs8_base64, - account_id: "account-12345".to_string(), - chatgpt_user_id: "user-12345".to_string(), - email: Some("user@example.com".to_string()), - plan_type: PlanType::Business, - chatgpt_account_is_fedramp: false, - task_id: Some("task-123".to_string()), - }, - "https://auth.openai.com/api/accounts", - &codex_login::test_support::transport_default_auth_route_config(), - ) - .await - .expect("agent identity record should be complete"), - )) -} - -fn chatgpt_auth_json( - plan_type: &str, - chatgpt_user_id: Option<&str>, - account_id: Option<&str>, - access_token: &str, - refresh_token: &str, -) -> serde_json::Value { - chatgpt_auth_json_with_last_refresh( - plan_type, - chatgpt_user_id, - account_id, - access_token, - refresh_token, - "2025-01-01T00:00:00Z", - ) -} - -fn chatgpt_auth_json_with_last_refresh( - plan_type: &str, - chatgpt_user_id: Option<&str>, - account_id: Option<&str>, - access_token: &str, - refresh_token: &str, - last_refresh: &str, -) -> serde_json::Value { - let fake_jwt = fake_chatgpt_jwt(plan_type, chatgpt_user_id, b"sig"); - json!({ - "OPENAI_API_KEY": null, - "tokens": { - "id_token": fake_jwt, - "access_token": access_token, - "refresh_token": refresh_token, - "account_id": account_id, - }, - "last_refresh": last_refresh, - }) -} - -fn fake_chatgpt_jwt(plan_type: &str, chatgpt_user_id: Option<&str>, signature: &[u8]) -> String { - let header = json!({ "alg": "none", "typ": "JWT" }); - let auth_payload = json!({ - "chatgpt_plan_type": plan_type, - "chatgpt_user_id": chatgpt_user_id, - "user_id": chatgpt_user_id, - }); - let payload = json!({ - "email": "user@example.com", - "https://api.openai.com/auth": auth_payload, - }); - let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).expect("header")); - let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).expect("payload")); - let signature_b64 = URL_SAFE_NO_PAD.encode(signature); - format!("{header_b64}.{payload_b64}.{signature_b64}") -} - -fn test_bundle() -> CloudConfigBundle { - CloudConfigBundle { - config_toml: CloudConfigTomlBundle { - enterprise_managed: vec![test_config_fragment()], - }, - requirements_toml: CloudRequirementsTomlBundle { - enterprise_managed: vec![test_requirements_fragment()], - }, - } -} - -fn test_config_fragment() -> CloudConfigFragment { - CloudConfigFragment { - id: "cfg_1".to_string(), - name: "Base config".to_string(), - contents: "model = \"gpt-5\"".to_string(), - } -} - -fn test_requirements_fragment() -> CloudRequirementsFragment { - CloudRequirementsFragment { - id: "req_1".to_string(), - name: "Base requirements".to_string(), - contents: "allowed_approval_policies = [\"never\"]".to_string(), - } -} - -fn invalid_config_bundle() -> CloudConfigBundle { - CloudConfigBundle { - config_toml: CloudConfigTomlBundle { - enterprise_managed: vec![CloudConfigFragment { - id: "cfg_invalid".to_string(), - name: "Invalid config".to_string(), - contents: "model = [".to_string(), - }], - }, - requirements_toml: CloudRequirementsTomlBundle::default(), - } -} - -fn request_error() -> BundleRequestError { - BundleRequestError::Retryable(RetryableFailureKind::Request { status_code: None }) -} - -#[tokio::test] -async fn superseded_staged_cache_write_cannot_replace_newer_service_bundle() { - let codex_home = tempdir().expect("tempdir"); - let auth_manager = auth_manager_with_plan("business").await; - let auth = auth_manager.auth().await.expect("auth"); - let service = Arc::new(CloudConfigBundleService::new( - auth_manager, - Arc::new(StaticBundleClient::new(test_bundle())), - codex_home.path().to_path_buf(), - Duration::from_secs(10), - )); - let old = test_bundle(); - let new = CloudConfigBundle::default(); - let (staged, staging) = tokio::sync::oneshot::channel(); - let (resume, resumed) = tokio::sync::oneshot::channel(); - let older = Arc::clone(&service); - let pending = tokio::spawn(async move { - let revision = older - .policy - .observe_remote_bundle(&old) - .expect("old revision"); - let output = older - .cache - .prepare( - Some("user-12345".to_string()), - Some("account-12345".to_string()), - old, - ) - .await - .expect("stage older cache"); - staged.send(()).expect("announce staging"); - resumed.await.expect("resume older writer"); - output - .publish_if_current(revision) - .await - .expect("discard older cache"); - }); - staging.await.expect("older cache is staged"); - service - .validate_and_cache_remote_bundle(&auth, "refresh", /*attempt*/ 1, new.clone()) - .await - .expect("publish newer bundle"); - resume.send(()).expect("resume older writer"); - pending.await.expect("older writer completed"); - - assert_eq!( - service - .cache - .load(Some("user-12345"), Some("account-12345")) - .await - .expect("load cache") - .bundle, - new - ); - let files: Vec<_> = std::fs::read_dir(codex_home.path()) - .expect("read cache directory") - .map(|entry| entry.expect("directory entry").path()) - .collect(); - assert_eq!(files, vec![service.cache.path().to_path_buf()]); -} - -#[tokio::test] -async fn retired_policy_discards_staged_cache_and_retains_previous_payload() { - let codex_home = tempdir().expect("tempdir"); - let auth_manager = auth_manager_with_plan("business").await; - let auth = auth_manager.auth().await.expect("auth"); - let service = CloudConfigBundleService::new( - auth_manager, - Arc::new(StaticBundleClient::new(test_bundle())), - codex_home.path().to_path_buf(), - Duration::from_secs(10), - ); - let previous = test_bundle(); - service - .validate_and_cache_remote_bundle(&auth, "refresh", /*attempt*/ 1, previous.clone()) - .await - .expect("publish previous bundle"); - let changed = CloudConfigBundle::default(); - let revision = service - .policy - .observe_remote_bundle(&changed) - .expect("changed revision"); - let output = service - .cache - .prepare( - Some("user-12345".to_string()), - Some("account-12345".to_string()), - changed, - ) - .await - .expect("stage changed cache"); - let loader = codex_config::CloudConfigBundleLoader::new(async { Ok(None) }) - .with_ema_policy_snapshots(service.policy.clone(), || async { - CloudConfigBundleSnapshot { - config_server: None, - bundle: Ok(None), - binding: None, - } - }); - loader.retire_ema_policy(); - output - .publish_if_current(revision) - .await - .expect("discard retired cache"); - assert_eq!( - service - .cache - .load(Some("user-12345"), Some("account-12345")) - .await - .expect("load cache") - .bundle, - previous - ); -} - -struct StaticBundleClient { - bundle: CloudConfigBundle, - request_count: AtomicUsize, -} - -impl StaticBundleClient { - fn new(bundle: CloudConfigBundle) -> Self { - Self { - bundle, - request_count: AtomicUsize::new(0), - } - } -} - -impl BundleClient for StaticBundleClient { - async fn get_bundle(&self, _auth: &CodexAuth) -> Result { - self.request_count.fetch_add(1, Ordering::SeqCst); - Ok(self.bundle.clone()) - } -} - -struct PendingBundleClient; - -impl BundleClient for PendingBundleClient { - async fn get_bundle(&self, _auth: &CodexAuth) -> Result { - pending::<()>().await; - Ok(CloudConfigBundle::default()) - } -} - -struct NotifyingPendingBundleClient { - request_started: Arc, - request_cancelled: Arc, -} - -impl Drop for NotifyingPendingBundleClient { - fn drop(&mut self) { - self.request_cancelled.notify_one(); - } -} - -impl BundleClient for NotifyingPendingBundleClient { - async fn get_bundle(&self, _auth: &CodexAuth) -> Result { - self.request_started.notify_one(); - pending::<()>().await; - Ok(CloudConfigBundle::default()) - } -} - -struct SequenceBundleClient { - responses: tokio::sync::Mutex>>, - request_count: AtomicUsize, - request_started: tokio::sync::Notify, - timeout_attempts: usize, -} - -impl SequenceBundleClient { - fn new(responses: Vec>) -> Self { - Self { - responses: tokio::sync::Mutex::new(VecDeque::from(responses)), - request_count: AtomicUsize::new(0), - request_started: tokio::sync::Notify::new(), - timeout_attempts: 0, - } - } -} - -impl BundleClient for SequenceBundleClient { - async fn get_bundle(&self, _auth: &CodexAuth) -> Result { - let attempt = self.request_count.fetch_add(1, Ordering::SeqCst); - self.request_started.notify_one(); - if attempt < self.timeout_attempts { - pending::<()>().await; - } - let mut responses = self.responses.lock().await; - responses - .pop_front() - .unwrap_or_else(|| Ok(CloudConfigBundle::default())) - } -} - -struct TokenBundleClient { - expected_token: String, - bundle: CloudConfigBundle, - request_count: AtomicUsize, -} - -impl BundleClient for TokenBundleClient { - async fn get_bundle(&self, auth: &CodexAuth) -> Result { - self.request_count.fetch_add(1, Ordering::SeqCst); - if matches!( - auth.get_token().as_deref(), - Ok(token) if token == self.expected_token.as_str() - ) { - Ok(self.bundle.clone()) - } else { - Err(BundleRequestError::Unauthorized { - status_code: Some(401), - message: "GET /config/bundle failed: 401".to_string(), - }) - } - } -} - -struct UnauthorizedBundleClient { - message: String, - request_count: AtomicUsize, -} - -struct TestExternalChatgptAuth { - current: RwLock, - refreshed: CodexAuth, - refresh_count: AtomicUsize, -} - -impl ExternalAuth for TestExternalChatgptAuth { - fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, CodexAuth> { - Box::pin(async { - self.current - .read() - .map(|auth| auth.clone()) - .map_err(|_| std::io::Error::other("external auth lock is poisoned")) - }) - } - - fn refresh( - &self, - _context: ExternalAuthRefreshContext, - ) -> codex_login::ExternalAuthFuture<'_, CodexAuth> { - Box::pin(async { - let refreshed = self.refreshed.clone(); - *self - .current - .write() - .map_err(|_| std::io::Error::other("external auth lock is poisoned"))? = - refreshed.clone(); - self.refresh_count.fetch_add(1, Ordering::SeqCst); - Ok(refreshed) - }) - } -} - -impl BundleClient for UnauthorizedBundleClient { - async fn get_bundle(&self, _auth: &CodexAuth) -> Result { - self.request_count.fetch_add(1, Ordering::SeqCst); - Err(BundleRequestError::Unauthorized { - status_code: Some(401), - message: self.message.clone(), - }) - } -} - -#[test] -fn bundle_shape_tag_describes_sorted_enterprise_sources() { - assert_eq!(bundle_shape_tag(/*bundle*/ None), "none"); - assert_eq!( - bundle_shape_tag(Some(&CloudConfigBundle::default())), - "empty" - ); - assert_eq!( - bundle_shape_tag(Some(&CloudConfigBundle { - config_toml: CloudConfigTomlBundle { - enterprise_managed: vec![test_config_fragment()], - }, - requirements_toml: CloudRequirementsTomlBundle::default(), - })), - "enterprise_config" - ); - assert_eq!( - bundle_shape_tag(Some(&CloudConfigBundle { - config_toml: CloudConfigTomlBundle::default(), - requirements_toml: CloudRequirementsTomlBundle { - enterprise_managed: vec![test_requirements_fragment()], - }, - })), - "enterprise_requirements" - ); - assert_eq!( - bundle_shape_tag(Some(&CloudConfigBundle { - config_toml: CloudConfigTomlBundle { - enterprise_managed: vec![test_config_fragment()], - }, - requirements_toml: CloudRequirementsTomlBundle { - enterprise_managed: vec![test_requirements_fragment()], - }, - })), - "enterprise_config,enterprise_requirements" - ); -} - -#[tokio::test] -async fn get_bundle_skips_non_chatgpt_auth() { - let fetcher = Arc::new(StaticBundleClient::new(test_bundle())); - let codex_home = tempdir().expect("tempdir"); - let service = CloudConfigBundleService::new( - auth_manager_with_api_key().await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - assert_eq!(service.load_startup_bundle().await, Ok(None)); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 0); -} - -#[tokio::test] -async fn get_bundle_skips_individual_plan() { - let fetcher = Arc::new(StaticBundleClient::new(test_bundle())); - let codex_home = tempdir().expect("tempdir"); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("pro").await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - assert_eq!(service.load_startup_bundle().await, Ok(None)); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 0); -} - -#[tokio::test] -async fn get_bundle_allows_eligible_workspace_plans_and_writes_cache() { - for plan_type in [ - "business", - "ent26", - "enterprise_cbp_automation", - "enterprise_cbp_usage_based", - "enterprise", - "hc", - "edu", - "education", - "edu_plus", - "edu_pro", - "sci", - "sci_plus", - ] { - let bundle = test_bundle(); - let fetcher = Arc::new(StaticBundleClient::new(bundle.clone())); - let codex_home = tempdir().expect("tempdir"); - let service = CloudConfigBundleService::new( - auth_manager_with_plan(plan_type).await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - assert_eq!( - service.load_startup_bundle().await, - Ok(Some(bundle)), - "plan_type: {plan_type}" - ); - assert_eq!( - fetcher.request_count.load(Ordering::SeqCst), - 1, - "plan_type: {plan_type}" - ); - assert!( - codex_home - .path() - .join(CLOUD_CONFIG_BUNDLE_CACHE_FILENAME) - .exists(), - "plan_type: {plan_type}" - ); - } -} - -#[tokio::test] -async fn get_bundle_allows_agent_identity_business_plan() { - let bundle = test_bundle(); - let fetcher = Arc::new(StaticBundleClient::new(bundle.clone())); - let codex_home = tempdir().expect("tempdir"); - let service = CloudConfigBundleService::new( - auth_manager_with_agent_identity_business_plan().await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - assert_eq!(service.load_startup_bundle().await, Ok(Some(bundle))); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); - assert!( - codex_home - .path() - .join(CLOUD_CONFIG_BUNDLE_CACHE_FILENAME) - .exists() - ); -} - -#[tokio::test] -async fn get_bundle_skips_team_like_business_plans() { - for plan_type in [ - "self_serve_business_prolite", - "self_serve_business_usage_based", - ] { - let fetcher = Arc::new(StaticBundleClient::new(test_bundle())); - let codex_home = tempdir().expect("tempdir"); - let service = CloudConfigBundleService::new( - auth_manager_with_plan(plan_type).await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - assert_eq!(service.load_startup_bundle().await, Ok(None)); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 0); - } -} - -#[tokio::test] -async fn get_bundle_rejects_invalid_remote_bundle_before_cache_write() { - let codex_home = tempdir().expect("tempdir"); - let mut invalid = invalid_config_bundle(); - invalid.config_toml.enterprise_managed[0].contents = - "secret_credential = [secret-token".to_string(); - let fetcher = Arc::new(StaticBundleClient::new(invalid)); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - let err = service - .load_startup_bundle() - .await - .expect_err("invalid remote bundle should fail closed"); - - assert_eq!(err.code(), CloudConfigBundleLoadErrorCode::InvalidBundle); - assert!(err.to_string().contains("invalid cloud config bundle")); - assert!(!err.to_string().contains("secret")); - assert!(!format!("{err:?}").contains("secret")); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); - assert!( - !codex_home - .path() - .join(CLOUD_CONFIG_BUNDLE_CACHE_FILENAME) - .exists() - ); -} - -#[tokio::test] -async fn invalid_requirements_do_not_replace_cached_bundle() { - let codex_home = tempdir().expect("tempdir"); - let cache = create_test_cache(codex_home.path()); - let previous = test_bundle(); - write_test_cache(&cache, previous.clone()).await; - - for contents in [ - "allowed_approval_policies = ['secret-policy']", - "[model_providers.openai]\nname = 'Reserved'", - "[model_providers.secret-provider]\nname = ' '", - "[model_providers.gateway]\nbase_url = 'https://gateway.example/v1'", - "[model_providers.amazon-bedrock]\nname = 'Managed Bedrock'", - "[model_providers.amazon-bedrock-runtime]\nname = 'Managed Bedrock Runtime'", - "[model_providers.amazon-bedrock]\nrequest_max_retries = 3", - "[model_providers.gateway]\nname = 'Gateway'\n[model_providers.gateway.auth]\ntimeout_ms = 10000", - ] { - let mut invalid = test_bundle(); - invalid.requirements_toml.enterprise_managed[0].contents = contents.to_string(); - let auth_manager = auth_manager_with_plan("business").await; - let auth = auth_manager.auth().await.expect("business auth"); - let service = CloudConfigBundleService::new( - auth_manager, - Arc::new(StaticBundleClient::new(invalid.clone())), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - let error = service - .validate_and_cache_remote_bundle(&auth, "refresh", /*attempt*/ 1, invalid) - .await - .expect_err("invalid requirements must fail before cache write"); - assert_eq!(error.code(), CloudConfigBundleLoadErrorCode::InvalidBundle); - assert!(!error.to_string().contains("secret")); - assert!(!format!("{error:?}").contains("secret")); - assert_eq!( - cache - .load(Some("user-12345"), Some("account-12345")) - .await - .expect("retain previous cache") - .bundle, - previous - ); - } -} - -#[tokio::test] -async fn get_bundle_ignores_invalid_cache_and_refetches() { - let codex_home = tempdir().expect("tempdir"); - let cache = create_test_cache(codex_home.path()); - write_test_cache(&cache, invalid_config_bundle()).await; - let replacement_bundle = test_bundle(); - let fetcher = Arc::new(StaticBundleClient::new(replacement_bundle.clone())); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - assert_eq!( - service.load_startup_bundle().await, - Ok(Some(replacement_bundle.clone())) - ); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); - assert_eq!( - cache - .load(Some("user-12345"), Some("account-12345")) - .await - .expect("load refreshed cache") - .bundle, - replacement_bundle - ); -} - -#[tokio::test] -async fn get_bundle_empty_response_is_success_and_cached() { - let codex_home = tempdir().expect("tempdir"); - let fetcher = Arc::new(StaticBundleClient::new(CloudConfigBundle::default())); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("enterprise").await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - assert_eq!(service.load_startup_bundle().await, Ok(None)); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); - assert!( - codex_home - .path() - .join(CLOUD_CONFIG_BUNDLE_CACHE_FILENAME) - .exists() - ); -} - -#[tokio::test] -async fn get_bundle_uses_cache_when_valid() { - let bundle = test_bundle(); - let codex_home = tempdir().expect("tempdir"); - let prime_service = CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - Arc::new(StaticBundleClient::new(bundle.clone())), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - let _ = prime_service.load_startup_bundle().await; - - let fetcher = Arc::new(SequenceBundleClient::new(vec![Err(request_error())])); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - assert_eq!(service.load_startup_bundle().await, Ok(Some(bundle))); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 0); -} - -#[tokio::test] -async fn get_bundle_without_cache_ignores_and_preserves_valid_cache() { - let codex_home = tempdir().expect("tempdir"); - let cache = create_test_cache(codex_home.path()); - write_test_cache(&cache, CloudConfigBundle::default()).await; - let cached_bytes = std::fs::read(cache.path()).expect("read cache"); - let bundle = test_bundle(); - let fetcher = Arc::new(StaticBundleClient::new(bundle.clone())); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ) - .without_cache(); - - assert_eq!( - service.load_startup_bundle_with_timeout().await, - Ok(Some(bundle)) - ); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); - assert_eq!( - std::fs::read(cache.path()).expect("read unchanged cache"), - cached_bytes - ); -} - -#[tokio::test(start_paused = true)] -async fn get_bundle_without_cache_fails_closed_on_request_failure() { - let codex_home = tempdir().expect("tempdir"); - write_test_cache(&create_test_cache(codex_home.path()), test_bundle()).await; - let fetcher = Arc::new(SequenceBundleClient::new(vec![ - Err(request_error()); - CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS - ])); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ) - .without_cache(); - - let err = service - .load_startup_bundle_with_timeout() - .await - .expect_err("request failure must not fall back to the cache"); - assert_eq!(err.code(), CloudConfigBundleLoadErrorCode::RequestFailed); - assert_eq!( - fetcher.request_count.load(Ordering::SeqCst), - CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS - ); -} - -#[tokio::test] -async fn get_bundle_ignores_cache_for_different_auth_identity() { - let codex_home = tempdir().expect("tempdir"); - let prime_service = CloudConfigBundleService::new( - auth_manager_with_plan_and_identity("business", Some("user-12345"), Some("account-12345")) - .await, - Arc::new(StaticBundleClient::new(test_bundle())), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - let _ = prime_service.load_startup_bundle().await; - - let replacement_bundle = CloudConfigBundle { - config_toml: CloudConfigTomlBundle::default(), - requirements_toml: CloudRequirementsTomlBundle { - enterprise_managed: vec![CloudRequirementsFragment { - id: "req_2".to_string(), - name: "Replacement requirements".to_string(), - contents: "allowed_approval_policies = [\"on-request\"]".to_string(), - }], - }, - }; - let fetcher = Arc::new(SequenceBundleClient::new(vec![Ok( - replacement_bundle.clone() - )])); - let service = CloudConfigBundleService::new( - auth_manager_with_plan_and_identity("business", Some("user-99999"), Some("account-12345")) - .await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - assert_eq!( - service.load_startup_bundle().await, - Ok(Some(replacement_bundle)) - ); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); -} - -#[tokio::test(start_paused = true)] -async fn get_bundle_times_out() { - let codex_home = tempdir().expect("tempdir"); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("enterprise").await, - Arc::new(PendingBundleClient), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - let handle = tokio::spawn(async move { service.load_startup_bundle_with_timeout().await }); - tokio::time::advance(CLOUD_CONFIG_BUNDLE_TIMEOUT + Duration::from_millis(1)).await; - - let result = handle.await.expect("cloud config bundle task"); - let err = result.expect_err("cloud config bundle timeout should fail closed"); - assert!( - err.to_string() - .contains("timed out waiting for cloud config bundle") - ); -} - -#[tokio::test(start_paused = true)] -async fn get_bundle_retries_until_success() { - let fetcher = Arc::new(SequenceBundleClient::new(vec![ - Err(request_error()), - Ok(test_bundle()), - ])); - let codex_home = tempdir().expect("tempdir"); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - let handle = tokio::spawn(async move { service.load_startup_bundle().await }); - tokio::task::yield_now().await; - tokio::time::advance(Duration::from_secs(1)).await; - - assert_eq!(handle.await.expect("bundle task"), Ok(Some(test_bundle()))); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 2); -} - -#[tokio::test] -async fn get_bundle_recovers_after_unauthorized_reload() { - let auth_home = tempdir().expect("tempdir"); - write_auth_json( - auth_home.path(), - chatgpt_auth_json_with_last_refresh( - "business", - Some("user-12345"), - Some("account-12345"), - "stale-access-token", - "test-refresh-token", - // Keep auth "fresh" so the first request hits unauthorized recovery - // instead of AuthManager::auth() proactively reloading from disk. - "3025-01-01T00:00:00Z", - ), - ) - .expect("write initial auth"); - let auth_manager = Arc::new( - AuthManager::new( - auth_home.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::File, - /*forced_chatgpt_workspace_id*/ None, - /*chatgpt_base_url*/ None, - AuthKeyringBackendKind::default(), - codex_login::test_support::transport_default_auth_route_config(), - ) - .await, - ); - - write_auth_json( - auth_home.path(), - chatgpt_auth_json_with_last_refresh( - "business", - Some("user-12345"), - Some("account-12345"), - "fresh-access-token", - "test-refresh-token", - "3025-01-01T00:00:00Z", - ), - ) - .expect("write refreshed auth"); - let fetcher = Arc::new(TokenBundleClient { - expected_token: "fresh-access-token".to_string(), - bundle: test_bundle(), - request_count: AtomicUsize::new(0), - }); - let codex_home = tempdir().expect("tempdir"); - let service = CloudConfigBundleService::new( - auth_manager, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - assert_eq!(service.load_startup_bundle().await, Ok(Some(test_bundle()))); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 2); -} - -#[tokio::test] -async fn get_bundle_recovers_after_unauthorized_reload_updates_cache_identity() { - let auth_home = tempdir().expect("tempdir"); - write_auth_json( - auth_home.path(), - chatgpt_auth_json_with_last_refresh( - "business", - Some("user-12345"), - Some("account-12345"), - "stale-access-token", - "test-refresh-token", - "3025-01-01T00:00:00Z", - ), - ) - .expect("write initial auth"); - let auth_manager = Arc::new( - AuthManager::new( - auth_home.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::File, - /*forced_chatgpt_workspace_id*/ None, - /*chatgpt_base_url*/ None, - AuthKeyringBackendKind::default(), - codex_login::test_support::transport_default_auth_route_config(), - ) - .await, - ); - - write_auth_json( - auth_home.path(), - chatgpt_auth_json_with_last_refresh( - "business", - Some("user-99999"), - Some("account-12345"), - "fresh-access-token", - "test-refresh-token", - "3025-01-01T00:00:00Z", - ), - ) - .expect("write refreshed auth"); - let fetcher = Arc::new(TokenBundleClient { - expected_token: "fresh-access-token".to_string(), - bundle: test_bundle(), - request_count: AtomicUsize::new(0), - }); - let codex_home = tempdir().expect("tempdir"); - let service = CloudConfigBundleService::new( - auth_manager, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - assert_eq!(service.load_startup_bundle().await, Ok(Some(test_bundle()))); - let cache = create_test_cache(codex_home.path()); - assert_eq!( - cache - .load(Some("user-99999"), Some("account-12345")) - .await - .expect("load cache") - .bundle, - test_bundle() - ); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 2); -} - -#[tokio::test] -async fn get_bundle_surfaces_auth_recovery_message() { - let auth_home = tempdir().expect("tempdir"); - write_auth_json( - auth_home.path(), - chatgpt_auth_json( - "enterprise", - Some("user-12345"), - Some("account-12345"), - "stale-access-token", - "test-refresh-token", - ), - ) - .expect("write auth"); - let auth_manager = Arc::new( - AuthManager::new( - auth_home.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::File, - /*forced_chatgpt_workspace_id*/ None, - /*chatgpt_base_url*/ None, - AuthKeyringBackendKind::default(), - codex_login::test_support::transport_default_auth_route_config(), - ) - .await, - ); - - write_auth_json( - auth_home.path(), - chatgpt_auth_json( - "enterprise", - Some("user-12345"), - Some("account-99999"), - "fresh-access-token", - "test-refresh-token", - ), - ) - .expect("write mismatched auth"); - let fetcher = Arc::new(UnauthorizedBundleClient { - message: "GET /config/bundle failed: 401".to_string(), - request_count: AtomicUsize::new(0), - }); - let codex_home = tempdir().expect("tempdir"); - let service = CloudConfigBundleService::new( - auth_manager, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - let err = service - .load_startup_bundle() - .await - .expect_err("cloud config bundle should surface auth recovery errors"); - assert_eq!( - err, - CloudConfigBundleLoadError::new( - CloudConfigBundleLoadErrorCode::Auth, - Some(401), - "Your access token could not be refreshed because you have since logged out or signed in to another account. Please sign in again.", - ) - ); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); -} - -#[tokio::test] -async fn external_auth_recovers_once_per_bundle_fetch() { - let auth_home = tempdir().expect("tempdir"); - let auth_manager = Arc::new( - AuthManager::new( - auth_home.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::Ephemeral, - /*forced_chatgpt_workspace_id*/ None, - /*chatgpt_base_url*/ None, - AuthKeyringBackendKind::default(), - codex_login::test_support::transport_default_auth_route_config(), - ) - .await, - ); - let initial_auth = CodexAuth::from_external_chatgpt_tokens( - &fake_chatgpt_jwt("enterprise", Some("user-12345"), b"initial"), - "account-12345", - Some("enterprise"), - ) - .expect("initial external auth"); - let refreshed_token = fake_chatgpt_jwt("enterprise", Some("user-12345"), b"refreshed"); - let refreshed_auth = CodexAuth::from_external_chatgpt_tokens( - &refreshed_token, - "account-12345", - Some("enterprise"), - ) - .expect("refreshed external auth"); - let external_auth = Arc::new(TestExternalChatgptAuth { - current: RwLock::new(initial_auth), - refreshed: refreshed_auth, - refresh_count: AtomicUsize::new(0), - }); - auth_manager - .set_external_auth(external_auth.clone()) - .await - .expect("set external auth"); - - let fetcher = Arc::new(TokenBundleClient { - expected_token: refreshed_token, - bundle: test_bundle(), - request_count: AtomicUsize::new(0), - }); - let codex_home = tempdir().expect("tempdir"); - let service = CloudConfigBundleService::new( - Arc::clone(&auth_manager), - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - assert_eq!(service.load_startup_bundle().await, Ok(Some(test_bundle()))); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 2); - assert_eq!(external_auth.refresh_count.load(Ordering::SeqCst), 1); - let retried_fetcher = Arc::new(SequenceBundleClient::new(vec![ - Err(BundleRequestError::Unauthorized { - status_code: Some(401), - message: "rejected".into(), - }), - Err(request_error()), - Err(BundleRequestError::Unauthorized { - status_code: Some(401), - message: "still rejected".into(), - }), - Ok(test_bundle()), - ])); - let retrying = CloudConfigBundleService::new( - Arc::clone(&auth_manager), - retried_fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ) - .without_cache(); - assert_eq!( - retrying.get_latest().await.unwrap_err().code(), - CloudConfigBundleLoadErrorCode::Auth - ); - assert_eq!(retried_fetcher.request_count.load(Ordering::SeqCst), 3); - assert_eq!(external_auth.refresh_count.load(Ordering::SeqCst), 2); -} - -#[tokio::test] -async fn get_bundle_does_not_use_cache_when_auth_identity_is_incomplete() { - let codex_home = tempdir().expect("tempdir"); - let prime_service = CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - Arc::new(StaticBundleClient::new(test_bundle())), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - let _ = prime_service.load_startup_bundle().await; - - let replacement_bundle = CloudConfigBundle { - config_toml: CloudConfigTomlBundle::default(), - requirements_toml: CloudRequirementsTomlBundle { - enterprise_managed: vec![CloudRequirementsFragment { - id: "req_2".to_string(), - name: "Replacement requirements".to_string(), - contents: "allowed_approval_policies = [\"on-request\"]".to_string(), - }], - }, - }; - let fetcher = Arc::new(SequenceBundleClient::new(vec![Ok( - replacement_bundle.clone() - )])); - let service = CloudConfigBundleService::new( - auth_manager_with_plan_and_identity( - "business", - /*chatgpt_user_id*/ None, - Some("account-12345"), - ) - .await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - assert_eq!( - service.load_startup_bundle().await, - Ok(Some(replacement_bundle)) - ); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); -} - -#[tokio::test(start_paused = true)] -async fn get_bundle_stops_after_max_retries() { - let fetcher = Arc::new(SequenceBundleClient::new(vec![ - Err(request_error()); - CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS - ])); - let codex_home = tempdir().expect("tempdir"); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("enterprise").await, - fetcher.clone(), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - let handle = tokio::spawn(async move { service.load_startup_bundle().await }); - tokio::task::yield_now().await; - tokio::time::advance(Duration::from_secs(5)).await; - tokio::task::yield_now().await; - - let err = handle - .await - .expect("cloud config bundle task") - .expect_err("cloud config bundle retry exhaustion should fail closed"); - assert_eq!(err.to_string(), CLOUD_CONFIG_BUNDLE_LOAD_FAILED_MESSAGE); - assert_eq!(err.code(), CloudConfigBundleLoadErrorCode::RequestFailed); - assert_eq!( - fetcher.request_count.load(Ordering::SeqCst), - CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS - ); -} - -#[tokio::test] -async fn refresh_from_remote_updates_cached_bundle() { - let replacement_bundle = CloudConfigBundle { - config_toml: CloudConfigTomlBundle::default(), - requirements_toml: CloudRequirementsTomlBundle { - enterprise_managed: vec![CloudRequirementsFragment { - id: "req_2".to_string(), - name: "Replacement requirements".to_string(), - contents: "allowed_approval_policies = [\"on-request\"]".to_string(), - }], - }, - }; - let codex_home = tempdir().expect("tempdir"); - let fetcher = Arc::new(SequenceBundleClient::new(vec![ - Ok(test_bundle()), - Ok(replacement_bundle.clone()), - ])); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - fetcher, - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - - assert_eq!(service.get_latest().await, Ok(Some(test_bundle()))); - assert!(service.refresh_cache_once().await); - assert_eq!( - service.get_latest().await, - Ok(Some(replacement_bundle.clone())) - ); - - let cache = create_test_cache(codex_home.path()); - let signed_payload = cache - .load(Some("user-12345"), Some("account-12345")) - .await - .expect("load cache"); - assert_eq!(signed_payload.bundle, replacement_bundle); -} - -#[tokio::test(start_paused = true)] -async fn production_loader_recovers_startup_timeouts_in_background() { - let codex_home = tempdir().expect("tempdir"); - let fetcher = Arc::new(SequenceBundleClient { - timeout_attempts: 2, - ..SequenceBundleClient::new(vec![Ok(test_bundle())]) - }); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - Arc::clone(&fetcher), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - let (loader, _) = crate::bundle_loader::managed_config_bundle_loader_for_service(service); - let (initial, ()) = tokio::join!(loader.get(), async { - fetcher.request_started.notified().await; - tokio::time::advance(CLOUD_CONFIG_BUNDLE_TIMEOUT + Duration::from_millis(1)).await; - }); - assert_eq!( - initial - .as_ref() - .expect_err("startup should time out") - .code(), - CloudConfigBundleLoadErrorCode::Timeout - ); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); - - for attempt in 2..=3 { - tokio::time::timeout( - CLOUD_CONFIG_BUNDLE_TIMEOUT_RETRY_INTERVAL + Duration::from_millis(1), - fetcher.request_started.notified(), - ) - .await - .expect("the worker should retry before the normal refresh interval"); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), attempt); - if attempt == 2 { - // Readers keep returning the snapshot while the worker's retry is pending. - let (first, second) = tokio::join!(loader.get(), loader.get()); - assert_eq!((first, second), (initial.clone(), initial.clone())); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 2); - tokio::time::advance(CLOUD_CONFIG_BUNDLE_TIMEOUT + Duration::from_millis(1)).await; - } - } - - let recovery_deadline = std::time::Instant::now() + Duration::from_secs(5); - while loader.get().await != Ok(Some(test_bundle())) { - assert!( - std::time::Instant::now() < recovery_deadline, - "the worker should publish the recovered bundle" - ); - tokio::task::yield_now().await; - } - let config = ConfigBuilder::default() - .loader_overrides(codex_config::LoaderOverrides::without_managed_config_for_tests()) - .codex_home(codex_home.path().to_path_buf()) - .cloud_config_bundle(loader.clone()) - .build() - .await - .expect("later configuration loads should apply the recovered bundle"); - assert_eq!(config.model.as_deref(), Some("gpt-5")); - assert_eq!( - config.permissions.approval_policy.value(), - codex_protocol::protocol::AskForApproval::Never - ); - - tokio::time::timeout( - CLOUD_CONFIG_BUNDLE_TIMEOUT_RETRY_INTERVAL + Duration::from_millis(1), - fetcher.request_started.notified(), - ) - .await - .expect_err("successful recovery should restore the normal refresh interval"); - tokio::time::timeout( - CLOUD_CONFIG_BUNDLE_CACHE_REFRESH_INTERVAL, - fetcher.request_started.notified(), - ) - .await - .expect("normal background refresh should continue after recovery"); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 4); -} - -#[tokio::test(start_paused = true)] -async fn production_loader_restores_normal_refresh_interval_after_non_timeout_error() { - let codex_home = tempdir().expect("tempdir"); - let fetcher = Arc::new(SequenceBundleClient { - timeout_attempts: 1, - ..SequenceBundleClient::new(vec![Ok(invalid_config_bundle()), Ok(test_bundle())]) - }); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - Arc::clone(&fetcher), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - let (loader, _) = crate::bundle_loader::managed_config_bundle_loader_for_service(service); - let (initial, ()) = tokio::join!(loader.get(), async { - fetcher.request_started.notified().await; - tokio::time::advance(CLOUD_CONFIG_BUNDLE_TIMEOUT + Duration::from_millis(1)).await; - }); - assert_eq!( - initial.expect_err("startup should time out").code(), - CloudConfigBundleLoadErrorCode::Timeout - ); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); - - tokio::time::timeout( - CLOUD_CONFIG_BUNDLE_TIMEOUT_RETRY_INTERVAL + Duration::from_millis(1), - fetcher.request_started.notified(), - ) - .await - .expect("the worker should retry the startup timeout promptly"); - let refresh_deadline = std::time::Instant::now() + Duration::from_secs(5); - loop { - let error = loader - .get() - .await - .expect_err("the invalid bundle should fail closed"); - if error.code() == CloudConfigBundleLoadErrorCode::InvalidBundle { - break; - } - assert!( - std::time::Instant::now() < refresh_deadline, - "the retry should replace the cached timeout with the validation error" - ); - tokio::task::yield_now().await; - } - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 2); - - tokio::time::timeout( - CLOUD_CONFIG_BUNDLE_CACHE_REFRESH_INTERVAL - Duration::from_secs(1), - fetcher.request_started.notified(), - ) - .await - .expect_err("the non-timeout error should stop fast retries"); - tokio::time::timeout( - Duration::from_secs(1) + Duration::from_millis(1), - fetcher.request_started.notified(), - ) - .await - .expect("refresh should resume at the normal interval"); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 3); -} - -#[tokio::test(start_paused = true)] -async fn production_loader_refreshes_later_configs_and_preserves_failed_refreshes() { - let codex_home = tempdir().expect("tempdir"); - let initial_bundle = test_bundle(); - let refreshed_bundle = CloudConfigBundle { - config_toml: CloudConfigTomlBundle { - enterprise_managed: vec![CloudConfigFragment { - id: "cfg_refreshed".to_string(), - name: "Refreshed config".to_string(), - contents: "model = \"gpt-5-refreshed\"".to_string(), - }], - }, - requirements_toml: initial_bundle.requirements_toml.clone(), - }; - let mut responses = vec![Ok(initial_bundle.clone()), Ok(refreshed_bundle.clone())]; - responses.extend(vec![Err(request_error()); CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS]); - let fetcher = Arc::new(SequenceBundleClient::new(responses)); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - Arc::clone(&fetcher), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - let (loader, _) = crate::bundle_loader::managed_config_bundle_loader_for_service(service); - - let (first, second) = tokio::join!(loader.get(), loader.get()); - assert_eq!(first, Ok(Some(initial_bundle.clone()))); - assert_eq!(second, Ok(Some(initial_bundle))); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 1); - tokio::task::yield_now().await; - tokio::time::advance(CLOUD_CONFIG_BUNDLE_CACHE_REFRESH_INTERVAL + Duration::from_millis(1)) - .await; - let refresh_deadline = std::time::Instant::now() + Duration::from_secs(5); - while loader.get().await != Ok(Some(refreshed_bundle.clone())) { - assert!( - std::time::Instant::now() < refresh_deadline, - "the production refresh task should update the latest bundle" - ); - tokio::task::yield_now().await; - } - let refreshed_config = ConfigBuilder::default() - .codex_home(codex_home.path().to_path_buf()) - .cloud_config_bundle(loader.clone()) - .build() - .await - .expect("later session config should load the refreshed bundle"); - assert_eq!(refreshed_config.model.as_deref(), Some("gpt-5-refreshed")); - - tokio::task::yield_now().await; - tokio::time::advance(CLOUD_CONFIG_BUNDLE_CACHE_REFRESH_INTERVAL + Duration::from_millis(1)) - .await; - let failed_refresh_deadline = std::time::Instant::now() + Duration::from_secs(5); - for expected_request_count in 3..=2 + CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS { - if expected_request_count > 3 { - tokio::task::yield_now().await; - tokio::time::advance(Duration::from_secs(2)).await; - } - while fetcher.request_count.load(Ordering::SeqCst) < expected_request_count { - assert!( - std::time::Instant::now() < failed_refresh_deadline, - "the production refresh task should retry the failed bundle request" - ); - tokio::task::yield_now().await; - } - } - - assert_eq!(loader.get().await, Ok(Some(refreshed_bundle))); -} - -#[tokio::test(start_paused = true)] -async fn each_loader_owns_refresh_until_its_last_clone_is_dropped() { - let codex_home = tempdir().expect("tempdir"); - let fetcher = Arc::new(SequenceBundleClient::new(vec![Ok(test_bundle()); 3])); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - Arc::clone(&fetcher), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - let (loader, original_task) = - crate::bundle_loader::managed_config_bundle_loader_for_service(service); - let cloned_loader = loader.clone(); - assert_eq!(loader.get().await, Ok(Some(test_bundle()))); - fetcher.request_started.notified().await; - - drop(loader); - tokio::time::timeout( - CLOUD_CONFIG_BUNDLE_CACHE_REFRESH_INTERVAL + Duration::from_millis(1), - fetcher.request_started.notified(), - ) - .await - .expect("the refresh should remain active while another loader clone exists"); - - let replacement_fetcher = Arc::new(SequenceBundleClient::new(vec![Ok(test_bundle()); 2])); - let replacement_service = CloudConfigBundleService::new( - auth_manager_with_plan_and_identity( - "business", - Some("user-replacement"), - Some("account-replacement"), - ) - .await, - Arc::clone(&replacement_fetcher), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - let (replacement_loader, replacement_task) = - crate::bundle_loader::managed_config_bundle_loader_for_service(replacement_service); - assert_eq!(replacement_loader.get().await, Ok(Some(test_bundle()))); - replacement_fetcher.request_started.notified().await; - - tokio::time::timeout( - CLOUD_CONFIG_BUNDLE_CACHE_REFRESH_INTERVAL + Duration::from_millis(1), - async { - tokio::join!( - fetcher.request_started.notified(), - replacement_fetcher.request_started.notified(), - ); - }, - ) - .await - .expect("both loader owners should keep refreshing"); - assert_eq!(fetcher.request_count.load(Ordering::SeqCst), 3); - - // Aborting is asynchronous; joining waits for cancellation to finish. - drop(cloned_loader); - assert!(original_task.await.unwrap_err().is_cancelled()); - assert!(!replacement_task.is_finished()); - - drop(replacement_loader); - assert!(replacement_task.await.unwrap_err().is_cancelled()); - tokio::time::advance(CLOUD_CONFIG_BUNDLE_CACHE_REFRESH_INTERVAL + Duration::from_secs(1)).await; - tokio::task::yield_now().await; - assert_eq!(replacement_fetcher.request_count.load(Ordering::SeqCst), 2); -} - -#[tokio::test(start_paused = true)] -async fn dropping_loader_cancels_in_flight_startup_and_refresh() { - for starts_from_cache in [false, true] { - let codex_home = tempdir().expect("tempdir"); - if starts_from_cache { - write_test_cache(&create_test_cache(codex_home.path()), test_bundle()).await; - } - let request_started = Arc::new(tokio::sync::Notify::new()); - let request_cancelled = Arc::new(tokio::sync::Notify::new()); - let service = CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - Arc::new(NotifyingPendingBundleClient { - request_started: Arc::clone(&request_started), - request_cancelled: Arc::clone(&request_cancelled), - }), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - ); - let (loader, _) = crate::bundle_loader::managed_config_bundle_loader_for_service(service); - if starts_from_cache { - assert_eq!(loader.get().await, Ok(Some(test_bundle()))); - tokio::task::yield_now().await; - tokio::time::advance(CLOUD_CONFIG_BUNDLE_CACHE_REFRESH_INTERVAL).await; - } - request_started.notified().await; - - drop(loader); - - tokio::time::timeout(Duration::from_secs(1), request_cancelled.notified()) - .await - .expect("loader drop should cancel the in-flight fetch"); - } -} - -#[tokio::test(start_paused = true)] -async fn refresh_can_clear_preserve_and_restore_the_latest_bundle() { - let codex_home = tempdir().expect("tempdir"); - let mut invalid = test_bundle(); - invalid.requirements_toml.enterprise_managed[0].contents = "invalid = [".to_string(); - let mut responses = vec![ - Ok(test_bundle()), - Ok(invalid), - Ok(test_bundle()), - Ok(CloudConfigBundle::default()), - ]; - responses.extend(vec![Err(request_error()); CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS]); - responses.push(Ok(test_bundle())); - let service = Arc::new(CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - Arc::new(SequenceBundleClient::new(responses)), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - )); - - assert_eq!(service.get_latest().await, Ok(Some(test_bundle()))); - let initial = service - .get_latest_snapshot() - .await - .binding - .expect("initial binding"); - assert!(service.refresh_cache_once().await); - assert_eq!(service.get_latest().await, Ok(Some(test_bundle()))); - assert_eq!( - initial.read().status, - CloudConfigBundleBindingStatus::Suspended - ); - - assert!(service.refresh_cache_once().await); - assert_eq!(service.get_latest().await, Ok(Some(test_bundle()))); - let recovered = service - .get_latest_snapshot() - .await - .binding - .expect("recovered binding"); - assert_eq!(initial.read().status, CloudConfigBundleBindingStatus::Stale); - assert_eq!( - recovered.read().status, - CloudConfigBundleBindingStatus::Current - ); - - assert!(service.refresh_cache_once().await); - assert_eq!(service.get_latest().await, Ok(None)); - let cleared = service - .get_latest_snapshot() - .await - .binding - .expect("cleared binding"); - assert_eq!( - recovered.read().status, - CloudConfigBundleBindingStatus::Stale - ); - - let refresh_service = Arc::clone(&service); - let refresh = tokio::spawn(async move { refresh_service.refresh_cache_once().await }); - tokio::task::yield_now().await; - tokio::time::advance(Duration::from_secs(5)).await; - tokio::task::yield_now().await; - assert!(refresh.await.expect("failed refresh task")); - assert_eq!(service.get_latest().await, Ok(None)); - assert_eq!( - cleared.read().status, - CloudConfigBundleBindingStatus::Current - ); - - assert!(service.refresh_cache_once().await); - assert_eq!(service.get_latest().await, Ok(Some(test_bundle()))); -} - -#[tokio::test(start_paused = true)] -async fn refresh_replaces_initial_errors_and_recovers_with_success() { - let codex_home = tempdir().expect("tempdir"); - let initial_error = BundleRequestError::Retryable(RetryableFailureKind::Request { - status_code: Some(500), - }); - let refresh_error = BundleRequestError::Retryable(RetryableFailureKind::Request { - status_code: Some(503), - }); - let mut responses = vec![Err(initial_error); CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS]; - responses.extend(vec![Err(refresh_error); CLOUD_CONFIG_BUNDLE_MAX_ATTEMPTS]); - responses.push(Ok(test_bundle())); - let service = Arc::new(CloudConfigBundleService::new( - auth_manager_with_plan("business").await, - Arc::new(SequenceBundleClient::new(responses)), - codex_home.path().to_path_buf(), - CLOUD_CONFIG_BUNDLE_TIMEOUT, - )); - - let initial_service = Arc::clone(&service); - let initial = tokio::spawn(async move { initial_service.get_latest().await }); - tokio::task::yield_now().await; - tokio::time::advance(Duration::from_secs(5)).await; - tokio::task::yield_now().await; - let initial_error = initial - .await - .expect("initial task") - .expect_err("initial fetch should fail"); - assert_eq!(initial_error.status_code(), Some(500)); - - let refresh_service = Arc::clone(&service); - let refresh = tokio::spawn(async move { refresh_service.refresh_cache_once().await }); - tokio::task::yield_now().await; - tokio::time::advance(Duration::from_secs(5)).await; - tokio::task::yield_now().await; - assert!(refresh.await.expect("failed refresh task")); - let latest_error = service - .get_latest() - .await - .expect_err("latest failed refresh should replace the initial error"); - assert_eq!(latest_error.status_code(), Some(503)); - - assert!(service.refresh_cache_once().await); - assert_eq!(service.get_latest().await, Ok(Some(test_bundle()))); -} - -#[test] -fn bundle_response_conversion_preserves_fragment_order() { - let response = ConfigBundleResponse { - config_toml: Some(Some(Box::new(codex_backend_client::DeliveredConfigToml { - enterprise_managed: Some(Some(vec![ - DeliveredTomlFragment::new( - "cfg_high".to_string(), - "High config".to_string(), - "model = \"high\"".to_string(), - ), - DeliveredTomlFragment::new( - "cfg_low".to_string(), - "Low config".to_string(), - "model = \"low\"".to_string(), - ), - ])), - managed_layers: None, - }))), - requirements_toml: Some(Some(Box::new( - codex_backend_client::DeliveredRequirementsToml { - enterprise_managed: Some(Some(vec![DeliveredTomlFragment::new( - "req_high".to_string(), - "High requirements".to_string(), - "allowed_approval_policies = [\"never\"]".to_string(), - )])), - managed_layers: None, - }, - ))), - }; - - assert_eq!( - bundle_from_response(response), - CloudConfigBundle { - config_toml: CloudConfigTomlBundle { - enterprise_managed: vec![ - CloudConfigFragment { - id: "cfg_high".to_string(), - name: "High config".to_string(), - contents: "model = \"high\"".to_string(), - }, - CloudConfigFragment { - id: "cfg_low".to_string(), - name: "Low config".to_string(), - contents: "model = \"low\"".to_string(), - }, - ], - }, - requirements_toml: CloudRequirementsTomlBundle { - enterprise_managed: vec![CloudRequirementsFragment { - id: "req_high".to_string(), - name: "High requirements".to_string(), - contents: "allowed_approval_policies = [\"never\"]".to_string(), - }], - }, - } - ); -} - -#[test] -fn bundle_response_conversion_treats_missing_sections_as_empty() { - assert_eq!( - bundle_from_response(ConfigBundleResponse::new()), - CloudConfigBundle::default() - ); -} diff --git a/codex-rs/cloud-config/src/validation.rs b/codex-rs/cloud-config/src/validation.rs deleted file mode 100644 index 4718658a..00000000 --- a/codex-rs/cloud-config/src/validation.rs +++ /dev/null @@ -1,48 +0,0 @@ -use codex_config::AbsolutePathBuf; -use codex_config::CloudConfigBundle; -use codex_config::CloudConfigBundleLayers; -use codex_config::CloudConfigBundleLoadError; -use codex_config::CloudConfigBundleLoadErrorCode; -use codex_config::compose_requirements; -use codex_config::config_toml::validate_model_providers; - -pub(crate) fn validate_bundle( - bundle: &CloudConfigBundle, - base_dir: &AbsolutePathBuf, -) -> Result<(), CloudConfigBundleLoadError> { - let bundle_layers = - CloudConfigBundleLayers::from_bundle(bundle.clone(), base_dir).map_err(|_| { - CloudConfigBundleLoadError::new( - CloudConfigBundleLoadErrorCode::InvalidBundle, - /*status_code*/ None, - "invalid cloud config bundle: invalid TOML", - ) - })?; - let CloudConfigBundleLayers { - enterprise_managed_config: _, - enterprise_managed_requirements, - } = bundle_layers; - - let requirements = compose_requirements(enterprise_managed_requirements).map_err(|_| { - CloudConfigBundleLoadError::new( - CloudConfigBundleLoadErrorCode::InvalidBundle, - /*status_code*/ None, - "invalid cloud config bundle: invalid requirements", - ) - })?; - if let Some(providers) = requirements.and_then(|requirements| requirements.model_providers) { - validate_model_providers(&providers).map_err(|_| { - CloudConfigBundleLoadError::new( - CloudConfigBundleLoadErrorCode::InvalidBundle, - /*status_code*/ None, - "invalid cloud config bundle: invalid model provider configuration", - ) - })?; - } - - Ok(()) -} - -#[cfg(test)] -#[path = "validation_tests.rs"] -mod tests; diff --git a/codex-rs/cloud-config/src/validation_tests.rs b/codex-rs/cloud-config/src/validation_tests.rs deleted file mode 100644 index ad5503f9..00000000 --- a/codex-rs/cloud-config/src/validation_tests.rs +++ /dev/null @@ -1,78 +0,0 @@ -use super::*; -use codex_config::CloudRequirementsFragment; -use pretty_assertions::assert_eq; -use tempfile::tempdir; - -#[test] -fn cloud_validation_rejects_mixed_network_requirements() { - let home = tempdir().expect("tempdir"); - let base_dir = AbsolutePathBuf::from_absolute_path(home.path()).expect("absolute path"); - let mut bundle = CloudConfigBundle::default(); - for alias in ["experimental_network", "network_proxy"] { - let nested = "[permissions.network]\nenabled = false"; - let top_level = format!("[{alias}]\nenabled = false"); - for contents in [ - vec![format!("{nested}\n{top_level}")], - vec![nested.to_owned(), top_level], - ] { - bundle.requirements_toml.enterprise_managed = contents - .into_iter() - .enumerate() - .map(|(index, contents)| CloudRequirementsFragment { - id: index.to_string(), - name: index.to_string(), - contents, - }) - .collect(); - let err = validate_bundle(&bundle, &base_dir).expect_err("mixed policy spellings"); - assert_eq!(err.code(), CloudConfigBundleLoadErrorCode::InvalidBundle); - } - } -} - -#[test] -fn cloud_fragments_combine_before_provider_validation() { - let home = tempdir().expect("tempdir"); - let base_dir = AbsolutePathBuf::from_absolute_path(home.path()).expect("absolute path"); - let mut bundle = CloudConfigBundle::default(); - // Cloud fragments arrive highest-priority first. - bundle.requirements_toml.enterprise_managed = vec![ - CloudRequirementsFragment { - id: "high".to_string(), - name: "URL".to_string(), - contents: "[model_providers.gateway]\nbase_url = 'https://gateway.example/v1'\n[model_providers.gateway.auth]\ntimeout_ms = 10000\ncwd = 'auth'" - .to_string(), - }, - CloudRequirementsFragment { - id: "low".to_string(), - name: "Name".to_string(), - contents: "[model_providers.gateway]\nname = 'Gateway'\n[model_providers.gateway.auth]\ncommand = 'get-token'".to_string(), - }, - ]; - assert_eq!(validate_bundle(&bundle, &base_dir), Ok(())); -} - -#[test] -fn cloud_bedrock_overrides_accept_supported_fields() { - let home = tempdir().expect("tempdir"); - let base_dir = AbsolutePathBuf::from_absolute_path(home.path()).expect("absolute path"); - for provider in ["amazon-bedrock", "amazon-bedrock-runtime"] { - let mut bundle = CloudConfigBundle::default(); - bundle.requirements_toml.enterprise_managed = vec![CloudRequirementsFragment { - id: "bedrock".to_string(), - name: "Bedrock".to_string(), - contents: format!( - r#" -[model_providers.{provider}] -base_url = "https://bedrock.example" -[model_providers.{provider}.http_headers] -X-Managed = "required" -[model_providers.{provider}.aws] -profile = "managed" -region = "us-east-1" -"# - ), - }]; - assert_eq!(validate_bundle(&bundle, &base_dir), Ok(())); - } -} diff --git a/codex-rs/codex-api/src/files.rs b/codex-rs/codex-api/src/files.rs deleted file mode 100644 index af25c211..00000000 --- a/codex-rs/codex-api/src/files.rs +++ /dev/null @@ -1,937 +0,0 @@ -use std::collections::HashMap; -use std::future::Future; -use std::time::Duration; - -use crate::AuthProvider; -use bytes::Bytes; -use codex_http_client::HttpResponse; -use codex_http_client::RequestBuilder; -use codex_http_client::RouteAwareClientPool; -use codex_http_client::RouteAwareRequestError; -use futures::Stream; -use http::HeaderMap; -use http::Method; -use http::StatusCode; -use http::header::CONTENT_LENGTH; -use serde::Deserialize; -use tokio::time::Instant; -use uuid::Uuid; - -pub const OPENAI_FILE_URI_PREFIX: &str = "sediment://"; -pub const OPENAI_FILE_UPLOAD_LIMIT_BYTES: u64 = 512 * 1024 * 1024; - -const OPENAI_FILE_REQUEST_TIMEOUT: Duration = Duration::from_secs(60); -const OPENAI_FILE_BLOB_UPLOAD_TIMEOUT: Duration = Duration::from_secs(5 * 60); -const MAX_BLOB_UPLOAD_ATTEMPTS: u64 = 5; -const OPENAI_FILE_FINALIZE_TIMEOUT: Duration = Duration::from_secs(30); -const OPENAI_FILE_FINALIZE_RETRY_DELAY: Duration = Duration::from_millis(250); -const OPENAI_FILE_USE_CASE: &str = "codex"; - -#[derive(Debug)] -pub struct HostedFileUploadContext { - pub thread_id: Option, - pub connector_id: String, - pub action_name: String, - pub model: String, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct UploadedOpenAiFile { - pub file_id: String, - pub uri: String, - pub download_url: String, - pub file_name: String, - pub file_size_bytes: u64, - pub mime_type: Option, -} - -#[derive(Debug, thiserror::Error)] -pub enum OpenAiFileError { - #[error("failed to open OpenAI file upload contents: {0}")] - ReadContents(#[source] std::io::Error), - #[error(transparent)] - Auth(#[from] crate::AuthError), - #[error( - "file `{file_name}` is too large: {size_bytes} bytes exceeds the limit of {limit_bytes} bytes" - )] - FileTooLarge { - file_name: String, - size_bytes: u64, - limit_bytes: u64, - }, - #[error("failed to send OpenAI file request to {url}: {source}")] - Request { - url: String, - #[source] - source: RouteAwareRequestError, - }, - #[error( - "OpenAI file blob upload to {host} failed after {elapsed_ms} ms ({error_kind}, azure_client_request_id={azure_client_request_id}): {source}" - )] - BlobUploadRequest { - host: String, - elapsed_ms: u128, - error_kind: &'static str, - azure_client_request_id: String, - #[source] - source: RouteAwareRequestError, - }, - #[error( - "OpenAI file blob upload to {host} failed with status {status} (azure_client_request_id={azure_client_request_id}, azure_request_id={azure_request_id}, azure_error_code={azure_error_code})" - )] - BlobUploadStatus { - host: String, - status: StatusCode, - azure_client_request_id: String, - azure_request_id: String, - azure_error_code: String, - }, - #[error("OpenAI file request to {url} failed with status {status}: {body}")] - UnexpectedStatus { - url: String, - status: StatusCode, - body: String, - }, - #[error("failed to parse OpenAI file response from {url}: {source}")] - Decode { - url: String, - #[source] - source: serde_json::Error, - }, - #[error("OpenAI file upload for `{file_id}` is not ready yet")] - UploadNotReady { file_id: String }, - #[error("OpenAI file upload for `{file_id}` failed: {message}")] - UploadFailed { file_id: String, message: String }, -} - -#[derive(Deserialize)] -struct CreateFileResponse { - file_id: String, - upload_url: String, - upload_headers: Option>, - #[serde(default)] - pdf_c2pa_reservation: bool, -} - -#[derive(Deserialize)] -#[serde(rename_all = "snake_case")] -struct DownloadLinkResponse { - status: String, - download_url: Option, - file_name: Option, - mime_type: Option, - error_message: Option, - #[serde(default)] - file_size_bytes: Option, -} - -pub fn openai_file_uri(file_id: &str) -> String { - format!("{OPENAI_FILE_URI_PREFIX}{file_id}") -} - -/// Creates and finalizes one file record, reopening the same contents for blob PUT retries. -pub async fn upload_openai_file( - base_url: &str, - auth: &dyn AuthProvider, - client_pool: &RouteAwareClientPool, - file_name: String, - file_size_bytes: u64, - mut open_contents: Open, - hosted_upload: Option<&HostedFileUploadContext>, -) -> Result -where - Open: FnMut() -> OpenFuture, - OpenFuture: Future>, - Contents: Stream> + Send + 'static, -{ - if file_size_bytes > OPENAI_FILE_UPLOAD_LIMIT_BYTES { - return Err(OpenAiFileError::FileTooLarge { - file_name, - size_bytes: file_size_bytes, - limit_bytes: OPENAI_FILE_UPLOAD_LIMIT_BYTES, - }); - } - - let create_url = format!("{}/files", base_url.trim_end_matches('/')); - let create_request = serde_json::json!({ - "file_name": file_name.as_str(), - "file_size": file_size_bytes, - "use_case": OPENAI_FILE_USE_CASE, - }); - let request = authorized_request(client_pool, auth, Method::POST, &create_url).await?; - let mut create_request = match hosted_upload { - Some(context) => serde_json::json!({ - "file_name": file_name.as_str(), - "file_size": file_size_bytes, - "use_case": OPENAI_FILE_USE_CASE, - "codex_connector_id": context.connector_id, - "codex_action_name": context.action_name, - "codex_model": context.model, - }), - None => create_request, - }; - if let Some(thread_id) = hosted_upload.and_then(|context| context.thread_id.as_ref()) { - create_request["codex_thread_id"] = serde_json::Value::String(thread_id.clone()); - } - let create_response = request - .json(&create_request) - .send() - .await - .map_err(|source| OpenAiFileError::Request { - url: create_url.clone(), - source, - })?; - let create_status = create_response.status(); - let create_body = create_response - .text() - .await - .map_err(|source| OpenAiFileError::Request { - url: create_url.clone(), - source, - })?; - if !create_status.is_success() { - return Err(OpenAiFileError::UnexpectedStatus { - url: create_url, - status: create_status, - body: create_body, - }); - } - let create_payload: CreateFileResponse = - serde_json::from_str(&create_body).map_err(|source| OpenAiFileError::Decode { - url: create_url.clone(), - source, - })?; - - let upload_host = url::Url::parse(&create_payload.upload_url) - .ok() - .and_then(|url| url.host_str().map(str::to_owned)) - .unwrap_or_else(|| "unknown-host".to_string()); - let upload_started_at = Instant::now(); - let deadline = upload_started_at + OPENAI_FILE_BLOB_UPLOAD_TIMEOUT; - let mut retry_delay = Duration::ZERO; - for attempt in 1..=MAX_BLOB_UPLOAD_ATTEMPTS { - let azure_client_request_id = Uuid::new_v4().to_string(); - let request_error = |source: RouteAwareRequestError| { - let error_kind = if source.is_timeout() { - "timeout" - } else if source.is_connect() { - "connect" - } else if source.is_body() { - "body" - } else if source.is_request() { - "request" - } else { - "other" - }; - OpenAiFileError::BlobUploadRequest { - host: upload_host.clone(), - elapsed_ms: upload_started_at.elapsed().as_millis(), - error_kind, - azure_client_request_id: azure_client_request_id.clone(), - source: source.without_url(), - } - }; - // Opening the stream, sending every attempt, and backoff share one deadline. - let result = tokio::time::timeout_at(deadline, async { - if Instant::now() >= deadline { - return Err(request_error(RouteAwareRequestError::Timeout)); - } - let contents = open_contents() - .await - .map_err(OpenAiFileError::ReadContents)?; - let remaining = deadline.saturating_duration_since(Instant::now()); - if remaining.is_zero() { - return Err(request_error(RouteAwareRequestError::Timeout)); - } - let mut request = client_pool - .put(&create_payload.upload_url) - .timeout(remaining) - .header("x-ms-blob-type", "BlockBlob") - .header("x-ms-client-request-id", &azure_client_request_id) - .header(CONTENT_LENGTH, file_size_bytes); - if let Some(headers) = &create_payload.upload_headers { - for (name, value) in headers { - request = request.header(name.as_str(), value.as_str()); - } - } - request - .body_stream(contents) - .send() - .await - .map_err(request_error) - }) - .await - .unwrap_or_else(|_| Err(request_error(RouteAwareRequestError::Timeout))); - - let mut status = None; - let mut cloudflare_ray_id = "missing".to_string(); - let mut azure_request_id = "missing".to_string(); - let mut azure_error_code = "missing".to_string(); - let mut server_delay = None; - let (error, retryable, error_kind) = match result { - Ok(response) => { - let upload_status = response.status(); - status = Some(upload_status.to_string()); - cloudflare_ray_id = upload_response_header(&response, "cf-ray"); - azure_request_id = upload_response_header(&response, "x-ms-request-id"); - azure_error_code = upload_response_header(&response, "x-ms-error-code"); - if upload_status.is_success() { - if attempt > 1 { - tracing::event!( - target: "codex_otel.log_only", - tracing::Level::INFO, - event.name = "codex.openai_file_blob_upload_recovered", - file_id = %create_payload.file_id, - host = %upload_host, - file_size_bytes, - elapsed_ms = upload_started_at.elapsed().as_millis(), - attempt, - delay_ms = retry_delay.as_millis(), - status = status.as_deref(), - cloudflare_ray_id, - azure_client_request_id, - azure_request_id, - azure_error_code, - "OpenAI file blob upload recovered" - ); - } - break; - } - server_delay = blob_retry_after(response.headers()); - ( - OpenAiFileError::BlobUploadStatus { - host: upload_host.clone(), - status: upload_status, - azure_client_request_id: azure_client_request_id.clone(), - azure_request_id: azure_request_id.clone(), - azure_error_code: azure_error_code.clone(), - }, - matches!( - upload_status, - StatusCode::BAD_GATEWAY - | StatusCode::SERVICE_UNAVAILABLE - | StatusCode::GATEWAY_TIMEOUT - ), - "http_status", - ) - } - Err(error) => { - let (retryable, error_kind) = match &error { - OpenAiFileError::BlobUploadRequest { - source, error_kind, .. - } => ( - source.is_timeout() - || source.is_connect() - || source.is_body() - || source.is_request(), - *error_kind, - ), - _ => (false, "read"), - }; - (error, retryable, error_kind) - } - }; - retry_delay = server_delay - .unwrap_or_else(|| codex_client::backoff(Duration::from_millis(125), attempt)); - let will_retry = retryable - && attempt < MAX_BLOB_UPLOAD_ATTEMPTS - && retry_delay < deadline.saturating_duration_since(Instant::now()); - let event_name = if will_retry { - "codex.openai_file_blob_upload_retry" - } else { - "codex.openai_file_blob_upload_failed" - }; - tracing::event!( - target: "codex_otel.log_only", - tracing::Level::WARN, - event.name = event_name, - file_id = %create_payload.file_id, - host = %upload_host, - file_size_bytes, - elapsed_ms = upload_started_at.elapsed().as_millis(), - attempt, - delay_ms = if will_retry { retry_delay.as_millis() } else { 0 }, - status = status.as_deref(), - error_kind, - cloudflare_ray_id, - azure_client_request_id, - azure_request_id, - azure_error_code, - "OpenAI file blob upload attempt failed" - ); - if !will_retry { - return Err(error); - } - tokio::time::sleep(retry_delay).await; - } - - let finalize_url = format!( - "{}/files/{}/uploaded", - base_url.trim_end_matches('/'), - create_payload.file_id, - ); - let finalize_request = serde_json::json!({}); - let finalize_request = if create_payload.pdf_c2pa_reservation { - serde_json::json!({"pdf_c2pa_create_request": create_request}) - } else { - finalize_request - }; - let finalize_started_at = Instant::now(); - loop { - let finalize_response = authorized_request(client_pool, auth, Method::POST, &finalize_url) - .await? - .json(&finalize_request) - .send() - .await - .map_err(|source| OpenAiFileError::Request { - url: finalize_url.clone(), - source, - })?; - let finalize_status = finalize_response.status(); - let finalize_body = - finalize_response - .text() - .await - .map_err(|source| OpenAiFileError::Request { - url: finalize_url.clone(), - source, - })?; - if !finalize_status.is_success() { - return Err(OpenAiFileError::UnexpectedStatus { - url: finalize_url.clone(), - status: finalize_status, - body: finalize_body, - }); - } - let finalize_payload: DownloadLinkResponse = - serde_json::from_str(&finalize_body).map_err(|source| OpenAiFileError::Decode { - url: finalize_url.clone(), - source, - })?; - - match finalize_payload.status.as_str() { - "success" => { - let file_size_bytes = finalize_payload.file_size_bytes.unwrap_or(file_size_bytes); - return Ok(UploadedOpenAiFile { - file_id: create_payload.file_id.clone(), - uri: openai_file_uri(&create_payload.file_id), - download_url: finalize_payload.download_url.ok_or_else(|| { - OpenAiFileError::UploadFailed { - file_id: create_payload.file_id.clone(), - message: "missing download_url".to_string(), - } - })?, - file_name: finalize_payload.file_name.unwrap_or(file_name), - file_size_bytes, - mime_type: finalize_payload.mime_type, - }); - } - "retry" => { - if finalize_started_at.elapsed() >= OPENAI_FILE_FINALIZE_TIMEOUT { - return Err(OpenAiFileError::UploadNotReady { - file_id: create_payload.file_id, - }); - } - tokio::time::sleep(OPENAI_FILE_FINALIZE_RETRY_DELAY).await; - } - _ => { - return Err(OpenAiFileError::UploadFailed { - file_id: create_payload.file_id, - message: finalize_payload - .error_message - .unwrap_or_else(|| "upload finalization returned an error".to_string()), - }); - } - } - } -} - -async fn authorized_request( - client_pool: &RouteAwareClientPool, - auth: &dyn AuthProvider, - method: Method, - url: &str, -) -> Result { - let headers = auth.apply_auth_headers(HeaderMap::new()).await?; - - Ok(client_pool - .request(method, url) - .timeout(OPENAI_FILE_REQUEST_TIMEOUT) - .headers(headers)) -} - -fn upload_response_header(response: &HttpResponse, header: &str) -> String { - response - .headers() - .get(header) - .and_then(|value| value.to_str().ok()) - .unwrap_or("missing") - .to_string() -} - -fn blob_retry_after(headers: &http::HeaderMap) -> Option { - if let Some(delay) = headers - .get("x-ms-retry-after-ms") - .and_then(|value| value.to_str().ok()) - .and_then(|value| value.parse().ok()) - { - return Some(Duration::from_millis(delay)); - } - let value = headers.get(http::header::RETRY_AFTER)?.to_str().ok()?; - if let Ok(seconds) = value.parse() { - return Some(Duration::from_secs(seconds)); - } - let date = chrono::DateTime::parse_from_rfc2822(value).ok()?; - Some( - date.signed_duration_since(chrono::Utc::now()) - .to_std() - .unwrap_or_default(), - ) -} - -#[cfg(test)] -#[path = "files_retry_tests.rs"] -mod retry_tests; - -#[cfg(test)] -mod tests { - use super::*; - use codex_http_client::ClientRouteClass; - use codex_http_client::HttpClientFactory; - use codex_http_client::OutboundProxyPolicy; - use http::header::HeaderValue; - use pretty_assertions::assert_eq; - use std::sync::Arc; - use std::sync::atomic::AtomicUsize; - use std::sync::atomic::Ordering; - use wiremock::Mock; - use wiremock::MockServer; - use wiremock::Request; - use wiremock::ResponseTemplate; - use wiremock::matchers::body_json; - use wiremock::matchers::header; - use wiremock::matchers::header_regex; - use wiremock::matchers::method; - use wiremock::matchers::path; - - #[derive(Clone, Copy)] - pub(super) struct ChatGptTestAuth; - - pub(super) fn default_http_client_pool() -> RouteAwareClientPool { - RouteAwareClientPool::new_without_request_logging( - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - ClientRouteClass::Api, - ) - .with_legacy_custom_ca_fallback() - } - - impl AuthProvider for ChatGptTestAuth { - fn add_auth_headers(&self, headers: &mut http::HeaderMap) -> Result<(), crate::AuthError> { - headers.insert( - http::header::AUTHORIZATION, - HeaderValue::from_static("Bearer token"), - ); - headers.insert("ChatGPT-Account-ID", HeaderValue::from_static("account_id")); - Ok(()) - } - } - - pub(super) fn chatgpt_auth() -> ChatGptTestAuth { - ChatGptTestAuth - } - - pub(super) fn base_url_for(server: &MockServer) -> String { - format!("{}/backend-api", server.uri()) - } - - #[tokio::test] - async fn upload_openai_file_returns_canonical_uri() { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/backend-api/files")) - .and(header("chatgpt-account-id", "account_id")) - .and(|request: &Request| !request.headers.contains_key("x-amz-tagging")) - .and(body_json(serde_json::json!({ - "file_name": "hello.txt", - "file_size": 5, - "use_case": "codex", - }))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "file_id": "file_123", - "upload_url": format!("{}/upload/file_123", server.uri()), - "upload_headers": { - "Content-Type": "text/plain", - "Content-Disposition": "attachment; filename=hello.txt", - "x-amz-tagging": "purpose=codex", - }, - }))) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path("/upload/file_123")) - .and(header("content-length", "5")) - .and(header("content-type", "text/plain")) - .and(header( - "content-disposition", - "attachment; filename=hello.txt", - )) - .and(header("x-amz-tagging", "purpose=codex")) - .and(|request: &Request| { - !request.headers.contains_key("authorization") - && !request.headers.contains_key("chatgpt-account-id") - }) - .and(header_regex("x-ms-client-request-id", "^[0-9a-f-]{36}$")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - let finalize_attempts = Arc::new(AtomicUsize::new(0)); - let finalize_attempts_responder = Arc::clone(&finalize_attempts); - let download_url = format!("{}/download/file_123", server.uri()); - Mock::given(method("POST")) - .and(path("/backend-api/files/file_123/uploaded")) - .and(|request: &Request| !request.headers.contains_key("x-amz-tagging")) - .respond_with(move |_request: &Request| { - if finalize_attempts_responder.fetch_add(1, Ordering::SeqCst) == 0 { - return ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "status": "retry" - })); - } - - ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "status": "success", - "download_url": download_url, - "file_name": "hello.txt", - "mime_type": "text/plain", - "file_size_bytes": 5 - })) - }) - .mount(&server) - .await; - - let base_url = base_url_for(&server); - let open_contents = - || async { Ok(futures::stream::iter([Ok(Bytes::from_static(b"hello"))])) }; - let uploaded = upload_openai_file( - &base_url, - &chatgpt_auth(), - &default_http_client_pool(), - "hello.txt".to_string(), - /*file_size_bytes*/ 5, - open_contents, - /*hosted_upload*/ None, - ) - .await - .expect("upload succeeds"); - - assert_eq!(uploaded.file_id, "file_123"); - assert_eq!(uploaded.uri, "sediment://file_123"); - assert_eq!( - uploaded.download_url, - format!("{}/download/file_123", server.uri()) - ); - assert_eq!(uploaded.file_name, "hello.txt"); - assert_eq!(uploaded.mime_type, Some("text/plain".to_string())); - assert_eq!(finalize_attempts.load(Ordering::SeqCst), 2); - } - #[tokio::test] - async fn upload_hosted_app_context_and_finalizes_reservation() { - let server = MockServer::start().await; - let create_request = serde_json::json!({ - "file_name": "report.pdf", - "file_size": 8, - "use_case": "codex", - "codex_thread_id": "00000000-0000-0000-0000-000000000001", - "codex_connector_id": "library", - "codex_action_name": "create_library_file", - "codex_model": "gpt-work", - }); - Mock::given(method("POST")) - .and(path("/backend-api/files")) - .and(header("chatgpt-account-id", "account_id")) - .and(body_json(create_request.clone())) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "file_id": "file_pdf", - "upload_url": format!("{}/upload/file_pdf", server.uri()), - "upload_headers": null, - "pdf_c2pa_reservation": true, - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path("/upload/file_pdf")) - .and(header("content-length", "8")) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/backend-api/files/file_pdf/uploaded")) - .and(body_json(serde_json::json!({ - "pdf_c2pa_create_request": create_request, - }))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "status": "success", - "download_url": format!("{}/download/file_pdf", server.uri()), - "file_name": "report.pdf", - "mime_type": "application/pdf", - "file_size_bytes": 24, - }))) - .expect(1) - .mount(&server) - .await; - - let hosted_upload = HostedFileUploadContext { - thread_id: Some("00000000-0000-0000-0000-000000000001".to_string()), - connector_id: "library".to_string(), - action_name: "create_library_file".to_string(), - model: "gpt-work".to_string(), - }; - let uploaded = upload_openai_file( - &base_url_for(&server), - &chatgpt_auth(), - &default_http_client_pool(), - "report.pdf".to_string(), - /*file_size_bytes*/ 8, - || async { Ok(futures::stream::iter([Ok(Bytes::from_static(b"%PDF-1.4"))])) }, - Some(&hosted_upload), - ) - .await - .expect("hosted PDF upload succeeds"); - - assert_eq!(uploaded.file_id, "file_pdf"); - assert_eq!(uploaded.file_size_bytes, 24); - server.verify().await; - } - - #[tokio::test] - async fn upload_hosted_app_preserves_empty_finalization_for_older_servers() { - let server = MockServer::start().await; - let hosted_upload = HostedFileUploadContext { - thread_id: None, - connector_id: "library".to_string(), - action_name: "create_library_file".to_string(), - model: "gpt-work".to_string(), - }; - Mock::given(method("POST")) - .and(path("/backend-api/files")) - .and(body_json(serde_json::json!({ - "file_name": "report.pdf", - "file_size": 8, - "use_case": "codex", - "codex_connector_id": "library", - "codex_action_name": "create_library_file", - "codex_model": "gpt-work", - }))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "file_id": "file_pdf", - "upload_url": format!("{}/upload/file_pdf", server.uri()), - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path("/upload/file_pdf")) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/backend-api/files/file_pdf/uploaded")) - .and(body_json(serde_json::json!({}))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "status": "success", - "download_url": format!("{}/download/file_pdf", server.uri()), - "file_name": "report.pdf", - "mime_type": "application/pdf", - }))) - .expect(1) - .mount(&server) - .await; - - let uploaded = upload_openai_file( - &base_url_for(&server), - &chatgpt_auth(), - &default_http_client_pool(), - "report.pdf".to_string(), - /*file_size_bytes*/ 8, - || async { Ok(futures::stream::iter([Ok(Bytes::from_static(b"%PDF-1.4"))])) }, - Some(&hosted_upload), - ) - .await - .expect("older servers retain the normal upload behavior"); - - assert_eq!(uploaded.file_size_bytes, 8); - server.verify().await; - } - - #[tokio::test] - async fn upload_openai_file_reuses_client_pool_across_uploads() { - let server = MockServer::start().await; - let files = [ - ("first.txt", "file_1", &b"first"[..]), - ("second.txt", "file_2", &b"second"[..]), - ]; - - for (file_name, file_id, contents) in files { - Mock::given(method("POST")) - .and(path("/backend-api/files")) - .and(header("chatgpt-account-id", "account_id")) - .and(body_json(serde_json::json!({ - "file_name": file_name, - "file_size": contents.len(), - "use_case": "codex", - }))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "file_id": file_id, - "upload_url": format!("{}/upload/{file_id}", server.uri()), - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path(format!("/upload/{file_id}"))) - .and(header("content-length", contents.len().to_string())) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path(format!("/backend-api/files/{file_id}/uploaded"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "status": "success", - "download_url": format!("{}/download/{file_id}", server.uri()), - "file_name": file_name, - "mime_type": "text/plain", - "file_size_bytes": contents.len(), - }))) - .expect(1) - .mount(&server) - .await; - } - - let client_pool = default_http_client_pool(); - let mut uploaded_files = Vec::new(); - for (file_name, _, contents) in files { - let open_contents = || async { - Ok(futures::stream::iter([Ok(Bytes::copy_from_slice( - contents, - ))])) - }; - let uploaded = upload_openai_file( - &base_url_for(&server), - &chatgpt_auth(), - &client_pool, - file_name.to_string(), - u64::try_from(contents.len()).expect("file size should fit in a u64"), - open_contents, - /*hosted_upload*/ None, - ) - .await - .expect("upload succeeds with the shared client pool"); - uploaded_files.push(uploaded); - } - - assert_eq!( - uploaded_files, - vec![ - UploadedOpenAiFile { - file_id: "file_1".to_string(), - uri: "sediment://file_1".to_string(), - download_url: format!("{}/download/file_1", server.uri()), - file_name: "first.txt".to_string(), - file_size_bytes: 5, - mime_type: Some("text/plain".to_string()), - }, - UploadedOpenAiFile { - file_id: "file_2".to_string(), - uri: "sediment://file_2".to_string(), - download_url: format!("{}/download/file_2", server.uri()), - file_name: "second.txt".to_string(), - file_size_bytes: 6, - mime_type: Some("text/plain".to_string()), - }, - ] - ); - server.verify().await; - } - - #[tokio::test] - async fn upload_openai_file_reports_blob_response_diagnostics_without_sas() { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/backend-api/files")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "file_id": "file_123", - "upload_url": format!("{}/upload/file_123?sig=secret", server.uri()), - }))) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path("/upload/file_123")) - .respond_with( - ResponseTemplate::new(500) - .insert_header("x-ms-request-id", "azure-request") - .insert_header("x-ms-error-code", "ServerBusy") - .set_body_string("try again"), - ) - .mount(&server) - .await; - - let error = upload_openai_file( - &base_url_for(&server), - &chatgpt_auth(), - &default_http_client_pool(), - "hello.txt".to_string(), - /*file_size_bytes*/ 5, - || async { Ok(futures::stream::iter([Ok(Bytes::from_static(b"hello"))])) }, - /*hosted_upload*/ None, - ) - .await - .expect_err("blob response failure should be returned"); - - let message = error.to_string(); - assert!(message.contains("failed with status 500")); - assert!(message.contains("azure_client_request_id=")); - assert!(message.contains("azure_request_id=azure-request")); - assert!(message.contains("azure_error_code=ServerBusy")); - assert!(!message.contains("try again")); - assert!(!message.contains("sig=secret")); - } - - #[tokio::test] - async fn upload_openai_file_reports_blob_transport_diagnostics_without_sas() { - let upload_listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind upload address"); - let upload_address = upload_listener.local_addr().expect("upload address"); - drop(upload_listener); - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/backend-api/files")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "file_id": "file_123", - "upload_url": format!("http://{upload_address}/upload?sig=secret"), - }))) - .mount(&server) - .await; - - let error = upload_openai_file( - &base_url_for(&server), - &chatgpt_auth(), - &default_http_client_pool(), - "hello.txt".to_string(), - /*file_size_bytes*/ 5, - || async { Ok(futures::stream::iter([Ok(Bytes::from_static(b"hello"))])) }, - /*hosted_upload*/ None, - ) - .await - .expect_err("blob transport failure should be returned"); - - let message = error.to_string(); - assert!(message.contains("failed after")); - assert!(message.contains("(connect,"), "{message}"); - assert!(message.contains("azure_client_request_id=")); - assert!(!message.contains("sig=secret")); - } -} diff --git a/codex-rs/codex-api/src/files_retry_tests.rs b/codex-rs/codex-api/src/files_retry_tests.rs deleted file mode 100644 index bc8e6e32..00000000 --- a/codex-rs/codex-api/src/files_retry_tests.rs +++ /dev/null @@ -1,234 +0,0 @@ -//! Upload retries replay bytes without allocating or finalizing another file record. - -use super::tests::base_url_for; -use super::tests::chatgpt_auth; -use super::tests::default_http_client_pool; -use super::*; -use pretty_assertions::assert_eq; -use std::collections::HashSet; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::Request; -use wiremock::Respond; -use wiremock::ResponseTemplate; -use wiremock::matchers::body_bytes; -use wiremock::matchers::method; -use wiremock::matchers::path; - -async fn mock_upload( - server: &MockServer, - response: impl Respond + 'static, - puts: u64, - finalizes: u64, -) { - Mock::given(method("POST")) - .and(path("/backend-api/files")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "file_id": "file_123", - "upload_url": format!("{}/upload?sig=secret", server.uri()), - }))) - .expect(1) - .mount(server) - .await; - Mock::given(method("PUT")) - .and(path("/upload")) - .and(body_bytes(b"hello")) - .respond_with(response) - .expect(puts) - .mount(server) - .await; - Mock::given(method("POST")) - .and(path("/backend-api/files/file_123/uploaded")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "status": "success", "download_url": "https://example.com/file" - }))) - .expect(finalizes) - .mount(server) - .await; -} - -#[tokio::test] -async fn retries_transient_upload_statuses_within_budget() { - for (statuses, azure_code, retry_after) in [ - (vec![502, 200], None, None), - (vec![503, 200], Some("ServerBusy"), None), - (vec![504, 200], None, None), - (vec![502, 504, 503, 200], None, None), - (vec![502; 5], None, None), - (vec![503; 5], Some("ServerBusy"), None), - (vec![504; 5], None, None), - (vec![403], Some("AuthenticationFailed"), None), - (vec![409], None, None), - (vec![500], None, None), - (vec![502], None, Some("301")), - (vec![503], Some("ServerBusy"), Some("301")), - (vec![504], None, Some("301")), - ] { - let server = MockServer::start().await; - let attempts = statuses.len(); - let succeeds = statuses.last() == Some(&200); - let put_count = AtomicUsize::new(0); - mock_upload( - &server, - move |_request: &Request| { - let index = put_count.fetch_add(1, Ordering::SeqCst); - let response = ResponseTemplate::new(statuses[index]) - .insert_header("x-ms-request-id", format!("request-{index}")); - let response = match retry_after { - Some(delay) => response.insert_header("retry-after", delay), - None => response.insert_header("x-ms-retry-after-ms", "0"), - }; - match azure_code { - Some(code) => response.insert_header("x-ms-error-code", code), - None => response, - } - }, - attempts as u64, - u64::from(succeeds), - ) - .await; - let mut opens = 0; - - let result = upload_openai_file( - &base_url_for(&server), - &chatgpt_auth(), - &default_http_client_pool(), - "hello.txt".into(), - /*file_size_bytes*/ 5, - || { - opens += 1; - async { Ok(futures::stream::iter([Ok(Bytes::from_static(b"hello"))])) } - }, - /*hosted_upload*/ None, - ) - .await; - - assert_eq!((result.is_ok(), opens), (succeeds, attempts)); - if let Err(error) = result { - let message = error.to_string(); - assert!(message.contains(&format!("azure_request_id=request-{}", attempts - 1))); - assert!(message.contains(azure_code.unwrap_or("missing"))); - assert!(!format!("{error:?}").contains("sig=secret")); - } - let requests = server.received_requests().await.expect("requests"); - let mut request_ids = HashSet::new(); - for request in requests.iter().filter(|r| r.method == Method::PUT) { - let id = request.headers["x-ms-client-request-id"] - .to_str() - .expect("id"); - assert!(request_ids.insert(id.to_owned())); - } - assert_eq!(request_ids.len(), attempts); - server.verify().await; - } -} - -#[tokio::test] -async fn reopens_after_a_stream_closure_and_sends_the_complete_body() { - let server = MockServer::start().await; - mock_upload( - &server, - ResponseTemplate::new(200), - /*puts*/ 1, - /*finalizes*/ 1, - ) - .await; - let mut opens = 0; - - let result = upload_openai_file( - &base_url_for(&server), - &chatgpt_auth(), - &default_http_client_pool(), - "hello.txt".into(), - /*file_size_bytes*/ 5, - || { - opens += 1; - let chunks = if opens == 1 { - vec![ - Ok(Bytes::from_static(b"he")), - Err(std::io::Error::new( - std::io::ErrorKind::ConnectionReset, - "stream closed", - )), - ] - } else { - vec![Ok(Bytes::from_static(b"hello"))] - }; - async move { Ok(futures::stream::iter(chunks)) } - }, - /*hosted_upload*/ None, - ) - .await - .expect("replayed upload"); - - assert_eq!((result.file_id.as_str(), opens), ("file_123", 2)); - server.verify().await; -} - -#[tokio::test] -async fn reopening_cannot_extend_the_shared_upload_deadline() { - let server = MockServer::start().await; - mock_upload( - &server, - ResponseTemplate::new(503).insert_header("x-ms-retry-after-ms", "0"), - /*puts*/ 1, - /*finalizes*/ 0, - ) - .await; - let mut opens = 0; - let result = upload_openai_file( - &base_url_for(&server), - &chatgpt_auth(), - &default_http_client_pool(), - "hello.txt".into(), - /*file_size_bytes*/ 5, - || { - opens += 1; - let attempt = opens; - async move { - if attempt == 2 { - tokio::time::pause(); - tokio::time::sleep(OPENAI_FILE_BLOB_UPLOAD_TIMEOUT).await; - } - Ok(futures::stream::iter([Ok(Bytes::from_static(b"hello"))])) - } - }, - /*hosted_upload*/ None, - ) - .await; - - assert!(matches!( - result, - Err(OpenAiFileError::BlobUploadRequest { - error_kind: "timeout", - .. - }) - )); - assert_eq!(opens, 2); - server.verify().await; -} - -#[test] -fn server_retry_delays_accept_milliseconds_seconds_and_http_dates() { - for (milliseconds, retry_after, expected) in [ - (Some("250"), Some("5"), Some(Duration::from_millis(250))), - (Some("invalid"), Some("5"), Some(Duration::from_secs(5))), - ( - None, - Some("Wed, 21 Oct 2015 07:28:00 GMT"), - Some(Duration::ZERO), - ), - (None, Some("invalid"), None), - ] { - let mut headers = http::HeaderMap::new(); - if let Some(value) = milliseconds { - headers.insert("x-ms-retry-after-ms", value.parse().expect("header")); - } - if let Some(value) = retry_after { - headers.insert("retry-after", value.parse().expect("header")); - } - assert_eq!(blob_retry_after(&headers), expected); - } -} diff --git a/codex-rs/codex-api/src/lib.rs b/codex-rs/codex-api/src/lib.rs index 68b0c1c4..e8556abc 100644 --- a/codex-rs/codex-api/src/lib.rs +++ b/codex-rs/codex-api/src/lib.rs @@ -3,7 +3,6 @@ pub(crate) mod auth; pub(crate) mod common; pub(crate) mod endpoint; pub(crate) mod error; -pub(crate) mod files; mod guardian_assessment; pub(crate) mod images; pub(crate) mod provider; @@ -84,9 +83,6 @@ pub use crate::endpoint::ResponsesWebsocketProbeFailureStage; pub use crate::endpoint::SearchClient; pub use crate::endpoint::session_update_session_json; pub use crate::error::ApiError; -pub use crate::files::HostedFileUploadContext; -pub use crate::files::OPENAI_FILE_UPLOAD_LIMIT_BYTES; -pub use crate::files::upload_openai_file; pub use crate::guardian_assessment::GuardianAssessment; pub use crate::images::GifOptions; pub use crate::images::ImageBackground; diff --git a/codex-rs/codex-mcp/src/binding_tests.rs b/codex-rs/codex-mcp/src/binding_tests.rs index 5d784dd9..a41be20a 100644 --- a/codex-rs/codex-mcp/src/binding_tests.rs +++ b/codex-rs/codex-mcp/src/binding_tests.rs @@ -72,7 +72,6 @@ async fn test_step( format!("{label} catalog"), Arc::new(JsonObject::default()), ), - openai_file_input_optional_fields: Default::default(), connector_id: None, connector_name: None, plugin_display_names: Vec::new(), diff --git a/codex-rs/codex-mcp/src/codex_apps.rs b/codex-rs/codex-mcp/src/codex_apps.rs index 809b8ec9..a33f7353 100644 --- a/codex-rs/codex-mcp/src/codex_apps.rs +++ b/codex-rs/codex-mcp/src/codex_apps.rs @@ -5,11 +5,6 @@ use codex_utils_plugins::mcp_connector::sanitize_name; -mod file_params; - -pub use file_params::declared_openai_file_input_param_names; -pub(crate) use file_params::prepare_openai_file_params_for_model; - pub(crate) fn normalize_codex_apps_tool_title(connector_name: Option<&str>, value: &str) -> String { let Some(connector_name) = connector_name .map(str::trim) diff --git a/codex-rs/codex-mcp/src/codex_apps/file_params.rs b/codex-rs/codex-mcp/src/codex_apps/file_params.rs deleted file mode 100644 index 98e2fa5d..00000000 --- a/codex-rs/codex-mcp/src/codex_apps/file_params.rs +++ /dev/null @@ -1,219 +0,0 @@ -//! Apps SDK `openai/fileParams` metadata and schema shaping. -//! -//! For each declared file argument, this module derives the provided-file fields -//! accepted by its input schema and records them on `ToolInfo` for execution-time -//! argument rewriting. It also presents file arguments to the model as local paths. -//! -//! See . - -use std::collections::HashMap; -use std::collections::HashSet; -use std::sync::Arc; - -use rmcp::model::Tool; -use serde_json::Map; -use serde_json::Value as JsonValue; - -use crate::tools::ToolInfo; - -const META_OPENAI_FILE_PARAMS: &str = "openai/fileParams"; - -#[derive(Default)] -struct OpenAiFileSchemaInfo { - accepts_mime_type: bool, - accepts_file_name: bool, -} - -pub fn declared_openai_file_input_param_names( - meta: Option<&Map>, -) -> Vec { - let Some(meta) = meta else { - return Vec::new(); - }; - - meta.get(META_OPENAI_FILE_PARAMS) - .and_then(JsonValue::as_array) - .into_iter() - .flatten() - .filter_map(JsonValue::as_str) - .filter(|value| !value.is_empty()) - .map(str::to_string) - .collect() -} - -/// Derives execution-time file capabilities from the raw schema, then masks -/// declared file arguments as local paths for the model. -pub(crate) fn prepare_openai_file_params_for_model(tool_info: &mut ToolInfo) { - let file_params = declared_openai_file_input_param_names(tool_info.tool.meta.as_deref()); - tool_info.openai_file_input_optional_fields = - supported_openai_file_input_optional_fields(&tool_info.tool, &file_params); - - if file_params.is_empty() { - return; - } - - let mut tool = tool_info.tool.clone(); - let mut input_schema = JsonValue::Object(tool.input_schema.as_ref().clone()); - rewrite_input_schema_for_local_file_paths(&mut input_schema, &file_params); - if let JsonValue::Object(input_schema) = input_schema { - tool.input_schema = Arc::new(input_schema); - } - tool_info.tool = tool; -} - -fn supported_openai_file_input_optional_fields( - tool: &Tool, - file_params: &[String], -) -> HashMap> { - let properties = tool - .input_schema - .get("properties") - .and_then(JsonValue::as_object); - - file_params - .iter() - .map(|field_name| { - let optional_fields = properties - .and_then(|properties| properties.get(field_name)) - .map(|schema| { - let schema_info = openai_file_schema_info(schema, tool.input_schema.as_ref()); - let mut optional_fields = Vec::new(); - if schema_info.accepts_mime_type { - optional_fields.push("mime_type".to_string()); - } - if schema_info.accepts_file_name { - optional_fields.push("file_name".to_string()); - } - optional_fields - }) - .unwrap_or_default(); - (field_name.clone(), optional_fields) - }) - .collect() -} - -fn openai_file_schema_info( - schema: &JsonValue, - root_schema: &Map, -) -> OpenAiFileSchemaInfo { - let mut info = OpenAiFileSchemaInfo::default(); - let mut pending = vec![schema]; - let mut visited_refs = HashSet::new(); - - while let Some(schema) = pending.pop() { - let Some(schema) = schema.as_object() else { - continue; - }; - - if let Some(schema_ref) = schema.get("$ref").and_then(JsonValue::as_str) - && visited_refs.insert(schema_ref) - && let Some(referenced_schema) = resolve_local_schema_ref(root_schema, schema_ref) - { - pending.push(referenced_schema); - } - - for keyword in ["anyOf", "oneOf", "allOf"] { - if let Some(variants) = schema.get(keyword).and_then(JsonValue::as_array) { - pending.extend(variants); - } - } - - if schema.get("type").and_then(JsonValue::as_str) == Some("array") - || schema.contains_key("items") - { - if let Some(items) = schema.get("items") { - pending.push(items); - } - continue; - } - - let properties = schema.get("properties").and_then(JsonValue::as_object); - let is_object_schema = schema.get("type").and_then(JsonValue::as_str) == Some("object") - || properties.is_some() - || schema.contains_key("additionalProperties"); - if !is_object_schema { - continue; - } - let accepts_additional_properties = !matches!( - schema.get("additionalProperties"), - Some(JsonValue::Bool(false) | JsonValue::Object(_)) - ); - info.accepts_mime_type |= accepts_additional_properties - || properties.is_some_and(|properties| properties.contains_key("mime_type")); - info.accepts_file_name |= accepts_additional_properties - || properties.is_some_and(|properties| properties.contains_key("file_name")); - } - - info -} - -fn resolve_local_schema_ref<'a>( - root_schema: &'a Map, - schema_ref: &str, -) -> Option<&'a JsonValue> { - let pointer = schema_ref.strip_prefix("#/")?; - let mut segments = pointer.split('/'); - let first_segment = segments.next()?.replace("~1", "/").replace("~0", "~"); - let mut referenced_schema = root_schema.get(&first_segment)?; - - for segment in segments { - let segment = segment.replace("~1", "/").replace("~0", "~"); - referenced_schema = match referenced_schema { - JsonValue::Object(object) => object.get(&segment)?, - JsonValue::Array(array) => array.get(segment.parse::().ok()?)?, - _ => return None, - }; - } - - Some(referenced_schema) -} - -fn rewrite_input_schema_for_local_file_paths(input_schema: &mut JsonValue, file_params: &[String]) { - let Some(properties) = input_schema - .as_object_mut() - .and_then(|schema| schema.get_mut("properties")) - .and_then(JsonValue::as_object_mut) - else { - return; - }; - - for field_name in file_params { - let Some(property_schema) = properties.get_mut(field_name) else { - continue; - }; - rewrite_input_property_schema_as_local_file_path(property_schema); - } -} - -fn rewrite_input_property_schema_as_local_file_path(schema: &mut JsonValue) { - let Some(object) = schema.as_object_mut() else { - return; - }; - - let mut description = object - .get("description") - .and_then(JsonValue::as_str) - .map(str::to_string) - .unwrap_or_default(); - let guidance = "This parameter expects an absolute local file path. If you want to upload a file, provide the absolute path to that file here."; - if description.is_empty() { - description = guidance.to_string(); - } else if !description.contains(guidance) { - description = format!("{description} {guidance}"); - } - - let is_array = object.get("type").and_then(JsonValue::as_str) == Some("array") - || object.get("items").is_some(); - object.clear(); - object.insert("description".to_string(), JsonValue::String(description)); - if is_array { - object.insert("type".to_string(), JsonValue::String("array".to_string())); - object.insert("items".to_string(), serde_json::json!({ "type": "string" })); - } else { - object.insert("type".to_string(), JsonValue::String("string".to_string())); - } -} - -#[cfg(test)] -#[path = "file_params_tests.rs"] -mod tests; diff --git a/codex-rs/codex-mcp/src/codex_apps/file_params_tests.rs b/codex-rs/codex-mcp/src/codex_apps/file_params_tests.rs deleted file mode 100644 index 3d7f326e..00000000 --- a/codex-rs/codex-mcp/src/codex_apps/file_params_tests.rs +++ /dev/null @@ -1,284 +0,0 @@ -use std::collections::HashMap; -use std::sync::Arc; - -use pretty_assertions::assert_eq; -use rmcp::model::JsonObject; -use rmcp::model::MetaObject; -use rmcp::model::Tool; - -use super::*; -use crate::tools::ToolInfo; - -fn tool_info(tool: Tool) -> ToolInfo { - ToolInfo { - server_name: "codex_apps".to_string(), - supports_parallel_tool_calls: false, - server_origin: None, - callable_name: tool.name.to_string(), - callable_namespace: "codex_apps".to_string(), - namespace_description: None, - tool, - openai_file_input_optional_fields: HashMap::new(), - connector_id: None, - connector_name: None, - plugin_display_names: Vec::new(), - } -} - -fn test_tool(name: &str) -> Tool { - Tool::new( - name.to_string(), - format!("Test tool: {name}"), - Arc::new(JsonObject::default()), - ) -} - -#[test] -fn declared_openai_file_fields_treat_names_literally() { - let meta = serde_json::json!({ - "openai/fileParams": ["file", "input_file", "attachments"] - }); - let meta = meta.as_object().expect("meta object"); - - assert_eq!( - declared_openai_file_input_param_names(Some(meta)), - vec![ - "file".to_string(), - "input_file".to_string(), - "attachments".to_string(), - ] - ); -} - -#[test] -fn prepare_openai_file_params_for_model_masks_file_params() { - let mut tool = test_tool("upload"); - tool.input_schema = Arc::new( - serde_json::json!({ - "type": "object", - "properties": { - "file": { - "type": "object", - "description": "Original file payload." - }, - "files": { - "type": "array", - "items": {"type": "object"} - } - } - }) - .as_object() - .expect("object") - .clone(), - ); - tool.meta = Some(MetaObject( - serde_json::json!({ - "openai/fileParams": ["file", "files"] - }) - .as_object() - .expect("object") - .clone(), - )); - let mut tool_info = tool_info(tool); - - prepare_openai_file_params_for_model(&mut tool_info); - - assert_eq!( - *tool_info.tool.input_schema, - serde_json::json!({ - "type": "object", - "properties": { - "file": { - "type": "string", - "description": "Original file payload. This parameter expects an absolute local file path. If you want to upload a file, provide the absolute path to that file here." - }, - "files": { - "type": "array", - "items": {"type": "string"}, - "description": "This parameter expects an absolute local file path. If you want to upload a file, provide the absolute path to that file here." - } - } - }) - .as_object() - .expect("object") - .clone() - ); -} - -#[test] -fn prepare_openai_file_params_for_model_derives_supported_optional_fields() { - let mut tool = Tool::new( - "upload".to_string(), - "Upload files".to_string(), - Arc::new( - serde_json::json!({ - "type": "object", - "$defs": { - "Rich/File": { - "type": "object", - "properties": { - "download_url": {"type": "string"}, - "file_id": {"type": "string"}, - "file_name": {"type": "string"} - }, - "additionalProperties": false - } - }, - "properties": { - "photoshop_image": { - "type": "object", - "properties": { - "download_url": {"type": "string"}, - "file_id": {"type": "string"} - }, - "additionalProperties": false - }, - "drive_import": { - "type": "object", - "properties": { - "download_url": {"type": "string"}, - "file_id": {"type": "string"}, - "mime_type": {"type": "string"}, - "file_name": {"type": "string"} - }, - "additionalProperties": false - }, - "attachments": { - "anyOf": [ - { - "type": "array", - "items": { - "oneOf": [ - { - "allOf": [ - { - "type": "object", - "properties": { - "download_url": {"type": "string"}, - "file_id": {"type": "string"} - } - }, - { - "type": "object", - "properties": { - "mime_type": {"type": "string"} - } - } - ] - }, - {"type": "null"} - ] - } - }, - {"type": "null"} - ] - }, - "referenced_file": { - "$ref": "#/$defs/Rich~1File" - }, - "custom_file": { - "type": "object", - "properties": { - "download_url": {"type": "string"}, - "file_id": {"type": "string"}, - "mime_type": {"type": "string"}, - "uri": {"type": "string"} - }, - "additionalProperties": false - }, - "open_file": { - "type": "object", - "properties": { - "download_url": {"type": "string"}, - "file_id": {"type": "string"} - } - }, - "explicitly_open_file": { - "type": "object", - "properties": { - "download_url": {"type": "string"}, - "file_id": {"type": "string"} - }, - "additionalProperties": true - }, - "items_only_files": { - "items": { - "type": "object", - "properties": { - "download_url": {"type": "string"}, - "file_id": {"type": "string"}, - "file_name": {"type": "string"} - }, - "additionalProperties": false - } - } - } - }) - .as_object() - .expect("object") - .clone(), - ), - ); - tool.meta = Some(MetaObject( - serde_json::json!({ - "openai/fileParams": [ - "photoshop_image", - "drive_import", - "attachments", - "referenced_file", - "custom_file", - "open_file", - "explicitly_open_file", - "items_only_files", - "missing_file" - ] - }) - .as_object() - .expect("object") - .clone(), - )); - let mut tool_info = tool_info(tool); - - prepare_openai_file_params_for_model(&mut tool_info); - - assert_eq!( - tool_info.openai_file_input_optional_fields, - HashMap::from([ - ("photoshop_image".to_string(), Vec::new()), - ( - "drive_import".to_string(), - vec!["mime_type".to_string(), "file_name".to_string()] - ), - ( - "attachments".to_string(), - vec!["mime_type".to_string(), "file_name".to_string()] - ), - ("referenced_file".to_string(), vec!["file_name".to_string()]), - ("custom_file".to_string(), vec!["mime_type".to_string()]), - ( - "open_file".to_string(), - vec!["mime_type".to_string(), "file_name".to_string()] - ), - ( - "explicitly_open_file".to_string(), - vec!["mime_type".to_string(), "file_name".to_string()] - ), - ( - "items_only_files".to_string(), - vec!["file_name".to_string()] - ), - ("missing_file".to_string(), Vec::new()), - ]) - ); -} - -#[test] -fn prepare_openai_file_params_for_model_leaves_tools_without_file_params_unchanged() { - let original_tool = test_tool("upload"); - let mut tool_info = tool_info(original_tool.clone()); - - prepare_openai_file_params_for_model(&mut tool_info); - - assert_eq!(tool_info.tool, original_tool); - assert!(tool_info.openai_file_input_optional_fields.is_empty()); -} diff --git a/codex-rs/codex-mcp/src/connection_manager_tests.rs b/codex-rs/codex-mcp/src/connection_manager_tests.rs index 0ab671d8..750d84a3 100644 --- a/codex-rs/codex-mcp/src/connection_manager_tests.rs +++ b/codex-rs/codex-mcp/src/connection_manager_tests.rs @@ -198,7 +198,6 @@ pub(crate) fn create_test_tool(server_name: &str, tool_name: &str) -> ToolInfo { format!("Test tool: {tool_name}"), Arc::new(JsonObject::default()), ), - openai_file_input_optional_fields: Default::default(), connector_id: None, connector_name: None, plugin_display_names: Vec::new(), diff --git a/codex-rs/codex-mcp/src/lib.rs b/codex-rs/codex-mcp/src/lib.rs index a6a3596a..c5beaad7 100644 --- a/codex-rs/codex-mcp/src/lib.rs +++ b/codex-rs/codex-mcp/src/lib.rs @@ -81,12 +81,9 @@ pub use auth_elicitation::connector_auth_failure_from_tool_result; pub use auth_elicitation::is_connector_auth_failure_from_tool_result; /// Backward-compatible name for the Codex Apps runtime context key builder. pub use codex_connectors::connector_runtime_context_key as codex_apps_tools_cache_key; -pub use mcp::codex_apps_mcp_server_config; pub use mcp::configured_mcp_servers; pub use mcp::effective_mcp_servers; pub use mcp::effective_mcp_servers_from_configured; -pub use mcp::host_owned_codex_apps_enabled; -pub use mcp::hosted_plugin_runtime_mcp_server_config; pub use mcp::tool_plugin_context; pub use plugin_config::PluginMcpConfigParseOutcome; pub use plugin_config::PluginMcpServerParseError; @@ -113,7 +110,6 @@ pub use mcp::resolve_oauth_callback; pub use mcp::resolve_oauth_scopes; pub use mcp::should_retry_without_scopes; -pub use codex_apps::declared_openai_file_input_param_names; pub use mcp::McpPermissionPromptAutoApproveContext; pub use mcp::mcp_permission_prompt_is_auto_approved; pub use mcp::qualified_mcp_tool_name_prefix; diff --git a/codex-rs/codex-mcp/src/mcp/mod.rs b/codex-rs/codex-mcp/src/mcp/mod.rs index 492d72a0..ced2c129 100644 --- a/codex-rs/codex-mcp/src/mcp/mod.rs +++ b/codex-rs/codex-mcp/src/mcp/mod.rs @@ -14,7 +14,6 @@ pub(crate) mod auth; use std::collections::HashMap; use std::collections::HashSet; -use std::env; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; @@ -67,7 +66,6 @@ pub const CODEX_APPS_MCP_SERVER_NAME: &str = "codex_apps"; pub(crate) const DEFAULT_CODEX_APPS_MCP_PRODUCT_SKU: &str = "codex"; const MCP_TOOL_NAME_PREFIX: &str = "mcp"; const MCP_TOOL_NAME_DELIMITER: &str = "__"; -const CODEX_CONNECTORS_TOKEN_ENV_VAR: &str = "CODEX_CONNECTORS_TOKEN"; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum McpSnapshotDetail { @@ -369,10 +367,6 @@ impl ToolPluginContext { } } -pub fn host_owned_codex_apps_enabled(config: &McpConfig, auth: Option<&CodexAuth>) -> bool { - config.apps_enabled && auth.is_some_and(CodexAuth::uses_codex_backend) -} - pub fn configured_mcp_servers(config: &McpConfig) -> HashMap { config.mcp_server_catalog.configured_servers() } @@ -428,7 +422,7 @@ pub(crate) fn is_trusted_chatgpt_mcp_server( pub fn effective_mcp_servers_from_configured( configured_servers: HashMap, config: &McpConfig, - auth: Option<&CodexAuth>, + _auth: Option<&CodexAuth>, ) -> HashMap { let mut servers = configured_servers .into_iter() @@ -459,9 +453,8 @@ pub fn effective_mcp_servers_from_configured( ) }) .collect::>(); - if !host_owned_codex_apps_enabled(config, auth) { - servers.remove(CODEX_APPS_MCP_SERVER_NAME); - } + // aKode never connects to the ChatGPT-hosted apps MCP server. + servers.remove(CODEX_APPS_MCP_SERVER_NAME); servers } @@ -644,101 +637,6 @@ pub(crate) fn sanitize_responses_api_tool_name(name: &str) -> String { } } -fn codex_apps_mcp_bearer_token_env_var() -> Option { - match env::var(CODEX_CONNECTORS_TOKEN_ENV_VAR) { - Ok(value) if !value.trim().is_empty() => Some(CODEX_CONNECTORS_TOKEN_ENV_VAR.to_string()), - Ok(_) => None, - Err(env::VarError::NotPresent) => None, - Err(env::VarError::NotUnicode(_)) => Some(CODEX_CONNECTORS_TOKEN_ENV_VAR.to_string()), - } -} - -fn normalize_codex_apps_base_url(base_url: &str) -> String { - let mut base_url = base_url.trim_end_matches('/').to_string(); - if (base_url.starts_with("https://chatgpt.com") - || base_url.starts_with("https://chat.openai.com")) - && !base_url.contains("/backend-api") - { - base_url = format!("{base_url}/backend-api"); - } - base_url -} - -fn codex_apps_mcp_url_for_base_url(base_url: &str) -> String { - let base_url = normalize_codex_apps_base_url(base_url); - let base_url = if base_url.contains("/backend-api") || base_url.contains("/api/codex") { - base_url - } else { - format!("{base_url}/api/codex") - }; - format!("{base_url}/ps/mcp") -} - -pub fn codex_apps_mcp_server_config( - chatgpt_base_url: &str, - apps_mcp_product_sku: Option<&str>, - originator: Option<&str>, -) -> McpServerConfig { - mcp_server_config_for_url( - codex_apps_mcp_url_for_base_url(chatgpt_base_url), - apps_mcp_product_sku, - originator, - McpServerAuth::ChatGpt, - ) -} - -/// Builds the ChatGPT-hosted plugin runtime served by plugin-service. -pub fn hosted_plugin_runtime_mcp_server_config( - chatgpt_base_url: &str, - apps_mcp_product_sku: Option<&str>, - originator: Option<&str>, -) -> McpServerConfig { - codex_apps_mcp_server_config(chatgpt_base_url, apps_mcp_product_sku, originator) -} - -fn mcp_server_config_for_url( - url: String, - apps_mcp_product_sku: Option<&str>, - originator: Option<&str>, - auth_mode: McpServerAuth, -) -> McpServerConfig { - let product_sku = apps_mcp_product_sku.unwrap_or(DEFAULT_CODEX_APPS_MCP_PRODUCT_SKU); - let mut http_headers = - HashMap::from([("X-OpenAI-Product-Sku".to_string(), product_sku.to_string())]); - if let Some(originator) = originator { - http_headers.insert("originator".to_string(), originator.to_string()); - } - let env_http_headers = None; - - McpServerConfig { - transport: McpServerTransportConfig::StreamableHttp { - url, - bearer_token_env_var: codex_apps_mcp_bearer_token_env_var(), - http_headers: Some(http_headers), - env_http_headers, - http_headers_helper: None, - }, - auth: auth_mode, - environment_id: codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(), - enabled: true, - required: false, - startup_readiness: Default::default(), - supports_parallel_tool_calls: false, - tool_input_schema_max_bytes: None, - omit_tools_from: None, - disabled_reason: None, - startup_timeout_sec: Some(Duration::from_secs(30)), - tool_timeout_sec: None, - default_tools_approval_mode: None, - enabled_tools: None, - disabled_tools: None, - scopes: None, - oauth: None, - oauth_resource: None, - tools: HashMap::new(), - } -} - fn protocol_tool_from_rmcp_tool(name: &str, tool: &rmcp::model::Tool) -> Option { match serde_json::to_value(tool) { Ok(value) => match Tool::from_mcp_value(value) { diff --git a/codex-rs/codex-mcp/src/rmcp_client.rs b/codex-rs/codex-mcp/src/rmcp_client.rs index c6440742..e2476ed5 100644 --- a/codex-rs/codex-mcp/src/rmcp_client.rs +++ b/codex-rs/codex-mcp/src/rmcp_client.rs @@ -37,7 +37,6 @@ use crate::client_tool_catalog::ClientToolCatalog; use crate::codex_apps::normalize_codex_apps_callable_name; use crate::codex_apps::normalize_codex_apps_callable_namespace; use crate::codex_apps::normalize_codex_apps_tool_title; -use crate::codex_apps::prepare_openai_file_params_for_model; use crate::connection_pool::ConnectionKey; use crate::connection_pool::ConnectionSharing; use crate::connection_pool::ConnectionSlot; @@ -892,8 +891,7 @@ pub(crate) async fn list_tools_for_client_uncached( Ok((tools, meta)) } -/// Filters disabled connectors, presents declared Codex Apps file parameters to the model as -/// local-path inputs, and adds plugin names to each tool. Plugin membership is resolved by +/// Filters disabled connectors and adds plugin names to each tool. Plugin membership is resolved by /// connector ID, falling back to the MCP server when absent. pub(crate) fn prepare_codex_apps_tools_for_model( mut tools: Vec, @@ -901,7 +899,6 @@ pub(crate) fn prepare_codex_apps_tools_for_model( ) -> Vec { tools.retain(|tool| tool_plugin_context.allows_connector_id(tool.connector_id.as_deref())); for tool in &mut tools { - prepare_openai_file_params_for_model(tool); let plugin_names = match tool.connector_id.as_deref() { Some(connector_id) => { tool_plugin_context.plugin_display_names_for_connector_id(connector_id) @@ -1035,7 +1032,6 @@ fn codex_apps_tool_info_from_listed_tool( callable_namespace, namespace_description, tool: tool_def, - openai_file_input_optional_fields: HashMap::new(), connector_id, connector_name, plugin_display_names: Vec::new(), @@ -1059,7 +1055,6 @@ fn regular_mcp_tool_info_from_listed_tool( callable_namespace: server_name.to_string(), namespace_description: server_instructions.map(str::to_string), tool: tool_def, - openai_file_input_optional_fields: HashMap::new(), connector_id: None, connector_name: None, plugin_display_names: Vec::new(), @@ -1792,7 +1787,6 @@ mod tests { callable_namespace: "codex_apps__gmail".to_string(), namespace_description: Some("Mail connector".to_string()), tool: expected_tool, - openai_file_input_optional_fields: HashMap::new(), connector_id: Some("connector_gmail".to_string()), connector_name: Some("Gmail".to_string()), plugin_display_names: Vec::new(), diff --git a/codex-rs/codex-mcp/src/tools.rs b/codex-rs/codex-mcp/src/tools.rs index 68f60c62..ee482dab 100644 --- a/codex-rs/codex-mcp/src/tools.rs +++ b/codex-rs/codex-mcp/src/tools.rs @@ -43,11 +43,6 @@ pub struct ToolInfo { pub namespace_description: Option, /// Raw MCP tool definition; `tool.name` is sent back to the MCP server. pub tool: Tool, - /// Optional provided-file fields accepted by each declared `openai/fileParams` - /// argument. This is derived from the raw MCP schema before file arguments are - /// masked as local paths for the model. - #[serde(default, skip_serializing_if = "HashMap::is_empty")] - pub openai_file_input_optional_fields: HashMap>, pub connector_id: Option, pub connector_name: Option, #[serde(default)] diff --git a/codex-rs/core-plugins/src/discoverable_tests.rs b/codex-rs/core-plugins/src/discoverable_tests.rs index 5642ee21..5d3da944 100644 --- a/codex-rs/core-plugins/src/discoverable_tests.rs +++ b/codex-rs/core-plugins/src/discoverable_tests.rs @@ -4,10 +4,6 @@ use crate::OPENAI_BUNDLED_MARKETPLACE_NAME; use crate::PluginInstallRequest; use crate::PluginsConfigInput; use crate::PluginsManager; -use crate::remote::InstalledPluginDisplayAssets; -use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME; -use crate::remote::RemotePluginServiceConfig; -use crate::remote::fetch_and_cache_global_remote_plugin_catalog; use crate::startup_sync::curated_plugins_repo_path; use crate::test_support::TEST_CURATED_PLUGIN_SHA; use crate::test_support::load_plugins_config; @@ -27,7 +23,6 @@ use codex_protocol::auth::AuthMode; use codex_protocol::protocol::Product; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; -use serde_json::json; use std::collections::HashSet; use std::path::Path; use std::sync::Arc; @@ -35,13 +30,6 @@ use tempfile::tempdir; use tracing::Level; use tracing_subscriber::fmt::format::FmtSpan; use tracing_test::internal::MockWriter; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; -use wiremock::matchers::query_param_is_missing; #[tokio::test] async fn returns_fallback_plugins_when_remote_disabled_for_codex_auth() { @@ -839,238 +827,6 @@ source = "/tmp/{sales_marketplace_name}" assert_eq!(discoverable_plugins, Vec::new()); } -#[tokio::test] -async fn cached_remote_discovery_requires_installed_cache_and_filters_candidates() { - assert_cached_remote_discovery_filters_candidates(InstalledPluginDisplayAssets::Include).await; -} - -/// Tool suggestions need installed IDs even when display enrichment was skipped. -#[tokio::test] -async fn cached_remote_discovery_accepts_snapshot_without_display_assets() { - assert_cached_remote_discovery_filters_candidates(InstalledPluginDisplayAssets::Skip).await; -} - -async fn assert_cached_remote_discovery_filters_candidates( - display_assets: InstalledPluginDisplayAssets, -) { - let codex_home = tempdir().expect("tempdir should succeed"); - write_file( - &codex_home.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/list")) - .and(query_param("scope", "GLOBAL")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [ - { - "id": "plugins~Plugin_remote_github", - "name": "github", - "scope": "GLOBAL", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "status": "AVAILABLE", - "release": { - "display_name": "Remote GitHub", - "description": "Remote GitHub long", - "app_ids": ["github"], - "interface": {"short_description": "Remote GitHub short"}, - "skills": [{ - "name": "github", - "description": "Use GitHub", - "interface": null - }] - } - }, - { - "id": "plugins~Plugin_remote_unlisted", - "name": "remote-unlisted", - "scope": "GLOBAL", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "status": "AVAILABLE", - "release": { - "display_name": "Remote Unlisted", - "description": "Remote Unlisted long", - "app_ids": ["remote-unlisted-app"], - "interface": { - "short_description": "Remote Unlisted short", - "long_description": null, - "developer_name": null, - "category": null, - "capabilities": [], - "website_url": null, - "privacy_policy_url": null, - "terms_of_service_url": null, - "brand_color": null, - "default_prompt": null, - "composer_icon_url": null, - "logo_url": null, - "screenshot_urls": [] - }, - "skills": [ - { - "name": "remote-unlisted", - "description": "Use unlisted remote plugin", - "interface": null - } - ] - } - }, - { - "id": "plugins~Plugin_remote_slack_not_available", - "name": "slack", - "scope": "GLOBAL", - "installation_policy": "NOT_AVAILABLE", - "authentication_policy": "ON_USE", - "status": "AVAILABLE", - "release": { - "display_name": "Remote Slack", - "description": "Remote Slack long", - "interface": {"short_description": "Remote Slack short"} - } - }, - { - "id": "plugins~Plugin_remote_figma_admin_disabled", - "name": "figma", - "scope": "GLOBAL", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "status": "DISABLED_BY_ADMIN", - "release": { - "display_name": "Remote Figma", - "description": "Remote Figma long", - "interface": {"short_description": "Remote Figma short"} - } - } - ], - "pagination": { - "next_page_token": null - } - }))) - .expect(1) - .mount(&server) - .await; - - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let mut plugins = load_plugins_config(codex_home.path(), codex_home.path()).await; - plugins.chatgpt_base_url = format!("{}/backend-api", server.uri()); - let plugins_manager = test_plugins_manager_with_options( - codex_home.path().to_path_buf(), - Some(Product::Codex), - Some(AuthMode::Chatgpt), - ); - fetch_and_cache_global_remote_plugin_catalog( - codex_home.path(), - &RemotePluginServiceConfig::new( - plugins.chatgpt_base_url.clone(), - crate::test_support::test_http_client_factory(), - /*product_sku*/ None, - ), - Some(&auth), - ) - .await - .expect("remote plugin catalog cache should write"); - - assert_eq!( - list_discoverable_plugins( - &plugins_manager, - discovery_input(plugins.clone(), &[], &[], &["remote-unlisted-app"]), - Some(&auth), - ) - .await, - Vec::new() - ); - - let installed_request = Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param_is_missing("scope")) - .and(query_param_is_missing("includeDownloadUrls")); - let installed_request = match display_assets { - InstalledPluginDisplayAssets::Include => { - installed_request.and(query_param_is_missing("includeDisplayAssets")) - } - InstalledPluginDisplayAssets::Skip => { - installed_request.and(query_param("includeDisplayAssets", "false")) - } - }; - installed_request - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [], - "pagination": { - "next_page_token": null - } - }))) - .expect(1) - .mount(&server) - .await; - plugins_manager - .build_and_cache_remote_installed_plugin_marketplaces_with_display_assets( - &plugins, - Some(&auth), - &[REMOTE_GLOBAL_MARKETPLACE_NAME], - /*on_effective_plugins_changed*/ None, - display_assets, - ) - .await - .expect("remote installed plugin cache should write"); - - let expected_github = ToolSuggestDiscoverablePlugin { - id: "github@openai-curated-remote".to_string(), - remote_plugin_id: Some("plugins~Plugin_remote_github".to_string()), - name: "Remote GitHub".to_string(), - description: Some("Remote GitHub short".to_string()), - has_skills: true, - mcp_server_names: Vec::new(), - app_connector_ids: vec!["github".to_string()], - }; - assert_eq!( - list_discoverable_plugins( - &plugins_manager, - discovery_input(plugins.clone(), &[], &[], &[]), - Some(&auth), - ) - .await, - vec![expected_github.clone()] - ); - - let discoverable_plugins = list_discoverable_plugins( - &plugins_manager, - discovery_input(plugins.clone(), &[], &[], &["remote-unlisted-app"]), - Some(&auth), - ) - .await; - - assert_eq!( - discoverable_plugins, - vec![ - expected_github, - ToolSuggestDiscoverablePlugin { - id: "remote-unlisted@openai-curated-remote".to_string(), - remote_plugin_id: Some("plugins~Plugin_remote_unlisted".to_string()), - name: "Remote Unlisted".to_string(), - description: Some("Remote Unlisted short".to_string()), - has_skills: true, - mcp_server_names: Vec::new(), - app_connector_ids: vec!["remote-unlisted-app".to_string()], - }, - ] - ); - assert_eq!( - list_discoverable_plugins( - &plugins_manager, - discovery_input(plugins, &[], &["github@openai-curated-remote"], &[]), - Some(&auth), - ) - .await, - Vec::new() - ); -} - fn discovery_input( plugins: PluginsConfigInput, configured_plugin_ids: &[&str], diff --git a/codex-rs/core-plugins/src/http_client_selector.rs b/codex-rs/core-plugins/src/http_client_selector.rs index 0650f2a5..bb729338 100644 --- a/codex-rs/core-plugins/src/http_client_selector.rs +++ b/codex-rs/core-plugins/src/http_client_selector.rs @@ -1,8 +1,5 @@ -use codex_http_client::NetworkPolicy; use codex_http_client::OutboundProxyPolicy; -use codex_http_client::RequestBuilder; use codex_http_client::RouteAwareClientPool; -use http::Method; use std::fmt::Debug; use std::sync::Arc; @@ -12,13 +9,6 @@ use std::sync::Arc; /// client would let callers send a different URL than the one used for route selection. pub(crate) trait HttpClientSelector: Debug + Send + Sync { fn for_current_account(&self) -> Arc; - fn request(&self, method: Method, url: &str) -> RequestBuilder; - fn request_for_account( - &self, - method: Method, - url: &str, - binding: &NetworkPolicy, - ) -> Option; fn outbound_proxy_policy(&self) -> OutboundProxyPolicy; } @@ -27,19 +17,6 @@ impl HttpClientSelector for RouteAwareClientPool { Arc::new(RouteAwareClientPool::for_current_account(self)) } - fn request(&self, method: Method, url: &str) -> RequestBuilder { - RouteAwareClientPool::request(self, method, url) - } - - fn request_for_account( - &self, - method: Method, - url: &str, - binding: &NetworkPolicy, - ) -> Option { - Some(self.with_account_binding(binding)?.request(method, url)) - } - fn outbound_proxy_policy(&self) -> OutboundProxyPolicy { RouteAwareClientPool::outbound_proxy_policy(self) } diff --git a/codex-rs/core-plugins/src/lib.rs b/codex-rs/core-plugins/src/lib.rs index 8b8f57f8..37489a97 100644 --- a/codex-rs/core-plugins/src/lib.rs +++ b/codex-rs/core-plugins/src/lib.rs @@ -22,7 +22,6 @@ mod marketplace_staging; pub mod marketplace_upgrade; mod npm_source; mod plugin_bundle_archive; -mod plugin_measurement_references; mod plugin_metrics; mod plugin_metrics_sidecar; mod provider; @@ -109,8 +108,6 @@ pub use marketplace_policy::allowed_configured_marketplace_names; pub use marketplace_upgrade::ConfigLayerReload; pub use marketplace_upgrade::ConfiguredMarketplaceUpgradeError as PluginMarketplaceUpgradeError; pub use marketplace_upgrade::ConfiguredMarketplaceUpgradeOutcome as PluginMarketplaceUpgradeOutcome; -pub use plugin_measurement_references::PluginMeasurementReference; -pub use plugin_measurement_references::RemotePluginMeasurementCache; pub use plugin_metrics::PluginMeasurementDefinition; pub use plugin_metrics::PluginMetricsOperation; pub use plugin_metrics::ResolvedPluginMetricsOperation; diff --git a/codex-rs/core-plugins/src/manager_errors.rs b/codex-rs/core-plugins/src/manager_errors.rs index 60fdb049..72cb9674 100644 --- a/codex-rs/core-plugins/src/manager_errors.rs +++ b/codex-rs/core-plugins/src/manager_errors.rs @@ -89,6 +89,7 @@ pub(super) fn marketplace_error_sub_error_type(err: &MarketplaceError) -> Option fn remote_plugin_mutation_error_type(err: &RemotePluginMutationError) -> &'static str { match err { + RemotePluginMutationError::Unavailable => "remote_mutation_unavailable", RemotePluginMutationError::AuthRequired => "remote_mutation_auth_required", RemotePluginMutationError::UnsupportedAuthMode => "remote_mutation_unsupported_auth_mode", RemotePluginMutationError::AuthToken(_) => "remote_mutation_auth_token", diff --git a/codex-rs/core-plugins/src/manager_tests.rs b/codex-rs/core-plugins/src/manager_tests.rs index 6bd2482b..f6a31f5b 100644 --- a/codex-rs/core-plugins/src/manager_tests.rs +++ b/codex-rs/core-plugins/src/manager_tests.rs @@ -17,7 +17,6 @@ use crate::marketplace::MarketplacePluginInstallPolicy; use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME; use crate::remote::REMOTE_WORKSPACE_MARKETPLACE_NAME; use crate::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME; -use crate::remote::RecommendedPlugin; use crate::remote::RemoteInstalledPlugin; use crate::startup_sync::curated_plugins_repo_path; use crate::test_support::TEST_CURATED_PLUGIN_CACHE_VERSION; @@ -65,16 +64,8 @@ use codex_utils_plugins::SkillDiscoveryMode; use pretty_assertions::assert_eq; use std::fs; use std::path::Path; -use std::time::Duration; use tempfile::TempDir; use toml::Value; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; const MAX_CAPABILITY_SUMMARY_DESCRIPTION_LEN: usize = 1024; @@ -6023,460 +6014,6 @@ enabled = true ); } -#[tokio::test] -async fn featured_plugin_ids_for_config_uses_restriction_product_query_param() { - let tmp = tempfile::tempdir().unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/plugins/featured")) - .and(query_param("platform", "chat")) - .and(header("authorization", "Bearer Access Token")) - .and(header("chatgpt-account-id", "account_id")) - .respond_with(ResponseTemplate::new(200).set_body_string(r#"["chat-plugin"]"#)) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = format!("{}/backend-api/", server.uri()); - let manager = test_plugins_manager_with_options( - tmp.path().to_path_buf(), - Some(Product::Chatgpt), - /*auth_mode*/ None, - ); - - let featured_plugin_ids = manager - .featured_plugin_ids_for_config( - &config, - Some(&CodexAuth::create_dummy_chatgpt_auth_for_testing()), - ) - .await - .unwrap(); - - assert_eq!(featured_plugin_ids, vec!["chat-plugin".to_string()]); -} - -#[tokio::test] -async fn featured_plugin_ids_for_config_defaults_query_param_to_codex() { - let tmp = tempfile::tempdir().unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/plugins/featured")) - .and(query_param("platform", "codex")) - .respond_with(ResponseTemplate::new(200).set_body_string(r#"["codex-plugin"]"#)) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = format!("{}/backend-api/", server.uri()); - let manager = test_plugins_manager_with_options( - tmp.path().to_path_buf(), - /*restriction_product*/ None, - /*auth_mode*/ None, - ); - - let featured_plugin_ids = manager - .featured_plugin_ids_for_config(&config, /*auth*/ None) - .await - .unwrap(); - - assert_eq!(featured_plugin_ids, vec!["codex-plugin".to_string()]); -} - -#[tokio::test] -async fn remote_plugin_caches_refresh_warms_recommended_plugins_cache() { - let tmp = tempfile::tempdir().unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/ps/plugins/suggested/codex")) - .and(query_param("scope", "GLOBAL")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "enabled": true, - "plugins": [] - }))) - .expect(1) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = server.uri(); - let manager = std::sync::Arc::new(test_plugins_manager(tmp.path().to_path_buf())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let cache_key = recommended_plugins_cache_key(&config); - - manager.maybe_start_remote_plugin_caches_refresh( - &config, - Some(auth.clone()), - /*on_effective_plugins_changed*/ None, - ); - - let mode = tokio::time::timeout(Duration::from_secs(2), async { - loop { - if let Some(mode) = manager.cached_recommended_plugins_mode(&cache_key) { - break mode; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("recommended plugins cache should be warmed"); - assert_eq!( - mode, - RecommendedPluginsMode::Endpoint { - plugins: Vec::new() - } - ); - assert_eq!( - manager - .recommended_plugins_mode_for_config(&config, Some(&auth)) - .await, - mode - ); - manager.clear_recommended_plugins_cache(); - assert_eq!(manager.cached_recommended_plugins_mode(&cache_key), None); -} - -#[tokio::test] -async fn recommended_plugins_mode_deduplicates_concurrent_cache_misses() { - let tmp = tempfile::tempdir().unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/ps/plugins/suggested/codex")) - .and(query_param("scope", "GLOBAL")) - .and(header("authorization", "Bearer Access Token")) - .and(header("chatgpt-account-id", "account_id")) - .and(header("OAI-Product-Sku", "codex")) - .respond_with( - ResponseTemplate::new(200) - .set_body_json(serde_json::json!({ - "enabled": true, - "plugins": [ - { - "id": "plugin_slack", - "name": "slack", - "display_name": "Slack" - }, - { - "id": "plugin_github", - "name": "github", - "display_name": "GitHub" - } - ] - })) - .set_delay(Duration::from_millis(100)), - ) - .expect(1) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = server.uri(); - let manager = test_plugins_manager(tmp.path().to_path_buf()); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let expected = RecommendedPluginsMode::Endpoint { - plugins: vec![ - RecommendedPlugin { - config_id: "github@openai-curated-remote".to_string(), - remote_plugin_id: "plugin_github".to_string(), - display_name: "GitHub".to_string(), - }, - RecommendedPlugin { - config_id: "slack@openai-curated-remote".to_string(), - remote_plugin_id: "plugin_slack".to_string(), - display_name: "Slack".to_string(), - }, - ], - }; - - let (left, right) = tokio::join!( - manager.recommended_plugins_mode_for_config(&config, Some(&auth)), - manager.recommended_plugins_mode_for_config(&config, Some(&auth)), - ); - assert_eq!((left, right), (expected.clone(), expected.clone())); - assert_eq!( - manager - .recommended_plugins_mode_for_config(&config, Some(&auth)) - .await, - expected - ); -} - -#[tokio::test] -async fn recommended_plugins_cache_clear_rejects_stale_fetch_completion() { - let tmp = tempfile::tempdir().unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - "[features]\nplugins = true\n", - ); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let server = MockServer::start().await; - let request_started = Arc::new(tokio::sync::Notify::new()); - let started = Arc::clone(&request_started); - let (release_response, released) = std::sync::mpsc::channel(); - let released = std::sync::Mutex::new(released); - let old_response = ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "enabled": true, - "plugins": [{"id": "plugin_old", "name": "old", "display_name": "Old"}] - })); - Mock::given(method("GET")) - .and(path("/ps/plugins/suggested/codex")) - .respond_with(move |_: &wiremock::Request| { - started.notify_one(); - // Wiremock runs its own server thread. Dropping the sender also releases it. - let _ = released.lock().unwrap().recv(); - old_response.clone() - }) - .up_to_n_times(1) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/ps/plugins/suggested/codex")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "enabled": true, - "plugins": [] - }))) - .expect(1) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = server.uri(); - let manager = test_plugins_manager(tmp.path().to_path_buf()); - let old_lookup = manager.recommended_plugins_mode_for_config(&config, Some(&auth)); - tokio::pin!(old_lookup); - tokio::select! { - biased; - _ = request_started.notified() => {} - mode = old_lookup.as_mut() => panic!("old fetch finished before release: {mode:?}"), - } - - manager.clear_recommended_plugins_cache(); - release_response - .send(()) - .expect("release old HTTP response"); - - // Keep the old initializer unpolled until the new fetch publishes. An invalidated - // fetch must not overwrite the fresh result. - let new_mode = tokio::time::timeout( - Duration::from_secs(10), - manager.recommended_plugins_mode_for_config(&config, Some(&auth)), - ) - .await - .expect("new lookup should finish independently of the invalidated fetch"); - assert_eq!( - new_mode, - RecommendedPluginsMode::Endpoint { - plugins: Vec::new() - } - ); - assert_eq!( - old_lookup.await, - RecommendedPluginsMode::Endpoint { - plugins: vec![RecommendedPlugin { - config_id: "old@openai-curated-remote".to_string(), - remote_plugin_id: "plugin_old".to_string(), - display_name: "Old".to_string(), - }] - } - ); - assert_eq!( - manager - .recommended_plugins_mode_for_config(&config, Some(&auth)) - .await, - new_mode - ); - server.verify().await; -} - -#[tokio::test] -async fn recommended_plugin_candidates_filter_installed_and_disabled_plugins() { - let tmp = tempfile::tempdir().unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/ps/plugins/suggested/codex")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "enabled": true, - "plugins": [ - { - "id": "plugin_linear", - "name": "linear", - "display_name": "Linear" - }, - { - "id": "plugin_github", - "name": "github", - "display_name": "GitHub" - }, - { - "id": "plugin_slack", - "name": "slack", - "display_name": "Slack" - } - ] - }))) - .expect(1) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = server.uri(); - let manager = test_plugins_manager(tmp.path().to_path_buf()); - let mut installed_linear = remote_installed_plugin("linear"); - installed_linear.id = "plugin_linear".to_string(); - manager.write_remote_installed_plugins_cache(vec![installed_linear]); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let disabled_tools = [ToolSuggestDisabledTool::plugin( - "github@openai-curated-remote", - )]; - let loaded_plugins = manager.plugins_for_config(&config).await; - - let candidates = manager - .recommended_plugin_candidates_for_config(RecommendedPluginCandidatesInput { - plugins_config: &config, - loaded_plugins: &loaded_plugins, - auth: Some(&auth), - disabled_tools: &disabled_tools, - app_server_client_name: None, - }) - .await; - - assert_eq!( - candidates, - Some(vec![DiscoverableTool::from(DiscoverablePluginInfo { - id: "slack@openai-curated-remote".to_string(), - remote_plugin_id: Some("plugin_slack".to_string()), - name: "Slack".to_string(), - description: None, - has_skills: false, - mcp_server_names: Vec::new(), - app_connector_ids: Vec::new(), - })]) - ); -} - -#[tokio::test] -async fn recommended_plugins_mode_caches_explicit_false() { - let tmp = tempfile::tempdir().unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/ps/plugins/suggested/codex")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "enabled": false, - "plugins": [] - }))) - .expect(1) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = server.uri(); - let manager = test_plugins_manager(tmp.path().to_path_buf()); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - assert_eq!( - manager - .recommended_plugins_mode_for_config(&config, Some(&auth)) - .await, - RecommendedPluginsMode::Legacy - ); - assert_eq!( - manager - .recommended_plugins_mode_for_config(&config, Some(&auth)) - .await, - RecommendedPluginsMode::Legacy - ); -} - -#[tokio::test] -async fn recommended_plugins_mode_retries_after_fetch_failure() { - let tmp = tempfile::tempdir().unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/ps/plugins/suggested/codex")) - .respond_with(ResponseTemplate::new(500).set_body_string("unavailable")) - .expect(1) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = server.uri(); - let manager = test_plugins_manager(tmp.path().to_path_buf()); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - assert_eq!( - manager - .recommended_plugins_mode_for_config(&config, Some(&auth)) - .await, - RecommendedPluginsMode::Legacy - ); - - server.reset().await; - Mock::given(method("GET")) - .and(path("/ps/plugins/suggested/codex")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "enabled": true, - "plugins": [] - }))) - .expect(1) - .mount(&server) - .await; - - assert_eq!( - manager - .recommended_plugins_mode_for_config(&config, Some(&auth)) - .await, - RecommendedPluginsMode::Endpoint { - plugins: Vec::new() - } - ); -} - #[test] fn refresh_curated_plugin_cache_replaces_existing_local_version_with_short_sha_version() { let tmp = tempfile::tempdir().unwrap(); @@ -7488,386 +7025,6 @@ fn remote_installed_plugins_cache_refresh_coalesces_materializations() { ); } -#[tokio::test] -async fn background_remote_installed_bundle_sync_stays_deduped() { - let codex_home = TempDir::new().unwrap(); - write_file( - &codex_home.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -remote_plugin = true -"#, - ); - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("includeDownloadUrls", "true")) - .respond_with( - ResponseTemplate::new(200) - .set_delay(Duration::from_millis(200)) - .set_body_json(serde_json::json!({ - "plugins": [], - "pagination": {"next_page_token": null}, - })), - ) - .expect(1) - .mount(&server) - .await; - - let mut config = load_config(codex_home.path(), codex_home.path()).await; - config.chatgpt_base_url = format!("{}/backend-api", server.uri()); - let first_manager = std::sync::Arc::new(test_plugins_manager_with_options( - codex_home.path().to_path_buf(), - Some(Product::Codex), - Some(AuthMode::Chatgpt), - )); - let second_manager = std::sync::Arc::new(test_plugins_manager_with_options( - codex_home.path().to_path_buf(), - Some(Product::Codex), - Some(AuthMode::Chatgpt), - )); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - first_manager.maybe_start_remote_installed_plugin_bundle_sync( - &config, - Some(auth.clone()), - /*on_effective_plugins_changed*/ None, - ); - second_manager.maybe_start_remote_installed_plugin_bundle_sync( - &config, - Some(auth), - /*on_effective_plugins_changed*/ None, - ); - - let _guard = first_manager - .acquire_remote_installed_plugin_sync_guard() - .await - .expect("background bundle sync should finish"); - server.verify().await; -} - -#[tokio::test] -async fn reconcile_remote_installed_plugins_reports_cached_state_changes() { - let codex_home = TempDir::new().unwrap(); - write_file( - &codex_home.path().join(CONFIG_TOML_FILE), - "[features]\nplugins = true\n", - ); - write_cached_plugin( - codex_home.path(), - REMOTE_WORKSPACE_MARKETPLACE_NAME, - "linear", - ); - let plugin_root = codex_home - .path() - .join("plugins/cache/workspace-directory/linear/local"); - write_file( - &plugin_root.join(".mcp.json"), - r#"{"mcpServers":{"example":{"command":"unused"}}}"#, - ); - write_file( - &plugin_root.join("hooks/hooks.json"), - r#"{"hooks":{"UserPromptSubmit":[{"hooks":[{"type":"command","command":"echo hook"}]}]}}"#, - ); - let server = MockServer::start().await; - let mut config = load_config(codex_home.path(), codex_home.path()).await; - config.chatgpt_base_url = format!("{}/backend-api", server.uri()); - let auth_manager = test_auth_manager(Some(AuthMode::Chatgpt)); - let auth = auth_manager.auth_cached().expect("test ChatGPT auth"); - let manager = test_plugins_manager_with_auth_manager( - codex_home.path().to_path_buf(), - Some(Product::Codex), - auth_manager, - ); - let change = RemotePluginChange { - plugin_id: "linear@workspace-directory".to_string(), - capabilities: RemotePluginCapabilities { - has_mcps: true, - has_hooks: true, - has_skills: true, - ..Default::default() - }, - }; - // None represents an uninstall. Reinstalling its retained bundle must report an - // activation even though the known previous snapshot has no entry for the plugin. - for (enabled, changes) in [ - (Some(true), Vec::new()), - (Some(false), vec![change.clone()]), - (Some(false), Vec::new()), - (Some(true), vec![change.clone()]), - (None, vec![change.clone()]), - (Some(true), vec![change.clone()]), - (Some(true), Vec::new()), - ] { - if enabled.is_none() { - // Fail cleanup before it reaches the bundle; removal hints must survive. - write_file( - &codex_home - .path() - .join("plugins/cache/openai-curated-remote"), - "not a directory", - ); - } - let plugins = enabled - .into_iter() - .map(|enabled| { - serde_json::json!({ - "id": "plugins~Plugin_linear", - "name": "linear", - "scope": "WORKSPACE", - "discoverability": "LISTED", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "release": { - "version": "local", - "display_name": "Linear", - "description": "Test plugin", - "interface": {}, - }, - "enabled": enabled, - }) - }) - .collect::>(); - // No download URL: every installed pass must reuse the cached version. - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("includeDownloadUrls", "true")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "plugins": plugins, - "pagination": { "next_page_token": null }, - }))) - .expect(1) - .mount(&server) - .await; - assert_eq!( - manager - .reconcile_remote_installed_plugins(&config, Some(&auth)) - .await - .expect("reconcile cached plugin state"), - RemoteInstalledPluginBundleSyncOutcome { - changed_plugins: changes, - ..Default::default() - } - ); - assert!(plugin_root.exists()); - if enabled.is_none() { - assert_eq!( - manager.plugins_for_config(&config).await, - PluginLoadOutcome::default() - ); - } - server.verify().await; - server.reset().await; - } -} - -#[tokio::test] -async fn reconcile_remote_installed_plugins_rejects_incomplete_snapshot_without_cleanup() { - let codex_home = TempDir::new().unwrap(); - write_file( - &codex_home.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -remote_plugin = true -"#, - ); - write_cached_plugin(codex_home.path(), REMOTE_GLOBAL_MARKETPLACE_NAME, "linear"); - write_cached_plugin( - codex_home.path(), - REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME, - "malformed", - ); - write_cached_plugin( - codex_home.path(), - REMOTE_WORKSPACE_MARKETPLACE_NAME, - "renamed-malformed", - ); - let malformed_remote_plugin_id = "plugins~Plugin_malformed"; - let malformed_plugin_id = PluginId::new( - "malformed".to_string(), - REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME.to_string(), - ) - .expect("valid malformed plugin id"); - PluginStore::new(codex_home.path().to_path_buf()) - .write_remote_plugin_id(&malformed_plugin_id, malformed_remote_plugin_id) - .expect("persist malformed plugin identity"); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("includeDownloadUrls", "true")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "plugins": [ - { - "id": "plugins~Plugin_linear", - "name": "linear", - "scope": "GLOBAL", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "status": "ENABLED", - "release": { - "version": "local", - "display_name": "", - "description": "Track work", - "interface": {}, - }, - "enabled": true, - }, - { - "id": malformed_remote_plugin_id, - "name": "renamed-malformed", - "scope": "WORKSPACE", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "status": "ENABLED", - "release": { - "version": "local", - "display_name": "Malformed", - "description": "Missing discoverability", - "interface": {}, - }, - "enabled": true, - }, - ], - "pagination": {"next_page_token": null}, - }))) - .expect(1) - .mount(&server) - .await; - - let mut config = load_config(codex_home.path(), codex_home.path()).await; - config.chatgpt_base_url = format!("{}/backend-api", server.uri()); - let auth_manager = test_auth_manager(Some(AuthMode::Chatgpt)); - let auth = auth_manager.auth_cached().expect("test ChatGPT auth"); - let manager = std::sync::Arc::new(test_plugins_manager_with_auth_manager( - codex_home.path().to_path_buf(), - Some(Product::Codex), - auth_manager, - )); - let mut previous_malformed = remote_installed_plugin_in_marketplace( - "malformed", - REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME, - ); - previous_malformed.id = malformed_remote_plugin_id.to_string(); - previous_malformed.version = Some("local".to_string()); - previous_malformed.enabled = false; - manager.write_remote_installed_plugins_cache(vec![previous_malformed.clone()]); - - let result = manager - .reconcile_remote_installed_plugins(&config, Some(&auth)) - .await; - - assert!(matches!( - result, - Err(RemoteInstalledPluginBundleSyncError::Catalog( - RemotePluginCatalogError::UnexpectedResponse(_) - )) - )); - server.verify().await; - assert_eq!( - manager - .remote_installed_plugins_cache - .read() - .expect("installed plugin cache lock") - .plugins - .clone(), - Some(vec![previous_malformed]) - ); - let plugin_cache_root = codex_home.path().join("plugins/cache"); - let renamed_malformed_cache = plugin_cache_root - .join(REMOTE_WORKSPACE_MARKETPLACE_NAME) - .join("renamed-malformed"); - let previous_malformed_cache = plugin_cache_root - .join(REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME) - .join("malformed"); - let linear_metadata = plugin_cache_root - .join(REMOTE_GLOBAL_MARKETPLACE_NAME) - .join("linear") - .join(".codex-remote-plugin-install.json"); - assert!(renamed_malformed_cache.exists()); - assert!(previous_malformed_cache.exists()); - assert!(!linear_metadata.exists()); -} - -#[tokio::test] -async fn failed_installed_plugin_pagination_preserves_inventory_and_releases_mutation_gate() { - let codex_home = TempDir::new().unwrap(); - write_file( - &codex_home.path().join(CONFIG_TOML_FILE), - "[features]\nplugins = true\nremote_plugin = true\n", - ); - write_cached_plugin( - codex_home.path(), - REMOTE_GLOBAL_MARKETPLACE_NAME, - "retained", - ); - let server = MockServer::start().await; - // Both bundle sync and its metadata fallback must reject the incomplete inventory. - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "plugins": [], - "pagination": {"next_page_token": "next"}, - }))) - .expect(4) - .mount(&server) - .await; - let mut config = load_config(codex_home.path(), codex_home.path()).await; - config.chatgpt_base_url = format!("{}/backend-api", server.uri()); - let auth_manager = test_auth_manager(Some(AuthMode::Chatgpt)); - let auth = auth_manager.auth_cached().expect("test ChatGPT auth"); - let manager = Arc::new(test_plugins_manager_with_auth_manager( - codex_home.path().to_path_buf(), - Some(Product::Codex), - auth_manager, - )); - let previous_inventory = vec![remote_installed_plugin("retained")]; - manager.write_remote_installed_plugins_cache(previous_inventory.clone()); - - manager.maybe_start_remote_installed_plugin_bundle_sync( - &config, - Some(auth), - /*on_effective_plugins_changed*/ None, - ); - // Starting the sync acquires the gate synchronously, so this waits for its release. - let _guard = tokio::time::timeout( - Duration::from_secs(5), - manager.acquire_remote_installed_plugin_sync_guard(), - ) - .await - .expect("failed pagination should promptly release the mutation gate") - .expect("mutation gate should remain available"); - tokio::time::timeout(Duration::from_secs(5), async { - while manager - .remote_installed_plugins_cache_refresh_state - .read() - .expect("refresh state lock") - .in_flight - { - tokio::task::yield_now().await; - } - }) - .await - .expect("fallback metadata refresh should finish"); - - assert_eq!( - manager - .remote_installed_plugins_cache - .read() - .expect("installed cache lock") - .plugins - .clone(), - Some(previous_inventory), - ); - assert!( - codex_home - .path() - .join("plugins/cache/openai-curated-remote/retained") - .exists() - ); - server.verify().await; -} - #[test] fn reconciliation_fences_refresh_publication_and_recovers_after_cancellation() { let codex_home = TempDir::new().unwrap(); diff --git a/codex-rs/core-plugins/src/plugin_bundle_archive.rs b/codex-rs/core-plugins/src/plugin_bundle_archive.rs index 0063510d..2722620c 100644 --- a/codex-rs/core-plugins/src/plugin_bundle_archive.rs +++ b/codex-rs/core-plugins/src/plugin_bundle_archive.rs @@ -1,31 +1,11 @@ -use crate::manifest::load_plugin_manifest; -use flate2::Compression; use flate2::read::GzDecoder; -use flate2::write::GzEncoder; -use std::fmt; use std::fs; use std::io; use std::io::Read; -use std::io::Write; use std::path::Path; use std::path::PathBuf; use tar::Archive; -#[derive(Debug, thiserror::Error)] -pub(crate) enum PluginBundlePackError { - #[error("invalid plugin path `{path}`: {reason}")] - InvalidPluginPath { path: PathBuf, reason: String }, - - #[error("plugin archive would be {bytes} bytes, exceeding maximum size of {max_bytes} bytes")] - ArchiveTooLarge { bytes: usize, max_bytes: usize }, - - #[error("failed to archive plugin bundle: {source}")] - Io { - #[source] - source: io::Error, - }, -} - #[derive(Debug, thiserror::Error)] pub(crate) enum PluginBundleUnpackError { #[error( @@ -50,80 +30,6 @@ impl PluginBundleUnpackError { } } -pub(crate) fn pack_plugin_bundle_tar_gz( - plugin_path: &Path, - max_bytes: usize, -) -> Result, PluginBundlePackError> { - if !plugin_path.is_dir() { - return Err(PluginBundlePackError::InvalidPluginPath { - path: plugin_path.to_path_buf(), - reason: "expected a plugin directory".to_string(), - }); - } - if !plugin_path.join(".codex-plugin/plugin.json").is_file() - && load_plugin_manifest(plugin_path).is_none() - { - return Err(PluginBundlePackError::InvalidPluginPath { - path: plugin_path.to_path_buf(), - reason: "missing .codex-plugin/plugin.json or valid Agent Plugin manifest".to_string(), - }); - } - - let encoder = GzEncoder::new(SizeLimitedBuffer::new(max_bytes), Compression::default()); - let mut archive = tar::Builder::new(encoder); - append_plugin_tree(&mut archive, plugin_path, plugin_path).map_err(archive_io_error)?; - let encoder = archive.into_inner().map_err(archive_io_error)?; - encoder - .finish() - .map(SizeLimitedBuffer::into_inner) - .map_err(archive_io_error) -} - -fn append_plugin_tree( - archive: &mut tar::Builder, - plugin_root: &Path, - current: &Path, -) -> io::Result<()> { - let mut entries = fs::read_dir(current)?.collect::, io::Error>>()?; - entries.sort_by_key(fs::DirEntry::file_name); - for entry in entries { - let path = entry.path(); - let file_type = entry.file_type()?; - let relative_path = path.strip_prefix(plugin_root).map_err(|err| { - io::Error::other(format!( - "failed to compute plugin archive path for `{}`: {err}", - path.display() - )) - })?; - if file_type.is_dir() { - archive.append_dir(relative_path, &path)?; - append_plugin_tree(archive, plugin_root, &path)?; - } else if file_type.is_file() { - archive.append_path_with_name(&path, relative_path)?; - } else { - return Err(io::Error::other(format!( - "unsupported plugin archive entry type: {}", - path.display() - ))); - } - } - Ok(()) -} - -fn archive_io_error(source: io::Error) -> PluginBundlePackError { - if let Some(limit) = source - .get_ref() - .and_then(|err| err.downcast_ref::()) - { - return PluginBundlePackError::ArchiveTooLarge { - bytes: limit.bytes, - max_bytes: limit.max_bytes, - }; - } - - PluginBundlePackError::Io { source } -} - pub(crate) fn unpack_plugin_bundle_tar_gz( bytes: &[u8], destination: &Path, @@ -257,66 +163,3 @@ fn enforce_total_extracted_size( Ok(()) } -struct SizeLimitedBuffer { - bytes: Vec, - max_bytes: usize, -} - -impl SizeLimitedBuffer { - fn new(max_bytes: usize) -> Self { - Self { - bytes: Vec::new(), - max_bytes, - } - } - - fn into_inner(self) -> Vec { - self.bytes - } -} - -impl Write for SizeLimitedBuffer { - fn write(&mut self, buf: &[u8]) -> io::Result { - let next_len = self.bytes.len().checked_add(buf.len()).ok_or_else(|| { - io::Error::other(ArchiveSizeLimitExceeded { - bytes: usize::MAX, - max_bytes: self.max_bytes, - }) - })?; - if next_len > self.max_bytes { - return Err(io::Error::other(ArchiveSizeLimitExceeded { - bytes: next_len, - max_bytes: self.max_bytes, - })); - } - - self.bytes.extend_from_slice(buf); - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -#[derive(Debug)] -struct ArchiveSizeLimitExceeded { - bytes: usize, - max_bytes: usize, -} - -impl fmt::Display for ArchiveSizeLimitExceeded { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "archive would be {} bytes, exceeding maximum size of {} bytes", - self.bytes, self.max_bytes - ) - } -} - -impl std::error::Error for ArchiveSizeLimitExceeded {} - -#[cfg(test)] -#[path = "plugin_bundle_archive_tests.rs"] -mod tests; diff --git a/codex-rs/core-plugins/src/plugin_bundle_archive_tests.rs b/codex-rs/core-plugins/src/plugin_bundle_archive_tests.rs deleted file mode 100644 index aa77c466..00000000 --- a/codex-rs/core-plugins/src/plugin_bundle_archive_tests.rs +++ /dev/null @@ -1,41 +0,0 @@ -use super::*; -use tempfile::tempdir; - -#[test] -fn portable_root_manifest_can_be_packed_and_unpacked() { - let source = tempdir().expect("source tempdir"); - fs::write( - source.path().join("plugin.json"), - r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"portable"}"#, - ) - .expect("write portable manifest"); - fs::create_dir_all(source.path().join("skills/demo")).expect("create skill directory"); - fs::write(source.path().join("skills/demo/SKILL.md"), "# Demo\n").expect("write skill"); - - let archive = - pack_plugin_bundle_tar_gz(source.path(), 1024 * 1024).expect("pack portable plugin"); - let destination = tempdir().expect("destination tempdir"); - unpack_plugin_bundle_tar_gz(&archive, destination.path(), 1024 * 1024) - .expect("unpack portable plugin"); - - assert!(destination.path().join("plugin.json").is_file()); - assert!(destination.path().join("skills/demo/SKILL.md").is_file()); -} - -#[test] -fn invalid_portable_manifest_is_rejected_before_packing() { - let source = tempdir().expect("source tempdir"); - fs::write( - source.path().join("plugin.json"), - r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"UPPER"}"#, - ) - .expect("write invalid portable manifest"); - - let error = pack_plugin_bundle_tar_gz(source.path(), 1024 * 1024) - .expect_err("invalid Agent Plugin manifest should fail"); - - assert!(matches!( - error, - PluginBundlePackError::InvalidPluginPath { .. } - )); -} diff --git a/codex-rs/core-plugins/src/plugin_measurement_catalog.rs b/codex-rs/core-plugins/src/plugin_measurement_catalog.rs deleted file mode 100644 index dc1400f3..00000000 --- a/codex-rs/core-plugins/src/plugin_measurement_catalog.rs +++ /dev/null @@ -1,63 +0,0 @@ -//! Selects one authenticated installed GLOBAL plugin without capability loading. - -use super::*; -use crate::store::validate_plugin_version_segment; -use codex_utils_path_uri::PathConvention; - -/// Fetches installation authorization and download metadata, but materializes no -/// other installed plugins and never publishes to the shared plugin catalog. -pub(crate) async fn fetch_measurement_reference_bundle( - config: &RemotePluginServiceConfig, - auth: &CodexAuth, - target: &crate::script_attribution::PluginMeasurementTarget, -) -> anyhow::Result> { - ensure_chatgpt_auth(Some(auth))?; - let installed = fetch_installed_plugins( - config, - auth, - RemoteInstalledPluginScope::Single(RemotePluginScope::Global), - /*include_download_urls*/ true, - InstalledPluginDisplayAssets::Include, - ) - .await?; - let mut matching = installed.into_iter().filter(|installed| { - let plugin = &installed.plugin; - let Some(version) = plugin.release.version.as_deref().map(str::trim) else { - return false; - }; - if validate_plugin_version_segment(version).is_err() { - return false; - } - // Compare with the executor's path rules, retaining the catalog's - // spelling for the validated bundle and cache identity below. - let matches_target = match target.path_convention { - PathConvention::Windows => target - .plugin_id - .plugin_name - .eq_ignore_ascii_case(&plugin.name), - PathConvention::Posix => target.plugin_id.plugin_name == plugin.name, - }; - installed.enabled - && plugin.scope == RemotePluginScope::Global - && matches_target - && plugin.availability == PluginAvailability::Available - && plugin.installation_policy != PluginInstallPolicy::NotAvailable - && plugin.disabled_reason.is_none() - }); - let Some(installed) = matching.next() else { - return Ok(None); - }; - if matching.next().is_some() { - return Ok(None); - } - let plugin = installed.plugin; - let bundle = crate::remote_bundle::validate_remote_plugin_bundle( - &plugin.id, - REMOTE_GLOBAL_MARKETPLACE_NAME, - &plugin.name, - plugin.release.version.as_deref(), - plugin.release.bundle_download_url.as_deref(), - plugin.release.app_manifest, - )?; - Ok(Some((plugin.id, bundle))) -} diff --git a/codex-rs/core-plugins/src/plugin_measurement_references.rs b/codex-rs/core-plugins/src/plugin_measurement_references.rs deleted file mode 100644 index 4d3a8dce..00000000 --- a/codex-rs/core-plugins/src/plugin_measurement_references.rs +++ /dev/null @@ -1,244 +0,0 @@ -//! Authenticated, immutable references for one executor plugin's measurements. - -use crate::PluginsConfigInput; -use crate::TrustedPluginRoots; -use crate::manager::RemoteInstalledPluginsAuthIdentity; -use crate::remote::fetch_measurement_reference_bundle; -use crate::remote_bundle::download_remote_plugin_bundle; -use crate::remote_bundle::install_remote_plugin_bundle; -use crate::script_attribution::PluginMeasurementTarget; -use codex_features::RuntimeAuthMode; -use codex_login::CodexAuth; -use codex_plugin::PluginId; -use codex_runtime_agent_instance::RuntimeAuthSlot; -use codex_utils_path_uri::PathConvention; -use std::sync::Arc; -use tempfile::TempDir; -use tokio::sync::Mutex; -use tokio::sync::watch; - -const MAX_CACHED_REFERENCES: usize = 4; - -/// Owns the immutable files backing its roots. Keep the reference alive for the -/// full command/turn that consumes those roots, including asynchronous commands. -pub struct PluginMeasurementReference { - roots: TrustedPluginRoots, - home: Option, -} - -impl Drop for PluginMeasurementReference { - fn drop(&mut self) { - let Some(home) = self.home.take() else { - return; - }; - if let Ok(runtime) = tokio::runtime::Handle::try_current() { - runtime.spawn_blocking(move || drop(home)); - } else { - drop(home); - } - } -} - -impl PluginMeasurementReference { - pub fn roots(&self) -> &TrustedPluginRoots { - &self.roots - } -} - -#[derive(PartialEq, Eq)] -struct ReferenceKey { - actor: RemoteInstalledPluginsAuthIdentity, - endpoint: String, - remote_id: String, - plugin_id: PluginId, - version: String, -} - -type ReferenceCell = Arc>>>; - -fn is_preparing(cell: &ReferenceCell) -> bool { - cell.has_changed().is_ok() && cell.borrow().is_none() -} - -/// A thread-scoped cache, separate from the installed plugin/capability store. -/// Each version has its own store so installing a new version cannot remove -/// files still leased by an earlier turn. At most four entries are retained, -/// including active preparations; command-held leases can outlive eviction. -#[derive(Default)] -pub struct RemotePluginMeasurementCache { - references: Mutex>, -} - -impl RemotePluginMeasurementCache { - pub fn new() -> Self { - Self::default() - } - - /// Rechecks current installation authorization, then prepares only the - /// requested version. Previously authenticated versions remain reusable after - /// a release update; a cache miss can download only the current release. - /// Callers apply analytics consent and product gates. - /// Concurrent callers share a download even if one caller is cancelled. - /// Returns no reference when all cache entries are actively preparing. - /// Failures omit authenticated URLs and response bodies from diagnostics. - pub async fn prepare( - &self, - config: &PluginsConfigInput, - auth: &CodexAuth, - target: &PluginMeasurementTarget, - runtime_auth: Option<(RuntimeAuthSlot, RuntimeAuthMode)>, - ) -> anyhow::Result>> { - if !config.plugins_enabled || !config.remote_plugin_enabled || !auth.uses_codex_backend() { - return Ok(None); - } - // Like normal remote loading, the authenticated installed catalog is - // authoritative for enabled state, including default installations. - // GLOBAL plugins have already passed server-side admission; local - // marketplace product policy and skill capability loading are separate. - let service = config - .remote_plugin_service_config(runtime_auth) - .for_current_account(); - let Some((remote_id, bundle)) = fetch_measurement_reference_bundle(&service, auth, target) - .await - .map_err(|_| anyhow::anyhow!("plugin measurement catalog lookup failed"))? - else { - return Ok(None); - }; - // The executor hint follows its filesystem's case rules. The cache and - // local store use the authenticated bundle's exact identity instead. - let plugin_id = bundle.plugin_id.clone(); - let version = bundle.plugin_version.clone(); - let current_version = match target.path_convention { - PathConvention::Windows => target.version.eq_ignore_ascii_case(&version), - PathConvention::Posix => target.version == version, - }; - let key = ReferenceKey { - actor: RemoteInstalledPluginsAuthIdentity::from_auth(Some(auth)), - endpoint: config.chatgpt_base_url.clone(), - remote_id: remote_id.clone(), - plugin_id: plugin_id.clone(), - version: if current_version { - version.clone() - } else { - target.version.clone() - }, - }; - let (cell, initializer, retired) = { - let mut references = self.references.lock().await; - let mut retired = Vec::new(); - // Keep active preparations admitted until they finish, even after an - // identity change; they can never match the new key. - for index in (0..references.len()).rev() { - let (existing, cell) = &references[index]; - // A closed, empty result is a completed failure. Only a new - // caller can admit a retry; existing waiters observe that failure. - if (cell.has_changed().is_err() && cell.borrow().is_none()) - || (!is_preparing(cell) - && (existing.actor != key.actor - || existing.endpoint != key.endpoint - || (existing.plugin_id == key.plugin_id - && existing.remote_id != key.remote_id))) - { - retired.push(references.remove(index)); - } - } - let mut initializer = None; - let mut matching = references.iter().enumerate().filter(|(_, (existing, _))| { - if current_version { - return existing == &key; - } - existing.actor == key.actor - && existing.endpoint == key.endpoint - && existing.remote_id == key.remote_id - && existing.plugin_id == key.plugin_id - && match target.path_convention { - PathConvention::Windows => { - existing.version.eq_ignore_ascii_case(&key.version) - } - PathConvention::Posix => existing.version == key.version, - } - }); - // Historical Windows hints must not select between case-distinct releases. - let cached_index = match (matching.next(), matching.next()) { - (Some((index, _)), None) => Some(index), - _ => None, - }; - let cell = if let Some(index) = cached_index { - let entry = references.remove(index); - let cell = Arc::clone(&entry.1); - references.push(entry); - Some(cell) - } else if !current_version { - // The catalog cannot supply a trusted historical bundle. - None - } else if references.len() < MAX_CACHED_REFERENCES { - let (sender, receiver) = watch::channel(None); - let cell = Arc::new(receiver); - initializer = Some(sender); - references.push((key, Arc::clone(&cell))); - Some(cell) - } else if let Some(index) = references.iter().position(|(_, cell)| !is_preparing(cell)) - { - retired.push(references.remove(index)); - let (sender, receiver) = watch::channel(None); - let cell = Arc::new(receiver); - initializer = Some(sender); - references.push((key, Arc::clone(&cell))); - Some(cell) - } else { - None - }; - (cell, initializer, retired) - }; - // Final reference drops schedule store cleanup outside the cache mutex. - drop(retired); - let Some(cell) = cell else { - return Ok(None); - }; - if let Some(sender) = initializer { - // The cache keeps the receiver alive when individual callers cancel. - // Once the cache and all callers disappear, stop waiting/downloading. - tokio::spawn(async move { - let reference = tokio::select! { - biased; - _ = sender.closed() => return, - reference = async { - let bytes = download_remote_plugin_bundle(&service, &bundle).await?; - // Blocking extraction cannot be aborted once started. Its - // owner must keep the store alive even if this task stops. - tokio::task::spawn_blocking(move || { - let home = tempfile::tempdir()?; - install_remote_plugin_bundle(home.path().to_owned(), bundle, bytes)?; - let roots = TrustedPluginRoots::from_measurement_reference( - home.path(), - &plugin_id, - &version, - &remote_id, - ) - .ok_or_else(|| anyhow::anyhow!("invalid plugin measurement reference"))?; - Ok::<_, anyhow::Error>(Arc::new(PluginMeasurementReference { - roots, - home: Some(home), - })) - }).await? - } => reference, - }; - if let Ok(reference) = reference { - sender.send_replace(Some(reference)); - } - // Closing an empty channel reports failure without retaining - // authenticated URLs or response bodies in the shared result. - }); - } - let mut receiver = cell.as_ref().clone(); - let reference = receiver - .wait_for(Option::is_some) - .await - .map_err(|_| anyhow::anyhow!("plugin measurement preparation failed"))?; - Ok(reference.clone()) - } -} - -#[cfg(test)] -#[path = "plugin_measurement_references_tests.rs"] -mod tests; diff --git a/codex-rs/core-plugins/src/plugin_measurement_references_tests.rs b/codex-rs/core-plugins/src/plugin_measurement_references_tests.rs deleted file mode 100644 index 6902fcf7..00000000 --- a/codex-rs/core-plugins/src/plugin_measurement_references_tests.rs +++ /dev/null @@ -1,775 +0,0 @@ -//! Real bundle preparation tests without mutating the parent test environment. - -use super::*; -use crate::test_support::load_plugins_config; -use crate::test_support::write_file; -use anyhow::Context; -use anyhow::Result; -use codex_exec_server::LOCAL_FS; -use codex_utils_path_uri::PathConvention; -use codex_utils_path_uri::PathUri; -use flate2::Compression; -use flate2::write::GzEncoder; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use std::path::Path; -use std::process::Command; -use std::time::Duration; -use tokio::io::AsyncBufReadExt; -use tokio::io::AsyncReadExt; -use tokio::io::AsyncWriteExt; -use tokio::sync::Semaphore; -use tokio::sync::mpsc; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; - -const SCRIPT: &str = "console.log('installed');\n"; -const ANALYTICS: &str = "version: 1\noperations:\n install:\n path: scripts/install.mjs\n measurements:\n duration_ms:\n dimensions:\n outcome: [success, error]\n"; - -fn isolated_bundle_test(name: &str) -> Result { - const CHILD: &str = "CODEX_MEASUREMENT_REFERENCE_TEST"; - if std::env::var(CHILD).as_deref() == Ok(name) { - return Ok(true); - } - let output = Command::new(std::env::current_exe()?) - .args([ - "--exact", - &format!("plugin_measurement_references::tests::{name}"), - "--nocapture", - ]) - .env(CHILD, name) - .env("CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS", "1") - .output()?; - assert!( - output.status.success(), - "{}\n{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); - Ok(false) -} - -fn installed(server: &MockServer, version: &str) -> Value { - json!({ - "id": "plugins~sites", "name": "sites", "scope": "GLOBAL", "enabled": true, - "installation_policy": "AVAILABLE", "authentication_policy": "ON_USE", "status": "ENABLED", - "release": {"version": version, "display_name": "Sites", "description": "", - "bundle_download_url": format!("{}/bundle/{version}", server.uri()), "interface": {}} - }) -} - -async fn catalog(server: &MockServer, plugins: Vec) { - Mock::given(method("GET")) - .and(path("/ps/plugins/installed")) - .and(query_param("scope", "GLOBAL")) - .and(query_param("includeDownloadUrls", "true")) - .respond_with( - ResponseTemplate::new(200).set_body_json(json!({"plugins": plugins, "pagination": {}})), - ) - .mount(server) - .await; -} - -fn archive(plugin_name: &str) -> Result> { - let mut archive = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::default())); - let manifest = json!({"name": plugin_name, "version": "1.0.0"}).to_string(); - for (name, bytes) in [ - (".codex-plugin/plugin.json", manifest.as_str()), - ("scripts/install.mjs", SCRIPT), - ("analytics.yaml", ANALYTICS), - // Invalid capability files must not be parsed by measurement preparation. - (".mcp.json", "invalid json"), - ("skills/broken/SKILL.md", "invalid skill"), - ] { - let mut header = tar::Header::new_gnu(); - header.set_size(bytes.len() as u64); - header.set_mode(0o644); - header.set_cksum(); - archive.append_data(&mut header, name, bytes.as_bytes())?; - } - Ok(archive.into_inner()?.finish()?) -} - -async fn bundle(server: &MockServer, version: &str, count: u64) -> Result<()> { - Mock::given(method("GET")) - .and(path(format!("/bundle/{version}"))) - .respond_with(ResponseTemplate::new(200).set_body_bytes(archive("sites")?)) - .expect(count) - .mount(server) - .await; - Ok(()) -} - -async fn wait_until_removed(path: &Path) -> Result<()> { - tokio::time::timeout(Duration::from_secs(5), async { - while path.exists() { - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await?; - Ok(()) -} - -fn named_plugin(server: &MockServer, name: &str) -> Result<(Value, PluginMeasurementTarget)> { - let mut plugin = installed(server, "1.0.0"); - plugin["name"] = json!(name); - plugin["id"] = json!(format!("plugins~{name}")); - plugin["release"]["bundle_download_url"] = json!(format!("{}/bundle/{name}", server.uri())); - let target = PluginMeasurementTarget { - plugin_id: PluginId::new(name.to_owned(), "openai-curated-remote".to_owned())?, - version: "1.0.0".to_owned(), - path_convention: PathConvention::Posix, - }; - Ok((plugin, target)) -} - -async fn target( - executor: &Path, - version: &str, -) -> Result<(PluginMeasurementTarget, Vec, PathUri)> { - let script = executor.join(format!( - "plugins/cache/openai-curated-remote/sites/{version}/scripts/install.mjs" - )); - write_file(&script, SCRIPT); - let command = vec!["node".to_owned(), script.to_string_lossy().into_owned()]; - let cwd = PathUri::from_host_native_path(executor)?; - let target = PluginMeasurementTarget::from_command(&command, &cwd, LOCAL_FS.as_ref()) - .await - .context("canonical plugin target")?; - Ok((target, command, cwd)) -} - -struct Fixture { - server: MockServer, - home: TempDir, - executor: TempDir, - config: PluginsConfigInput, - auth: CodexAuth, - cache: RemotePluginMeasurementCache, -} - -impl Fixture { - async fn new() -> Result { - let server = MockServer::start().await; - let home = tempfile::tempdir()?; - let executor = tempfile::tempdir()?; - let mut config = load_plugins_config(home.path(), executor.path()).await; - config.chatgpt_base_url = server.uri(); - Ok(Self { - server, - home, - executor, - config, - auth: CodexAuth::create_dummy_chatgpt_auth_for_testing(), - cache: RemotePluginMeasurementCache::new(), - }) - } - - async fn prepare( - &self, - target: &PluginMeasurementTarget, - ) -> Result>> { - self.cache - .prepare(&self.config, &self.auth, target, /*runtime_auth*/ None) - .await - } - - async fn assert_request_count(&self, expected: usize) { - assert_eq!( - self.server - .received_requests() - .await - .expect("requests") - .len(), - expected - ); - } - - async fn wait_for_cached_reference( - &self, - ready: impl Fn(&ReferenceCell) -> bool, - ) -> Result<()> { - tokio::time::timeout(Duration::from_secs(5), async { - loop { - let is_ready = { - let references = self.cache.references.lock().await; - ready(&references[0].1) - }; - if is_ready { - break; - } - tokio::task::yield_now().await; - } - }) - .await?; - Ok(()) - } -} - -#[tokio::test] -async fn narrow_preparation_reuses_versions_and_keeps_old_leases_alive() -> Result<()> { - if !isolated_bundle_test("narrow_preparation_reuses_versions_and_keeps_old_leases_alive")? { - return Ok(()); - } - let mut f = Fixture::new().await?; - let (first, command, cwd) = target(f.executor.path(), "1.0.0").await?; - let mut unrelated = installed(&f.server, "1.0.0"); - unrelated["id"] = json!("plugins~unrelated"); - unrelated["name"] = json!("unrelated"); - unrelated["release"]["bundle_download_url"] = json!("invalid URL must never be examined"); - catalog(&f.server, vec![unrelated, installed(&f.server, "1.0.0")]).await; - bundle(&f.server, "1.0.0", /*count*/ 1).await?; - let (left, right) = tokio::join!(f.prepare(&first), f.prepare(&first)); - let first_ref = left?.context("first reference")?; - assert!(Arc::ptr_eq( - &first_ref, - &right?.context("parallel reference")? - )); - let warm = f.prepare(&first).await?.context("warm reference")?; - assert!(Arc::ptr_eq(&first_ref, &warm)); - let old_home = first_ref - .home - .as_ref() - .expect("reference store") - .path() - .to_owned(); - let resolved = first_ref - .roots() - .resolve_metrics_operation_in_filesystem(&command, &cwd, LOCAL_FS.as_ref()) - .await - .context("real resolver")?; - assert_eq!(resolved.operation.operation_name, "install"); - f.server.verify().await; - f.server.reset().await; - - let (second, _, _) = target(f.executor.path(), "2.0.0").await?; - catalog(&f.server, vec![installed(&f.server, "2.0.0")]).await; - assert!(Arc::ptr_eq( - &first_ref, - &f.prepare(&first).await?.context("reference after update")? - )); - // A newer release cannot supply an older version's declaration on a cold cache. - assert!( - RemotePluginMeasurementCache::new() - .prepare(&f.config, &f.auth, &first, /*runtime_auth*/ None) - .await? - .is_none() - ); - bundle(&f.server, "2.0.0", /*count*/ 1).await?; - let new_ref = f.prepare(&second).await?.context("new reference")?; - assert_ne!( - new_ref.home.as_ref().expect("reference store").path(), - old_home - ); - assert!(Arc::ptr_eq( - &first_ref, - &f.prepare(&first).await?.context("retained older version")? - )); - assert!( - first_ref - .roots() - .resolve_metrics_operation_in_filesystem(&command, &cwd, LOCAL_FS.as_ref()) - .await - .is_some() - ); - f.server.verify().await; - f.server.reset().await; - - let mut disabled = installed(&f.server, "2.0.0"); - disabled["enabled"] = json!(false); - let mut replaced = installed(&f.server, "2.0.0"); - replaced["id"] = json!("plugins~replacement"); - for plugins in [vec![], vec![disabled], vec![replaced]] { - catalog(&f.server, plugins).await; - assert!(f.prepare(&first).await?.is_none()); - f.assert_request_count(/*expected*/ 1).await; - f.server.reset().await; - } - drop(warm); - drop(first_ref); - - catalog(&f.server, vec![installed(&f.server, "2.0.0")]).await; - bundle(&f.server, "2.0.0", /*count*/ 1).await?; - f.auth = CodexAuth::from_external_chatgpt_tokens( - "header.e30.other", - "other-account", - /*chatgpt_plan_type*/ None, - )?; - let other_ref = f.prepare(&second).await?.context("other actor reference")?; - assert!(!Arc::ptr_eq(&new_ref, &other_ref)); - assert!(f.prepare(&first).await?.is_none()); - wait_until_removed(&old_home).await?; - f.server.verify().await; - f.server.reset().await; - - let mut disabled = installed(&f.server, "2.0.0"); - disabled["enabled"] = json!(false); - catalog(&f.server, vec![disabled]).await; - assert!(f.prepare(&second).await?.is_none()); - Ok(()) -} - -#[tokio::test] -async fn preparation_preserves_catalog_spelling_and_executor_case_rules() -> Result<()> { - if !isolated_bundle_test("preparation_preserves_catalog_spelling_and_executor_case_rules")? { - return Ok(()); - } - let f = Fixture::new().await?; - let mut plugin = installed(&f.server, "2.0.0-RC1"); - plugin["name"] = json!("Sites"); - plugin["release"]["version"] = json!(" 2.0.0-RC1\n"); - catalog(&f.server, vec![plugin.clone()]).await; - Mock::given(method("GET")) - .and(path("/bundle/2.0.0-RC1")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(archive("Sites")?)) - .expect(1) - .mount(&f.server) - .await; - - // Drive and UNC preselection normalize these hints identically on every host. - let windows = PluginMeasurementTarget { - plugin_id: PluginId::parse("sites@openai-curated-remote")?, - version: "2.0.0-rc1".to_owned(), - path_convention: PathConvention::Windows, - }; - let reference = f.prepare(&windows).await?.context("Windows reference")?; - let exact = PluginMeasurementTarget { - plugin_id: PluginId::parse("Sites@openai-curated-remote")?, - version: "2.0.0-RC1".to_owned(), - path_convention: PathConvention::Posix, - }; - assert!(Arc::ptr_eq( - &reference, - &f.prepare(&exact) - .await? - .context("same authenticated bundle")? - )); - let store = crate::store::PluginStore::new( - reference - .home - .as_ref() - .expect("reference store") - .path() - .to_owned(), - ); - assert_eq!( - store.active_plugin_version(&exact.plugin_id), - Some(exact.version.clone()) - ); - let root = store.plugin_root(&exact.plugin_id, &exact.version); - let command = vec![ - "node".to_owned(), - root.join("scripts/install.mjs") - .to_string_lossy() - .into_owned(), - ]; - let operation = reference - .roots() - .resolve_metrics_operation(&command, &root) - .context("trusted declaration retains the authenticated identity")?; - assert_eq!( - (operation.plugin_id, operation.operation.operation_name), - (exact.plugin_id.clone(), "install".to_owned()) - ); - for (name, version) in [("sites", "2.0.0-RC1"), ("Sites", "2.0.0-rc1")] { - let mismatch = PluginMeasurementTarget { - plugin_id: PluginId::new(name.to_owned(), "openai-curated-remote".to_owned())?, - version: version.to_owned(), - path_convention: PathConvention::Posix, - }; - assert!(f.prepare(&mismatch).await?.is_none()); - } - f.server.verify().await; - f.server.reset().await; - - let mut ambiguous = installed(&f.server, "2.0.0-rc1"); - ambiguous["id"] = json!("plugins~other-case"); - catalog(&f.server, vec![plugin.clone(), ambiguous]).await; - assert!(f.prepare(&windows).await?.is_none()); - f.assert_request_count(/*expected*/ 1).await; - // POSIX still selects its exact entry, even when another entry folds the same way. - assert!(Arc::ptr_eq( - &reference, - &f.prepare(&exact) - .await? - .context("exact POSIX catalog entry")? - )); - f.server.reset().await; - - plugin["release"]["version"] = json!("2.0.0-rc1"); - catalog(&f.server, vec![plugin.clone()]).await; - Mock::given(method("GET")) - .and(path("/bundle/2.0.0-RC1")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(archive("Sites")?)) - .expect(1) - .mount(&f.server) - .await; - let lower_case = f - .prepare(&windows) - .await? - .context("current catalog version")?; - assert!(!Arc::ptr_eq(&reference, &lower_case)); - f.server.verify().await; - f.server.reset().await; - - plugin["release"]["version"] = json!("3.0.0"); - catalog(&f.server, vec![plugin]).await; - assert!(f.prepare(&windows).await?.is_none()); - assert!(Arc::ptr_eq( - &reference, - &f.prepare(&exact) - .await? - .context("unambiguous historical version")? - )); - Ok(()) -} - -#[tokio::test] -async fn preparation_requires_enabled_matching_installed_global_plugin() -> Result<()> { - if !isolated_bundle_test("preparation_requires_enabled_matching_installed_global_plugin")? { - return Ok(()); - } - let mut f = Fixture::new().await?; - let (target, _, _) = target(f.executor.path(), "1.0.0").await?; - for (field, value) in [ - ("/enabled", json!(false)), - ("/scope", json!("WORKSPACE")), - ("/installation_policy", json!("NOT_AVAILABLE")), - ("/status", json!("DISABLED_BY_ADMIN")), - ("/name", json!("other")), - ("/release/version", json!(" ")), - ("/release/version", json!("../1.0.0")), - ] { - let mut plugin = installed(&f.server, "1.0.0"); - *plugin.pointer_mut(field).expect("catalog field") = value; - catalog(&f.server, vec![plugin]).await; - assert!(f.prepare(&target).await?.is_none(), "{field}"); - f.assert_request_count(/*expected*/ 1).await; - f.server.reset().await; - } - catalog(&f.server, vec![installed(&f.server, "1.0.0"); 2]).await; - assert!(f.prepare(&target).await?.is_none()); - f.server.reset().await; - for (enabled, auth) in [ - (false, f.auth.clone()), - (true, CodexAuth::from_api_key("test")), - ] { - f.config.remote_plugin_enabled = enabled; - f.auth = auth; - assert!(f.prepare(&target).await?.is_none()); - } - f.assert_request_count(/*expected*/ 0).await; - - write_file( - &f.home.path().join("config.toml"), - "[plugins.\"sites@openai-curated-remote\"]\nenabled = false\n", - ); - f.config = load_plugins_config(f.home.path(), f.executor.path()).await; - f.config.chatgpt_base_url = f.server.uri(); - f.auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let mut forced = installed(&f.server, "1.0.0"); - forced["installation_policy"] = json!("INSTALLED_BY_DEFAULT"); - catalog(&f.server, vec![forced]).await; - bundle(&f.server, "1.0.0", /*count*/ 1).await?; - assert!(f.prepare(&target).await?.is_some()); - Ok(()) -} - -#[tokio::test] -async fn preparation_failures_do_not_expose_authenticated_urls_or_response_bodies() -> Result<()> { - if !isolated_bundle_test( - "preparation_failures_do_not_expose_authenticated_urls_or_response_bodies", - )? { - return Ok(()); - } - let f = Fixture::new().await?; - let (target, _, _) = target(f.executor.path(), "1.0.0").await?; - for invalid_url in [true, false] { - let mut plugin = installed(&f.server, "1.0.0"); - plugin["release"]["bundle_download_url"] = json!(if invalid_url { - "not a URL?sig=query-secret".to_owned() - } else { - format!("{}/bundle/1.0.0?sig=query-secret", f.server.uri()) - }); - catalog(&f.server, vec![plugin]).await; - Mock::given(method("GET")) - .and(path("/bundle/1.0.0")) - .respond_with(ResponseTemplate::new(500).set_body_string("response-body-secret")) - .expect(u64::from(!invalid_url)) - .mount(&f.server) - .await; - let error = match f.prepare(&target).await { - Err(error) => error, - Ok(_) => anyhow::bail!("expected a preparation failure"), - }; - for diagnostic in [ - format!("{error}"), - format!("{error:#}"), - format!("{error:?}"), - format!("{error:#?}"), - ] - .into_iter() - .chain(error.chain().map(ToString::to_string)) - { - for secret in [ - "query-secret", - "response-body-secret", - "sig=", - f.server.uri().as_str(), - ] { - assert!(!diagnostic.contains(secret), "diagnostic exposed {secret}"); - } - } - f.server.verify().await; - f.server.reset().await; - } - Ok(()) -} - -#[tokio::test] -async fn canceled_waiters_do_not_retry_a_failed_preparation() -> Result<()> { - if !isolated_bundle_test("canceled_waiters_do_not_retry_a_failed_preparation")? { - return Ok(()); - } - let f = Arc::new(Fixture::new().await?); - let (target, _, _) = target(f.executor.path(), "1.0.0").await?; - let target = Arc::new(target); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; - let mut plugin = installed(&f.server, "1.0.0"); - plugin["release"]["bundle_download_url"] = - json!(format!("http://{}/bundle", listener.local_addr()?)); - catalog(&f.server, vec![plugin]).await; - let release = Arc::new(Semaphore::new(0)); - let (requested, mut requests) = mpsc::unbounded_channel(); - let bundle_server = tokio::spawn({ - let release = Arc::clone(&release); - async move { - for attempt in 0..2 { - let (socket, _) = listener.accept().await?; - let mut socket = tokio::io::BufReader::new(socket); - let mut line = String::new(); - loop { - line.clear(); - socket.read_line(&mut line).await?; - if line == "\r\n" || line.is_empty() { - break; - } - } - requested.send(attempt)?; - let (status, body) = if attempt == 0 { - release.acquire().await?.forget(); - ("500 Internal Server Error", Vec::new()) - } else { - ("200 OK", archive("sites")?) - }; - socket - .write_all( - format!( - "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", - body.len() - ) - .as_bytes(), - ) - .await?; - socket.write_all(&body).await?; - } - Ok::<_, anyhow::Error>(()) - } - }); - let mut callers = Vec::new(); - for _ in 0..4 { - let f = Arc::clone(&f); - let target = Arc::clone(&target); - callers.push(tokio::spawn(async move { f.prepare(&target).await })); - } - assert_eq!( - tokio::time::timeout(Duration::from_secs(5), requests.recv()).await?, - Some(0) - ); - // Wait until all four callers hold the cell alongside the cache before - // canceling the callers during the held download. - f.wait_for_cached_reference(|cell| Arc::strong_count(cell) >= 5) - .await?; - for caller in callers { - caller.abort(); - assert!(matches!(caller.await, Err(error) if error.is_cancelled())); - } - release.add_permits(1); - // Observe all admitted workers finishing before checking the request count; - // an abandoned waiter must not become a second initializer after the failure. - f.wait_for_cached_reference(|cell| cell.has_changed().is_err()) - .await?; - assert!(requests.try_recv().is_err(), "canceled caller retried"); - let reference = tokio::time::timeout(Duration::from_secs(5), f.prepare(&target)) - .await?? - .context("a new caller can retry the failed preparation")?; - assert_eq!(requests.recv().await, Some(1)); - assert!(Arc::ptr_eq( - &reference, - &f.prepare(&target).await?.context("retry is cached")? - )); - bundle_server.await??; - Ok(()) -} - -#[tokio::test] -async fn cache_evicts_least_recently_used_bundles_without_invalidating_command_leases() -> Result<()> -{ - if !isolated_bundle_test( - "cache_evicts_least_recently_used_bundles_without_invalidating_command_leases", - )? { - return Ok(()); - } - let f = Fixture::new().await?; - let mut plugins = Vec::new(); - let mut targets = Vec::new(); - for index in 0..=MAX_CACHED_REFERENCES { - let name = format!("plugin-{index}"); - let (plugin, target) = named_plugin(&f.server, &name)?; - plugins.push(plugin); - targets.push(target); - Mock::given(method("GET")) - .and(path(format!("/bundle/{name}"))) - .respond_with(ResponseTemplate::new(200).set_body_bytes(archive(&name)?)) - .expect(if index == 1 { 2 } else { 1 }) - .mount(&f.server) - .await; - } - catalog(&f.server, plugins).await; - let mut leases = Vec::new(); - for target in &targets[..MAX_CACHED_REFERENCES] { - leases.push(f.prepare(target).await?.context("initial reference")?); - } - // A concurrent warm reader must not make a completed entry unevictable. - let completed_reader = Arc::clone(&f.cache.references.lock().await[1].1); - assert!(Arc::ptr_eq( - &leases[0], - &f.prepare(&targets[0]).await?.context("recent reference")? - )); - let extra = f - .prepare(&targets[MAX_CACHED_REFERENCES]) - .await? - .context("new plugin")?; - let evicted_home = leases[1] - .home - .as_ref() - .expect("reference store") - .path() - .to_owned(); - assert!( - evicted_home.exists(), - "command lease survives cache eviction" - ); - assert!(Arc::ptr_eq( - &leases[0], - &f.prepare(&targets[0]) - .await? - .context("retained recent reference")? - )); - let replacement = f - .prepare(&targets[1]) - .await? - .context("evicted plugin reload")?; - assert_ne!( - replacement.home.as_ref().expect("reference store").path(), - evicted_home - ); - drop(completed_reader); - drop(leases.remove(1)); - wait_until_removed(&evicted_home).await?; - assert!( - extra - .home - .as_ref() - .expect("reference store") - .path() - .exists() - ); - f.server.verify().await; - Ok(()) -} - -#[tokio::test] -async fn dropping_the_cache_cancels_an_unused_download() -> Result<()> { - if !isolated_bundle_test("dropping_the_cache_cancels_an_unused_download")? { - return Ok(()); - } - let f = Arc::new(Fixture::new().await?); - let (target, _, _) = target(f.executor.path(), "1.0.0").await?; - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; - let mut plugin = installed(&f.server, "1.0.0"); - plugin["release"]["bundle_download_url"] = - json!(format!("http://{}/bundle", listener.local_addr()?)); - catalog(&f.server, vec![plugin]).await; - let (requested, request) = tokio::sync::oneshot::channel(); - let download = tokio::spawn(async move { - let (socket, _) = listener.accept().await?; - let mut socket = tokio::io::BufReader::new(socket); - let mut line = String::new(); - loop { - line.clear(); - socket.read_line(&mut line).await?; - if line == "\r\n" || line.is_empty() { - break; - } - } - requested.send(()).expect("test awaits bundle request"); - // Hold the response until cancellation closes the download connection. - let mut remainder = Vec::new(); - socket.read_to_end(&mut remainder).await?; - Ok::<_, anyhow::Error>(()) - }); - let caller = tokio::spawn({ - let f = Arc::clone(&f); - async move { f.prepare(&target).await } - }); - tokio::time::timeout(Duration::from_secs(5), request).await??; - caller.abort(); - assert!(matches!(caller.await, Err(error) if error.is_cancelled())); - drop(f); - tokio::time::timeout(Duration::from_secs(5), download).await???; - Ok(()) -} - -#[test] -fn final_store_cleanup_runs_outside_the_async_worker() -> Result<()> { - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .max_blocking_threads(1) - .build()?; - runtime.block_on(async { - let (started, ready) = tokio::sync::oneshot::channel(); - let (release, wait) = std::sync::mpsc::channel::<()>(); - let blocker = tokio::task::spawn_blocking(move || { - let _ = started.send(()); - let _ = wait.recv(); - }); - ready.await?; - let home = tempfile::tempdir()?; - let path = home.path().to_owned(); - drop(PluginMeasurementReference { - roots: TrustedPluginRoots::default(), - home: Some(home), - }); - assert!(path.exists(), "cleanup must wait for the blocking worker"); - release.send(())?; - blocker.await?; - wait_until_removed(&path).await - })?; - - // References may also outlive their runtime and still need ordinary cleanup. - let home = tempfile::tempdir()?; - let path = home.path().to_owned(); - drop(runtime); - drop(PluginMeasurementReference { - roots: TrustedPluginRoots::default(), - home: Some(home), - }); - assert!(!path.exists()); - Ok(()) -} diff --git a/codex-rs/core-plugins/src/plugins_config_input_tests.rs b/codex-rs/core-plugins/src/plugins_config_input_tests.rs index 73a18408..a4303945 100644 --- a/codex-rs/core-plugins/src/plugins_config_input_tests.rs +++ b/codex-rs/core-plugins/src/plugins_config_input_tests.rs @@ -1,18 +1,10 @@ //! Verify connection reuse without retaining request metadata or crossing config lifetimes. use super::PluginsConfigInput; -use crate::remote::fetch_recommended_plugins; use crate::test_support::test_http_client_factory; use codex_config::ConfigLayerStack; -use codex_login::CodexAuth; use pretty_assertions::assert_eq; use std::sync::Arc; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; #[test] fn repeated_service_configs_and_early_clones_share_one_lazy_pool() { @@ -62,71 +54,3 @@ fn repeated_service_configs_and_early_clones_share_one_lazy_pool() { (vec![true; 220], false) ); } - -#[tokio::test] -async fn reused_pool_uses_current_endpoint_product_and_authentication() { - let first_server = MockServer::start().await; - let second_server = MockServer::start().await; - for (server, token, account, product_sku) in [ - (&first_server, "header.e30.first", "first-account", "codex"), - ( - &second_server, - "header.e30.second", - "second-account", - "updated", - ), - ] { - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/suggested/codex")) - .and(header("authorization", format!("Bearer {token}"))) - .and(header("chatgpt-account-id", account)) - .and(header("oai-product-sku", product_sku)) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "enabled": true, - "plugins": [], - }))) - .expect(1) - .mount(server) - .await; - } - let mut input = PluginsConfigInput::new( - ConfigLayerStack::default(), - Default::default(), - "openai".to_string(), - /*plugins_enabled*/ true, - /*remote_plugin_enabled*/ true, - format!("{}/backend-api", first_server.uri()), - test_http_client_factory(), - /*product_sku*/ None, - ); - let first = input.remote_plugin_service_config(/*runtime_auth*/ None); - let first_auth = CodexAuth::from_external_chatgpt_tokens( - "header.e30.first", - "first-account", - /*chatgpt_plan_type*/ None, - ) - .unwrap(); - let first_result = fetch_recommended_plugins(&first, Some(&first_auth)) - .await - .unwrap(); - - input.chatgpt_base_url = format!("{}/backend-api", second_server.uri()); - input.product_sku = Some("updated".to_string()); - let second = input.remote_plugin_service_config(/*runtime_auth*/ None); - let second_auth = CodexAuth::from_external_chatgpt_tokens( - "header.e30.second", - "second-account", - /*chatgpt_plan_type*/ None, - ) - .unwrap(); - let second_result = fetch_recommended_plugins(&second, Some(&second_auth)) - .await - .unwrap(); - assert_eq!( - ( - first_result, - Arc::ptr_eq(&first.http_clients, &second.http_clients), - ), - (second_result, true) - ); -} diff --git a/codex-rs/core-plugins/src/remote.rs b/codex-rs/core-plugins/src/remote.rs index 957d0d6e..fbb6137f 100644 --- a/codex-rs/core-plugins/src/remote.rs +++ b/codex-rs/core-plugins/src/remote.rs @@ -1,13 +1,8 @@ -#[path = "plugin_measurement_catalog.rs"] -mod measurement_catalog; -pub(crate) use measurement_catalog::fetch_measurement_reference_bundle; use crate::app_mcp_routing::apply_app_mcp_routing_policy; use crate::error_subtype::http_status_sub_error_type; use crate::http_client_selector::HttpClientSelector; use crate::loader::plugin_app_declarations_from_value; -use crate::store::PLUGINS_CACHE_DIR; -use crate::store::PluginStore; use chrono::DateTime; use chrono::Utc; use codex_app_server_protocol::JSONRPCErrorError; @@ -22,11 +17,9 @@ use codex_app_server_protocol::SkillInterface; use codex_features::RuntimeAuthMode; use codex_http_client::ClientRouteClass; use codex_http_client::HttpClientFactory; -use codex_http_client::RequestBuilder; use codex_http_client::RouteAwareClientPool; use codex_http_client::RouteAwareRequestError; use codex_login::CodexAuth; -use codex_login::default_client::default_headers; use codex_plugin::AppConnectorId; use codex_plugin::AppDeclaration; use codex_plugin::PluginCapabilitySummary; @@ -35,8 +28,6 @@ use codex_plugin::app_connector_ids_from_declarations; use codex_plugin::prompt_safe_plugin_description; use codex_runtime_agent_instance::RuntimeAuthSlot; use codex_utils_absolute_path::AbsolutePathBuf; -use http::HeaderMap; -use http::Method; use http::StatusCode; use serde::Deserialize; use serde::Serialize; @@ -45,13 +36,11 @@ use std::collections::BTreeMap; use std::collections::BTreeSet; use std::collections::HashMap; use std::collections::HashSet; -use std::fs; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use tracing::instrument; -use url::Url; mod catalog_cache; mod plugin_capabilities; @@ -59,10 +48,6 @@ mod remote_installed_plugin_sync; mod search; mod share; -#[cfg(test)] -#[path = "remote_tests.rs"] -mod tests; - pub use plugin_capabilities::RemotePluginCapabilities; pub use remote_installed_plugin_sync::RemoteInstalledPluginBundleSyncError; pub use remote_installed_plugin_sync::RemoteInstalledPluginBundleSyncOutcome; @@ -109,7 +94,6 @@ pub const REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_DISPLAY_NAME: &st "Shared with me (unlisted)"; const OPENAI_CURATED_REMOTE_COLLECTION_KEY: &str = "vertical"; -const OAI_PRODUCT_SKU_HEADER: &str = "OAI-Product-Sku"; pub(crate) const CODEX_PRODUCT_SKU: &str = "codex"; const REMOTE_PLUGIN_CATALOG_TIMEOUT: Duration = Duration::from_secs(30); // Leave room within the 120-second mutation-gate wait even when successful pages keep arriving. @@ -117,10 +101,6 @@ const REMOTE_INSTALLED_PLUGINS_FETCH_TIMEOUT: Duration = Duration::from_secs(60) // Allow 20,000 installed plugins without unbounded cursor history. const MAX_REMOTE_INSTALLED_PLUGIN_PAGES: usize = 100; const RECOMMENDED_PLUGINS_TIMEOUT: Duration = Duration::from_secs(5); -const REMOTE_PLUGIN_LIST_PAGE_LIMIT: u32 = 200; -const MAX_RECOMMENDED_PLUGINS: usize = 50; -const MAX_RECOMMENDED_PLUGIN_NAME_LEN: usize = 64; -const MAX_RECOMMENDED_PLUGIN_DISPLAY_NAME_LEN: usize = 64; const MAX_REMOTE_DEFAULT_PROMPT_COUNT: usize = 3; const MAX_REMOTE_DEFAULT_PROMPT_LEN: usize = 128; const INVALID_REQUEST_ERROR_CODE: i64 = -32600; @@ -189,105 +169,6 @@ impl RemotePluginServiceConfig { } } - #[cfg(test)] - pub(crate) fn new_with_runtime_auth( - chatgpt_base_url: String, - http_client_factory: HttpClientFactory, - product_sku: Option, - runtime_auth: (RuntimeAuthSlot, RuntimeAuthMode), - ) -> Self { - if codex_http_client::classify_openai_api_url(&chatgpt_base_url) - == codex_http_client::OpenAiDestination::Other - { - return Self::new(chatgpt_base_url, http_client_factory, product_sku); - } - Self::new_with_selected_runtime_auth( - chatgpt_base_url, - http_client_factory, - product_sku, - runtime_auth, - ) - } - - #[cfg(test)] - pub(crate) fn new_with_selected_runtime_auth( - chatgpt_base_url: String, - http_client_factory: HttpClientFactory, - product_sku: Option, - runtime_auth: (RuntimeAuthSlot, RuntimeAuthMode), - ) -> Self { - let mut config = Self::new( - chatgpt_base_url, - http_client_factory.with_sensitive_header_protection(), - product_sku, - ); - config.runtime_auth = Some(runtime_auth); - config - } - - // Keep runtime registration out of callers' async stack frames. - pub(crate) fn authenticated_request<'a>( - &'a self, - method: Method, - url: &'a str, - auth: &'a CodexAuth, - ) -> std::pin::Pin< - Box< - dyn std::future::Future> - + Send - + 'a, - >, - > { - Box::pin(async move { - if self.runtime_auth.is_some() { - codex_model_provider::validate_runtime_destination(Some(&self.chatgpt_base_url)) - .map_err(|error| codex_api::AuthError::Build(error.to_string()))?; - } - let runtime = self - .runtime_auth - .as_ref() - .map(|(slot, mode)| { - slot.get() - .map(|manager| (Arc::clone(manager), *mode)) - .ok_or_else(|| { - codex_api::AuthError::Build( - "runtime authentication has not been initialized".to_string(), - ) - }) - }) - .transpose()?; - let resolved = codex_model_provider::auth_provider_for_request( - auth, - runtime.as_ref(), - &HeaderMap::new(), - ) - .await?; - let request = match &resolved.runtime { - Some(runtime) => self - .http_clients - .request_for_account( - method, - url, - runtime.http_client_factory().network_policy(), - ) - .ok_or_else(|| { - codex_api::AuthError::Build( - "plugin credentials and transport must share the application network policy" - .to_string(), - ) - })?, - None => self.http_clients.request(method, url), - }; - let headers = resolved.auth.apply_auth_headers(HeaderMap::new()).await?; - Ok(request.headers(default_headers()).headers(headers)) - }) - } - - pub(crate) fn http_request(&self, method: Method, url: &str) -> RequestBuilder { - self.http_clients - .request(method, url) - .headers(default_headers()) - } } impl PartialEq for RemotePluginServiceConfig { @@ -512,6 +393,9 @@ pub fn validate_remote_plugin_id(plugin_id: &str) -> Result<(), JSONRPCErrorErro #[derive(Debug, thiserror::Error)] pub enum RemotePluginCatalogError { + #[error("remote plugins are not available in aKode")] + Unavailable, + #[error("chatgpt authentication required for remote plugin catalog")] AuthRequired, @@ -613,7 +497,8 @@ impl RemotePluginCatalogError { Self::UnexpectedStatus { status, .. } => { Some(http_status_sub_error_type(*status).to_string()) } - Self::AuthRequired + Self::Unavailable + | Self::AuthRequired | Self::UnsupportedAuthMode | Self::AuthToken(_) | Self::Request { .. } @@ -713,13 +598,6 @@ struct RemotePluginSkillResponse { interface: Option, } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -struct RemotePluginSkillDetailResponse { - plugin_id: String, - name: String, - skill_md_contents: Option, -} - #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] struct RemotePluginReleaseInterfaceResponse { short_description: Option, @@ -897,32 +775,12 @@ struct RemotePluginListResponse { pagination: RemotePluginPagination, } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -struct RecommendedPluginsResponse { - enabled: bool, - plugins: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -struct RecommendedPluginItem { - id: String, - name: String, - display_name: String, -} - #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] struct RemotePluginInstalledResponse { plugins: Vec, pagination: RemotePluginPagination, } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -struct RemotePluginMutationResponse { - id: String, - enabled: bool, - app_ids_needing_auth: Option>, -} - #[derive(Debug, Clone, PartialEq, Eq)] pub struct RemotePluginInstallResult { pub app_ids_needing_auth: Option>, @@ -1152,17 +1010,8 @@ pub async fn fetch_recommended_plugins( config: &RemotePluginServiceConfig, auth: Option<&CodexAuth>, ) -> Result { - let auth = ensure_chatgpt_auth(auth)?; - let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let mut url = Url::parse(&format!("{base_url}/ps/plugins/suggested/codex")) - .map_err(RemotePluginCatalogError::InvalidBaseUrl)?; - url.query_pairs_mut().append_pair("scope", "GLOBAL"); - let url = url.to_string(); - let request = authenticated_request(config, Method::GET, &url, auth) - .await? - .timeout(RECOMMENDED_PLUGINS_TIMEOUT); - let response: RecommendedPluginsResponse = send_and_decode(request, &url).await?; - Ok(recommended_plugins_mode(response)) + let _ = (config, auth); + Err(RemotePluginCatalogError::Unavailable) } #[instrument(level = "trace", skip_all)] @@ -1205,55 +1054,6 @@ pub(crate) async fn fetch_recommended_plugin_install_metadata( Ok(Some(app_connector_ids)) } -fn recommended_plugins_mode(response: RecommendedPluginsResponse) -> RecommendedPluginsMode { - if !response.enabled { - return RecommendedPluginsMode::Legacy; - } - - let mut plugins = BTreeMap::new(); - for plugin in response.plugins { - if !is_valid_remote_plugin_id(&plugin.id) - || plugin.name.chars().count() > MAX_RECOMMENDED_PLUGIN_NAME_LEN - { - continue; - } - let plugin_id = match PluginId::new( - plugin.name.clone(), - REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(), - ) { - Ok(plugin_id) => plugin_id, - Err(err) => { - tracing::warn!( - plugin_name = plugin.name, - error = %err, - "ignoring invalid recommended plugin" - ); - continue; - } - }; - let display_name = non_empty_string(Some(&plugin.display_name)) - .unwrap_or_else(|| plugin.name.clone()) - .chars() - .take(MAX_RECOMMENDED_PLUGIN_DISPLAY_NAME_LEN) - .collect(); - let config_id = plugin_id.as_key(); - plugins - .entry(config_id.clone()) - .or_insert(RecommendedPlugin { - config_id, - remote_plugin_id: plugin.id, - display_name, - }); - } - - RecommendedPluginsMode::Endpoint { - plugins: plugins - .into_values() - .take(MAX_RECOMMENDED_PLUGINS) - .collect(), - } -} - pub(crate) fn has_fresh_cached_remote_plugin_catalog( codex_home: &Path, config: &RemotePluginServiceConfig, @@ -1523,32 +1323,8 @@ pub async fn fetch_remote_plugin_skill_detail( plugin_id: &str, skill_name: &str, ) -> Result { - let auth = ensure_chatgpt_auth(auth)?; - if RemotePluginScope::from_marketplace_name(marketplace_name).is_none() { - return Err(RemotePluginCatalogError::UnknownMarketplace { - marketplace_name: marketplace_name.to_string(), - }); - } - - let url = remote_plugin_skill_detail_url(config, plugin_id, skill_name)?; - let request = authenticated_request(config, Method::GET, &url, auth).await?; - let response: RemotePluginSkillDetailResponse = send_and_decode(request, &url).await?; - if response.plugin_id != plugin_id { - return Err(RemotePluginCatalogError::UnexpectedPluginId { - expected: plugin_id.to_string(), - actual: response.plugin_id, - }); - } - if response.name != skill_name { - return Err(RemotePluginCatalogError::UnexpectedSkillName { - expected: skill_name.to_string(), - actual: response.name, - }); - } - - Ok(RemotePluginSkillDetail { - contents: response.skill_md_contents, - }) + let _ = (config, auth, marketplace_name, plugin_id, skill_name); + Err(RemotePluginCatalogError::Unavailable) } async fn fetch_remote_plugin_detail_with_download_url_option( @@ -1683,11 +1459,6 @@ fn effective_remote_plugin_apps_and_mcp_servers( (app_ids, mcp_server_names) } -#[derive(Serialize)] -struct RemotePluginInstallRequest<'a> { - install_attempt_id: &'a str, -} - pub async fn install_remote_plugin( config: &RemotePluginServiceConfig, auth: Option<&CodexAuth>, @@ -1728,40 +1499,8 @@ async fn install_remote_plugin_inner( plugin_id: &str, install_attempt_id: Option<&str>, ) -> Result { - let auth = ensure_chatgpt_auth(auth)?; - // Remote plugin IDs uniquely identify remote plugins, so the caller-provided - // marketplace name is not validated before sending the install mutation. - - let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let mut url = Url::parse(&format!("{base_url}/ps/plugins/{plugin_id}/install")) - .map_err(RemotePluginCatalogError::InvalidBaseUrl)?; - url.query_pairs_mut() - .append_pair("includeAppsNeedingAuth", "true"); - let url = url.to_string(); - let request = authenticated_request(config, Method::POST, &url, auth).await?; - let request = if let Some(install_attempt_id) = install_attempt_id { - request.json(&RemotePluginInstallRequest { install_attempt_id }) - } else { - request - }; - let response: RemotePluginMutationResponse = send_and_decode(request, &url).await?; - if response.id != plugin_id { - return Err(RemotePluginCatalogError::UnexpectedPluginId { - expected: plugin_id.to_string(), - actual: response.id, - }); - } - if !response.enabled { - return Err(RemotePluginCatalogError::UnexpectedEnabledState { - plugin_id: plugin_id.to_string(), - expected_enabled: true, - actual_enabled: response.enabled, - }); - } - - Ok(RemotePluginInstallResult { - app_ids_needing_auth: response.app_ids_needing_auth, - }) + let _ = (config, auth, plugin_id, install_attempt_id); + Err(RemotePluginCatalogError::Unavailable) } pub async fn resolve_remote_plugin_uninstall_target( @@ -1820,90 +1559,8 @@ pub async fn uninstall_remote_plugin( codex_home: PathBuf, target: RemotePluginUninstallTarget, ) -> Result<(), RemotePluginCatalogError> { - let auth = ensure_chatgpt_auth(auth)?; - let RemotePluginUninstallTarget { - plugin_id, - remote_plugin_id, - fallback_capability_summary: _, - } = target; - let marketplace_name = plugin_id.marketplace_name.clone(); - let plugin_name = plugin_id.plugin_name.clone(); - - let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let url = format!("{base_url}/ps/plugins/{remote_plugin_id}/uninstall"); - let request = authenticated_request(config, Method::POST, &url, auth).await?; - let response: RemotePluginMutationResponse = send_and_decode(request, &url).await?; - if response.id != remote_plugin_id { - return Err(RemotePluginCatalogError::UnexpectedPluginId { - expected: remote_plugin_id, - actual: response.id, - }); - } - if response.enabled { - return Err(RemotePluginCatalogError::UnexpectedEnabledState { - plugin_id: response.id, - expected_enabled: false, - actual_enabled: response.enabled, - }); - } - - let legacy_plugin_id = response.id; - tokio::task::spawn_blocking(move || { - remove_remote_plugin_cache(codex_home, marketplace_name, plugin_name, legacy_plugin_id) - }) - .await - .map_err(|err| { - RemotePluginCatalogError::CacheRemove(format!( - "failed to join remote plugin cache removal task: {err}" - )) - })? - .map_err(RemotePluginCatalogError::CacheRemove)?; - - Ok(()) -} - -fn remove_remote_plugin_cache( - codex_home: PathBuf, - marketplace_name: String, - plugin_name: String, - legacy_plugin_id: String, -) -> Result<(), String> { - let store = PluginStore::try_new(codex_home.clone()) - .map_err(|err| format!("failed to resolve remote plugin cache root: {err}"))?; - let plugin_id = - PluginId::new(plugin_name.clone(), marketplace_name.clone()).map_err(|err| { - format!( - "invalid remote plugin cache id for `{plugin_name}` in `{marketplace_name}`: {err}" - ) - })?; - let plugin_cache_root = store.plugin_base_root(&plugin_id); - store.uninstall(&plugin_id).map_err(|err| { - format!( - "failed to remove remote plugin cache entry {}: {err}", - plugin_cache_root.display() - ) - })?; - - let legacy_remote_plugin_cache_root = codex_home - .join(PLUGINS_CACHE_DIR) - .join(marketplace_name) - .join(legacy_plugin_id); - if legacy_remote_plugin_cache_root != plugin_cache_root.as_path() - && legacy_remote_plugin_cache_root.exists() - { - let result = if legacy_remote_plugin_cache_root.is_dir() { - fs::remove_dir_all(&legacy_remote_plugin_cache_root) - } else { - fs::remove_file(&legacy_remote_plugin_cache_root) - }; - result.map_err(|err| { - format!( - "failed to remove remote plugin cache entry {}: {err}", - legacy_remote_plugin_cache_root.display() - ) - })?; - } - Ok(()) + let _ = (config, auth, codex_home, target); + Err(RemotePluginCatalogError::Unavailable) } fn build_remote_plugin_summary( @@ -2326,21 +1983,8 @@ async fn get_remote_plugin_list_page( page_token: Option<&str>, collection: Option<&str>, ) -> Result { - let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let mut url = Url::parse(&format!("{base_url}/ps/plugins/list")) - .map_err(RemotePluginCatalogError::InvalidBaseUrl)?; - url.query_pairs_mut() - .append_pair("scope", scope.api_value()) - .append_pair("limit", &REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string()); - if let Some(collection) = collection { - url.query_pairs_mut().append_pair("collection", collection); - } - if let Some(page_token) = page_token { - url.query_pairs_mut().append_pair("pageToken", page_token); - } - let url = url.to_string(); - let request = authenticated_request(config, Method::GET, &url, auth).await?; - send_and_decode(request, &url).await + let _ = (config, auth, scope, page_token, collection); + Err(RemotePluginCatalogError::Unavailable) } async fn get_remote_shared_workspace_plugins_page( @@ -2348,17 +1992,8 @@ async fn get_remote_shared_workspace_plugins_page( auth: &CodexAuth, page_token: Option<&str>, ) -> Result { - let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let mut url = Url::parse(&format!("{base_url}/ps/plugins/workspace/shared")) - .map_err(RemotePluginCatalogError::InvalidBaseUrl)?; - url.query_pairs_mut() - .append_pair("limit", &REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string()); - if let Some(page_token) = page_token { - url.query_pairs_mut().append_pair("pageToken", page_token); - } - let url = url.to_string(); - let request = authenticated_request(config, Method::GET, &url, auth).await?; - send_and_decode(request, &url).await + let _ = (config, auth, page_token); + Err(RemotePluginCatalogError::Unavailable) } async fn get_remote_plugin_installed_page( @@ -2369,29 +2004,8 @@ async fn get_remote_plugin_installed_page( include_download_urls: bool, display_assets: InstalledPluginDisplayAssets, ) -> Result { - let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let mut url = Url::parse(&format!("{base_url}/ps/plugins/installed")) - .map_err(RemotePluginCatalogError::InvalidBaseUrl)?; - if let RemoteInstalledPluginScope::Single(scope) = scope { - url.query_pairs_mut() - .append_pair("scope", scope.api_value()); - } - url.query_pairs_mut() - .append_pair("limit", &REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string()); - if include_download_urls { - url.query_pairs_mut() - .append_pair("includeDownloadUrls", "true"); - } - if display_assets == InstalledPluginDisplayAssets::Skip { - url.query_pairs_mut() - .append_pair("includeDisplayAssets", "false"); - } - if let Some(page_token) = page_token { - url.query_pairs_mut().append_pair("pageToken", page_token); - } - let url = url.to_string(); - let request = authenticated_request(config, Method::GET, &url, auth).await?; - send_and_decode(request, &url).await + let _ = (config, auth, scope, page_token, include_download_urls, display_assets); + Err(RemotePluginCatalogError::Unavailable) } async fn fetch_plugin_detail( @@ -2417,39 +2031,8 @@ async fn fetch_plugin_detail_with_timeout( include_download_urls: bool, timeout: Duration, ) -> Result { - let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let mut url = Url::parse(&format!("{base_url}/ps/plugins/{plugin_id}")) - .map_err(RemotePluginCatalogError::InvalidBaseUrl)?; - if include_download_urls { - url.query_pairs_mut() - .append_pair("includeDownloadUrls", "true"); - } - let url = url.to_string(); - let request = authenticated_request(config, Method::GET, &url, auth) - .await? - .timeout(timeout); - send_and_decode(request, &url).await -} - -fn remote_plugin_skill_detail_url( - config: &RemotePluginServiceConfig, - plugin_id: &str, - skill_name: &str, -) -> Result { - let mut url = Url::parse(config.chatgpt_base_url.trim_end_matches('/')) - .map_err(RemotePluginCatalogError::InvalidBaseUrl)?; - { - let mut segments = url - .path_segments_mut() - .map_err(|()| RemotePluginCatalogError::InvalidBaseUrlPath)?; - segments.pop_if_empty(); - segments.push("ps"); - segments.push("plugins"); - segments.push(plugin_id); - segments.push("skills"); - segments.push(skill_name); - } - Ok(url.to_string()) + let _ = (config, auth, plugin_id, include_download_urls, timeout); + Err(RemotePluginCatalogError::Unavailable) } fn ensure_chatgpt_auth(auth: Option<&CodexAuth>) -> Result<&CodexAuth, RemotePluginCatalogError> { @@ -2461,55 +2044,3 @@ fn ensure_chatgpt_auth(auth: Option<&CodexAuth>) -> Result<&CodexAuth, RemotePlu } Ok(auth) } - -async fn authenticated_request( - config: &RemotePluginServiceConfig, - method: Method, - url: &str, - auth: &CodexAuth, -) -> Result { - Ok(config - .authenticated_request(method, url, auth) - .await - .map_err(std::io::Error::other) - .map_err(RemotePluginCatalogError::AuthToken)? - .timeout(REMOTE_PLUGIN_CATALOG_TIMEOUT) - .header(OAI_PRODUCT_SKU_HEADER, &config.product_sku)) -} - -async fn send_and_decode Deserialize<'de>>( - request: RequestBuilder, - url: &str, -) -> Result { - let response = request - .send() - .await - .map_err(|source| RemotePluginCatalogError::Request { - url: url.to_string(), - source, - })?; - let status = response.status(); - let body = response - .text() - .await - .map_err(|source| RemotePluginCatalogError::Request { - url: url.to_string(), - source, - })?; - if !status.is_success() { - return Err(RemotePluginCatalogError::UnexpectedStatus { - url: url.to_string(), - status, - body, - }); - } - - serde_json::from_str(&body).map_err(|source| RemotePluginCatalogError::Decode { - url: url.to_string(), - source, - }) -} - -#[cfg(test)] -#[path = "remote_runtime_auth_tests.rs"] -mod runtime_auth_tests; diff --git a/codex-rs/core-plugins/src/remote/plugin_capabilities_tests.rs b/codex-rs/core-plugins/src/remote/plugin_capabilities_tests.rs index 746ff9c7..1cdb8c5c 100644 --- a/codex-rs/core-plugins/src/remote/plugin_capabilities_tests.rs +++ b/codex-rs/core-plugins/src/remote/plugin_capabilities_tests.rs @@ -1,22 +1,11 @@ //! Covers local capability accumulation and removal hints from the shared bundle sync. use super::*; -use crate::remote::RemoteInstalledPluginBundleSyncOutcome; -use crate::remote::RemotePluginChange; -use crate::remote::RemotePluginServiceConfig; -use crate::remote::sync_remote_installed_plugin_bundles_once; use crate::test_support::write_file; -use codex_login::CodexAuth; use codex_utils_plugins::AGENT_PLUGIN_SCHEMA_URI; use pretty_assertions::assert_eq; use serde_json::json; use tempfile::TempDir; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; #[tokio::test] async fn agent_plugin_capabilities_do_not_require_runtime_data_directory() { @@ -67,92 +56,3 @@ async fn agent_plugin_capabilities_do_not_require_runtime_data_directory() { assert!(!data_root.as_path().is_dir()); } } - -#[tokio::test] -async fn capabilities_union_cached_versions_and_sync_reports_removal() -> anyhow::Result<()> { - let codex_home = TempDir::new()?; - let store = PluginStore::new(codex_home.path().to_path_buf()); - let plugin_id = PluginId::parse("example@openai-curated-remote")?; - let old_root = store.plugin_root(&plugin_id, "1.0.0"); - for (path, contents) in [ - (".codex-plugin/plugin.json", r#"{"name":"example"}"#), - ( - ".mcp.json", - r#"{"mcpServers":{"example":{"command":"unused"}}}"#, - ), - ( - "hooks/hooks.json", - r#"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"echo example"}]}]}}"#, - ), - ( - "skills/example/SKILL.md", - "---\nname: example\ndescription: Example skill\n---\nExample skill", - ), - ] { - write_file(old_root.join(path).as_path(), contents); - } - let mut capabilities = RemotePluginCapabilities::default(); - capabilities.include_active_bundle(&store, &plugin_id).await; - - // Accumulate the old and new declarations without involving bundle transport. - let new_root = store.plugin_root(&plugin_id, "2.0.0"); - write_file( - new_root.join(".codex-plugin/plugin.json").as_path(), - r#"{"name":"example"}"#, - ); - write_file( - new_root.join(".app.json").as_path(), - r#"{"apps":{"example":{"id":"connector_example"}}}"#, - ); - capabilities.include_active_bundle(&store, &plugin_id).await; - assert_eq!( - capabilities, - RemotePluginCapabilities { - has_mcps: true, - has_apps: true, - has_hooks: true, - has_skills: true, - } - ); - - let server = MockServer::start().await; - let config = RemotePluginServiceConfig::new( - format!("{}/backend-api", server.uri()), - crate::test_support::test_http_client_factory(), - /*product_sku*/ None, - ); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("includeDownloadUrls", "true")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [], - "pagination": {"next_page_token": null}, - }))) - .expect(1) - .mount(&server) - .await; - - // Removal describes only the active version, not the union accumulated above. - assert_eq!( - sync_remote_installed_plugin_bundles_once( - codex_home.path().to_path_buf(), - &config, - Some(&auth), - ) - .await?, - RemoteInstalledPluginBundleSyncOutcome { - changed_plugins: vec![RemotePluginChange { - plugin_id: plugin_id.as_key(), - capabilities: RemotePluginCapabilities { - has_apps: true, - ..Default::default() - }, - }], - ..Default::default() - } - ); - assert!(!store.plugin_base_root(&plugin_id).as_path().exists()); - server.verify().await; - Ok(()) -} diff --git a/codex-rs/core-plugins/src/remote/remote_installed_plugin_sync.rs b/codex-rs/core-plugins/src/remote/remote_installed_plugin_sync.rs index 00748af8..74a97d35 100644 --- a/codex-rs/core-plugins/src/remote/remote_installed_plugin_sync.rs +++ b/codex-rs/core-plugins/src/remote/remote_installed_plugin_sync.rs @@ -502,305 +502,6 @@ fn is_remote_plugin_cache_mutation_in_flight( mod tests { use super::*; use pretty_assertions::assert_eq; - use serde_json::json; - use wiremock::Mock; - use wiremock::MockServer; - use wiremock::ResponseTemplate; - use wiremock::matchers::method; - use wiremock::matchers::path; - use wiremock::matchers::query_param; - use wiremock::matchers::query_param_is_missing; - - #[tokio::test] - async fn sync_same_version_backfills_metadata_and_missing_version_requires_materialization() { - let server = MockServer::start().await; - let codex_home = tempfile::tempdir().expect("create codex home"); - let cached_manifest = codex_home - .path() - .join(PLUGINS_CACHE_DIR) - .join(REMOTE_GLOBAL_MARKETPLACE_NAME) - .join("linear") - .join("1.2.3") - .join(".codex-plugin") - .join("plugin.json"); - std::fs::create_dir_all(cached_manifest.parent().expect("manifest parent")) - .expect("create cached plugin manifest parent"); - std::fs::write(&cached_manifest, r#"{"name":"linear","version":"1.2.3"}"#) - .expect("write cached plugin manifest"); - let remote_plugin_id = "plugins~Plugin_linear"; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param_is_missing("scope")) - .and(query_param("limit", "200")) - .and(query_param("includeDownloadUrls", "true")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [ - { - "id": remote_plugin_id, - "name": "linear", - "scope": "GLOBAL", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "status": "ENABLED", - "release": { - "version": "1.2.3", - "display_name": "Linear", - "description": "Track work", - "interface": {}, - }, - "enabled": true, - }, - { - "id": "plugins~Plugin_missing_version", - "name": "missing-version", - "scope": "GLOBAL", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "status": "ENABLED", - "release": { - "display_name": "Missing version", - "description": "Needs materialization", - "interface": {}, - }, - "enabled": true, - }, - ], - "pagination": {"next_page_token": null}, - }))) - .expect(1) - .mount(&server) - .await; - let config = RemotePluginServiceConfig::new( - format!("{}/backend-api", server.uri()), - crate::test_support::test_http_client_factory(), - /*product_sku*/ None, - ); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - let outcome = sync_remote_installed_plugin_bundles_once( - codex_home.path().to_path_buf(), - &config, - Some(&auth), - ) - .await - .expect("sync current remote plugin bundle"); - - assert_eq!( - outcome, - RemoteInstalledPluginBundleSyncOutcome { - failed_remote_plugin_ids: vec!["plugins~Plugin_missing_version".to_string()], - failed_materialization_remote_plugin_ids: vec![ - "plugins~Plugin_missing_version".to_string() - ], - ..RemoteInstalledPluginBundleSyncOutcome::default() - } - ); - let plugin_id = PluginId::new( - "linear".to_string(), - REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(), - ) - .expect("valid plugin id"); - let metadata_path = PluginStore::new(codex_home.path().to_path_buf()) - .plugin_base_root(&plugin_id) - .join(".codex-remote-plugin-install.json"); - assert_eq!( - serde_json::from_str::( - &std::fs::read_to_string(metadata_path.as_path()) - .expect("read remote plugin install metadata") - ) - .expect("parse remote plugin install metadata"), - json!({ - "schema_version": 1, - "remote_plugin_id": remote_plugin_id, - }) - ); - assert!( - !codex_home - .path() - .join(PLUGINS_CACHE_DIR) - .join(REMOTE_GLOBAL_MARKETPLACE_NAME) - .join("missing-version") - .exists() - ); - } - - #[tokio::test] - async fn sync_all_scopes_paginates_and_reconciles_each_marketplace() { - let server = MockServer::start().await; - let codex_home = tempfile::tempdir().expect("create codex home"); - let cached_plugins = [ - ( - REMOTE_GLOBAL_MARKETPLACE_NAME, - "global-plugin", - "GLOBAL", - None, - ), - ( - REMOTE_CREATED_BY_ME_MARKETPLACE_NAME, - "user-plugin", - "USER", - None, - ), - ( - REMOTE_WORKSPACE_MARKETPLACE_NAME, - "workspace-plugin", - "WORKSPACE", - Some("LISTED"), - ), - ( - REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME, - "shared-plugin", - "WORKSPACE", - Some("PRIVATE"), - ), - ]; - for (marketplace_name, plugin_name, _, _) in cached_plugins { - for cached_plugin_name in [plugin_name, "stale"] { - let manifest = codex_home - .path() - .join(PLUGINS_CACHE_DIR) - .join(marketplace_name) - .join(cached_plugin_name) - .join("1.2.3") - .join(".codex-plugin") - .join("plugin.json"); - std::fs::create_dir_all(manifest.parent().expect("manifest parent")) - .expect("create cached plugin manifest parent"); - std::fs::write( - &manifest, - format!(r#"{{"name":"{cached_plugin_name}","version":"1.2.3"}}"#), - ) - .expect("write cached plugin manifest"); - } - } - let installed_plugins = cached_plugins - .iter() - .map(|(_, plugin_name, scope, discoverability)| { - let mut plugin = json!({ - "id": format!("plugins~Plugin_{plugin_name}"), - "name": plugin_name, - "scope": scope, - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "status": "ENABLED", - "release": { - "version": "1.2.3", - "display_name": plugin_name, - "description": "Installed plugin", - "interface": {}, - }, - "enabled": true, - }); - if let Some(discoverability) = discoverability { - plugin["discoverability"] = json!(discoverability); - } - plugin - }) - .collect::>(); - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param_is_missing("scope")) - .and(query_param("limit", "200")) - .and(query_param("includeDownloadUrls", "true")) - .and(query_param_is_missing("pageToken")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": &installed_plugins[..2], - "pagination": {"next_page_token": "page-2"}, - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param_is_missing("scope")) - .and(query_param("limit", "200")) - .and(query_param("includeDownloadUrls", "true")) - .and(query_param("pageToken", "page-2")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": &installed_plugins[2..], - "pagination": {"next_page_token": null}, - }))) - .expect(1) - .mount(&server) - .await; - let (config, selected_urls) = crate::test_support::recording_remote_plugin_service_config( - format!("{}/backend-api", server.uri()), - ); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - let outcome = sync_remote_installed_plugin_bundles_once( - codex_home.path().to_path_buf(), - &config, - Some(&auth), - ) - .await - .expect("sync installed plugins across every marketplace"); - let mut removed_cache_plugin_ids = cached_plugins - .iter() - .map(|(marketplace_name, _, _, _)| format!("stale@{marketplace_name}")) - .collect::>(); - removed_cache_plugin_ids.sort(); - - assert_eq!( - outcome, - RemoteInstalledPluginBundleSyncOutcome { - materialized_remote_plugins: Vec::new(), - changed_plugins: removed_cache_plugin_ids - .into_iter() - .map(|plugin_id| RemotePluginChange { - plugin_id, - capabilities: RemotePluginCapabilities::default(), - }) - .collect(), - failed_remote_plugin_ids: Vec::new(), - failed_materialization_remote_plugin_ids: Vec::new(), - } - ); - assert_eq!( - crate::test_support::recorded_http_client_urls(&selected_urls), - vec![ - format!( - "{}/backend-api/ps/plugins/installed?limit=200&includeDownloadUrls=true", - server.uri() - ), - format!( - "{}/backend-api/ps/plugins/installed?limit=200&includeDownloadUrls=true&pageToken=page-2", - server.uri() - ), - ] - ); - for (marketplace_name, plugin_name, _, _) in cached_plugins { - let plugin_root = codex_home - .path() - .join(PLUGINS_CACHE_DIR) - .join(marketplace_name) - .join(plugin_name); - assert!( - plugin_root - .join("1.2.3/.codex-plugin/plugin.json") - .is_file() - ); - assert_eq!( - serde_json::from_str::( - &std::fs::read_to_string(plugin_root.join(".codex-remote-plugin-install.json")) - .expect("read remote plugin install metadata") - ) - .expect("parse remote plugin install metadata"), - json!({ - "schema_version": 1, - "remote_plugin_id": format!("plugins~Plugin_{plugin_name}"), - }) - ); - assert!( - !codex_home - .path() - .join(PLUGINS_CACHE_DIR) - .join(marketplace_name) - .join("stale") - .exists() - ); - } - } #[tokio::test] async fn stale_remote_plugin_cleanup_skips_cache_mutations_in_progress() { diff --git a/codex-rs/core-plugins/src/remote/search.rs b/codex-rs/core-plugins/src/remote/search.rs index 2d9c5188..91dc6475 100644 --- a/codex-rs/core-plugins/src/remote/search.rs +++ b/codex-rs/core-plugins/src/remote/search.rs @@ -1,16 +1,9 @@ use super::RemotePluginCatalogError; -use super::RemotePluginListResponse; use super::RemotePluginScope; use super::RemotePluginServiceConfig; use super::RemotePluginSummary; -use super::authenticated_request; -use super::build_remote_plugin_summary; -use super::ensure_chatgpt_auth; -use super::send_and_decode; use codex_login::CodexAuth; -use http::Method; use tracing::instrument; -use url::Url; /// Search parameters forwarded directly to plugin-service. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -39,53 +32,7 @@ pub async fn search_remote_plugins( auth: Option<&CodexAuth>, search: RemotePluginSearchRequest<'_>, ) -> Result { - let auth = ensure_chatgpt_auth(auth)?; - let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let mut url = Url::parse(&format!("{base_url}/ps/plugins/search")) - .map_err(RemotePluginCatalogError::InvalidBaseUrl)?; - // Search terms and page tokens can contain user data. Keep the queryless endpoint for - // diagnostics so neither value is exposed through errors or telemetry. - let url_for_error = url.to_string(); - - { - let mut query_pairs = url.query_pairs_mut(); - query_pairs.append_pair("q", search.query); - if let Some(scope) = search.scope { - query_pairs.append_pair("scope", scope.api_value()); - } - query_pairs.append_pair("limit", &search.limit.to_string()); - if let Some(page_token) = search.page_token { - query_pairs.append_pair("pageToken", page_token); - } - } - - let url = url.to_string(); - let request = authenticated_request(config, Method::GET, &url, auth).await?; - let response: RemotePluginListResponse = send_and_decode(request, &url_for_error) - .await - .map_err(|error| match error { - RemotePluginCatalogError::Request { url, source } => { - RemotePluginCatalogError::Request { - url, - source: source.without_url(), - } - } - other => other, - })?; - let plugins = response - .plugins - .iter() - // Search intentionally does not join against `/ps/plugins/installed`, so these - // summaries always report `installed: false`. - .map(|plugin| build_remote_plugin_summary(plugin, /*installed_plugin*/ None)) - .collect::, _>>()?; - - Ok(RemotePluginSearchPage { - plugins, - next_page_token: response.pagination.next_page_token, - }) + let _ = (config, auth, search); + Err(RemotePluginCatalogError::Unavailable) } -#[cfg(test)] -#[path = "search_tests.rs"] -mod tests; diff --git a/codex-rs/core-plugins/src/remote/search_tests.rs b/codex-rs/core-plugins/src/remote/search_tests.rs deleted file mode 100644 index 568b9d8f..00000000 --- a/codex-rs/core-plugins/src/remote/search_tests.rs +++ /dev/null @@ -1,490 +0,0 @@ -use super::*; -use crate::remote::REMOTE_CREATED_BY_ME_MARKETPLACE_NAME; -use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME; -use crate::remote::REMOTE_WORKSPACE_MARKETPLACE_NAME; -use crate::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME; -use crate::remote::RemotePluginShareDiscoverability; -use crate::test_support::recorded_http_client_urls; -use crate::test_support::recording_remote_plugin_service_config; -use codex_app_server_protocol::PluginAuthPolicy; -use codex_app_server_protocol::PluginAvailability; -use codex_app_server_protocol::PluginDisabledReason; -use codex_app_server_protocol::PluginInstallPolicy; -use codex_app_server_protocol::PluginInstallPolicySource; -use codex_app_server_protocol::PluginInterface; -use http::StatusCode; -use pretty_assertions::assert_eq; -use serde_json::json; -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; -use wiremock::matchers::query_param; -use wiremock::matchers::query_param_is_missing; - -fn remote_plugin_json(remote_plugin_id: &str, plugin_name: &str, scope: &str) -> serde_json::Value { - let discoverability = (scope == "WORKSPACE").then_some("LISTED"); - json!({ - "id": remote_plugin_id, - "name": plugin_name, - "scope": scope, - "discoverability": discoverability, - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "release": { - "display_name": plugin_name, - "description": format!("{plugin_name} description"), - "interface": {}, - }, - }) -} - -#[tokio::test] -async fn search_remote_plugins_forwards_parameters_and_converts_results() { - let server = MockServer::start().await; - let remote_plugin = json!({ - "id": "plugins~Plugin_linear", - "name": "linear", - "scope": "GLOBAL", - "installation_policy": "NOT_AVAILABLE", - "installation_policy_source": "WORKSPACE_SETTING", - "must_show_installation_interstitial": true, - "authentication_policy": "ON_INSTALL", - "status": "DISABLED_BY_ADMIN", - "disabled_reason": "plan_not_eligible", - "eligible_plan_types": ["pro"], - "release": { - "version": "1.2.3", - "display_name": "Linear", - "description": "Track issues", - "keywords": ["issues"], - "interface": { - "short_description": "Issue tracking", - "category": "Productivity", - "capabilities": ["Create issues"], - "logo_url": "https://example.com/linear.png", - }, - }, - }); - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/search")) - .and(query_param("q", "linear & docs/+")) - .and(query_param("scope", "GLOBAL")) - .and(query_param("limit", "16")) - .and(query_param("pageToken", "next page/+")) - .and(header("authorization", "Bearer Access Token")) - .and(header("chatgpt-account-id", "account_id")) - .and(header("oai-product-sku", "codex")) - .and(header_exists("user-agent")) - .and(header_exists("originator")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [remote_plugin], - "pagination": {"next_page_token": "later page/+"}, - }))) - .expect(1) - .mount(&server) - .await; - let (config, selected_urls) = - recording_remote_plugin_service_config(format!("{}/backend-api/", server.uri())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - let result = search_remote_plugins( - &config, - Some(&auth), - RemotePluginSearchRequest { - query: "linear & docs/+", - scope: Some(RemotePluginScope::Global), - limit: 16, - page_token: Some("next page/+"), - }, - ) - .await - .expect("plugin search should succeed"); - - assert_eq!( - result, - RemotePluginSearchPage { - plugins: vec![RemotePluginSummary { - id: format!("linear@{REMOTE_GLOBAL_MARKETPLACE_NAME}"), - remote_plugin_id: "plugins~Plugin_linear".to_string(), - version: Some("1.2.3".to_string()), - local_version: None, - name: "linear".to_string(), - share_context: None, - installed: false, - installed_at: None, - enabled: false, - install_policy: PluginInstallPolicy::NotAvailable, - install_policy_source: Some(PluginInstallPolicySource::WorkspaceSetting), - must_show_installation_interstitial: Some(true), - auth_policy: PluginAuthPolicy::OnInstall, - availability: PluginAvailability::DisabledByAdmin, - disabled_reason: Some(PluginDisabledReason::PlanNotEligible), - eligible_plan_types: Some(vec!["pro".to_string()]), - interface: Some(PluginInterface { - display_name: Some("Linear".to_string()), - short_description: Some("Issue tracking".to_string()), - long_description: None, - developer_name: None, - category: Some("Productivity".to_string()), - capabilities: vec!["Create issues".to_string()], - website_url: None, - privacy_policy_url: None, - terms_of_service_url: None, - default_prompt: None, - brand_color: None, - composer_icon: None, - composer_icon_url: None, - logo: None, - logo_dark: None, - logo_url: Some("https://example.com/linear.png".to_string()), - logo_url_dark: None, - screenshots: Vec::new(), - screenshot_urls: Vec::new(), - }), - keywords: vec!["issues".to_string()], - }], - next_page_token: Some("later page/+".to_string()), - } - ); - assert_eq!( - recorded_http_client_urls(&selected_urls), - vec![format!( - "{}/backend-api/ps/plugins/search?q=linear+%26+docs%2F%2B&scope=GLOBAL&limit=16&pageToken=next+page%2F%2B", - server.uri() - )] - ); -} - -#[tokio::test] -async fn search_remote_plugins_omits_optional_scope_and_page_token() { - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/search")) - .and(query_param("q", "calendar")) - .and(query_param("limit", "25")) - .and(query_param_is_missing("scope")) - .and(query_param_is_missing("pageToken")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [], - "pagination": {"next_page_token": null}, - }))) - .expect(2) - .mount(&server) - .await; - let (config, _) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - for _ in 0..2 { - let result = search_remote_plugins( - &config, - Some(&auth), - RemotePluginSearchRequest { - query: "calendar", - scope: None, - limit: 25, - page_token: None, - }, - ) - .await - .expect("unscoped plugin search should succeed"); - - assert_eq!( - result, - RemotePluginSearchPage { - plugins: Vec::new(), - next_page_token: None, - } - ); - } -} - -#[tokio::test] -async fn search_remote_plugins_forwards_each_supported_scope() { - let server = MockServer::start().await; - let (config, _) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - for (scope, expected_scope) in [ - (RemotePluginScope::Global, "GLOBAL"), - (RemotePluginScope::User, "USER"), - (RemotePluginScope::Workspace, "WORKSPACE"), - ] { - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/search")) - .and(query_param("scope", expected_scope)) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [], - "pagination": {"next_page_token": null}, - }))) - .expect(1) - .mount(&server) - .await; - - search_remote_plugins( - &config, - Some(&auth), - RemotePluginSearchRequest { - query: "calendar", - scope: Some(scope), - limit: 16, - page_token: None, - }, - ) - .await - .expect("scoped plugin search should succeed"); - } -} - -#[tokio::test] -async fn search_remote_plugins_preserves_order_and_canonical_marketplaces() { - let server = MockServer::start().await; - let mut shared_plugin = remote_plugin_json("plugin-shared", "shared", "WORKSPACE"); - shared_plugin["discoverability"] = json!("PRIVATE"); - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/search")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [ - remote_plugin_json("plugin-user", "personal", "USER"), - remote_plugin_json("plugin-global", "global", "GLOBAL"), - remote_plugin_json("plugin-workspace", "workspace", "WORKSPACE"), - shared_plugin, - ], - "pagination": {"next_page_token": null}, - }))) - .expect(1) - .mount(&server) - .await; - let (config, _) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - let result = search_remote_plugins( - &config, - Some(&auth), - RemotePluginSearchRequest { - query: "plugin", - scope: None, - limit: 16, - page_token: None, - }, - ) - .await - .expect("mixed-scope plugin search should succeed"); - - let identities = result - .plugins - .into_iter() - .map(|plugin| { - ( - plugin.id, - plugin.remote_plugin_id, - plugin.share_context.map(|context| context.discoverability), - ) - }) - .collect::>(); - assert_eq!( - identities, - vec![ - ( - format!("personal@{REMOTE_CREATED_BY_ME_MARKETPLACE_NAME}"), - "plugin-user".to_string(), - None, - ), - ( - format!("global@{REMOTE_GLOBAL_MARKETPLACE_NAME}"), - "plugin-global".to_string(), - None, - ), - ( - format!("workspace@{REMOTE_WORKSPACE_MARKETPLACE_NAME}"), - "plugin-workspace".to_string(), - Some(RemotePluginShareDiscoverability::Listed), - ), - ( - format!("shared@{REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME}"), - "plugin-shared".to_string(), - Some(RemotePluginShareDiscoverability::Private), - ), - ] - ); -} - -#[tokio::test] -async fn search_remote_plugins_requires_chatgpt_authentication() { - let (config, selected_urls) = - recording_remote_plugin_service_config("https://chatgpt.example/backend-api".to_string()); - - let result = search_remote_plugins( - &config, - /*auth*/ None, - RemotePluginSearchRequest { - query: "calendar", - scope: None, - limit: 16, - page_token: None, - }, - ) - .await; - - assert!(matches!( - result, - Err(RemotePluginCatalogError::AuthRequired) - )); - assert_eq!( - recorded_http_client_urls(&selected_urls), - Vec::::new() - ); -} - -#[tokio::test] -async fn search_remote_plugins_rejects_api_key_authentication() { - let (config, selected_urls) = - recording_remote_plugin_service_config("https://chatgpt.example/backend-api".to_string()); - let auth = CodexAuth::from_api_key("test-api-key"); - - let result = search_remote_plugins( - &config, - Some(&auth), - RemotePluginSearchRequest { - query: "calendar", - scope: Some(RemotePluginScope::Global), - limit: 16, - page_token: None, - }, - ) - .await; - - assert!(matches!( - result, - Err(RemotePluginCatalogError::UnsupportedAuthMode) - )); - assert_eq!( - recorded_http_client_urls(&selected_urls), - Vec::::new() - ); -} - -#[tokio::test] -async fn search_remote_plugins_redacts_sensitive_parameters_from_transport_errors() { - let listener = std::net::TcpListener::bind("127.0.0.1:0") - .expect("test listener should bind to a local port"); - let address = listener - .local_addr() - .expect("test listener should have a local address"); - let connection = std::thread::spawn(move || { - let (stream, _) = listener - .accept() - .expect("test listener should accept the plugin search request"); - drop(stream); - }); - let (config, _) = - recording_remote_plugin_service_config(format!("http://{address}/backend-api")); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - let error = search_remote_plugins( - &config, - Some(&auth), - RemotePluginSearchRequest { - query: "sensitive search term", - scope: Some(RemotePluginScope::Global), - limit: 16, - page_token: Some("sensitive pagination token"), - }, - ) - .await - .expect_err("closed connection should fail the plugin search request"); - connection - .join() - .expect("test listener should close the accepted connection"); - - let error_message = error.to_string(); - assert!(!error_message.contains("sensitive search term")); - assert!(!error_message.contains("sensitive pagination token")); - let RemotePluginCatalogError::Request { url, source } = error else { - panic!("expected transport request error"); - }; - assert_eq!( - url, - format!("http://{address}/backend-api/ps/plugins/search") - ); - assert!(!source.to_string().contains("sensitive")); -} - -#[tokio::test] -async fn search_remote_plugins_preserves_upstream_http_errors() { - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/search")) - .respond_with(ResponseTemplate::new(503).set_body_string("plugin search unavailable")) - .expect(1) - .mount(&server) - .await; - let (config, _) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - let result = search_remote_plugins( - &config, - Some(&auth), - RemotePluginSearchRequest { - query: "sensitive search term", - scope: Some(RemotePluginScope::Global), - limit: 16, - page_token: Some("sensitive pagination token"), - }, - ) - .await; - - let error = result.expect_err("upstream HTTP status should fail"); - let error_message = error.to_string(); - assert!(!error_message.contains("sensitive search term")); - assert!(!error_message.contains("sensitive pagination token")); - let RemotePluginCatalogError::UnexpectedStatus { url, status, body } = error else { - panic!("expected upstream HTTP status error"); - }; - assert_eq!( - (url, status, body), - ( - format!("{}/backend-api/ps/plugins/search", server.uri()), - StatusCode::SERVICE_UNAVAILABLE, - "plugin search unavailable".to_string(), - ) - ); -} - -#[tokio::test] -async fn search_remote_plugins_preserves_response_decode_errors() { - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/search")) - .respond_with(ResponseTemplate::new(200).set_body_string("not-json")) - .expect(1) - .mount(&server) - .await; - let (config, _) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - let result = search_remote_plugins( - &config, - Some(&auth), - RemotePluginSearchRequest { - query: "calendar", - scope: None, - limit: 16, - page_token: None, - }, - ) - .await; - - assert!(matches!( - result, - Err(RemotePluginCatalogError::Decode { .. }) - )); -} diff --git a/codex-rs/core-plugins/src/remote/share.rs b/codex-rs/core-plugins/src/remote/share.rs index 98ee12ae..6b139167 100644 --- a/codex-rs/core-plugins/src/remote/share.rs +++ b/codex-rs/core-plugins/src/remote/share.rs @@ -1,24 +1,15 @@ use super::*; -use crate::plugin_bundle_archive::PluginBundlePackError; -use crate::plugin_bundle_archive::pack_plugin_bundle_tar_gz; -use codex_http_client::RequestBuilder; use codex_login::CodexAuth; use codex_utils_absolute_path::AbsolutePathBuf; -use http::Method; -use http::StatusCode; use serde::Deserialize; use serde::Serialize; use std::collections::BTreeMap; use std::io; use std::path::Path; -use tracing::warn; -use url::Url; mod checkout; mod local_paths; -const REMOTE_PLUGIN_SHARE_MAX_ARCHIVE_BYTES: usize = 50 * 1024 * 1024; - pub use checkout::checkout_remote_plugin_share; #[derive(Debug, Clone, PartialEq, Eq)] @@ -94,52 +85,6 @@ pub struct RemotePluginShareUpdateTargetsResult { pub discoverability: RemotePluginShareDiscoverability, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -struct RemoteWorkspacePluginUploadUrlRequest<'a> { - filename: &'a str, - mime_type: &'a str, - size_bytes: usize, - #[serde(skip_serializing_if = "Option::is_none")] - plugin_id: Option<&'a str>, -} - -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -struct RemoteWorkspacePluginUploadUrlResponse { - file_id: String, - upload_url: String, - etag: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -struct RemoteWorkspacePluginCreateRequest { - file_id: String, - etag: String, - #[serde(skip_serializing_if = "Option::is_none")] - discoverability: Option, - #[serde(skip_serializing_if = "Option::is_none")] - share_targets: Option>, -} - -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -struct RemoteWorkspacePluginCreateResponse { - plugin_id: String, - share_url: Option, - #[serde(default)] - can_publish_to_workspace: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -struct RemotePluginShareUpdateTargetsRequest { - discoverability: RemotePluginShareUpdateDiscoverability, - targets: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -struct RemotePluginShareUpdateTargetsResponse { - principals: Vec, - discoverability: RemotePluginShareDiscoverability, -} - pub async fn save_remote_plugin_share( config: &RemotePluginServiceConfig, auth: Option<&CodexAuth>, @@ -148,65 +93,8 @@ pub async fn save_remote_plugin_share( remote_plugin_id: Option<&str>, access_policy: RemotePluginShareAccessPolicy, ) -> Result { - let auth = ensure_chatgpt_auth(auth)?; - let config = &config.for_current_account(); - let plugin_path_for_archive = plugin_path.as_path().to_path_buf(); - let (filename, archive_bytes) = tokio::task::spawn_blocking(move || { - let filename = archive_filename(&plugin_path_for_archive)?; - let archive_bytes = archive_plugin_for_upload(&plugin_path_for_archive)?; - Ok::<_, RemotePluginCatalogError>((filename, archive_bytes)) - }) - .await - .map_err(RemotePluginCatalogError::ArchiveJoin)??; - let upload = create_workspace_plugin_upload( - config, - auth, - &filename, - archive_bytes.len(), - remote_plugin_id, - ) - .await?; - let etag = upload - .etag - .ok_or(RemotePluginCatalogError::MissingUploadEtag)?; - put_workspace_plugin_upload(config, &upload.upload_url, archive_bytes).await?; - let share_targets = access_policy.share_targets; - let share_targets = - ensure_unlisted_workspace_target(auth, access_policy.discoverability, share_targets)?; - let response = finalize_workspace_plugin_upload( - config, - auth, - remote_plugin_id, - RemoteWorkspacePluginCreateRequest { - file_id: upload.file_id, - etag, - discoverability: access_policy.discoverability, - share_targets, - }, - ) - .await?; - if response.plugin_id.is_empty() { - return Err(RemotePluginCatalogError::UnexpectedResponse( - "workspace plugin create response did not include a plugin id".to_string(), - )); - } - - if let Err(err) = local_paths::record_plugin_share_local_path( - codex_home, - &response.plugin_id, - plugin_path.clone(), - ) { - warn!( - remote_plugin_id = %response.plugin_id, - "failed to record plugin share local path mapping: {err}" - ); - } - - Ok(RemotePluginShareSaveResult { - remote_plugin_id: response.plugin_id, - share_url: response.share_url, - can_publish_to_workspace: response.can_publish_to_workspace, - }) + let _ = (config, auth, codex_home, plugin_path, remote_plugin_id, access_policy); + Err(RemotePluginCatalogError::Unavailable) } pub async fn list_remote_plugin_shares( @@ -214,47 +102,8 @@ pub async fn list_remote_plugin_shares( auth: Option<&CodexAuth>, codex_home: &Path, ) -> Result, RemotePluginCatalogError> { - let auth = ensure_chatgpt_auth(auth)?; - let created_plugins = fetch_created_workspace_plugins(config, auth).await?; - if created_plugins.is_empty() { - return Ok(Vec::new()); - } - - let installed_by_id = - fetch_installed_plugins_for_scope(config, auth, RemotePluginScope::Workspace) - .await? - .into_iter() - .map(|plugin| (plugin.plugin.id.clone(), plugin)) - .collect::>(); - let local_plugin_paths = - local_paths::load_plugin_share_local_paths(codex_home).map_err(|err| { - RemotePluginCatalogError::UnexpectedResponse(format!( - "failed to load plugin share local path mapping: {err}" - )) - })?; - - created_plugins - .into_iter() - .map(|plugin| { - let summary = build_remote_plugin_summary(&plugin, installed_by_id.get(&plugin.id))?; - if summary - .share_context - .as_ref() - .and_then(|context| context.share_principals.as_ref()) - .is_none() - { - return Err(RemotePluginCatalogError::UnexpectedResponse(format!( - "created workspace plugin `{}` did not include share_principals", - plugin.id - ))); - } - let local_plugin_path = local_plugin_paths.get(&plugin.id).cloned(); - Ok(RemotePluginShareSummary { - summary, - local_plugin_path, - }) - }) - .collect() + let _ = (config, auth, codex_home); + Err(RemotePluginCatalogError::Unavailable) } pub fn load_plugin_share_remote_ids_by_local_path( @@ -283,18 +132,8 @@ pub async fn delete_remote_plugin_share( codex_home: &Path, remote_plugin_id: &str, ) -> Result<(), RemotePluginCatalogError> { - let auth = ensure_chatgpt_auth(auth)?; - let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let url = format!("{base_url}/public/plugins/workspace/{remote_plugin_id}"); - let request = authenticated_request(config, Method::DELETE, &url, auth).await?; - send_and_expect_status(request, &url, &[StatusCode::NO_CONTENT]).await?; - if let Err(err) = local_paths::remove_plugin_share_local_path(codex_home, remote_plugin_id) { - warn!( - remote_plugin_id = %remote_plugin_id, - "failed to remove plugin share local path mapping: {err}" - ); - } - Ok(()) + let _ = (config, auth, codex_home, remote_plugin_id); + Err(RemotePluginCatalogError::Unavailable) } pub async fn update_remote_plugin_share_targets( @@ -304,233 +143,7 @@ pub async fn update_remote_plugin_share_targets( targets: Vec, discoverability: RemotePluginShareUpdateDiscoverability, ) -> Result { - let auth = ensure_chatgpt_auth(auth)?; - let target_discoverability = match discoverability { - RemotePluginShareUpdateDiscoverability::Listed => RemotePluginShareDiscoverability::Listed, - RemotePluginShareUpdateDiscoverability::Unlisted => { - RemotePluginShareDiscoverability::Unlisted - } - RemotePluginShareUpdateDiscoverability::Private => { - RemotePluginShareDiscoverability::Private - } - }; - let targets = - ensure_unlisted_workspace_target(auth, Some(target_discoverability), Some(targets))? - .unwrap_or_default(); - let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let url = format!("{base_url}/ps/plugins/{remote_plugin_id}/shares"); - let request = authenticated_request(config, Method::PUT, &url, auth) - .await? - .json(&RemotePluginShareUpdateTargetsRequest { - discoverability, - targets, - }); - let response: RemotePluginShareUpdateTargetsResponse = send_and_decode(request, &url).await?; - Ok(RemotePluginShareUpdateTargetsResult { - principals: response.principals, - discoverability: response.discoverability, - }) + let _ = (config, auth, remote_plugin_id, targets, discoverability); + Err(RemotePluginCatalogError::Unavailable) } -fn ensure_unlisted_workspace_target( - auth: &CodexAuth, - discoverability: Option, - targets: Option>, -) -> Result>, RemotePluginCatalogError> { - if discoverability != Some(RemotePluginShareDiscoverability::Unlisted) { - return Ok(targets); - } - let account_id = auth.get_account_id().ok_or_else(|| { - RemotePluginCatalogError::UnexpectedResponse( - "workspace plugin share requires an account id".to_string(), - ) - })?; - let mut targets = targets.unwrap_or_default(); - if !targets.iter().any(|target| { - target.principal_type == RemotePluginSharePrincipalType::Workspace - && target.principal_id == account_id - }) { - targets.push(RemotePluginShareTarget { - principal_type: RemotePluginSharePrincipalType::Workspace, - principal_id: account_id, - role: RemotePluginShareTargetRole::Reader, - }); - } - Ok(Some(targets)) -} - -async fn fetch_created_workspace_plugins( - config: &RemotePluginServiceConfig, - auth: &CodexAuth, -) -> Result, RemotePluginCatalogError> { - let mut plugins = Vec::new(); - let mut page_token = None; - loop { - let response = - get_created_workspace_plugins_page(config, auth, page_token.as_deref()).await?; - plugins.extend(response.plugins); - let Some(next_page_token) = response.pagination.next_page_token else { - break; - }; - page_token = Some(next_page_token); - } - Ok(plugins) -} - -async fn get_created_workspace_plugins_page( - config: &RemotePluginServiceConfig, - auth: &CodexAuth, - page_token: Option<&str>, -) -> Result { - let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let mut url = Url::parse(&format!("{base_url}/ps/plugins/workspace/created")) - .map_err(RemotePluginCatalogError::InvalidBaseUrl)?; - url.query_pairs_mut() - .append_pair("limit", &REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string()); - if let Some(page_token) = page_token { - url.query_pairs_mut().append_pair("pageToken", page_token); - } - let url = url.to_string(); - let request = authenticated_request(config, Method::GET, &url, auth).await?; - send_and_decode(request, &url).await -} - -async fn create_workspace_plugin_upload( - config: &RemotePluginServiceConfig, - auth: &CodexAuth, - filename: &str, - size_bytes: usize, - remote_plugin_id: Option<&str>, -) -> Result { - let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let url = format!("{base_url}/public/plugins/workspace/upload-url"); - let request = authenticated_request(config, Method::POST, &url, auth) - .await? - .json(&RemoteWorkspacePluginUploadUrlRequest { - filename, - mime_type: "application/gzip", - size_bytes, - plugin_id: remote_plugin_id, - }); - send_and_decode(request, &url).await -} - -async fn put_workspace_plugin_upload( - config: &RemotePluginServiceConfig, - upload_url: &str, - archive_bytes: Vec, -) -> Result<(), RemotePluginCatalogError> { - let request = config - .http_request(Method::PUT, upload_url) - .timeout(REMOTE_PLUGIN_CATALOG_TIMEOUT) - .header("x-ms-blob-type", "BlockBlob") - .header("Content-Type", "application/gzip") - .body(archive_bytes); - let response = request - .send() - .await - .map_err(|source| RemotePluginCatalogError::Request { - url: "workspace plugin upload URL".to_string(), - source, - })?; - let status = response.status(); - let body = response - .text() - .await - .map_err(|source| RemotePluginCatalogError::Request { - url: "workspace plugin upload URL".to_string(), - source, - })?; - if ![StatusCode::OK, StatusCode::CREATED].contains(&status) { - return Err(RemotePluginCatalogError::UnexpectedStatus { - url: "workspace plugin upload URL".to_string(), - status, - body, - }); - } - Ok(()) -} - -async fn finalize_workspace_plugin_upload( - config: &RemotePluginServiceConfig, - auth: &CodexAuth, - remote_plugin_id: Option<&str>, - body: RemoteWorkspacePluginCreateRequest, -) -> Result { - let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let url = if let Some(remote_plugin_id) = remote_plugin_id { - format!("{base_url}/public/plugins/workspace/{remote_plugin_id}") - } else { - format!("{base_url}/public/plugins/workspace") - }; - let request = authenticated_request(config, Method::POST, &url, auth) - .await? - .json(&body); - send_and_decode(request, &url).await -} - -fn archive_filename(plugin_path: &Path) -> Result { - let plugin_name = plugin_path - .file_name() - .and_then(|name| name.to_str()) - .ok_or_else(|| RemotePluginCatalogError::InvalidPluginPath { - path: plugin_path.to_path_buf(), - reason: "plugin path must end in a valid UTF-8 directory name".to_string(), - })?; - Ok(format!("{plugin_name}.tar.gz")) -} - -fn archive_plugin_for_upload(plugin_path: &Path) -> Result, RemotePluginCatalogError> { - archive_plugin_for_upload_with_limit(plugin_path, REMOTE_PLUGIN_SHARE_MAX_ARCHIVE_BYTES) -} - -fn archive_plugin_for_upload_with_limit( - plugin_path: &Path, - max_bytes: usize, -) -> Result, RemotePluginCatalogError> { - pack_plugin_bundle_tar_gz(plugin_path, max_bytes).map_err(|err| match err { - PluginBundlePackError::InvalidPluginPath { path, reason } => { - RemotePluginCatalogError::InvalidPluginPath { path, reason } - } - PluginBundlePackError::ArchiveTooLarge { bytes, max_bytes } => { - RemotePluginCatalogError::ArchiveTooLarge { bytes, max_bytes } - } - PluginBundlePackError::Io { source } => RemotePluginCatalogError::Archive { - path: plugin_path.to_path_buf(), - source, - }, - }) -} - -async fn send_and_expect_status( - request: RequestBuilder, - url_for_error: &str, - expected_statuses: &[StatusCode], -) -> Result<(), RemotePluginCatalogError> { - let response = request - .send() - .await - .map_err(|source| RemotePluginCatalogError::Request { - url: url_for_error.to_string(), - source, - })?; - let status = response.status(); - let body = response - .text() - .await - .map_err(|source| RemotePluginCatalogError::Request { - url: url_for_error.to_string(), - source, - })?; - if !expected_statuses.contains(&status) { - return Err(RemotePluginCatalogError::UnexpectedStatus { - url: url_for_error.to_string(), - status, - body, - }); - } - Ok(()) -} - -#[cfg(test)] -mod tests; diff --git a/codex-rs/core-plugins/src/remote/share/local_paths.rs b/codex-rs/core-plugins/src/remote/share/local_paths.rs index 50e8fba8..646687dd 100644 --- a/codex-rs/core-plugins/src/remote/share/local_paths.rs +++ b/codex-rs/core-plugins/src/remote/share/local_paths.rs @@ -35,16 +35,6 @@ pub(crate) fn record_plugin_share_local_path( write_plugin_share_local_paths(codex_home, mapping) } -pub(crate) fn remove_plugin_share_local_path( - codex_home: &Path, - remote_plugin_id: &str, -) -> io::Result<()> { - let _guard = lock_plugin_share_local_paths()?; - let mut mapping = read_plugin_share_local_paths_for_update(codex_home)?; - mapping.remove(remote_plugin_id); - write_plugin_share_local_paths(codex_home, mapping) -} - fn lock_plugin_share_local_paths() -> io::Result> { PLUGIN_SHARE_LOCAL_PATHS_LOCK .lock() diff --git a/codex-rs/core-plugins/src/remote/share/tests.rs b/codex-rs/core-plugins/src/remote/share/tests.rs deleted file mode 100644 index c5e05b63..00000000 --- a/codex-rs/core-plugins/src/remote/share/tests.rs +++ /dev/null @@ -1,824 +0,0 @@ -use super::*; -use crate::test_support::recorded_http_client_urls; -use crate::test_support::recording_remote_plugin_service_config; -use codex_app_server_protocol::PluginAuthPolicy; -use codex_app_server_protocol::PluginInstallPolicy; -use codex_app_server_protocol::PluginInterface; -use codex_login::CodexAuth; -use codex_utils_absolute_path::AbsolutePathBuf; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::collections::BTreeMap; -use std::fs; -use std::io::Read; -use std::path::Path; -use std::path::PathBuf; -use tempfile::TempDir; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::body_json; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; -use wiremock::matchers::query_param_is_missing; - -fn test_config(server: &MockServer) -> RemotePluginServiceConfig { - RemotePluginServiceConfig::new( - format!("{}/backend-api", server.uri()), - crate::test_support::test_http_client_factory(), - /*product_sku*/ None, - ) -} - -fn test_auth() -> CodexAuth { - CodexAuth::create_dummy_chatgpt_auth_for_testing() -} - -fn write_file(path: &Path, contents: &str) { - fs::create_dir_all(path.parent().expect("file should have a parent")).unwrap(); - fs::write(path, contents).unwrap(); -} - -fn write_test_plugin(root: &Path, plugin_name: &str) -> PathBuf { - let plugin_path = root.join(plugin_name); - write_file( - &plugin_path.join(".codex-plugin/plugin.json"), - &format!(r#"{{"name":"{plugin_name}"}}"#), - ); - write_file( - &plugin_path.join("skills/example/SKILL.md"), - "# Example\n\nA test skill.\n", - ); - plugin_path -} - -fn write_plugin_share_local_path_mapping( - codex_home: &Path, - remote_plugin_id: &str, - plugin_path: &AbsolutePathBuf, -) { - write_file( - &codex_home.join(".tmp/plugin-share-local-paths-v1.json"), - &format!( - "{}\n", - serde_json::to_string_pretty(&json!({ - "localPluginPathsByRemotePluginId": { - remote_plugin_id: plugin_path, - }, - })) - .unwrap() - ), - ); -} - -fn archive_file_entries(archive_bytes: &[u8]) -> BTreeMap> { - let decoder = flate2::read::GzDecoder::new(archive_bytes); - let mut archive = tar::Archive::new(decoder); - archive - .entries() - .unwrap() - .filter_map(|entry| { - let mut entry = entry.unwrap(); - if !entry.header().entry_type().is_file() { - return None; - } - let path = entry.path().unwrap().to_string_lossy().into_owned(); - let mut contents = Vec::new(); - entry.read_to_end(&mut contents).unwrap(); - Some((path, contents)) - }) - .collect() -} - -fn remote_plugin_json(plugin_id: &str) -> serde_json::Value { - json!({ - "id": plugin_id, - "name": "demo-plugin", - "scope": "WORKSPACE", - "discoverability": "PRIVATE", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "release": { - "version": "0.1.0", - "display_name": "Demo Plugin", - "description": "Demo plugin description", - "interface": { - "short_description": "A demo plugin", - "capabilities": ["Read", "Write"] - }, - "skills": [] - } - }) -} - -fn remote_plugin_json_with_share_url_and_principals( - plugin_id: &str, - share_url: Option<&str>, - share_principals: serde_json::Value, -) -> serde_json::Value { - let mut plugin = remote_plugin_json(plugin_id); - let serde_json::Value::Object(fields) = &mut plugin else { - unreachable!("plugin json should be an object"); - }; - fields.insert("discoverability".to_string(), json!("PRIVATE")); - fields.insert("share_url".to_string(), json!(share_url)); - fields.insert("share_principals".to_string(), share_principals); - plugin -} - -fn installed_remote_plugin_json(plugin_id: &str) -> serde_json::Value { - let mut plugin = remote_plugin_json(plugin_id); - let serde_json::Value::Object(fields) = &mut plugin else { - unreachable!("plugin json should be an object"); - }; - fields.insert("enabled".to_string(), json!(true)); - fields.insert("disabled_skill_names".to_string(), json!([])); - plugin -} - -fn empty_pagination_json() -> serde_json::Value { - json!({ - "next_page_token": null - }) -} - -fn expected_plugin_interface() -> PluginInterface { - PluginInterface { - display_name: Some("Demo Plugin".to_string()), - short_description: Some("A demo plugin".to_string()), - long_description: None, - developer_name: None, - category: None, - capabilities: vec!["Read".to_string(), "Write".to_string()], - website_url: None, - privacy_policy_url: None, - terms_of_service_url: None, - default_prompt: None, - brand_color: None, - composer_icon: None, - composer_icon_url: None, - logo: None, - logo_dark: None, - logo_url: None, - logo_url_dark: None, - screenshots: Vec::new(), - screenshot_urls: Vec::new(), - } -} - -#[tokio::test] -async fn save_remote_plugin_share_creates_workspace_plugin() { - let codex_home = TempDir::new().unwrap(); - let temp_dir = TempDir::new().unwrap(); - let plugin_path = - AbsolutePathBuf::try_from(write_test_plugin(temp_dir.path(), "demo-plugin")).unwrap(); - let archive_size = archive_plugin_for_upload(plugin_path.as_path()) - .unwrap() - .len(); - let server = MockServer::start().await; - let (config, selected_urls) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let auth = test_auth(); - - Mock::given(method("POST")) - .and(path("/backend-api/public/plugins/workspace/upload-url")) - .and(header("authorization", "Bearer Access Token")) - .and(header("chatgpt-account-id", "account_id")) - .and(body_json(json!({ - "filename": "demo-plugin.tar.gz", - "mime_type": "application/gzip", - "size_bytes": archive_size, - }))) - .respond_with(ResponseTemplate::new(201).set_body_json(json!({ - "file_id": "file_123", - "upload_url": format!("{}/upload/file_123", server.uri()), - "etag": "\"upload_etag_123\"", - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path("/upload/file_123")) - .and(header("x-ms-blob-type", "BlockBlob")) - .and(header("content-type", "application/gzip")) - .respond_with(ResponseTemplate::new(201).insert_header("etag", "\"blob_etag_123\"")) - .expect(1) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/backend-api/public/plugins/workspace")) - .and(header("authorization", "Bearer Access Token")) - .and(header("chatgpt-account-id", "account_id")) - .and(body_json(json!({ - "file_id": "file_123", - "etag": "\"upload_etag_123\"", - "discoverability": "UNLISTED", - "share_targets": [ - { - "principal_type": "user", - "principal_id": "user-1", - "role": "reader", - }, - { - "principal_type": "workspace", - "principal_id": "account_id", - "role": "reader", - }, - ], - }))) - .respond_with(ResponseTemplate::new(201).set_body_json(json!({ - "plugin_id": "plugins_123", - "share_url": "https://chatgpt.example/plugins/share/share-key-1", - "can_publish_to_workspace": true, - }))) - .expect(1) - .mount(&server) - .await; - - let result = save_remote_plugin_share( - &config, - Some(&auth), - codex_home.path(), - &plugin_path, - /*remote_plugin_id*/ None, - RemotePluginShareAccessPolicy { - discoverability: Some(RemotePluginShareDiscoverability::Unlisted), - share_targets: Some(vec![RemotePluginShareTarget { - principal_type: RemotePluginSharePrincipalType::User, - principal_id: "user-1".to_string(), - role: RemotePluginShareTargetRole::Reader, - }]), - }, - ) - .await - .unwrap(); - - assert_eq!( - result, - RemotePluginShareSaveResult { - remote_plugin_id: "plugins_123".to_string(), - share_url: Some("https://chatgpt.example/plugins/share/share-key-1".to_string()), - can_publish_to_workspace: Some(true), - } - ); - assert_eq!( - local_paths::load_plugin_share_local_paths(codex_home.path()).unwrap(), - BTreeMap::from([("plugins_123".to_string(), plugin_path)]) - ); - assert_eq!( - recorded_http_client_urls(&selected_urls), - vec![ - format!( - "{}/backend-api/public/plugins/workspace/upload-url", - server.uri() - ), - format!("{}/upload/file_123", server.uri()), - format!("{}/backend-api/public/plugins/workspace", server.uri()), - ] - ); - - let requests = server.received_requests().await.unwrap_or_default(); - let upload_request = requests - .iter() - .find(|request| request.method == "PUT" && request.url.path() == "/upload/file_123") - .unwrap(); - let archive_files = archive_file_entries(&upload_request.body); - assert_eq!( - archive_files - .get(".codex-plugin/plugin.json") - .map(Vec::as_slice), - Some(br#"{"name":"demo-plugin"}"#.as_slice()) - ); - assert_eq!( - archive_files - .get("skills/example/SKILL.md") - .map(Vec::as_slice), - Some(b"# Example\n\nA test skill.\n".as_slice()) - ); -} - -#[test] -fn archive_plugin_for_upload_rejects_archives_over_limit() { - let temp_dir = TempDir::new().unwrap(); - let plugin_path = write_test_plugin(temp_dir.path(), "demo-plugin"); - write_file( - &plugin_path.join("large.txt"), - &"0123456789abcdef".repeat(1024), - ); - - let err = archive_plugin_for_upload_with_limit(&plugin_path, /*max_bytes*/ 16) - .expect_err("oversized plugin archive should fail"); - - assert!(matches!( - err, - RemotePluginCatalogError::ArchiveTooLarge { .. } - )); -} - -#[test] -fn archive_plugin_for_upload_places_manifest_at_archive_root() { - let temp_dir = TempDir::new().unwrap(); - let plugin_path = write_test_plugin(temp_dir.path(), "demo-plugin"); - - let archive_bytes = archive_plugin_for_upload(&plugin_path).unwrap(); - let archive_files = archive_file_entries(&archive_bytes); - - assert_eq!( - archive_files.keys().cloned().collect::>(), - vec![ - ".codex-plugin/plugin.json".to_string(), - "skills/example/SKILL.md".to_string() - ] - ); - assert_eq!( - archive_files - .get(".codex-plugin/plugin.json") - .map(Vec::as_slice), - Some(br#"{"name":"demo-plugin"}"#.as_slice()) - ); - assert_eq!( - archive_files - .get("skills/example/SKILL.md") - .map(Vec::as_slice), - Some(b"# Example\n\nA test skill.\n".as_slice()) - ); -} - -#[test] -fn archive_plugin_for_upload_round_trips_through_plugin_bundle_archive_with_long_paths() { - let temp_dir = TempDir::new().unwrap(); - let plugin_path = write_test_plugin(temp_dir.path(), "demo-plugin"); - let long_skill_path = Path::new("skills") - .join(["segment"; 40].join("/")) - .join("SKILL.md"); - write_file(&plugin_path.join(&long_skill_path), "# Long path skill\n"); - - let archive_bytes = archive_plugin_for_upload(&plugin_path).unwrap(); - let destination = TempDir::new().unwrap(); - crate::plugin_bundle_archive::unpack_plugin_bundle_tar_gz( - &archive_bytes, - destination.path(), - /*max_total_bytes*/ 1024 * 1024, - ) - .expect("extract shared plugin archive"); - - assert_eq!( - fs::read_to_string(destination.path().join(".codex-plugin/plugin.json")).unwrap(), - r#"{"name":"demo-plugin"}"# - ); - assert_eq!( - fs::read_to_string(destination.path().join(long_skill_path)).unwrap(), - "# Long path skill\n" - ); -} - -#[tokio::test] -async fn save_remote_plugin_share_updates_existing_workspace_plugin() { - let codex_home = TempDir::new().unwrap(); - let temp_dir = TempDir::new().unwrap(); - let plugin_path = - AbsolutePathBuf::try_from(write_test_plugin(temp_dir.path(), "demo-plugin")).unwrap(); - let archive_size = archive_plugin_for_upload(plugin_path.as_path()) - .unwrap() - .len(); - let server = MockServer::start().await; - let config = test_config(&server); - let auth = test_auth(); - - Mock::given(method("POST")) - .and(path("/backend-api/public/plugins/workspace/upload-url")) - .and(body_json(json!({ - "filename": "demo-plugin.tar.gz", - "mime_type": "application/gzip", - "size_bytes": archive_size, - "plugin_id": "plugins_123", - }))) - .respond_with(ResponseTemplate::new(201).set_body_json(json!({ - "file_id": "file_456", - "upload_url": format!("{}/upload/file_456", server.uri()), - "etag": "\"upload_etag_456\"", - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path("/upload/file_456")) - .respond_with(ResponseTemplate::new(201).insert_header("etag", "\"blob_etag_456\"")) - .expect(1) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/backend-api/public/plugins/workspace/plugins_123")) - .and(body_json(json!({ - "file_id": "file_456", - "etag": "\"upload_etag_456\"", - }))) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugin_id": "plugins_123", - }))) - .expect(1) - .mount(&server) - .await; - - let result = save_remote_plugin_share( - &config, - Some(&auth), - codex_home.path(), - &plugin_path, - Some("plugins_123"), - RemotePluginShareAccessPolicy::default(), - ) - .await - .unwrap(); - - assert_eq!( - result, - RemotePluginShareSaveResult { - remote_plugin_id: "plugins_123".to_string(), - share_url: None, - can_publish_to_workspace: None, - } - ); -} - -#[tokio::test] -async fn update_remote_plugin_share_targets_updates_targets() { - let server = MockServer::start().await; - let config = test_config(&server); - let auth = test_auth(); - - Mock::given(method("PUT")) - .and(path("/backend-api/ps/plugins/plugins_123/shares")) - .and(header("authorization", "Bearer Access Token")) - .and(header("chatgpt-account-id", "account_id")) - .and(body_json(json!({ - "discoverability": "UNLISTED", - "targets": [ - { - "principal_type": "user", - "principal_id": "user-1", - "role": "editor", - }, - { - "principal_type": "group", - "principal_id": "group-1", - "role": "reader", - }, - { - "principal_type": "workspace", - "principal_id": "account_id", - "role": "reader", - }, - ], - }))) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "principals": [ - { - "principal_type": "user", - "principal_id": "user-1", - "role": "editor", - "name": "Gavin", - }, - { - "principal_type": "group", - "principal_id": "group-1", - "role": "reader", - "name": "Engineering", - }, - ], - "discoverability": "UNLISTED", - }))) - .expect(1) - .mount(&server) - .await; - - let result = update_remote_plugin_share_targets( - &config, - Some(&auth), - "plugins_123", - vec![ - RemotePluginShareTarget { - principal_type: RemotePluginSharePrincipalType::User, - principal_id: "user-1".to_string(), - role: RemotePluginShareTargetRole::Editor, - }, - RemotePluginShareTarget { - principal_type: RemotePluginSharePrincipalType::Group, - principal_id: "group-1".to_string(), - role: RemotePluginShareTargetRole::Reader, - }, - ], - RemotePluginShareUpdateDiscoverability::Unlisted, - ) - .await - .unwrap(); - - assert_eq!( - result, - RemotePluginShareUpdateTargetsResult { - principals: vec![ - RemotePluginSharePrincipal { - principal_type: RemotePluginSharePrincipalType::User, - principal_id: "user-1".to_string(), - role: RemotePluginSharePrincipalRole::Editor, - name: "Gavin".to_string(), - }, - RemotePluginSharePrincipal { - principal_type: RemotePluginSharePrincipalType::Group, - principal_id: "group-1".to_string(), - role: RemotePluginSharePrincipalRole::Reader, - name: "Engineering".to_string(), - }, - ], - discoverability: RemotePluginShareDiscoverability::Unlisted, - } - ); -} - -#[tokio::test] -async fn list_remote_plugin_shares_fetches_created_workspace_plugins() { - let codex_home = TempDir::new().unwrap(); - let local_plugin_path = - AbsolutePathBuf::try_from(codex_home.path().join("local-plugin")).unwrap(); - write_plugin_share_local_path_mapping(codex_home.path(), "plugins_123", &local_plugin_path); - let server = MockServer::start().await; - let config = test_config(&server); - let auth = test_auth(); - - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/workspace/created")) - .and(header("authorization", "Bearer Access Token")) - .and(header("chatgpt-account-id", "account_id")) - .and(query_param( - "limit", - REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string(), - )) - .and(query_param_is_missing("pageToken")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [remote_plugin_json_with_share_url_and_principals( - "plugins_123", - Some("https://chatgpt.example/plugins/share/share-key-1"), - json!([ - { - "principal_type": "user", - "principal_id": "user-owner", - "role": "owner", - "name": "Owner", - }, - { - "principal_type": "user", - "principal_id": "user-reader", - "role": "reader", - "name": "Reader", - }, - ]), - )], - "pagination": { - "next_page_token": "page-2" - }, - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/workspace/created")) - .and(header("authorization", "Bearer Access Token")) - .and(header("chatgpt-account-id", "account_id")) - .and(query_param( - "limit", - REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string(), - )) - .and(query_param("pageToken", "page-2")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [remote_plugin_json_with_share_url_and_principals( - "plugins_456", - /*share_url*/ None, - json!([ - { - "principal_type": "user", - "principal_id": "user-owner", - "role": "owner", - "name": "Owner", - }, - { - "principal_type": "user", - "principal_id": "user-editor", - "role": "editor", - "name": "Editor", - }, - ]), - )], - "pagination": empty_pagination_json(), - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("scope", "WORKSPACE")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [installed_remote_plugin_json("plugins_456")], - "pagination": empty_pagination_json(), - }))) - .expect(1) - .mount(&server) - .await; - - let result = list_remote_plugin_shares(&config, Some(&auth), codex_home.path()) - .await - .unwrap(); - - assert_eq!( - result, - vec![ - RemotePluginShareSummary { - summary: RemotePluginSummary { - id: "demo-plugin@workspace-shared-with-me".to_string(), - remote_plugin_id: "plugins_123".to_string(), - version: Some("0.1.0".to_string()), - local_version: None, - name: "demo-plugin".to_string(), - share_context: Some(RemotePluginShareContext { - remote_plugin_id: "plugins_123".to_string(), - remote_version: Some("0.1.0".to_string()), - discoverability: RemotePluginShareDiscoverability::Private, - share_url: Some( - "https://chatgpt.example/plugins/share/share-key-1".to_string(), - ), - creator_account_user_id: None, - creator_name: None, - share_principals: Some(vec![ - RemotePluginSharePrincipal { - principal_type: RemotePluginSharePrincipalType::User, - principal_id: "user-owner".to_string(), - role: RemotePluginSharePrincipalRole::Owner, - name: "Owner".to_string(), - }, - RemotePluginSharePrincipal { - principal_type: RemotePluginSharePrincipalType::User, - principal_id: "user-reader".to_string(), - role: RemotePluginSharePrincipalRole::Reader, - name: "Reader".to_string(), - }, - ]), - can_publish_to_workspace: None, - }), - installed: false, - installed_at: None, - enabled: false, - install_policy: PluginInstallPolicy::Available, - install_policy_source: None, - must_show_installation_interstitial: None, - auth_policy: PluginAuthPolicy::OnUse, - availability: PluginAvailability::Available, - disabled_reason: None, - eligible_plan_types: None, - interface: Some(expected_plugin_interface()), - keywords: Vec::new(), - }, - local_plugin_path: Some(local_plugin_path), - }, - RemotePluginShareSummary { - summary: RemotePluginSummary { - id: "demo-plugin@workspace-shared-with-me".to_string(), - remote_plugin_id: "plugins_456".to_string(), - version: Some("0.1.0".to_string()), - local_version: Some("0.1.0".to_string()), - name: "demo-plugin".to_string(), - share_context: Some(RemotePluginShareContext { - remote_plugin_id: "plugins_456".to_string(), - remote_version: Some("0.1.0".to_string()), - discoverability: RemotePluginShareDiscoverability::Private, - share_url: None, - creator_account_user_id: None, - creator_name: None, - share_principals: Some(vec![ - RemotePluginSharePrincipal { - principal_type: RemotePluginSharePrincipalType::User, - principal_id: "user-owner".to_string(), - role: RemotePluginSharePrincipalRole::Owner, - name: "Owner".to_string(), - }, - RemotePluginSharePrincipal { - principal_type: RemotePluginSharePrincipalType::User, - principal_id: "user-editor".to_string(), - role: RemotePluginSharePrincipalRole::Editor, - name: "Editor".to_string(), - }, - ]), - can_publish_to_workspace: None, - }), - installed: true, - installed_at: None, - enabled: true, - install_policy: PluginInstallPolicy::Available, - install_policy_source: None, - must_show_installation_interstitial: None, - auth_policy: PluginAuthPolicy::OnUse, - availability: PluginAvailability::Available, - disabled_reason: None, - eligible_plan_types: None, - interface: Some(expected_plugin_interface()), - keywords: Vec::new(), - }, - local_plugin_path: None, - } - ] - ); -} - -#[tokio::test] -async fn delete_remote_plugin_share_deletes_workspace_plugin() { - let codex_home = TempDir::new().unwrap(); - let local_plugin_path = - AbsolutePathBuf::try_from(codex_home.path().join("local-plugin")).unwrap(); - write_plugin_share_local_path_mapping(codex_home.path(), "plugins_123", &local_plugin_path); - let server = MockServer::start().await; - let config = test_config(&server); - let auth = test_auth(); - - Mock::given(method("DELETE")) - .and(path("/backend-api/public/plugins/workspace/plugins_123")) - .and(header("authorization", "Bearer Access Token")) - .and(header("chatgpt-account-id", "account_id")) - .respond_with(ResponseTemplate::new(204)) - .expect(1) - .mount(&server) - .await; - - delete_remote_plugin_share(&config, Some(&auth), codex_home.path(), "plugins_123") - .await - .unwrap(); - assert_eq!( - local_paths::load_plugin_share_local_paths(codex_home.path()).unwrap(), - BTreeMap::new() - ); -} - -#[tokio::test] -async fn revoked_success_body_is_a_request_error() { - for method in [Method::PUT, Method::POST] { - use tokio::io::AsyncReadExt; - use tokio::io::AsyncWriteExt; - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}/upload", listener.local_addr().unwrap()); - let controller = codex_http_client::NetworkPolicyController::default(); - let policy = controller.policy(); - controller.publish( - policy.revision(), - codex_http_client::DestinationPolicy::Unrestricted, - ); - let config = RemotePluginServiceConfig::new( - url.clone(), - crate::test_support::test_http_client_factory().with_network_policy(policy), - /*product_sku*/ None, - ); - let server = async { - let (mut socket, _) = listener.accept().await.unwrap(); - let mut headers = Vec::new(); - while !headers.ends_with(b"\r\n\r\n") { - headers.push(socket.read_u8().await.unwrap()); - } - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\na") - .await - .unwrap(); - // Let the client consume the successful headers and wait for the remaining body. - tokio::time::sleep(std::time::Duration::from_millis(/*millis*/ 50)).await; - controller.publish( - controller.policy().revision(), - codex_http_client::DestinationPolicy::Restricted { - allowed_hosts: Default::default(), - }, - ); - }; - let operation = async { - if method == Method::PUT { - put_workspace_plugin_upload(&config, &url, Vec::new()).await - } else { - send_and_expect_status(config.http_request(method, &url), &url, &[StatusCode::OK]) - .await - } - }; - let (result, ()) = - tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 5), async { - tokio::join!(operation, server) - }) - .await - .unwrap(); - assert!( - matches!( - result, - Err(RemotePluginCatalogError::Request { - source: codex_http_client::RouteAwareRequestError::Policy( - codex_http_client::NetworkPolicyDenied::Revoked - ), - .. - }) - ), - "{result:?}" - ); - } -} diff --git a/codex-rs/core-plugins/src/remote_bundle.rs b/codex-rs/core-plugins/src/remote_bundle.rs index 9292e2c2..8cf9ad2b 100644 --- a/codex-rs/core-plugins/src/remote_bundle.rs +++ b/codex-rs/core-plugins/src/remote_bundle.rs @@ -8,7 +8,6 @@ use crate::store::PluginStore; use crate::store::PluginStoreError; use crate::store::error_context_sub_error_type; use crate::store::validate_plugin_version_segment; -use codex_http_client::HttpResponse; use codex_http_client::RouteAwareRequestError; use codex_plugin::PluginId; use codex_plugin::PluginIdError; @@ -17,20 +16,16 @@ use codex_utils_plugins::AGENT_PLUGIN_MANIFEST_RELATIVE_PATH; use codex_utils_plugins::AgentPluginSchemaStatus; use codex_utils_plugins::agent_plugin_schema_status; use codex_utils_plugins::find_plugin_manifest_path; -use http::Method; use http::StatusCode; use serde_json::Value as JsonValue; use std::fs; use std::io; use std::path::Path; use std::path::PathBuf; -use std::time::Duration; use url::Host; use url::Url; -const REMOTE_PLUGIN_BUNDLE_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(60); const REMOTE_PLUGIN_BUNDLE_MAX_DOWNLOAD_BYTES: u64 = 100 * 1024 * 1024; -const REMOTE_PLUGIN_BUNDLE_ERROR_BODY_MAX_BYTES: u64 = 8 * 1024; const REMOTE_PLUGIN_BUNDLE_MAX_EXTRACTED_BYTES: u64 = 512 * 1024 * 1024; const REMOTE_PLUGIN_INSTALL_STAGING_DIR: &str = "plugins/.remote-plugin-install-staging"; #[cfg(debug_assertions)] @@ -59,6 +54,9 @@ impl std::fmt::Debug for ValidatedRemotePluginBundle { #[derive(Debug, thiserror::Error)] pub enum RemotePluginBundleInstallError { + #[error("remote plugin bundles are not available in aKode")] + Unavailable, + #[error("backend did not return a release version for remote plugin `{remote_plugin_id}`")] MissingReleaseVersion { remote_plugin_id: String }, @@ -159,7 +157,8 @@ impl RemotePluginBundleInstallError { Self::DownloadStatus { status, .. } => { Some(http_status_sub_error_type(*status).to_string()) } - Self::MissingReleaseVersion { .. } + Self::Unavailable + | Self::MissingReleaseVersion { .. } | Self::InvalidReleaseVersion { .. } | Self::MissingBundleDownloadUrl { .. } | Self::InvalidBundleDownloadUrl { .. } @@ -316,111 +315,8 @@ async fn download_remote_plugin_bundle_with_limit( bundle_download_url: &str, max_bytes: u64, ) -> Result, RemotePluginBundleInstallError> { - let response = config - .http_request(Method::GET, bundle_download_url) - .timeout(REMOTE_PLUGIN_BUNDLE_DOWNLOAD_TIMEOUT) - .send() - .await - .map_err(|source| RemotePluginBundleInstallError::DownloadRequest { - host: Url::parse(bundle_download_url) - .ok() - .and_then(|url| url.host_str().map(str::to_owned)) - .unwrap_or_else(|| "unknown-host".to_string()), - source: source.without_url(), - })?; - - let final_url = response.url().clone(); - // Keep only the host in URL error fields. - let host = final_url.host_str().unwrap_or("unknown-host").to_string(); - // The shared client has already followed redirects here. Reject an unsupported final scheme - // before caching a backend-issued bundle. - if !is_allowed_bundle_download_url(&final_url, allow_test_loopback_http_bundle_downloads()) { - return Err( - RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { - host, - scheme: final_url.scheme().to_string(), - }, - ); - } - - let status = response.status(); - if !status.is_success() { - let mut response = response; - let mut body = Vec::new(); - let mut body_truncated = false; - let mut body_read_error = None; - loop { - let chunk = match response.chunk().await { - Ok(Some(chunk)) => chunk, - Ok(None) => break, - Err(source) => { - body_read_error = Some(source.without_url()); - break; - } - }; - let remaining = REMOTE_PLUGIN_BUNDLE_ERROR_BODY_MAX_BYTES as usize - body.len(); - if chunk.len() > remaining { - body.extend_from_slice(&chunk[..remaining]); - body_truncated = true; - break; - } - body.extend_from_slice(&chunk); - } - - let mut body = String::from_utf8_lossy(&body).into_owned(); - if body_truncated { - body.push_str(&format!( - "\n[response body truncated after {REMOTE_PLUGIN_BUNDLE_ERROR_BODY_MAX_BYTES} bytes]" - )); - } - if let Some(source) = body_read_error { - body.push_str(&format!("\n[failed to read response body: {source}]")); - } - return Err(RemotePluginBundleInstallError::DownloadStatus { host, status, body }); - } - - read_response_body_with_limit(response, &host, max_bytes).await -} - -async fn read_response_body_with_limit( - mut response: HttpResponse, - host: &str, - max_bytes: u64, -) -> Result, RemotePluginBundleInstallError> { - if let Some(content_length) = response.content_length() { - enforce_download_size_limit(host, content_length, max_bytes)?; - } - - let mut body = Vec::new(); - while let Some(chunk) = - response - .chunk() - .await - .map_err(|source| RemotePluginBundleInstallError::DownloadBody { - host: host.to_string(), - source: source.without_url(), - })? - { - let next_len = body.len() as u64 + chunk.len() as u64; - enforce_download_size_limit(host, next_len, max_bytes)?; - body.extend_from_slice(&chunk); - } - - Ok(body) -} - -fn enforce_download_size_limit( - host: &str, - bytes: u64, - max_bytes: u64, -) -> Result<(), RemotePluginBundleInstallError> { - if bytes > max_bytes { - return Err(RemotePluginBundleInstallError::DownloadTooLarge { - host: host.to_string(), - max_bytes, - }); - } - Ok(()) + let _ = (config, bundle_download_url, max_bytes); + Err(RemotePluginBundleInstallError::Unavailable) } pub(crate) fn install_remote_plugin_bundle( @@ -657,19 +553,11 @@ fn is_standard_plugin_root(path: &Path) -> bool { #[cfg(test)] mod tests { use super::*; - use crate::test_support::recorded_http_client_urls; - use crate::test_support::recording_remote_plugin_service_config; use flate2::Compression; use flate2::write::GzEncoder; use pretty_assertions::assert_eq; use std::io::Write; use tempfile::tempdir; - use wiremock::Mock; - use wiremock::MockServer; - use wiremock::ResponseTemplate; - use wiremock::matchers::method; - use wiremock::matchers::path; - use wiremock::matchers::query_param; const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_00000000000000000000000000000000"; @@ -783,49 +671,6 @@ mod tests { )); } - #[test] - fn download_size_limit_rejects_oversized_bundle() { - let err = - enforce_download_size_limit("example.com", /*bytes*/ 5, /*max_bytes*/ 4) - .expect_err("oversized bundle download should fail"); - - assert!(matches!( - err, - RemotePluginBundleInstallError::DownloadTooLarge { .. } - )); - } - - #[tokio::test] - async fn bundle_download_routes_the_backend_supplied_url() { - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/signed/plugin-bundle")) - .and(query_param("sig", "signed-token")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(b"bundle")) - .expect(1) - .mount(&server) - .await; - let (config, selected_urls) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let download_url = format!("{}/signed/plugin-bundle?sig=signed-token", server.uri()); - - let err = - download_remote_plugin_bundle_with_limit(&config, &download_url, /*max_bytes*/ 64) - .await - .expect_err("plain HTTP final URL should remain unsupported"); - - assert!(matches!( - err, - RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { .. } - )); - assert!(!err.to_string().contains("signed-token")); - assert!(!format!("{err:?}").contains("signed-token")); - assert_eq!( - recorded_http_client_urls(&selected_urls), - vec![download_url] - ); - } - #[test] fn install_rejects_invalid_tar_gz_bundle() { let codex_home = tempdir().expect("tempdir"); @@ -1148,7 +993,3 @@ mod tests { } } } - -#[cfg(test)] -#[path = "remote_bundle_runtime_auth_tests.rs"] -mod runtime_auth_tests; diff --git a/codex-rs/core-plugins/src/remote_bundle_runtime_auth_tests.rs b/codex-rs/core-plugins/src/remote_bundle_runtime_auth_tests.rs deleted file mode 100644 index 2ca0934e..00000000 --- a/codex-rs/core-plugins/src/remote_bundle_runtime_auth_tests.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! Runtime-authenticated catalogs keep presigned bundle transfers unauthenticated. - -use super::*; -use codex_features::RuntimeAuthMode; -use codex_http_client::HttpClientFactory; -use codex_http_client::OutboundProxyPolicy; -use pretty_assertions::assert_eq; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::path; - -#[tokio::test] -async fn runtime_bundle_download_follows_redirect_without_actor_auth() { - let origin = MockServer::start().await; - let destination = MockServer::start().await; - let final_url = format!("{}/bundle", destination.uri()); - Mock::given(path("/bundle")) - .respond_with(ResponseTemplate::new(307).insert_header("location", &final_url)) - .expect(1) - .mount(&origin) - .await; - Mock::given(path("/bundle")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(b"bundle")) - .expect(1) - .mount(&destination) - .await; - let config = RemotePluginServiceConfig::new_with_selected_runtime_auth( - origin.uri(), - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - /*product_sku*/ None, - (Default::default(), RuntimeAuthMode::AssertionOnly), - ); - let error = download_remote_plugin_bundle_with_limit( - &config, - &format!("{}/bundle", origin.uri()), - /*max_bytes*/ 64, - ) - .await - .expect_err("HTTP final URLs remain unsupported after following redirects"); - assert!( - matches!( - &error, - RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { .. } - ), - "expected rejection of the HTTP redirect destination: {error}" - ); - let mut requests = origin.received_requests().await.unwrap(); - requests.extend(destination.received_requests().await.unwrap()); - assert_eq!(requests.len(), 2); - for request in requests { - assert!(!request.headers.contains_key("authorization")); - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - } -} diff --git a/codex-rs/core-plugins/src/remote_legacy.rs b/codex-rs/core-plugins/src/remote_legacy.rs index 3d5e94af..8182781b 100644 --- a/codex-rs/core-plugins/src/remote_legacy.rs +++ b/codex-rs/core-plugins/src/remote_legacy.rs @@ -3,14 +3,8 @@ use crate::remote::RemotePluginServiceConfig; use codex_http_client::RouteAwareRequestError; use codex_login::CodexAuth; use codex_protocol::protocol::Product; -use http::Method; use http::StatusCode; use serde::Deserialize; -use std::time::Duration; -use url::Url; - -const REMOTE_FEATURED_PLUGIN_FETCH_TIMEOUT: Duration = Duration::from_secs(10); -const REMOTE_PLUGIN_MUTATION_TIMEOUT: Duration = Duration::from_secs(30); #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(rename_all = "camelCase")] @@ -21,6 +15,9 @@ struct RemotePluginMutationResponse { #[derive(Debug, thiserror::Error)] pub enum RemotePluginMutationError { + #[error("remote plugins are not available in aKode")] + Unavailable, + #[error("chatgpt authentication required for remote plugin mutation")] AuthRequired, @@ -80,7 +77,8 @@ impl RemotePluginMutationError { Self::UnexpectedStatus { status, .. } => { Some(http_status_sub_error_type(*status).to_string()) } - Self::AuthRequired + Self::Unavailable + | Self::AuthRequired | Self::UnsupportedAuthMode | Self::AuthToken(_) | Self::InvalidBaseUrl(_) @@ -127,41 +125,8 @@ pub async fn fetch_remote_featured_plugin_ids( auth: Option<&CodexAuth>, product: Option, ) -> Result, RemotePluginFetchError> { - let base_url = config.chatgpt_base_url.trim_end_matches('/'); - let mut url = Url::parse(&format!("{base_url}/plugins/featured")) - .map_err(RemotePluginFetchError::InvalidBaseUrl)?; - url.query_pairs_mut().append_pair( - "platform", - product.unwrap_or(Product::Codex).to_app_platform(), - ); - let url = url.to_string(); - let request = match auth.filter(|auth| auth.uses_codex_backend()) { - Some(auth) => config - .authenticated_request(Method::GET, &url, auth) - .await - .map_err(std::io::Error::other) - .map_err(RemotePluginFetchError::AuthToken)?, - None => config.http_request(Method::GET, &url), - } - .timeout(REMOTE_FEATURED_PLUGIN_FETCH_TIMEOUT); - - let response = request - .send() - .await - .map_err(|source| RemotePluginFetchError::Request { - url: url.clone(), - source, - })?; - let status = response.status(); - let body = response.text().await.unwrap_or_default(); - if !status.is_success() { - return Err(RemotePluginFetchError::UnexpectedStatus { url, status, body }); - } - - serde_json::from_str(&body).map_err(|source| RemotePluginFetchError::Decode { - url: url.clone(), - source, - }) + let _ = (config, auth, product); + Ok(Vec::new()) } pub async fn enable_remote_plugin( @@ -182,84 +147,12 @@ pub async fn uninstall_remote_plugin( Ok(()) } -fn ensure_codex_backend_auth( - auth: Option<&CodexAuth>, -) -> Result<&CodexAuth, RemotePluginMutationError> { - let Some(auth) = auth else { - return Err(RemotePluginMutationError::AuthRequired); - }; - if !auth.uses_codex_backend() { - return Err(RemotePluginMutationError::UnsupportedAuthMode); - } - Ok(auth) -} - async fn post_remote_plugin_mutation( config: &RemotePluginServiceConfig, auth: Option<&CodexAuth>, plugin_id: &str, action: &str, ) -> Result { - let auth = ensure_codex_backend_auth(auth)?; - let url = remote_plugin_mutation_url(config, plugin_id, action)?; - let request = config - .authenticated_request(Method::POST, &url, auth) - .await - .map_err(std::io::Error::other) - .map_err(RemotePluginMutationError::AuthToken)? - .timeout(REMOTE_PLUGIN_MUTATION_TIMEOUT); - - let response = request - .send() - .await - .map_err(|source| RemotePluginMutationError::Request { - url: url.clone(), - source, - })?; - let status = response.status(); - let body = response.text().await.unwrap_or_default(); - if !status.is_success() { - return Err(RemotePluginMutationError::UnexpectedStatus { url, status, body }); - } - - let parsed: RemotePluginMutationResponse = - serde_json::from_str(&body).map_err(|source| RemotePluginMutationError::Decode { - url: url.clone(), - source, - })?; - let expected_enabled = action == "enable"; - if parsed.id != plugin_id { - return Err(RemotePluginMutationError::UnexpectedPluginId { - expected: plugin_id.to_string(), - actual: parsed.id, - }); - } - if parsed.enabled != expected_enabled { - return Err(RemotePluginMutationError::UnexpectedEnabledState { - plugin_id: plugin_id.to_string(), - expected_enabled, - actual_enabled: parsed.enabled, - }); - } - - Ok(parsed) -} - -fn remote_plugin_mutation_url( - config: &RemotePluginServiceConfig, - plugin_id: &str, - action: &str, -) -> Result { - let mut url = Url::parse(config.chatgpt_base_url.trim_end_matches('/')) - .map_err(RemotePluginMutationError::InvalidBaseUrl)?; - { - let mut segments = url - .path_segments_mut() - .map_err(|()| RemotePluginMutationError::InvalidBaseUrlPath)?; - segments.pop_if_empty(); - segments.push("plugins"); - segments.push(plugin_id); - segments.push(action); - } - Ok(url.to_string()) + let _ = (config, auth, plugin_id, action); + Err(RemotePluginMutationError::Unavailable) } diff --git a/codex-rs/core-plugins/src/remote_mutations.rs b/codex-rs/core-plugins/src/remote_mutations.rs index 0ec012d2..4878d241 100644 --- a/codex-rs/core-plugins/src/remote_mutations.rs +++ b/codex-rs/core-plugins/src/remote_mutations.rs @@ -22,9 +22,6 @@ use codex_plugin::PluginId; use codex_plugin::PluginTelemetryMetadata; use std::sync::Arc; -#[cfg(test)] -#[path = "remote_mutations_tests.rs"] -mod tests; pub struct RemotePluginInstallRequest { pub marketplace_name: String, diff --git a/codex-rs/core-plugins/src/remote_mutations_tests.rs b/codex-rs/core-plugins/src/remote_mutations_tests.rs deleted file mode 100644 index f82d3bc4..00000000 --- a/codex-rs/core-plugins/src/remote_mutations_tests.rs +++ /dev/null @@ -1,473 +0,0 @@ -//! Regression coverage for remote mutations and account-bound storage transfers. - -use super::*; -use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME; -use crate::test_support::load_plugins_config; -use crate::test_support::test_auth_manager; -use crate::test_support::test_plugins_manager_with_auth_manager; -use crate::test_support::write_file; -use codex_protocol::auth::AuthMode; -use codex_utils_absolute_path::AbsolutePathBuf; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering; -use tempfile::TempDir; -use tokio::sync::Notify; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; - -#[tokio::test] -async fn uninstall_serializes_backend_mutations_and_preserves_cache_on_failure() { - for uninstall_fails in [false, true] { - let home = TempDir::new().unwrap(); - let server = MockServer::start().await; - let mut config = load_plugins_config(home.path(), home.path()).await; - config.chatgpt_base_url = format!("{}/backend-api", server.uri()); - let auth_manager = test_auth_manager(Some(AuthMode::Chatgpt)); - let auth = auth_manager.auth().await; - let manager = Arc::new(test_plugins_manager_with_auth_manager( - home.path().to_path_buf(), - /*restriction_product*/ None, - auth_manager, - )); - let remote_id = "b1234567-89ab-4cde-8f01-234567890abc"; - let plugin_id = PluginId::new( - "sample".to_string(), - REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(), - ) - .unwrap(); - let cache = manager.store.plugin_base_root(&plugin_id); - write_file( - cache.join("1.0.0/.codex-plugin/plugin.json").as_path(), - r#"{"name":"sample","version":"1.0.0"}"#, - ); - Mock::given(method("GET")) - .and(path(format!("/backend-api/ps/plugins/{remote_id}"))) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "id": remote_id, "name": "sample", "scope": "GLOBAL", - "installation_policy": "AVAILABLE", "authentication_policy": "ON_USE", - "release": {"display_name": "Sample", "description": "Sample plugin", "interface": {}} - }))).mount(&server).await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .respond_with( - ResponseTemplate::new(200) - .set_body_json(json!({"plugins": [], "pagination": {"next_page_token": null}})), - ) - .expect(if uninstall_fails { 0 } else { 1 }) - .mount(&server) - .await; - let gate_held = Arc::new(AtomicBool::new(false)); - let gate_held_at_post = Arc::clone(&gate_held); - let manager_at_post = Arc::clone(&manager); - Mock::given(method("POST")) - .and(path(format!( - "/backend-api/ps/plugins/{remote_id}/uninstall" - ))) - .respond_with(move |_: &wiremock::Request| { - gate_held_at_post.store( - manager_at_post - .remote_installed_plugin_bundle_sync_gate - .available_permits() - == 0, - Ordering::SeqCst, - ); - ResponseTemplate::new(if uninstall_fails { 400 } else { 200 }) - .set_body_json(json!({"id": remote_id, "enabled": false})) - }) - .expect(1) - .mount(&server) - .await; - let refreshed = Arc::new(Notify::new()); - let refreshed_callback = Arc::clone(&refreshed); - let outcome = manager - .uninstall_remote_plugin( - &config, - auth.as_ref(), - remote_id, - Some(Arc::new(move |_| refreshed_callback.notify_one())), - ) - .await; - assert_eq!( - ( - gate_held.load(Ordering::SeqCst), - manager - .remote_installed_plugin_bundle_sync_gate - .available_permits(), - cache.as_path().exists(), - outcome.is_err() - ), - (true, 1, uninstall_fails, uninstall_fails), - ); - if !uninstall_fails { - tokio::time::timeout(std::time::Duration::from_secs(5), refreshed.notified()) - .await - .expect("successful uninstall should refresh installed state"); - } - } -} - -/// Switch only after metadata has been read, immediately before constructing the storage request. -/// Metadata-body cancellation would not exercise the separate request these tests protect. -#[derive(Clone)] -struct TransferHttpClients { - delegate: codex_http_client::RouteAwareClientPool, - controller: codex_http_client::NetworkPolicyController, - switch_before_storage: Arc, - api_origin: String, - storage_origin: String, -} - -impl std::fmt::Debug for TransferHttpClients { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("TransferHttpClients") - .finish_non_exhaustive() - } -} - -impl crate::http_client_selector::HttpClientSelector for TransferHttpClients { - fn for_current_account(&self) -> Arc { - Arc::new(Self { - delegate: self.delegate.for_current_account(), - ..self.clone() - }) - } - - fn request(&self, method: http::Method, url: &str) -> codex_http_client::RequestBuilder { - if url.starts_with("https://storage.example/") - && self.switch_before_storage.swap(false, Ordering::SeqCst) - { - let policy = self.controller.policy(); - policy.invalidate(); - assert!(self.controller.publish( - policy.revision(), - codex_http_client::DestinationPolicy::Unrestricted, - )); - } - self.delegate.request( - method, - url.replace("https://storage.example", &self.storage_origin) - .replace("https://chatgpt.com", &self.api_origin), - ) - } - - fn request_for_account( - &self, - method: http::Method, - url: &str, - binding: &codex_http_client::NetworkPolicy, - ) -> Option { - Some( - self.delegate - .with_account_binding(binding)? - .request(method, url.replace("https://chatgpt.com", &self.api_origin)), - ) - } - - fn outbound_proxy_policy(&self) -> codex_http_client::OutboundProxyPolicy { - self.delegate.outbound_proxy_policy() - } -} - -struct PluginTransferTest { - api: MockServer, - storage: MockServer, - config: PluginsConfigInput, - manager: Arc, - auth: CodexAuth, - switch_before_storage: Arc, -} - -impl PluginTransferTest { - async fn new( - home: &std::path::Path, - mode: codex_features::RuntimeAuthMode, - switch: bool, - ) -> Self { - use base64::Engine; - use codex_http_client::ClientRouteClass; - use codex_http_client::DestinationPolicy; - use codex_http_client::HttpClientFactory; - use codex_http_client::NetworkPolicyController; - use codex_http_client::OutboundProxyPolicy; - use codex_http_client::RouteAwareClientPool; - use codex_runtime_agent_instance::AgentHostAuthorization; - use codex_runtime_agent_instance::RuntimeAuthManager; - use codex_runtime_agent_instance::RuntimeAuthSlot; - use codex_runtime_agent_instance::RuntimeRegistrationMetadata; - use codex_runtime_agent_instance::RuntimeRole; - - let api = MockServer::start().await; - let storage = MockServer::start().await; - Mock::given(path("/agent/register")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "runtime_agent_instance_id": "runtime-plugins", "agent_host_id": "host-a", - "actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "account-a"}, - }))) - .expect(1) - .mount(&api) - .await; - let claims = json!({ - "iss": "https://auth.openai.com/", "session_id": "login-a", - "https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "account-a"}, - }); - let token = format!( - "header.{}.signature", - base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string()), - ); - let auth = CodexAuth::from_external_chatgpt_tokens( - &token, - "account-a", - /*chatgpt_plan_type*/ None, - ) - .unwrap(); - let credentials = codex_login::AuthManager::from_auth_for_testing(auth.clone()); - let slot = RuntimeAuthSlot::default(); - slot.set(Arc::new(RuntimeAuthManager::new( - Arc::clone(&credentials), - AgentHostAuthorization::InstallationId { - installation_id: uuid::Uuid::nil(), - }, - RuntimeRegistrationMetadata { - harness: Some("codex".into()), - harness_version: None, - role: RuntimeRole::Orchestrator, - }, - format!("{}/agent/register", api.uri()).parse().unwrap(), - ))) - .unwrap(); - let controller = NetworkPolicyController::default(); - assert!(controller.publish( - controller.policy().revision(), - DestinationPolicy::Unrestricted - )); - let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault) - .with_network_policy(controller.policy()) - .with_sensitive_header_protection(); - let switch_before_storage = Arc::new(AtomicBool::new(switch)); - let clients = Arc::new(TransferHttpClients { - delegate: RouteAwareClientPool::with_chatgpt_cloudflare_cookies_without_request_logging( - factory.clone(), - ClientRouteClass::Api, - ), - controller, - switch_before_storage: Arc::clone(&switch_before_storage), - api_origin: api.uri(), - storage_origin: storage.uri(), - }); - let config = PluginsConfigInput::new( - Default::default(), - Default::default(), - "openai".into(), - /*plugins_enabled*/ true, - /*remote_plugin_enabled*/ true, - "https://chatgpt.com/backend-api".into(), - factory, - /*product_sku*/ None, - ) - .with_runtime_auth_mode(Some(mode)); - config.runtime_http_clients.set(clients).unwrap(); - let manager = Arc::new(crate::PluginsManager::new_with_options( - home.to_path_buf(), - /*restriction_product*/ None, - credentials, - slot, - crate::test_support::test_skill_root_loader(), - )); - Self { - api, - storage, - config, - manager, - auth, - switch_before_storage, - } - } - - async fn verify(&self, account_changed: bool, mode: codex_features::RuntimeAuthMode) { - assert!(!self.switch_before_storage.load(Ordering::SeqCst)); - self.api.verify().await; - let storage_requests = self.storage.received_requests().await.unwrap(); - assert_eq!(storage_requests.len(), usize::from(!account_changed)); - for request in storage_requests { - for name in [ - "authorization", - "x-openai-agent-assertion", - "chatgpt-account-id", - ] { - assert!(!request.headers.contains_key(name)); - } - } - for request in self.api.received_requests().await.unwrap() { - if request.url.path() == "/agent/register" { - continue; - } - let authorization = request.headers["authorization"].to_str().unwrap(); - match mode { - codex_features::RuntimeAuthMode::DualHeader => { - assert!(authorization.starts_with("Bearer ")); - assert!(request.headers.contains_key("x-openai-agent-assertion")); - } - codex_features::RuntimeAuthMode::AssertionOnly => { - assert!(authorization.starts_with("AgentAssertion ")); - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - } - } - } - } -} - -#[tokio::test] -async fn plugin_share_keeps_account_binding_through_storage_upload() { - use codex_features::RuntimeAuthMode; - use codex_http_client::NetworkPolicyDenied; - use codex_http_client::RouteAwareRequestError; - - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - for account_changed in [false, true] { - let home = TempDir::new().unwrap(); - let fixture = PluginTransferTest::new(home.path(), mode, account_changed).await; - let plugin_path = home.path().join("sample"); - write_file( - &plugin_path.join(".codex-plugin/plugin.json"), - r#"{"name":"sample"}"#, - ); - Mock::given(method("POST")) - .and(path("/backend-api/public/plugins/workspace/upload-url")) - .respond_with(ResponseTemplate::new(201).set_body_json(json!({ - "file_id": "file_123", "upload_url": "https://storage.example/upload", - "etag": "\"metadata-etag\"", - }))) - .expect(1) - .mount(&fixture.api) - .await; - Mock::given(method("PUT")) - .and(path("/upload")) - .respond_with(ResponseTemplate::new(201)) - .mount(&fixture.storage) - .await; - Mock::given(method("POST")) - .and(path("/backend-api/public/plugins/workspace")) - .respond_with(ResponseTemplate::new(201).set_body_json(json!({ - "plugin_id": "plugins_123", "share_url": null, - }))) - .expect(u64::from(!account_changed)) - .mount(&fixture.api) - .await; - let result = remote::save_remote_plugin_share( - &fixture - .manager - .remote_plugin_service_config(&fixture.config), - Some(&fixture.auth), - home.path(), - &AbsolutePathBuf::try_from(plugin_path).unwrap(), - /*remote_plugin_id*/ None, - remote::RemotePluginShareAccessPolicy::default(), - ) - .await; - if account_changed { - assert!( - matches!( - result, - Err(RemotePluginCatalogError::Request { - source: RouteAwareRequestError::Policy(NetworkPolicyDenied::Revoked), - .. - }) - ), - "{result:?}" - ); - } else { - assert_eq!(result.unwrap().remote_plugin_id, "plugins_123"); - } - fixture.verify(account_changed, mode).await; - } - } -} - -#[tokio::test] -async fn plugin_install_keeps_account_binding_through_storage_download() { - use codex_features::RuntimeAuthMode; - use codex_http_client::NetworkPolicyDenied; - use codex_http_client::RouteAwareRequestError; - - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - for account_changed in [false, true] { - let home = TempDir::new().unwrap(); - let fixture = PluginTransferTest::new(home.path(), mode, account_changed).await; - let remote_id = "b1234567-89ab-4cde-8f01-234567890abc"; - Mock::given(method("GET")) - .and(path(format!("/backend-api/ps/plugins/{remote_id}"))) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "id": remote_id, "name": "sample", "scope": "GLOBAL", - "installation_policy": "AVAILABLE", "authentication_policy": "ON_USE", - "release": { - "version": "1.0.0", "display_name": "Sample", - "description": "Sample plugin", "interface": {}, - "bundle_download_url": "https://storage.example/bundle", - } - }))) - .expect(1) - .mount(&fixture.api) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [], "pagination": {"next_page_token": null}, - }))) - .expect(1) - .mount(&fixture.api) - .await; - Mock::given(method("GET")) - .and(path("/bundle")) - .respond_with(ResponseTemplate::new(200).set_body_string("bundle")) - .mount(&fixture.storage) - .await; - let result = fixture - .manager - .install_remote_plugin( - &fixture.config, - Some(&fixture.auth), - RemotePluginInstallRequest { - marketplace_name: REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(), - remote_plugin_id: remote_id.to_string(), - install_attempt_id: None, - }, - /*on_effective_plugins_changed*/ None, - ) - .await; - let error = result.err().expect("test transfer should fail"); - if account_changed { - assert!( - matches!( - *error.kind, - RemotePluginOperationErrorKind::Bundle( - RemotePluginBundleInstallError::DownloadRequest { - source: RouteAwareRequestError::Policy( - NetworkPolicyDenied::Revoked - ), - .. - } - ) - ), - "{error:?}" - ); - } else { - // The local HTTP control reaches storage, then fails the final-URL HTTPS check. - assert!( - matches!( - *error.kind, - RemotePluginOperationErrorKind::Bundle( - RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { .. } - ) - ), - "{error:?}" - ); - } - fixture.verify(account_changed, mode).await; - } - } -} diff --git a/codex-rs/core-plugins/src/remote_runtime_auth_tests.rs b/codex-rs/core-plugins/src/remote_runtime_auth_tests.rs deleted file mode 100644 index b9bdadd3..00000000 --- a/codex-rs/core-plugins/src/remote_runtime_auth_tests.rs +++ /dev/null @@ -1,307 +0,0 @@ -//! Exercise modern and legacy plugin requests with a shared, late-initialized runtime. - -use super::*; -use base64::Engine; -use codex_features::RuntimeAuthMode; -use codex_http_client::DestinationPolicy; -use codex_http_client::NetworkPolicyController; -use codex_http_client::NetworkPolicyDenied; -use codex_http_client::OutboundProxyPolicy; -use codex_login::AuthCredentialsStoreMode; -use codex_login::AuthKeyringBackendKind; -use codex_login::AuthManager; -use codex_login::AuthRouteConfig; -use codex_runtime_agent_instance::AgentHostAuthorization; -use codex_runtime_agent_instance::RuntimeAuthManager; -use codex_runtime_agent_instance::RuntimeAuthSlot; -use codex_runtime_agent_instance::RuntimeRegistrationMetadata; -use codex_runtime_agent_instance::RuntimeRole; -use pretty_assertions::assert_eq; -use serde_json::json; -use uuid::Uuid; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::path; - -#[tokio::test] -async fn plugin_runtime_auth_shares_registration_and_strips_cross_origin_auth() { - for (mode, pooled) in [ - (RuntimeAuthMode::DualHeader, false), - (RuntimeAuthMode::AssertionOnly, false), - (RuntimeAuthMode::DualHeader, true), - (RuntimeAuthMode::AssertionOnly, true), - ] { - let server = MockServer::start().await; - let destination = MockServer::start().await; - Mock::given(path("/")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "enabled": true, "plugins": [], - }))) - .expect(1) - .mount(&destination) - .await; - Mock::given(path("/agent/register")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "runtime_agent_instance_id": "runtime-plugins", "agent_host_id": "host-a", - "actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "account-a"}, - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(path("/backend-api/ps/plugins/list")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plugins": [], "pagination": {"next_page_token": null}, - }))) - .expect(2) - .mount(&server) - .await; - Mock::given(path("/backend-api/plugins/featured")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!([]))) - .expect(1) - .mount(&server) - .await; - Mock::given(path("/backend-api/ps/plugins/suggested/codex")) - .respond_with(ResponseTemplate::new(307).insert_header("location", destination.uri())) - .expect(1) - .mount(&server) - .await; - let claims = json!({ - "iss": "https://auth.openai.com/", "session_id": "login-a", - "https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "account-a"}, - }); - let token = format!( - "header.{}.signature", - base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string()) - ); - let auth = CodexAuth::from_external_chatgpt_tokens( - &token, - "account-a", - /*chatgpt_plan_type*/ None, - ) - .unwrap(); - let slot = RuntimeAuthSlot::default(); - let controller = NetworkPolicyController::default(); - let policy = controller.policy(); - let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault) - .with_network_policy(policy.clone()); - let home = tempfile::tempdir().unwrap(); - codex_login::auth::login_with_chatgpt_auth_tokens( - home.path(), - &token, - "account-a", - /*chatgpt_plan_type*/ None, - ) - .unwrap(); - let credentials = Arc::new( - AuthManager::new( - home.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::Ephemeral, - /*forced_chatgpt_workspace_id*/ None, - /*chatgpt_base_url*/ None, - AuthKeyringBackendKind::Direct, - AuthRouteConfig::from_http_client_factory(factory.clone()), - ) - .await, - ); - assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted)); - let mut config = if pooled { - crate::manager::PluginsConfigInput::new( - Default::default(), - Default::default(), - "openai".into(), - /*plugins_enabled*/ true, - /*remote_plugin_enabled*/ true, - "https://chatgpt.com/backend-api".into(), - factory, - /*product_sku*/ None, - ) - .remote_plugin_service_config(Some((Arc::clone(&slot), mode))) - } else { - RemotePluginServiceConfig::new_with_selected_runtime_auth( - "https://chatgpt.com/backend-api".into(), - factory, - /*product_sku*/ None, - (Arc::clone(&slot), mode), - ) - }; - config.chatgpt_base_url = format!("{}/backend-api", server.uri()); - // Enabled requests cannot silently fall back before the harness initializes the slot. - assert!( - fetch_recommended_plugins(&config, Some(&auth)) - .await - .is_err() - ); - assert!(server.received_requests().await.unwrap().is_empty()); - slot.set(Arc::new(RuntimeAuthManager::new( - credentials, - AgentHostAuthorization::InstallationId { - installation_id: Uuid::nil(), - }, - RuntimeRegistrationMetadata { - harness: Some("codex".into()), - harness_version: None, - role: RuntimeRole::Orchestrator, - }, - format!("{}/agent/register", server.uri()).parse().unwrap(), - ))) - .unwrap(); - get_remote_plugin_list_page( - &config, - &auth, - RemotePluginScope::Global, - /*page_token*/ None, - /*collection*/ None, - ) - .await - .unwrap(); - crate::remote_legacy::fetch_remote_featured_plugin_ids( - &config, - Some(&auth), - /*product*/ None, - ) - .await - .unwrap(); - fetch_recommended_plugins(&config, Some(&auth)) - .await - .unwrap(); - let redirected = destination.received_requests().await.unwrap(); - assert_eq!(redirected.len(), 1); - assert!(!redirected[0].headers.contains_key("authorization")); - assert!( - !redirected[0] - .headers - .contains_key("x-openai-agent-assertion") - ); - destination.verify().await; - let url = format!("{}/backend-api/ps/plugins/list", server.uri()); - let pending = config - .authenticated_request(Method::GET, &url, &auth) - .await - .unwrap(); - policy.invalidate(); - assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted)); - assert!(matches!( - pending.send().await, - Err(RouteAwareRequestError::Policy(NetworkPolicyDenied::Revoked)) - )); - let response = config - .authenticated_request(Method::GET, &url, &auth) - .await - .unwrap() - .send() - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::OK); - let requests = server.received_requests().await.unwrap(); - let mut proof_ids = HashSet::new(); - for request in requests - .iter() - .filter(|r| r.url.path() != "/agent/register") - { - let authorization = request.headers["authorization"].to_str().unwrap(); - let proof = match mode { - RuntimeAuthMode::DualHeader => { - assert_eq!(authorization, format!("Bearer {token}")); - request.headers["x-openai-agent-assertion"] - .to_str() - .unwrap() - } - RuntimeAuthMode::AssertionOnly => { - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - authorization.strip_prefix("AgentAssertion ").unwrap() - } - }; - assert_eq!(request.headers["chatgpt-account-id"], "account-a"); - let payload: JsonValue = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(proof.split('.').nth(2).unwrap()) - .unwrap(), - ) - .unwrap(); - assert_eq!(payload["runtime_agent_instance"], "runtime-plugins"); - assert!(proof_ids.insert(payload["id"].as_str().unwrap().to_string())); - } - assert_eq!(proof_ids.len(), 4); - server.verify().await; - } -} - -#[tokio::test] -async fn custom_plugin_backend_keeps_legacy_auth_with_runtime_enabled() { - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - let server = MockServer::start().await; - Mock::given(path("/backend-api/plugins/featured")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!([]))) - .expect(1) - .mount(&server) - .await; - let config = RemotePluginServiceConfig::new_with_runtime_auth( - format!("{}/backend-api", server.uri()), - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - /*product_sku*/ None, - (RuntimeAuthSlot::default(), mode), - ); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - crate::remote_legacy::fetch_remote_featured_plugin_ids( - &config, - Some(&auth), - /*product*/ None, - ) - .await - .unwrap(); - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 1); - assert!( - requests[0].headers["authorization"] - .to_str() - .unwrap() - .starts_with("Bearer ") - ); - assert!(!requests[0].headers.contains_key("x-openai-agent-assertion")); - server.verify().await; - } -} - -#[tokio::test] -async fn unsupported_openai_plugin_backend_fails_before_registration() { - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - let server = MockServer::start().await; - let auth = CodexAuth::from_api_key("key-a"); - let runtime = ( - Arc::new(std::sync::OnceLock::from(Arc::new( - RuntimeAuthManager::new( - AuthManager::from_auth_for_testing(auth.clone()), - AgentHostAuthorization::InstallationId { - installation_id: Uuid::nil(), - }, - RuntimeRegistrationMetadata { - harness: Some("codex".into()), - harness_version: None, - role: RuntimeRole::Orchestrator, - }, - format!("{}/register", server.uri()).parse().unwrap(), - ), - ))), - mode, - ); - let config = RemotePluginServiceConfig::new_with_runtime_auth( - "https://future.openai.com/backend-api".to_string(), - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - /*product_sku*/ None, - runtime, - ); - assert!( - config - .authenticated_request( - Method::GET, - "https://future.openai.com/backend-api/plugins/featured", - &auth, - ) - .await - .is_err() - ); - assert!(server.received_requests().await.unwrap().is_empty()); - } -} diff --git a/codex-rs/core-plugins/src/remote_tests.rs b/codex-rs/core-plugins/src/remote_tests.rs deleted file mode 100644 index f53e5eb3..00000000 --- a/codex-rs/core-plugins/src/remote_tests.rs +++ /dev/null @@ -1,1009 +0,0 @@ -use super::*; -use crate::test_support::recorded_http_client_urls; -use crate::test_support::recording_remote_plugin_service_config; -use pretty_assertions::assert_eq; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header_exists; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; -use wiremock::matchers::query_param_is_missing; - -#[tokio::test] -async fn remote_plugin_list_routes_the_complete_query_url() { - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/list")) - .and(header_exists("user-agent")) - .and(header_exists("originator")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "plugins": [], - "pagination": {"next_page_token": null}, - }))) - .expect(1) - .mount(&server) - .await; - let (config, selected_urls) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - get_remote_plugin_list_page( - &config, - &auth, - RemotePluginScope::Global, - Some("next page/+"), - Some("vertical & special"), - ) - .await - .expect("plugin list request should succeed"); - - assert_eq!( - recorded_http_client_urls(&selected_urls), - vec![format!( - "{}/backend-api/ps/plugins/list?scope=GLOBAL&limit=200&collection=vertical+%26+special&pageToken=next+page%2F%2B", - server.uri() - )] - ); -} - -#[tokio::test] -async fn recommended_plugins_requests_codex_suggestions_endpoint() { - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/suggested/codex")) - .and(query_param("scope", "GLOBAL")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "enabled": true, - "plugins": [], - }))) - .expect(1) - .mount(&server) - .await; - let (config, selected_urls) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - let mode = fetch_recommended_plugins(&config, Some(&auth)) - .await - .expect("recommended plugin request should succeed"); - - assert_eq!( - mode, - RecommendedPluginsMode::Endpoint { - plugins: Vec::new(), - } - ); - assert_eq!( - recorded_http_client_urls(&selected_urls), - vec![format!( - "{}/backend-api/ps/plugins/suggested/codex?scope=GLOBAL", - server.uri() - )] - ); -} - -#[tokio::test] -async fn remote_installed_plugins_paginate_across_all_scopes_without_download_urls() { - let server = MockServer::start().await; - let installed_plugin = |scope: RemotePluginScope, id: &str, name: &str| { - let mut plugin = directory_plugin(id, name); - plugin.scope = scope; - if scope == RemotePluginScope::Workspace { - plugin.discoverability = Some(RemotePluginShareDiscoverability::Listed); - } - let mut plugin = serde_json::to_value(plugin).expect("serialize installed plugin"); - plugin["enabled"] = serde_json::json!(true); - plugin - }; - let global = installed_plugin(RemotePluginScope::Global, "plugin-global", "global-plugin"); - let user = installed_plugin(RemotePluginScope::User, "plugin-user", "user-plugin"); - let workspace = installed_plugin( - RemotePluginScope::Workspace, - "plugin-workspace", - "workspace-plugin", - ); - - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param_is_missing("scope")) - .and(query_param("limit", "200")) - .and(query_param_is_missing("includeDownloadUrls")) - .and(query_param_is_missing("pageToken")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "plugins": [user.clone(), workspace.clone()], - "pagination": {"next_page_token": "next page/+"}, - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param_is_missing("scope")) - .and(query_param("limit", "200")) - .and(query_param_is_missing("includeDownloadUrls")) - .and(query_param("pageToken", "next page/+")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "plugins": [global.clone()], - "pagination": {"next_page_token": null}, - }))) - .expect(1) - .mount(&server) - .await; - let (config, selected_urls) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - let installed_plugins = fetch_remote_installed_plugins(&config, Some(&auth)) - .await - .expect("all-scopes installed plugin request should succeed"); - let expected_plugins = [user, global, workspace] - .into_iter() - .map(|plugin| { - let plugin = serde_json::from_value(plugin).expect("deserialize installed plugin"); - remote_installed_plugin_to_cache_entry(&plugin).expect("valid installed plugin") - }) - .collect::>(); - - assert_eq!(installed_plugins, expected_plugins); - assert_eq!( - recorded_http_client_urls(&selected_urls), - vec![ - format!( - "{}/backend-api/ps/plugins/installed?limit=200", - server.uri() - ), - format!( - "{}/backend-api/ps/plugins/installed?limit=200&pageToken=next+page%2F%2B", - server.uri() - ), - ] - ); -} - -// Skipping display assets must survive pagination without requesting bundle downloads. -#[tokio::test] -async fn installed_plugins_skip_display_resolution_on_every_page() { - let server = MockServer::start().await; - for (cursor, next_cursor) in [(None, Some("next page/+")), (Some("next page/+"), None)] { - let mock = Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("includeDisplayAssets", "false")) - .and(query_param_is_missing("includeDownloadUrls")); - let mock = match cursor { - Some(cursor) => mock.and(query_param("pageToken", cursor)), - None => mock.and(query_param_is_missing("pageToken")), - }; - mock.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "plugins": [], - "pagination": {"next_page_token": next_cursor}, - }))) - .expect(1) - .mount(&server) - .await; - } - let (config, selected_urls) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - let plugins = fetch_remote_installed_plugins_with_display_assets( - &config, - Some(&auth), - InstalledPluginDisplayAssets::Skip, - ) - .await - .expect("runtime metadata request succeeds"); - - assert_eq!(plugins, Vec::new()); - assert_eq!( - recorded_http_client_urls(&selected_urls), - vec![ - format!( - "{}/backend-api/ps/plugins/installed?limit=200&includeDisplayAssets=false", - server.uri() - ), - format!( - "{}/backend-api/ps/plugins/installed?limit=200&includeDisplayAssets=false&pageToken=next+page%2F%2B", - server.uri() - ), - ] - ); -} - -#[tokio::test] -async fn remote_installed_plugins_reject_cyclic_cursors() { - let server = MockServer::start().await; - for (cursor, next_cursor) in [ - (None, "cursor-a"), - (Some("cursor-a"), "cursor-b"), - (Some("cursor-b"), "cursor-a"), - ] { - let mock = Mock::given(method("GET")).and(path("/backend-api/ps/plugins/installed")); - let mock = match cursor { - Some(cursor) => mock.and(query_param("pageToken", cursor)), - None => mock.and(query_param_is_missing("pageToken")), - }; - mock.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "plugins": [], - "pagination": {"next_page_token": next_cursor}, - }))) - .up_to_n_times(1) - .expect(1) - .mount(&server) - .await; - } - let (config, _) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - let error = fetch_remote_installed_plugins(&config, Some(&auth)) - .await - .expect_err("a cursor cycle must not produce an installed inventory"); - - assert!(matches!( - error, - RemotePluginCatalogError::UnexpectedResponse(_) - )); -} - -#[tokio::test] -async fn remote_installed_plugins_require_a_complete_inventory_within_the_page_limit() { - for complete in [false, true] { - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .respond_with(move |request: &wiremock::Request| { - let page = request - .url - .query_pairs() - .find(|(name, _)| name == "pageToken") - .map_or(0, |(_, value)| value.parse::().unwrap()); - let next_cursor = (!complete || page + 1 < MAX_REMOTE_INSTALLED_PLUGIN_PAGES) - .then(|| (page + 1).to_string()); - ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "plugins": [], - "pagination": {"next_page_token": next_cursor}, - })) - }) - .up_to_n_times(MAX_REMOTE_INSTALLED_PLUGIN_PAGES as u64) - .expect(MAX_REMOTE_INSTALLED_PLUGIN_PAGES as u64) - .mount(&server) - .await; - let (config, _) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - let result = fetch_remote_installed_plugins(&config, Some(&auth)).await; - - if complete { - assert_eq!( - result.expect("the last permitted page can complete the inventory"), - Vec::new() - ); - } else { - assert!(matches!( - result, - Err(RemotePluginCatalogError::UnexpectedResponse(_)) - )); - } - } -} - -#[tokio::test] -async fn remote_installed_plugins_timeout_cancels_a_late_page_after_successful_pages() { - let server = MockServer::start().await; - let request_started = Arc::new(tokio::sync::Notify::new()); - let started = Arc::clone(&request_started); - let (release_response, released) = std::sync::mpsc::channel(); - let released = std::sync::Mutex::new(released); - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .respond_with(move |request: &wiremock::Request| { - let page = request - .url - .query_pairs() - .find(|(name, _)| name == "pageToken") - .map_or(0, |(_, value)| value.parse::().unwrap()); - started.notify_one(); - // Wiremock serves requests on its own runtime. Dropping the sender also releases it. - let _ = released.lock().unwrap().recv(); - ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "plugins": [], - "pagination": {"next_page_token": (page + 1).to_string()}, - })) - }) - .up_to_n_times(3) - .expect(3) - .mount(&server) - .await; - let (config, _) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let fetch = fetch_remote_installed_plugins(&config, Some(&auth)); - tokio::pin!(fetch); - - // Each page stays below the individual request timeout, but together exceeds the fetch budget. - // Keep time running during socket I/O so Tokio cannot auto-advance past a response in flight. - for _ in 0..2 { - tokio::select! { - _ = request_started.notified() => {} - result = fetch.as_mut() => panic!("inventory fetch finished before its next page: {result:?}"), - } - tokio::time::pause(); - tokio::time::advance(Duration::from_secs(21)).await; - tokio::time::resume(); - release_response.send(()).unwrap(); - } - tokio::select! { - _ = request_started.notified() => {} - result = fetch.as_mut() => panic!("inventory fetch finished before its late page: {result:?}"), - } - tokio::time::pause(); - tokio::time::advance(Duration::from_secs(21)).await; - let result = fetch.await; - tokio::time::resume(); - drop(release_response); - - assert!(matches!( - result, - Err(RemotePluginCatalogError::InstalledPluginsFetchTimeout) - )); -} - -#[tokio::test] -async fn remote_catalog_cache_modes_control_refresh_and_persist_fetched_results() { - let server = MockServer::start().await; - let plugin = directory_plugin("plugin-gmail", "gmail"); - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/list")) - .and(query_param("scope", "GLOBAL")) - .and(query_param_is_missing("collection")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "plugins": [plugin], - "pagination": {"next_page_token": null}, - }))) - .expect(3) - .mount(&server) - .await; - let codex_home = tempfile::tempdir().expect("create codex home"); - let (config, selected_urls) = - recording_remote_plugin_service_config(format!("{}/backend-api", server.uri())); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - - for (mode, expire_cache, expected_refresh_needed, expected_cache_used) in [ - ( - RemotePluginCatalogCacheMode::PreferFreshCache, - false, - false, - false, - ), - ( - RemotePluginCatalogCacheMode::PreferFreshCache, - false, - false, - true, - ), - (RemotePluginCatalogCacheMode::PreferCache, true, true, true), - ( - RemotePluginCatalogCacheMode::PreferFreshCache, - false, - false, - false, - ), - ( - RemotePluginCatalogCacheMode::ForceRefetch, - false, - false, - false, - ), - ] { - if expire_cache { - let cache_path = - std::fs::read_dir(codex_home.path().join("cache/remote_plugin_catalog")) - .expect("read catalog cache directory") - .next() - .expect("catalog cache exists") - .expect("read cache entry") - .path(); - let mut cached: serde_json::Value = - serde_json::from_slice(&std::fs::read(&cache_path).expect("read cache")) - .expect("decode cache"); - cached["fetched_at"] = serde_json::json!("2000-01-01T00:00:00Z"); - std::fs::write( - cache_path, - serde_json::to_vec(&cached).expect("encode cache"), - ) - .expect("expire catalog cache"); - } - - let outcome = fetch_directory_plugins_for_scope_with_cache( - Some(codex_home.path()), - &config, - &auth, - RemotePluginScope::Global, - /*collection*/ None, - mode, - ) - .await - .expect("fetch directory plugins"); - assert_eq!( - ( - outcome.plugins, - outcome.cache_refresh_needed, - outcome.catalog_cache_used, - ), - ( - vec![plugin.clone()], - expected_refresh_needed, - expected_cache_used, - ), - ); - } - - assert_eq!( - recorded_http_client_urls(&selected_urls), - vec![ - format!( - "{}/backend-api/ps/plugins/list?scope=GLOBAL&limit=200", - server.uri() - ); - 3 - ], - ); - assert!(has_fresh_cached_remote_plugin_catalog( - codex_home.path(), - &config, - Some(&auth), - RemotePluginScope::Global, - )); -} - -#[test] -fn catalog_cache_invalidation_clears_global_collections_and_preserves_other_scopes() { - let codex_home = tempfile::tempdir().expect("create codex home"); - let config = RemotePluginServiceConfig::new( - "https://chatgpt.com/backend-api".to_string(), - crate::test_support::test_http_client_factory(), - /*product_sku*/ None, - ); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let scopes = [RemotePluginScope::Global, RemotePluginScope::Workspace]; - for scope in scopes { - catalog_cache::write_cached_directory_plugins( - codex_home.path(), - &config, - &auth, - scope, - /*collection*/ None, - &[], - ); - } - - let has_cached_scope = |scope| { - has_fresh_cached_remote_plugin_catalog(codex_home.path(), &config, Some(&auth), scope) - }; - assert!(scopes.into_iter().all(has_cached_scope)); - catalog_cache::write_cached_directory_plugins( - codex_home.path(), - &config, - &auth, - RemotePluginScope::Global, - Some(OPENAI_CURATED_REMOTE_COLLECTION_KEY), - &[], - ); - - invalidate_cached_remote_plugin_catalog_scopes( - codex_home.path(), - &config, - Some(&auth), - &[RemotePluginScope::Global], - ); - - assert!(!has_cached_scope(RemotePluginScope::Global)); - assert!(has_cached_scope(RemotePluginScope::Workspace)); - assert!( - catalog_cache::load_cached_directory_plugins::( - codex_home.path(), - &config, - &auth, - RemotePluginScope::Global, - Some(OPENAI_CURATED_REMOTE_COLLECTION_KEY), - RemotePluginCatalogCacheMode::PreferCache, - ) - .is_none() - ); -} - -#[test] -fn build_remote_marketplace_preserves_directory_order_and_appends_installed_only_plugins() { - let directory_plugins = vec![ - directory_plugin("plugin-z", "zulu"), - directory_plugin("plugin-m", "mike"), - ]; - let installed_plugins = vec![RemotePluginInstalledItem { - plugin: directory_plugin("plugin-a", "alpha"), - installed_at: None, - enabled: true, - disabled_skill_names: Vec::new(), - }]; - - let marketplace = build_remote_marketplace( - "marketplace", - "Marketplace", - directory_plugins, - installed_plugins, - /*include_installed_only*/ true, - ) - .expect("marketplace should be valid") - .expect("marketplace should not be empty"); - - assert_eq!( - marketplace - .plugins - .into_iter() - .map(|plugin| plugin.remote_plugin_id) - .collect::>(), - vec!["plugin-z", "plugin-m", "plugin-a"] - ); -} - -#[test] -fn installation_policy_source_is_preserved_across_remote_summary_paths() { - let mut directory_plugin = directory_plugin("plugin-linear", "linear"); - directory_plugin.installation_policy_source = - Some(RemotePluginInstallPolicySource::ImplicitCanonicalApp); - let installed_plugin = RemotePluginInstalledItem { - plugin: directory_plugin.clone(), - installed_at: None, - enabled: true, - disabled_skill_names: Vec::new(), - }; - - let marketplace = build_remote_marketplace( - REMOTE_GLOBAL_MARKETPLACE_NAME, - REMOTE_GLOBAL_MARKETPLACE_DISPLAY_NAME, - vec![directory_plugin], - vec![installed_plugin.clone()], - /*include_installed_only*/ false, - ) - .expect("marketplace should be valid") - .expect("marketplace should not be empty"); - assert_eq!( - marketplace - .plugins - .into_iter() - .map(|plugin| plugin.install_policy_source) - .collect::>(), - vec![Some(PluginInstallPolicySource::ImplicitCanonicalApp)] - ); - - let mut installed_plugin = installed_plugin; - installed_plugin.plugin.installation_policy_source = - Some(RemotePluginInstallPolicySource::WorkspaceSetting); - let installed_plugin = remote_installed_plugin_to_cache_entry(&installed_plugin) - .expect("installed plugin should be valid"); - let marketplaces = group_remote_installed_plugins_by_marketplaces( - &[installed_plugin], - &[REMOTE_GLOBAL_MARKETPLACE_NAME], - ); - assert_eq!( - marketplaces - .into_iter() - .flat_map(|marketplace| marketplace.plugins) - .map(|plugin| plugin.install_policy_source) - .collect::>(), - vec![Some(PluginInstallPolicySource::WorkspaceSetting)] - ); -} - -#[test] -fn plan_eligibility_is_preserved_across_remote_summary_paths() { - let mut directory_plugin = directory_plugin("plugin-gmail", "gmail"); - directory_plugin.installation_policy = PluginInstallPolicy::NotAvailable; - directory_plugin.availability = PluginAvailability::DisabledByAdmin; - directory_plugin.disabled_reason = Some(PluginDisabledReason::PlanNotEligible); - directory_plugin.eligible_plan_types = Some(vec![ - "plus".to_string(), - "pro".to_string(), - "enterprise_cbp_automation".to_string(), - ]); - let installed_plugin = RemotePluginInstalledItem { - plugin: directory_plugin.clone(), - installed_at: None, - enabled: false, - disabled_skill_names: Vec::new(), - }; - - let marketplace = build_remote_marketplace( - REMOTE_GLOBAL_MARKETPLACE_NAME, - REMOTE_GLOBAL_MARKETPLACE_DISPLAY_NAME, - vec![directory_plugin], - Vec::new(), - /*include_installed_only*/ false, - ) - .expect("marketplace should be valid") - .expect("marketplace should not be empty"); - let expected = vec![( - PluginAvailability::DisabledByAdmin, - Some(PluginDisabledReason::PlanNotEligible), - Some(vec![ - "plus".to_string(), - "pro".to_string(), - "enterprise_cbp_automation".to_string(), - ]), - )]; - assert_eq!( - marketplace - .plugins - .into_iter() - .map(|plugin| ( - plugin.availability, - plugin.disabled_reason, - plugin.eligible_plan_types, - )) - .collect::>(), - expected - ); - - let installed_plugin = remote_installed_plugin_to_cache_entry(&installed_plugin) - .expect("installed plugin should be valid"); - let marketplaces = group_remote_installed_plugins_by_marketplaces( - &[installed_plugin], - &[REMOTE_GLOBAL_MARKETPLACE_NAME], - ); - assert_eq!( - marketplaces - .into_iter() - .flat_map(|marketplace| marketplace.plugins) - .map(|plugin| ( - plugin.availability, - plugin.disabled_reason, - plugin.eligible_plan_types, - )) - .collect::>(), - expected - ); -} - -#[test] -fn unknown_plugin_disabled_reason_preserves_remote_catalog_compatibility() { - let plugin = directory_plugin("plugin-gmail", "gmail"); - let mut plugin_json = serde_json::to_value(plugin).expect("plugin should serialize"); - plugin_json["disabled_reason"] = serde_json::json!("future_disabled_reason"); - - let plugin: RemotePluginDirectoryItem = - serde_json::from_value(plugin_json).expect("unknown reason should deserialize"); - - assert_eq!(plugin.disabled_reason, Some(PluginDisabledReason::Unknown)); -} - -#[test] -fn installation_interstitial_requirement_is_preserved_across_remote_summary_paths() { - let mut directory_plugin = directory_plugin("plugin-linear", "linear"); - directory_plugin.must_show_installation_interstitial = Some(true); - let marketplace = build_remote_marketplace( - REMOTE_GLOBAL_MARKETPLACE_NAME, - REMOTE_GLOBAL_MARKETPLACE_DISPLAY_NAME, - vec![directory_plugin.clone()], - Vec::new(), - /*include_installed_only*/ false, - ) - .expect("marketplace should be valid") - .expect("marketplace should not be empty"); - assert_eq!( - marketplace - .plugins - .into_iter() - .map(|plugin| plugin.must_show_installation_interstitial) - .collect::>(), - vec![Some(true)] - ); - - directory_plugin.must_show_installation_interstitial = Some(false); - let installed_plugin = remote_installed_plugin_to_cache_entry(&RemotePluginInstalledItem { - plugin: directory_plugin, - installed_at: None, - enabled: true, - disabled_skill_names: Vec::new(), - }) - .expect("installed plugin should be valid"); - let marketplaces = group_remote_installed_plugins_by_marketplaces( - &[installed_plugin], - &[REMOTE_GLOBAL_MARKETPLACE_NAME], - ); - assert_eq!( - marketplaces - .into_iter() - .flat_map(|marketplace| marketplace.plugins) - .map(|plugin| plugin.must_show_installation_interstitial) - .collect::>(), - vec![Some(false)] - ); -} - -#[test] -fn missing_installation_interstitial_requirement_deserializes_to_none() { - let plugin = directory_plugin("plugin-linear", "linear"); - let mut plugin_json = serde_json::to_value(plugin).expect("plugin should serialize"); - plugin_json - .as_object_mut() - .expect("plugin should serialize to an object") - .remove("must_show_installation_interstitial"); - - let plugin: RemotePluginDirectoryItem = - serde_json::from_value(plugin_json).expect("missing requirement should deserialize"); - - assert_eq!(plugin.must_show_installation_interstitial, None); -} - -#[test] -fn unknown_installation_policy_source_maps_to_none() { - let plugin = directory_plugin("plugin-linear", "linear"); - let mut plugin_json = serde_json::to_value(plugin).expect("plugin should serialize"); - plugin_json["installation_policy_source"] = - serde_json::Value::String("FUTURE_POLICY_SOURCE".to_string()); - let plugin: RemotePluginDirectoryItem = - serde_json::from_value(plugin_json).expect("unknown source should deserialize"); - - let summary = build_remote_plugin_summary(&plugin, /*installed_plugin*/ None) - .expect("summary should be valid"); - - assert_eq!(summary.install_policy_source, None); -} - -#[test] -fn scheduled_task_metadata_distinguishes_unavailable_from_empty() { - let release = serde_json::json!({ - "display_name": "Example", - "description": "Example plugin", - "interface": {}, - }); - let without_metadata: RemotePluginReleaseResponse = - serde_json::from_value(release.clone()).expect("release should deserialize"); - assert_eq!(without_metadata.scheduled_tasks, None); - - let mut with_empty_metadata = release; - with_empty_metadata["scheduled_tasks"] = serde_json::json!([]); - let with_empty_metadata: RemotePluginReleaseResponse = - serde_json::from_value(with_empty_metadata).expect("release should deserialize"); - assert_eq!(with_empty_metadata.scheduled_tasks, Some(Vec::new())); -} - -#[test] -fn workspace_share_context_preserves_publish_capability() { - let mut plugin = directory_plugin("plugin-workspace", "workspace plugin"); - plugin.scope = RemotePluginScope::Workspace; - plugin.discoverability = Some(RemotePluginShareDiscoverability::Private); - plugin.can_publish_to_workspace = Some(true); - - let context = remote_plugin_share_context(&plugin) - .expect("workspace plugin should be valid") - .expect("workspace plugin should have share context"); - - assert_eq!(context.can_publish_to_workspace, Some(true)); -} - -fn directory_plugin(id: &str, name: &str) -> RemotePluginDirectoryItem { - RemotePluginDirectoryItem { - canonical_app_id: None, - id: id.to_string(), - name: name.to_string(), - scope: RemotePluginScope::Global, - discoverability: None, - creator_account_user_id: None, - creator_name: None, - share_url: None, - share_principals: None, - can_publish_to_workspace: None, - installation_policy: PluginInstallPolicy::Available, - installation_policy_source: None, - must_show_installation_interstitial: None, - authentication_policy: PluginAuthPolicy::OnUse, - availability: PluginAvailability::Available, - disabled_reason: None, - eligible_plan_types: None, - release: RemotePluginReleaseResponse { - version: None, - display_name: name.to_string(), - description: String::new(), - bundle_download_url: None, - app_ids: Vec::new(), - app_manifest: None, - app_templates: Vec::new(), - keywords: Vec::new(), - interface: RemotePluginReleaseInterfaceResponse { - short_description: None, - long_description: None, - developer_name: None, - category: None, - capabilities: Vec::new(), - website_url: None, - privacy_policy_url: None, - terms_of_service_url: None, - brand_color: None, - default_prompt: None, - default_prompts: None, - composer_icon_url: None, - logo_url: None, - logo_url_dark: None, - screenshot_urls: Vec::new(), - }, - skills: Vec::new(), - onboarding_skill_name: None, - mcp_servers: Vec::new(), - scheduled_tasks: None, - }, - } -} - -#[test] -fn remote_plugin_interface_maps_dark_logo_url() { - let mut plugin = directory_plugin("plugin-linear", "linear"); - plugin.release.interface.logo_url_dark = - Some("https://example.com/linear/logo-dark.png".to_string()); - - assert_eq!( - remote_plugin_interface_to_info(&plugin) - .expect("plugin interface") - .logo_url_dark, - Some("https://example.com/linear/logo-dark.png".to_string()) - ); -} -fn item(name: &str) -> RecommendedPluginItem { - RecommendedPluginItem { - id: format!("plugin_{name}"), - name: name.to_string(), - display_name: name.to_string(), - } -} - -#[test] -fn recommended_plugins_enabled_flag_selects_endpoint_or_legacy_mode() { - let disabled: RecommendedPluginsResponse = serde_json::from_value(serde_json::json!({ - "enabled": false, - "plugins": [{"id": "plugin_github", "name": "github", "display_name": "GitHub"}] - })) - .expect("response should deserialize"); - assert_eq!( - recommended_plugins_mode(disabled), - RecommendedPluginsMode::Legacy - ); - - let enabled: RecommendedPluginsResponse = serde_json::from_value(serde_json::json!({ - "enabled": true, - "plugins": [] - })) - .expect("response should deserialize"); - assert_eq!( - recommended_plugins_mode(enabled), - RecommendedPluginsMode::Endpoint { - plugins: Vec::new() - } - ); -} - -#[test] -fn recommended_plugins_require_remote_install_identity() { - let response = serde_json::from_value::(serde_json::json!({ - "enabled": true, - "plugins": [{"name": "github", "display_name": "GitHub"}] - })); - - assert!(response.is_err()); -} - -#[test] -fn recommended_plugins_are_validated_deduplicated_sorted_and_capped() { - let mut plugins = (0..=52) - .rev() - .map(|index| item(&format!("plugin-{index:02}"))) - .collect::>(); - plugins.push(item("plugin-00")); - plugins.push(item("not/a/plugin")); - - let mode = recommended_plugins_mode(RecommendedPluginsResponse { - enabled: true, - plugins, - }); - let RecommendedPluginsMode::Endpoint { plugins } = mode else { - panic!("expected endpoint mode"); - }; - - assert_eq!(plugins.len(), MAX_RECOMMENDED_PLUGINS); - assert_eq!( - plugins.first(), - Some(&RecommendedPlugin { - config_id: "plugin-00@openai-curated-remote".to_string(), - remote_plugin_id: "plugin_plugin-00".to_string(), - display_name: "plugin-00".to_string(), - }) - ); - assert_eq!( - plugins.last(), - Some(&RecommendedPlugin { - config_id: "plugin-49@openai-curated-remote".to_string(), - remote_plugin_id: "plugin_plugin-49".to_string(), - display_name: "plugin-49".to_string(), - }) - ); -} - -#[test] -fn recommended_plugins_bound_model_visible_fields() { - let overlong_name = "n".repeat(MAX_RECOMMENDED_PLUGIN_NAME_LEN + 1); - let overlong_display_name = "D".repeat(MAX_RECOMMENDED_PLUGIN_DISPLAY_NAME_LEN + 1); - let mode = recommended_plugins_mode(RecommendedPluginsResponse { - enabled: true, - plugins: vec![ - item(&overlong_name), - RecommendedPluginItem { - id: "plugin_bounded".to_string(), - name: "bounded".to_string(), - display_name: overlong_display_name, - }, - RecommendedPluginItem { - id: "plugin_fallback".to_string(), - name: "fallback".to_string(), - display_name: String::new(), - }, - ], - }); - - assert_eq!( - mode, - RecommendedPluginsMode::Endpoint { - plugins: vec![ - RecommendedPlugin { - config_id: "bounded@openai-curated-remote".to_string(), - remote_plugin_id: "plugin_bounded".to_string(), - display_name: "D".repeat(MAX_RECOMMENDED_PLUGIN_DISPLAY_NAME_LEN), - }, - RecommendedPlugin { - config_id: "fallback@openai-curated-remote".to_string(), - remote_plugin_id: "plugin_fallback".to_string(), - display_name: "fallback".to_string(), - }, - ], - } - ); -} - -#[test] -fn recommended_plugins_accept_codex_suggestion_items() { - let response: RecommendedPluginsResponse = serde_json::from_value(serde_json::json!({ - "enabled": true, - "plugins": [{"id": "plugin_box", "name": "box", "display_name": "Box"}] - })) - .expect("compact response should deserialize"); - - assert_eq!( - recommended_plugins_mode(response), - RecommendedPluginsMode::Endpoint { - plugins: vec![RecommendedPlugin { - config_id: "box@openai-curated-remote".to_string(), - remote_plugin_id: "plugin_box".to_string(), - display_name: "Box".to_string(), - }], - } - ); -} - -#[test] -fn recommended_plugins_ignore_invalid_remote_plugin_ids() { - let mode = recommended_plugins_mode(RecommendedPluginsResponse { - enabled: true, - plugins: vec![RecommendedPluginItem { - id: "not/a/plugin".to_string(), - name: "sample".to_string(), - display_name: "Sample".to_string(), - }], - }); - - assert_eq!( - mode, - RecommendedPluginsMode::Endpoint { - plugins: Vec::new(), - } - ); -} diff --git a/codex-rs/core-plugins/src/script_attribution.rs b/codex-rs/core-plugins/src/script_attribution.rs index 111b9e38..7869007b 100644 --- a/codex-rs/core-plugins/src/script_attribution.rs +++ b/codex-rs/core-plugins/src/script_attribution.rs @@ -124,31 +124,6 @@ impl PluginMeasurementTarget { } impl TrustedPluginRoots { - /// Called only after the authenticated remote bundle installer has prepared - /// an isolated store. Read declarations without loading plugin capabilities. - pub(crate) fn from_measurement_reference( - codex_home: &Path, - plugin_id: &PluginId, - version: &str, - remote_id: &str, - ) -> Option { - let store = PluginStore::try_new(codex_home.to_owned()).ok()?; - if store.active_plugin_version(plugin_id).as_deref() != Some(version) - || store.remote_plugin_id(plugin_id).ok()?.as_deref() != Some(remote_id) - { - return None; - } - let root = store.plugin_root(plugin_id, version).canonicalize().ok()?; - let metrics_operations_by_path = load_plugin_metrics_operations(&root).unwrap_or_default(); - Some(Self { - roots: vec![TrustedPluginRoot { - plugin_id: plugin_id.clone(), - version: version.to_owned(), - root, - metrics_operations_by_path, - }], - }) - } /// Adds already-trusted roots, preserving the existing root for each plugin and version. /// Distinct versions remain eligible for exact executor-version matching. diff --git a/codex-rs/core-plugins/src/test_support.rs b/codex-rs/core-plugins/src/test_support.rs index 60dcdc29..84755474 100644 --- a/codex-rs/core-plugins/src/test_support.rs +++ b/codex-rs/core-plugins/src/test_support.rs @@ -4,23 +4,17 @@ use std::fs; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; -use std::sync::Mutex; use crate::OPENAI_API_CURATED_MARKETPLACE_NAME; use crate::OPENAI_CURATED_MARKETPLACE_NAME; use crate::PluginsConfigInput; use crate::PluginsManager; -use crate::http_client_selector::HttpClientSelector; -use crate::remote::RemotePluginServiceConfig; use codex_config::LoaderOverrides; use codex_config::NoopThreadConfigLoader; use codex_config::loader::load_config_layers_state; use codex_exec_server::LOCAL_FS; -use codex_http_client::ClientRouteClass; use codex_http_client::HttpClientFactory; use codex_http_client::OutboundProxyPolicy; -use codex_http_client::RequestBuilder; -use codex_http_client::RouteAwareClientPool; use codex_login::AuthHeaders; use codex_login::AuthManager; use codex_login::CodexAuth; @@ -47,7 +41,6 @@ use codex_utils_path_uri::PathUri; use codex_utils_plugins::PluginSkillRoot; use codex_utils_plugins::SkillDiscoveryMode; use codex_utils_plugins::migrated_command_skills_root; -use http::Method; use toml::Value; pub(crate) const TEST_CURATED_PLUGIN_SHA: &str = "0123456789abcdef0123456789abcdef01234567"; @@ -323,85 +316,6 @@ pub(crate) fn test_http_client_factory() -> HttpClientFactory { HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault) } -#[derive(Debug)] -pub(crate) struct RecordingHttpClientSelector { - selected_urls: Arc>>, - delegate: RouteAwareClientPool, -} - -impl RecordingHttpClientSelector { - fn record_url(&self, url: &str) { - match self.selected_urls.lock() { - Ok(mut selected_urls) => selected_urls.push(url.to_string()), - Err(error) => panic!("selected URL recorder lock should not be poisoned: {error}"), - } - } - - pub(crate) fn new() -> (Arc, Arc>>) { - let selected_urls = Arc::new(Mutex::new(Vec::new())); - let delegate = RouteAwareClientPool::with_chatgpt_cloudflare_cookies( - test_http_client_factory(), - ClientRouteClass::Api, - ); - ( - Arc::new(Self { - selected_urls: Arc::clone(&selected_urls), - delegate, - }), - selected_urls, - ) - } -} - -impl HttpClientSelector for RecordingHttpClientSelector { - fn for_current_account(&self) -> Arc { - Arc::new(Self { - selected_urls: Arc::clone(&self.selected_urls), - delegate: self.delegate.for_current_account(), - }) - } - - fn request(&self, method: Method, url: &str) -> RequestBuilder { - self.record_url(url); - self.delegate.request(method, url) - } - - fn request_for_account( - &self, - method: Method, - url: &str, - binding: &codex_http_client::NetworkPolicy, - ) -> Option { - self.record_url(url); - self.delegate.request_for_account(method, url, binding) - } - fn outbound_proxy_policy(&self) -> OutboundProxyPolicy { - self.delegate.outbound_proxy_policy() - } -} - -pub(crate) fn recording_remote_plugin_service_config( - chatgpt_base_url: String, -) -> (RemotePluginServiceConfig, Arc>>) { - let (http_clients, selected_urls) = RecordingHttpClientSelector::new(); - ( - RemotePluginServiceConfig { - runtime_auth: None, - chatgpt_base_url, - product_sku: crate::remote::CODEX_PRODUCT_SKU.to_string(), - http_clients, - }, - selected_urls, - ) -} - -pub(crate) fn recorded_http_client_urls(selected_urls: &Mutex>) -> Vec { - match selected_urls.lock() { - Ok(selected_urls) => selected_urls.clone(), - Err(error) => panic!("selected URL recorder lock should not be poisoned: {error}"), - } -} - pub(crate) fn write_file(path: &Path, contents: &str) { fs::create_dir_all(path.parent().expect("file should have a parent")).unwrap(); fs::write(path, contents).unwrap(); diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 5c26e95f..a9acbcdf 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -142,7 +142,6 @@ openssl-sys = { workspace = true, features = ["vendored"] } openssl-sys = { workspace = true, features = ["vendored"] } [dev-dependencies] -codex-backend-client = { workspace = true } codex-message-board = { workspace = true } codex-agent-message-board-host = { workspace = true } assert_cmd = { workspace = true } diff --git a/codex-rs/core/src/connectors.rs b/codex-rs/core/src/connectors.rs index 04bb4987..037a1f2f 100644 --- a/codex-rs/core/src/connectors.rs +++ b/codex-rs/core/src/connectors.rs @@ -238,9 +238,8 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_mcp_manager( McpRuntimeContext::new(Arc::clone(&environment_manager), config.cwd.to_path_buf()); let cancel_token = CancellationToken::new(); - let codex_apps_auth_manager = - codex_mcp::host_owned_codex_apps_enabled(&mcp_config, auth.as_ref()) - .then(|| Arc::clone(&auth_manager)); + // The ChatGPT-hosted apps MCP server is never connected in aKode. + let codex_apps_auth_manager = None; let mcp_runtime = McpRuntime::new(McpRuntimeInput { network_policy_metadata: None, runtime_auth: mcp_manager.runtime_auth_for_config(config), diff --git a/codex-rs/core/src/connectors_tests.rs b/codex-rs/core/src/connectors_tests.rs index 6d861884..9b417a77 100644 --- a/codex-rs/core/src/connectors_tests.rs +++ b/codex-rs/core/src/connectors_tests.rs @@ -47,7 +47,6 @@ fn codex_app_tool( callable_namespace: tool_namespace, namespace_description: None, tool: test_tool_definition(tool_name), - openai_file_input_optional_fields: Default::default(), connector_id: Some(connector_id.to_string()), connector_name: connector_name.map(ToOwned::to_owned), plugin_display_names: plugin_names(plugin_display_names), @@ -92,7 +91,6 @@ fn accessible_connectors_from_mcp_tools_carries_plugin_display_names() { callable_namespace: "sample".to_string(), namespace_description: None, tool: test_tool_definition("echo"), - openai_file_input_optional_fields: Default::default(), connector_id: None, connector_name: None, plugin_display_names: plugin_names(&["ignored"]), @@ -275,7 +273,6 @@ fn accessible_connectors_from_mcp_tools_preserves_description() { "Create a calendar event", Arc::new(JsonObject::default()), ), - openai_file_input_optional_fields: Default::default(), connector_id: Some("calendar".to_string()), connector_name: Some("Calendar".to_string()), plugin_display_names: Vec::new(), diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index f9515751..0030b398 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -119,7 +119,6 @@ pub use mcp::McpServersDisabled; mod original_image_detail; pub use codex_mcp::CodexAppsToolsCache; pub use codex_mcp::SandboxState; -mod mcp_openai_file; mod mcp_tool_call; pub(crate) mod mention_syntax; pub(crate) mod utils; diff --git a/codex-rs/core/src/mcp.rs b/codex-rs/core/src/mcp.rs index ce3f0b26..2e04127b 100644 --- a/codex-rs/core/src/mcp.rs +++ b/codex-rs/core/src/mcp.rs @@ -21,7 +21,6 @@ use codex_extension_api::McpServerContributionContext; use codex_extension_api::SelectedPlugin; use codex_extension_api::SelectedPluginIdentity; use codex_extension_api::SelectedPluginSnapshot; -use codex_extension_api::SessionIsolation; use codex_features::Feature; use codex_login::CodexAuth; use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; @@ -32,7 +31,6 @@ use codex_mcp::McpPluginAttribution; use codex_mcp::McpServerRegistration; use codex_mcp::McpToolCatalogCache; use codex_mcp::ToolInfo; -use codex_mcp::codex_apps_mcp_server_config; use codex_mcp::configured_mcp_servers; use codex_mcp::effective_mcp_servers; use codex_plugin::AppConnectorId; @@ -203,10 +201,6 @@ impl McpManager { pub async fn runtime_config(&self, config: &Config) -> McpConfig { self.runtime_config_with_context( McpServerContributionContext::global(config), - // Threadless discovery and control-plane paths have no effective thread - // originator; active-thread tool calls use runtime_config_for_step below. - /*originator*/ - None, McpEnvironmentScope::HostOnly, &[], ) @@ -242,7 +236,6 @@ impl McpManager { } self.runtime_config_with_context( context, - Some(identity.originator), identity.environments, identity.disabled_plugin_ids, ) @@ -307,7 +300,6 @@ impl McpManager { async fn runtime_config_with_context( &self, context: McpServerContributionContext<'_, Config>, - originator: Option<&str>, environment_scope: McpEnvironmentScope<'_>, disabled_plugin_ids: &[String], ) -> McpRuntimeProjection { @@ -497,29 +489,11 @@ impl McpManager { .to_mcp_config_with_loaded_plugins(&loaded_plugins, selected_plugin_registrations); mcp_config.ema_state = Arc::clone(&self.ema_state); let mut catalog = mcp_config.mcp_server_catalog.to_builder(); - // Isolated sessions do not inherit the implicit Apps connection. - if mcp_config.apps_enabled - && context - .thread_init() - .and_then(codex_extension_api::ExtensionDataInit::get::) - .as_deref() - != Some(&SessionIsolation::Isolated) - { - catalog.register(McpServerRegistration::from_compatibility( - CODEX_APPS_MCP_SERVER_NAME.to_string(), - LEGACY_CODEX_APPS_REGISTRATION_ID, - codex_apps_mcp_server_config( - &mcp_config.chatgpt_base_url, - mcp_config.apps_mcp_product_sku.as_deref(), - originator, - ), - )); - } else { - catalog.remove_compatibility( - CODEX_APPS_MCP_SERVER_NAME.to_string(), - LEGACY_CODEX_APPS_REGISTRATION_ID, - ); - } + // aKode never registers the ChatGPT-hosted apps MCP server. + catalog.remove_compatibility( + CODEX_APPS_MCP_SERVER_NAME.to_string(), + LEGACY_CODEX_APPS_REGISTRATION_ID, + ); for overlay in overlays { match overlay { diff --git a/codex-rs/core/src/mcp_openai_file.rs b/codex-rs/core/src/mcp_openai_file.rs deleted file mode 100644 index 1a7608d7..00000000 --- a/codex-rs/core/src/mcp_openai_file.rs +++ /dev/null @@ -1,718 +0,0 @@ -//! Bridges Apps SDK-style `openai/fileParams` metadata into Codex's MCP flow. -//! -//! Strategy: -//! - Inspect `_meta["openai/fileParams"]` to discover which tool arguments are -//! file inputs. -//! - At tool execution time, read those files from the primary environment, -//! upload them to OpenAI file storage, -//! and rewrite only the declared arguments into the provided-file payload -//! shape expected by the downstream Apps tool. -//! -//! The model-facing local-path schema is owned by `codex-mcp` alongside MCP tool inventory, so this -//! module only handles uploading the files and rewriting the execution-time arguments. - -use crate::session::session::Session; -use crate::session::step_context::StepContext; -use codex_api::HostedFileUploadContext; -use codex_api::OPENAI_FILE_UPLOAD_LIMIT_BYTES; -use codex_api::upload_openai_file; -use codex_exec_server::GetMetadataOptions; -use codex_login::CodexAuth; -use codex_protocol::permissions::FileSystemAccessMode; -use codex_sandboxing::policy_transforms::effective_file_system_sandbox_policy; -use serde_json::Value as JsonValue; -use std::collections::HashMap; -use std::sync::Arc; - -struct FileArgumentLocation<'a> { - field_name: &'a str, - index: Option, -} - -pub(crate) async fn rewrite_mcp_tool_arguments_for_openai_files( - sess: &Session, - step_context: &StepContext, - arguments_value: Option, - openai_file_input_optional_fields: Option<&HashMap>>, - hosted_upload: Option<&HostedFileUploadContext>, -) -> Result, String> { - let Some(openai_file_input_optional_fields) = openai_file_input_optional_fields else { - return Ok(arguments_value); - }; - - let Some(arguments_value) = arguments_value else { - return Ok(None); - }; - let Some(arguments) = arguments_value.as_object() else { - return Ok(Some(arguments_value)); - }; - let auth = sess.services.auth_manager.auth().await; - let mut rewritten_arguments = arguments.clone(); - - for (field_name, optional_fields) in openai_file_input_optional_fields { - let Some(value) = arguments.get(field_name) else { - continue; - }; - let Some(uploaded_value) = rewrite_argument_value_for_openai_files( - sess, - step_context, - auth.as_ref(), - field_name, - optional_fields, - value, - hosted_upload, - ) - .await? - else { - continue; - }; - rewritten_arguments.insert(field_name.clone(), uploaded_value); - } - - if rewritten_arguments == *arguments { - return Ok(Some(arguments_value)); - } - - Ok(Some(JsonValue::Object(rewritten_arguments))) -} - -async fn rewrite_argument_value_for_openai_files( - sess: &Session, - step_context: &StepContext, - auth: Option<&CodexAuth>, - field_name: &str, - optional_fields: &[String], - value: &JsonValue, - hosted_upload: Option<&HostedFileUploadContext>, -) -> Result, String> { - match value { - JsonValue::String(file_path) => { - let rewritten = build_uploaded_argument_value( - sess, - step_context, - auth, - FileArgumentLocation { - field_name, - index: None, - }, - optional_fields, - file_path, - hosted_upload, - ) - .await?; - Ok(Some(rewritten)) - } - JsonValue::Array(values) => { - let mut rewritten_values = Vec::with_capacity(values.len()); - for (index, item) in values.iter().enumerate() { - let Some(file_path) = item.as_str() else { - return Ok(None); - }; - let rewritten = build_uploaded_argument_value( - sess, - step_context, - auth, - FileArgumentLocation { - field_name, - index: Some(index), - }, - optional_fields, - file_path, - hosted_upload, - ) - .await?; - rewritten_values.push(rewritten); - } - Ok(Some(JsonValue::Array(rewritten_values))) - } - _ => Ok(None), - } -} - -async fn build_uploaded_argument_value( - sess: &Session, - step_context: &StepContext, - auth: Option<&CodexAuth>, - argument: FileArgumentLocation<'_>, - optional_fields: &[String], - file_path: &str, - hosted_upload: Option<&HostedFileUploadContext>, -) -> Result { - let FileArgumentLocation { field_name, index } = argument; - let contextualize_error = |error: String| match index { - Some(index) => { - format!("failed to upload `{file_path}` for `{field_name}[{index}]`: {error}") - } - None => format!("failed to upload `{file_path}` for `{field_name}`: {error}"), - }; - let Some(auth) = auth else { - return Err("ChatGPT auth is required to upload files for Codex Apps tools".to_string()); - }; - if !auth.uses_codex_backend() { - return Err("ChatGPT auth is required to upload files for Codex Apps tools".to_string()); - } - let turn_context = &step_context.turn; - let Some(turn_environment) = step_context.environments.primary() else { - return Err(contextualize_error( - "no primary turn environment is available".to_string(), - )); - }; - let path_uri = turn_environment - .cwd() - .join(file_path) - .map_err(|error| contextualize_error(error.to_string()))?; - let additional_permissions = - turn_context.granted_permissions(&turn_environment.selection.environment_id); - let file_system_policy = effective_file_system_sandbox_policy( - &turn_environment - .permission_profile() - .file_system_sandbox_policy(), - additional_permissions.as_ref(), - ); - let requires_sandbox = !file_system_policy.has_full_disk_read_access() - || file_system_policy - .entries - .iter() - .any(|entry| entry.access == FileSystemAccessMode::Deny); - let sandbox = - requires_sandbox.then(|| turn_environment.sandbox_context(additional_permissions)); - if sandbox.is_some() { - let environment_info = turn_environment - .environment() - .info() - .await - .map_err(|error| contextualize_error(error.to_string()))?; - if !environment_info.capabilities.sandboxed_file_streaming { - return Err(contextualize_error( - "selected executor does not support sandboxed file streaming".to_string(), - )); - } - } - let fs = turn_environment.environment().get_filesystem(); - let metadata = fs - .get_metadata(&path_uri, GetMetadataOptions::default(), sandbox.as_ref()) - .await - .map_err(|error| contextualize_error(error.to_string()))?; - if !metadata.is_file { - return Err(contextualize_error(format!( - "path `{}` is not a file", - path_uri.inferred_native_path_string() - ))); - } - if metadata.size > OPENAI_FILE_UPLOAD_LIMIT_BYTES { - return Err(contextualize_error(format!( - "file `{}` is too large: {} bytes exceeds the limit of {} bytes", - path_uri.inferred_native_path_string(), - metadata.size, - OPENAI_FILE_UPLOAD_LIMIT_BYTES, - ))); - } - // Keep the initial read permission check before allocating a remote file record. - let mut first_contents = Some( - fs.read_file_stream(&path_uri, sandbox.as_ref()) - .await - .map_err(|error| contextualize_error(error.to_string()))?, - ); - let file_name = path_uri - .basename() - .or_else(|| { - path_uri.infer_path_convention().and_then(|convention| { - convention - .path_segments(file_path) - .rfind(|segment| !segment.is_empty()) - .map(str::to_string) - }) - }) - .unwrap_or_else(|| "file".to_string()); - let open_contents = move || { - let first_contents = first_contents.take(); - let fs = Arc::clone(&fs); - let path_uri = path_uri.clone(); - let sandbox = sandbox.clone(); - async move { - match first_contents { - Some(contents) => Ok(contents), - None => fs.read_file_stream(&path_uri, sandbox.as_ref()).await, - } - } - }; - let runtime = if turn_context - .config - .features - .enabled(codex_features::Feature::RuntimeAgentInstances) - && codex_http_client::classify_openai_api_url(&turn_context.config.chatgpt_base_url) - != codex_http_client::OpenAiDestination::Other - { - codex_model_provider::validate_runtime_destination(Some( - &turn_context.config.chatgpt_base_url, - )) - .map_err(|error| contextualize_error(error.to_string()))?; - let manager = sess.services.runtime_auth.get().ok_or_else(|| { - contextualize_error("runtime authentication has not been initialized".to_string()) - })?; - Some((Arc::clone(manager), turn_context.config.runtime_auth_mode)) - } else { - None - }; - let upload_auth = codex_model_provider::auth_provider_for_request( - auth, - runtime.as_ref(), - &http::HeaderMap::new(), - ) - .await - .map_err(|error| contextualize_error(error.to_string()))?; - let upload_clients = upload_auth - .bind_http_client_pool(&sess.services.openai_file_upload_client_pool) - .map_err(|error| contextualize_error(error.to_string()))?; - let uploaded = upload_openai_file( - turn_context.config.chatgpt_base_url.trim_end_matches('/'), - upload_auth.auth.as_ref(), - &upload_clients, - file_name, - metadata.size, - open_contents, - hosted_upload, - ) - .await - .map_err(|error| contextualize_error(error.to_string()))?; - let mut payload = serde_json::Map::new(); - payload.insert( - "download_url".to_string(), - JsonValue::String(uploaded.download_url), - ); - payload.insert("file_id".to_string(), JsonValue::String(uploaded.file_id)); - if optional_fields - .iter() - .any(|optional_field| optional_field == "mime_type") - && let Some(mime_type) = uploaded.mime_type - { - payload.insert("mime_type".to_string(), JsonValue::String(mime_type)); - } - if optional_fields - .iter() - .any(|optional_field| optional_field == "file_name") - { - payload.insert( - "file_name".to_string(), - JsonValue::String(uploaded.file_name), - ); - } - Ok(JsonValue::Object(payload)) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::environment_selection::TurnEnvironmentState; - use crate::session::tests::make_session_and_context; - use crate::session::turn_context::TurnContext; - use codex_utils_absolute_path::AbsolutePathBuf; - use codex_utils_path_uri::PathUri; - use pretty_assertions::assert_eq; - use std::path::Path; - use std::sync::Arc; - use tempfile::tempdir; - - fn set_primary_environment_cwd(turn_context: &mut TurnContext, cwd: &Path) { - let cwd = AbsolutePathBuf::try_from(cwd).expect("absolute path"); - let TurnEnvironmentState::Ready(primary) = - &mut turn_context.initial_environments.environments[0] - else { - panic!("expected ready primary environment"); - }; - primary.selection.cwd = PathUri::from_abs_path(&cwd); - primary.selection.workspace_roots.clear(); - primary.config_mut().workspace_roots.clear(); - } - - #[tokio::test] - async fn openai_file_argument_rewrite_requires_declared_file_params() { - let (session, turn_context) = make_session_and_context().await; - let step_context = StepContext::for_test(Arc::new(turn_context)); - let arguments = Some(serde_json::json!({ - "file": "/tmp/codex-smoke-file.txt" - })); - - let rewritten = rewrite_mcp_tool_arguments_for_openai_files( - &session, - &step_context, - arguments.clone(), - /*openai_file_input_optional_fields*/ None, - /*hosted_upload*/ None, - ) - .await - .expect("rewrite should succeed"); - - assert_eq!(rewritten, arguments); - } - - #[tokio::test] - async fn build_uploaded_argument_value_uses_environment_that_becomes_ready_during_turn() { - use wiremock::Mock; - use wiremock::MockServer; - use wiremock::ResponseTemplate; - use wiremock::matchers::body_json; - use wiremock::matchers::header; - use wiremock::matchers::method; - use wiremock::matchers::path; - - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/backend-api/files")) - .and(header("chatgpt-account-id", "account_id")) - .and(body_json(serde_json::json!({ - "file_name": "file_report.csv", - "file_size": 5, - "use_case": "codex", - }))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "file_id": "file_123", - "upload_url": format!("{}/upload/file_123", server.uri()), - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path("/upload/file_123")) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/backend-api/files/file_123/uploaded")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "status": "success", - "download_url": format!("{}/download/file_123", server.uri()), - "file_name": "file_report.csv", - "mime_type": "text/csv", - "file_size_bytes": 5, - }))) - .expect(1) - .mount(&server) - .await; - - let (session, mut turn_context) = make_session_and_context().await; - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let dir = tempdir().expect("temp dir"); - let local_path = dir.path().join("file_report.csv"); - tokio::fs::write(&local_path, b"hello") - .await - .expect("write local file"); - set_primary_environment_cwd(&mut turn_context, dir.path()); - let environment = turn_context - .initial_environments - .primary() - .expect("ready primary environment"); - let selection = environment.selection(); - let environment_config = environment.config().clone(); - let local_windows_sandbox_type = environment_config.windows_sandbox_type; - let environments = crate::environment_selection::ThreadEnvironments::new( - session.services.turn_environments.environment_manager(), - crate::shell::default_user_shell(), - crate::session::ThreadEnvironmentDefaults::new( - environment_config, - local_windows_sandbox_type, - ), - crate::shell_snapshot::ShellSnapshot::disabled(), - Default::default(), - /*non_blocking_snapshots*/ true, - ); - environments.update_selections(std::slice::from_ref(&selection)); - turn_context.initial_environments = environments.snapshot().await; - turn_context - .initial_environments - .starting() - .next() - .expect("environment should initially be starting") - .wait_until_ready() - .await - .expect("environment should become ready"); - let step_environments = turn_context.initial_environments.refresh_readiness(); - - let mut config = (*turn_context.config).clone(); - config.chatgpt_base_url = format!("{}/backend-api", server.uri()); - turn_context.config = Arc::new(config); - let mut step_context = StepContext::for_test(Arc::new(turn_context)); - Arc::get_mut(&mut step_context) - .expect("step context should be uniquely owned") - .environments = step_environments; - - let rewritten = build_uploaded_argument_value( - &session, - &step_context, - Some(&auth), - FileArgumentLocation { - field_name: "file", - index: None, - }, - &["mime_type".to_string(), "file_name".to_string()], - "file_report.csv", - /*hosted_upload*/ None, - ) - .await - .expect("rewrite should upload the local file"); - - assert_eq!( - rewritten, - serde_json::json!({ - "download_url": format!("{}/download/file_123", server.uri()), - "file_id": "file_123", - "mime_type": "text/csv", - "file_name": "file_report.csv", - }) - ); - } - - #[tokio::test] - async fn build_uploaded_argument_value_rejects_oversized_file_before_reading() { - let (session, mut turn_context) = make_session_and_context().await; - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let dir = tempdir().expect("temp dir"); - let file_path = dir.path().join("oversized.bin"); - let file = std::fs::File::create(&file_path).expect("create sparse file"); - file.set_len(OPENAI_FILE_UPLOAD_LIMIT_BYTES + 1) - .expect("size sparse file"); - set_primary_environment_cwd(&mut turn_context, dir.path()); - let step_context = StepContext::for_test(Arc::new(turn_context)); - - let error = build_uploaded_argument_value( - &session, - &step_context, - Some(&auth), - FileArgumentLocation { - field_name: "file", - index: None, - }, - &[], - "oversized.bin", - /*hosted_upload*/ None, - ) - .await - .expect_err("oversized file should be rejected"); - - assert!(error.contains("is too large")); - assert!(error.contains(&(OPENAI_FILE_UPLOAD_LIMIT_BYTES + 1).to_string())); - } - - #[tokio::test] - async fn rewrite_argument_value_for_openai_files_omits_undeclared_optional_fields() { - use wiremock::Mock; - use wiremock::MockServer; - use wiremock::ResponseTemplate; - use wiremock::matchers::body_json; - use wiremock::matchers::header; - use wiremock::matchers::method; - use wiremock::matchers::path; - - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/backend-api/files")) - .and(header("chatgpt-account-id", "account_id")) - .and(body_json(serde_json::json!({ - "file_name": "file_report.csv", - "file_size": 5, - "use_case": "codex", - }))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "file_id": "file_123", - "upload_url": format!("{}/upload/file_123", server.uri()), - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path("/upload/file_123")) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/backend-api/files/file_123/uploaded")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "status": "success", - "download_url": format!("{}/download/file_123", server.uri()), - "file_name": "file_report.csv", - "mime_type": "text/csv", - "file_size_bytes": 5, - }))) - .expect(1) - .mount(&server) - .await; - - let (session, mut turn_context) = make_session_and_context().await; - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let dir = tempdir().expect("temp dir"); - let local_path = dir.path().join("file_report.csv"); - tokio::fs::write(&local_path, b"hello") - .await - .expect("write local file"); - set_primary_environment_cwd(&mut turn_context, dir.path()); - - let mut config = (*turn_context.config).clone(); - config.chatgpt_base_url = format!("{}/backend-api", server.uri()); - turn_context.config = Arc::new(config); - let step_context = StepContext::for_test(Arc::new(turn_context)); - let rewritten = rewrite_argument_value_for_openai_files( - &session, - &step_context, - Some(&auth), - "file", - &[], - &serde_json::json!("file_report.csv"), - /*hosted_upload*/ None, - ) - .await - .expect("rewrite should succeed"); - - assert_eq!( - rewritten, - Some(serde_json::json!({ - "download_url": format!("{}/download/file_123", server.uri()), - "file_id": "file_123", - })) - ); - } - - #[tokio::test] - async fn rewrite_argument_value_for_openai_files_rewrites_array_paths() { - use wiremock::Mock; - use wiremock::MockServer; - use wiremock::ResponseTemplate; - use wiremock::matchers::body_json; - use wiremock::matchers::header; - use wiremock::matchers::method; - use wiremock::matchers::path; - - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/backend-api/files")) - .and(header("chatgpt-account-id", "account_id")) - .and(body_json(serde_json::json!({ - "file_name": "one.csv", - "file_size": 3, - "use_case": "codex", - }))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "file_id": "file_1", - "upload_url": format!("{}/upload/file_1", server.uri()), - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/backend-api/files")) - .and(header("chatgpt-account-id", "account_id")) - .and(body_json(serde_json::json!({ - "file_name": "two.csv", - "file_size": 3, - "use_case": "codex", - }))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "file_id": "file_2", - "upload_url": format!("{}/upload/file_2", server.uri()), - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path("/upload/file_1")) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(&server) - .await; - Mock::given(method("PUT")) - .and(path("/upload/file_2")) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/backend-api/files/file_1/uploaded")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "status": "success", - "download_url": format!("{}/download/file_1", server.uri()), - "file_name": "one.csv", - "mime_type": "text/csv", - "file_size_bytes": 3, - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/backend-api/files/file_2/uploaded")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "status": "success", - "download_url": format!("{}/download/file_2", server.uri()), - "file_name": "two.csv", - "mime_type": "text/csv", - "file_size_bytes": 3, - }))) - .expect(1) - .mount(&server) - .await; - - let (session, mut turn_context) = make_session_and_context().await; - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let dir = tempdir().expect("temp dir"); - tokio::fs::write(dir.path().join("one.csv"), b"one") - .await - .expect("write first local file"); - tokio::fs::write(dir.path().join("two.csv"), b"two") - .await - .expect("write second local file"); - set_primary_environment_cwd(&mut turn_context, dir.path()); - - let mut config = (*turn_context.config).clone(); - config.chatgpt_base_url = format!("{}/backend-api", server.uri()); - turn_context.config = Arc::new(config); - let step_context = StepContext::for_test(Arc::new(turn_context)); - let rewritten = rewrite_argument_value_for_openai_files( - &session, - &step_context, - Some(&auth), - "files", - &[], - &serde_json::json!(["one.csv", "two.csv"]), - /*hosted_upload*/ None, - ) - .await - .expect("rewrite should succeed"); - - assert_eq!( - rewritten, - Some(serde_json::json!([ - { - "download_url": format!("{}/download/file_1", server.uri()), - "file_id": "file_1", - }, - { - "download_url": format!("{}/download/file_2", server.uri()), - "file_id": "file_2", - } - ])) - ); - } - - #[tokio::test] - async fn rewrite_mcp_tool_arguments_for_openai_files_surfaces_upload_failures() { - let (mut session, turn_context) = make_session_and_context().await; - session.services.auth_manager = crate::test_support::auth_manager_from_auth( - CodexAuth::create_dummy_chatgpt_auth_for_testing(), - ); - let step_context = StepContext::for_test(Arc::new(turn_context)); - let error = rewrite_mcp_tool_arguments_for_openai_files( - &session, - &step_context, - Some(serde_json::json!({ - "file": "/definitely/missing/file.csv", - })), - Some(&HashMap::from([("file".to_string(), Vec::new())])), - /*hosted_upload*/ None, - ) - .await - .expect_err("missing file should fail"); - - assert!(error.contains("failed to upload")); - assert!(error.contains("file")); - } -} diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index a7094d26..34e207fb 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -11,7 +11,6 @@ use crate::connectors; use crate::guardian::GuardianApprovalRequest; use crate::guardian::GuardianMcpAnnotations; use crate::guardian::GuardianReviewContext; -use crate::mcp_openai_file::rewrite_mcp_tool_arguments_for_openai_files; use crate::mcp_tool_approval_templates::RenderedMcpToolApprovalParam; use crate::mcp_tool_approval_templates::render_mcp_tool_approval_template; use crate::session::session::Session; @@ -31,7 +30,6 @@ use codex_analytics::ElicitationType; use codex_analytics::InvocationType; use codex_analytics::McpToolCallElicitation; use codex_analytics::build_track_events_context; -use codex_api::HostedFileUploadContext; use codex_config::ConfigLayerSource; use codex_config::types::AppToolApproval; use codex_connectors::AppToolPolicy; @@ -483,7 +481,7 @@ async fn handle_approved_mcp_tool_call( let server_origin = prepared_call.server_origin().map(str::to_string); let start = Instant::now(); - let mut tool_input = arguments_value + let tool_input = arguments_value .clone() .unwrap_or_else(|| JsonValue::Object(serde_json::Map::new())); let is_search = prepared_call.is_host_owned_apps() @@ -553,28 +551,6 @@ async fn handle_approved_mcp_tool_call( } maybe_mark_thread_memory_mode_polluted(sess, turn_context, &prepared_call) .await; - let hosted_upload = item_metadata - .connector_id - .as_ref() - .zip(item_metadata.action_name.as_ref()) - .map(|(connector_id, action_name)| HostedFileUploadContext { - thread_id: None, - connector_id: connector_id.clone(), - action_name: action_name.clone(), - model: step_context.settings.model_info.slug.clone(), - }); - let rewritten_arguments = rewrite_mcp_tool_arguments_for_openai_files( - sess, - step_context, - arguments_value, - metadata.openai_file_input_optional_fields.as_ref(), - hosted_upload.as_ref(), - ) - .await - .map_err(anyhow::Error::msg)?; - if let Some(rewritten_arguments) = rewritten_arguments.as_ref() { - tool_input = rewritten_arguments.clone(); - } let mut request_meta = build_mcp_tool_call_request_meta( step_context, &server, @@ -669,7 +645,7 @@ async fn handle_approved_mcp_tool_call( ) .await?; } - Ok((rewritten_arguments, request_meta)) + Ok((None, request_meta)) }) .await .map_err(|error| { @@ -1318,7 +1294,6 @@ pub(crate) struct McpToolApprovalMetadata { mcp_app_resource_uri: Option, mcp_app_ui: Option, codex_apps_meta: Option>, - openai_file_input_optional_fields: Option>>, } #[derive(Clone)] @@ -2144,23 +2119,9 @@ fn mcp_tool_metadata( mcp_app_resource_uri, mcp_app_ui, codex_apps_meta, - // Disallow custom MCPs from uploading files via fileParams. - openai_file_input_optional_fields: openai_file_input_optional_fields_for_server( - server, - &tool_info.openai_file_input_optional_fields, - ), }) } -fn openai_file_input_optional_fields_for_server( - server: &str, - openai_file_input_optional_fields: &HashMap>, -) -> Option>> { - (server == CODEX_APPS_MCP_SERVER_NAME) - .then(|| openai_file_input_optional_fields.clone()) - .filter(|params| !params.is_empty()) -} - fn get_mcp_app_resource_uri( meta: Option<&serde_json::Map>, ) -> Option { diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index 0792cd27..406cb2ad 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -99,7 +99,6 @@ fn approval_metadata( mcp_app_resource_uri: None, mcp_app_ui: None, codex_apps_meta: None, - openai_file_input_optional_fields: None, } } @@ -375,20 +374,6 @@ fn mcp_app_resource_uri_reads_known_tool_meta_keys() { ); } -#[test] -fn openai_file_params_are_only_honored_for_codex_apps() { - let params = HashMap::from([("file".to_string(), Vec::new())]); - - assert_eq!( - openai_file_input_optional_fields_for_server(CODEX_APPS_MCP_SERVER_NAME, ¶ms), - Some(params.clone()) - ); - assert_eq!( - openai_file_input_optional_fields_for_server("minimaltest", ¶ms), - None - ); -} - #[test] fn approval_required_when_read_only_false_and_destructive() { let annotations = annotations(Some(false), Some(true), /*open_world*/ None); @@ -1594,7 +1579,6 @@ async fn codex_apps_tool_call_request_meta_includes_turn_metadata_and_codex_apps .cloned() .expect("_codex_apps metadata should be an object"), ), - openai_file_input_optional_fields: None, }; let mut expected_apps_meta = serde_json::json!({ @@ -2086,7 +2070,6 @@ fn guardian_mcp_review_request_includes_annotations_when_present() { mcp_app_resource_uri: None, mcp_app_ui: None, codex_apps_meta: None, - openai_file_input_optional_fields: None, }; let request = build_guardian_mcp_tool_review_request("call-1", &invocation, Some(&metadata)); @@ -2904,7 +2887,6 @@ async fn approve_mode_skips_when_annotations_do_not_require_approval() { mcp_app_resource_uri: None, mcp_app_ui: None, codex_apps_meta: None, - openai_file_input_optional_fields: None, }; let decision = maybe_request_mcp_tool_approval( @@ -2987,7 +2969,6 @@ async fn guardian_mode_skips_auto_when_annotations_do_not_require_approval() { mcp_app_resource_uri: None, mcp_app_ui: None, codex_apps_meta: None, - openai_file_input_optional_fields: None, }; let decision = maybe_request_mcp_tool_approval( @@ -3052,7 +3033,6 @@ async fn permission_request_hook_allows_mcp_tool_call() { mcp_app_resource_uri: None, mcp_app_ui: None, codex_apps_meta: None, - openai_file_input_optional_fields: None, }; let decision = maybe_request_mcp_tool_approval( @@ -3220,7 +3200,6 @@ async fn permission_request_hook_runs_after_remembered_mcp_approval() { mcp_app_resource_uri: None, mcp_app_ui: None, codex_apps_meta: None, - openai_file_input_optional_fields: None, }; let remembered_key = session_mcp_tool_approval_key(&invocation, Some(&metadata), AppToolApproval::Auto) @@ -3323,7 +3302,6 @@ async fn strict_auto_review_forces_guardian_for_mcp_policy_skip() { mcp_app_resource_uri: None, mcp_app_ui: None, codex_apps_meta: None, - openai_file_input_optional_fields: None, }; let mut captured_mcp_config = approval_config(&turn_context); captured_mcp_config @@ -3418,7 +3396,6 @@ async fn assert_mcp_user_approval_persistence( mcp_app_resource_uri: None, mcp_app_ui: None, codex_apps_meta: None, - openai_file_input_optional_fields: None, }; let approval_task = tokio::spawn({ @@ -3510,7 +3487,6 @@ async fn prompt_mode_waits_for_approval_when_annotations_do_not_require_approval mcp_app_resource_uri: None, mcp_app_ui: None, codex_apps_meta: None, - openai_file_input_optional_fields: None, }; let mut approval_task = { @@ -3577,7 +3553,6 @@ async fn full_access_mode_skips_mcp_tool_approval_for_all_approval_modes() { mcp_app_resource_uri: None, mcp_app_ui: None, codex_apps_meta: None, - openai_file_input_optional_fields: None, }; for approval_mode in [ @@ -3638,7 +3613,6 @@ async fn approve_mode_skips_guardian_in_every_permission_mode() { mcp_app_resource_uri: None, mcp_app_ui: None, codex_apps_meta: None, - openai_file_input_optional_fields: None, }; for approval_policy in [ diff --git a/codex-rs/core/src/mcp_tool_exposure_test.rs b/codex-rs/core/src/mcp_tool_exposure_test.rs index 5a9967d3..d5793aaf 100644 --- a/codex-rs/core/src/mcp_tool_exposure_test.rs +++ b/codex-rs/core/src/mcp_tool_exposure_test.rs @@ -40,7 +40,6 @@ fn make_mcp_tool( format!("Test tool: {tool_name}"), Arc::new(JsonObject::default()), ), - openai_file_input_optional_fields: Default::default(), connector_id: connector_id.map(str::to_string), connector_name: connector_name.map(str::to_string), plugin_display_names: Vec::new(), diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 2afcb80a..fae3bab5 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -29,8 +29,6 @@ use crate::turn_metadata::ExecutionMetadata; use codex_analytics::ThreadProductUpdate; use codex_attachment_store::AttachmentStore; use codex_extension_api::ExtensionDataInit; -use codex_http_client::ClientRouteClass; -use codex_http_client::RouteAwareClientPool; use codex_login::auth::AgentIdentityAuthPolicy; use codex_model_provider::SharedModelProvider; use codex_prompts::render_model_instructions; @@ -1996,24 +1994,6 @@ impl Session { exec_policy, auth_manager: Arc::clone(&auth_manager), runtime_auth, - openai_file_upload_client_pool: if config - .features - .enabled(Feature::RuntimeAgentInstances) - && codex_runtime_agent_instance::is_openai_api_url(&config.chatgpt_base_url) - { - RouteAwareClientPool::new_without_request_logging( - config - .http_client_factory() - .with_sensitive_header_protection(), - ClientRouteClass::Api, - ) - } else { - RouteAwareClientPool::new_without_request_logging( - config.http_client_factory(), - ClientRouteClass::Api, - ) - .with_legacy_custom_ca_fallback() - }, session_telemetry, models_manager: Arc::clone(&models_manager), git_root_discovery, diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index c332c8d9..018111b2 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -6955,10 +6955,6 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { exec_policy, auth_manager: auth_manager.clone(), runtime_auth: Default::default(), - openai_file_upload_client_pool: RouteAwareClientPool::new_without_request_logging( - config.http_client_factory(), - ClientRouteClass::Api, - ) .with_legacy_custom_ca_fallback(), session_telemetry: session_telemetry.clone(), models_manager: Arc::clone(&models_manager), @@ -9299,10 +9295,6 @@ where exec_policy, auth_manager: Arc::clone(&auth_manager), runtime_auth: Default::default(), - openai_file_upload_client_pool: RouteAwareClientPool::new_without_request_logging( - config.http_client_factory(), - ClientRouteClass::Api, - ) .with_legacy_custom_ca_fallback(), session_telemetry: session_telemetry.clone(), models_manager: Arc::clone(&models_manager), diff --git a/codex-rs/core/src/state/service.rs b/codex-rs/core/src/state/service.rs index 2bb25c75..1ca8297e 100644 --- a/codex-rs/core/src/state/service.rs +++ b/codex-rs/core/src/state/service.rs @@ -31,7 +31,6 @@ use codex_extension_api::ExtensionData; use codex_extension_api::ExtensionDataInit; use codex_extension_api::ExtensionRegistry; use codex_hooks::Hooks; -use codex_http_client::RouteAwareClientPool; use codex_login::AuthManager; use codex_mcp::McpRuntime; use codex_models_manager::manager::SharedModelsManager; @@ -65,7 +64,6 @@ pub(crate) struct SessionServices { pub(crate) auth_manager: Arc, pub(crate) runtime_auth: RuntimeAuthSlot, /// Upload-only clients shared across turns without logging signed blob URLs. - pub(crate) openai_file_upload_client_pool: RouteAwareClientPool, pub(crate) models_manager: SharedModelsManager, pub(crate) git_root_discovery: Arc, pub(crate) session_telemetry: SessionTelemetry, diff --git a/codex-rs/core/src/tools/handlers/mcp.rs b/codex-rs/core/src/tools/handlers/mcp.rs index 20a237a0..33350bb3 100644 --- a/codex-rs/core/src/tools/handlers/mcp.rs +++ b/codex-rs/core/src/tools/handlers/mcp.rs @@ -968,7 +968,6 @@ mod tests { "type": "object", }))), ), - openai_file_input_optional_fields: Default::default(), connector_id: None, connector_name: None, plugin_display_names: Vec::new(), diff --git a/codex-rs/core/src/tools/handlers/mcp_search_tests.rs b/codex-rs/core/src/tools/handlers/mcp_search_tests.rs index d1b2be67..f6188638 100644 --- a/codex-rs/core/src/tools/handlers/mcp_search_tests.rs +++ b/codex-rs/core/src/tools/handlers/mcp_search_tests.rs @@ -136,7 +136,6 @@ fn tool_info() -> ToolInfo { }))), ) .with_title("Create event"), - openai_file_input_optional_fields: Default::default(), connector_id: None, connector_name: Some("Calendar".to_string()), plugin_display_names: vec![" Calendar plugin ".to_string(), " ".to_string()], diff --git a/codex-rs/core/src/tools/handlers/tool_search.rs b/codex-rs/core/src/tools/handlers/tool_search.rs index 65d87945..eb3cca94 100644 --- a/codex-rs/core/src/tools/handlers/tool_search.rs +++ b/codex-rs/core/src/tools/handlers/tool_search.rs @@ -603,7 +603,6 @@ mod tests { "additionalProperties": false, }))), ), - openai_file_input_optional_fields: Default::default(), connector_id: None, connector_name: None, plugin_display_names: Vec::new(), diff --git a/codex-rs/core/src/tools/router_tests.rs b/codex-rs/core/src/tools/router_tests.rs index 1544c077..c7c37518 100644 --- a/codex-rs/core/src/tools/router_tests.rs +++ b/codex-rs/core/src/tools/router_tests.rs @@ -594,7 +594,6 @@ fn mcp_tool_info( "type": "object", }))), ), - openai_file_input_optional_fields: Default::default(), connector_id: None, connector_name: None, plugin_display_names: Vec::new(), diff --git a/codex-rs/core/src/tools/spec_plan_tests.rs b/codex-rs/core/src/tools/spec_plan_tests.rs index bcff2ed2..417ce700 100644 --- a/codex-rs/core/src/tools/spec_plan_tests.rs +++ b/codex-rs/core/src/tools/spec_plan_tests.rs @@ -412,7 +412,6 @@ fn mcp_tool(server: &str, namespace: &str, name: &str) -> ToolInfo { "additionalProperties": false, }))), ), - openai_file_input_optional_fields: Default::default(), connector_id: None, connector_name: None, plugin_display_names: Vec::new(), diff --git a/codex-rs/core/tests/suite/analytics_runtime_auth.rs b/codex-rs/core/tests/suite/analytics_runtime_auth.rs deleted file mode 100644 index ca6a496d..00000000 --- a/codex-rs/core/tests/suite/analytics_runtime_auth.rs +++ /dev/null @@ -1,142 +0,0 @@ -//! Analytics plan discovery must not follow redirects with runtime authentication. - -use anyhow::Result; -use base64::Engine; -use codex_backend_client::AnalyticsSession; -use codex_features::RuntimeAuthMode; -use codex_http_client::HttpClientFactory; -use codex_http_client::OutboundProxyPolicy; -use codex_login::AuthCredentialsStoreMode; -use core_test_support::load_default_config_for_test; -use core_test_support::runtime_auth::PROBE_SERVER; -use core_test_support::runtime_auth::run_harness_through_proxy_with_env; -use core_test_support::skip_if_no_network; -use pretty_assertions::assert_eq; -use serde_json::json; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn analytics_does_not_follow_runtime_redirects() -> Result<()> { - skip_if_no_network!(Ok(())); - let token = format!( - "e30.{}.c2ln", - base64::engine::general_purpose::URL_SAFE_NO_PAD.encode( - json!({ - "exp": 4_102_444_800_u64, - "iss": "https://auth.openai.com", - "session_id": "session-analytics", - "https://api.openai.com/auth": { - "chatgpt_user_id": "user-analytics", - "chatgpt_account_id": "account-analytics", - }, - }) - .to_string(), - ), - ); - if std::env::var(PROBE_SERVER).is_ok() { - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - let home = tempfile::tempdir()?; - codex_login::auth::login_with_chatgpt_auth_tokens( - home.path(), - &token, - "account-analytics", - Some("plus"), - )?; - let mut config = load_default_config_for_test(&home).await; - config.chatgpt_base_url = "https://chatgpt.com/backend-api".into(); - config.cli_auth_credentials_store_mode = AuthCredentialsStoreMode::Ephemeral; - let result = AnalyticsSession::from_config( - &config, - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - Some(mode), - ) - .await; - assert!( - result.is_err(), - "Analytics must reject a redirected plan response" - ); - } - return Ok(()); - } - - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/agent/register")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "runtime_agent_instance_id": "runtime-analytics", - "agent_host_id": "host-analytics", - "actor": { - "kind": "chatgpt", - "user_id": "user-analytics", - "account_id": "account-analytics", - }, - }))) - .expect(/*r*/ 2) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/accounts/check")) - .respond_with(ResponseTemplate::new(/*s*/ 307).insert_header( - "Location", - "https://chatgpt.com/backend-api/redirected-plan", - )) - .expect(/*r*/ 2) - .mount(&server) - .await; - Mock::given(path("/backend-api/redirected-plan")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "accounts": [], - "account_ordering": [], - }))) - .expect(/*r*/ 0) - .mount(&server) - .await; - - run_harness_through_proxy_with_env( - &server, - "suite::analytics_runtime_auth::analytics_does_not_follow_runtime_redirects", - /*realtime_target*/ None, - &[ - ("OPENAI_API_KEY", None), - ("CODEX_API_KEY", None), - ("OPENAI_FEDERATION_RULE_ID", None), - ("OPENAI_IDENTITY_TOKEN_FILE", None), - ], - ) - .await?; - - let requests = server - .received_requests() - .await - .expect("requests should be recorded"); - let discovery: Vec<_> = requests - .iter() - .filter(|request| request.url.path() == "/backend-api/wham/accounts/check") - .collect(); - assert_eq!(discovery.len(), 2); - assert_eq!( - discovery[0].headers["authorization"], - format!("Bearer {token}") - ); - assert!( - discovery[0] - .headers - .contains_key("x-openai-agent-assertion") - ); - assert!( - discovery[1].headers["authorization"] - .to_str()? - .starts_with("AgentAssertion ") - ); - assert!( - !discovery[1] - .headers - .contains_key("x-openai-agent-assertion") - ); - server.verify().await; - Ok(()) -} diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index b1f7a423..c966dfac 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -48,7 +48,6 @@ mod agent_execution; mod agent_message_wake; mod agent_websocket; mod agents_md; -mod analytics_runtime_auth; mod app_tool_exposure; mod apply_patch_cli; mod apply_patch_serialization; @@ -170,7 +169,6 @@ mod multi_agent_tool_descriptions; #[cfg(unix)] mod multi_exec_server_sandbox; mod network_approval; -mod openai_file_mcp; mod otel; mod output_token_replay; mod override_updates; @@ -214,8 +212,6 @@ mod rmcp_client; mod rollout_budget; mod rollout_compression; mod rollout_list_find; -mod runtime_auth; -mod runtime_auth_denials; mod safety_buffering; mod safety_check_downgrade; mod scenarios; diff --git a/codex-rs/core/tests/suite/openai_file_mcp.rs b/codex-rs/core/tests/suite/openai_file_mcp.rs deleted file mode 100644 index 48ce20a0..00000000 --- a/codex-rs/core/tests/suite/openai_file_mcp.rs +++ /dev/null @@ -1,442 +0,0 @@ -#![cfg(not(target_os = "windows"))] - -use std::fs; -use std::path::Path; - -use anyhow::Context; -use anyhow::Result; -use codex_core::config::Config; -use codex_protocol::models::PermissionProfile; -use codex_protocol::permissions::FileSystemAccessMode; -use codex_protocol::permissions::FileSystemSandboxEntry; -use codex_protocol::permissions::FileSystemSandboxPolicy; -use codex_protocol::permissions::NetworkSandboxPolicy; -use codex_protocol::protocol::AskForApproval; -use codex_utils_absolute_path::AbsolutePathBuf; -use codex_utils_path_uri::PathUri; -use core_test_support::PathExt; -use core_test_support::apps_test_server::AppsTestServer; -use core_test_support::apps_test_server::CALENDAR_EXTRACT_TEXT_TOOL_NAME; -use core_test_support::apps_test_server::DIRECT_CALENDAR_EXTRACT_TEXT_TOOL as DOCUMENT_EXTRACT_HOOK_MATCHER; -use core_test_support::apps_test_server::DOCUMENT_EXTRACT_TEXT_RESOURCE_URI; -use core_test_support::apps_test_server::SEARCH_CALENDAR_EXTRACT_TEXT_TOOL as DOCUMENT_EXTRACT_TOOL; -use core_test_support::apps_test_server::SEARCH_CALENDAR_NAMESPACE as DOCUMENT_EXTRACT_NAMESPACE; -use core_test_support::apps_test_server::apps_enabled_builder; -use core_test_support::apps_test_server::recorded_apps_tool_call_by_name; -use core_test_support::hooks::trust_discovered_hooks; -use core_test_support::responses::ResponseMock; -use core_test_support::responses::ev_assistant_message; -use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_function_call_with_namespace; -use core_test_support::responses::ev_response_created; -use core_test_support::responses::ev_tool_search_call; -use core_test_support::responses::mount_sse_sequence; -use core_test_support::responses::namespace_child_tool; -use core_test_support::responses::sse; -use core_test_support::responses::start_mock_server; -use core_test_support::skip_if_sandbox; -use core_test_support::skip_if_target_windows; -use core_test_support::test_codex::TestCodex; -use core_test_support::test_codex::executor_path_uri; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::body_partial_json; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; - -const STREAMED_FILE_SIZE: usize = 2 * 1024 * 1024; - -fn restrict_apps_upload_reads(config: &mut Config, denied_file_name: &str) { - let denied_path = - AbsolutePathBuf::from_absolute_path(config.cwd.as_path().join(denied_file_name)) - .expect("denied file path should be absolute"); - let mut file_system_policy = FileSystemSandboxPolicy::read_only(); - file_system_policy.entries.push(FileSystemSandboxEntry::new( - denied_path.into(), - FileSystemAccessMode::Deny, - )); - config - .permissions - .set_permission_profile(PermissionProfile::from_runtime_permissions( - &file_system_policy, - NetworkSandboxPolicy::Restricted, - )) - .expect("test config should allow a restricted read policy"); - - let user_config_path = config.codex_home.join("config.toml").abs(); - let user_config = toml::from_str( - r#" -[apps.calendar] -default_tools_approval_mode = "approve" -"#, - ) - .expect("Apps approval config should parse"); - config.config_layer_stack = config - .config_layer_stack - .with_user_config(&user_config_path, user_config) - .expect("Apps approval config should be valid"); -} - -fn write_post_tool_use_hook(home: &Path) -> Result<()> { - let script_path = home.join("post_tool_use_hook.py"); - let log_path = home.join("post_tool_use_hook_log.jsonl"); - let script = format!( - r#"import json -from pathlib import Path -import sys - -payload = json.load(sys.stdin) - -with Path(r"{log_path}").open("a", encoding="utf-8") as handle: - handle.write(json.dumps(payload) + "\n") - -print(json.dumps({{ - "hookSpecificOutput": {{ - "hookEventName": "PostToolUse", - "additionalContext": "observed apps file payload" - }} -}})) -"#, - log_path = log_path.display(), - ); - let hooks = serde_json::json!({ - "hooks": { - "PostToolUse": [{ - "matcher": DOCUMENT_EXTRACT_HOOK_MATCHER, - "hooks": [{ - "type": "command", - "command": format!("python3 {}", script_path.display()), - "statusMessage": "running apps file post tool use hook", - }] - }] - } - }); - - fs::write(&script_path, script).context("write post tool use hook script")?; - fs::write(home.join("hooks.json"), hooks.to_string()).context("write hooks.json")?; - Ok(()) -} - -fn read_post_tool_use_hook_inputs(home: &Path) -> Result> { - fs::read_to_string(home.join("post_tool_use_hook_log.jsonl")) - .context("read post tool use hook log")? - .lines() - .filter(|line| !line.trim().is_empty()) - .map(|line| serde_json::from_str(line).context("parse post tool use hook input")) - .collect() -} - -fn schema_filtered_uploaded_file(server: &MockServer) -> Value { - json!({ - "download_url": format!("{}/download/file_123", server.uri()), - "file_id": "file_123", - }) -} - -async fn mount_file_upload_mocks(server: &MockServer, file_size_bytes: u64) { - Mock::given(method("POST")) - .and(path("/files")) - .and(header("chatgpt-account-id", "account_id")) - .and(body_partial_json(json!({ - "file_name": "report.txt", - "file_size": file_size_bytes, - "use_case": "codex", - }))) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "file_id": "file_123", - "upload_url": format!("{}/upload/file_123", server.uri()), - }))) - .expect(1) - .mount(server) - .await; - Mock::given(method("PUT")) - .and(path("/upload/file_123")) - .and(header("content-length", file_size_bytes.to_string())) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(server) - .await; - Mock::given(method("POST")) - .and(path("/files/file_123/uploaded")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "status": "success", - "download_url": format!("{}/download/file_123", server.uri()), - "file_name": "report.txt", - "mime_type": "text/plain", - "file_size_bytes": file_size_bytes, - }))) - .expect(1) - .mount(server) - .await; -} - -async fn run_extract_turn( - test: &TestCodex, - server: &MockServer, - permission_profile: PermissionProfile, -) -> Result { - let mock = mount_sse_sequence( - server, - vec![ - sse(vec![ - ev_response_created("resp-1"), - ev_tool_search_call( - "extract-search-1", - &json!({ - "query": "extract text from uploaded document", - "limit": 1, - }), - ), - ev_completed("resp-1"), - ]), - sse(vec![ - ev_response_created("resp-2"), - ev_function_call_with_namespace( - "extract-call-1", - DOCUMENT_EXTRACT_NAMESPACE, - DOCUMENT_EXTRACT_TOOL, - &json!({"file": "report.txt"}).to_string(), - ), - ev_completed("resp-2"), - ]), - sse(vec![ - ev_response_created("resp-3"), - ev_assistant_message("msg-1", "done"), - ev_completed("resp-3"), - ]), - ], - ) - .await; - - test.submit_turn_with_approval_and_permission_profile( - "Extract the report text with the app tool.", - AskForApproval::Never, - permission_profile, - ) - .await?; - - Ok(mock) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn codex_apps_file_params_omit_fields_absent_from_tool_schema() -> Result<()> { - let server = start_mock_server().await; - let apps_server = AppsTestServer::mount(&server).await?; - mount_file_upload_mocks(&server, STREAMED_FILE_SIZE as u64).await; - - let mut builder = apps_enabled_builder(apps_server.chatgpt_base_url.clone()) - .with_workspace_setup(|cwd, fs| async move { - let report_path = executor_path_uri(cwd.join("report.txt"))?; - fs.write_file( - &report_path, - vec![b'x'; STREAMED_FILE_SIZE], - Default::default(), - /*sandbox*/ None, - ) - .await?; - Ok(()) - }); - let test = builder.build_with_auto_env(&server).await?; - let mock = run_extract_turn(&test, &server, PermissionProfile::Disabled).await?; - - let requests = mock.requests(); - let search_output = requests[1].tool_search_output("extract-search-1"); - let missing_tool_message = format!( - "missing tool {DOCUMENT_EXTRACT_NAMESPACE}{DOCUMENT_EXTRACT_TOOL} in tool_search output: {search_output:?}" - ); - let extract_tool = namespace_child_tool( - &search_output, - DOCUMENT_EXTRACT_NAMESPACE, - DOCUMENT_EXTRACT_TOOL, - ) - .expect(&missing_tool_message); - assert_eq!( - extract_tool.pointer("/parameters/properties/file"), - Some(&json!({ - "type": "string", - "description": "Document file payload. This parameter expects an absolute local file path. If you want to upload a file, provide the absolute path to that file here." - })) - ); - - let apps_tool_call = - recorded_apps_tool_call_by_name(&server, CALENDAR_EXTRACT_TEXT_TOOL_NAME).await; - - assert_eq!( - apps_tool_call.pointer("/params/arguments/file"), - Some(&schema_filtered_uploaded_file(&server)) - ); - assert_eq!( - apps_tool_call.pointer("/params/_meta/_codex_apps"), - Some(&json!({ - "call_id": "extract-call-1", - "root_turn_id": requests[0].body_json()["client_metadata"]["turn_id"], - "resource_uri": DOCUMENT_EXTRACT_TEXT_RESOURCE_URI, - "contains_mcp_source": true, - "connector_id": "calendar", - })) - ); - let requests = server.received_requests().await.expect("capture requests"); - let upload_request = requests - .iter() - .find(|request| request.url.path() == "/files") - .expect("app tool should create a Files upload"); - let upload_body: Value = - serde_json::from_slice(&upload_request.body).expect("Files request should be JSON"); - assert_eq!( - upload_body.get("codex_connector_id"), - Some(&json!("calendar")) - ); - let thread_id = json!(test.session_configured.session_id); - assert_eq!( - apps_tool_call.pointer("/params/_meta/threadId"), - Some(&thread_id) - ); - assert_eq!(upload_body.get("codex_thread_id"), None); - assert_eq!(upload_body.get("upload_source"), None); - assert_eq!(upload_body.get("store_in_library"), None); - - server.verify().await; - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn codex_apps_file_params_pass_uploaded_file_to_post_tool_use_hook() -> Result<()> { - let server = start_mock_server().await; - let apps_server = AppsTestServer::mount(&server).await?; - mount_file_upload_mocks(&server, /*file_size_bytes*/ 11).await; - - let mut builder = apps_enabled_builder(apps_server.chatgpt_base_url.clone()) - .with_pre_build_hook(move |home| { - if let Err(error) = write_post_tool_use_hook(home) { - panic!("failed to write apps file post tool use hook fixture: {error}"); - } - }) - .with_config(move |config| { - trust_discovered_hooks(config); - }); - let test = builder.build(&server).await?; - tokio::fs::write(test.cwd.path().join("report.txt"), b"hello world").await?; - let _responses = run_extract_turn(&test, &server, PermissionProfile::Disabled).await?; - - let hook_inputs = read_post_tool_use_hook_inputs(test.codex_home_path())?; - assert_eq!(hook_inputs.len(), 1); - assert_eq!( - hook_inputs[0]["tool_input"]["file"], - schema_filtered_uploaded_file(&server) - ); - - server.verify().await; - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn codex_apps_file_params_retry_stream_under_restricted_read_policy() -> Result<()> { - skip_if_target_windows!( - Ok(()), - "Windows restricted-token sandbox cannot enforce deny-read policies" - ); - skip_if_sandbox!(Ok(())); - - let server = start_mock_server().await; - let apps_server = AppsTestServer::mount(&server).await?; - mount_file_upload_mocks(&server, STREAMED_FILE_SIZE as u64).await; - Mock::given(method("PUT")) - .and(path("/upload/file_123")) - .respond_with(ResponseTemplate::new(503).insert_header("x-ms-retry-after-ms", "0")) - .with_priority(1) - .up_to_n_times(1) - .expect(1) - .mount(&server) - .await; - - let mut builder = apps_enabled_builder(apps_server.chatgpt_base_url) - .with_config(|config| restrict_apps_upload_reads(config, "private.txt")) - .with_workspace_setup(|cwd, fs| async move { - let report_path = PathUri::from_abs_path(&cwd.join("report.txt")); - fs.write_file( - &report_path, - vec![b'x'; STREAMED_FILE_SIZE], - Default::default(), - /*sandbox*/ None, - ) - .await?; - Ok(()) - }); - let test = builder.build_with_auto_env(&server).await?; - let permission_profile = test.config.permissions.permission_profile().clone(); - - run_extract_turn(&test, &server, permission_profile).await?; - - let requests = server.received_requests().await.expect("capture requests"); - let bodies: Vec<_> = requests - .iter() - .filter(|request| request.url.path() == "/upload/file_123") - .map(|request| request.body.as_slice()) - .collect(); - let contents = vec![b'x'; STREAMED_FILE_SIZE]; - assert_eq!(bodies, vec![contents.as_slice(); 2]); - - let apps_tool_call = - recorded_apps_tool_call_by_name(&server, CALENDAR_EXTRACT_TEXT_TOOL_NAME).await; - assert_eq!( - apps_tool_call.pointer("/params/arguments/file"), - Some(&schema_filtered_uploaded_file(&server)) - ); - server.verify().await; - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn codex_apps_file_params_reject_denied_file_before_upload() -> Result<()> { - skip_if_target_windows!( - Ok(()), - "Windows restricted-token sandbox cannot enforce deny-read policies" - ); - skip_if_sandbox!(Ok(())); - - let server = start_mock_server().await; - let apps_server = AppsTestServer::mount(&server).await?; - let mut builder = apps_enabled_builder(apps_server.chatgpt_base_url) - .with_config(|config| restrict_apps_upload_reads(config, "report.txt")) - .with_workspace_setup(|cwd, fs| async move { - let report_path = PathUri::from_abs_path(&cwd.join("report.txt")); - fs.write_file( - &report_path, - b"private".to_vec(), - Default::default(), - /*sandbox*/ None, - ) - .await?; - Ok(()) - }); - let test = builder.build_with_auto_env(&server).await?; - let permission_profile = test.config.permissions.permission_profile().clone(); - - let responses = run_extract_turn(&test, &server, permission_profile).await?; - let requests = responses.requests(); - let output_item = requests[2].function_call_output("extract-call-1"); - let output = output_item["output"][1]["text"] - .as_str() - .context("denied Apps upload should return a tool error")?; - - assert!( - output.contains("failed to upload `report.txt`") - && (output.contains("Permission denied") || output.contains("Operation not permitted")), - "unexpected upload error: {output}" - ); - assert!( - server - .received_requests() - .await - .context("mock server should expose received requests")? - .iter() - .all(|request| request.url.path() != "/files"), - "denied files must not start an upload" - ); - Ok(()) -} diff --git a/codex-rs/core/tests/suite/request_plugin_install.rs b/codex-rs/core/tests/suite/request_plugin_install.rs index 834e338e..38cb627e 100644 --- a/codex-rs/core/tests/suite/request_plugin_install.rs +++ b/codex-rs/core/tests/suite/request_plugin_install.rs @@ -75,9 +75,6 @@ use wiremock::matchers::query_param; use super::rmcp_client::remote_aware_environment_id; use super::rmcp_client::remote_aware_stdio_server_bin; -#[path = "request_plugin_install_runtime_auth.rs"] -mod runtime_auth_tests; - const TOOL_SEARCH_TOOL_NAME: &str = "tool_search"; const LIST_AVAILABLE_PLUGINS_TO_INSTALL_TOOL_NAME: &str = "list_available_plugins_to_install"; const REQUEST_PLUGIN_INSTALL_TOOL_NAME: &str = "request_plugin_install"; diff --git a/codex-rs/core/tests/suite/request_plugin_install_runtime_auth.rs b/codex-rs/core/tests/suite/request_plugin_install_runtime_auth.rs deleted file mode 100644 index eb0e51ec..00000000 --- a/codex-rs/core/tests/suite/request_plugin_install_runtime_auth.rs +++ /dev/null @@ -1,248 +0,0 @@ -//! Exercise recommended-plugin metadata after resuming with another account. - -use super::*; -use base64::Engine; -use codex_features::RuntimeAuthMode; -use codex_history::InitialHistory; -use codex_history::ResumedHistory; -use codex_protocol::mcp::ClientMcpExtensions; -use core_test_support::runtime_auth::PROBE_SERVER; -use core_test_support::runtime_auth::run_harness_through_proxy; -use pretty_assertions::assert_eq; -use test_case::test_case; - -fn actor_token(actor: &str) -> String { - let claims = json!({ - "exp": 4_102_444_800_u64, - "session_id": format!("session-{actor}"), - "iss": "https://auth.openai.com", - "https://api.openai.com/auth": { - "chatgpt_user_id": format!("user-{actor}"), - "chatgpt_account_id": format!("account-{actor}"), - }, - }); - format!( - "e30.{}.c2ln", - base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string()) - ) -} - -#[test_case(RuntimeAuthMode::DualHeader; "dual_header")] -#[test_case(RuntimeAuthMode::AssertionOnly; "assertion_only")] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn resumed_plugin_install_uses_the_threads_account(mode: RuntimeAuthMode) -> Result<()> { - skip_if_no_network!(Ok(())); - const PLUGIN_ID: &str = "plugin_connector_github"; - if std::env::var(PROBE_SERVER).is_ok() { - let server = start_mock_server().await; - let requests = mount_sse_sequence( - &server, - vec![ - sse(vec![ev_completed("original")]), - sse(vec![ - ev_function_call( - "install-github", - REQUEST_PLUGIN_INSTALL_TOOL_NAME, - &json!({ - "plugin_id": "github@openai-curated-remote", - "suggest_reason": "Use GitHub for this request", - }) - .to_string(), - ), - ev_completed("install"), - ]), - sse(vec![ev_completed("finished")]), - ], - ) - .await; - let mut builder = test_codex() - .with_auth(CodexAuth::from_external_chatgpt_tokens( - &actor_token("a"), - "account-a", - Some("plus"), - )?) - .with_config(move |config| { - config - .permissions - .set_permission_profile(PermissionProfile::Disabled) - .expect("test config should allow disabled permissions"); - configure_apps_without_search_tool(config, "https://chatgpt.com"); - config - .features - .enable(Feature::RuntimeAgentInstances) - .unwrap(); - config.runtime_auth_mode = mode; - }); - let test = builder.build_with_auto_env(&server).await?; - test.codex - .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { - text: "Original account".into(), - text_elements: Vec::new(), - }])) - .await?; - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - test.codex.ensure_rollout_materialized().await; - test.codex.flush_rollout().await?; - let rollout = test.codex.rollout_path().context("original rollout")?; - test.codex.shutdown_and_wait().await?; - let _ = test - .thread_manager - .remove_thread(&test.session_configured.thread_id) - .await; - let history = test - .thread_store - .load_latest_model_context(codex_thread_store::LoadThreadHistoryParams { - thread_id: test.session_configured.thread_id, - include_archived: false, - }) - .await?; - let replacement = codex_core::test_support::auth_manager_from_auth_with_home( - CodexAuth::from_external_chatgpt_tokens(&actor_token("b"), "account-b", Some("plus"))?, - test.codex_home_path().to_path_buf(), - ); - let resumed = test - .thread_manager - .resume_thread_with_history( - test.config.clone(), - InitialHistory::Resumed(ResumedHistory { - history_revision: None, - conversation_id: history.thread_id, - history: Arc::new(history.items), - rollout_path: Some(rollout), - }), - replacement, - /*parent_trace*/ None, - ClientMcpExtensions::default(), - ) - .await?; - resumed - .thread - .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { - text: "Use GitHub".into(), - text_elements: Vec::new(), - }])) - .await?; - let elicitation = wait_for_event_match(&resumed.thread, |event| match event { - EventMsg::ElicitationRequest(request) => Some(Ok(request.clone())), - EventMsg::TurnComplete(_) => Some(Err(anyhow::anyhow!( - "the resumed account must reach the plugin installation prompt" - ))), - _ => None, - }) - .await?; - let ElicitationRequest::Form { - meta: Some(meta), .. - } = &elicitation.request - else { - anyhow::bail!("expected plugin installation metadata"); - }; - assert_eq!(meta["remote_plugin_id"], PLUGIN_ID); - resumed - .thread - .submit(Op::ResolveElicitation { - server_name: elicitation.server_name, - request_id: elicitation.id, - decision: ElicitationAction::Decline, - content: None, - meta: None, - }) - .await?; - wait_for_event(&resumed.thread, |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - assert_eq!(requests.requests().len(), 3); - resumed.thread.shutdown_and_wait().await?; - return Ok(()); - } - - let server = start_mock_server().await; - let _apps = AppsTestServer::mount(&server).await?; - mount_recommendations( - &server, - ResponseTemplate::new(200).set_body_json(json!({ - "enabled": true, - "plugins": [{"id": PLUGIN_ID, "name": "github", "display_name": "GitHub"}], - })), - ) - .await; - Mock::given(method("POST")) - .and(path("/agent/register")) - .respond_with(|request: &wiremock::Request| { - let body: Value = request.body_json().unwrap(); - let actor = if body["actor_auth"]["credential"] == actor_token("a") { - "a" - } else { - "b" - }; - assert_eq!(body["actor_auth"]["credential"], actor_token(actor)); - ResponseTemplate::new(200).set_body_json(json!({ - "runtime_agent_instance_id": format!("runtime-{actor}"), - "agent_host_id": "host-a", - "actor": { - "kind": "chatgpt", - "user_id": format!("user-{actor}"), - "account_id": format!("account-{actor}"), - }, - })) - }) - .expect(2) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path(format!("/ps/plugins/{PLUGIN_ID}"))) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "id": PLUGIN_ID, "name": "github", "scope": "GLOBAL", "status": "ENABLED", - "installation_policy": "AVAILABLE", "authentication_policy": "ON_USE", - "release": { - "display_name": "GitHub", "description": "Work with GitHub repositories.", - "app_ids": [], "interface": {}, - }, - }))) - .expect(1) - .mount(&server) - .await; - let case = match mode { - RuntimeAuthMode::DualHeader => "dual_header", - RuntimeAuthMode::AssertionOnly => "assertion_only", - }; - run_harness_through_proxy( - &server, - &format!("suite::request_plugin_install::runtime_auth_tests::resumed_plugin_install_uses_the_threads_account::{case}"), - /*realtime_target*/ None, - ).await?; - let requests = server - .received_requests() - .await - .context("recorded requests")?; - let metadata = requests - .iter() - .find(|request| request.url.path() == format!("/ps/plugins/{PLUGIN_ID}")) - .context("plugin metadata request")?; - let proof = match mode { - RuntimeAuthMode::DualHeader => { - assert_eq!( - metadata.headers["authorization"], - format!("Bearer {}", actor_token("b")) - ); - metadata.headers["x-openai-agent-assertion"].to_str()? - } - RuntimeAuthMode::AssertionOnly => { - assert!(!metadata.headers.contains_key("x-openai-agent-assertion")); - metadata.headers["authorization"] - .to_str()? - .strip_prefix("AgentAssertion ") - .context("assertion auth")? - } - }; - let claims: Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(proof.split('.').nth(2).context("assertion payload")?)?, - )?; - assert_eq!(claims["runtime_agent_instance"], "runtime-b"); - server.verify().await; - Ok(()) -} diff --git a/codex-rs/core/tests/suite/runtime_auth.rs b/codex-rs/core/tests/suite/runtime_auth.rs deleted file mode 100644 index 1c49cc36..00000000 --- a/codex-rs/core/tests/suite/runtime_auth.rs +++ /dev/null @@ -1,1157 +0,0 @@ -//! Exercise harness-owned auth through real sessions, subagents, and delegated review. - -use anyhow::Context; -use anyhow::Result; -use base64::Engine; -use codex_core::CodexThread; -use codex_core::StartThreadOptions; -use codex_core::TurnInputRequest; -use codex_features::Feature; -use codex_features::RuntimeAuthMode; -use codex_history::InitialHistory; -use codex_history::ResumedHistory; -use codex_login::CodexAuth; -use codex_model_provider::ProviderAuthContext; -use codex_models_manager::manager::ModelCatalogSettings; -use codex_models_manager::manager::RefreshStrategy; -use codex_protocol::mcp::ClientMcpExtensions; -use codex_protocol::protocol::EventMsg; -use codex_protocol::protocol::InternalSessionSource; -use codex_protocol::protocol::Op; -use codex_protocol::protocol::ReviewRequest; -use codex_protocol::protocol::ReviewTarget; -use codex_protocol::protocol::SessionSource; -use codex_protocol::protocol::SubAgentSource; -use codex_protocol::user_input::UserInput; -use core_test_support::responses; -use core_test_support::runtime_auth::PROBE_SERVER; -use core_test_support::runtime_auth::run_harness_through_proxy; -use core_test_support::skip_if_no_network; -use core_test_support::test_codex::test_codex; -use core_test_support::wait_for_event; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use std::collections::BTreeSet; -use std::sync::Arc; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::body_string_contains; -use wiremock::matchers::header_regex; -use wiremock::matchers::method; -use wiremock::matchers::path; - -const TEST_NAME: &str = "suite::runtime_auth::harness_shares_runtime_and_honors_thread_auth_config"; - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn harness_shares_runtime_and_honors_thread_auth_config() -> Result<()> { - skip_if_no_network!(Ok(())); - if let Ok(server_uri) = std::env::var(PROBE_SERVER) { - return exercise_harness(server_uri).await; - } - - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/agent/register")) - .respond_with(|request: &wiremock::Request| { - let body: Value = request.body_json().expect("registration body should parse"); - let replacement = body["actor_auth"]["credential"] == "key-b"; - ResponseTemplate::new(200).set_body_json(json!({ - "runtime_agent_instance_id": if replacement { "runtime-replacement" } else { "runtime-shared" }, - "agent_host_id": "host-a", - "actor": {"kind": "platform", "user_id": if replacement { "user-b" } else { "user-a" }, "organization_id": "org-a", "project_id": null}, - })) - }) - .expect(2) - .mount(&server) - .await; - // Both runtime modes retain the normal same-origin redirect behavior. - for label in ["parent-dual", "child-assertion"] { - Mock::given(method("POST")) - .and(path("/v1/responses")) - .and(body_string_contains(label)) - .respond_with( - ResponseTemplate::new(307) - .insert_header("Location", "https://api.openai.com/redirected/responses"), - ) - .up_to_n_times(1) - .expect(1) - .with_priority(1) - .mount(&server) - .await; - } - Mock::given(path("/backend-api/files")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "file_id": "file-a", "upload_url": format!("{}/blob", server.uri()), - }))) - .expect(2) - .mount(&server) - .await; - Mock::given(path("/backend-api/files/file-a/uploaded")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "status": "success", "download_url": format!("{}/blob", server.uri()), - "file_name": "empty.txt", "file_size_bytes": 0, - }))) - .expect(2) - .mount(&server) - .await; - Mock::given(path("/blob")) - .and(method("PUT")) - .respond_with(ResponseTemplate::new(200)) - .expect(2) - .mount(&server) - .await; - let responses = responses::mount_response_sequence( - &server, - (0..14) - .map(|i| { - let response = - responses::sse_response(responses::sse(vec![responses::ev_completed( - &format!("resp-{i}"), - )])); - if (1..=4).contains(&i) { - response.insert_header("X-Models-Etag", format!("catalog-refreshed-{i}")) - } else { - response - } - }) - .collect(), - ) - .await; - Mock::given(method("GET")) - .and(path("/catalog-isolation")) - .respond_with(ResponseTemplate::new(200).set_body_json(catalog_fixture())) - .expect(2) - .mount(&server) - .await; - - Mock::given(method("GET")) - .and(path("/selected-catalog")) - .and(header_regex("authorization", "^AgentAssertion ")) - .respond_with(ResponseTemplate::new(200).set_body_json(catalog_fixture())) - .expect(1) - .mount(&server) - .await; - - for mode in ["dual", "assertion", "disabled"] { - Mock::given(method("GET")) - .and(path(format!("/catalog-reload/{mode}"))) - .respond_with( - ResponseTemplate::new(200) - .insert_header("ETag", "catalog-initial") - .set_body_json(catalog_fixture()), - ) - .expect(2) - .mount(&server) - .await; - } - - Mock::given(method("GET")) - .and(path("/resumed-off-models")) - .respond_with(ResponseTemplate::new(200).set_body_json(catalog_fixture())) - .mount(&server) - .await; - - run_harness_through_proxy(&server, TEST_NAME, /*realtime_target*/ None).await?; - - let requests = responses.requests(); - let expected = [ - (Some("startup-disabled"), "Bearer key-a", None), - ( - Some("discovery-off"), - "Bearer key-a", - Some("runtime-shared"), - ), - (Some("catalog-dual"), "Bearer key-a", Some("runtime-shared")), - ( - Some("catalog-assertion"), - "AgentAssertion ", - Some("runtime-shared"), - ), - (Some("catalog-disabled"), "Bearer key-a", None), - (Some("parent-dual"), "Bearer key-a", Some("runtime-shared")), - // Explicit first-party inference with a third-party catalog. - (None, "Bearer key-a", Some("runtime-shared")), - ( - Some("child-assertion"), - "AgentAssertion ", - Some("runtime-shared"), - ), - (None, "AgentAssertion ", Some("runtime-shared")), - // The inline review delegate inherits the parent's dual-header mode. - (None, "Bearer key-a", Some("runtime-shared")), - (Some("thread-disabled"), "Bearer key-a", None), - (Some("third-party"), "Bearer key-a", None), - ( - Some("replacement-root"), - "Bearer key-b", - Some("runtime-replacement"), - ), - ( - Some("replacement-child"), - "Bearer key-b", - Some("runtime-replacement"), - ), - ]; - assert_eq!(requests.len(), expected.len()); - let mut proof_ids = BTreeSet::new(); - for (request, (label, expected_auth, expected_runtime)) in requests.iter().zip(expected) { - if let Some(label) = label { - assert_eq!( - request - .message_input_texts("user") - .last() - .map(String::as_str), - Some(label) - ); - } - let auth = request.header("authorization").unwrap(); - let proof = if expected_auth == "AgentAssertion " { - assert!(request.header("x-openai-agent-assertion").is_none()); - Some( - auth.strip_prefix(expected_auth) - .context("assertion-only request")? - .to_owned(), - ) - } else { - assert_eq!(auth, expected_auth); - request.header("x-openai-agent-assertion") - }; - assert_eq!(proof.is_some(), expected_runtime.is_some(), "{label:?}"); - if let Some(proof) = proof { - let payload: Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(proof.split('.').nth(2).unwrap())?, - )?; - assert_eq!(payload["runtime_agent_instance"], expected_runtime.unwrap()); - assert!(proof_ids.insert(payload["id"].as_str().unwrap().to_owned())); - } - } - let resumed_catalog: Vec<_> = server - .received_requests() - .await - .unwrap() - .into_iter() - .filter(|request| request.url.path() == "/resumed-off-models") - .collect(); - assert!( - !resumed_catalog.is_empty(), - "resumed thread must fetch its catalog" - ); - for request in resumed_catalog { - assert_eq!(request.headers["authorization"], "Bearer key-b"); - assert!(!request.headers.contains_key("openai-agent-assertion")); - } - let catalogs: Vec<_> = server - .received_requests() - .await - .unwrap() - .into_iter() - .filter(|request| request.url.path() == "/catalog-isolation") - .collect(); - assert_eq!(catalogs.len(), 2); - for request in catalogs { - assert!( - request.headers.contains_key("x-openai-agent-assertion") - || request.headers["authorization"] - .to_str()? - .starts_with("AgentAssertion ") - ); - } - let requests = server.received_requests().await.unwrap(); - let reloaded_catalogs: Vec<_> = requests - .iter() - .filter(|request| request.url.path().starts_with("/catalog-reload/")) - .collect(); - assert_eq!(reloaded_catalogs.len(), 6); - for request in reloaded_catalogs { - assert_eq!(request.headers["originator"], "codex_work_cca"); - let authorization = request.headers["authorization"].to_str()?; - if request.url.path().ends_with("/disabled") { - assert_eq!(authorization, "Bearer key-a"); - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - continue; - } - let proof = if request.url.path().ends_with("/dual") { - assert_eq!(authorization, "Bearer key-a"); - request.headers["x-openai-agent-assertion"].to_str()? - } else { - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - authorization - .strip_prefix("AgentAssertion ") - .context("catalog assertion")? - }; - let payload: Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(proof.split('.').nth(2).unwrap())?, - )?; - assert_eq!(payload["runtime_agent_instance"], "runtime-shared"); - assert!(proof_ids.insert(payload["id"].as_str().unwrap().to_owned())); - } - let files: Vec<_> = requests - .iter() - .filter(|r| r.url.path().starts_with("/backend-api/files")) - .collect(); - assert_eq!(files.len(), 4); - for (index, request) in files.iter().enumerate() { - let authorization = request.headers["authorization"].to_str()?; - let proof = if index < 2 { - assert_eq!(authorization, "Bearer key-a"); - request.headers["x-openai-agent-assertion"].to_str()? - } else { - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - authorization - .strip_prefix("AgentAssertion ") - .context("assertion-only file auth")? - }; - let payload: Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(proof.split('.').nth(2).unwrap())?, - )?; - assert_eq!(payload["runtime_agent_instance"], "runtime-shared"); - assert!(proof_ids.insert(payload["id"].as_str().unwrap().to_owned())); - } - server.verify().await; - Ok(()) -} - -async fn exercise_harness(server_uri: String) -> Result<()> { - let server = MockServer::start().await; - let test = test_codex() - .with_auth(CodexAuth::from_api_key("key-a")) - .with_config(|config| { - config.model_provider.base_url = Some("https://api.openai.com/v1".into()); - config.chatgpt_base_url = "https://us.chatgpt.com/backend-api".to_string(); - config.model_provider.env_http_headers = None; - config - .features - .disable(Feature::RuntimeAgentInstances) - .expect("test config should allow disabling runtime auth"); - config.model_catalog = Some( - codex_models_manager::bundled_models_response() - .expect("bundled models should parse"), - ); - }) - .build_with_auto_env(&server) - .await?; - turn(&test.codex, "startup-disabled").await?; - - // Enable after startup, then share one lazy registration with a child and an inline delegate. - let mut enabled = test.config.clone(); - enabled.features.enable(Feature::RuntimeAgentInstances)?; - // Initial discovery and response-triggered ETag refresh use each thread's effective auth. - for (mode, runtime_enabled) in [ - (RuntimeAuthMode::DualHeader, true), - (RuntimeAuthMode::AssertionOnly, true), - (RuntimeAuthMode::DualHeader, false), - ] { - let mut catalog_config = enabled.clone(); - catalog_config.model_catalog = None; - catalog_config - .features - .enable(Feature::ApiKeyModelDiscovery)?; - catalog_config.runtime_auth_mode = mode; - if !runtime_enabled { - catalog_config - .features - .disable(Feature::RuntimeAgentInstances)?; - } - catalog_config.model = None; - let label = if !runtime_enabled { - "disabled" - } else if mode == RuntimeAuthMode::AssertionOnly { - "assertion" - } else { - "dual" - }; - catalog_config.model_provider.model_catalog_url = - Some(format!("https://api.openai.com/catalog-reload/{label}").into()); - if mode == RuntimeAuthMode::AssertionOnly { - let mut selected = catalog_config.clone(); - selected.model_provider.base_url = Some(server_uri.clone()); - selected.model_provider.model_catalog_url = - Some("https://api.openai.com/selected-catalog".into()); - let models = test - .thread_manager - .temporary_models_manager_for_config(&selected, &ModelCatalogSettings::default()); - models - .raw_model_catalog(RefreshStrategy::Online, selected.http_client_factory()) - .await; - assert_eq!(models.get_remote_models().await, catalog_fixture().models); - } - let catalog_thread = test - .thread_manager - .start_thread(StartThreadOptions { - metrics_service_name: Some("codex_work_cca".into()), - ..StartThreadOptions::new(catalog_config) - }) - .await?; - assert_eq!( - catalog_thread.session_configured.model, - "catalog-isolation-model" - ); - if label == "dual" { - // The first new ETag must not fetch while discovery is disabled. A second, - // distinct ETag on the same thread must fetch once discovery is enabled again. - test.thread_manager - .set_api_key_model_discovery_enabled(/*enabled*/ false); - turn(&catalog_thread.thread, "discovery-off").await?; - test.thread_manager - .set_api_key_model_discovery_enabled(/*enabled*/ true); - } - turn(&catalog_thread.thread, &format!("catalog-{label}")).await?; - } - let parent = test - .thread_manager - .start_thread(StartThreadOptions::new(enabled.clone())) - .await?; - turn(&parent.thread, "parent-dual").await?; - exercise_provider_destinations(&parent.thread, &enabled).await?; - upload_with_harness(&test.thread_manager, &enabled).await?; - let mut child_config = enabled.clone(); - child_config.runtime_auth_mode = RuntimeAuthMode::AssertionOnly; - parent.thread.ensure_rollout_materialized().await; - parent.thread.flush_rollout().await?; - let prepared = test - .thread_store - .prepare_fork(codex_thread_store::PrepareForkParams { - thread_id: parent.thread_id, - boundary: codex_thread_store::ForkBoundary::Latest, - }) - .await?; - let child = test - .thread_manager - .fork_prepared_thread( - StartThreadOptions { - session_source: Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { - parent_thread_id: parent.thread_id, - depth: 1, - agent_path: None, - agent_nickname: None, - agent_role: None, - })), - ..StartThreadOptions::new(child_config.clone()) - }, - prepared, - ) - .await?; - turn(&child.thread, "child-assertion").await?; - exercise_provider_destinations(&child.thread, &enabled).await?; - upload_with_harness(&test.thread_manager, &child_config).await?; - parent - .thread - .submit(Op::Review { - review_request: ReviewRequest { - target: ReviewTarget::Custom { - instructions: "Review this change".into(), - }, - user_facing_hint: None, - }, - }) - .await?; - wait_for_event(&parent.thread, |e| matches!(e, EventMsg::TurnComplete(_))).await; - - let disabled = test - .thread_manager - .start_thread(StartThreadOptions::new(test.config.clone())) - .await?; - turn(&disabled.thread, "thread-disabled").await?; - // A third-party OpenAI-compatible endpoint still uses its existing provider authentication. - enabled.model_provider.base_url = Some(format!("{server_uri}/v1")); - enabled.chatgpt_base_url = "https://custom.example.test/backend-api".to_string(); - let third_party = test - .thread_manager - .start_thread(StartThreadOptions::new(enabled)) - .await?; - turn(&third_party.thread, "third-party").await?; - - // Resume a stopped thread under a separately supplied credential context. An internal child - // must inherit the resumed parent's runtime, not the ThreadManager's original default. - let rollout = parent - .thread - .rollout_path() - .context("parent rollout should exist")?; - parent.thread.submit(Op::Shutdown).await?; - wait_for_event(&parent.thread, |e| matches!(e, EventMsg::ShutdownComplete)).await; - test.thread_manager.remove_thread(&parent.thread_id).await; - let context = test - .thread_store - .load_latest_model_context(codex_thread_store::LoadThreadHistoryParams { - thread_id: parent.thread_id, - include_archived: false, - }) - .await?; - let replacement = codex_core::test_support::auth_manager_from_auth_with_home( - CodexAuth::from_api_key("key-b"), - test.codex_home_path().to_path_buf(), - ); - let history = InitialHistory::Resumed(ResumedHistory { - history_revision: None, - conversation_id: context.thread_id, - history: Arc::new(context.items), - rollout_path: Some(rollout), - }); - let mut disabled = test.config.clone(); - disabled.model_catalog = None; - disabled.model = None; - disabled.model_provider.model_catalog_url = - Some("https://api.openai.com/resumed-off-models".into()); - let resumed_off = test - .thread_manager - .resume_thread_with_history( - disabled, - history.clone(), - Arc::clone(&replacement), - /*parent_trace*/ None, - ClientMcpExtensions::default(), - ) - .await?; - assert_eq!( - resumed_off.session_configured.model, - "catalog-isolation-model" - ); - resumed_off.thread.submit(Op::Shutdown).await?; - wait_for_event(&resumed_off.thread, |e| { - matches!(e, EventMsg::ShutdownComplete) - }) - .await; - test.thread_manager - .remove_thread(&resumed_off.thread_id) - .await; - - let mut resumed_config = test.config.clone(); - resumed_config - .features - .enable(Feature::RuntimeAgentInstances)?; - let resumed = test - .thread_manager - .resume_thread_with_history( - resumed_config.clone(), - history, - replacement, - /*parent_trace*/ None, - ClientMcpExtensions::default(), - ) - .await?; - turn(&resumed.thread, "replacement-root").await?; - let internal = test - .thread_manager - .spawn_internal_session( - resumed.thread_id, - StartThreadOptions { - session_source: Some(SessionSource::Internal( - InternalSessionSource::MemoryConsolidation, - )), - ..StartThreadOptions::new(resumed_config) - }, - ) - .await?; - turn(&internal.thread, "replacement-child").await?; - Ok(()) -} - -fn catalog_fixture() -> codex_protocol::openai_models::ModelsResponse { - let mut models = codex_models_manager::bundled_models_response() - .expect("bundled catalog should provide a valid model fixture"); - models.models.truncate(1); - models.models[0].slug = "catalog-isolation-model".into(); - models -} - -async fn exercise_provider_destinations( - thread: &CodexThread, - config: &codex_core::config::Config, -) -> Result<()> { - let external = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/catalog-isolation")) - .respond_with(ResponseTemplate::new(200).set_body_json(catalog_fixture())) - .expect(1) - .mount(&external) - .await; - let external_responses = responses::mount_sse_once( - &external, - responses::sse(vec![responses::ev_completed("external-response")]), - ) - .await; - let auth = thread - .thread_extension_data() - .get::() - .context("thread should publish its provider auth context")?; - for (inference, catalog) in [ - ("https://api.openai.com/v1".to_string(), external.uri()), - (external.uri(), "https://api.openai.com".to_string()), - ] { - let mut info = config.model_provider.clone(); - info.base_url = Some(inference); - info.model_catalog_url = Some(format!("{catalog}/catalog-isolation").into()); - let provider = auth.model_provider(info); - let setup = codex_model_provider::resolve_request( - provider.as_ref(), - /*scope*/ None, - /*routing*/ None, - config.http_client_factory(), - ) - .await?; - let client = codex_api::ResponsesClient::new( - setup.http_transport("responses")?, - setup.api_provider, - setup.api_auth, - ); - let _stream = client - .stream( - json!({"model": "test", "input": []}), - http::HeaderMap::new(), - codex_api::Compression::None, - /*turn_state*/ None, - ) - .await?; - let models = provider.models_manager_without_cache(/*config_model_catalog*/ None); - models.set_api_key_model_discovery_enabled(/*enabled*/ true); - models - .raw_model_catalog(RefreshStrategy::Online, config.http_client_factory()) - .await; - assert_eq!(models.get_remote_models().await, catalog_fixture().models); - } - assert_eq!(external_responses.requests().len(), 1); - let requests = external - .received_requests() - .await - .context("external destination should record requests")?; - assert_eq!(requests.len(), 2); - for request in requests { - assert_eq!(request.headers["authorization"], "Bearer key-a"); - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - } - external.verify().await; - Ok(()) -} - -async fn turn(thread: &Arc, label: &str) -> Result<()> { - thread - .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { - text: label.into(), - text_elements: Vec::new(), - }])) - .await?; - wait_for_event(thread, |e| matches!(e, EventMsg::TurnComplete(_))).await; - Ok(()) -} - -async fn upload_with_harness( - manager: &codex_core::ThreadManager, - config: &codex_core::config::Config, -) -> Result<()> { - let (runtime, mode) = manager - .runtime_auth_for_config(config)? - .context("enabled harness runtime")?; - let selected = runtime.auth().await?; - let clients = - codex_http_client::RouteAwareClientPool::new_without_redirects_or_request_logging( - config.http_client_factory(), - codex_http_client::ClientRouteClass::Api, - ) - .with_account_binding(selected.http_client_factory().network_policy()) - .context("upload auth and transport share the application policy")?; - let auth = selected.into_auth_provider(mode); - let uploaded = codex_api::upload_openai_file( - &config.chatgpt_base_url, - auth.as_ref(), - &clients, - "empty.txt".into(), - /*file_size_bytes*/ 0, - || async { Ok(futures::stream::empty()) }, - /*hosted_upload*/ None, - ) - .await?; - assert_eq!(uploaded.uri, "sediment://file-a"); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn mcp_uploads_follow_a_resumed_actors_runtime() -> Result<()> { - use core_test_support::apps_test_server::*; - skip_if_no_network!(Ok(())); - if std::env::var(PROBE_SERVER).is_ok() { - return exercise_mcp_uploads().await; - } - let server = MockServer::start().await; - let other_origin = MockServer::start().await; - let _apps = AppsTestServer::mount(&server).await?; - Mock::given(path("/agent/register")) - .respond_with(|request: &wiremock::Request| { - let body: Value = request.body_json().unwrap(); - let credential = body["actor_auth"]["credential"].as_str().unwrap(); - let claims: Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(credential.split('.').nth(1).unwrap()) - .unwrap(), - ) - .unwrap(); - let user = claims["https://api.openai.com/auth"]["user_id"] - .as_str() - .unwrap(); - ResponseTemplate::new(200).set_body_json(json!({ - "runtime_agent_instance_id": format!("runtime-{user}"), "agent_host_id": "host-a", - "actor": {"kind": "chatgpt", "user_id": user, "account_id": "account_id"}, - })) - }) - .expect(2) - .mount(&server) - .await; - Mock::given(path("/files")) - .respond_with( - ResponseTemplate::new(307).insert_header("location", "/files/create-redirect"), - ) - .expect(3) - .mount(&server) - .await; - Mock::given(path("/files/create-redirect")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "file_id": "file-runtime", "upload_url": format!("{}/blob", server.uri()), - }))) - .expect(3) - .mount(&server) - .await; - Mock::given(path("/files/file-runtime/uploaded")) - .respond_with( - ResponseTemplate::new(307) - .insert_header("location", "/files/file-runtime/uploaded-redirect"), - ) - .expect(3) - .mount(&server) - .await; - Mock::given(path("/files/file-runtime/uploaded-redirect")) - .respond_with( - ResponseTemplate::new(307) - .insert_header("location", format!("{}/finalize", other_origin.uri())), - ) - .expect(3) - .mount(&server) - .await; - Mock::given(path("/finalize")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "status": "success", "download_url": format!("{}/blob", server.uri()), - "file_name": "report.txt", "file_size_bytes": 6, - }))) - .expect(3) - .mount(&other_origin) - .await; - Mock::given(path("/blob")) - .and(method("PUT")) - .respond_with(ResponseTemplate::new(200)) - .expect(3) - .mount(&server) - .await; - let events = (0..3) - .flat_map(|_| { - [ - responses::sse(vec![ - responses::ev_tool_search_call( - "search-file", - &json!({"query": "extract text from uploaded document", "limit": 1}), - ), - responses::ev_completed("search"), - ]), - responses::sse(vec![ - responses::ev_function_call_with_namespace( - "extract-file", - SEARCH_CALENDAR_NAMESPACE, - SEARCH_CALENDAR_EXTRACT_TEXT_TOOL, - &json!({"file": "report.txt"}).to_string(), - ), - responses::ev_completed("extract"), - ]), - responses::sse(vec![ - responses::ev_assistant_message("done", "done"), - responses::ev_completed("done"), - ]), - ] - }) - .collect(); - let responses = responses::mount_sse_sequence(&server, events).await; - run_harness_through_proxy( - &server, - "suite::runtime_auth::mcp_uploads_follow_a_resumed_actors_runtime", - /*realtime_target*/ None, - ) - .await?; - assert_eq!(responses.requests().len(), 9); - let requests = server.received_requests().await.unwrap(); - let mut proof_ids = BTreeSet::new(); - let mut runtimes = BTreeSet::new(); - let mut uploaded_calls = 0; - let mut file_requests = 0; - for request in &requests { - let path = request.url.path().trim_end_matches('/'); - if path == "/blob" { - assert!(!request.headers.contains_key("authorization")); - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - assert_eq!(request.body, b"report"); - continue; - } - if !(path.ends_with("/responses") - || path == "/backend-api/ps/mcp" - || path.starts_with("/files")) - { - continue; - } - file_requests += usize::from(path.starts_with("/files")); - let authorization = request.headers["authorization"].to_str()?; - let assertion_only = authorization.starts_with("AgentAssertion "); - let proof = if let Some(proof) = authorization.strip_prefix("AgentAssertion ") { - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - proof - } else { - assert_eq!( - authorization, - format!("Bearer {}", mcp_actor_token("user-a")) - ); - request.headers["x-openai-agent-assertion"].to_str()? - }; - let claims: Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(proof.split('.').nth(2).unwrap())?, - )?; - let runtime = claims["runtime_agent_instance"].as_str().unwrap(); - assert!(matches!(runtime, "runtime-user-a" | "runtime-user-b")); - if !assertion_only { - assert_eq!(runtime, "runtime-user-a"); - } - let proof_id = claims["id"].as_str().unwrap(); - if path.ends_with("-redirect") { - assert!( - proof_ids.contains(proof_id), - "redirect preserves the request proof" - ); - } else { - assert!(proof_ids.insert(proof_id.to_owned())); - } - runtimes.insert(runtime.to_owned()); - if path == "/backend-api/ps/mcp" - && let Ok(body) = request.body_json::() - && body["method"] == "tools/call" - && body["params"]["name"] == CALENDAR_EXTRACT_TEXT_TOOL_NAME - { - assert_eq!( - body["params"]["arguments"]["file"]["file_id"], - "file-runtime" - ); - assert_eq!(assertion_only, uploaded_calls != 0); - assert_eq!( - runtime, - if uploaded_calls < 2 { - "runtime-user-a" - } else { - "runtime-user-b" - } - ); - uploaded_calls += 1; - } - } - assert_eq!(runtimes.len(), 2); - let rpc_calls: Vec<_> = requests - .iter() - .map(|request| { - let body = request.body_json::().unwrap_or_default(); - ( - request.url.path(), - body["method"].clone(), - body["params"]["name"].clone(), - ) - }) - .collect(); - assert_eq!( - uploaded_calls, 3, - "recorded RPC calls: {rpc_calls:?}; file control requests: {file_requests}" - ); - assert_eq!(file_requests, 12); - let redirected = other_origin.received_requests().await.unwrap(); - assert_eq!(redirected.len(), 3); - for request in redirected { - assert!( - !request.headers.contains_key("authorization"), - "cross-origin finalization must not receive authorization", - ); - assert!( - !request.headers.contains_key("x-openai-agent-assertion"), - "cross-origin finalization must not receive the runtime assertion", - ); - } - other_origin.verify().await; - server.verify().await; - Ok(()) -} - -fn mcp_actor_token(user: &str) -> String { - let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode( - json!({ - "iss": "https://auth.openai.com/", "session_id": format!("login-{user}"), - "https://api.openai.com/auth": {"user_id": user, "chatgpt_account_id": "account_id"}, - }) - .to_string(), - ); - format!("header.{claims}.signature") -} - -async fn exercise_mcp_uploads() -> Result<()> { - use core_test_support::apps_test_server::apps_enabled_builder; - let server = MockServer::start().await; - let actor = |user| { - CodexAuth::from_external_chatgpt_tokens( - &mcp_actor_token(user), - "account_id", - /*chatgpt_plan_type*/ None, - ) - .expect("valid test actor") - }; - let mut test = apps_enabled_builder("https://chatgpt.com") - .with_auth(actor("user-a")) - .with_config(|config| { - config.model_provider.base_url = Some("https://api.openai.com/v1".into()); - config.model_provider.env_http_headers = None; - core_test_support::apps_test_server::configure_search_capable_model(config); - config - .features - .enable(Feature::RuntimeAgentInstances) - .expect("enable runtime auth"); - }) - .with_workspace_setup(|cwd, fs| async move { - let report = core_test_support::test_codex::executor_path_uri(cwd.join("report.txt"))?; - fs.write_file( - &report, - b"report".to_vec(), - Default::default(), - /*sandbox*/ None, - ) - .await?; - Ok(()) - }) - .build_with_auto_env(&server) - .await?; - test.submit_turn_with_environments( - "Extract the report text with the app tool.", - Some(vec![test.executor_environment().selection().clone()]), - ) - .await?; - // A second thread uses the same actor and MCP manager but must not inherit dual-header auth. - let mut assertion_only = test.config.clone(); - assertion_only.runtime_auth_mode = RuntimeAuthMode::AssertionOnly; - let assertion_thread = test - .thread_manager - .start_thread(StartThreadOptions::new(assertion_only)) - .await?; - let thread_id = assertion_thread.thread_id; - test.codex = assertion_thread.thread; - test.submit_turn_with_environments( - "Extract the report text with the app tool.", - Some(vec![test.executor_environment().selection().clone()]), - ) - .await?; - let rollout = test.codex.rollout_path().context("saved thread")?; - test.codex.submit(Op::Shutdown).await?; - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::ShutdownComplete) - }) - .await; - test.thread_manager.remove_thread(&thread_id).await; - let context = test - .thread_store - .load_latest_model_context(codex_thread_store::LoadThreadHistoryParams { - thread_id, - include_archived: false, - }) - .await?; - let mut config = test.config.clone(); - config.runtime_auth_mode = RuntimeAuthMode::AssertionOnly; - let auth = codex_core::test_support::auth_manager_from_auth_with_home( - actor("user-b"), - test.codex_home_path().to_path_buf(), - ); - let resumed = test - .thread_manager - .resume_thread_with_history( - config, - InitialHistory::Resumed(ResumedHistory { - history_revision: None, - conversation_id: context.thread_id, - history: Arc::new(context.items), - rollout_path: Some(rollout), - }), - auth, - /*parent_trace*/ None, - ClientMcpExtensions::default(), - ) - .await?; - test.codex = resumed.thread; - test.submit_turn_with_environments( - "Extract the report text with the app tool.", - Some(vec![test.executor_environment().selection().clone()]), - ) - .await?; - // Custom MCP hosts use their own authentication, without ambient OpenAI credentials. - let external = MockServer::start().await; - let _apps = core_test_support::apps_test_server::AppsTestServer::mount(&external).await?; - let mut custom = test.config.clone(); - custom.chatgpt_base_url = external.uri(); - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - custom.runtime_auth_mode = mode; - let apps = - codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager( - &custom, - /*force_refetch*/ true, - test.thread_manager.environment_manager(), - test.codex.mcp_manager(), - ) - .await?; - assert!(apps.codex_apps_ready); - assert!(!apps.connectors.is_empty()); - } - let requests = external - .received_requests() - .await - .context("custom MCP destination should record requests")?; - assert!(requests.iter().any(|request| { - request - .body_json::() - .is_ok_and(|body| body["method"] == "tools/list") - })); - for request in requests { - assert!(!request.headers.contains_key("authorization")); - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - } - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn daybreak_requests_use_runtime_auth() -> Result<()> { - use core_test_support::stdio_server_bin; - skip_if_no_network!(Ok(())); - let original = mcp_actor_token("user-a"); - if std::env::var(PROBE_SERVER).is_ok() { - let actor = |token: &str| { - CodexAuth::from_external_chatgpt_tokens( - token, - "account_id", - /*chatgpt_plan_type*/ None, - ) - }; - let home = Arc::new(tempfile::TempDir::new()?); - let plugin = super::plugins::write_sample_plugin_manifest_and_config(&home); - std::fs::write( - plugin.join(".mcp.json"), - serde_json::to_vec(&json!({ - "mcpServers":{"sample":{"command":stdio_server_bin()?,"cwd":plugin, - "environment_id":"local","default_tools_approval_mode":"approve", - "env":{"MCP_TEST_DAYBREAK_READ_ONLY":"true"}}} - }))?, - )?; - let server = MockServer::start().await; - let test = test_codex() - .with_home(home) - .with_auth(actor(&original)?) - .with_config(|config| { - config.chatgpt_base_url = "https://chatgpt.com".into(); - config - .features - .enable(Feature::RuntimeAgentInstances) - .unwrap(); - config.features.disable(Feature::Apps).unwrap(); - }) - .build_with_remote_and_local_env(&server) - .await?; - core_test_support::wait_for_mcp_server(&test.codex, "sample").await?; - responses::mount_sse_sequence( - &server, - vec![ - responses::sse(vec![ - responses::ev_tool_search_call( - "search", - &json!({"query":"get_codex_security_daybreak_access"}), - ), - responses::ev_completed("response-1"), - ]), - responses::sse(vec![ - responses::ev_function_call_with_namespace( - "access", - "mcp__sample", - "get_codex_security_daybreak_access", - "{}", - ), - responses::ev_completed("response-2"), - ]), - responses::sse(vec![ - responses::ev_assistant_message("done", "done"), - responses::ev_completed("response-3"), - ]), - ], - ) - .await; - test.codex - .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { - text: "Call the sample Daybreak access tool".into(), - text_elements: Vec::new(), - }])) - .await?; - let event = wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::McpToolCallEnd(_)) - }) - .await; - let EventMsg::McpToolCallEnd(event) = event else { - unreachable!() - }; - assert!( - event.result.is_ok(), - "the authenticated tool call must succeed" - ); - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - test.codex.shutdown_and_wait().await?; - return Ok(()); - } - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/agent/register")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "runtime_agent_instance_id":"runtime-access", "agent_host_id":"host-a", - "actor":{"kind":"chatgpt","user_id":"user-a","account_id":"account_id"}, - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(method("GET")).and(path("/accounts/verified_access")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({"programs":[{ - "program":"cyber", "state":"active", "grants":[{"level":"tac1","source":"individual"}] - }]}))).expect(1).mount(&server).await; - run_harness_through_proxy( - &server, - "suite::runtime_auth::daybreak_requests_use_runtime_auth", - /*realtime_target*/ None, - ) - .await?; - let requests = server.received_requests().await.unwrap(); - let access: Vec<_> = requests - .iter() - .filter(|request| request.url.path() == "/accounts/verified_access") - .collect(); - let mut proofs = BTreeSet::new(); - for request in access { - assert_eq!( - request.headers["authorization"], - format!("Bearer {original}") - ); - assert_eq!(request.headers["chatgpt-account-id"], "account_id"); - let proof = request.headers["x-openai-agent-assertion"].to_str()?; - assert!(proofs.insert(proof.to_string())); - let payload: Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(proof.split('.').nth(2).unwrap())?, - )?; - assert_eq!(payload["runtime_agent_instance"], "runtime-access"); - } - server.verify().await; - Ok(()) -} diff --git a/codex-rs/core/tests/suite/runtime_auth_denials.rs b/codex-rs/core/tests/suite/runtime_auth_denials.rs deleted file mode 100644 index d6c8dfb6..00000000 --- a/codex-rs/core/tests/suite/runtime_auth_denials.rs +++ /dev/null @@ -1,215 +0,0 @@ -//! Check terminal runtime failures and credential recovery through complete turns. - -use anyhow::Result; -use base64::Engine; -use codex_core::TurnInputRequest; -use codex_features::Feature; -use codex_features::RuntimeAuthMode; -use codex_login::CodexAuth; -use codex_login::ExternalAuth; -use codex_login::ExternalAuthFuture; -use codex_login::ExternalAuthRefreshContext; -use codex_protocol::protocol::EventMsg; -use codex_protocol::protocol::Op; -use codex_protocol::user_input::UserInput; -use core_test_support::responses; -use core_test_support::runtime_auth::PROBE_SERVER; -use core_test_support::runtime_auth::run_harness_through_proxy; -use core_test_support::skip_if_no_network; -use core_test_support::test_codex::test_codex; -use core_test_support::wait_for_event; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use std::collections::BTreeSet; -use std::sync::Arc; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::body_string_contains; -use wiremock::matchers::method; -use wiremock::matchers::path; - -const TEST_NAME: &str = - "suite::runtime_auth_denials::turns_stop_on_runtime_denial_but_recover_ordinary_401"; -const CASES: [&str; 3] = ["revoked", "header-denial", "expired"]; -const MODES: [(&str, RuntimeAuthMode); 2] = [ - ("dual", RuntimeAuthMode::DualHeader), - ("assertion", RuntimeAuthMode::AssertionOnly), -]; - -#[derive(Default)] -struct Credentials { - refreshes: AtomicUsize, -} - -impl ExternalAuth for Credentials { - fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> { - Box::pin(async { Ok(CodexAuth::from_api_key("key-a")) }) - } - - fn refresh(&self, _: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> { - self.refreshes.fetch_add(1, Ordering::SeqCst); - self.resolve() - } -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn turns_stop_on_runtime_denial_but_recover_ordinary_401() -> Result<()> { - skip_if_no_network!(Ok(())); - if std::env::var_os(PROBE_SERVER).is_some() { - return exercise_turns().await; - } - - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/agent/register")) - .respond_with(|request: &wiremock::Request| { - ResponseTemplate::new(200).set_body_json(json!({ - "runtime_agent_instance_id": request.headers["idempotency-key"].to_str().unwrap(), - "agent_host_id": "host-a", - "actor": {"kind": "platform", "user_id": "user-a", - "organization_id": "org-a", "project_id": null}, - })) - }) - .expect(6) - .mount(&server) - .await; - for (mode, _) in MODES { - for case in CASES { - let label = format!("{mode}-{case}"); - let denial = match case { - "revoked" => ResponseTemplate::new(403).set_body_json(json!({ - "error": {"code": "runtime_instance_revoked", "message": "Runtime revoked"} - })), - "header-denial" => ResponseTemplate::new(401) - .insert_header( - "x-error-json", - base64::engine::general_purpose::STANDARD - .encode(br#"{"error":{"code":"invalid_agent_instance_assertion"}}"#), - ) - .set_body_json(json!({"error": {"message": "Runtime rejected"}})), - _ => ResponseTemplate::new(401).set_body_json(json!({ - "error": {"code": "token_expired", "message": "Credential expired"} - })), - }; - Mock::given(method("POST")) - .and(path("/v1/responses")) - .and(body_string_contains(label.clone())) - .respond_with(denial) - .with_priority(1) - .up_to_n_times(1) - .expect(1) - .mount(&server) - .await; - // A mistaken retry would complete the turn, making either denial assertion fail. - Mock::given(method("POST")) - .and(path("/v1/responses")) - .and(body_string_contains(label)) - .respond_with( - ResponseTemplate::new(200) - .insert_header("content-type", "text/event-stream") - .set_body_string(responses::sse_completed("completed")), - ) - .with_priority(2) - .expect(u64::from(case == "expired")) - .mount(&server) - .await; - } - } - - run_harness_through_proxy(&server, TEST_NAME, /*realtime_target*/ None).await?; - let mut proof_ids = BTreeSet::new(); - let requests = server.received_requests().await.unwrap(); - let attempts: Vec<_> = requests - .iter() - .filter(|request| request.url.path() == "/v1/responses") - .collect(); - assert_eq!(attempts.len(), 8); - for request in attempts { - let authorization = request.headers["authorization"].to_str()?; - let proof = if let Some(proof) = authorization.strip_prefix("AgentAssertion ") { - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - proof - } else { - assert_eq!(authorization, "Bearer key-a"); - request.headers["x-openai-agent-assertion"].to_str()? - }; - let payload: Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(proof.split('.').nth(2).unwrap())?, - )?; - assert!(proof_ids.insert(payload["id"].as_str().unwrap().to_owned())); - } - server.verify().await; - Ok(()) -} - -async fn exercise_turns() -> Result<()> { - let server = MockServer::start().await; - for (mode_label, mode) in MODES { - for case in CASES { - let test = test_codex() - .with_auth(CodexAuth::from_api_key("key-a")) - .with_config(move |config| { - config.model_provider.base_url = Some("https://api.openai.com/v1".into()); - config.model_provider.env_http_headers = None; - config.model_provider.supports_websockets = false; - config.model_provider.request_max_retries = Some(2); - config.model_provider.stream_max_retries = Some(2); - config - .features - .enable(Feature::RuntimeAgentInstances) - .expect("enable runtime agent instances"); - config.runtime_auth_mode = mode; - config.model_catalog = Some( - codex_models_manager::bundled_models_response() - .expect("load bundled models"), - ); - }) - .build_with_auto_env(&server) - .await?; - let credentials = Arc::new(Credentials::default()); - test.thread_manager - .auth_manager() - .set_external_auth(credentials.clone()) - .await?; - test.codex - .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { - text: format!("{mode_label}-{case}"), - text_elements: Vec::new(), - }])) - .await?; - let mut errors = Vec::new(); - let mut stream_retries = 0; - wait_for_event(&test.codex, |event| { - match event { - EventMsg::Error(error) => errors.push(error.message.clone()), - EventMsg::StreamError(_) => stream_retries += 1, - _ => {} - } - matches!(event, EventMsg::TurnComplete(_)) - }) - .await; - assert_eq!( - errors.len(), - usize::from(case != "expired"), - "{mode_label}-{case}" - ); - assert_eq!(stream_retries, 0, "{mode_label}-{case}"); - assert_eq!( - credentials.refreshes.load(Ordering::SeqCst), - usize::from(case == "expired"), - "{mode_label}-{case}" - ); - test.codex.submit(Op::Shutdown).await?; - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::ShutdownComplete) - }) - .await; - } - } - Ok(()) -} diff --git a/codex-rs/exec-server-cli/Cargo.toml b/codex-rs/exec-server-cli/Cargo.toml index 1743ee52..6d0c3e3b 100644 --- a/codex-rs/exec-server-cli/Cargo.toml +++ b/codex-rs/exec-server-cli/Cargo.toml @@ -22,7 +22,6 @@ codex-app-server = { workspace = true } codex-arg0 = { workspace = true } codex-aws-auth = { workspace = true } codex-build-info = { workspace = true } -codex-cloud-config = { workspace = true } codex-config = { workspace = true } codex-core = { workspace = true } codex-exec-server = { workspace = true } diff --git a/codex-rs/exec-server-cli/src/command.rs b/codex-rs/exec-server-cli/src/command.rs index 0615a2c9..9a4b4687 100644 --- a/codex-rs/exec-server-cli/src/command.rs +++ b/codex-rs/exec-server-cli/src/command.rs @@ -189,7 +189,6 @@ impl ExecServerCommand { ) -> anyhow::Result<()> { let strict_config = self.strict_config; self.validate_remote_transport()?; - let enable_cloud_config = self.should_load_cloud_config(); let websocket_auth = self.websocket_auth.try_into_settings()?; if websocket_auth.config.is_some() && (self.remote.is_some() || self.command.is_some()) { anyhow::bail!("WebSocket listener auth cannot be used with --remote or forward"); @@ -231,7 +230,6 @@ impl ExecServerCommand { let config = load_exec_server_config( root_config_overrides, strict_config, - enable_cloud_config, stdin_auth.as_ref(), ); let mut parent_lifetime = if self.exit_on_stdin_close && stdin_auth.is_some() { @@ -356,7 +354,6 @@ impl ExecServerCommand { let config_result = load_exec_server_config( root_config_overrides, strict_config, - enable_cloud_config, /*stdin_auth*/ None, ) .await; @@ -398,15 +395,6 @@ impl ExecServerCommand { } } - fn should_load_cloud_config(&self) -> bool { - self.remote.is_some() - && self.command.is_none() - && !self.executor_credential_stdin - && !self.registration_bearer_stdin - && !self.aws_sigv4 - && !self.use_agent_identity_auth - } - fn validate_remote_transport(&self) -> anyhow::Result<()> { // Clap checks global flag conflicts separately on either side of `forward`. if self.registration_bearer_stdin && self.executor_credential_stdin { diff --git a/codex-rs/exec-server-cli/src/config.rs b/codex-rs/exec-server-cli/src/config.rs index 464d8bda..c5125c41 100644 --- a/codex-rs/exec-server-cli/src/config.rs +++ b/codex-rs/exec-server-cli/src/config.rs @@ -2,8 +2,6 @@ use anyhow::Context; use codex_app_server::in_process::EmbeddedNetworkPolicy; -use codex_cloud_config::chatgpt_config_bundle_loader; -use codex_cloud_config::managed_config_bundle_loader_for_auth; use codex_config::LoaderOverrides; use codex_core::config::ConfigBuilder; use codex_core::config::ConfigLoadOptions; @@ -178,66 +176,14 @@ pub(super) fn validate_api_key_remote_host(base_url: &str) -> anyhow::Result<()> pub(super) async fn load_exec_server_config( root_config_overrides: &CliConfigOverrides, strict_config: bool, - enable_cloud_config: bool, stdin_auth: Option<&CodexAuth>, ) -> anyhow::Result { let cli_kv_overrides = root_config_overrides .parse_overrides() .map_err(anyhow::Error::msg)?; - let bootstrap_cli_overrides = cli_kv_overrides.clone(); - let mut builder = ConfigBuilder::default() + let builder = ConfigBuilder::default() .cli_overrides(cli_kv_overrides) .strict_config(strict_config); - if enable_cloud_config { - let codex_home = find_codex_home()?; - let loader_overrides = LoaderOverrides::default(); - let network_policy = EmbeddedNetworkPolicy::load(&loader_overrides).await; - let bootstrap_cwd = AbsolutePathBuf::current_dir()?; - let bootstrap_config = load_config_toml_with_layer_stack( - &codex_home, - Some(&bootstrap_cwd), - bootstrap_cli_overrides, - ConfigLoadOptions { - loader_overrides, - strict_config, - cloud_config_bundle: Default::default(), - }, - ) - .await?; - let bootstrap_auth_config = network_policy - .bind_bootstrap_auth(bootstrap_auth_config(&codex_home, &bootstrap_config)?); - let cloud_config_bundle = if let Some(auth) = stdin_auth { - anyhow::ensure!( - bootstrap_auth_config.allows_auth(auth), - "ChatGPT authentication is not permitted for this account" - ); - managed_config_bundle_loader_for_auth( - bootstrap_auth_config, - auth, - bootstrap_config.config_layer_stack.requirements_toml(), - ) - .await? - } else { - let auth_manager = AuthManager::shared_from_auth_config_with_auth_modes( - bootstrap_auth_config.clone(), - /*enable_codex_api_key_env*/ true, - REMOTE_AUTH_MODES.to_vec(), - ) - .await?; - chatgpt_config_bundle_loader( - auth_manager, - bootstrap_auth_config - .chatgpt_base_url - .unwrap_or_else(|| "https://chatgpt.com/backend-api/".to_string()), - bootstrap_auth_config.codex_home, - bootstrap_auth_config - .auth_route_config - .http_client_factory() - .clone(), - ) - }; - builder = builder.cloud_config_bundle(cloud_config_bundle); - } let mut config = builder.build().await?; if stdin_auth.is_some() { config.config_layer_stack.ensure_config_server_applied()?; diff --git a/codex-rs/exec-server-cli/src/exec_server_args_tests.rs b/codex-rs/exec-server-cli/src/exec_server_args_tests.rs index d000825a..2ec655dc 100644 --- a/codex-rs/exec-server-cli/src/exec_server_args_tests.rs +++ b/codex-rs/exec-server-cli/src/exec_server_args_tests.rs @@ -49,7 +49,7 @@ fn exec_server_defaults_preserve_local_and_noise_modes() { } #[test] -fn remote_forwarder_skips_cloud_config() { +fn remote_forwarder_rejects_chatgpt_token_stdin() { let mut command = exec_server_from_args(&[ "forward", "--connect", @@ -59,7 +59,6 @@ fn remote_forwarder_skips_cloud_config() { "--environment-id", "env-1", ]); - assert!(!command.should_load_cloud_config()); command.chatgpt_token_stdin = true; assert!(command.validate_remote_transport().is_err()); } @@ -98,8 +97,7 @@ fn exec_server_parses_direct_aws_options() { ); assert_eq!(command.environment_id.as_deref(), Some("env-1")); assert_eq!(command.remote_transport, ExecServerRemoteTransport::Direct); - assert!(!command.should_load_cloud_config()); - assert!(command.aws_sigv4); + assert!(command.aws_sigv4); assert_eq!( ( command.aws_profile.as_deref(), diff --git a/codex-rs/exec/Cargo.toml b/codex-rs/exec/Cargo.toml index c4bd6e49..caa024b1 100644 --- a/codex-rs/exec/Cargo.toml +++ b/codex-rs/exec/Cargo.toml @@ -27,7 +27,6 @@ clap = { workspace = true, features = ["derive"] } codex-arg0 = { workspace = true } codex-app-server-client = { workspace = true } codex-app-server-protocol = { workspace = true } -codex-cloud-config = { workspace = true } codex-config = { workspace = true } codex-core = { workspace = true } codex-exec-server = { workspace = true } diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 827eb2be..9ec793b3 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -62,7 +62,6 @@ use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::TurnStartedNotification; use codex_arg0::Arg0DispatchPaths; -use codex_cloud_config::managed_config_bundle_loader_for_storage; use codex_config::CloudConfigBundleLoader; use codex_config::ConfigLoadError; use codex_config::ConfigLoadOptions; @@ -74,7 +73,6 @@ use codex_core::config::Config; use codex_core::config::ConfigBuilder; use codex_core::config::ConfigOverrides; use codex_core::config::ConfigTomlLoadResult; -use codex_core::config::bootstrap_auth_config; use codex_core::config::edit::ConfigEditsBuilder; use codex_core::config::find_codex_home; use codex_core::config::load_config_toml_with_layer_stack; @@ -411,22 +409,7 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result let managed_worktree = if worktree { let embedded_network_policy = codex_app_server_client::EmbeddedNetworkPolicy::load(&loader_overrides).await; - let gate_bootstrap = load_bootstrap_config_or_exit( - &codex_home, - /*cwd*/ None, - cli_kv_overrides.clone(), - loader_overrides.clone(), - strict_config, - CloudConfigBundleLoader::default(), - ) - .await; - let gate_cloud_config = managed_config_bundle_loader_for_storage( - embedded_network_policy - .bind_bootstrap_auth(bootstrap_auth_config(&codex_home, &gate_bootstrap)?), - gate_bootstrap.config_layer_stack.requirements_toml(), - /*enable_codex_api_key_env*/ false, - ) - .await?; + let gate_cloud_config = CloudConfigBundleLoader::default(); let gate_config = ConfigBuilder::default() .codex_home(codex_home.to_path_buf()) .cli_overrides(cli_kv_overrides.clone()) @@ -516,17 +499,8 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result ) .await; let bootstrap_config_toml = &bootstrap_config.config_toml; - let bootstrap_auth_config = embedded_network_policy - .bind_bootstrap_auth(bootstrap_auth_config(&codex_home, &bootstrap_config)?); - // API keys cannot fetch workspace-managed configuration. Preserve the - // existing ChatGPT bootstrap identity even when model requests allow - // CODEX_API_KEY. - let cloud_config_bundle = managed_config_bundle_loader_for_storage( - bootstrap_auth_config, - bootstrap_config.config_layer_stack.requirements_toml(), - /*enable_codex_api_key_env*/ false, - ) - .await?; + // aKode only loads local configuration; managed bundles are never fetched remotely. + let cloud_config_bundle = CloudConfigBundleLoader::default(); if let Some(worktree) = managed_worktree.as_ref() { // Destination auth can fetch source policy that the host bootstrap could not. let source_config = ConfigBuilder::default() diff --git a/codex-rs/ext/connectors/BUILD.bazel b/codex-rs/ext/connectors/BUILD.bazel deleted file mode 100644 index 304349b8..00000000 --- a/codex-rs/ext/connectors/BUILD.bazel +++ /dev/null @@ -1,6 +0,0 @@ -load("//:defs.bzl", "codex_rust_crate") - -codex_rust_crate( - name = "connectors", - crate_name = "codex_connectors_extension", -) diff --git a/codex-rs/ext/connectors/Cargo.toml b/codex-rs/ext/connectors/Cargo.toml deleted file mode 100644 index 1aead727..00000000 --- a/codex-rs/ext/connectors/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -[package] -edition.workspace = true -license.workspace = true -name = "codex-connectors-extension" -version.workspace = true - -[lib] -name = "codex_connectors_extension" -path = "src/lib.rs" -doctest = false -test = false - -[lints] -workspace = true - -[dependencies] -codex-connectors = { workspace = true } -codex-core-plugins = { workspace = true } -codex-file-system = { workspace = true } -codex-plugin = { workspace = true } -codex-utils-path-uri = { workspace = true } -serde_json = { workspace = true } -thiserror = { workspace = true } -tracing = { workspace = true } diff --git a/codex-rs/ext/connectors/src/lib.rs b/codex-rs/ext/connectors/src/lib.rs deleted file mode 100644 index 5d8528b2..00000000 --- a/codex-rs/ext/connectors/src/lib.rs +++ /dev/null @@ -1,6 +0,0 @@ -//! Plugin app declaration loading. - -mod plugin_app; - -pub use plugin_app::PluginAppProvider; -pub use plugin_app::PluginAppProviderError; diff --git a/codex-rs/ext/connectors/src/plugin_app.rs b/codex-rs/ext/connectors/src/plugin_app.rs deleted file mode 100644 index a82486a8..00000000 --- a/codex-rs/ext/connectors/src/plugin_app.rs +++ /dev/null @@ -1,68 +0,0 @@ -use codex_connectors::parse_plugin_app_config; -use codex_core_plugins::ResolvedExecutorPlugin; -use codex_file_system::ReadFileOptions; -use codex_plugin::AppDeclaration; -use codex_plugin::PluginResourceLocator; -use codex_utils_path_uri::PathUri; -use std::io; -use thiserror::Error; - -/// Loads app declarations from a resolved plugin. -#[derive(Clone, Copy, Debug, Default)] -pub struct PluginAppProvider; - -/// Failure to load app declarations from a plugin. -#[derive(Debug, Error)] -pub enum PluginAppProviderError { - #[error("failed to read app config for selected plugin `{plugin_id}` at `{path}`: {source}")] - ReadConfig { - plugin_id: String, - path: PathUri, - #[source] - source: io::Error, - }, - #[error("failed to parse app config for selected plugin `{plugin_id}` at `{path}`: {source}")] - ParseConfig { - plugin_id: String, - path: PathUri, - #[source] - source: serde_json::Error, - }, -} - -impl PluginAppProvider { - /// Returns the app declarations contributed by `plugin`. - #[tracing::instrument(name = "connectors.plugin.declarations.load", skip_all)] - pub async fn load( - &self, - plugin: &ResolvedExecutorPlugin, - ) -> Result, PluginAppProviderError> { - let resolved_plugin = plugin.plugin(); - let plugin_id = resolved_plugin.selected_root_id(); - let Some(PluginResourceLocator::Environment { - path: config_path, .. - }) = resolved_plugin.manifest().paths.apps.as_ref() - else { - return Ok(Vec::new()); - }; - let contents = plugin - .file_system() - .read_file_text( - config_path, - ReadFileOptions::default(), - /*sandbox*/ None, - ) - .await - .map_err(|source| PluginAppProviderError::ReadConfig { - plugin_id: plugin_id.to_string(), - path: config_path.clone(), - source, - })?; - - parse_plugin_app_config(&contents).map_err(|source| PluginAppProviderError::ParseConfig { - plugin_id: plugin_id.to_string(), - path: config_path.clone(), - source, - }) - } -} diff --git a/codex-rs/ext/git-attribution/Cargo.toml b/codex-rs/ext/git-attribution/Cargo.toml index cd154449..3f83f3b0 100644 --- a/codex-rs/ext/git-attribution/Cargo.toml +++ b/codex-rs/ext/git-attribution/Cargo.toml @@ -13,16 +13,5 @@ doctest = false workspace = true [dependencies] -codex-backend-client = { workspace = true } codex-extension-api = { workspace = true } -codex-features = { workspace = true } -codex-http-client = { workspace = true } -codex-login = { workspace = true } -codex-model-provider = { workspace = true } -codex-runtime-agent-instance = { workspace = true } serde_json = { workspace = true } -tokio = { workspace = true, features = ["time"] } - -[dev-dependencies] -tokio = { workspace = true, features = ["macros", "rt"] } -wiremock = { workspace = true } diff --git a/codex-rs/ext/git-attribution/src/git_attribution_tests.rs b/codex-rs/ext/git-attribution/src/git_attribution_tests.rs deleted file mode 100644 index 38b03460..00000000 --- a/codex-rs/ext/git-attribution/src/git_attribution_tests.rs +++ /dev/null @@ -1,236 +0,0 @@ -use std::sync::Arc; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; -use std::time::Duration; - -use codex_http_client::HttpClientFactory; -use codex_http_client::OutboundProxyPolicy; -use codex_login::AuthManager; -use codex_login::CodexAuth; -use codex_login::ExternalAuth; -use codex_login::ExternalAuthFuture; -use codex_login::ExternalAuthRefreshContext; -use tokio::sync::Notify; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; - -use super::policy::resolve_attribution_policy; - -fn enterprise_auth_manager() -> Arc { - AuthManager::from_auth_for_testing(enterprise_auth("workspace-123")) -} - -fn http_client_factory() -> HttpClientFactory { - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault) -} - -fn enterprise_auth(account_id: &str) -> CodexAuth { - CodexAuth::from_external_chatgpt_tokens("e30.e30.c2ln", account_id, Some("enterprise")) - .expect("fake ChatGPT auth should parse") -} - -struct StaticExternalAuth(CodexAuth); - -impl ExternalAuth for StaticExternalAuth { - fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> { - Box::pin(async { Ok(self.0.clone()) }) - } - - fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> { - self.resolve() - } -} - -async fn set_auth(auth_manager: &AuthManager, account_id: &str) { - auth_manager - .set_external_auth(Arc::new(StaticExternalAuth(enterprise_auth(account_id)))) - .await - .expect("auth refresh should succeed"); -} - -#[tokio::test] -async fn policy_resolution_recovers_after_unauthorized() { - let server = MockServer::start().await; - let request_count = Arc::new(AtomicUsize::new(0)); - Mock::given(method("GET")) - .and(path("/backend-api/wham/settings/user")) - .respond_with({ - let request_count = request_count.clone(); - move |_request: &wiremock::Request| { - if request_count.fetch_add(1, Ordering::SeqCst) == 0 { - ResponseTemplate::new(401) - } else { - ResponseTemplate::new(200) - .set_body_json(serde_json::json!({"commit_attribution_enabled": true})) - } - } - }) - .expect(2) - .mount(&server) - .await; - let auth_manager = enterprise_auth_manager(); - set_auth(auth_manager.as_ref(), "workspace-123").await; - - let policy = resolve_attribution_policy( - &auth_manager, - &format!("{}/backend-api", server.uri()), - &http_client_factory(), - /*runtime_auth*/ None, - ) - .await - .expect("policy resolution should not time out") - .expect("policy should resolve after auth recovery"); - - assert!(policy.enabled); - assert_eq!(request_count.load(Ordering::SeqCst), 2); - server.verify().await; -} - -#[tokio::test] -async fn policy_resolution_retries_after_auth_refresh() { - let server = MockServer::start().await; - let request_started = Arc::new(Notify::new()); - let request_count = Arc::new(AtomicUsize::new(0)); - Mock::given(method("GET")) - .and(path("/backend-api/wham/settings/user")) - .respond_with({ - let request_started = request_started.clone(); - let request_count = request_count.clone(); - move |_request: &wiremock::Request| match request_count.fetch_add(1, Ordering::SeqCst) { - 0 => { - request_started.notify_one(); - ResponseTemplate::new(200) - .set_delay(Duration::from_millis(100)) - .set_body_json(serde_json::json!({ - "commit_attribution_enabled": true, - })) - } - 1 => ResponseTemplate::new(401), - _ => ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "commit_attribution_enabled": true, - })), - } - }) - .expect(3) - .mount(&server) - .await; - let auth_manager = enterprise_auth_manager(); - let resolve = tokio::spawn({ - let auth_manager = auth_manager.clone(); - let base_url = format!("{}/backend-api", server.uri()); - async move { - resolve_attribution_policy( - &auth_manager, - &base_url, - &http_client_factory(), - /*runtime_auth*/ None, - ) - .await - .ok() - .flatten() - } - }); - - tokio::time::timeout(Duration::from_secs(5), request_started.notified()) - .await - .expect("first settings request should start"); - set_auth(auth_manager.as_ref(), "workspace-456").await; - - assert!( - resolve - .await - .expect("policy task should complete") - .expect("policy should resolve after refresh") - .enabled - ); - server.verify().await; -} - -struct RotatingExternalAuth(AtomicUsize); - -impl ExternalAuth for RotatingExternalAuth { - fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> { - Box::pin(async { - let generation = self.0.load(Ordering::SeqCst); - CodexAuth::from_external_chatgpt_tokens( - &format!("e30.e30.signature-{generation}"), - "workspace-123", - Some("enterprise"), - ) - }) - } - - fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> { - self.0.fetch_add(/*val*/ 1, Ordering::SeqCst); - self.resolve() - } -} - -#[tokio::test] -async fn world_state_stops_after_rejected_refresh() { - use codex_extension_api::ContextContributor; - use codex_extension_api::ExtensionData; - use codex_extension_api::PreviousWorldStateSection; - use codex_extension_api::WorldStateContributionInput; - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/settings/user")) - .respond_with(ResponseTemplate::new(401)) - .expect(2) - .mount(&server) - .await; - let source = Arc::new(RotatingExternalAuth(AtomicUsize::new(/*v*/ 0))); - let auth_manager = enterprise_auth_manager(); - auth_manager - .set_external_auth(source.clone()) - .await - .expect("external credentials should load"); - let extension = super::GitAttributionExtension { - auth_manager, - base_url: format!("{}/backend-api", server.uri()), - http_client_factory: http_client_factory(), - }; - let model_info = serde_json::from_value(serde_json::json!({ - "slug": "test-model", - "display_name": "Test model", - "supported_reasoning_levels": [], - "shell_type": "shell_command", - "visibility": "list", - "supported_in_api": true, - "priority": 0, - "support_verbosity": false, - "truncation_policy": {"mode": "bytes", "limit": 10000}, - "experimental_supported_tools": [] - })) - .expect("model metadata should parse"); - let store = ExtensionData::new("test"); - let sections = tokio::time::timeout( - Duration::from_secs(2), - extension.contribute_world_state(WorldStateContributionInput { - thread_id: Default::default(), - turn_id: "turn", - model_info: &model_info, - environments: &[], - extension_metrics: None, - session_store: &store, - thread_store: &store, - turn_store: &store, - step_store: &store, - previous_world_state: None, - }), - ) - .await - .expect("an optional settings failure must not keep refreshing credentials"); - assert_eq!(source.0.load(Ordering::SeqCst), 1); - assert!(sections.iter().all(|section| { - section - .render_diff(PreviousWorldStateSection::Absent) - .1 - .is_none() - })); - server.verify().await; -} diff --git a/codex-rs/ext/git-attribution/src/lib.rs b/codex-rs/ext/git-attribution/src/lib.rs index e2067669..98217d10 100644 --- a/codex-rs/ext/git-attribution/src/lib.rs +++ b/codex-rs/ext/git-attribution/src/lib.rs @@ -1,118 +1,38 @@ -mod policy; mod world_state; use std::sync::Arc; -use std::time::Instant; use codex_extension_api::ContextContributor; use codex_extension_api::ExtensionFuture; use codex_extension_api::ExtensionRegistryBuilder; use codex_extension_api::WorldStateContributionInput; use codex_extension_api::WorldStateSectionContribution; -use codex_http_client::HttpClientFactory; -use codex_login::AuthManager; -use codex_model_provider::ProviderAuthContext; -use crate::policy::GitAttributionPolicy; -use crate::policy::GitAttributionRetry; -use crate::policy::POLICY_RETRY_DELAY; -use crate::policy::auth_generation; -use crate::policy::cached_attribution_policy; -use crate::policy::resolve_attribution_policy; -use crate::policy::retry_deferred; use crate::world_state::git_attribution_world_state_section; +/// Local default for commit and pull request attribution. aKode never fetches a +/// remote workspace policy, so attribution stays disabled. +const ATTRIBUTION_ENABLED_BY_DEFAULT: bool = false; + /// Contributes model instructions for agent-created git commits and pull requests. #[derive(Clone)] struct GitAttributionExtension { - auth_manager: Arc, - base_url: String, - http_client_factory: HttpClientFactory, + enabled: bool, } impl ContextContributor for GitAttributionExtension { fn contribute_world_state<'a>( &'a self, - input: WorldStateContributionInput<'a>, + _input: WorldStateContributionInput<'a>, ) -> ExtensionFuture<'a, Vec> { - Box::pin(async move { - let auth_context = input.thread_store.get::(); - let auth_manager = auth_context - .as_ref() - .map_or(&self.auth_manager, |context| &context.credentials); - let runtime_auth = auth_context - .as_ref() - .and_then(|context| context.runtime_auth.as_ref()); - let enabled = loop { - let current_auth_generation = auth_generation(auth_manager.as_ref()); - let policy = match cached_attribution_policy( - input.thread_store, - input.turn_store, - current_auth_generation, - ) { - Some(policy) => policy, - None if retry_deferred(input.thread_store, current_auth_generation) => { - GitAttributionPolicy { - auth_generation: current_auth_generation, - enabled: false, - } - } - None => { - match resolve_attribution_policy( - auth_manager, - &self.base_url, - &self.http_client_factory, - runtime_auth, - ) - .await - { - Ok(Some(policy)) => { - input.thread_store.insert(policy.clone()); - policy - } - Ok(None) => { - input.turn_store.insert(GitAttributionPolicy { - auth_generation: current_auth_generation, - enabled: false, - }); - break false; - } - Err(_) => { - let auth_generation = auth_generation(auth_manager.as_ref()); - if auth_generation == current_auth_generation { - input.thread_store.insert(GitAttributionRetry { - auth_generation, - retry_at: Instant::now() + POLICY_RETRY_DELAY, - }); - } - break false; - } - } - } - }; - if policy.auth_generation == auth_generation(auth_manager.as_ref()) { - break policy.enabled; - } - }; - vec![git_attribution_world_state_section(enabled)] - }) + let enabled = self.enabled; + Box::pin(async move { vec![git_attribution_world_state_section(enabled)] }) } } /// Installs the git-attribution contributor into the extension registry. -pub fn install( - registry: &mut ExtensionRegistryBuilder, - auth_manager: Arc, - base_url: String, - http_client_factory: HttpClientFactory, -) { +pub fn install(registry: &mut ExtensionRegistryBuilder) { registry.prompt_contributor(Arc::new(GitAttributionExtension { - auth_manager, - base_url, - http_client_factory, + enabled: ATTRIBUTION_ENABLED_BY_DEFAULT, })); } - -#[cfg(test)] -#[path = "git_attribution_tests.rs"] -mod tests; diff --git a/codex-rs/ext/git-attribution/src/policy.rs b/codex-rs/ext/git-attribution/src/policy.rs deleted file mode 100644 index df756820..00000000 --- a/codex-rs/ext/git-attribution/src/policy.rs +++ /dev/null @@ -1,122 +0,0 @@ -use std::sync::Arc; -use std::time::Duration; -use std::time::Instant; - -use codex_backend_client::Client as BackendClient; -use codex_extension_api::ExtensionData; -use codex_features::RuntimeAuthMode; -use codex_http_client::HttpClientFactory; -use codex_login::AuthManager; -use codex_runtime_agent_instance::RuntimeAuthManager; -use tokio::time::timeout; - -#[derive(Clone, Debug)] -pub(super) struct GitAttributionPolicy { - pub(super) auth_generation: u64, - pub(super) enabled: bool, -} - -pub(super) struct GitAttributionRetry { - pub(super) auth_generation: u64, - pub(super) retry_at: Instant, -} - -pub(super) fn retry_deferred(thread_store: &ExtensionData, auth_generation: u64) -> bool { - thread_store - .get::() - .is_some_and(|retry| { - retry.auth_generation == auth_generation && retry.retry_at > Instant::now() - }) -} - -pub(super) fn cached_attribution_policy( - thread_store: &ExtensionData, - turn_store: &ExtensionData, - auth_generation: u64, -) -> Option { - thread_store - .get::() - .filter(|policy| policy.auth_generation == auth_generation) - .or_else(|| { - turn_store - .get::() - .filter(|policy| policy.auth_generation == auth_generation) - }) - .map(|policy| policy.as_ref().clone()) -} - -#[cfg(not(test))] -const POLICY_RESOLUTION_TIMEOUT: Duration = Duration::from_secs(5); -#[cfg(test)] -const POLICY_RESOLUTION_TIMEOUT: Duration = Duration::from_millis(500); -pub(super) const POLICY_RETRY_DELAY: Duration = Duration::from_secs(30); - -pub(super) async fn resolve_attribution_policy( - auth_manager: &Arc, - base_url: &str, - http_client_factory: &HttpClientFactory, - runtime_auth: Option<&(Arc, RuntimeAuthMode)>, -) -> Result, tokio::time::error::Elapsed> { - timeout(POLICY_RESOLUTION_TIMEOUT, async { - let mut recovery_generation = auth_generation(auth_manager); - let mut auth_recovery = auth_manager.unauthorized_recovery(); - loop { - let auth_generation_at_start = auth_generation(auth_manager); - if auth_generation_at_start != recovery_generation { - auth_recovery = auth_manager.unauthorized_recovery(); - recovery_generation = auth_generation_at_start; - } - let auth = auth_manager.auth_with_http_client_factory().await; - if auth_generation(auth_manager) != auth_generation_at_start { - continue; - } - let enabled = match auth { - Some((auth, captured_factory)) if auth.uses_codex_backend() => { - let policy = http_client_factory - .network_policy() - .clone() - .with_account_binding(captured_factory.network_policy())?; - let client = BackendClient::from_auth_with_runtime( - base_url, - &auth, - http_client_factory.clone().with_network_policy(policy), - runtime_auth, - /*headers*/ &Default::default(), - ) - .await; - if auth_generation(auth_manager) != auth_generation_at_start { - continue; - } - let settings = client.ok()?.get_user_settings().await; - if auth_generation(auth_manager) != auth_generation_at_start { - continue; - } - match settings { - Ok(settings) => Some(settings.commit_attribution_enabled), - Err(err) if err.is_unauthorized() && auth_recovery.has_next() => { - if auth_recovery.next().await.is_ok() { - recovery_generation = auth_generation(auth_manager); - continue; - } - None - } - Err(_) => None, - } - } - Some(_) | None => Some(false), - }; - if auth_generation(auth_manager) != auth_generation_at_start { - continue; - } - return enabled.map(|enabled| GitAttributionPolicy { - auth_generation: auth_generation_at_start, - enabled, - }); - } - }) - .await -} - -pub(super) fn auth_generation(auth_manager: &AuthManager) -> u64 { - *auth_manager.auth_change_receiver().borrow() -} diff --git a/codex-rs/ext/mcp/Cargo.toml b/codex-rs/ext/mcp/Cargo.toml index a30517a3..71de4569 100644 --- a/codex-rs/ext/mcp/Cargo.toml +++ b/codex-rs/ext/mcp/Cargo.toml @@ -18,7 +18,6 @@ codex-core = { workspace = true } codex-core-plugins = { workspace = true } codex-config = { workspace = true } codex-connectors = { workspace = true } -codex-connectors-extension = { workspace = true } codex-exec-server = { workspace = true } codex-extension-api = { workspace = true } codex-features = { workspace = true } diff --git a/codex-rs/ext/mcp/src/lib.rs b/codex-rs/ext/mcp/src/lib.rs index 9418f490..af274ee6 100644 --- a/codex-rs/ext/mcp/src/lib.rs +++ b/codex-rs/ext/mcp/src/lib.rs @@ -1,12 +1,3 @@ -use codex_core::config::Config; -use codex_extension_api::ExtensionFuture; -use codex_extension_api::ExtensionRegistryBuilder; -use codex_extension_api::McpServerContribution; -use codex_extension_api::McpServerContributionContext; -use codex_extension_api::McpServerContributor; -use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; -use codex_mcp::hosted_plugin_runtime_mcp_server_config; - mod catalog_observability; mod cloud_plugin; mod plugin; @@ -27,40 +18,3 @@ pub use plugin_providers::PluginProviders; pub use stream_manager::McpEventStreamManager; pub use stream_manager::McpEventStreamUpdate; -struct HostedPluginRuntimeExtension; - -impl McpServerContributor for HostedPluginRuntimeExtension { - fn id(&self) -> &'static str { - "hosted_plugin_runtime" - } - - fn contribute<'a>( - &'a self, - context: McpServerContributionContext<'a, Config>, - ) -> ExtensionFuture<'a, Vec> { - Box::pin(async move { - let config = context.config(); - let name = CODEX_APPS_MCP_SERVER_NAME.to_string(); - if !config.features.enabled(codex_features::Feature::Apps) { - return vec![McpServerContribution::Remove { name }]; - } - - vec![McpServerContribution::HostedApps { - config: Box::new(hosted_plugin_runtime_mcp_server_config( - &config.chatgpt_base_url, - config.apps_mcp_product_sku.as_deref(), - context.originator(), - )), - protocol_mode: None, - }] - }) - } -} - -pub fn install(builder: &mut ExtensionRegistryBuilder) { - builder.mcp_server_contributor(std::sync::Arc::new(HostedPluginRuntimeExtension)); -} - -#[cfg(test)] -#[path = "lib_tests.rs"] -mod tests; diff --git a/codex-rs/ext/mcp/src/lib_tests.rs b/codex-rs/ext/mcp/src/lib_tests.rs deleted file mode 100644 index 1ada27e5..00000000 --- a/codex-rs/ext/mcp/src/lib_tests.rs +++ /dev/null @@ -1,61 +0,0 @@ -use super::*; -use codex_config::McpServerTransportConfig; -use codex_core::config::ConfigBuilder; -use codex_extension_api::ExtensionData; -use codex_extension_api::ExtensionDataInit; -use pretty_assertions::assert_eq; - -#[tokio::test] -async fn hosted_plugin_runtime_forwards_thread_originator() -> Result<(), Box> -{ - let codex_home = tempfile::tempdir()?; - let config = ConfigBuilder::default() - .codex_home(codex_home.path().to_path_buf()) - .fallback_cwd(Some(codex_home.path().to_path_buf())) - .cli_overrides(vec![ - ("features.apps".to_string(), true.into()), - ("chatgpt_base_url".to_string(), "https://chatgpt.com".into()), - ]) - .build() - .await?; - let thread_init = ExtensionDataInit::new(); - let thread_store = ExtensionData::new("thread"); - - let contributions = HostedPluginRuntimeExtension - .contribute(McpServerContributionContext::for_step( - &config, - &thread_init, - &thread_store, - "codex_work_desktop", - /*ready_selected_capability_roots*/ &[], - /*executor_capability_discovery*/ None, - /*executor_capability_discovery_v2*/ None, - )) - .await; - let [ - McpServerContribution::HostedApps { - config: server, - protocol_mode: None, - }, - ] = contributions.as_slice() - else { - panic!("hosted plugin runtime should contribute one server"); - }; - let McpServerTransportConfig::StreamableHttp { http_headers, .. } = &server.transport else { - panic!("hosted plugin runtime should use streamable HTTP"); - }; - - assert_eq!( - http_headers - .as_ref() - .and_then(|headers| headers.get("originator")), - Some(&"codex_work_desktop".to_string()) - ); - - Ok(()) -} - -#[path = "event_stream_tests.rs"] -mod event_stream_tests; -#[path = "stream_manager_tests.rs"] -mod stream_manager_tests; diff --git a/codex-rs/ext/mcp/src/plugin.rs b/codex-rs/ext/mcp/src/plugin.rs index e2095bdf..8f184314 100644 --- a/codex-rs/ext/mcp/src/plugin.rs +++ b/codex-rs/ext/mcp/src/plugin.rs @@ -1,5 +1,4 @@ use codex_config::types::PluginsConfigToml; -use codex_connectors_extension::PluginAppProvider; use codex_core::config::Config; use codex_core_plugins::ExecutorPluginProviderError; use codex_core_plugins::PluginIdentity; @@ -125,14 +124,8 @@ impl PluginContributor { }; let metadata = match plugin { Some(plugin) => { - // MCP server and app declarations are separate - // executor-owned files. Read them together so a remote environment only - // pays for the slower read instead of both reads back-to-back. - let (servers, app_declarations) = tokio::join!( - PluginMcpProvider.load(&plugin), - PluginAppProvider.load(&plugin) - ); - let servers = servers.unwrap_or_else(|err| { + // ChatGPT app declarations are ignored in aKode; only MCP servers load. + let servers = PluginMcpProvider.load(&plugin).await.unwrap_or_else(|err| { tracing::warn!( selected_root = selected_root.id, error = %err, @@ -140,18 +133,7 @@ impl PluginContributor { ); Vec::new() }); - let connector_ids = app_declarations - .unwrap_or_else(|err| { - tracing::warn!( - selected_root = selected_root.id, - error = %err, - "failed to load selected plugin apps" - ); - Vec::new() - }) - .into_iter() - .map(|declaration| declaration.connector_id.0) - .collect(); + let connector_ids = Vec::new(); let CapabilityRootLocation::Environment { environment_id, .. } = &selected_root.location; Some(SelectedPluginContribution { diff --git a/codex-rs/ext/mcp/tests/hosted_apps_mcp.rs b/codex-rs/ext/mcp/tests/hosted_apps_mcp.rs deleted file mode 100644 index 5de9c29c..00000000 --- a/codex-rs/ext/mcp/tests/hosted_apps_mcp.rs +++ /dev/null @@ -1,233 +0,0 @@ -use std::sync::Arc; - -use codex_config::McpServerTransportConfig; -use codex_config::test_support::CloudConfigBundleFixture; -use codex_core::McpManager; -use codex_core::config::Config; -use codex_core::config::ConfigBuilder; -use codex_core::plugins_manager_for_config; -use codex_extension_api::ExtensionRegistryBuilder; -use codex_extension_api::McpServerContribution; -use codex_extension_api::McpServerContributionContext; -use codex_extension_api::McpServerContributor; -use codex_login::AuthManager; -use codex_login::CodexAuth; -use codex_login::test_support::auth_manager_from_optional_auth; -use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; -use pretty_assertions::assert_eq; - -type TestResult = Result<(), Box>; - -#[tokio::test] -async fn contributes_hosted_plugin_runtime_without_an_executor() -> TestResult { - let codex_home = tempfile::tempdir()?; - let config = ConfigBuilder::default() - .codex_home(codex_home.path().to_path_buf()) - .fallback_cwd(Some(codex_home.path().to_path_buf())) - .cli_overrides(vec![ - ("features.apps".to_string(), true.into()), - ("chatgpt_base_url".to_string(), "https://chatgpt.com".into()), - ]) - .build() - .await?; - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let manager = installed_manager(&config, Some(auth.clone())); - - let servers = manager.effective_servers(&config, Some(&auth)).await; - let server = servers - .get(CODEX_APPS_MCP_SERVER_NAME) - .ok_or("hosted plugin runtime should be contributed as a configured server")? - .config(); - let McpServerTransportConfig::StreamableHttp { url, .. } = &server.transport else { - panic!("hosted plugin runtime should use streamable HTTP"); - }; - assert_eq!(url, "https://chatgpt.com/backend-api/ps/mcp"); - - Ok(()) -} - -#[tokio::test] -async fn runtime_overlay_preserves_disabled_server() -> TestResult { - let codex_home = tempfile::tempdir()?; - let config = ConfigBuilder::default() - .codex_home(codex_home.path().to_path_buf()) - .fallback_cwd(Some(codex_home.path().to_path_buf())) - .cli_overrides(vec![ - ("features.apps".to_string(), true.into()), - ( - "mcp_servers.codex_apps.url".to_string(), - "https://example.com/mcp".into(), - ), - ("mcp_servers.codex_apps.enabled".to_string(), false.into()), - ]) - .cloud_config_bundle( - CloudConfigBundleFixture::loader_with_enterprise_requirement("[mcp_servers]"), - ) - .build() - .await?; - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let manager = installed_manager(&config, Some(auth.clone())); - - let configured = manager.configured_servers(&config).await; - // Standalone login must still reject requirements-denied, explicitly disabled entries. - let login_client = Arc::new(codex_exec_server::RouteAwareHttpClient::new( - config.http_client_factory(), - )); - assert_eq!( - codex_mcp::apply_http_headers_helper( - login_client, - &configured[CODEX_APPS_MCP_SERVER_NAME], - codex_home.path().to_path_buf(), - ) - .err(), - Some("the MCP server is disabled by managed requirements".to_string()) - ); - let servers = manager.effective_servers(&config, Some(&auth)).await; - let server = servers - .get(CODEX_APPS_MCP_SERVER_NAME) - .ok_or("hosted plugin runtime should remain configured")?; - - assert!(!server.enabled()); - Ok(()) -} - -#[tokio::test] -async fn default_fallback_overwrites_reserved_config_without_an_extension() -> TestResult { - let codex_home = tempfile::tempdir()?; - let config = ConfigBuilder::default() - .codex_home(codex_home.path().to_path_buf()) - .fallback_cwd(Some(codex_home.path().to_path_buf())) - .cli_overrides(vec![ - ("features.apps".to_string(), true.into()), - ( - "mcp_servers.codex_apps.url".to_string(), - "https://example.com/mcp".into(), - ), - ]) - .build() - .await?; - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let manager = McpManager::new(Arc::new(plugins_manager_for_config( - &config, - AuthManager::from_auth_for_testing(auth.clone()), - ))); - - let servers = manager.effective_servers(&config, Some(&auth)).await; - let server = servers - .get(CODEX_APPS_MCP_SERVER_NAME) - .ok_or("default Apps MCP should be present")? - .config(); - let McpServerTransportConfig::StreamableHttp { url, .. } = &server.transport else { - panic!("default Apps MCP should use streamable HTTP"); - }; - assert_eq!(url, "https://chatgpt.com/backend-api/ps/mcp"); - - Ok(()) -} - -#[tokio::test] -async fn later_extension_can_remove_same_name_registration() -> TestResult { - let codex_home = tempfile::tempdir()?; - let config = ConfigBuilder::default() - .codex_home(codex_home.path().to_path_buf()) - .fallback_cwd(Some(codex_home.path().to_path_buf())) - .cli_overrides(vec![("features.apps".to_string(), true.into())]) - .build() - .await?; - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let mut builder = ExtensionRegistryBuilder::new(); - codex_mcp_extension::install(&mut builder); - builder.mcp_server_contributor(Arc::new(RemoveCodexApps)); - let manager = McpManager::new_with_extensions( - Arc::new(plugins_manager_for_config( - &config, - AuthManager::from_auth_for_testing(auth.clone()), - )), - Arc::new(builder.build()), - codex_core::CodexAppsToolsCache::default(), - ); - - let servers = manager.effective_servers(&config, Some(&auth)).await; - - assert!(!servers.contains_key(CODEX_APPS_MCP_SERVER_NAME)); - Ok(()) -} - -#[tokio::test] -async fn hosted_apps_mcp_requires_chatgpt_auth() -> TestResult { - let codex_home = tempfile::tempdir()?; - let config = ConfigBuilder::default() - .codex_home(codex_home.path().to_path_buf()) - .fallback_cwd(Some(codex_home.path().to_path_buf())) - .cli_overrides(vec![("features.apps".to_string(), true.into())]) - .build() - .await?; - let auth = CodexAuth::from_api_key("test"); - let manager = installed_manager(&config, Some(auth.clone())); - - let servers = manager.effective_servers(&config, Some(&auth)).await; - assert!(!servers.contains_key(CODEX_APPS_MCP_SERVER_NAME)); - - Ok(()) -} - -#[tokio::test] -async fn disabled_apps_remove_reserved_server_config_for_all_hosts() -> TestResult { - let codex_home = tempfile::tempdir()?; - let config = ConfigBuilder::default() - .codex_home(codex_home.path().to_path_buf()) - .fallback_cwd(Some(codex_home.path().to_path_buf())) - .cli_overrides(vec![ - ("features.apps".to_string(), false.into()), - ( - "mcp_servers.codex_apps.url".to_string(), - "https://example.com/mcp".into(), - ), - ]) - .build() - .await?; - let managers = [ - installed_manager(&config, /*auth*/ None), - McpManager::new(Arc::new(plugins_manager_for_config( - &config, - auth_manager_from_optional_auth(/*auth*/ None), - ))), - ]; - for manager in managers { - let servers = manager.runtime_servers(&config).await; - assert!(!servers.contains_key(CODEX_APPS_MCP_SERVER_NAME)); - } - Ok(()) -} - -fn installed_manager(config: &Config, auth: Option) -> McpManager { - let mut builder = ExtensionRegistryBuilder::new(); - codex_mcp_extension::install(&mut builder); - McpManager::new_with_extensions( - Arc::new(plugins_manager_for_config( - config, - auth_manager_from_optional_auth(auth), - )), - Arc::new(builder.build()), - codex_core::CodexAppsToolsCache::default(), - ) -} - -struct RemoveCodexApps; - -impl McpServerContributor for RemoveCodexApps { - fn id(&self) -> &'static str { - "remove_codex_apps" - } - - fn contribute<'a>( - &'a self, - _context: McpServerContributionContext<'a, Config>, - ) -> codex_extension_api::ExtensionFuture<'a, Vec> { - Box::pin(async move { - vec![McpServerContribution::Remove { - name: CODEX_APPS_MCP_SERVER_NAME.to_string(), - }] - }) - } -} diff --git a/codex-rs/memories/write/Cargo.toml b/codex-rs/memories/write/Cargo.toml index 1e5d9cdc..38af2e52 100644 --- a/codex-rs/memories/write/Cargo.toml +++ b/codex-rs/memories/write/Cargo.toml @@ -15,7 +15,6 @@ workspace = true [dependencies] anyhow = { workspace = true } chrono = { workspace = true } -codex-backend-client = { workspace = true } codex-core = { workspace = true } codex-config = { workspace = true } codex-features = { workspace = true } diff --git a/codex-rs/memories/write/src/guard.rs b/codex-rs/memories/write/src/guard.rs deleted file mode 100644 index 42d1712c..00000000 --- a/codex-rs/memories/write/src/guard.rs +++ /dev/null @@ -1,83 +0,0 @@ -use codex_backend_client::Client as BackendClient; -use codex_core::config::Config; -use codex_model_provider::ProviderAuthContext; -use codex_protocol::protocol::RateLimitSnapshot; -use codex_protocol::protocol::RateLimitWindow; -use tracing::info; -use tracing::warn; - -pub(crate) async fn rate_limits_ok(auth_context: &ProviderAuthContext, config: &Config) -> bool { - rate_limits_check(auth_context, config) - .await - .unwrap_or(true) -} - -async fn rate_limits_check(auth_context: &ProviderAuthContext, config: &Config) -> Option { - let (auth, captured_factory) = auth_context - .credentials - .auth_with_http_client_factory() - .await?; - if !auth.uses_codex_backend() { - return None; - } - - let factory = config.http_client_factory(); - let policy = factory - .network_policy() - .clone() - .with_account_binding(captured_factory.network_policy())?; - let client = BackendClient::from_auth_with_runtime( - config.chatgpt_base_url.clone(), - &auth, - factory.with_network_policy(policy), - auth_context.runtime_auth.as_ref(), - /*headers*/ &Default::default(), - ) - .await - .map_err(|error| warn!(%error, "failed to prepare memory rate-limit authentication")) - .ok()?; - - let snapshots = client - .get_rate_limits_many() - .await - .map_err(|err| warn!(%err, "failed to fetch rate limits")) - .ok()?; - - let snapshot = snapshots - .iter() - .find(|s| s.limit_id.as_deref() == Some(crate::guard_limits::CODEX_LIMIT_ID)) - .or_else(|| snapshots.first())?; - - let min_remaining_percent = config.memories.min_rate_limit_remaining_percent; - let allowed = snapshot_allows_startup(snapshot, min_remaining_percent); - - if !allowed { - info!( - min_remaining_percent, - "skipping memories startup because Codex rate limits are below the configured threshold" - ); - } - - Some(allowed) -} - -fn snapshot_allows_startup(snapshot: &RateLimitSnapshot, min_remaining_percent: i64) -> bool { - if snapshot.rate_limit_reached_type.is_some() { - return false; - } - - let max_used_percent = 100.0 - min_remaining_percent.clamp(0, 100) as f64; - window_allows_startup(snapshot.primary.as_ref(), max_used_percent) - && window_allows_startup(snapshot.secondary.as_ref(), max_used_percent) -} - -fn window_allows_startup(window: Option<&RateLimitWindow>, max_used_percent: f64) -> bool { - match window { - Some(window) => window.used_percent <= max_used_percent, - None => true, - } -} - -#[cfg(test)] -#[path = "guard_tests.rs"] -mod tests; diff --git a/codex-rs/memories/write/src/guard_tests.rs b/codex-rs/memories/write/src/guard_tests.rs deleted file mode 100644 index 5271070c..00000000 --- a/codex-rs/memories/write/src/guard_tests.rs +++ /dev/null @@ -1,81 +0,0 @@ -use super::*; -use codex_protocol::protocol::RateLimitReachedType; - -fn snapshot( - primary_used_percent: Option, - secondary_used_percent: Option, -) -> RateLimitSnapshot { - RateLimitSnapshot { - limit_id: Some(crate::guard_limits::CODEX_LIMIT_ID.to_string()), - limit_name: None, - normal_model_slug: None, - primary: primary_used_percent.map(window), - secondary: secondary_used_percent.map(window), - credits: None, - individual_limit: None, - spend_control_reached: None, - plan_type: None, - rate_limit_reached_type: None, - } -} - -fn window(used_percent: f64) -> RateLimitWindow { - RateLimitWindow { - used_percent, - window_minutes: None, - resets_at: None, - } -} - -#[test] -fn startup_check_uses_configured_remaining_threshold() { - let snapshot = snapshot( - /*primary_used_percent*/ Some(89.9), - /*secondary_used_percent*/ Some(50.0), - ); - - assert!(snapshot_allows_startup( - &snapshot, /*min_remaining_percent*/ 10 - )); - assert!(!snapshot_allows_startup( - &snapshot, /*min_remaining_percent*/ 11 - )); -} - -#[test] -fn startup_check_skips_when_primary_or_secondary_is_too_low() { - assert!(!snapshot_allows_startup( - &snapshot( - /*primary_used_percent*/ Some(75.1), - /*secondary_used_percent*/ Some(10.0), - ), - /*min_remaining_percent*/ 25, - )); - assert!(!snapshot_allows_startup( - &snapshot( - /*primary_used_percent*/ Some(10.0), - /*secondary_used_percent*/ Some(75.1), - ), - /*min_remaining_percent*/ 25, - )); - assert!(snapshot_allows_startup( - &snapshot( - /*primary_used_percent*/ Some(74.9), - /*secondary_used_percent*/ Some(74.9), - ), - /*min_remaining_percent*/ 25, - )); -} - -#[test] -fn startup_check_skips_when_limit_is_reached() { - let mut snapshot = snapshot( - /*primary_used_percent*/ Some(10.0), - /*secondary_used_percent*/ Some(10.0), - ); - snapshot.rate_limit_reached_type = Some(RateLimitReachedType::RateLimitReached); - - assert!(!snapshot_allows_startup( - &snapshot, /*min_remaining_percent*/ 25, - )); -} diff --git a/codex-rs/memories/write/src/lib.rs b/codex-rs/memories/write/src/lib.rs index f6a38068..d894efa5 100644 --- a/codex-rs/memories/write/src/lib.rs +++ b/codex-rs/memories/write/src/lib.rs @@ -6,7 +6,6 @@ mod control; mod extensions; -mod guard; mod metrics; mod phase1; mod phase1_output; @@ -47,10 +46,6 @@ mod extension_resources { pub(super) const RETENTION_DAYS: i64 = 14; } -mod guard_limits { - pub(super) const CODEX_LIMIT_ID: &str = "codex"; -} - mod prompt_blocks { pub(super) const EXTENSIONS_FOLDER_STRUCTURE: &str = r#" Memory extensions (under {{ memory_extensions_root }}/): diff --git a/codex-rs/memories/write/src/metrics.rs b/codex-rs/memories/write/src/metrics.rs index 408c3669..d11abcde 100644 --- a/codex-rs/memories/write/src/metrics.rs +++ b/codex-rs/memories/write/src/metrics.rs @@ -1,4 +1,3 @@ -pub(crate) const MEMORY_STARTUP: &str = "codex.memory.startup"; pub(crate) const MEMORY_STORAGE_BYTES: &str = "codex.memory.storage_bytes"; pub(crate) const MEMORY_PHASE_ONE_JOBS: &str = "codex.memory.phase1"; diff --git a/codex-rs/memories/write/src/start.rs b/codex-rs/memories/write/src/start.rs index 5dae0d17..2b5d8df4 100644 --- a/codex-rs/memories/write/src/start.rs +++ b/codex-rs/memories/write/src/start.rs @@ -1,7 +1,5 @@ use crate::ensure_layout; use crate::extensions::seed_extension_instructions; -use crate::guard; -use crate::metrics::MEMORY_STARTUP; use crate::phase1; use crate::phase2; use crate::runtime::MemoryStartupContext; @@ -84,15 +82,6 @@ pub fn start_memories_startup_task( // done before the quota check. phase1::prune(context.as_ref(), &config).await; - if !guard::rate_limits_ok(&auth, &config).await { - context.counter( - MEMORY_STARTUP, - /*inc*/ 1, - &[("status", "skipped_rate_limit")], - ); - return; - } - // Run phase 1. phase1::run(Arc::clone(&context), Arc::clone(&config)).await; // Run phase 2. diff --git a/codex-rs/memories/write/src/startup_tests.rs b/codex-rs/memories/write/src/startup_tests.rs index 0c58e2f6..ed83f895 100644 --- a/codex-rs/memories/write/src/startup_tests.rs +++ b/codex-rs/memories/write/src/startup_tests.rs @@ -1642,176 +1642,3 @@ async fn memories_startup_phase2_v2_consolidates_without_a_handbook() -> anyhow: assert_eq!(request.body_json()["service_tier"], "flex"); Ok(()) } - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -#[ignore = "aKode: runtime registration with auth.openai.com is disabled"] -async fn memories_startup_uses_thread_runtime_and_keeps_custom_destinations_independent() --> anyhow::Result<()> { - use base64::Engine; - use codex_features::RuntimeAuthMode; - use codex_login::AuthManager; - use codex_login::CodexAuth; - use codex_model_provider::ProviderAuthContext; - use codex_runtime_agent_instance::AgentHostAuthorization; - use codex_runtime_agent_instance::RuntimeAuthManager; - use codex_runtime_agent_instance::RuntimeRegistrationMetadata; - use codex_runtime_agent_instance::RuntimeRole; - use core_test_support::runtime_auth::PROBE_SERVER; - use core_test_support::runtime_auth::run_harness_through_proxy; - use pretty_assertions::assert_eq; - use serde_json::json; - use std::sync::Arc; - use wiremock::Mock; - use wiremock::MockServer; - use wiremock::ResponseTemplate; - use wiremock::matchers::method; - use wiremock::matchers::path; - - core_test_support::skip_if_no_network!(Ok(())); - let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode( - json!({ - "iss": "https://auth.openai.com/", "session_id": "memory-login", - "https://api.openai.com/auth": {"user_id": "actor", "chatgpt_account_id": "account_id"} - }) - .to_string(), - ); - let token = format!("header.{claims}.signature"); - if let Ok(server) = std::env::var(PROBE_SERVER) { - let credentials = - AuthManager::from_auth_for_testing(CodexAuth::from_external_chatgpt_tokens( - &token, - "account_id", - /*chatgpt_plan_type*/ None, - )?); - let runtime = Arc::new(RuntimeAuthManager::new( - Arc::clone(&credentials), - AgentHostAuthorization::InstallationId { - installation_id: uuid::Uuid::nil(), - }, - RuntimeRegistrationMetadata { - harness: Some("codex".into()), - harness_version: None, - role: RuntimeRole::Orchestrator, - }, - "https://auth.openai.com/agent/register".parse()?, - )); - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - let auth = ProviderAuthContext { - credentials: Arc::clone(&credentials), - runtime_auth: Some((Arc::clone(&runtime), mode)), - }; - for base_url in [ - "https://chatgpt.com/backend-api".to_owned(), - format!("{server}/custom/backend-api"), - ] { - let model_server = MockServer::start().await; - let home = Arc::new(TempDir::new()?); - let mut test = test_codex() - .with_home(Arc::clone(&home)) - .with_auth(CodexAuth::from_api_key("ambient-key")) - .with_config(|config| { - config - .features - .enable(Feature::Sqlite) - .expect("enable state database"); - config.memories = startup_test_memories_config(); - config.memories.version = codex_protocol::MemoryVersion::V1; - config.memories.dual_write = false; - }) - .build(&model_server) - .await?; - test.config.chatgpt_base_url = base_url; - test.codex.thread_extension_data().insert(auth.clone()); - let db = test.codex.state_db().expect("startup state database"); - seed_stage1_output( - db.as_ref(), - home.path(), - chrono::Utc::now(), - "source memory", - "source summary", - "quota-auth", - ) - .await?; - let root = home.path().join("memories"); - tokio::fs::create_dir_all(&root).await?; - seed_required_memory_artifacts(&root).await?; - let phase2 = mount_sse_once( - &model_server, - sse(vec![ - ev_response_created("quota-consolidation"), - ev_assistant_message("quota-result", "memory complete"), - ev_completed("quota-consolidation"), - ]), - ) - .await; - trigger_memories_startup(&test).await; - // Consolidation starts only after the startup quota request finishes. - wait_for_single_request(&phase2).await; - shutdown_test_codex(&test).await?; - } - } - return Ok(()); - } - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/agent/register")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "runtime_agent_instance_id": "runtime-memory", "agent_host_id": "host", - "actor": {"kind": "chatgpt", "user_id": "actor", "account_id": "account_id"} - }))) - .expect(/*r*/ 1) - .mount(&server) - .await; - let quota = json!({"plan_type": "plus", "rate_limit": { - "allowed": true, "limit_reached": false, - "primary_window": {"used_percent": 0, "limit_window_seconds": 300, - "reset_after_seconds": 60, "reset_at": 2000000000} - }}); - for url in ["/backend-api/wham/usage", "/custom/backend-api/wham/usage"] { - Mock::given(method("GET")) - .and(path(url)) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(quota.clone())) - .expect(/*r*/ 2) - .mount(&server) - .await; - } - run_harness_through_proxy( - &server, - "startup_tests::memories_startup_uses_thread_runtime_and_keeps_custom_destinations_independent", - /*realtime_target*/ None, - ) - .await?; - let requests = server.received_requests().await.unwrap(); - let quota_requests = requests - .iter() - .filter(|r| r.url.path() == "/backend-api/wham/usage") - .collect::>(); - assert_eq!(quota_requests.len(), 2); - let mut dual = 0; - for request in quota_requests { - assert_eq!(request.headers["chatgpt-account-id"], "account_id"); - let authorization = request.headers["authorization"].to_str()?; - let proof = if let Some(proof) = request.headers.get("x-openai-agent-assertion") { - dual += 1; - assert_eq!(authorization, format!("Bearer {token}")); - proof.to_str()? - } else { - authorization.strip_prefix("AgentAssertion ").unwrap() - }; - let payload: serde_json::Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(proof.split('.').nth(/*n*/ 2).unwrap())?, - )?; - assert_eq!(payload["runtime_agent_instance"], "runtime-memory"); - } - assert_eq!(dual, 1); - for request in requests - .iter() - .filter(|r| r.url.path().starts_with("/custom/")) - { - assert_eq!(request.headers["authorization"], format!("Bearer {token}")); - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - } - server.verify().await; - Ok(()) -} diff --git a/codex-rs/runtime-agent-instance/src/manager_tests.rs b/codex-rs/runtime-agent-instance/src/manager_tests.rs index 7b6483e3..2e2bef1b 100644 --- a/codex-rs/runtime-agent-instance/src/manager_tests.rs +++ b/codex-rs/runtime-agent-instance/src/manager_tests.rs @@ -724,93 +724,6 @@ async fn captured_request_auth_allows_refresh_but_rejects_source_replacement() { assert_eq!(server.received_requests().await.unwrap().len(), 1); } -#[tokio::test] -async fn file_upload_runtime_auth_signs_control_requests_but_not_blob_uploads() { - use wiremock::matchers::path; - for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] { - let server = MockServer::start().await; - let blob = MockServer::start().await; - Mock::given(path("/agent/register")) - .respond_with(registered) - .expect(1) - .mount(&server) - .await; - Mock::given(path("/files")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "file_id": "file-a", "upload_url": blob.uri(), - }))) - .expect(1) - .mount(&server) - .await; - Mock::given(path("/files/file-a/uploaded")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({"status": "retry"}))) - .up_to_n_times(1) - .with_priority(1) - .mount(&server) - .await; - Mock::given(path("/files/file-a/uploaded")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "status": "success", "download_url": blob.uri(), "file_name": "hello.txt", "file_size_bytes": 5, - }))).expect(1).mount(&server).await; - Mock::given(method("PUT")) - .respond_with(ResponseTemplate::new(200)) - .expect(1) - .mount(&blob) - .await; - let initial = CodexAuth::from_api_key("key-a"); - let (manager, _, _) = setup(&server, initial.clone(), initial).await; - let provider = manager.auth().await.unwrap().into_auth_provider(mode); - let pool = - codex_http_client::RouteAwareClientPool::new_without_redirects_or_request_logging( - HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - codex_http_client::ClientRouteClass::Api, - ); - let uploaded = codex_api::upload_openai_file( - &server.uri(), - provider.as_ref(), - &pool, - "hello.txt".into(), - /*file_size_bytes*/ 5, - || async { - Ok(futures::stream::iter([Ok::<_, std::io::Error>( - bytes::Bytes::from_static(b"hello"), - )])) - }, - /*hosted_upload*/ None, - ) - .await - .unwrap(); - assert_eq!(uploaded.uri, "sediment://file-a"); - let requests = server.received_requests().await.unwrap(); - let mut proofs = std::collections::HashSet::new(); - for request in requests - .iter() - .filter(|r| r.url.path().starts_with("/files")) - { - let authorization = request.headers[AUTHORIZATION].to_str().unwrap(); - let proof = match mode { - RuntimeAuthMode::DualHeader => { - assert_eq!(authorization, "Bearer key-a"); - request.headers["x-openai-agent-assertion"] - .to_str() - .unwrap() - } - RuntimeAuthMode::AssertionOnly => { - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - authorization.strip_prefix("AgentAssertion ").unwrap() - } - }; - assert!(proofs.insert(proof)); - } - assert_eq!(proofs.len(), 3); - let blobs = blob.received_requests().await.unwrap(); - assert_eq!(blobs.len(), 1); - assert!(!blobs[0].headers.contains_key(AUTHORIZATION)); - assert!(!blobs[0].headers.contains_key("x-openai-agent-assertion")); - assert_eq!(blobs[0].body, b"hello"); - } -} - #[tokio::test] async fn source_outage_preserves_registered_pending_and_denied_runtimes() { for status in [200, 403, 503] { diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 913ee8f8..90eabde6 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -35,7 +35,6 @@ codex-app-server-protocol = { workspace = true } codex-arg0 = { workspace = true } codex-backend-client = { workspace = true } codex-install-context = { workspace = true } -codex-cloud-config = { workspace = true } codex-config = { workspace = true } codex-context-fragments = { workspace = true } codex-connectors = { workspace = true } diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index cdadf12f..57081724 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -47,7 +47,6 @@ use codex_app_server_protocol::ThreadListCwdFilter; use codex_app_server_protocol::ThreadListParams; use codex_app_server_protocol::ThreadSortKey as AppServerThreadSortKey; use codex_app_server_protocol::ThreadSourceKind; -use codex_cloud_config::managed_config_bundle_loader_for_storage; use codex_config::CloudConfigBundleLoader; use codex_config::ConfigLoadError; use codex_config::LoaderOverrides; @@ -1126,21 +1125,15 @@ fn app_server_target_for_launch( }) } +/// aKode never loads managed config bundles from a remote service; only local +/// configuration and requirements files apply. async fn cloud_config_bundle_for_app_server_target( - app_server_target: &AppServerTarget, - bootstrap_config: &ConfigTomlLoadResult, - codex_home: &Path, - embedded_network_policy: &codex_app_server_client::EmbeddedNetworkPolicy, + _app_server_target: &AppServerTarget, + _bootstrap_config: &ConfigTomlLoadResult, + _codex_home: &Path, + _embedded_network_policy: &codex_app_server_client::EmbeddedNetworkPolicy, ) -> std::io::Result { - managed_config_bundle_loader_for_storage( - embedded_network_policy - .bind_bootstrap_auth(app_server_target.auth_config_for_cloud_loader( - bootstrap_auth_config(codex_home, bootstrap_config)?, - )), - bootstrap_config.config_layer_stack.requirements_toml(), - /*enable_codex_api_key_env*/ false, - ) - .await + Ok(CloudConfigBundleLoader::default()) } fn loader_overrides_are_default(loader_overrides: &LoaderOverrides) -> bool { @@ -1236,7 +1229,7 @@ async fn run_ratatui_app( manually_selected_oss_provider: Option, overrides: ConfigOverrides, cli_kv_overrides: Vec<(String, toml::Value)>, - mut cloud_config_bundle: CloudConfigBundleLoader, + cloud_config_bundle: CloudConfigBundleLoader, feedback: codex_feedback::CodexFeedback, log_db: Option, mut state_db: Option, @@ -1544,17 +1537,6 @@ async fn run_ratatui_app( } let reloaded_config = startup_draft .run_until(&mut tui, async { - // If this onboarding run included the login step, always refresh the cloud config - // bundle and rebuild config. This avoids missing newly available cloud-managed - // policy due to login status detection edge cases. - if show_login_screen && !uses_remote_workspace && !workload_identity_selected { - cloud_config_bundle = managed_config_bundle_loader_for_storage( - embedded_network_policy.bind_bootstrap_auth(initial_config.auth_config()), - initial_config.config_layer_stack.requirements_toml(), - /*enable_codex_api_key_env*/ false, - ) - .await?; - } // Reload config when persisted trust or auth changes alter the current process. Ok::<_, std::io::Error>( diff --git a/codex-rs/tui/src/startup_orchestration.rs b/codex-rs/tui/src/startup_orchestration.rs index 9611d154..8d5414c3 100644 --- a/codex-rs/tui/src/startup_orchestration.rs +++ b/codex-rs/tui/src/startup_orchestration.rs @@ -313,19 +313,6 @@ pub(super) async fn run_main_inner( err } })?; - if std::io::stdin().is_terminal() && std::io::stdout().is_terminal() { - codex_cloud_config::ensure_config_server_login( - embedded_network_policy.bind_bootstrap_auth(bootstrap_auth_config( - &codex_home, - &presentation.bootstrap_config, - )?), - presentation - .bootstrap_config - .config_layer_stack - .requirements_toml(), - ) - .await?; - } // Keep normal terminal signals available until local configuration is ready. Once raw // mode begins, StartupDraft immediately takes ownership of input. let (initialized_terminal, terminal_restore_guard) = tokio::task::spawn_blocking(|| { @@ -394,7 +381,7 @@ pub(super) async fn run_main_inner( } else { Ok(()) }; - let cloud_config_bundle = startup_draft + let mut cloud_config_bundle = startup_draft .run_until(cloud_config_bundle_for_app_server_target( &app_server_target, &bootstrap_config, @@ -525,19 +512,6 @@ pub(super) async fn run_main_inner( config.cwd.as_path(), ); - let mut cloud_config_bundle = if workload_identity_selected { - cloud_config_bundle - } else { - startup_draft - .run_until(managed_config_bundle_loader_for_storage( - embedded_network_policy.bind_bootstrap_auth( - app_server_target.auth_config_for_cloud_loader(config.auth_config()), - ), - config.config_layer_stack.requirements_toml(), - /*enable_codex_api_key_env*/ false, - )) - .await?? - }; let managed_worktree = if cli.shared.worktree { let (destination, bundle, worktree) = startup_draft .run_until(worktree_startup::prepare( diff --git a/codex-rs/windows-sandbox-service/Cargo.toml b/codex-rs/windows-sandbox-service/Cargo.toml index b4652f85..59372aed 100644 --- a/codex-rs/windows-sandbox-service/Cargo.toml +++ b/codex-rs/windows-sandbox-service/Cargo.toml @@ -18,7 +18,6 @@ workspace = true [dependencies] anyhow = { workspace = true } -codex-cloud-config = { workspace = true } codex-config = { workspace = true } codex-core = { workspace = true } codex-windows-sandbox = { workspace = true } diff --git a/codex-rs/windows-sandbox-service/src/machine_policy.rs b/codex-rs/windows-sandbox-service/src/machine_policy.rs index 4acac15b..4a5adbea 100644 --- a/codex-rs/windows-sandbox-service/src/machine_policy.rs +++ b/codex-rs/windows-sandbox-service/src/machine_policy.rs @@ -4,11 +4,9 @@ use anyhow::Context; use anyhow::Result; use anyhow::bail; -use codex_cloud_config::chatgpt_config_bundle_loader_for_storage_without_cache; use codex_config::ConfigLoadOptions; use codex_config::ConfigRequirements; use codex_config::types::WindowsSandboxModeToml; -use codex_core::config::bootstrap_auth_config; use codex_core::config::load_config_toml_with_layer_stack; use codex_windows_sandbox::WindowsSandboxProvisioningSettings; use codex_windows_sandbox::WindowsSandboxProxyListeners; @@ -65,31 +63,12 @@ pub(crate) fn validate_provisioning_request( Err(anyhow::anyhow!("configuration runtime worker failed to impersonate the provisioning client")) }, result = async { - let mut bootstrap_config = load_config_toml_with_layer_stack( - codex_home, - /*cwd*/ None, - Vec::new(), - ConfigLoadOptions::default(), - ) - .await - .context("load bootstrap configuration")?; - // Use the default cloud-policy endpoint unless managed requirements override it. - bootstrap_config.config_toml.chatgpt_base_url = None; - let cloud_config_bundle = chatgpt_config_bundle_loader_for_storage_without_cache( - bootstrap_auth_config(codex_home, &bootstrap_config) - .context("resolve cloud configuration authentication")?, - /*enable_codex_api_key_env*/ false, - ) - .await - .context("initialize cloud configuration authentication")?; + // aKode only enforces local managed requirements; no cloud bundle is fetched. let config = load_config_toml_with_layer_stack( codex_home, /*cwd*/ None, Vec::new(), - ConfigLoadOptions { - cloud_config_bundle, - ..Default::default() - }, + ConfigLoadOptions::default(), ) .await .context("load managed configuration")?;