aKode fase 2c: eliminato il codice di invio dati (crate analytics, otel-trace-websocket, sentry, esportatori OTLP); /feedback salva solo in locale; chiavi legacy [analytics]/[otel] accettate e ignorate; test di analytics/OTLP/upload rimossi
Some checks failed
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled

This commit is contained in:
Andrea
2026-11-09 18:45:41 +01:00
parent 981745ccc8
commit 60532b6337
509 changed files with 2043 additions and 46606 deletions

View File

@@ -16,7 +16,6 @@ workspace = true
codex-utils-process = { workspace = true }
anyhow = { workspace = true }
chrono = { workspace = true }
codex-analytics = { workspace = true }
codex-api = { workspace = true }
codex-app-server-protocol = { workspace = true }
codex-config = { workspace = true }

View File

@@ -22,8 +22,6 @@ mod marketplace_staging;
pub mod marketplace_upgrade;
mod npm_source;
mod plugin_bundle_archive;
mod plugin_metrics;
mod plugin_metrics_sidecar;
mod provider;
mod recommended_plugin_install;
pub mod remote;
@@ -107,13 +105,6 @@ pub use marketplace_policy::allowed_configured_marketplace_names;
pub use marketplace_upgrade::ConfigLayerReload;
pub use marketplace_upgrade::ConfiguredMarketplaceUpgradeError as PluginMarketplaceUpgradeError;
pub use marketplace_upgrade::ConfiguredMarketplaceUpgradeOutcome as PluginMarketplaceUpgradeOutcome;
pub use plugin_metrics::PluginMeasurementDefinition;
pub use plugin_metrics::PluginMetricsOperation;
pub use plugin_metrics::ResolvedPluginMetricsOperation;
pub use plugin_metrics_sidecar::PLUGIN_METRICS_OUTPUT_ENV_VAR;
pub use plugin_metrics_sidecar::PluginMeasurementBatch;
pub use plugin_metrics_sidecar::PluginMetricsSidecar;
pub use plugin_metrics_sidecar::strip_output_env;
pub use provider::PluginListQuery;
pub use provider::PluginProvider;
pub use provider::PluginProviderError;
@@ -124,7 +115,6 @@ pub use remote::RecommendedPlugin;
pub use remote::RecommendedPluginsMode;
pub use remote_metadata::remote_catalog_metadata_eq;
pub use script_attribution::PluginCommandAttribution;
pub use script_attribution::PluginMeasurementTarget;
pub use script_attribution::TrustedPluginRoots;
pub use script_attribution::command_script_arguments;

View File

