mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
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
This commit is contained in:
Generated
+2
@@ -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",
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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<String>,
|
||||
@@ -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,
|
||||
}),
|
||||
));
|
||||
|
||||
@@ -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()),
|
||||
|
||||
@@ -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<String>,
|
||||
pub(crate) remote_plugin_id: Option<String>,
|
||||
pub(crate) plugin_name: Option<String>,
|
||||
@@ -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<PluginEventMetadata> 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
|
||||
|
||||
@@ -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<PluginTelemetryMetadata> 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<String>,
|
||||
@@ -772,7 +788,6 @@ pub struct ExternalAgentConfigImportFailureInput {
|
||||
pub sub_error_type: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum PluginState {
|
||||
Installed,
|
||||
Uninstalled,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<String>,
|
||||
(error_type, sub_error_type): (&'static str, Option<String>),
|
||||
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<String>, 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 } => {
|
||||
|
||||
@@ -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<MockServer> {
|
||||
.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<serde_json::Value> {
|
||||
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?
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<serde_json::Value> {
|
||||
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;
|
||||
|
||||
@@ -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<PluginsManager>,
|
||||
auth: Option<CodexAuth>,
|
||||
// Keep the shared CLI dispatcher's stack frame small enough for interactive commands.
|
||||
config: Box<Config>,
|
||||
}
|
||||
|
||||
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),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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(),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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 || {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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<PluginReleaseId>,
|
||||
#[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<PluginInstallResult, RemotePluginBundleInstallError> {
|
||||
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<AbsolutePathBuf, RemotePluginBundleInstallError> {
|
||||
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<Vec<u8>, RemotePluginBundleInstallError> {
|
||||
) -> Result<(Vec<u8>, 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,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -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<Vec<String>>,
|
||||
_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,
|
||||
|
||||
@@ -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:?}"
|
||||
);
|
||||
|
||||
@@ -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"],
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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<String>,
|
||||
#[serde(
|
||||
default,
|
||||
rename = "id",
|
||||
deserialize_with = "deserialize_release_id",
|
||||
skip_serializing
|
||||
)]
|
||||
release_id: Option<PluginReleaseId>,
|
||||
#[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<Option<PluginReleaseId>, 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<String>) -> 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<Fut>(
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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<F: Future>(
|
||||
install: F,
|
||||
telemetry: impl FnOnce(&'static str) -> Option<(OtelProvider, Option<Dispatch>)>,
|
||||
) -> 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
|
||||
}
|
||||
@@ -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<PluginReleaseId>,
|
||||
}
|
||||
|
||||
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<PluginReleaseId>,
|
||||
) -> (&'static str, Option<String>, Self) {
|
||||
(
|
||||
"remote_bundle_archive_verification",
|
||||
Some(failure.as_str().to_owned()),
|
||||
Self {
|
||||
plugin_release_id,
|
||||
..Self::default()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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::<Value>()?;
|
||||
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(())
|
||||
|
||||
@@ -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::<Value>()?;
|
||||
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(())
|
||||
}
|
||||
Reference in New Issue
Block a user