From 7670578418503a5d8f259cdf8295891ea901d607 Mon Sep 17 00:00:00 2001 From: Alex Ionescu Date: Wed, 2 Dec 2026 20:05:46 +0000 Subject: [PATCH] Report remote plugin archive verification in install telemetry (#65330) ## Why Remote plugin install telemetry needs enough detail to distinguish archive verification failures from other bundle errors and associate those failures with a specific release when its ID is available. ## What changed - Include the archive verification outcome in successful app-server install events. Classify verification failures by reason and attach the `plugin_release_id` when available. Use the catalog plugin ID for bundle events when it is available. - Export `codex.plugins.archive_verification` through the configured OpenTelemetry logger during standalone CLI installs. ## Testing App-server tests check successful and failed install analytics. A CLI integration test checks that an archive verification failure exports the expected event fields and leaves the plugin uninstalled. GitOrigin-RevId: ea6cab1d04467d63f43fbd17e3d0a122fad15435 --- codex-rs/Cargo.lock | 2 + codex-rs/analytics/Cargo.toml | 1 + codex-rs/analytics/src/client.rs | 11 +- codex-rs/analytics/src/client_tests.rs | 1 + codex-rs/analytics/src/events.rs | 16 +- codex-rs/analytics/src/facts.rs | 21 +- codex-rs/analytics/src/lib.rs | 1 + codex-rs/analytics/src/reducer.rs | 7 +- .../src/tests/suite/plugins_tests.rs | 6 +- .../src/request_processors/plugins.rs | 74 +++++-- .../tests/common/analytics_server.rs | 43 ++++ codex-rs/app-server/tests/common/lib.rs | 2 + .../tests/suite/v2/plugin_install.rs | 44 +--- codex-rs/cli/src/plugin_cmd.rs | 48 +++-- codex-rs/core-plugins/src/manager.rs | 5 +- .../src/plugin_measurement_references.rs | 4 +- .../remote/remote_installed_plugin_sync.rs | 2 +- codex-rs/core-plugins/src/remote_bundle.rs | 20 +- .../remote_bundle_signing_key_cache_tests.rs | 2 +- codex-rs/core-plugins/src/remote_mutations.rs | 36 +++- .../src/remote_mutations_tests.rs | 17 +- .../plugin-archive-verification/BUILD.bazel | 1 + .../plugin-archive-verification/Cargo.toml | 3 +- .../src/archive_verification.rs | 40 +++- .../src/archive_verification_tests.rs | 13 +- .../src/cli_telemetry.rs | 26 +++ .../src/install_telemetry.rs | 42 ++++ .../plugin-archive-verification/src/lib.rs | 5 + .../tests/app_server.rs | 93 ++++++-- .../plugin-archive-verification/tests/cli.rs | 198 ++++++++++++++++++ 30 files changed, 644 insertions(+), 140 deletions(-) create mode 100644 codex-rs/plugin-archive-verification/src/cli_telemetry.rs create mode 100644 codex-rs/plugin-archive-verification/src/install_telemetry.rs create mode 100644 codex-rs/plugin-archive-verification/tests/cli.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 7613454afb..bfae009feb 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2066,6 +2066,7 @@ dependencies = [ "codex-model-provider", "codex-model-provider-info", "codex-plugin", + "codex-plugin-archive-verification", "codex-protocol", "codex-runtime-agent-instance", "codex-state", @@ -4755,6 +4756,7 @@ dependencies = [ "codex-http-client", "codex-login", "codex-otel", + "codex-utils-cargo-bin", "codex-utils-path-uri", "hex", "http 1.4.0", diff --git a/codex-rs/analytics/Cargo.toml b/codex-rs/analytics/Cargo.toml index ad134107e6..180ca7542b 100644 --- a/codex-rs/analytics/Cargo.toml +++ b/codex-rs/analytics/Cargo.toml @@ -21,6 +21,7 @@ codex-runtime-agent-instance = { workspace = true } codex-login = { workspace = true } codex-model-provider = { workspace = true } codex-plugin = { workspace = true } +codex-plugin-archive-verification = { workspace = true } codex-protocol = { workspace = true } codex-state = { workspace = true } codex-utils-path-uri = { workspace = true } diff --git a/codex-rs/analytics/src/client.rs b/codex-rs/analytics/src/client.rs index 7174197dd9..28503c6e0f 100644 --- a/codex-rs/analytics/src/client.rs +++ b/codex-rs/analytics/src/client.rs @@ -22,6 +22,7 @@ use crate::facts::HookRunFact; use crate::facts::HookRunInput; use crate::facts::ImagePreparationFact; use crate::facts::McpToolCallElicitation; +use crate::facts::PluginEventMetadata; use crate::facts::PluginInstallFailedInput; use crate::facts::PluginInstallRequested; use crate::facts::PluginInstallRequestedInput; @@ -800,7 +801,7 @@ impl AnalyticsEventsClient { )); } - pub fn track_plugin_installed(&self, plugin: PluginTelemetryMetadata) { + pub fn track_plugin_installed(&self, plugin: PluginEventMetadata) { self.record_fact(AnalyticsFact::Custom( CustomAnalyticsFact::PluginStateChanged(PluginStateChangedInput { plugin, @@ -811,7 +812,7 @@ impl AnalyticsEventsClient { pub fn track_plugin_install_failed( &self, - plugin: PluginTelemetryMetadata, + plugin: PluginEventMetadata, source: PluginInstallSource, error_type: String, sub_error_type: Option, @@ -847,7 +848,7 @@ impl AnalyticsEventsClient { pub fn track_plugin_uninstalled(&self, plugin: PluginTelemetryMetadata) { self.record_fact(AnalyticsFact::Custom( CustomAnalyticsFact::PluginStateChanged(PluginStateChangedInput { - plugin, + plugin: plugin.into(), state: PluginState::Uninstalled, }), )); @@ -856,7 +857,7 @@ impl AnalyticsEventsClient { pub fn track_plugin_enabled(&self, plugin: PluginTelemetryMetadata) { self.record_fact(AnalyticsFact::Custom( CustomAnalyticsFact::PluginStateChanged(PluginStateChangedInput { - plugin, + plugin: plugin.into(), state: PluginState::Enabled, }), )); @@ -865,7 +866,7 @@ impl AnalyticsEventsClient { pub fn track_plugin_disabled(&self, plugin: PluginTelemetryMetadata) { self.record_fact(AnalyticsFact::Custom( CustomAnalyticsFact::PluginStateChanged(PluginStateChangedInput { - plugin, + plugin: plugin.into(), state: PluginState::Disabled, }), )); diff --git a/codex-rs/analytics/src/client_tests.rs b/codex-rs/analytics/src/client_tests.rs index 003b4884cd..9179729cca 100644 --- a/codex-rs/analytics/src/client_tests.rs +++ b/codex-rs/analytics/src/client_tests.rs @@ -268,6 +268,7 @@ fn sample_plugin_used_track_event(thread_id: &str, plugin_id: Option<&str>) -> T event_params: CodexPluginUsedMetadata { turn_trigger: None, plugin: CodexPluginMetadata { + install_telemetry: Default::default(), plugin_id: plugin_id.map(str::to_string), remote_plugin_id: None, plugin_name: Some("sample".to_string()), diff --git a/codex-rs/analytics/src/events.rs b/codex-rs/analytics/src/events.rs index ee8166dd29..572c6f26b1 100644 --- a/codex-rs/analytics/src/events.rs +++ b/codex-rs/analytics/src/events.rs @@ -18,6 +18,7 @@ use crate::facts::GoalEventKind; use crate::facts::HookRunFact; use crate::facts::ImagePreparationMetadata; use crate::facts::InvocationType; +use crate::facts::PluginEventMetadata; use crate::facts::PluginInstallRequested; use crate::facts::PluginState; use crate::facts::SubAgentThreadStartedInput; @@ -35,6 +36,7 @@ use codex_app_server_protocol::CommandExecutionSource; use codex_login::default_client::originator; use codex_plugin::PluginId; use codex_plugin::PluginTelemetryMetadata; +use codex_plugin_archive_verification::PluginInstallTelemetry; use codex_protocol::approvals::NetworkApprovalProtocol; use codex_protocol::models::AdditionalPermissionProfile; use codex_protocol::models::SandboxPermissions; @@ -1287,6 +1289,8 @@ pub(crate) struct CodexTurnSteerEventRequest { #[derive(Serialize)] pub(crate) struct CodexPluginMetadata { + #[serde(flatten)] + pub(crate) install_telemetry: PluginInstallTelemetry, pub(crate) plugin_id: Option, pub(crate) remote_plugin_id: Option, pub(crate) plugin_name: Option, @@ -1398,7 +1402,7 @@ pub(crate) struct CodexPluginUsedEventRequest { pub(crate) event_params: CodexPluginUsedMetadata, } -pub(crate) fn plugin_state_event_type(state: PluginState) -> &'static str { +pub(crate) fn plugin_state_event_type(state: &PluginState) -> &'static str { match state { PluginState::Installed => "codex_plugin_installed", PluginState::Uninstalled => "codex_plugin_uninstalled", @@ -1424,6 +1428,15 @@ pub(crate) fn codex_app_metadata( } } +impl From for CodexPluginMetadata { + fn from(metadata: PluginEventMetadata) -> Self { + Self { + install_telemetry: metadata.install_telemetry, + ..codex_plugin_metadata(metadata.plugin) + } + } +} + pub(crate) fn codex_plugin_metadata(plugin: PluginTelemetryMetadata) -> CodexPluginMetadata { codex_plugin_metadata_with_product_client_id(plugin, originator().value) } @@ -1438,6 +1451,7 @@ fn codex_plugin_metadata_with_product_client_id( capability_summary, } = plugin; CodexPluginMetadata { + install_telemetry: PluginInstallTelemetry::default(), plugin_id: plugin_id.as_ref().map(PluginId::as_key), remote_plugin_id, plugin_name: plugin_id diff --git a/codex-rs/analytics/src/facts.rs b/codex-rs/analytics/src/facts.rs index 7e4e1970df..ab15b381cd 100644 --- a/codex-rs/analytics/src/facts.rs +++ b/codex-rs/analytics/src/facts.rs @@ -11,6 +11,7 @@ use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequest; use codex_app_server_protocol::ServerResponse; use codex_plugin::PluginTelemetryMetadata; +use codex_plugin_archive_verification::PluginInstallTelemetry; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Personality; @@ -734,8 +735,23 @@ pub(crate) struct PluginInstallRequestedInput { pub request: PluginInstallRequested, } -pub(crate) struct PluginStateChangedInput { +/// Plugin identity and verification details carried by plugin lifecycle events. +pub struct PluginEventMetadata { pub plugin: PluginTelemetryMetadata, + pub install_telemetry: PluginInstallTelemetry, +} + +impl From for PluginEventMetadata { + fn from(plugin: PluginTelemetryMetadata) -> Self { + Self { + plugin, + install_telemetry: PluginInstallTelemetry::default(), + } + } +} + +pub(crate) struct PluginStateChangedInput { + pub plugin: PluginEventMetadata, pub state: PluginState, } @@ -747,7 +763,7 @@ pub enum PluginInstallSource { } pub(crate) struct PluginInstallFailedInput { - pub plugin: PluginTelemetryMetadata, + pub plugin: PluginEventMetadata, pub source: PluginInstallSource, pub error_type: String, pub sub_error_type: Option, @@ -772,7 +788,6 @@ pub struct ExternalAgentConfigImportFailureInput { pub sub_error_type: Option, } -#[derive(Clone, Copy)] pub(crate) enum PluginState { Installed, Uninstalled, diff --git a/codex-rs/analytics/src/lib.rs b/codex-rs/analytics/src/lib.rs index 7666dad3b5..52ef43ec9a 100644 --- a/codex-rs/analytics/src/lib.rs +++ b/codex-rs/analytics/src/lib.rs @@ -61,6 +61,7 @@ pub use facts::ImagePreparationMetadata; pub use facts::InputError; pub use facts::InvocationType; pub use facts::McpToolCallElicitation; +pub use facts::PluginEventMetadata; pub use facts::PluginInstallRequestSource; pub use facts::PluginInstallRequested; pub use facts::PluginInstallRequestedPlugin; diff --git a/codex-rs/analytics/src/reducer.rs b/codex-rs/analytics/src/reducer.rs index b9c2ad774f..438aab1c80 100644 --- a/codex-rs/analytics/src/reducer.rs +++ b/codex-rs/analytics/src/reducer.rs @@ -74,7 +74,6 @@ use crate::events::codex_compaction_event_params; use crate::events::codex_goal_event_params; use crate::events::codex_hook_run_metadata; use crate::events::codex_plugin_install_requested_metadata; -use crate::events::codex_plugin_metadata; use crate::events::codex_plugin_used_metadata; use crate::events::plugin_state_event_type; use crate::events::subagent_source_name; @@ -1672,8 +1671,8 @@ impl AnalyticsReducer { ) { let PluginStateChangedInput { plugin, state } = input; let event = CodexPluginEventRequest { - event_type: plugin_state_event_type(state), - event_params: codex_plugin_metadata(plugin), + event_type: plugin_state_event_type(&state), + event_params: plugin.into(), }; out.push(match state { PluginState::Installed => TrackEventRequest::PluginInstalled(event), @@ -1698,7 +1697,7 @@ impl AnalyticsReducer { CodexPluginInstallFailedEventRequest { event_type: "codex_plugin_install_failed", event_params: CodexPluginInstallFailedMetadata { - plugin: codex_plugin_metadata(plugin), + plugin: plugin.into(), source, error_type, sub_error_type, diff --git a/codex-rs/analytics/src/tests/suite/plugins_tests.rs b/codex-rs/analytics/src/tests/suite/plugins_tests.rs index 584f5d0c84..987f997684 100644 --- a/codex-rs/analytics/src/tests/suite/plugins_tests.rs +++ b/codex-rs/analytics/src/tests/suite/plugins_tests.rs @@ -309,7 +309,7 @@ async fn reducer_ingests_plugin_state_changed_fact() { .ingest( AnalyticsFact::Custom(CustomAnalyticsFact::PluginStateChanged( PluginStateChangedInput { - plugin: sample_plugin_metadata(), + plugin: sample_plugin_metadata().into(), state: PluginState::Disabled, }, )), @@ -405,7 +405,7 @@ async fn reducer_ingests_plugin_install_failed_fact() { .ingest( AnalyticsFact::Custom(CustomAnalyticsFact::PluginInstallFailed( PluginInstallFailedInput { - plugin: sample_plugin_metadata(), + plugin: sample_plugin_metadata().into(), source: PluginInstallSource::ExternalAgentMigration, error_type: "invalid_plugin".to_string(), sub_error_type: Some("failed_to_copy_plugin_file".to_string()), @@ -451,7 +451,7 @@ async fn reducer_ingests_plugin_install_failed_fact_without_detail() { .ingest( AnalyticsFact::Custom(CustomAnalyticsFact::PluginInstallFailed( PluginInstallFailedInput { - plugin, + plugin: plugin.into(), source: PluginInstallSource::Manual, error_type: "remote_catalog_unexpected_status".to_string(), sub_error_type: None, diff --git a/codex-rs/app-server/src/request_processors/plugins.rs b/codex-rs/app-server/src/request_processors/plugins.rs index 2f9909cbd5..1a7f6c9ae3 100644 --- a/codex-rs/app-server/src/request_processors/plugins.rs +++ b/codex-rs/app-server/src/request_processors/plugins.rs @@ -3,6 +3,7 @@ use super::config_processor::reload_user_config; use super::*; use crate::error_code::internal_error; use crate::error_code::invalid_request; +use codex_analytics::PluginEventMetadata; use codex_analytics::PluginInstallSource; use codex_app_server_protocol::PluginAvailability; use codex_app_server_protocol::PluginSharePrincipalRole; @@ -30,6 +31,7 @@ use codex_core_plugins::remote::RemotePluginCatalogCacheMode; use codex_core_plugins::remote::RemotePluginScope; use codex_core_plugins::remote::is_valid_remote_plugin_id; use codex_core_plugins::remote::validate_remote_plugin_id; +use codex_core_plugins::remote_bundle::PluginInstallTelemetry; use codex_core_plugins::remote_bundle::RemotePluginBundleInstallError; use codex_mcp::McpOAuthLoginSupport; use codex_mcp::McpRuntimeContext; @@ -1700,35 +1702,47 @@ impl PluginRequestProcessor { RemotePluginOperationErrorKind::Catalog { source, .. } => Some(( remote_plugin_catalog_error_type(source), source.sub_error_type(), + PluginInstallTelemetry::default(), )), - RemotePluginOperationErrorKind::Bundle(source) => Some(( - remote_plugin_bundle_install_error_type(source), - source.sub_error_type(), - )), + RemotePluginOperationErrorKind::Bundle { source, .. } => { + Some(remote_plugin_bundle_install_failure(source)) + } RemotePluginOperationErrorKind::DisabledByAdmin(_) => Some(( "remote_plugin_not_available", Some("disabled_by_admin".to_string()), + PluginInstallTelemetry::default(), )), RemotePluginOperationErrorKind::NotAvailable(_) => Some(( "remote_plugin_not_available", Some("install_policy_not_available".to_string()), + PluginInstallTelemetry::default(), )), RemotePluginOperationErrorKind::Sync { .. } | RemotePluginOperationErrorKind::InvalidRequest(_) | RemotePluginOperationErrorKind::Internal(_) => None, }; - if let Some((error_type, sub_error_type)) = classification { + if let Some((error_type, sub_error_type, install_telemetry)) = classification { let marketplace = err .plugin_id .as_ref() .map(|id| id.marketplace_name.as_str()) .unwrap_or(&remote_marketplace_name); - self.track_plugin_install_failed_for_remote_plugin( + let catalog_plugin_id = match err.kind.as_ref() { + RemotePluginOperationErrorKind::Bundle { + catalog_plugin_id, .. + } => Some(catalog_plugin_id.as_str()), + _ => None, + }; + let remote_plugin_id = PluginInstallTelemetry::remote_plugin_id( &remote_plugin_id, + catalog_plugin_id, + ); + self.track_plugin_install_failed_for_remote_plugin( + remote_plugin_id, marketplace, err.plugin_id.as_ref(), - error_type, - sub_error_type, + (error_type, sub_error_type), + install_telemetry, err.to_string(), ); } @@ -1743,11 +1757,19 @@ impl PluginRequestProcessor { .plugins_manager() .telemetry_metadata_for_installed_plugin_with_remote_id( &result.plugin_id, - &remote_plugin_id, + PluginInstallTelemetry::remote_plugin_id( + &remote_plugin_id, + Some(&remote_detail.summary.remote_plugin_id), + ), ) .await; self.analytics_events_client - .track_plugin_installed(plugin_metadata); + .track_plugin_installed(PluginEventMetadata { + plugin: plugin_metadata, + install_telemetry: PluginInstallTelemetry::installed( + installation.archive_verification, + ), + }); let config = match self.load_latest_config(/*fallback_cwd*/ None).await { Ok(mut reloaded_config) => { @@ -1841,8 +1863,8 @@ impl PluginRequestProcessor { remote_plugin_id: &str, marketplace_name: &str, plugin_id: Option<&PluginId>, - error_type: &'static str, - sub_error_type: Option, + (error_type, sub_error_type): (&'static str, Option), + install_telemetry: PluginInstallTelemetry, error_message: String, ) { tracing::warn!( @@ -1865,7 +1887,10 @@ impl PluginRequestProcessor { } }; self.analytics_events_client.track_plugin_install_failed( - plugin, + PluginEventMetadata { + plugin, + install_telemetry, + }, PluginInstallSource::Manual, error_type.to_string(), sub_error_type, @@ -2534,8 +2559,10 @@ fn remote_plugin_catalog_error_type(err: &RemotePluginCatalogError) -> &'static } } -fn remote_plugin_bundle_install_error_type(err: &RemotePluginBundleInstallError) -> &'static str { - match err { +fn remote_plugin_bundle_install_failure( + err: &RemotePluginBundleInstallError, +) -> (&'static str, Option, PluginInstallTelemetry) { + let error_type = match err { RemotePluginBundleInstallError::MissingReleaseVersion { .. } => { "remote_bundle_missing_release_version" } @@ -2561,8 +2588,12 @@ fn remote_plugin_bundle_install_error_type(err: &RemotePluginBundleInstallError) RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { .. } => { "remote_bundle_unsupported_download_final_url" } - RemotePluginBundleInstallError::ArchiveVerification { .. } => { - "remote_bundle_archive_verification" + RemotePluginBundleInstallError::ArchiveVerification { + plugin_release_id, + source, + .. + } => { + return PluginInstallTelemetry::archive_failed(*source, plugin_release_id.clone()); } RemotePluginBundleInstallError::ExtractedBundleTooLarge { .. } => { "remote_bundle_extracted_too_large" @@ -2570,7 +2601,12 @@ fn remote_plugin_bundle_install_error_type(err: &RemotePluginBundleInstallError) RemotePluginBundleInstallError::Io { .. } => "remote_bundle_io", RemotePluginBundleInstallError::InvalidBundle(_) => "remote_bundle_invalid_bundle", RemotePluginBundleInstallError::Store(_) => "remote_bundle_store", - } + }; + ( + error_type, + err.sub_error_type(), + PluginInstallTelemetry::default(), + ) } fn remote_plugin_catalog_error_to_jsonrpc( @@ -2618,7 +2654,7 @@ fn remote_plugin_operation_error_to_jsonrpc(err: RemotePluginOperationError) -> RemotePluginOperationErrorKind::Catalog { context, source } => { remote_plugin_catalog_error_to_jsonrpc(source, context) } - RemotePluginOperationErrorKind::Bundle(source) => { + RemotePluginOperationErrorKind::Bundle { source, .. } => { remote_plugin_bundle_install_error_to_jsonrpc(source) } RemotePluginOperationErrorKind::Sync { context, source } => { diff --git a/codex-rs/app-server/tests/common/analytics_server.rs b/codex-rs/app-server/tests/common/analytics_server.rs index 75b8df60ec..71ca4011d7 100644 --- a/codex-rs/app-server/tests/common/analytics_server.rs +++ b/codex-rs/app-server/tests/common/analytics_server.rs @@ -1,4 +1,6 @@ use anyhow::Result; +use std::time::Duration; +use tokio::time::timeout; use wiremock::Mock; use wiremock::MockServer; use wiremock::ResponseTemplate; @@ -14,3 +16,44 @@ pub async fn start_analytics_events_server() -> Result { .await; Ok(server) } + +pub async fn mount_backend_analytics_events(server: &MockServer) { + Mock::given(method("POST")) + .and(path("/backend-api/codex/analytics-events/events")) + .respond_with(ResponseTemplate::new(200).set_body_string(r#"{"status":"ok"}"#)) + .mount(server) + .await; +} + +pub async fn wait_for_plugin_analytics_payload( + server: &MockServer, + event_type: &str, +) -> Result { + timeout(Duration::from_secs(60), async { + loop { + let Some(requests) = server.received_requests().await else { + tokio::time::sleep(Duration::from_millis(25)).await; + continue; + }; + for request in requests.iter().filter(|request| { + request.method == "POST" + && request + .url + .path() + .ends_with("/codex/analytics-events/events") + }) { + let mut payload: serde_json::Value = serde_json::from_slice(&request.body) + .map_err(|err| anyhow::anyhow!("invalid analytics payload: {err}"))?; + let events = payload["events"] + .as_array_mut() + .ok_or_else(|| anyhow::anyhow!("analytics payload missing events array"))?; + events.retain(|event| event["event_type"] == event_type); + if !events.is_empty() { + return Ok(payload); + } + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + }) + .await? +} diff --git a/codex-rs/app-server/tests/common/lib.rs b/codex-rs/app-server/tests/common/lib.rs index 8335d6acba..dcbb49334d 100644 --- a/codex-rs/app-server/tests/common/lib.rs +++ b/codex-rs/app-server/tests/common/lib.rs @@ -12,7 +12,9 @@ mod rollout; mod rpc_delay; mod test_app_server; +pub use analytics_server::mount_backend_analytics_events; pub use analytics_server::start_analytics_events_server; +pub use analytics_server::wait_for_plugin_analytics_payload; pub use auth_fixtures::ChatGptAuthFixture; pub use auth_fixtures::ChatGptIdTokenClaims; pub use auth_fixtures::encode_id_token; 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 749f01f8e5..6e090970db 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_install.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_install.rs @@ -11,7 +11,9 @@ use anyhow::bail; use app_test_support::ChatGptAuthFixture; use app_test_support::DEFAULT_CLIENT_NAME; use app_test_support::TestAppServer; +use app_test_support::mount_backend_analytics_events; use app_test_support::start_analytics_events_server; +use app_test_support::wait_for_plugin_analytics_payload; use app_test_support::write_chatgpt_auth; use axum::Json; use axum::Router; @@ -1169,6 +1171,7 @@ async fn plugin_install_tracks_remote_plugin_analytics_event() -> Result<()> { "plugin_name": "linear", "marketplace_name": "openai-curated-remote", "has_skills": true, + "archive_verification": "not_required", "mcp_server_count": 0, "connector_ids": [], "product_client_id": DEFAULT_CLIENT_NAME, @@ -2874,47 +2877,6 @@ fn write_analytics_config(codex_home: &std::path::Path, base_url: &str) -> std:: ) } -async fn mount_backend_analytics_events(server: &MockServer) { - Mock::given(method("POST")) - .and(path("/backend-api/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(200).set_body_string(r#"{"status":"ok"}"#)) - .mount(server) - .await; -} - -async fn wait_for_plugin_analytics_payload( - server: &MockServer, - event_type: &str, -) -> Result { - timeout(DEFAULT_TIMEOUT, async { - loop { - let Some(requests) = server.received_requests().await else { - tokio::time::sleep(Duration::from_millis(25)).await; - continue; - }; - for request in requests.iter().filter(|request| { - request.method == "POST" - && request - .url - .path() - .ends_with("/codex/analytics-events/events") - }) { - let mut payload: serde_json::Value = serde_json::from_slice(&request.body) - .map_err(|err| anyhow::anyhow!("invalid analytics payload: {err}"))?; - let events = payload["events"] - .as_array_mut() - .ok_or_else(|| anyhow::anyhow!("analytics payload missing events array"))?; - events.retain(|event| event["event_type"] == event_type); - if !events.is_empty() { - return Ok(payload); - } - } - tokio::time::sleep(Duration::from_millis(25)).await; - } - }) - .await? -} - #[tokio::test] async fn plugin_analytics_wait_ignores_unrelated_requests_and_batched_events() -> Result<()> { let server = MockServer::start().await; diff --git a/codex-rs/cli/src/plugin_cmd.rs b/codex-rs/cli/src/plugin_cmd.rs index bc65acaf94..39d747dbce 100644 --- a/codex-rs/cli/src/plugin_cmd.rs +++ b/codex-rs/cli/src/plugin_cmd.rs @@ -32,6 +32,7 @@ use codex_core_plugins::remote::RemoteMarketplace; use codex_core_plugins::remote::RemoteMarketplaceSource; use codex_core_plugins::remote::RemotePluginCatalogCacheMode; use codex_core_plugins::remote::RemotePluginSummary; +use codex_core_plugins::remote_bundle::with_archive_verification_telemetry; use codex_login::AuthManager; use codex_login::CodexAuth; use codex_plugin::PluginId; @@ -45,6 +46,10 @@ use std::io::Write; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; +use tracing::Dispatch; +use tracing_subscriber::Layer; +use tracing_subscriber::filter::filter_fn; +use tracing_subscriber::layer::SubscriberExt; use crate::cloud_config; use crate::marketplace_cmd::MarketplaceCli; @@ -171,20 +176,34 @@ pub async fn run_plugin_add(overrides: &CliConfigOverrides, args: AddPluginArgs) .await?; } let plugin = resolve_remote_plugin(listing.marketplaces, &selection)?; - context - .manager - .install_remote_plugin( - &context.plugins_input, - context.auth.as_ref(), - RemotePluginInstallRequest { - marketplace_name: selection.marketplace_name, - remote_plugin_id: plugin.remote_plugin_id, - install_attempt_id: None, - }, - /*on_effective_plugins_changed*/ None, + let install = context.manager.install_remote_plugin( + &context.plugins_input, + context.auth.as_ref(), + RemotePluginInstallRequest { + marketplace_name: selection.marketplace_name, + remote_plugin_id: plugin.remote_plugin_id, + install_attempt_id: None, + }, + /*on_effective_plugins_changed*/ None, + ); + with_archive_verification_telemetry(install, |event_name| { + let provider = codex_core::otel_init::build_provider( + &context.config, + env!("CARGO_PKG_VERSION"), + /*service_name_override*/ None, + /*default_analytics_enabled*/ false, ) - .await? - .installed + .ok() + .flatten()?; + let dispatch = provider.logger_layer().map(|logger| { + let logger = + logger.with_filter(filter_fn(move |metadata| metadata.name() == event_name)); + Dispatch::new(tracing_subscriber::registry().with(logger)) + }); + Some((provider, dispatch)) + }) + .await? + .installed } else { let marketplace = find_marketplace_for_plugin( &context.manager, @@ -763,6 +782,8 @@ struct PluginCommandContext { plugins_input: PluginsConfigInput, manager: Arc, auth: Option, + // Keep the shared CLI dispatcher's stack frame small enough for interactive commands. + config: Box, } async fn load_plugin_command_context( @@ -802,6 +823,7 @@ async fn plugin_command_context_from_config( plugins_input, manager, auth, + config: Box::new(config), }) } diff --git a/codex-rs/core-plugins/src/manager.rs b/codex-rs/core-plugins/src/manager.rs index eed5afee66..04dfaa014c 100644 --- a/codex-rs/core-plugins/src/manager.rs +++ b/codex-rs/core-plugins/src/manager.rs @@ -2627,7 +2627,7 @@ impl PluginsManager { }; if let Some(analytics_events_client) = analytics_events_client { analytics_events_client.track_plugin_install_failed( - plugin, + plugin.into(), self.plugin_install_source, error_type.to_string(), sub_error_type, @@ -2700,7 +2700,8 @@ impl PluginsManager { if let Some(analytics_events_client) = analytics_events_client { analytics_events_client.track_plugin_installed( self.telemetry_metadata_for_installed_plugin(&result.plugin_id) - .await, + .await + .into(), ); } diff --git a/codex-rs/core-plugins/src/plugin_measurement_references.rs b/codex-rs/core-plugins/src/plugin_measurement_references.rs index 8f31a6eaab..5cd45329dd 100644 --- a/codex-rs/core-plugins/src/plugin_measurement_references.rs +++ b/codex-rs/core-plugins/src/plugin_measurement_references.rs @@ -209,7 +209,9 @@ impl RemotePluginMeasurementCache { biased; _ = sender.closed() => return, reference = async { - let bytes = download_remote_plugin_bundle(&service, Some(&auth), &bundle).await?; + let (bytes, _) = download_remote_plugin_bundle( + &service, Some(&auth), &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 || { 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 34822ae430..6da72b9c18 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 @@ -298,7 +298,7 @@ pub(crate) async fn sync_remote_installed_plugin_bundles_once_with_snapshot( ) .await { - Ok(result) => { + Ok((result, _)) => { let plugin_id = result.plugin_id; capabilities.include_active_bundle(&store, &plugin_id).await; changed_plugins.insert( diff --git a/codex-rs/core-plugins/src/remote_bundle.rs b/codex-rs/core-plugins/src/remote_bundle.rs index e4d31b831f..a6aaf32e96 100644 --- a/codex-rs/core-plugins/src/remote_bundle.rs +++ b/codex-rs/core-plugins/src/remote_bundle.rs @@ -31,7 +31,11 @@ use url::Host; use url::Url; use codex_plugin_archive_verification::ArchiveVerificationFailure; +pub use codex_plugin_archive_verification::PluginArchiveVerification; +pub use codex_plugin_archive_verification::PluginInstallTelemetry; +use codex_plugin_archive_verification::PluginReleaseId; use codex_plugin_archive_verification::RemotePluginArchiveDownload; +pub use codex_plugin_archive_verification::with_archive_verification_telemetry; const REMOTE_PLUGIN_BUNDLE_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(60); const REMOTE_PLUGIN_BUNDLE_MAX_DOWNLOAD_BYTES: u64 = 100 * 1024 * 1024; @@ -140,6 +144,7 @@ pub enum RemotePluginBundleInstallError { ArchiveVerification { plugin_id: String, plugin_version: String, + plugin_release_id: Option, #[source] source: ArchiveVerificationFailure, }, @@ -290,9 +295,9 @@ pub async fn download_and_install_remote_plugin_bundle( auth: Option<&CodexAuth>, codex_home: PathBuf, bundle: ValidatedRemotePluginBundle, -) -> Result { - let bundle_bytes = download_remote_plugin_bundle(config, auth, &bundle).await?; - tokio::task::spawn_blocking(move || { +) -> Result<(PluginInstallResult, PluginArchiveVerification), RemotePluginBundleInstallError> { + let (bundle_bytes, verification) = download_remote_plugin_bundle(config, auth, &bundle).await?; + let installed = tokio::task::spawn_blocking(move || { install_remote_plugin_bundle(codex_home, bundle, bundle_bytes) }) .await @@ -300,7 +305,8 @@ pub async fn download_and_install_remote_plugin_bundle( RemotePluginBundleInstallError::InvalidBundle(format!( "failed to join remote plugin bundle install task: {err}" )) - })? + })??; + Ok((installed, verification)) } pub(crate) async fn download_and_extract_remote_plugin_bundle_to_path( @@ -309,7 +315,7 @@ pub(crate) async fn download_and_extract_remote_plugin_bundle_to_path( bundle: ValidatedRemotePluginBundle, destination: AbsolutePathBuf, ) -> Result { - let bundle_bytes = download_remote_plugin_bundle(config, auth, &bundle).await?; + let (bundle_bytes, _) = download_remote_plugin_bundle(config, auth, &bundle).await?; tokio::task::spawn_blocking(move || { extract_remote_plugin_bundle_to_path(bundle, bundle_bytes, destination) }) @@ -325,7 +331,7 @@ pub(crate) async fn download_remote_plugin_bundle( config: &RemotePluginServiceConfig, auth: Option<&CodexAuth>, bundle: &ValidatedRemotePluginBundle, -) -> Result, RemotePluginBundleInstallError> { +) -> Result<(Vec, PluginArchiveVerification), RemotePluginBundleInstallError> { let bytes = download_remote_plugin_bundle_with_limit( config, &bundle.bundle_download_url, @@ -341,11 +347,11 @@ pub(crate) async fn download_remote_plugin_bundle( |url| prepare_signing_key_request(config, url, auth), ) .await - .map(|(bytes, _)| bytes) .map_err( |source| RemotePluginBundleInstallError::ArchiveVerification { plugin_id: bundle.plugin_id.as_key(), plugin_version: bundle.plugin_version.clone(), + plugin_release_id: bundle.archive_download.release_id().cloned(), source, }, ) diff --git a/codex-rs/core-plugins/src/remote_bundle_signing_key_cache_tests.rs b/codex-rs/core-plugins/src/remote_bundle_signing_key_cache_tests.rs index 0e2ad9fa0d..049c2155b9 100644 --- a/codex-rs/core-plugins/src/remote_bundle_signing_key_cache_tests.rs +++ b/codex-rs/core-plugins/src/remote_bundle_signing_key_cache_tests.rs @@ -74,7 +74,7 @@ async fn signed_downloads_reuse_keys_only_within_the_same_plugin_manager() -> an .for_current_account(); assert_eq!( download_remote_plugin_bundle(&service, Some(&auth), &bundle).await?, - archive + (archive.clone(), PluginArchiveVerification::Verified) ); let requests = server.received_requests().await.unwrap(); assert_eq!( diff --git a/codex-rs/core-plugins/src/remote_mutations.rs b/codex-rs/core-plugins/src/remote_mutations.rs index 5d103642ca..674dc6e178 100644 --- a/codex-rs/core-plugins/src/remote_mutations.rs +++ b/codex-rs/core-plugins/src/remote_mutations.rs @@ -13,6 +13,7 @@ use crate::remote::RemotePluginCacheMutationGuard; use crate::remote::RemotePluginCatalogError; use crate::remote::RemotePluginDetail; use crate::remote_bundle; +use crate::remote_bundle::PluginArchiveVerification; use crate::remote_bundle::RemotePluginBundleInstallError; use codex_app_server_protocol::PluginAuthPolicy; use codex_app_server_protocol::PluginAvailability; @@ -36,6 +37,7 @@ pub struct RemotePluginInstallRequest { #[must_use] pub struct RemotePluginInstallOutcome { pub installed: PluginInstallOutcome, + pub archive_verification: PluginArchiveVerification, pub detail: RemotePluginDetail, pub app_ids_needing_auth: Option>, _cache_mutation: RemotePluginCacheMutationGuard, @@ -63,8 +65,12 @@ pub enum RemotePluginOperationErrorKind { context: &'static str, source: RemotePluginCatalogError, }, - #[error("install remote plugin bundle: {0}")] - Bundle(#[source] RemotePluginBundleInstallError), + #[error("install remote plugin bundle: {source}")] + Bundle { + catalog_plugin_id: String, + #[source] + source: RemotePluginBundleInstallError, + }, #[error("{context}: {source}")] Sync { context: &'static str, @@ -138,6 +144,12 @@ impl PluginsManager { if detail.summary.install_policy == PluginInstallPolicy::NotAvailable { return Err(resolved(Error::NotAvailable(remote_plugin_id))); } + let bundle_error = |source| { + resolved(Error::Bundle { + catalog_plugin_id: detail.summary.remote_plugin_id.clone(), + source, + }) + }; let bundle = remote_bundle::validate_remote_plugin_bundle( &remote_plugin_id, &detail.marketplace_name, @@ -146,7 +158,7 @@ impl PluginsManager { &detail.archive_download, detail.app_manifest.clone(), ) - .map_err(|err| resolved(Error::Bundle(err)))?; + .map_err(bundle_error)?; let _sync_guard = self .acquire_remote_installed_plugin_sync_guard() .await @@ -162,14 +174,15 @@ impl PluginsManager { &detail.summary.name, ); // Materialize first: a failed download must never leave a backend installation behind. - let installed = remote_bundle::download_and_install_remote_plugin_bundle( - &service, - auth, - self.codex_home.clone(), - bundle, - ) - .await - .map_err(|err| resolved(Error::Bundle(err)))?; + let (installed, archive_verification) = + remote_bundle::download_and_install_remote_plugin_bundle( + &service, + auth, + self.codex_home.clone(), + bundle, + ) + .await + .map_err(bundle_error)?; let install_result = if let Some(install_attempt_id) = install_attempt_id.as_deref() { remote::install_remote_plugin_with_install_attempt_id( &service, @@ -200,6 +213,7 @@ impl PluginsManager { on_effective_plugins_changed, ); Ok(RemotePluginInstallOutcome { + archive_verification, installed: PluginInstallOutcome { plugin_id: installed.plugin_id, plugin_version: installed.plugin_version, diff --git a/codex-rs/core-plugins/src/remote_mutations_tests.rs b/codex-rs/core-plugins/src/remote_mutations_tests.rs index f82d3bc4f1..6b977e3326 100644 --- a/codex-rs/core-plugins/src/remote_mutations_tests.rs +++ b/codex-rs/core-plugins/src/remote_mutations_tests.rs @@ -444,14 +444,15 @@ async fn plugin_install_keeps_account_binding_through_storage_download() { assert!( matches!( *error.kind, - RemotePluginOperationErrorKind::Bundle( - RemotePluginBundleInstallError::DownloadRequest { + RemotePluginOperationErrorKind::Bundle { + source: RemotePluginBundleInstallError::DownloadRequest { source: RouteAwareRequestError::Policy( NetworkPolicyDenied::Revoked ), .. - } - ) + }, + .. + } ), "{error:?}" ); @@ -460,9 +461,11 @@ async fn plugin_install_keeps_account_binding_through_storage_download() { assert!( matches!( *error.kind, - RemotePluginOperationErrorKind::Bundle( - RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { .. } - ) + RemotePluginOperationErrorKind::Bundle { + source: + RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { .. }, + .. + } ), "{error:?}" ); diff --git a/codex-rs/plugin-archive-verification/BUILD.bazel b/codex-rs/plugin-archive-verification/BUILD.bazel index 6acead5321..a5281ecf1f 100644 --- a/codex-rs/plugin-archive-verification/BUILD.bazel +++ b/codex-rs/plugin-archive-verification/BUILD.bazel @@ -13,6 +13,7 @@ codex_rust_crate( "//codex-rs/app-server:codex-app-server", "//codex-rs/app-server:exec-server", "//codex-rs/bwrap:bwrap", + "//codex-rs/cli:codex", "//codex-rs/code-mode-host:codex-code-mode-host", ], integration_compile_data_extra = ["testdata/plugin_archive_signing_v1.json"], diff --git a/codex-rs/plugin-archive-verification/Cargo.toml b/codex-rs/plugin-archive-verification/Cargo.toml index eaf0e4b801..8659a5d322 100644 --- a/codex-rs/plugin-archive-verification/Cargo.toml +++ b/codex-rs/plugin-archive-verification/Cargo.toml @@ -31,8 +31,9 @@ codex-config = { workspace = true } codex-core-plugins = { workspace = true } codex-exec-server = { workspace = true } codex-login = { workspace = true } +codex-utils-cargo-bin = { workspace = true } codex-utils-path-uri = { workspace = true } pretty_assertions = { workspace = true } tempfile = { workspace = true } -tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] } +tokio = { workspace = true, features = ["macros", "process", "rt-multi-thread", "time"] } wiremock = { workspace = true } diff --git a/codex-rs/plugin-archive-verification/src/archive_verification.rs b/codex-rs/plugin-archive-verification/src/archive_verification.rs index 3f983e5495..a0d795d1d4 100644 --- a/codex-rs/plugin-archive-verification/src/archive_verification.rs +++ b/codex-rs/plugin-archive-verification/src/archive_verification.rs @@ -25,16 +25,39 @@ const MAX_SIGNATURE_BASE64_BYTES: usize = 2048; const MAX_KEY_ID_BYTES: usize = 512; pub(super) const ARCHIVE_VERIFICATION_EVENT: &str = "codex.plugins.archive_verification"; +/// A service-generated Plugin Service release ID that identifies an exact plugin release. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(transparent)] +pub struct PluginReleaseId(String); + /// Download metadata supplied with an authorized Plugin Service archive URL. -/// Signing metadata is deliberately omitted when catalog responses are persisted. +/// Verification metadata is deliberately omitted when catalog responses are persisted. #[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] pub struct RemotePluginArchiveDownload { #[serde(default)] pub bundle_download_url: Option, + #[serde( + default, + rename = "id", + deserialize_with = "deserialize_release_id", + skip_serializing + )] + release_id: Option, #[serde(default, skip_serializing)] signing: ArchiveVerification, } +// Malformed or missing telemetry metadata must not affect verification. +fn deserialize_release_id<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + let value = Value::deserialize(deserializer)?; + let Value::String(id) = value else { + return Ok(None); + }; + Ok((!id.is_empty()).then_some(PluginReleaseId(id))) +} + #[derive(Debug, Clone, Default, PartialEq, Eq)] enum ArchiveVerification { #[default] @@ -187,10 +210,14 @@ impl RemotePluginArchiveDownload { pub fn new(bundle_download_url: Option) -> Self { Self { bundle_download_url, - signing: ArchiveVerification::Absent, + ..Self::default() } } + pub fn release_id(&self) -> Option<&PluginReleaseId> { + self.release_id.as_ref() + } + /// Checks the downloaded bytes before they can be extracted. The key request must /// use the authorized Plugin Service route and return its resolved authentication headers. pub async fn verify( @@ -261,6 +288,15 @@ impl RemotePluginArchiveDownload { &tags, ); } + tracing::event!( + name: ARCHIVE_VERIFICATION_EVENT, + target: "codex_otel.log_only", + tracing::Level::INFO, + event.name = ARCHIVE_VERIFICATION_EVENT, + outcome, + archive_kind, + plugin_release_id = self.release_id().map(|id| id.0.as_str()), + ); result } } diff --git a/codex-rs/plugin-archive-verification/src/archive_verification_tests.rs b/codex-rs/plugin-archive-verification/src/archive_verification_tests.rs index 55f88cad33..c5e81f1fc4 100644 --- a/codex-rs/plugin-archive-verification/src/archive_verification_tests.rs +++ b/codex-rs/plugin-archive-verification/src/archive_verification_tests.rs @@ -257,19 +257,26 @@ async fn rejects_keys_with_unsupported_purpose_algorithm_or_invalid_material() { } #[test] -fn retains_signing_metadata_only_for_download() { +fn retains_verification_metadata_only_for_download() { let url = "https://example.com/archive"; let signing = json!({"sha256": "digest", "key_id": "key", "signature": "signature", "algorithm": "algorithm"}); - let release = json!({"bundle_download_url": url, "signing": signing}); + let release_id = "pluginrel_0123456789abcdef0123456789abcdef"; + let release = json!({"id": release_id, "bundle_download_url": url, "signing": signing}); let download: RemotePluginArchiveDownload = serde_json::from_value(release).unwrap(); + assert_eq!( + download.release_id(), + Some(&PluginReleaseId(release_id.to_owned())) + ); assert!(matches!(download.signing, ArchiveVerification::Present(_))); assert_eq!( serde_json::to_value(&download).unwrap(), json!({"bundle_download_url": url}) ); let malformed: RemotePluginArchiveDownload = - serde_json::from_value(json!({"signing": {}})).unwrap(); + serde_json::from_value(json!({"id": {"unexpected": "object"}, "signing": {}})).unwrap(); + assert_eq!(malformed.release_id(), None); assert_eq!(malformed.signing, ArchiveVerification::Malformed); let unsigned: RemotePluginArchiveDownload = serde_json::from_value(json!({})).unwrap(); + assert_eq!(unsigned.release_id(), None); assert_eq!(unsigned.signing, ArchiveVerification::Absent); } diff --git a/codex-rs/plugin-archive-verification/src/cli_telemetry.rs b/codex-rs/plugin-archive-verification/src/cli_telemetry.rs new file mode 100644 index 0000000000..cad86aecab --- /dev/null +++ b/codex-rs/plugin-archive-verification/src/cli_telemetry.rs @@ -0,0 +1,26 @@ +//! Controls archive verification telemetry during a standalone remote install. + +use codex_otel::OtelProvider; +use std::time::Duration; +use tracing::Dispatch; +use tracing::instrument::WithSubscriber; + +use crate::archive_verification::ARCHIVE_VERIFICATION_EVENT; + +pub async fn with_archive_verification_telemetry( + install: F, + telemetry: impl FnOnce(&'static str) -> Option<(OtelProvider, Option)>, +) -> F::Output { + let Some((provider, dispatch)) = telemetry(ARCHIVE_VERIFICATION_EVENT) else { + return install.await; + }; + let result = if let Some(dispatch) = dispatch { + install.with_subscriber(dispatch).await + } else { + install.await + }; + let _ = provider + .shutdown_with_timeout(Duration::from_secs(/*secs*/ 2)) + .await; + result +} diff --git a/codex-rs/plugin-archive-verification/src/install_telemetry.rs b/codex-rs/plugin-archive-verification/src/install_telemetry.rs new file mode 100644 index 0000000000..06d737e714 --- /dev/null +++ b/codex-rs/plugin-archive-verification/src/install_telemetry.rs @@ -0,0 +1,42 @@ +//! Supplies archive-specific fields and attribution for remote plugin install analytics. + +use crate::ArchiveVerificationFailure; +use crate::PluginArchiveVerification; +use crate::PluginReleaseId; +use serde::Serialize; + +/// Fields flattened into an existing plugin install or install-failed event. +#[derive(Debug, Default, Serialize)] +pub struct PluginInstallTelemetry { + #[serde(skip_serializing_if = "Option::is_none")] + archive_verification: Option<&'static str>, + #[serde(skip_serializing_if = "Option::is_none")] + plugin_release_id: Option, +} + +impl PluginInstallTelemetry { + pub fn installed(verification: PluginArchiveVerification) -> Self { + Self { + archive_verification: Some(verification.as_str()), + ..Self::default() + } + } + + pub fn remote_plugin_id<'a>(requested: &'a str, catalog: Option<&'a str>) -> &'a str { + catalog.unwrap_or(requested) + } + + pub fn archive_failed( + failure: ArchiveVerificationFailure, + plugin_release_id: Option, + ) -> (&'static str, Option, Self) { + ( + "remote_bundle_archive_verification", + Some(failure.as_str().to_owned()), + Self { + plugin_release_id, + ..Self::default() + }, + ) + } +} diff --git a/codex-rs/plugin-archive-verification/src/lib.rs b/codex-rs/plugin-archive-verification/src/lib.rs index 0fe63ebc17..76fce47b76 100644 --- a/codex-rs/plugin-archive-verification/src/lib.rs +++ b/codex-rs/plugin-archive-verification/src/lib.rs @@ -1,5 +1,7 @@ mod archive_signing_keys; mod archive_verification; +mod cli_telemetry; +mod install_telemetry; #[cfg(test)] mod test_support; @@ -7,4 +9,7 @@ mod test_support; pub use archive_signing_keys::SigningKeyCache; pub use archive_verification::ArchiveVerificationFailure; pub use archive_verification::PluginArchiveVerification; +pub use archive_verification::PluginReleaseId; pub use archive_verification::RemotePluginArchiveDownload; +pub use cli_telemetry::with_archive_verification_telemetry; +pub use install_telemetry::PluginInstallTelemetry; diff --git a/codex-rs/plugin-archive-verification/tests/app_server.rs b/codex-rs/plugin-archive-verification/tests/app_server.rs index a9efed2f27..3282880eef 100644 --- a/codex-rs/plugin-archive-verification/tests/app_server.rs +++ b/codex-rs/plugin-archive-verification/tests/app_server.rs @@ -7,6 +7,8 @@ use anyhow::Result; use app_test_support::ChatGptAuthFixture; use app_test_support::TestAppServer; use app_test_support::TestAppServerBuilder; +use app_test_support::mount_backend_analytics_events; +use app_test_support::wait_for_plugin_analytics_payload; use app_test_support::write_chatgpt_auth; use codex_app_server_protocol::PluginAuthPolicy; use codex_app_server_protocol::PluginInstallParams; @@ -440,40 +442,46 @@ async fn share_checkout_verifies_before_writing_local_files() -> Result<()> { #[tokio::test] async fn install_verifies_eval_archives_before_cloud_mutation() -> Result<()> { let mut fixture = PluginArchiveSigningFixture::load()?; + let release_id = "pluginrel_0123456789abcdef0123456789abcdef"; let mut eval_key = fixture.signing_keys_response["keys"][0].clone(); eval_key["key_id"] = json!("scoped-eval-key"); eval_key["purpose"] = json!("EVAL_PLUGIN_RELEASE_ARCHIVE_SIGNING"); fixture.signing_keys_response["eval_keys"] = json!([eval_key]); fixture.signing["key_id"] = json!("scoped-eval-key"); - for tampered in [false, true] { + for (archive, expected_outcome, backend_rejects) in [ + (fixture.archive.clone(), Some("verified"), false), + (fixture.archive.clone(), None, true), + (tampered_archive(fixture.archive.clone()), None, false), + ] { + let materialized = expected_outcome.is_some() || backend_rejects; let server = MockServer::start().await; let codex_home = TempDir::new()?; let installed = codex_home.path().join(CACHE_DIR).join("1.2.3"); let requested_id = "linear-alias"; let mut plugin = catalog_plugin(&server, "1.2.3"); + plugin["release"]["id"] = json!(release_id); plugin["release"]["signing"] = fixture.signing.clone(); catalog_detail(requested_id, plugin).mount(&server).await; installed_snapshot(query_param("scope", "GLOBAL"), Vec::new()) .mount(&server) .await; - let archive = fixture.archive.clone(); - bundle(if tampered { - tampered_archive(archive) - } else { - archive - }) - .expect(1) - .mount(&server) - .await; + bundle(archive).expect(1).mount(&server).await; signing_keys(ResponseTemplate::new(200).set_body_json(&fixture.signing_keys_response)) - .expect(u64::from(!tampered)) + .expect(u64::from(materialized)) .mount(&server) .await; + let install_response = if backend_rejects { + ResponseTemplate::new(429) + } else { + remote_plugin_install_response(requested_id) + }; remote_plugin_install(requested_id) .and(CacheManifestExists(installed.join(MANIFEST))) - .respond_with(remote_plugin_install_response(requested_id)) + .respond_with(install_response) + .expect(u64::from(materialized)) .mount(&server) .await; + mount_backend_analytics_events(&server).await; let mut app = app_server(&server, codex_home.path())? .build_initialized() .await?; @@ -486,7 +494,14 @@ async fn install_verifies_eval_archives_before_cloud_mutation() -> Result<()> { plugin_name: requested_id.to_owned(), }) .await?; - if tampered { + if backend_rejects { + let err = timeout( + DEFAULT_TIMEOUT, + app.read_stream_until_error_message(RequestId::Integer(id)), + ) + .await??; + assert!(err.error.message.contains("failed with status 429")); + } else if !materialized { assert_digest_error(&mut app, id).await?; } else { let response: PluginInstallResponse = @@ -499,17 +514,65 @@ async fn install_verifies_eval_archives_before_cloud_mutation() -> Result<()> { } ); } - assert_eq!(installed.is_dir(), !tampered); + let event_type = if expected_outcome.is_some() { + "codex_plugin_installed" + } else { + "codex_plugin_install_failed" + }; + let payload = wait_for_plugin_analytics_payload(&server, event_type).await?; + let params = &payload["events"][0]["event_params"]; + assert_eq!( + params["remote_plugin_id"], + if backend_rejects { + requested_id + } else { + REMOTE_PLUGIN_ID + } + ); + assert_eq!( + params.get("plugin_release_id"), + (!materialized).then_some(&json!(release_id)), + ); + if let Some(outcome) = expected_outcome { + assert_eq!(params["archive_verification"], outcome); + } else { + assert!(params.get("archive_verification").is_none()); + let (error_type, sub_error_type) = if backend_rejects { + ("remote_catalog_unexpected_status", "http_429") + } else { + ("remote_bundle_archive_verification", "digest_mismatch") + }; + assert_eq!(params["error_type"], error_type); + assert_eq!(params["sub_error_type"], sub_error_type); + } + assert_eq!(installed.is_dir(), materialized); let requests = server .received_requests() .await .context("recorded requests")?; + if expected_outcome.is_none() { + // The analytics worker sends facts in order. A premature success would + // have reached the server by the time the failure was observed above. + for request in requests + .iter() + .filter(|req| req.url.path().ends_with("/codex/analytics-events/events")) + { + let batch = request.body_json::()?; + assert!( + batch["events"] + .as_array() + .context("analytics events")? + .iter() + .all(|event| event["event_type"] != "codex_plugin_installed") + ); + } + } assert_eq!( requests .iter() .filter(|req| req.method == "POST" && req.url.path().ends_with("/install")) .count(), - usize::from(!tampered) + usize::from(materialized) ); } Ok(()) diff --git a/codex-rs/plugin-archive-verification/tests/cli.rs b/codex-rs/plugin-archive-verification/tests/cli.rs new file mode 100644 index 0000000000..4b55f3182b --- /dev/null +++ b/codex-rs/plugin-archive-verification/tests/cli.rs @@ -0,0 +1,198 @@ +//! Exercises archive verification and OTLP export from the standalone remote plugin installer. + +mod common; + +use anyhow::Context; +use anyhow::Result; +use app_test_support::ChatGptAuthFixture; +use app_test_support::write_chatgpt_auth; +use codex_config::types::AuthCredentialsStoreMode; +use codex_utils_cargo_bin::cargo_bin; +use common::ALLOW_HTTP_BUNDLE_DOWNLOADS; +use common::PluginArchiveSigningFixture; +use pretty_assertions::assert_eq; +use serde_json::Value; +use serde_json::json; +use tempfile::TempDir; +use tokio::process::Command; +use wiremock::Mock; +use wiremock::MockServer; +use wiremock::ResponseTemplate; +use wiremock::matchers::header; +use wiremock::matchers::method; +use wiremock::matchers::path; +use wiremock::matchers::query_param; + +const MARKETPLACE: &str = "openai-curated-remote"; +const REMOTE_ID: &str = "plugins~Plugin_0123456789abcdef0123456789abcdef"; +const RELEASE_ID: &str = "pluginrel_0123456789abcdef0123456789abcdef"; + +#[tokio::test] +async fn remote_plugin_install_enforces_archive_signatures_before_mutation() -> Result<()> { + let fixture = PluginArchiveSigningFixture::load()?; + let home = TempDir::new()?; + let server = MockServer::start().await; + std::fs::write( + home.path().join("config.toml"), + format!( + r#" +cli_auth_credentials_store = "file" +chatgpt_base_url = "{}/backend-api" + +[features] +plugins = true +remote_plugin = true +"#, + server.uri() + ), + )?; + write_chatgpt_auth( + home.path(), + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .chatgpt_account_id("account-123"), + AuthCredentialsStoreMode::File, + )?; + + let private_version = "1.2.3+private-catalog-marker"; + let mut plugin = json!({ + "id": REMOTE_ID, "name": "linear", "scope": "GLOBAL", + "installation_policy": "AVAILABLE", "authentication_policy": "ON_USE", + "release": { + "id": RELEASE_ID, "version": private_version, + "display_name": "Linear", "description": "Track issues", + "interface": {}, "bundle_download_url": format!("{}/bundle", server.uri()), + } + }); + Mock::given(method("GET")) + .and(path("/backend-api/ps/plugins/list")) + .and(query_param("scope", "GLOBAL")) + .and(header("authorization", "Bearer chatgpt-token")) + .and(header("chatgpt-account-id", "account-123")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "plugins": [plugin.clone()], "pagination": {"next_page_token": null} + }))) + .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": {"next_page_token": null} + }))) + .mount(&server) + .await; + + plugin["release"]["signing"] = fixture.signing; + Mock::given(method("GET")) + .and(path(format!("/backend-api/ps/plugins/{REMOTE_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(plugin)) + .expect(1) + .mount(&server) + .await; + + let mut archive = fixture.archive; + // Changing gzip mtime preserves extraction but invalidates the signed digest. + archive[4] ^= 1; + Mock::given(method("GET")) + .and(path("/bundle")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(archive)) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/backend-api/ps/plugins/signing-keys")) + .respond_with(ResponseTemplate::new(200).set_body_json(fixture.signing_keys_response)) + .expect(0) + .mount(&server) + .await; + + let collector = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v1/logs")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({}))) + .expect(1) + .mount(&collector) + .await; + let log_exporter = format!( + r#"otel.exporter={{otlp-http={{endpoint="{}/v1/logs",protocol="json"}}}}"#, + collector.uri(), + ); + let output = Command::new(cargo_bin("codex")?) + .current_dir(home.path()) + .env("CODEX_HOME", home.path()) + .env("HOME", home.path()) + .env("USERPROFILE", home.path()) + // Use the synthetic ChatGPT session even on a workload-identity devbox. + .env_remove("OPENAI_API_KEY") + .env_remove("CODEX_API_KEY") + .env_remove("CODEX_ACCESS_TOKEN") + .env_remove("OPENAI_FEDERATION_RULE_ID") + .env_remove("OPENAI_IDENTITY_TOKEN_FILE") + .env_remove("OPENAI_IDENTITY_TOKEN_SOURCE") + .env_remove("OPENAI_SPIFFE_AUDIENCE") + .env_remove("OPENAI_SPIFFE_ID") + .env_remove("OPENAI_WORKLOAD_IDENTITY_CONTEXT") + .env(ALLOW_HTTP_BUNDLE_DOWNLOADS, "1") + .args([ + "-c", + &log_exporter, + "plugin", + "add", + "linear", + "-m", + MARKETPLACE, + ]) + .output() + .await?; + assert!(!output.status.success()); + let stderr = String::from_utf8(output.stderr)?; + let expected = format!( + "plugin `linear@{MARKETPLACE}` version `{private_version}` failed archive verification: archive digest does not match its signed metadata" + ); + assert!(stderr.contains(&expected), "{stderr}"); + + let logs = collector + .received_requests() + .await + .context("recorded logs")?; + let payload = logs + .first() + .context("missing exported log")? + .body_json::()?; + assert!(!payload.to_string().contains(private_version)); + let attributes = payload["resourceLogs"][0]["scopeLogs"][0]["logRecords"][0]["attributes"] + .as_array() + .context("missing log attributes")?; + let fields = [ + ("event.name", "codex.plugins.archive_verification"), + ("outcome", "digest_mismatch"), + ("archive_kind", "unknown"), + ("plugin_release_id", RELEASE_ID), + ]; + assert_eq!(attributes.len(), fields.len()); + for (key, value) in fields { + assert!( + attributes.contains(&json!({"key": key, "value": {"stringValue": value}})), + "{attributes:?}" + ); + } + + let requests = server + .received_requests() + .await + .context("recorded requests")?; + assert!(requests.iter().all(|request| request.method != "POST")); + assert!( + !home + .path() + .join("plugins/cache/openai-curated-remote/linear") + .join(private_version) + .join(".codex-plugin/plugin.json") + .is_file() + ); + Ok(()) +}