@@ -91,8 +91,6 @@ use crate::store::PluginInstallResult as StorePluginInstallResult;
use crate::store::PluginStore;
use crate::store::PluginStoreError;
use crate::tool_suggest_metadata::ToolSuggestMetadataCache;
use codex_analytics::AnalyticsEventsClient;
use codex_analytics::PluginInstallSource;
use codex_config::ConfigLayerStack;
use codex_config::SkillConfigRules;
use codex_config::clear_user_plugin;
@@ -322,7 +320,7 @@ enum RemoteInstalledPluginsCachePublication {
/// remote plugin mutations.
///
/// Callers should keep this guard only while mutating the remote plugin cache and backend
/// installed state, then release it before unrelated analytics, OAuth, or runtime refresh work.
/// installed state, then release it before unrelated OAuth or runtime refresh work.
struct RemoteInstalledPluginSyncGuard {
_permit: OwnedSemaphorePermit,
}
@@ -595,8 +593,6 @@ pub struct PluginsManager {
restriction_product: Option<Product>,
auth_manager: Arc<AuthManager>,
runtime_auth: RuntimeAuthSlot,
analytics_events_client: RwLock<Option<AnalyticsEventsClient>>,
plugin_install_source: PluginInstallSource,
}
#[derive(Clone)]
@@ -737,7 +733,6 @@ impl PluginsManager {
runtime_auth,
Arc::clone(&self.skill_root_loader),
)
.with_plugin_install_source(self.plugin_install_source)
}
pub fn new(
@@ -803,16 +798,9 @@ impl PluginsManager {
restriction_product,
auth_manager,
runtime_auth,
analytics_events_client: RwLock::new(None),
plugin_install_source: PluginInstallSource::Manual,
}
}
pub fn with_plugin_install_source(mut self, source: PluginInstallSource) -> Self {
self.plugin_install_source = source;
self
}
pub fn auth_mode(&self) -> Option<AuthMode> {
self.auth_manager.get_api_auth_mode()
}
@@ -821,14 +809,6 @@ impl PluginsManager {
config.remote_plugin_enabled && self.auth_mode().is_some_and(AuthMode::uses_codex_backend)
}
pub fn set_analytics_events_client(&self, analytics_events_client: AnalyticsEventsClient) {
let mut stored_client = match self.analytics_events_client.write() {
Ok(client_guard) => client_guard,
Err(err) => err.into_inner(),
};
*stored_client = Some(analytics_events_client);
}
fn restriction_product_matches(&self, products: Option<&[Product]>) -> bool {
match products {
None => true,
@@ -2293,15 +2273,6 @@ impl PluginsManager {
error = %err,
"plugin install failed while resolving marketplace plugin"
);
self.emit_plugin_install_failed(
PluginTelemetryMetadata {
plugin_id: None,
remote_plugin_id: None,
capability_summary: None,
},
marketplace_error_type(err),
sub_error_type,
);
}
}
@@ -2319,31 +2290,6 @@ impl PluginsManager {
error = %error_message,
"plugin install failed"
);
self.emit_plugin_install_failed(
self.telemetry_metadata_for_plugin_id(plugin_id),
error_type,
sub_error_type,
);
}
fn emit_plugin_install_failed(
&self,
plugin: PluginTelemetryMetadata,
error_type: &'static str,
sub_error_type: Option<String>,
) {
let analytics_events_client = match self.analytics_events_client.read() {
Ok(client) => client.clone(),
Err(err) => err.into_inner().clone(),
};
if let Some(analytics_events_client) = analytics_events_client {
analytics_events_client.track_plugin_install_failed(
plugin,
self.plugin_install_source,
error_type.to_string(),
sub_error_type,
);
}
}
async fn install_resolved_plugin(
@@ -2404,17 +2350,6 @@ impl PluginsManager {
.await
.map_err(anyhow::Error::from)?;
let analytics_events_client = match self.analytics_events_client.read() {
Ok(client) => client.clone(),
Err(err) => err.into_inner().clone(),
};
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,
);
}
Ok(PluginInstallOutcome {
plugin_id: result.plugin_id,
plugin_version: result.plugin_version,
@@ -2450,14 +2385,6 @@ impl PluginsManager {
}
async fn uninstall_plugin_id(&self, plugin_id: PluginId) -> Result<(), PluginUninstallError> {
let plugin_telemetry = if self.store.active_plugin_root(&plugin_id).is_some() {
Some(
self.telemetry_metadata_for_installed_plugin(&plugin_id)
.await,
)
} else {
None
};
let store = self.store.clone();
let plugin_id_for_store = plugin_id.clone();
tokio::task::spawn_blocking(move || store.uninstall(&plugin_id_for_store))
@@ -2468,16 +2395,6 @@ impl PluginsManager {
.await
.map_err(anyhow::Error::from)?;
let analytics_events_client = match self.analytics_events_client.read() {
Ok(client) => client.clone(),
Err(err) => err.into_inner().clone(),
};
if let Some(plugin_telemetry) = plugin_telemetry
&& let Some(analytics_events_client) = analytics_events_client
{
analytics_events_client.track_plugin_uninstalled(plugin_telemetry);
}
Ok(())
}

View File

@@ -1,158 +0,0 @@
use crate::script_attribution::normalized_relative_script_path;
use codex_plugin::PluginId;
use codex_protocol::items::is_safe_plugin_relative_path;
use codex_utils_absolute_path::AbsolutePathBuf;
use serde::Deserialize;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::fs::File;
use std::io::Read;
const ANALYTICS_MANIFEST_FILE: &str = "analytics.yaml";
const MAX_ANALYTICS_MANIFEST_BYTES: u64 = 64 * 1024;
const MAX_IDENTIFIER_LEN: usize = 64;
const MAX_DIMENSIONS_PER_MEASUREMENT: usize = 8;
/// The manifest declaration for one numeric measurement.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PluginMeasurementDefinition {
pub enum_dimensions: BTreeMap<String, BTreeSet<String>>,
}
/// Custom metrics allowed for one trusted plugin script operation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PluginMetricsOperation {
pub operation_name: String,
pub measurements: BTreeMap<String, PluginMeasurementDefinition>,
}
/// A metrics operation bound to identity from a fresh trusted command lookup.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedPluginMetricsOperation {
pub plugin_id: PluginId,
pub operation: PluginMetricsOperation,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct AnalyticsManifest {
version: u32,
#[serde(with = "serde_with::rust::maps_duplicate_key_is_error")]
operations: BTreeMap<String, OperationDeclaration>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct OperationDeclaration {
path: String,
#[serde(with = "serde_with::rust::maps_duplicate_key_is_error")]
measurements: BTreeMap<String, MeasurementDeclaration>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct MeasurementDeclaration {
#[serde(default, with = "serde_with::rust::maps_duplicate_key_is_error")]
dimensions: BTreeMap<String, Vec<String>>,
}
pub(crate) fn load_plugin_metrics_operations(
plugin_root: &AbsolutePathBuf,
) -> Option<BTreeMap<String, PluginMetricsOperation>> {
let manifest_path = plugin_root.join(ANALYTICS_MANIFEST_FILE);
let canonical_manifest_path = manifest_path.canonicalize().ok()?;
if canonical_manifest_path != manifest_path || !manifest_path.as_path().is_file() {
return None;
}
let mut contents = Vec::new();
File::open(manifest_path.as_path())
.ok()?
.take(MAX_ANALYTICS_MANIFEST_BYTES + 1)
.read_to_end(&mut contents)
.ok()?;
if contents.len() as u64 > MAX_ANALYTICS_MANIFEST_BYTES {
return None;
}
let manifest: AnalyticsManifest = serde_yaml::from_slice(&contents).ok()?;
validate_manifest(manifest, plugin_root)
}
fn validate_manifest(
manifest: AnalyticsManifest,
plugin_root: &AbsolutePathBuf,
) -> Option<BTreeMap<String, PluginMetricsOperation>> {
if manifest.version != 1 || manifest.operations.is_empty() {
return None;
}
let mut operations_by_path = BTreeMap::new();
for (operation_name, operation) in manifest.operations {
if !valid_identifier(&operation_name) || operation.measurements.is_empty() {
return None;
}
let normalized_path = validated_operation_path(plugin_root, &operation.path)?;
let mut measurements = BTreeMap::new();
for (measurement_name, measurement) in operation.measurements {
if !valid_identifier(&measurement_name)
|| measurement.dimensions.len() > MAX_DIMENSIONS_PER_MEASUREMENT
{
return None;
}
let mut enum_dimensions = BTreeMap::new();
for (dimension_name, values) in measurement.dimensions {
if !valid_identifier(&dimension_name) || values.is_empty() {
return None;
}
let value_count = values.len();
let values = values.into_iter().collect::<BTreeSet<_>>();
if values.len() != value_count
|| values.iter().any(|value| !valid_identifier(value))
{
return None;
}
enum_dimensions.insert(dimension_name, values);
}
measurements.insert(
measurement_name,
PluginMeasurementDefinition { enum_dimensions },
);
}
if operations_by_path
.insert(
normalized_path,
PluginMetricsOperation {
operation_name,
measurements,
},
)
.is_some()
{
return None;
}
}
Some(operations_by_path)
}
fn validated_operation_path(plugin_root: &AbsolutePathBuf, path: &str) -> Option<String> {
let normalized_path = path.strip_prefix("./").unwrap_or(path);
if !is_safe_plugin_relative_path(normalized_path) {
return None;
}
let script = plugin_root.join(normalized_path).canonicalize().ok()?;
if !script.as_path().is_file() {
return None;
}
let canonical_relative_path = script.as_path().strip_prefix(plugin_root.as_path()).ok()?;
(normalized_relative_script_path(canonical_relative_path)?.as_str() == normalized_path)
.then(|| normalized_path.to_string())
}
fn valid_identifier(value: &str) -> bool {
let mut chars = value.chars();
matches!(chars.next(), Some('a'..='z'))
&& value.len() <= MAX_IDENTIFIER_LEN
&& chars.all(|character| {
character.is_ascii_lowercase() || character.is_ascii_digit() || character == '_'
})
}

View File

@@ -1,299 +0,0 @@
use crate::ResolvedPluginMetricsOperation;
use codex_analytics::PluginMeasurementRow;
use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::Environment;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::FileSystemReadStream;
use codex_exec_server::RemoveOptions;
use codex_exec_server::WriteFileOptions;
use codex_protocol::models::AdditionalPermissionProfile;
use codex_protocol::models::FileSystemPermissions;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathConvention;
use codex_utils_path_uri::PathUri;
use futures::StreamExt;
use serde::Deserialize;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::sync::Arc;
use tempfile::NamedTempFile;
use uuid::Uuid;
pub const PLUGIN_METRICS_OUTPUT_ENV_VAR: &str = "CODEX_PLUGIN_METRICS_OUTPUT";
const MAX_OUTPUT_BYTES: u64 = 64 * 1024;
const MAX_OUTPUT_ROWS: usize = 100;
#[derive(Debug, PartialEq)]
pub struct PluginMeasurementBatch {
pub plugin_id: String,
pub execution_id: String,
pub operation: String,
pub rows: Vec<PluginMeasurementRow>,
}
pub struct PluginMetricsSidecar {
output: PluginMetricsOutput,
absolute_output_dir: AbsolutePathBuf,
output_env_value: String,
resolved: ResolvedPluginMetricsOperation,
execution_id: String,
}
enum PluginMetricsOutput {
Local {
file: NamedTempFile,
_directory: tempfile::TempDir,
},
Remote {
file_stream: tokio::sync::Mutex<FileSystemReadStream>,
_directory: RemotePluginMetricsDirectory,
},
}
struct RemotePluginMetricsDirectory {
filesystem: Arc<dyn ExecutorFileSystem>,
path: PathUri,
}
impl Drop for RemotePluginMetricsDirectory {
fn drop(&mut self) {
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
return;
};
let filesystem = Arc::clone(&self.filesystem);
let path = self.path.clone();
runtime.spawn(async move {
let _ = filesystem
.remove(
&path,
RemoveOptions {
recursive: true,
force: true,
follow_symlinks: true,
},
/*sandbox*/ None,
)
.await;
});
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct OutputEnvelope {
version: u32,
measurements: Vec<serde_json::Value>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct OutputMeasurement {
name: String,
value: f64,
#[serde(default)]
dimensions: BTreeMap<String, String>,
}
impl PluginMetricsSidecar {
pub fn create(resolved: ResolvedPluginMetricsOperation) -> Option<Self> {
let sidecar_dir = tempfile::Builder::new()
.prefix("codex-plugin-metrics-")
.tempdir()
.ok()?;
let output_file = tempfile::Builder::new()
.prefix("measurements-")
.suffix(".json")
.tempfile_in(sidecar_dir.path())
.ok()?;
let absolute_output_dir = AbsolutePathBuf::from_absolute_path(sidecar_dir.path()).ok()?;
let absolute_output_path = AbsolutePathBuf::from_absolute_path(output_file.path()).ok()?;
let output_env_value = absolute_output_path.as_path().to_str()?.to_string();
Some(Self {
output: PluginMetricsOutput::Local {
file: output_file,
_directory: sidecar_dir,
},
absolute_output_dir,
output_env_value,
resolved,
execution_id: Uuid::new_v4().to_string(),
})
}
pub async fn create_remote(
environment: &Environment,
resolved: ResolvedPluginMetricsOperation,
) -> Option<Self> {
let temp_dir = environment.info().await.ok()?.temp_dir?;
// Permission overlays still use host-native AbsolutePathBuf roots, so a
// foreign executor path cannot be granted its exact sidecar directory.
if !cfg!(unix) || temp_dir.infer_path_convention() != Some(PathConvention::Posix) {
tracing::debug!(
executor_temp_dir = %temp_dir,
"plugin metrics require POSIX executor paths on a POSIX frontend"
);
return None;
}
let execution_id = Uuid::new_v4().to_string();
let directory_path = temp_dir
.join(&format!("codex-plugin-metrics-{execution_id}"))
.ok()?;
let absolute_output_dir = directory_path.to_abs_path().ok()?;
let filesystem = environment.get_filesystem();
filesystem
.create_directory(
&directory_path,
CreateDirectoryOptions {
recursive: false,
follow_symlinks: true,
},
/*sandbox*/ None,
)
.await
.ok()?;
let directory = RemotePluginMetricsDirectory {
filesystem,
path: directory_path,
};
let output_path = directory.path.join("measurements.json").ok()?;
directory
.filesystem
.write_file(
&output_path,
Vec::new(),
WriteFileOptions::default(),
/*sandbox*/ None,
)
.await
.ok()?;
let file_stream = directory
.filesystem
.read_file_stream(&output_path, /*sandbox*/ None)
.await
.ok()?;
Some(Self {
output: PluginMetricsOutput::Remote {
file_stream: tokio::sync::Mutex::new(file_stream),
_directory: directory,
},
absolute_output_dir,
output_env_value: output_path.inferred_native_path_string(),
resolved,
execution_id,
})
}
pub fn install_output_env(&self, env: &mut HashMap<String, String>) {
env.insert(
PLUGIN_METRICS_OUTPUT_ENV_VAR.to_string(),
self.output_env_value.clone(),
);
}
#[cfg(test)]
fn absolute_output_path(&self) -> AbsolutePathBuf {
AbsolutePathBuf::from_absolute_path(&self.output_env_value).expect("absolute output path")
}
pub fn additional_permissions(&self) -> AdditionalPermissionProfile {
AdditionalPermissionProfile {
file_system: Some(FileSystemPermissions::from_read_write_roots(
/*read*/ None,
/*write*/ Some(vec![self.absolute_output_dir.clone()]),
)),
..Default::default()
}
}
pub async fn finish(mut self, exit_code: i32) -> Option<PluginMeasurementBatch> {
if exit_code != 0 {
return None;
}
let mut contents = Vec::new();
match &mut self.output {
PluginMetricsOutput::Local { file, .. } => {
let output_file = file.as_file_mut();
output_file.seek(SeekFrom::Start(0)).ok()?;
output_file
.take(MAX_OUTPUT_BYTES + 1)
.read_to_end(&mut contents)
.ok()?;
}
PluginMetricsOutput::Remote { file_stream, .. } => {
let file_stream = file_stream.get_mut();
while let Some(chunk) = file_stream.next().await {
let chunk = chunk.ok()?;
if contents.len().saturating_add(chunk.len()) > MAX_OUTPUT_BYTES as usize {
return None;
}
contents.extend_from_slice(&chunk);
}
}
}
let rows = parse_output(&contents, &self.resolved)?;
(!rows.is_empty()).then(|| PluginMeasurementBatch {
plugin_id: self.resolved.plugin_id.as_key(),
execution_id: self.execution_id,
operation: self.resolved.operation.operation_name,
rows,
})
}
}
pub fn strip_output_env(env: &mut HashMap<String, String>) {
if cfg!(windows) {
env.retain(|key, _| !key.eq_ignore_ascii_case(PLUGIN_METRICS_OUTPUT_ENV_VAR));
} else {
env.remove(PLUGIN_METRICS_OUTPUT_ENV_VAR);
}
}
fn parse_output(
contents: &[u8],
resolved: &ResolvedPluginMetricsOperation,
) -> Option<Vec<PluginMeasurementRow>> {
if contents.len() as u64 > MAX_OUTPUT_BYTES {
return None;
}
let output: OutputEnvelope = serde_json::from_slice(contents).ok()?;
if output.version != 1 || output.measurements.len() > MAX_OUTPUT_ROWS {
return None;
}
let mut seen = BTreeSet::new();
let mut rows = Vec::new();
for value in output.measurements {
let Ok(measurement) = serde_json::from_value::<OutputMeasurement>(value) else {
continue;
};
let Some(definition) = resolved.operation.measurements.get(&measurement.name) else {
continue;
};
if !measurement.value.is_finite()
|| measurement.dimensions.len() != definition.enum_dimensions.len()
|| !definition.enum_dimensions.iter().all(|(name, allowed)| {
measurement
.dimensions
.get(name)
.is_some_and(|value| allowed.contains(value))
})
|| !seen.insert((measurement.name.clone(), measurement.dimensions.clone()))
{
continue;
}
rows.push(PluginMeasurementRow {
measurement_name: measurement.name,
number_value: measurement.value,
dimensions: measurement.dimensions,
});
}
Some(rows)
}
#[cfg(test)]
#[path = "plugin_metrics_sidecar_tests.rs"]
mod tests;

View File

@@ -1,195 +0,0 @@
use super::*;
use crate::PluginMeasurementDefinition;
use crate::PluginMetricsOperation;
use codex_plugin::PluginId;
use codex_protocol::models::LegacyReadWriteRoots;
use pretty_assertions::assert_eq;
use serde_json::json;
fn create_sidecar() -> PluginMetricsSidecar {
PluginMetricsSidecar::create(resolved_operation()).expect("create sidecar")
}
#[test]
fn sidecar_is_created_in_system_temp_with_private_permissions() {
let output_dir =
AbsolutePathBuf::from_absolute_path(std::env::temp_dir()).expect("absolute temp directory");
let sidecar = PluginMetricsSidecar::create(resolved_operation()).expect("create sidecar");
assert_eq!(
sidecar.absolute_output_path().parent(),
Some(sidecar.absolute_output_dir.clone())
);
assert_eq!(sidecar.absolute_output_dir.parent(), Some(output_dir));
assert!(sidecar.absolute_output_dir.as_path().is_dir());
let roots = sidecar
.additional_permissions()
.file_system
.expect("file system permissions")
.legacy_read_write_roots()
.expect("legacy roots");
assert_eq!(
roots,
LegacyReadWriteRoots {
read: None,
write: Some(vec![sidecar.absolute_output_dir]),
}
);
}
fn resolved_operation() -> ResolvedPluginMetricsOperation {
ResolvedPluginMetricsOperation {
plugin_id: PluginId::parse("security@openai-curated").expect("valid plugin id"),
operation: PluginMetricsOperation {
operation_name: "security_scan".to_string(),
measurements: BTreeMap::from([
(
"finding_count".to_string(),
PluginMeasurementDefinition {
enum_dimensions: BTreeMap::from([(
"severity".to_string(),
BTreeSet::from(["high".to_string(), "low".to_string()]),
)]),
},
),
(
"files_scanned".to_string(),
PluginMeasurementDefinition {
enum_dimensions: BTreeMap::new(),
},
),
]),
},
}
}
#[tokio::test]
async fn sidecar_keeps_valid_rows_and_first_duplicate_then_cleans_up() {
let sidecar = create_sidecar();
let path = sidecar.absolute_output_path();
std::fs::write(
path.as_path(),
json!({
"version": 1,
"measurements": [
{"name": "finding_count", "value": 3, "dimensions": {"severity": "high"}},
{"name": "unknown", "value": 1},
{"name": "finding_count", "value": 4},
{"name": "finding_count", "value": 5, "dimensions": {"severity": "critical"}},
{"name": "finding_count", "value": 6, "dimensions": {"severity": "high", "extra": "x"}},
{"name": "finding_count", "value": 99, "dimensions": {"severity": "high"}},
{"name": "files_scanned", "value": 17},
{"name": "files_scanned", "value": "not-a-number"},
{"name": "files_scanned", "value": 18, "unknown": true}
]
})
.to_string(),
)
.expect("write output");
let batch = sidecar
.finish(/*exit_code*/ 0)
.await
.expect("valid measurements");
let execution_id = batch.execution_id.clone();
assert_eq!(
batch,
PluginMeasurementBatch {
plugin_id: "security@openai-curated".to_string(),
execution_id: execution_id.clone(),
operation: "security_scan".to_string(),
rows: vec![
PluginMeasurementRow {
measurement_name: "finding_count".to_string(),
number_value: 3.0,
dimensions: BTreeMap::from([("severity".to_string(), "high".to_string(),)]),
},
PluginMeasurementRow {
measurement_name: "files_scanned".to_string(),
number_value: 17.0,
dimensions: BTreeMap::new(),
},
],
}
);
assert_eq!(
Uuid::parse_str(&execution_id)
.expect("execution id UUID")
.get_version(),
Some(uuid::Version::Random)
);
assert!(!path.exists());
}
#[tokio::test]
async fn malformed_oversized_and_nonzero_outputs_are_ignored_and_cleaned_up() {
for output in [
r#"{"version":2,"measurements":[]}"#.as_bytes().to_vec(),
r#"{"version":1,"measurements":[],"unknown":true}"#.as_bytes().to_vec(),
json!({
"version": 1,
"measurements": vec![json!({"name": "files_scanned", "value": 1}); MAX_OUTPUT_ROWS + 1]
})
.to_string()
.into_bytes(),
vec![b' '; MAX_OUTPUT_BYTES as usize + 1],
] {
let sidecar = create_sidecar();
let path = sidecar.absolute_output_path();
std::fs::write(path.as_path(), output).expect("write output");
assert_eq!(sidecar.finish(/*exit_code*/ 0).await, None);
assert!(!path.exists());
}
let sidecar = create_sidecar();
let path = sidecar.absolute_output_path();
std::fs::write(
path.as_path(),
r#"{"version":1,"measurements":[{"name":"files_scanned","value":1}]}"#,
)
.expect("write output");
assert_eq!(sidecar.finish(/*exit_code*/ 1).await, None);
assert!(!path.exists());
}
#[test]
fn reserved_output_env_is_absent_without_sidecar_and_cannot_be_overridden() {
let mut env = HashMap::from([
(
PLUGIN_METRICS_OUTPUT_ENV_VAR.to_string(),
"/user/path".to_string(),
),
("KEEP".to_string(), "value".to_string()),
]);
strip_output_env(&mut env);
assert_eq!(
env,
HashMap::from([("KEEP".to_string(), "value".to_string())])
);
let sidecar = create_sidecar();
let path = sidecar.absolute_output_path();
sidecar.install_output_env(&mut env);
assert_eq!(
env.get(PLUGIN_METRICS_OUTPUT_ENV_VAR).map(String::as_str),
path.as_path().to_str()
);
drop(sidecar);
assert!(!path.exists());
}
#[cfg(unix)]
#[tokio::test]
async fn sidecar_reads_the_original_file_after_path_replacement() {
let sidecar = create_sidecar();
let path = sidecar.absolute_output_path();
std::fs::remove_file(path.as_path()).expect("remove original output path");
std::fs::write(
path.as_path(),
r#"{"version":1,"measurements":[{"name":"files_scanned","value":99}]}"#,
)
.expect("write replacement output");
assert_eq!(sidecar.finish(/*exit_code*/ 0).await, None);
assert!(!path.exists());
}

View File

@@ -6,9 +6,6 @@ use crate::loader::curated_plugin_cache_version;
use crate::marketplace::MarketplacePluginSource;
use crate::marketplace::find_marketplace_plugin;
use crate::marketplace_policy::primary_runtime_marketplace_root;
use crate::plugin_metrics::PluginMetricsOperation;
use crate::plugin_metrics::ResolvedPluginMetricsOperation;
use crate::plugin_metrics::load_plugin_metrics_operations;
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
use crate::startup_sync::curated_plugins_api_marketplace_path;
use crate::startup_sync::curated_plugins_repo_path;
@@ -16,7 +13,6 @@ use crate::startup_sync::read_curated_plugins_sha;
use crate::store::DEFAULT_PLUGIN_VERSION;
use crate::store::PluginStore;
use crate::store::plugin_version_for_source;
use crate::store::validate_plugin_version_segment;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::GetMetadataOptions;
use codex_exec_server::ReadFileOptions;
@@ -26,9 +22,7 @@ use codex_shell_command::bash::extract_bash_command;
use codex_shell_command::bash::parse_shell_lc_plain_commands;
use codex_shell_command::parse_command::is_pathish;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathConvention;
use codex_utils_path_uri::PathUri;
use std::collections::BTreeMap;
use std::collections::HashSet;
use std::path::Component;
use std::path::Path;
@@ -38,10 +32,9 @@ struct TrustedPluginRoot {
plugin_id: PluginId,
version: String,
root: AbsolutePathBuf,
metrics_operations_by_path: BTreeMap<String, PluginMetricsOperation>,
}
/// Trusted plugin command attribution safe to carry into command analytics.
/// Trusted plugin command attribution carried into local command events.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PluginCommandAttribution {
pub plugin_id: PluginId,
@@ -66,63 +59,6 @@ pub struct TrustedPluginRoots {
roots: Vec<TrustedPluginRoot>,
}
/// An untrusted hint from a canonical executor script path, never authorization.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PluginMeasurementTarget {
pub(crate) plugin_id: PluginId,
pub(crate) version: String,
pub(crate) path_convention: PathConvention,
}
impl PluginMeasurementTarget {
/// Selects one remote plugin using the same command parser as attribution.
/// Skip paths outside the remote plugin cache before consulting the executor.
pub async fn from_command(
command: &[String],
cwd: &PathUri,
file_system: &dyn ExecutorFileSystem,
) -> Option<Self> {
let command = single_plain_command(command)?;
let invocation = script_invocation(&command)?;
let script = cwd.join(invocation.script).ok()?;
Self::from_script_path(&script)?;
let script = file_system
.canonicalize(&script, /*sandbox*/ None)
.await
.ok()?;
Self::from_script_path(&script)
}
fn from_script_path(script: &PathUri) -> Option<Self> {
let path_convention = script.infer_path_convention()?;
let native_path = script.inferred_native_path_string();
// Normalize only the hint so equivalent Windows paths share preparation.
// Store identities must retain the authenticated catalog's spelling.
let native_path = match path_convention {
PathConvention::Windows => native_path.to_ascii_lowercase(),
PathConvention::Posix => native_path,
};
let components = path_convention
.path_segments(&native_path)
.collect::<Vec<_>>();
let mut candidates = components.windows(6).filter_map(|parts| {
if parts[..3] != ["plugins", "cache", REMOTE_GLOBAL_MARKETPLACE_NAME]
|| parts[4] == DEFAULT_PLUGIN_VERSION
{
return None;
}
validate_plugin_version_segment(parts[4]).ok()?;
Some(Self {
plugin_id: PluginId::new(parts[3].to_owned(), parts[2].to_owned()).ok()?,
version: parts[4].to_owned(),
path_convention,
})
});
let target = candidates.next()?;
candidates.next().is_none().then_some(target)
}
}
impl TrustedPluginRoots {
/// Adds already-trusted roots, preserving the existing root for each plugin and version.
/// Distinct versions remain eligible for exact executor-version matching.
@@ -167,8 +103,6 @@ impl TrustedPluginRoots {
root.as_path().is_dir().then(|| TrustedPluginRoot {
plugin_id,
version,
metrics_operations_by_path: load_plugin_metrics_operations(&root)
.unwrap_or_default(),
root,
})
})
@@ -258,15 +192,6 @@ impl TrustedPluginRoots {
.map(|candidate| candidate.attribution())
}
/// Resolves one exact command to one trusted manifest-declared operation.
pub fn resolve_metrics_operation(
&self,
command: &[String],
cwd: &AbsolutePathBuf,
) -> Option<ResolvedPluginMetricsOperation> {
self.local_candidate(command, cwd)?.metrics_operation()
}
fn local_candidate(
&self,
command: &[String],
@@ -312,31 +237,16 @@ impl TrustedPluginRoots {
cwd: &PathUri,
file_system: &dyn ExecutorFileSystem,
) -> Option<PluginCommandAttribution> {
self.executor_candidate(command, cwd, file_system, PluginVersionMatch::Any)
self.executor_candidate(command, cwd, file_system)
.await
.map(|candidate| candidate.matched.attribution())
}
/// Resolves one trusted executor script to one manifest-declared operation,
/// requiring the executor's version to match the trusted declaration's version.
pub async fn resolve_metrics_operation_in_filesystem(
&self,
command: &[String],
cwd: &PathUri,
file_system: &dyn ExecutorFileSystem,
) -> Option<ResolvedPluginMetricsOperation> {
self.executor_candidate(command, cwd, file_system, PluginVersionMatch::Exact)
.await?
.matched
.metrics_operation()
}
async fn executor_candidate(
&self,
command: &[String],
cwd: &PathUri,
file_system: &dyn ExecutorFileSystem,
version_match: PluginVersionMatch,
) -> Option<ExecutorAttributionCandidate<'_>> {
if self.roots.is_empty() {
return None;
@@ -349,7 +259,7 @@ impl TrustedPluginRoots {
let suffixes = normalized_script_suffixes(&script);
if !self.roots.iter().any(|root| {
suffixes.iter().any(|suffix| {
executor_plugin_root_matches(&script, root, suffix, PluginVersionMatch::Any)
executor_plugin_root_matches(&script, root, suffix)
|| root.root.join(suffix).as_path().is_file()
})
}) {
@@ -359,7 +269,7 @@ impl TrustedPluginRoots {
.canonicalize(&script, /*sandbox*/ None)
.await
.ok()?;
let candidates = self.local_candidates_for_executor_script(&script, version_match);
let candidates = self.local_candidates_for_executor_script(&script);
if candidates.is_empty() {
return None;
}
@@ -386,25 +296,21 @@ impl TrustedPluginRoots {
.into_iter()
.filter(|candidate| contents == candidate.contents);
let candidate = matches.next()?;
match version_match {
PluginVersionMatch::Any => matches
.all(|other| other.matched.attribution() == candidate.matched.attribution())
.then_some(candidate),
PluginVersionMatch::Exact => matches.next().is_none().then_some(candidate),
}
matches
.all(|other| other.matched.attribution() == candidate.matched.attribution())
.then_some(candidate)
}
fn local_candidates_for_executor_script(
&self,
script: &PathUri,
version_match: PluginVersionMatch,
) -> Vec<ExecutorAttributionCandidate<'_>> {
let suffixes = normalized_script_suffixes(script);
self.roots
.iter()
.filter_map(|root| {
let (script, normalized_relative_path) = suffixes.iter().find_map(|suffix| {
if !executor_plugin_root_matches(script, root, suffix, version_match) {
if !executor_plugin_root_matches(script, root, suffix) {
return None;
}
let script = root.root.join(suffix).canonicalize().ok()?;
@@ -439,17 +345,6 @@ impl MatchedPluginScript<'_> {
normalized_relative_path: self.normalized_relative_path.clone(),
}
}
fn metrics_operation(&self) -> Option<ResolvedPluginMetricsOperation> {
Some(ResolvedPluginMetricsOperation {
plugin_id: self.root.plugin_id.clone(),
operation: self
.root
.metrics_operations_by_path
.get(&self.normalized_relative_path)?
.clone(),
})
}
}
struct ExecutorAttributionCandidate<'a> {
@@ -457,12 +352,6 @@ struct ExecutorAttributionCandidate<'a> {
contents: Vec<u8>,
}
#[derive(Clone, Copy)]
enum PluginVersionMatch {
Any,
Exact,
}
fn normalized_script_suffixes(script: &PathUri) -> Vec<String> {
let path = script.inferred_native_path_string().replace('\\', "/");
let components = path
@@ -481,7 +370,6 @@ fn executor_plugin_root_matches(
script: &PathUri,
trusted: &TrustedPluginRoot,
relative_path: &str,
version_match: PluginVersionMatch,
) -> bool {
let relative_depth = relative_path.split('/').count();
let Some(root) = script.ancestors().nth(relative_depth) else {
@@ -496,12 +384,7 @@ fn executor_plugin_root_matches(
)) else {
return false;
};
match version_match {
PluginVersionMatch::Any => root.parent().as_ref() == Some(&plugin_root),
PluginVersionMatch::Exact => plugin_root
.join(&trusted.version)
.is_ok_and(|expected| expected == root),
}
root.parent().as_ref() == Some(&plugin_root)
}
/// Returns the structurally parsed arguments following a single script command.

View File

@@ -1,6 +1,5 @@
use super::*;
use crate::LoadedPlugin;
use crate::PluginMeasurementDefinition;
use crate::loader::curated_plugin_cache_version;
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
use crate::startup_sync::curated_plugins_repo_path;
@@ -22,8 +21,6 @@ use codex_utils_plugins::SkillDiscoveryMode;
use futures::FutureExt;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fs;
@@ -161,7 +158,6 @@ fn resolves_primary_runtime_scripts_from_the_installed_plugin_cache() {
roots: vec![TrustedPluginRoot {
plugin_id: plugin_id.clone(),
version: "0.1.29".to_string(),
metrics_operations_by_path: BTreeMap::new(),
root: plugin_root.canonicalize().expect("canonical plugin root"),
}],
};
@@ -245,7 +241,6 @@ fn recognizes_windows_executor_plugin_cache_root() {
plugin_id: PluginId::parse("presentations@openai-primary-runtime").expect("plugin id"),
version: "0.1.29".to_string(),
root: path(reference.path()),
metrics_operations_by_path: BTreeMap::new(),
};
let relative_path = "skills/presentations/container_tools/mark_artifact_operation_started.mjs";
let script = PathUri::parse(
@@ -256,38 +251,18 @@ fn recognizes_windows_executor_plugin_cache_root() {
assert!(executor_plugin_root_matches(
&script,
&trusted,
relative_path,
PluginVersionMatch::Exact,
relative_path
));
let wrong_version = PathUri::parse(
"file:///C:/Users/user/.codex/plugins/cache/openai-primary-runtime/presentations/0.1.28/skills/presentations/container_tools/mark_artifact_operation_started.mjs",
let other_plugin = PathUri::parse(
"file:///C:/Users/user/.codex/plugins/cache/openai-primary-runtime/other/0.1.29/skills/presentations/container_tools/mark_artifact_operation_started.mjs",
)
.expect("other-version Windows script URI");
.expect("other-plugin Windows script URI");
assert!(!executor_plugin_root_matches(
&wrong_version,
&other_plugin,
&trusted,
relative_path,
PluginVersionMatch::Exact,
relative_path
));
}
fn assert_invalid_metrics_manifest(codex_home: &Path, root: &AbsolutePathBuf, manifest: &str) {
fs::write(root.join("analytics.yaml"), manifest).expect("write analytics manifest");
let roots = roots_for(
codex_home,
vec![loaded_plugin(
"sample@openai-curated",
root.as_path(),
ENABLED,
)],
);
roots
.resolve_attribution(&command(&["scripts/run.py"]), root)
.expect("Part 1 attribution remains enabled");
assert_eq!(
roots.resolve_metrics_operation(&command(&["scripts/run.py"]), root),
None
);
}
fn assert_untrusted(codex_home: &Path, config_name: &str, root: &Path) {
assert!(
roots_for(codex_home, vec![loaded_plugin(config_name, root, ENABLED)])
@@ -348,20 +323,17 @@ fn trusted_roots_require_verified_curated_or_remote_cache() {
TrustedPluginRoot {
plugin_id: PluginId::parse("sample@openai-curated").expect("plugin id"),
version: curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA),
metrics_operations_by_path: BTreeMap::new(),
root: root.canonicalize().expect("canonical root"),
},
TrustedPluginRoot {
plugin_id: PluginId::parse("api-sample@openai-api-curated").expect("plugin id"),
version: curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA),
metrics_operations_by_path: BTreeMap::new(),
root: api_root.canonicalize().expect("canonical root"),
},
TrustedPluginRoot {
plugin_id: PluginId::parse("remote-sample@openai-curated-remote")
.expect("plugin id"),
version: "1.2.3".to_string(),
metrics_operations_by_path: BTreeMap::new(),
root: remote_root.canonicalize().expect("canonical root"),
},
]
@@ -407,184 +379,6 @@ fn trusted_roots_require_verified_curated_or_remote_cache() {
);
}
#[test]
fn resolves_manifest_operation_for_exact_attributed_script() {
let (temp, root, _) = script_fixture();
fs::write(
root.join("analytics.yaml"),
r#"version: 1
operations:
security_scan:
path: ./scripts/run.py
measurements:
repository_files: {}
findings:
dimensions:
severity: [critical, high, medium, low]
"#,
)
.expect("write analytics manifest");
let roots = roots_for(
temp.path(),
vec![loaded_plugin(
"sample@openai-curated",
root.as_path(),
ENABLED,
)],
);
assert_eq!(
roots.resolve_metrics_operation(&command(&["scripts/run.py"]), &root),
Some(ResolvedPluginMetricsOperation {
plugin_id: PluginId::parse("sample@openai-curated").expect("plugin id"),
operation: PluginMetricsOperation {
operation_name: "security_scan".to_string(),
measurements: BTreeMap::from([
(
"findings".to_string(),
PluginMeasurementDefinition {
enum_dimensions: BTreeMap::from([(
"severity".to_string(),
BTreeSet::from([
"critical".to_string(),
"high".to_string(),
"low".to_string(),
"medium".to_string(),
]),
)]),
},
),
(
"repository_files".to_string(),
PluginMeasurementDefinition {
enum_dimensions: BTreeMap::new(),
},
),
]),
},
})
);
let undeclared_script = root.join("scripts/undeclared.py");
fs::write(undeclared_script.as_path(), "print('ok')\n").expect("write undeclared script");
roots
.resolve_attribution(&command(&["scripts/undeclared.py"]), &root)
.expect("trusted attribution");
assert_eq!(
roots.resolve_metrics_operation(&command(&["scripts/undeclared.py"]), &root),
None
);
}
#[test]
fn allows_measurement_names_reused_across_operations() {
let (temp, root, _) = script_fixture();
let other_script = root.join("scripts/other.py");
fs::write(other_script.as_path(), "#!/usr/bin/env python3\n").expect("write script");
fs::write(
root.join("analytics.yaml"),
r#"version: 1
operations:
first:
path: ./scripts/run.py
measurements:
count: {}
second:
path: ./scripts/other.py
measurements:
count: {}
"#,
)
.expect("write analytics manifest");
let roots = roots_for(
temp.path(),
vec![loaded_plugin(
"sample@openai-curated",
root.as_path(),
ENABLED,
)],
);
for (script, operation_name) in [("scripts/run.py", "first"), ("scripts/other.py", "second")] {
let resolved = roots
.resolve_metrics_operation(&command(&[script]), &root)
.expect("resolved metrics operation");
assert_eq!(resolved.operation.operation_name, operation_name);
assert!(resolved.operation.measurements.contains_key("count"));
}
}
#[test]
fn invalid_manifest_disables_metrics_without_disabling_attribution() {
let (temp, root, _) = script_fixture();
let invalid_manifests = [
r#"version: 2
operations: {scan: {path: scripts/run.py, measurements: {count: {}}}}
"#,
r#"version: 1
unknown: true
operations: {scan: {path: scripts/run.py, measurements: {count: {}}}}
"#,
r#"version: 1
operations:
scan: {path: scripts/run.py, measurements: {count: {}}}
scan: {path: scripts/run.py, measurements: {count: {}}}
"#,
r#"version: 1
operations:
scan:
path: scripts/run.py
measurements:
count: {}
count: {}
"#,
r#"version: 1
operations:
scan:
path: ../outside.py
measurements:
count: {}
"#,
r#"version: 1
operations: {scan: {path: scripts/run.py, measurements: {count: {dimensions: {status: ["needs review"]}}}}}
"#,
r#"version: 1
operations: {BadName: {path: scripts/run.py, measurements: {count: {}}}}
"#,
r#"version: 1
operations: {scan: {path: scripts/run.py, measurements: {count: {}}}, scan_again: {path: ./scripts/run.py, measurements: {count: {}}}}
"#,
];
for manifest in invalid_manifests {
assert_invalid_metrics_manifest(temp.path(), &root, manifest);
}
let oversized_manifest = format!(
"version: 1\noperations: {{scan: {{path: scripts/run.py, measurements: {{count: {{}}}}}}}}\n#{}",
"x".repeat(64 * 1024)
);
assert_invalid_metrics_manifest(temp.path(), &root, &oversized_manifest);
#[cfg(unix)]
{
let outside = temp.path().join("outside.py");
fs::write(&outside, "print('outside')\n").expect("write outside script");
std::os::unix::fs::symlink(&outside, root.join("scripts/escape.py"))
.expect("symlink script");
assert_invalid_metrics_manifest(
temp.path(),
&root,
r#"version: 1
operations:
scan:
path: scripts/escape.py
measurements:
count: {}
"#,
);
}
}
#[test]
fn resolves_local_attribution_for_safe_interpreters_and_wrappers() {
let (temp, root, script) = script_fixture();
@@ -681,13 +475,11 @@ fn rejects_ambiguous_commands_overlaps_and_symlink_escapes() {
TrustedPluginRoot {
plugin_id: PluginId::parse("sample@openai-curated").expect("plugin id"),
version: curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA),
metrics_operations_by_path: BTreeMap::new(),
root: root.canonicalize().expect("canonical root"),
},
TrustedPluginRoot {
plugin_id: PluginId::parse("nested@openai-curated").expect("plugin id"),
version: curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA),
metrics_operations_by_path: BTreeMap::new(),
root: root.join("scripts").canonicalize().expect("nested root"),
},
],
@@ -722,51 +514,24 @@ fn rejects_ambiguous_commands_overlaps_and_symlink_escapes() {
const REFERENCE_HELPER: &str = "scripts/install-dependencies.sh";
fn reference_metrics_operation(variant: &str) -> PluginMetricsOperation {
PluginMetricsOperation {
operation_name: "dependency_install".to_string(),
measurements: BTreeMap::from([(
"duration_ms".to_string(),
PluginMeasurementDefinition {
enum_dimensions: BTreeMap::from([(
"variant".to_string(),
BTreeSet::from([variant.to_string()]),
)]),
},
)]),
}
}
fn reference_identity_fixture(root: &Path, variant: &str, contents: &str) -> AbsolutePathBuf {
fn reference_identity_fixture(root: &Path, contents: &str) -> AbsolutePathBuf {
fs::create_dir_all(root.join("scripts")).expect("create reference scripts");
fs::write(root.join(REFERENCE_HELPER), contents).expect("write helper");
fs::write(
root.join("analytics.yaml"),
format!(
"version: 1\noperations:\n dependency_install:\n path: ./{REFERENCE_HELPER}\n measurements:\n duration_ms:\n dimensions:\n variant: [{variant}]\n"
),
)
.expect("write operation manifest");
path(root).canonicalize().expect("canonical reference root")
}
fn reference_fixture(bundles: &[(&str, &str, &str, &str)]) -> (TempDir, TrustedPluginRoots) {
fn reference_fixture(bundles: &[(&str, &str, &str)]) -> (TempDir, TrustedPluginRoots) {
let home = TempDir::new().expect("references");
let roots = TrustedPluginRoots {
roots: bundles
.iter()
.map(|(name, version, variant, contents)| {
let root = reference_identity_fixture(
&home.path().join(name).join(version),
variant,
contents,
);
.map(|(name, version, contents)| {
let root =
reference_identity_fixture(&home.path().join(name).join(version), contents);
TrustedPluginRoot {
plugin_id: PluginId::parse(&format!("{name}@openai-curated-remote"))
.expect("plugin id"),
version: version.to_string(),
metrics_operations_by_path: load_plugin_metrics_operations(&root)
.expect("valid fixture analytics"),
root,
}
})
@@ -780,19 +545,16 @@ fn executor_plugin(home: &Path, name: &str, version: &str, contents: &str) -> Ab
&home.join(format!(
"plugins/cache/openai-curated-remote/{name}/{version}"
)),
"untrusted_executor_metadata",
contents,
)
}
// Check both APIs: ordinary attribution can survive version differences, while
// measurements must use the exact authenticated declaration (never executor YAML).
// Ordinary attribution can survive version differences.
async fn assert_executor_resolution(
roots: &TrustedPluginRoots,
command: &[String],
cwd: &PathUri,
plugin_id: &PluginId,
variant: Option<&str>,
) {
assert_eq!(
roots
@@ -804,123 +566,15 @@ async fn assert_executor_resolution(
}),
"attribution for {command:?} at {cwd:?}"
);
assert_eq!(
roots
.resolve_metrics_operation_in_filesystem(command, cwd, LOCAL_FS.as_ref())
.await,
variant.map(|variant| ResolvedPluginMetricsOperation {
plugin_id: plugin_id.clone(),
operation: reference_metrics_operation(variant),
}),
"measurements for {command:?} at {cwd:?}"
);
}
#[test]
fn executor_cache_identity_obeys_windows_and_posix_case_conventions() {
let (_reference, roots) =
reference_fixture(&[("sites", "2.0.0-RC1", "selected", "printf shared\\n\n")]);
let plugin_id = PluginId::parse("sites@openai-curated-remote").expect("plugin id");
for prefix in ["file:///C:/Users/user/.codex", "file://server/share/.codex"] {
let script = PathUri::parse(&format!(
"{prefix}/PLUGINS/CACHE/OPENAI-CURATED-REMOTE/SITES/2.0.0-rc1/{REFERENCE_HELPER}"
))
.expect("Windows script");
let target = PluginMeasurementTarget::from_script_path(&script)
.expect("Windows cache preselection follows the resolver's path identity");
assert_eq!(
target,
PluginMeasurementTarget {
plugin_id: plugin_id.clone(),
version: "2.0.0-rc1".to_string(),
path_convention: PathConvention::Windows,
}
);
let equivalent = PathUri::parse(&format!(
"{prefix}/plugins/cache/openai-curated-remote/sites/2.0.0-RC1/{REFERENCE_HELPER}"
))
.expect("equivalent Windows script");
assert_eq!(
PluginMeasurementTarget::from_script_path(&equivalent),
Some(target)
);
let candidates =
roots.local_candidates_for_executor_script(&script, PluginVersionMatch::Exact);
let candidate = candidates
.first()
.expect("Windows identity casing must not prevent canonicalization");
assert_eq!(
candidate.matched.metrics_operation(),
Some(ResolvedPluginMetricsOperation {
plugin_id: plugin_id.clone(),
operation: reference_metrics_operation("selected"),
})
);
}
for script in [
format!(
"file:///home/user/.codex/PLUGINS/CACHE/OPENAI-CURATED-REMOTE/SITES/2.0.0-rc1/{REFERENCE_HELPER}"
),
format!(
"file:///home/user/.codex/plugins/cache/openai-curated-remote/SITES/2.0.0-RC1/{REFERENCE_HELPER}"
),
format!(
"file:///C:/Users/user/.codex/PLUGINS/CACHE/OPENAI-CURATED-REMOTE/SITES/2.0.0-rc2/{REFERENCE_HELPER}"
),
format!(
"file:///C:/Users/user/.codex/PLUGINS/CACHE/OPENAI-CURATED-REMOTE/OTHER/2.0.0-rc1/{REFERENCE_HELPER}"
),
] {
let script = PathUri::parse(&script).expect("script");
let path_convention = script.infer_path_convention().expect("path convention");
let expected = PluginMeasurementTarget {
plugin_id: plugin_id.clone(),
version: match path_convention {
PathConvention::Windows => "2.0.0-rc1",
PathConvention::Posix => "2.0.0-RC1",
}
.to_string(),
path_convention,
};
assert_ne!(
PluginMeasurementTarget::from_script_path(&script),
Some(expected),
"preselection must not match a differently cased POSIX identity or another version"
);
assert!(
roots
.local_candidates_for_executor_script(&script, PluginVersionMatch::Exact)
.is_empty(),
"POSIX casing and different Windows versions must remain distinct"
);
}
for version in ["2.0.0-RC1", "2.0.0-rc1"] {
let script = PathUri::parse(&format!(
"file:///home/user/.codex/plugins/cache/openai-curated-remote/sites/{version}/{REFERENCE_HELPER}"
))
.expect("POSIX script");
let target =
PluginMeasurementTarget::from_script_path(&script).expect("POSIX cache preselection");
assert_eq!(
target,
PluginMeasurementTarget {
plugin_id: plugin_id.clone(),
version: version.to_string(),
path_convention: PathConvention::Posix,
}
);
}
}
#[test]
fn extending_trusted_roots_preserves_existing_plugins_and_deduplicates_snapshots() {
let contents = "printf shared\\n\n";
let (_frontend, mut roots) = reference_fixture(&[("sites", "1.2.3", "primary", contents)]);
let (_frontend, mut roots) = reference_fixture(&[("sites", "1.2.3", contents)]);
let original = roots.clone();
let (_snapshot, additional) = reference_fixture(&[
("sites", "1.2.3", "copied", contents),
("other", "1.2.3", "additional", contents),
]);
let (_snapshot, additional) =
reference_fixture(&[("sites", "1.2.3", contents), ("other", "1.2.3", contents)]);
roots.extend(&additional);
let expected = TrustedPluginRoots {
@@ -931,56 +585,14 @@ fn extending_trusted_roots_preserves_existing_plugins_and_deduplicates_snapshots
assert_eq!(roots, expected, "repeated snapshots must remain idempotent");
}
#[tokio::test]
async fn authenticated_v2_reference_coexists_with_loaded_frontend_v1() {
let frontend = TempDir::new().expect("frontend");
let v1 = installed_remote_plugin_root(frontend.path(), "sites");
reference_identity_fixture(v1.as_path(), "install_v1", "printf v1\\n\n");
let plugin_id = PluginId::parse("sites@openai-curated-remote").expect("plugin id");
let mut roots = roots_for(
frontend.path(),
vec![loaded_plugin(&plugin_id.as_key(), v1.as_path(), ENABLED)],
);
let (_reference, references) =
reference_fixture(&[("sites", "2.0.0", "install_v2", "printf v2\\n\n")]);
roots.extend(&references);
// The operation must stay bound to the selected root when two versions share
// a plugin ID and helper path, for both local and executor resolution.
for (root, variant) in [
(&v1, "install_v1"),
(&references.roots[0].root, "install_v2"),
] {
assert_eq!(
roots.resolve_metrics_operation(&command(&["sh", REFERENCE_HELPER]), root),
Some(ResolvedPluginMetricsOperation {
plugin_id: plugin_id.clone(),
operation: reference_metrics_operation(variant),
})
);
}
let executor = TempDir::new().expect("executor");
let root = executor_plugin(executor.path(), "sites", "2.0.0", "printf v2\\n\n");
let cwd = PathUri::from_host_native_path(root.as_path()).expect("executor URI");
assert_executor_resolution(
&roots,
&command(&["sh", REFERENCE_HELPER]),
&cwd,
&plugin_id,
Some("install_v2"),
)
.await;
}
#[tokio::test]
async fn same_helper_path_in_two_plugins_resolves_by_executor_identity() {
// Identical bytes: neither suffix nor content identifies a plugin.
let contents = "printf shared\\n\n";
let (_reference, roots) = reference_fixture(&[
("sites", "2.0.0", "sites_install", contents),
("other", "2.0.0", "other_install", contents),
]);
let (_reference, roots) =
reference_fixture(&[("sites", "2.0.0", contents), ("other", "2.0.0", contents)]);
let executor = TempDir::new().expect("executor");
for (name, variant) in [("sites", "sites_install"), ("other", "other_install")] {
for name in ["sites", "other"] {
let root = executor_plugin(executor.path(), name, "2.0.0", contents);
let cwd = PathUri::from_host_native_path(root.as_path()).expect("executor URI");
let plugin_id =
@@ -990,96 +602,17 @@ async fn same_helper_path_in_two_plugins_resolves_by_executor_identity() {
&command(&["sh", REFERENCE_HELPER]),
&cwd,
&plugin_id,
Some(variant),
)
.await;
}
}
#[tokio::test]
async fn identical_script_bytes_do_not_authorize_another_executor_version() {
let contents = "printf shared\\n\n";
let (_reference, roots) =
reference_fixture(&[("sites", "2.0.0", "v2_only_operation", contents)]);
let plugin_id = PluginId::parse("sites@openai-curated-remote").expect("plugin id");
let executor = TempDir::new().expect("executor");
for version in ["1.2.3", "2.0.0"] {
let root = executor_plugin(executor.path(), "sites", version, contents);
let cwd = PathUri::from_host_native_path(root.as_path()).expect("executor URI");
let candidate = command(&["bash", "-lc", &format!("sh {REFERENCE_HELPER}")]);
assert_eq!(
PluginMeasurementTarget::from_command(&candidate, &cwd, LOCAL_FS.as_ref()).await,
Some(PluginMeasurementTarget {
plugin_id: plugin_id.clone(),
version: version.to_string(),
path_convention: PathConvention::native(),
})
);
assert_executor_resolution(
&roots,
&command(&["sh", REFERENCE_HELPER]),
&cwd,
&plugin_id,
(version == "2.0.0").then_some("v2_only_operation"),
)
.await;
}
}
#[cfg(unix)]
#[tokio::test]
async fn executor_symlink_cannot_change_authenticated_plugin_or_version() {
let contents = "printf shared\\n\n";
let (_reference, roots) =
reference_fixture(&[("sites", "2.0.0", "v2_only_operation", contents)]);
let executor = TempDir::new().expect("executor");
let original = executor
.path()
.join("plugins/cache/openai-curated-remote/sites/2.0.0");
fs::create_dir_all(original.join("scripts")).expect("original scripts directory");
let cwd = PathUri::from_host_native_path(&original).expect("original executor URI");
for target_identity in [
"openai-curated-remote/other/2.0.0",
"openai-curated-remote/sites/1.2.3",
"openai-curated/sites/2.0.0",
"../outside-cache",
] {
let target = reference_identity_fixture(
&executor.path().join("plugins/cache").join(target_identity),
"ignored_executor_metadata",
contents,
);
std::os::unix::fs::symlink(
target.join(REFERENCE_HELPER),
original.join(REFERENCE_HELPER),
)
.expect("redirect helper to another identity");
assert_eq!(
roots
.resolve_metrics_operation_in_filesystem(
&command(&["sh", REFERENCE_HELPER]),
&cwd,
LOCAL_FS.as_ref(),
)
.await,
None,
"canonical identity changed to {target_identity}"
);
fs::remove_file(original.join(REFERENCE_HELPER)).expect("remove helper symlink");
}
}
#[cfg(unix)]
#[tokio::test]
async fn executor_aliases_use_canonical_plugin_paths() {
let contents = "printf shared\\n\n";
let (_reference, roots) = reference_fixture(&[
("sites", "1.2.3", "older", contents),
("sites", "2.0.0", "selected", contents),
]);
let older_roots = TrustedPluginRoots {
roots: vec![roots.roots[0].clone()],
};
let (_reference, roots) =
reference_fixture(&[("sites", "1.2.3", contents), ("sites", "2.0.0", contents)]);
let plugin_id = PluginId::parse("sites@openai-curated-remote").expect("plugin id");
let executor = TempDir::new().expect("executor");
let target = executor_plugin(executor.path(), "sites", "2.0.0", contents);
@@ -1098,48 +631,10 @@ async fn executor_aliases_use_canonical_plugin_paths() {
&command(&["sh", &alias.join(REFERENCE_HELPER).to_string_lossy()]),
&cwd,
&plugin_id,
Some("selected"),
)
.await;
let command = command(&["sh", &version_alias.to_string_lossy()]);
assert_eq!(
PluginMeasurementTarget::from_command(&command, &cwd, LOCAL_FS.as_ref()).await,
Some(PluginMeasurementTarget {
plugin_id: plugin_id.clone(),
version: "2.0.0".to_string(),
path_convention: PathConvention::Posix,
})
);
assert_executor_resolution(&roots, &command, &cwd, &plugin_id, Some("selected")).await;
assert_eq!(
older_roots
.resolve_metrics_operation_in_filesystem(&command, &cwd, LOCAL_FS.as_ref())
.await,
None,
"a V1-shaped alias and identical bytes cannot authorize V2 metrics"
);
}
#[tokio::test]
async fn measurement_target_rejects_inline_commands_and_local_versions() -> anyhow::Result<()> {
let executor = TempDir::new()?;
let root = reference_identity_fixture(
&executor
.path()
.join("plugins/cache/openai-curated-remote/sites/local"),
"ignored",
"printf fixture\n",
);
let cwd = PathUri::from_host_native_path(root.as_path())?;
for args in [&["node", "-e", "42"][..], &["sh", REFERENCE_HELPER][..]] {
let command = command(args);
let fs = codex_exec_server::LOCAL_FS.as_ref();
assert_eq!(
PluginMeasurementTarget::from_command(&command, &cwd, fs).await,
None
);
}
Ok(())
assert_executor_resolution(&roots, &command, &cwd, &plugin_id).await;
}
struct UnusedConnectProvider;
@@ -1155,8 +650,7 @@ impl NoiseRendezvousConnectProvider for UnusedConnectProvider {
#[tokio::test]
async fn unrelated_scripts_skip_executor_lookup() -> anyhow::Result<()> {
let (_reference, roots) =
reference_fixture(&[("sites", "2.0.0", "selected", "printf shared\\n\n")]);
let (_reference, roots) = reference_fixture(&[("sites", "2.0.0", "printf shared\\n\n")]);
let manager = environment_manager_without_environments();
let pending = manager.materialize_pending_noise_environment(
"tools".to_string(),
@@ -1167,13 +661,10 @@ async fn unrelated_scripts_skip_executor_lookup() -> anyhow::Result<()> {
let command = command(&["node", "build.js"]);
// An executor lookup waits for provisioning; unrelated scripts must finish immediately.
assert_eq!(
futures::future::join3(
roots.resolve_executor_attribution(&command, &cwd, fs.as_ref()),
roots.resolve_metrics_operation_in_filesystem(&command, &cwd, fs.as_ref()),
PluginMeasurementTarget::from_command(&command, &cwd, fs.as_ref()),
)
.now_or_never(),
Some((None, None, None)),
roots
.resolve_executor_attribution(&command, &cwd, fs.as_ref())
.now_or_never(),
Some(None),
);
Ok(())
}