Merge remote-tracking branch 'origin/main' into dev/stevenlee/plugin-service-preview-routing

# Conflicts:
#	codex-rs/app-server/src/request_processors/plugins.rs
#	codex-rs/codex-mcp/src/codex_apps.rs
#	codex-rs/codex-mcp/src/connection_manager_tests.rs
#	codex-rs/codex-mcp/src/mcp/mod.rs
#	codex-rs/core/src/connectors.rs
#	codex-rs/core/src/mcp_tool_call_tests.rs
#	codex-rs/core/src/session/mcp.rs
#	codex-rs/core/src/session/session.rs
This commit is contained in:
Steven Lee
2026-06-26 01:44:50 +00:00
769 changed files with 33876 additions and 6833 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
use codex_app_server_protocol::AuthMode;
use codex_plugin::AppDeclaration;
use codex_protocol::auth::AuthMode;
use std::collections::HashMap;
use std::collections::HashSet;
@@ -15,9 +15,9 @@ use crate::test_support::write_curated_plugin_sha_with;
use crate::test_support::write_file;
use crate::test_support::write_openai_api_curated_marketplace;
use crate::test_support::write_openai_curated_marketplace;
use codex_app_server_protocol::AuthMode;
use codex_config::CONFIG_TOML_FILE;
use codex_login::CodexAuth;
use codex_protocol::auth::AuthMode;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use serde_json::json;
@@ -933,14 +933,18 @@ fn string_set(values: &[&str]) -> HashSet<String> {
async fn install_marketplace_plugin(codex_home: &Path, marketplace_root: &Path, plugin_name: &str) {
write_curated_plugin_sha_with(codex_home, TEST_CURATED_PLUGIN_SHA);
let config = load_plugins_config(codex_home, marketplace_root).await;
PluginsManager::new(codex_home.to_path_buf())
.install_plugin(PluginInstallRequest {
plugin_name: plugin_name.to_string(),
marketplace_path: AbsolutePathBuf::try_from(
marketplace_root.join(".agents/plugins/marketplace.json"),
)
.expect("marketplace path"),
})
.install_plugin(
&config.config_layer_stack,
PluginInstallRequest {
plugin_name: plugin_name.to_string(),
marketplace_path: AbsolutePathBuf::try_from(
marketplace_root.join(".agents/plugins/marketplace.json"),
)
.expect("marketplace path"),
},
)
.await
.expect("plugin should install");
}
+3
View File
@@ -6,6 +6,7 @@ mod manager;
pub mod manifest;
pub mod marketplace;
pub mod marketplace_add;
mod marketplace_policy;
pub mod marketplace_remove;
pub mod marketplace_upgrade;
mod plugin_bundle_archive;
@@ -23,6 +24,8 @@ mod tool_suggest_metadata;
pub const OPENAI_CURATED_MARKETPLACE_NAME: &str = "openai-curated";
pub const OPENAI_API_CURATED_MARKETPLACE_NAME: &str = "openai-api-curated";
pub const OPENAI_BUNDLED_MARKETPLACE_NAME: &str = "openai-bundled";
pub(crate) const OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME: &str = "openai-bundled-alpha";
pub(crate) const OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME: &str = "openai-primary-runtime";
pub fn is_openai_curated_marketplace_name(marketplace_name: &str) -> bool {
marketplace_name == OPENAI_CURATED_MARKETPLACE_NAME
+47 -87
View File
@@ -15,12 +15,13 @@ use crate::remote::RemoteInstalledPlugin;
use crate::store::PluginStore;
use crate::store::plugin_version_for_source;
use crate::store::plugin_version_for_source_with_fallback_manifest;
use codex_app_server_protocol::AuthMode;
use codex_config::ConfigLayerStack;
use codex_config::HooksFile;
use codex_config::types::McpServerConfig;
use codex_config::types::PluginConfig;
use codex_config::types::PluginMcpServerConfig;
use codex_connectors::parse_plugin_app_config;
use codex_connectors::parse_plugin_app_config_value;
use codex_core_skills::PluginSkillSnapshots;
use codex_core_skills::SkillMetadata;
use codex_core_skills::config_rules::SkillConfigRules;
@@ -29,9 +30,7 @@ use codex_core_skills::config_rules::skill_config_rules_from_stack;
use codex_core_skills::loader::SkillRoot;
use codex_core_skills::loader::load_skills_from_roots;
use codex_exec_server::LOCAL_FS;
use codex_mcp::PluginMcpServerPlacement;
use codex_mcp::parse_plugin_mcp_config;
use codex_plugin::AppConnectorId;
use codex_plugin::AppDeclaration;
use codex_plugin::LoadedPlugin;
use codex_plugin::PluginCapabilitySummary;
@@ -39,12 +38,11 @@ use codex_plugin::PluginHookSource;
use codex_plugin::PluginId;
use codex_plugin::PluginIdError;
use codex_plugin::app_connector_ids_from_declarations;
use codex_protocol::auth::AuthMode;
use codex_protocol::protocol::Product;
use codex_protocol::protocol::SkillScope;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_plugins::find_plugin_manifest_path;
use indexmap::IndexMap;
use serde::Deserialize;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::collections::HashSet;
@@ -97,19 +95,6 @@ pub(crate) fn log_plugin_load_errors(plugins: &[LoadedPlugin<McpServerConfig>])
}
}
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PluginAppFile {
#[serde(default)]
apps: IndexMap<String, PluginAppConfig>,
}
#[derive(Debug, Default, Deserialize)]
struct PluginAppConfig {
id: String,
category: Option<String>,
}
/// Load configured plugins without applying auth-dependent runtime policies.
#[instrument(level = "trace", skip_all)]
pub(crate) async fn load_plugins_from_layer_stack(
@@ -118,14 +103,14 @@ pub(crate) async fn load_plugins_from_layer_stack(
store: &PluginStore,
plugin_skill_snapshots: Option<&PluginSkillSnapshots>,
restriction_product: Option<Product>,
prefer_remote_curated_conflicts: bool,
remote_global_catalog_active: bool,
) -> Vec<LoadedPlugin<McpServerConfig>> {
let skill_config_rules = skill_config_rules_from_stack(config_layer_stack);
load_plugins_from_layer_stack_with_scope(
config_layer_stack,
extra_plugins,
store,
prefer_remote_curated_conflicts,
remote_global_catalog_active,
PluginLoadScope::AllCapabilities {
restriction_product,
skill_config_rules: &skill_config_rules,
@@ -139,14 +124,14 @@ async fn load_plugins_from_layer_stack_with_scope(
config_layer_stack: &ConfigLayerStack,
extra_plugins: HashMap<String, PluginConfig>,
store: &PluginStore,
prefer_remote_curated_conflicts: bool,
remote_global_catalog_active: bool,
scope: PluginLoadScope<'_>,
) -> Vec<LoadedPlugin<McpServerConfig>> {
let configured_plugins = merge_configured_plugins_with_remote_installed(
configured_plugins_from_stack(config_layer_stack),
extra_plugins,
store,
prefer_remote_curated_conflicts,
remote_global_catalog_active,
);
let mut configured_plugins: Vec<_> = configured_plugins.into_iter().collect();
configured_plugins.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
@@ -178,13 +163,13 @@ pub async fn load_plugin_hooks_from_layer_stack(
config_layer_stack: &ConfigLayerStack,
extra_plugins: HashMap<String, PluginConfig>,
store: &PluginStore,
prefer_remote_curated_conflicts: bool,
remote_global_catalog_active: bool,
) -> PluginHookLoadOutcome {
let plugins = load_plugins_from_layer_stack_with_scope(
config_layer_stack,
extra_plugins,
store,
prefer_remote_curated_conflicts,
remote_global_catalog_active,
PluginLoadScope::HooksOnly,
)
.await;
@@ -206,8 +191,17 @@ fn merge_configured_plugins_with_remote_installed(
mut configured_plugins: HashMap<String, PluginConfig>,
extra_plugins: HashMap<String, PluginConfig>,
store: &PluginStore,
prefer_remote_curated_conflicts: bool,
remote_global_catalog_active: bool,
) -> HashMap<String, PluginConfig> {
if remote_global_catalog_active {
configured_plugins.retain(|plugin_key, _| match PluginId::parse(plugin_key) {
Ok(plugin_id) => plugin_id.marketplace_name != crate::OPENAI_CURATED_MARKETPLACE_NAME,
Err(_) => true,
});
configured_plugins.extend(extra_plugins);
return configured_plugins;
}
let mut local_curated_installed_plugin_keys = HashMap::<String, Vec<String>>::new();
for plugin_key in configured_plugins.keys() {
let Ok(plugin_id) = PluginId::parse(plugin_key) else {
@@ -234,14 +228,8 @@ fn merge_configured_plugins_with_remote_installed(
.as_ref()
.and_then(|plugin_name| local_curated_installed_plugin_keys.get(plugin_name));
if let Some(local_curated_plugin_keys) = local_curated_plugin_keys {
if prefer_remote_curated_conflicts {
for local_curated_plugin_key in local_curated_plugin_keys {
configured_plugins.remove(local_curated_plugin_key);
}
} else {
continue;
}
if local_curated_plugin_keys.is_some() {
continue;
}
configured_plugins.insert(plugin_key, plugin_config);
@@ -963,10 +951,10 @@ pub(crate) async fn load_plugin_apps_from_manifest(
}
pub fn plugin_app_declarations_from_value(value: &JsonValue) -> Vec<AppDeclaration> {
let Ok(parsed) = serde_json::from_value::<PluginAppFile>(value.clone()) else {
let Ok(mut apps) = parse_plugin_app_config_value(value.clone()) else {
return Vec::new();
};
let mut apps = app_declarations_from_file(parsed, /*plugin_root*/ None);
apps.retain(|app| !app.connector_id.0.trim().is_empty());
let mut seen_connector_ids = HashSet::new();
apps.retain(|app| seen_connector_ids.insert(app.connector_id.0.clone()));
apps
@@ -1114,8 +1102,8 @@ async fn load_apps_from_paths(
let Ok(contents) = tokio::fs::read_to_string(app_config_path.as_path()).await else {
continue;
};
let parsed = match serde_json::from_str::<PluginAppFile>(&contents) {
Ok(parsed) => parsed,
let declarations = match parse_plugin_app_config(&contents) {
Ok(declarations) => declarations,
Err(err) => {
warn!(
path = %app_config_path.display(),
@@ -1125,44 +1113,21 @@ async fn load_apps_from_paths(
}
};
app_declarations.extend(app_declarations_from_file(parsed, Some(plugin_root)));
app_declarations.extend(declarations.into_iter().filter(|app| {
if app.connector_id.0.trim().is_empty() {
warn!(
plugin = %plugin_root.display(),
"plugin app config is missing an app id"
);
false
} else {
true
}
}));
}
app_declarations
}
fn app_declarations_from_file(
parsed: PluginAppFile,
plugin_root: Option<&Path>,
) -> Vec<AppDeclaration> {
parsed
.apps
.into_iter()
.filter_map(|(name, app)| {
if app.id.trim().is_empty() {
if let Some(plugin_root) = plugin_root {
warn!(
plugin = %plugin_root.display(),
"plugin app config is missing an app id"
);
}
None
} else {
Some(AppDeclaration {
name,
connector_id: AppConnectorId(app.id),
category: cleaned_app_category(app.category),
})
}
})
.collect()
}
fn cleaned_app_category(category: Option<String>) -> Option<String> {
category
.map(|category| category.trim().to_string())
.filter(|category| !category.is_empty())
}
pub async fn plugin_capability_summary_from_root(
plugin_id: &PluginId,
plugin_root: &AbsolutePathBuf,
@@ -1279,17 +1244,16 @@ async fn load_mcp_servers_from_file(
let Ok(contents) = tokio::fs::read_to_string(mcp_config_path.as_path()).await else {
return PluginMcpDiscovery::default();
};
let parsed =
match parse_plugin_mcp_config(plugin_root, &contents, PluginMcpServerPlacement::Declared) {
Ok(parsed) => parsed,
Err(err) => {
warn!(
path = %mcp_config_path.display(),
"failed to parse plugin MCP config: {err}"
);
return PluginMcpDiscovery::default();
}
};
let parsed = match parse_plugin_mcp_config(plugin_root, &contents) {
Ok(parsed) => parsed,
Err(err) => {
warn!(
path = %mcp_config_path.display(),
"failed to parse plugin MCP config: {err}"
);
return PluginMcpDiscovery::default();
}
};
for error in parsed.errors {
warn!(
plugin = %plugin_root.display(),
@@ -1308,11 +1272,7 @@ fn load_mcp_servers_from_manifest_object(
plugin_root: &Path,
object_config: &str,
) -> PluginMcpDiscovery {
let parsed = match parse_plugin_mcp_config(
plugin_root,
object_config,
PluginMcpServerPlacement::Declared,
) {
let parsed = match parse_plugin_mcp_config(plugin_root, object_config) {
Ok(parsed) => parsed,
Err(err) => {
warn!(
+2 -2
View File
@@ -162,14 +162,14 @@ enabled = true
&store,
/*plugin_skill_snapshots*/ None,
Some(Product::Codex),
/*prefer_remote_curated_conflicts*/ false,
/*remote_global_catalog_active*/ false,
)
.await;
let hooks_only = load_plugins_from_layer_stack_with_scope(
&stack,
HashMap::new(),
&store,
/*prefer_remote_curated_conflicts*/ false,
/*remote_global_catalog_active*/ false,
PluginLoadScope::HooksOnly,
)
.await;
+55 -36
View File
@@ -34,9 +34,9 @@ use crate::marketplace::find_installable_marketplace_plugin;
use crate::marketplace::find_marketplace_plugin;
use crate::marketplace::list_marketplaces;
use crate::marketplace::plugin_interface_with_marketplace_category;
use crate::marketplace_policy::MarketplacePolicy;
use crate::marketplace_upgrade::ConfiguredMarketplaceUpgradeError;
use crate::marketplace_upgrade::ConfiguredMarketplaceUpgradeOutcome;
use crate::marketplace_upgrade::configured_git_marketplace_names;
use crate::marketplace_upgrade::upgrade_configured_git_marketplaces;
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
use crate::remote::RecommendedPluginsMode;
@@ -54,7 +54,6 @@ use crate::store::PluginStore;
use crate::store::PluginStoreError;
use crate::tool_suggest_metadata::ToolSuggestMetadataCache;
use codex_analytics::AnalyticsEventsClient;
use codex_app_server_protocol::AuthMode;
use codex_config::ConfigLayerStack;
use codex_config::clear_user_plugin;
use codex_config::set_user_plugin_enabled;
@@ -75,6 +74,7 @@ use codex_plugin::PluginIdError;
use codex_plugin::PluginTelemetryMetadata;
use codex_plugin::app_connector_ids_from_declarations;
use codex_plugin::prompt_safe_plugin_description;
use codex_protocol::auth::AuthMode;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::Product;
use codex_tools::DiscoverablePluginInfo;
@@ -392,15 +392,15 @@ struct LoadedPluginsCache {
struct PluginLoadCacheKey {
configured_plugins: HashMap<String, PluginConfig>,
skill_config_rules: SkillConfigRules,
remote_plugin_enabled: bool,
remote_global_catalog_active: bool,
}
impl PluginLoadCacheKey {
fn from_config(config: &PluginsConfigInput) -> Self {
fn from_config(config: &PluginsConfigInput, remote_global_catalog_active: bool) -> Self {
Self {
configured_plugins: configured_plugins_from_stack(&config.config_layer_stack),
skill_config_rules: skill_config_rules_from_stack(&config.config_layer_stack),
remote_plugin_enabled: config.remote_plugin_enabled,
remote_global_catalog_active,
}
}
}
@@ -467,6 +467,10 @@ impl PluginsManager {
}
}
fn remote_global_catalog_active(&self, config: &PluginsConfigInput) -> bool {
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,
@@ -498,7 +502,8 @@ impl PluginsManager {
if !config.plugins_enabled {
return None;
}
let key = PluginLoadCacheKey::from_config(config);
let key =
PluginLoadCacheKey::from_config(config, self.remote_global_catalog_active(config));
self.loaded_plugins_cache
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
@@ -527,7 +532,8 @@ impl PluginsManager {
return PluginLoadOutcome::default();
}
let cache_key = PluginLoadCacheKey::from_config(config);
let remote_global_catalog_active = self.remote_global_catalog_active(config);
let cache_key = PluginLoadCacheKey::from_config(config, remote_global_catalog_active);
if !force_reload && let Some(plugins) = self.cached_loaded_plugins(&cache_key) {
return self.resolve_loaded_plugins_for_auth(plugins);
}
@@ -547,7 +553,7 @@ impl PluginsManager {
&self.store,
Some(&plugin_skill_snapshots),
self.restriction_product,
config.remote_plugin_enabled,
remote_global_catalog_active,
)
.await;
log_plugin_load_errors(&plugins);
@@ -632,7 +638,7 @@ impl PluginsManager {
&self.store,
/*plugin_skill_snapshots*/ None,
self.restriction_product,
config.remote_plugin_enabled,
self.remote_global_catalog_active(config),
)
.await;
self.resolve_loaded_plugins_for_auth(plugins)
@@ -651,7 +657,7 @@ impl PluginsManager {
config_layer_stack,
self.remote_installed_plugin_configs(),
&self.store,
config.remote_plugin_enabled,
self.remote_global_catalog_active(config),
)
.await
}
@@ -1255,19 +1261,10 @@ impl PluginsManager {
pub async fn install_plugin(
&self,
config_layer_stack: &ConfigLayerStack,
request: PluginInstallRequest,
) -> Result<PluginInstallOutcome, PluginInstallError> {
let resolved = match find_installable_marketplace_plugin(
&request.marketplace_path,
&request.plugin_name,
self.restriction_product,
) {
Ok(resolved) => resolved,
Err(err) => {
self.track_plugin_install_resolution_failed(&err);
return Err(err.into());
}
};
let resolved = self.resolve_installable_plugin(config_layer_stack, &request)?;
let plugin_id = resolved.plugin_id.clone();
match self.install_resolved_plugin(resolved).await {
Ok(outcome) => Ok(outcome),
@@ -1282,12 +1279,11 @@ impl PluginsManager {
}
}
pub async fn install_plugin_with_remote_sync(
fn resolve_installable_plugin(
&self,
config: &PluginsConfigInput,
auth: Option<&CodexAuth>,
request: PluginInstallRequest,
) -> Result<PluginInstallOutcome, PluginInstallError> {
config_layer_stack: &ConfigLayerStack,
request: &PluginInstallRequest,
) -> Result<ResolvedMarketplacePlugin, PluginInstallError> {
let resolved = match find_installable_marketplace_plugin(
&request.marketplace_path,
&request.plugin_name,
@@ -1299,6 +1295,32 @@ impl PluginsManager {
return Err(err.into());
}
};
if let Err(message) =
MarketplacePolicy::from_requirements(config_layer_stack.requirements())
.validate_install(
config_layer_stack,
self.codex_home.as_path(),
&request.marketplace_path,
&resolved.plugin_id.marketplace_name,
)
{
let err = MarketplaceError::InvalidMarketplaceFile {
path: request.marketplace_path.to_path_buf(),
message,
};
self.track_plugin_install_resolution_failed(&err);
return Err(err.into());
}
Ok(resolved)
}
pub async fn install_plugin_with_remote_sync(
&self,
config: &PluginsConfigInput,
auth: Option<&CodexAuth>,
request: PluginInstallRequest,
) -> Result<PluginInstallOutcome, PluginInstallError> {
let resolved = self.resolve_installable_plugin(&config.config_layer_stack, &request)?;
let plugin_id = resolved.plugin_id.as_key();
// This only forwards the backend mutation before the local install flow.
if let Err(err) = crate::remote_legacy::enable_remote_plugin(
@@ -1997,21 +2019,18 @@ impl PluginsManager {
config: &PluginsConfigInput,
marketplace_name: Option<&str>,
) -> Result<ConfiguredMarketplaceUpgradeOutcome, String> {
if let Some(marketplace_name) = marketplace_name
&& !configured_git_marketplace_names(&config.config_layer_stack)
.iter()
.any(|name| name == marketplace_name)
{
return Err(format!(
"marketplace `{marketplace_name}` is not configured as a Git marketplace"
));
}
let mut outcome = upgrade_configured_git_marketplaces(
self.codex_home.as_path(),
&config.config_layer_stack,
marketplace_name,
);
if let Some(marketplace_name) = marketplace_name
&& outcome.selected_marketplaces.is_empty()
{
return Err(format!(
"marketplace `{marketplace_name}` is not configured as a Git marketplace"
));
}
if !outcome.upgraded_roots.is_empty() {
match refresh_non_curated_plugin_cache_force_reinstall(
self.codex_home.as_path(),
+233 -50
View File
@@ -25,17 +25,19 @@ use crate::test_support::write_curated_plugin_sha_with as write_curated_plugin_s
use crate::test_support::write_file;
use crate::test_support::write_openai_api_curated_marketplace;
use crate::test_support::write_openai_curated_marketplace;
use codex_app_server_protocol::AuthMode;
use codex_app_server_protocol::ConfigLayerSource;
use codex_config::AppToolApproval;
use codex_config::CONFIG_TOML_FILE;
use codex_config::ConfigLayerEntry;
use codex_config::ConfigLayerSource;
use codex_config::ConfigLayerStack;
use codex_config::ConfigRequirements;
use codex_config::ConfigRequirementsToml;
use codex_config::McpServerConfig;
use codex_config::McpServerOAuthConfig;
use codex_config::McpServerToolConfig;
use codex_config::RequirementSource;
use codex_config::RequirementsLayerEntry;
use codex_config::compose_requirements;
use codex_config::types::McpServerTransportConfig;
use codex_core_skills::PluginSkillSnapshots;
use codex_core_skills::SkillsLoadInput;
@@ -44,6 +46,7 @@ use codex_core_skills::config_rules::SkillConfigRules;
use codex_login::CodexAuth;
use codex_plugin::AppDeclaration;
use codex_plugin::PluginId;
use codex_protocol::auth::AuthMode;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::Product;
use codex_utils_absolute_path::AbsolutePathBuf;
@@ -64,6 +67,39 @@ use wiremock::matchers::query_param;
const MAX_CAPABILITY_SUMMARY_DESCRIPTION_LEN: usize = 1024;
fn unrestricted_config_layer_stack() -> ConfigLayerStack {
ConfigLayerStack::default()
}
fn config_layer_stack_with_requirements(
codex_home: &Path,
user_config: &str,
requirements: &str,
) -> ConfigLayerStack {
let with_sources = compose_requirements([RequirementsLayerEntry::from_toml(
RequirementSource::Unknown,
requirements,
)])
.expect("compose requirements")
.expect("requirements should be present");
let requirements_toml = with_sources.clone().into_toml();
let requirements = ConfigRequirements::try_from(with_sources).expect("normalize requirements");
let config_file =
AbsolutePathBuf::try_from(codex_home.join(CONFIG_TOML_FILE)).expect("absolute config path");
ConfigLayerStack::new(
vec![ConfigLayerEntry::new(
ConfigLayerSource::User {
file: config_file,
profile: None,
},
toml::from_str(user_config).expect("parse user config"),
)],
requirements,
requirements_toml,
)
.expect("build config layer stack")
}
#[test]
fn plugins_manager_tracks_auth_mode() {
let tmp = TempDir::new().unwrap();
@@ -641,6 +677,7 @@ async fn load_plugins_loads_default_skills_and_mcp_servers() {
mcp_servers: HashMap::from([(
"sample".to_string(),
McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: "https://sample.example/mcp".to_string(),
bearer_token_env_var: None,
@@ -732,6 +769,7 @@ enabled = true
HashMap::from([(
"counter".to_string(),
McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: "https://sample.example/counter/mcp".to_string(),
bearer_token_env_var: None,
@@ -1061,7 +1099,7 @@ enabled = true
}
#[tokio::test]
async fn remote_installed_cache_prefers_remote_curated_conflicts_when_remote_plugin_enabled() {
async fn remote_global_catalog_ignores_local_curated_plugins() {
let codex_home = TempDir::new().unwrap();
write_file(
&codex_home.path().join(CONFIG_TOML_FILE),
@@ -1086,7 +1124,11 @@ enabled = true
write_cached_plugin(codex_home.path(), "openai-curated-remote", "remote-only");
let config = load_config(codex_home.path(), codex_home.path()).await;
let manager = PluginsManager::new(codex_home.path().to_path_buf());
let manager = PluginsManager::new_with_options(
codex_home.path().to_path_buf(),
Some(Product::Codex),
Some(AuthMode::Chatgpt),
);
manager.write_remote_installed_plugins_cache(vec![
remote_installed_plugin("linear"),
remote_installed_plugin("remote-only"),
@@ -1100,13 +1142,54 @@ enabled = true
.map(|plugin| plugin.config_name.clone())
.collect::<Vec<_>>(),
vec![
"calendar@openai-curated".to_string(),
"linear@openai-api-curated".to_string(),
"linear@openai-curated-remote".to_string(),
"remote-only@openai-curated-remote".to_string(),
]
);
}
#[tokio::test]
async fn remote_plugin_feature_keeps_local_curated_without_codex_backend() {
let codex_home = TempDir::new().unwrap();
write_file(
&codex_home.path().join(CONFIG_TOML_FILE),
r#"[features]
plugins = true
remote_plugin = true
[plugins."linear@openai-curated"]
enabled = true
[plugins."linear@openai-api-curated"]
enabled = true
"#,
);
write_cached_plugin(codex_home.path(), "openai-curated", "linear");
write_cached_plugin(codex_home.path(), "openai-api-curated", "linear");
let config = load_config(codex_home.path(), codex_home.path()).await;
let manager = PluginsManager::new_with_options(
codex_home.path().to_path_buf(),
Some(Product::Codex),
Some(AuthMode::ApiKey),
);
let outcome = manager.plugins_for_config(&config).await;
assert_eq!(
outcome
.plugins()
.iter()
.map(|plugin| plugin.config_name.clone())
.collect::<Vec<_>>(),
vec![
"linear@openai-api-curated".to_string(),
"linear@openai-curated".to_string(),
]
);
}
#[tokio::test]
async fn build_remote_installed_plugin_marketplaces_from_cache_uses_remote_metadata() {
let codex_home = TempDir::new().unwrap();
@@ -1581,6 +1664,7 @@ async fn load_plugins_uses_manifest_configured_component_paths() {
HashMap::from([(
"custom".to_string(),
McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: "https://custom.example/mcp".to_string(),
bearer_token_env_var: None,
@@ -1761,6 +1845,7 @@ async fn load_plugins_ignores_manifest_component_paths_without_dot_slash() {
HashMap::from([(
"default".to_string(),
McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: "https://default.example/mcp".to_string(),
bearer_token_env_var: None,
@@ -2011,6 +2096,7 @@ fn capability_index_filters_inactive_and_zero_capability_plugins() {
let connector = |id: &str| AppConnectorId(id.to_string());
let app = |name: &str, connector_id: &str| app_declaration(name, connector_id);
let http_server = |url: &str| McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: url.to_string(),
bearer_token_env_var: None,
@@ -2273,7 +2359,7 @@ fn loaded_plugins_cache_invalidation_rejects_stale_load_completion() {
let cache_key = PluginLoadCacheKey {
configured_plugins: HashMap::new(),
skill_config_rules: SkillConfigRules::default(),
remote_plugin_enabled: false,
remote_global_catalog_active: false,
};
let stale_generation = manager.loaded_plugins_cache_generation();
@@ -2357,13 +2443,16 @@ async fn install_plugin_updates_config_with_relative_path_and_plugin_key() {
.unwrap();
let result = PluginsManager::new(tmp.path().to_path_buf())
.install_plugin(PluginInstallRequest {
plugin_name: "sample-plugin".to_string(),
marketplace_path: AbsolutePathBuf::try_from(
repo_root.join(".agents/plugins/marketplace.json"),
)
.unwrap(),
})
.install_plugin(
&unrestricted_config_layer_stack(),
PluginInstallRequest {
plugin_name: "sample-plugin".to_string(),
marketplace_path: AbsolutePathBuf::try_from(
repo_root.join(".agents/plugins/marketplace.json"),
)
.unwrap(),
},
)
.await
.unwrap();
@@ -2383,6 +2472,85 @@ async fn install_plugin_updates_config_with_relative_path_and_plugin_key() {
assert!(config.contains("enabled = true"));
}
#[tokio::test]
async fn strict_install_requires_allowed_local_marketplace_to_be_added_first() {
let codex_home = TempDir::new().expect("create Codex home");
let marketplace_root = codex_home.path().join("company-marketplace");
write_plugin(&marketplace_root, "sample", "sample");
write_file(
&marketplace_root.join(".agents/plugins/marketplace.json"),
r#"{
"name": "company",
"plugins": [
{
"name": "sample",
"source": {"source": "local", "path": "./sample"}
}
]
}"#,
);
let marketplace_root = marketplace_root
.canonicalize()
.expect("canonical marketplace root");
let requirements = format!(
r#"
[marketplaces]
restrict_to_allowed_sources = true
[marketplaces.allowed_sources.company]
source = "local"
path = {marketplace_root:?}
"#
);
let config = config_layer_stack_with_requirements(codex_home.path(), "", &requirements);
let marketplace_path =
AbsolutePathBuf::try_from(marketplace_root.join(".agents/plugins/marketplace.json"))
.expect("absolute marketplace path");
let manager = PluginsManager::new(codex_home.path().to_path_buf());
let err = manager
.install_plugin(
&config,
PluginInstallRequest {
plugin_name: "sample".to_string(),
marketplace_path: marketplace_path.clone(),
},
)
.await
.expect_err("unconfigured local marketplace should not be installable in strict mode");
assert!(matches!(
err,
PluginInstallError::Marketplace(MarketplaceError::InvalidMarketplaceFile { .. })
));
assert!(err.to_string().contains("must be added to config"));
assert!(!codex_home.path().join(CONFIG_TOML_FILE).exists());
let user_config = format!(
r#"
[marketplaces.company]
source_type = "local"
source = {marketplace_root:?}
"#
);
write_file(&codex_home.path().join(CONFIG_TOML_FILE), &user_config);
let config =
config_layer_stack_with_requirements(codex_home.path(), &user_config, &requirements);
let outcome = manager
.install_plugin(
&config,
PluginInstallRequest {
plugin_name: "sample".to_string(),
marketplace_path,
},
)
.await
.expect("configured allowlisted marketplace should be installable");
assert_eq!(
outcome.plugin_id,
PluginId::new("sample".to_string(), "company".to_string()).expect("plugin id")
);
}
#[tokio::test]
async fn install_openai_curated_plugin_uses_short_sha_cache_version() {
let tmp = tempfile::tempdir().unwrap();
@@ -2391,13 +2559,16 @@ async fn install_openai_curated_plugin_uses_short_sha_cache_version() {
write_curated_plugin_sha(tmp.path(), TEST_CURATED_PLUGIN_SHA);
let result = PluginsManager::new(tmp.path().to_path_buf())
.install_plugin(PluginInstallRequest {
plugin_name: "slack".to_string(),
marketplace_path: AbsolutePathBuf::try_from(
curated_root.join(".agents/plugins/marketplace.json"),
)
.unwrap(),
})
.install_plugin(
&unrestricted_config_layer_stack(),
PluginInstallRequest {
plugin_name: "slack".to_string(),
marketplace_path: AbsolutePathBuf::try_from(
curated_root.join(".agents/plugins/marketplace.json"),
)
.unwrap(),
},
)
.await
.unwrap();
@@ -2449,13 +2620,16 @@ async fn install_plugin_uses_manifest_version_for_non_curated_plugins() {
.unwrap();
let result = PluginsManager::new(tmp.path().to_path_buf())
.install_plugin(PluginInstallRequest {
plugin_name: "sample-plugin".to_string(),
marketplace_path: AbsolutePathBuf::try_from(
repo_root.join(".agents/plugins/marketplace.json"),
)
.unwrap(),
})
.install_plugin(
&unrestricted_config_layer_stack(),
PluginInstallRequest {
plugin_name: "sample-plugin".to_string(),
marketplace_path: AbsolutePathBuf::try_from(
repo_root.join(".agents/plugins/marketplace.json"),
)
.unwrap(),
},
)
.await
.unwrap();
@@ -2509,13 +2683,16 @@ async fn install_plugin_writes_marketplace_manifest_fallback_when_missing_plugin
.unwrap();
let result = PluginsManager::new(tmp.path().to_path_buf())
.install_plugin(PluginInstallRequest {
plugin_name: "quality-review".to_string(),
marketplace_path: AbsolutePathBuf::try_from(
repo_root.join(".agents/plugins/marketplace.json"),
)
.unwrap(),
})
.install_plugin(
&unrestricted_config_layer_stack(),
PluginInstallRequest {
plugin_name: "quality-review".to_string(),
marketplace_path: AbsolutePathBuf::try_from(
repo_root.join(".agents/plugins/marketplace.json"),
)
.unwrap(),
},
)
.await
.unwrap();
@@ -2598,13 +2775,16 @@ async fn install_plugin_supports_git_subdir_marketplace_sources() {
.unwrap();
let result = PluginsManager::new(tmp.path().to_path_buf())
.install_plugin(PluginInstallRequest {
plugin_name: "toolkit".to_string(),
marketplace_path: AbsolutePathBuf::try_from(
repo_root.join(".agents/plugins/marketplace.json"),
)
.unwrap(),
})
.install_plugin(
&unrestricted_config_layer_stack(),
PluginInstallRequest {
plugin_name: "toolkit".to_string(),
marketplace_path: AbsolutePathBuf::try_from(
repo_root.join(".agents/plugins/marketplace.json"),
)
.unwrap(),
},
)
.await
.unwrap();
@@ -2649,13 +2829,16 @@ async fn install_plugin_supports_relative_git_subdir_marketplace_sources() {
.unwrap();
let result = PluginsManager::new(tmp.path().to_path_buf())
.install_plugin(PluginInstallRequest {
plugin_name: "toolkit".to_string(),
marketplace_path: AbsolutePathBuf::try_from(
repo_root.join(".agents/plugins/marketplace.json"),
)
.unwrap(),
})
.install_plugin(
&unrestricted_config_layer_stack(),
PluginInstallRequest {
plugin_name: "toolkit".to_string(),
marketplace_path: AbsolutePathBuf::try_from(
repo_root.join(".agents/plugins/marketplace.json"),
)
.unwrap(),
},
)
.await
.unwrap();
@@ -4049,7 +4232,7 @@ source = "{remote_repo_url}"
run_git(&remote_repo, &["add", "."]);
run_git(&remote_repo, &["commit", "-m", "update plugin"]);
let upgrade = manager
.upgrade_configured_marketplaces_for_config(&config, /*marketplace_name*/ None)
.upgrade_configured_marketplaces_for_config(&config, Some("debug"))
.expect("marketplace upgrade should succeed");
assert_eq!(upgrade.errors, Vec::new());
assert_eq!(upgrade.upgraded_roots.len(), 1);
@@ -5398,7 +5581,7 @@ async fn load_plugins_ignores_project_config_files() {
&PluginStore::new(codex_home.path().to_path_buf()),
/*plugin_skill_snapshots*/ None,
Some(Product::Codex),
/*prefer_remote_curated_conflicts*/ false,
/*remote_global_catalog_active*/ false,
)
.await;
+199 -60
View File
@@ -1,10 +1,11 @@
use codex_config::HooksFile;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathConvention;
use codex_utils_path_uri::PathUri;
use codex_utils_plugins::find_plugin_manifest_path;
use serde::Deserialize;
use serde_json::Value as JsonValue;
use std::fs;
use std::path::Component;
use std::path::Path;
const MAX_DEFAULT_PROMPT_COUNT: usize = 3;
const MAX_DEFAULT_PROMPT_LEN: usize = 128;
@@ -16,6 +17,8 @@ pub type PluginManifestMcpServers =
codex_plugin::manifest::PluginManifestMcpServers<AbsolutePathBuf>;
pub type PluginManifestPaths = codex_plugin::manifest::PluginManifestPaths<AbsolutePathBuf>;
pub(crate) type UriPluginManifest = codex_plugin::manifest::PluginManifest<PathUri>;
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawPluginManifest {
@@ -141,6 +144,19 @@ pub(crate) fn parse_plugin_manifest(
manifest_path: &Path,
contents: &str,
) -> Result<PluginManifest, serde_json::Error> {
let plugin_root_uri =
PathUri::from_host_native_path(plugin_root).map_err(serde_json::Error::io)?;
let manifest_path_uri =
PathUri::from_host_native_path(manifest_path).map_err(serde_json::Error::io)?;
parse_plugin_manifest_uri(&plugin_root_uri, &manifest_path_uri, contents)?
.try_map_resources(|path| path.to_abs_path().map_err(serde_json::Error::io))
}
pub(crate) fn parse_plugin_manifest_uri(
plugin_root: &PathUri,
manifest_path: &PathUri,
contents: &str,
) -> Result<UriPluginManifest, serde_json::Error> {
let RawPluginManifest {
name: raw_name,
version,
@@ -153,11 +169,10 @@ pub(crate) fn parse_plugin_manifest(
interface,
} = serde_json::from_str::<RawPluginManifest>(contents)?;
let name = plugin_root
.file_name()
.and_then(|entry| entry.to_str())
.basename()
.filter(|_| raw_name.trim().is_empty())
.unwrap_or(&raw_name)
.to_string();
.unwrap_or(raw_name);
let manifest_path_for_warning = manifest_path.to_string();
let version = version.and_then(|version| {
let version = version.trim();
(!version.is_empty()).then(|| version.to_string())
@@ -181,7 +196,7 @@ pub(crate) fn parse_plugin_manifest(
screenshots,
} = interface;
let interface = PluginManifestInterface {
let interface = codex_plugin::manifest::PluginManifestInterface {
display_name,
short_description,
long_description,
@@ -191,7 +206,10 @@ pub(crate) fn parse_plugin_manifest(
website_url,
privacy_policy_url,
terms_of_service_url,
default_prompt: resolve_default_prompts(manifest_path, default_prompt.as_ref()),
default_prompt: resolve_default_prompts(
&manifest_path_for_warning,
default_prompt.as_ref(),
),
brand_color,
composer_icon: resolve_interface_asset_path(
plugin_root,
@@ -234,12 +252,12 @@ pub(crate) fn parse_plugin_manifest(
has_fields.then_some(interface)
});
Ok(PluginManifest {
Ok(codex_plugin::manifest::PluginManifest {
name,
version,
description,
keywords,
paths: PluginManifestPaths {
paths: codex_plugin::manifest::PluginManifestPaths {
skills: resolve_manifest_paths(plugin_root, "skills", skills.as_ref()),
mcp_servers: resolve_manifest_mcp_servers(plugin_root, mcp_servers),
apps: resolve_manifest_path(plugin_root, "apps", apps.as_deref()),
@@ -250,25 +268,28 @@ pub(crate) fn parse_plugin_manifest(
}
fn resolve_manifest_hooks(
plugin_root: &Path,
plugin_root: &PathUri,
hooks: Option<RawPluginManifestHooks>,
) -> Option<PluginManifestHooks> {
) -> Option<codex_plugin::manifest::PluginManifestHooks<PathUri>> {
match hooks? {
RawPluginManifestHooks::Path(path) => {
resolve_manifest_path(plugin_root, "hooks", Some(&path))
.map(|path| PluginManifestHooks::Paths(vec![path]))
.map(|path| codex_plugin::manifest::PluginManifestHooks::Paths(vec![path]))
}
RawPluginManifestHooks::Paths(paths) => {
let hooks = paths
.iter()
.filter_map(|path| resolve_manifest_path(plugin_root, "hooks", Some(path)))
.collect::<Vec<_>>();
(!hooks.is_empty()).then_some(PluginManifestHooks::Paths(hooks))
(!hooks.is_empty()).then_some(codex_plugin::manifest::PluginManifestHooks::Paths(hooks))
}
RawPluginManifestHooks::Inline(hooks) => Some(PluginManifestHooks::Inline(vec![hooks])),
RawPluginManifestHooks::InlineList(hooks) => {
(!hooks.is_empty()).then_some(PluginManifestHooks::Inline(hooks))
RawPluginManifestHooks::Inline(hooks) => {
Some(codex_plugin::manifest::PluginManifestHooks::Inline(vec![
hooks,
]))
}
RawPluginManifestHooks::InlineList(hooks) => (!hooks.is_empty())
.then_some(codex_plugin::manifest::PluginManifestHooks::Inline(hooks)),
RawPluginManifestHooks::Invalid(value) => {
tracing::warn!(
"ignoring hooks: expected a string, string array, object, or object array; found {}",
@@ -280,16 +301,18 @@ fn resolve_manifest_hooks(
}
fn resolve_manifest_mcp_servers(
plugin_root: &Path,
plugin_root: &PathUri,
mcp_servers: Option<RawPluginManifestMcpServers>,
) -> Option<PluginManifestMcpServers> {
) -> Option<codex_plugin::manifest::PluginManifestMcpServers<PathUri>> {
match mcp_servers? {
RawPluginManifestMcpServers::Path(path) => {
resolve_manifest_path(plugin_root, "mcpServers", Some(&path))
.map(PluginManifestMcpServers::Path)
.map(codex_plugin::manifest::PluginManifestMcpServers::Path)
}
RawPluginManifestMcpServers::Object(servers) => match serde_json::to_string(&servers) {
Ok(servers) => Some(PluginManifestMcpServers::Object(servers)),
Ok(servers) => Some(codex_plugin::manifest::PluginManifestMcpServers::Object(
servers,
)),
Err(err) => {
tracing::warn!("ignoring mcpServers: failed to serialize object: {err}");
None
@@ -306,15 +329,15 @@ fn resolve_manifest_mcp_servers(
}
fn resolve_interface_asset_path(
plugin_root: &Path,
plugin_root: &PathUri,
field: &'static str,
path: Option<&str>,
) -> Option<AbsolutePathBuf> {
) -> Option<PathUri> {
resolve_manifest_path(plugin_root, field, path)
}
fn resolve_default_prompts(
manifest_path: &Path,
manifest_path: &str,
value: Option<&RawPluginManifestDefaultPrompt>,
) -> Option<Vec<String>> {
match value? {
@@ -370,7 +393,7 @@ fn resolve_default_prompts(
}
}
fn resolve_default_prompt_str(manifest_path: &Path, field: &str, prompt: &str) -> Option<String> {
fn resolve_default_prompt_str(manifest_path: &str, field: &str, prompt: &str) -> Option<String> {
let prompt = prompt.split_whitespace().collect::<Vec<_>>().join(" ");
if prompt.is_empty() {
warn_invalid_default_prompt(manifest_path, field, "prompt must not be empty");
@@ -387,11 +410,8 @@ fn resolve_default_prompt_str(manifest_path: &Path, field: &str, prompt: &str) -
Some(prompt)
}
fn warn_invalid_default_prompt(manifest_path: &Path, field: &str, message: &str) {
tracing::warn!(
path = %manifest_path.display(),
"ignoring {field}: {message}"
);
fn warn_invalid_default_prompt(manifest_path: &str, field: &str, message: &str) {
tracing::warn!(path = %manifest_path, "ignoring {field}: {message}");
}
fn json_value_type(value: &JsonValue) -> &'static str {
@@ -406,10 +426,10 @@ fn json_value_type(value: &JsonValue) -> &'static str {
}
fn resolve_manifest_paths(
plugin_root: &Path,
plugin_root: &PathUri,
field: &'static str,
paths: Option<&RawPluginManifestPaths>,
) -> Vec<AbsolutePathBuf> {
) -> Vec<PathUri> {
match paths {
Some(RawPluginManifestPaths::Path(path)) => {
resolve_manifest_path(plugin_root, field, Some(path))
@@ -432,12 +452,10 @@ fn resolve_manifest_paths(
}
fn resolve_manifest_path(
plugin_root: &Path,
plugin_root: &PathUri,
field: &'static str,
path: Option<&str>,
) -> Option<AbsolutePathBuf> {
// `plugin.json` paths are required to be relative to the plugin root and we return the
// normalized absolute path to the rest of the system.
) -> Option<PathUri> {
let path = path?;
if path.is_empty() {
return None;
@@ -451,27 +469,40 @@ fn resolve_manifest_path(
return None;
}
let mut normalized = std::path::PathBuf::new();
for component in Path::new(relative_path).components() {
match component {
Component::Normal(component) => normalized.push(component),
Component::ParentDir => {
tracing::warn!("ignoring {field}: path must not contain '..'");
return None;
}
_ => {
tracing::warn!("ignoring {field}: path must stay within the plugin root");
return None;
}
let convention = plugin_root.infer_path_convention();
let has_parent_component = match convention {
Some(PathConvention::Windows) => relative_path
.split(['/', '\\'])
.any(|component| component == ".."),
Some(PathConvention::Posix) | None => {
relative_path.split('/').any(|component| component == "..")
}
};
if has_parent_component {
tracing::warn!("ignoring {field}: path must not contain '..'");
return None;
}
AbsolutePathBuf::try_from(plugin_root.join(normalized))
.map_err(|err| {
tracing::warn!("ignoring {field}: path must resolve to an absolute path: {err}");
err
})
.ok()
let has_windows_root = convention == Some(PathConvention::Windows)
&& (relative_path.starts_with('\\')
|| matches!(relative_path.as_bytes(), [drive, b':', ..] if drive.is_ascii_alphabetic()));
if relative_path.starts_with('/') || has_windows_root {
tracing::warn!("ignoring {field}: path must stay within the plugin root");
return None;
}
let resolved = match plugin_root.join(relative_path) {
Ok(resolved) => resolved,
Err(err) => {
tracing::warn!("ignoring {field}: path must resolve under plugin root: {err}");
return None;
}
};
if !resolved.starts_with(plugin_root) {
tracing::warn!("ignoring {field}: path must stay within the plugin root");
return None;
}
Some(resolved)
}
#[cfg(test)]
@@ -483,9 +514,15 @@ mod tests {
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_plugin::PluginProvider;
use codex_plugin::ResolvedPlugin;
use codex_plugin::manifest::PluginManifest as GenericPluginManifest;
use codex_plugin::manifest::PluginManifestHooks;
use codex_plugin::manifest::PluginManifestInterface;
use codex_plugin::manifest::PluginManifestMcpServers;
use codex_plugin::manifest::PluginManifestPaths;
use codex_protocol::capabilities::CapabilityRootLocation;
use codex_protocol::capabilities::SelectedCapabilityRoot;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use std::fs;
use std::path::Path;
@@ -695,6 +732,46 @@ mod tests {
);
}
#[test]
fn uri_manifest_uses_the_root_path_convention() {
let windows_root =
PathUri::parse("file:///C:/plugins/demo-plugin").expect("Windows plugin root URI");
let posix_root =
PathUri::parse("file:///plugins/demo-plugin").expect("POSIX plugin root URI");
let composer_icon = r"./assets\..\icon.svg";
assert_eq!(parse_uri_composer_icon(&windows_root, composer_icon), None);
assert_eq!(
parse_uri_composer_icon(&posix_root, composer_icon),
Some(
posix_root
.join(r"assets\..\icon.svg")
.expect("composer icon URI")
)
);
}
fn parse_uri_composer_icon(plugin_root: &PathUri, composer_icon: &str) -> Option<PathUri> {
let manifest_path = plugin_root
.join(".codex-plugin/plugin.json")
.expect("manifest URI");
let composer_icon_json =
serde_json::to_string(composer_icon).expect("serialize composer icon");
let contents = format!(
r#"{{
"name": "demo-plugin",
"interface": {{
"displayName": "Demo Plugin",
"composerIcon": {composer_icon_json}
}}
}}"#
);
super::parse_plugin_manifest_uri(plugin_root, &manifest_path, &contents)
.expect("URI manifest")
.interface
.and_then(|interface| interface.composer_icon)
}
#[tokio::test]
async fn host_and_executor_sources_parse_the_same_manifest() {
let temp_dir = tempdir().expect("tempdir");
@@ -707,14 +784,16 @@ mod tests {
"composerIcon": "./assets/icon.svg"
}"#,
);
let host_manifest = load_plugin_manifest(&plugin_root).expect("host manifest");
let plugin_root =
AbsolutePathBuf::from_absolute_path_checked(plugin_root).expect("absolute plugin root");
let plugin_root_uri = PathUri::from_abs_path(&plugin_root);
let provider =
ExecutorPluginProvider::new(Arc::new(EnvironmentManager::default_for_tests()));
let selected_root = SelectedCapabilityRoot {
id: "selected-demo".to_string(),
location: CapabilityRootLocation::Environment {
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
path: plugin_root.to_string_lossy().into_owned(),
path: plugin_root_uri.clone(),
},
};
@@ -723,17 +802,77 @@ mod tests {
.await
.expect("resolve executor plugin")
.expect("plugin descriptor");
let plugin_root =
AbsolutePathBuf::from_absolute_path_checked(plugin_root).expect("absolute plugin root");
let manifest_path = plugin_root_uri
.join(".codex-plugin/plugin.json")
.expect("manifest URI");
let manifest_contents =
fs::read_to_string(plugin_root.join(".codex-plugin/plugin.json")).expect("manifest");
let expected_manifest =
super::parse_plugin_manifest_uri(&plugin_root_uri, &manifest_path, &manifest_contents)
.expect("URI manifest");
let expected_plugin = ResolvedPlugin::from_environment(
"selected-demo".to_string(),
LOCAL_ENVIRONMENT_ID.to_string(),
plugin_root.clone(),
plugin_root.join(".codex-plugin/plugin.json"),
host_manifest,
plugin_root_uri,
manifest_path,
expected_manifest,
)
.expect("valid expected descriptor");
assert_eq!(executor_plugin, expected_plugin);
}
#[test]
fn uri_manifest_resolves_resources_below_foreign_root() {
let plugin_root =
PathUri::parse("file:///C:/plugins/demo-plugin").expect("plugin root URI");
let manifest_path = plugin_root
.join(".codex-plugin/plugin.json")
.expect("manifest URI");
let manifest = super::parse_plugin_manifest_uri(
&plugin_root,
&manifest_path,
r#"{
"name": "demo-plugin",
"skills": "./skills",
"mcpServers": "./.mcp.json",
"apps": "./apps",
"hooks": "./hooks.json",
"interface": {
"displayName": "Demo Plugin",
"composerIcon": "./assets/icon.svg"
}
}"#,
)
.expect("URI manifest");
assert_eq!(
manifest,
GenericPluginManifest {
name: "demo-plugin".to_string(),
version: None,
description: None,
keywords: Vec::new(),
paths: PluginManifestPaths {
skills: vec![plugin_root.join("skills").expect("skills URI")],
mcp_servers: Some(PluginManifestMcpServers::Path(
plugin_root.join(".mcp.json").expect("MCP URI"),
)),
apps: Some(plugin_root.join("apps").expect("apps URI")),
hooks: Some(PluginManifestHooks::Paths(vec![
plugin_root.join("hooks.json").expect("hooks URI"),
])),
},
interface: Some(PluginManifestInterface {
display_name: Some("Demo Plugin".to_string()),
composer_icon: Some(
plugin_root
.join("assets/icon.svg")
.expect("composer icon URI"),
),
..PluginManifestInterface::default()
}),
}
);
}
}
+5 -4
View File
@@ -86,11 +86,12 @@ impl MarketplacePluginManifestFallback {
}
pub(crate) fn parse_for_listing(&self) -> Option<crate::manifest::PluginManifest> {
// Git sources have no plugin root before install. Parse against a synthetic absolute root,
// then discard path-bearing fields so listings expose metadata only.
// Git sources have no plugin root before install. Parse against a host-native synthetic
// absolute root, then discard path-bearing fields so listings expose metadata only.
let plugin_root = Path::new(if cfg!(windows) { r"C:\" } else { "/" });
let mut manifest = crate::manifest::parse_plugin_manifest(
Path::new("/"),
Path::new("/.codex-plugin/plugin.json"),
plugin_root,
&fallback_plugin_manifest_path(plugin_root),
&self.contents,
)
.ok()?;
+93 -23
View File
@@ -1,5 +1,7 @@
use crate::installed_marketplaces::marketplace_install_root;
use crate::is_openai_curated_marketplace_name;
use crate::marketplace_policy::validate_marketplace_name_for_add;
use crate::marketplace_policy::validate_marketplace_source_for_add;
use codex_config::ConfigRequirements;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::fs;
use std::path::Path;
@@ -19,7 +21,7 @@ use metadata::MarketplaceInstallMetadata;
use metadata::find_marketplace_root_by_name;
use metadata::installed_marketplace_root_for_source;
use metadata::record_added_marketplace_entry;
use source::MarketplaceSource;
pub(crate) use source::MarketplaceSource;
pub(crate) use source::parse_marketplace_source;
use source::stage_marketplace_source;
use source::validate_marketplace_source_root;
@@ -49,11 +51,14 @@ pub enum MarketplaceAddError {
pub async fn add_marketplace(
codex_home: PathBuf,
requirements: ConfigRequirements,
request: MarketplaceAddRequest,
) -> Result<MarketplaceAddOutcome, MarketplaceAddError> {
tokio::task::spawn_blocking(move || add_marketplace_sync(codex_home.as_path(), request))
.await
.map_err(|err| MarketplaceAddError::Internal(format!("failed to add marketplace: {err}")))?
tokio::task::spawn_blocking(move || {
add_marketplace_sync(codex_home.as_path(), &requirements, request)
})
.await
.map_err(|err| MarketplaceAddError::Internal(format!("failed to add marketplace: {err}")))?
}
pub fn is_local_marketplace_source(
@@ -68,13 +73,15 @@ pub fn is_local_marketplace_source(
fn add_marketplace_sync(
codex_home: &Path,
requirements: &ConfigRequirements,
request: MarketplaceAddRequest,
) -> Result<MarketplaceAddOutcome, MarketplaceAddError> {
add_marketplace_sync_with_cloner(codex_home, request, clone_git_source)
add_marketplace_sync_with_cloner(codex_home, requirements, request, clone_git_source)
}
fn add_marketplace_sync_with_cloner<F>(
codex_home: &Path,
requirements: &ConfigRequirements,
request: MarketplaceAddRequest,
clone_source: F,
) -> Result<MarketplaceAddOutcome, MarketplaceAddError>
@@ -87,6 +94,9 @@ where
sparse_paths,
} = request;
let source = parse_marketplace_source(&source, ref_name)?;
let managed_marketplace_name =
validate_marketplace_source_for_add(codex_home, requirements, &source)
.map_err(MarketplaceAddError::InvalidRequest)?;
if !sparse_paths.is_empty() && !matches!(source, MarketplaceSource::Git { .. }) {
return Err(MarketplaceAddError::InvalidRequest(
"--sparse is only supported for git marketplace sources".to_string(),
@@ -106,6 +116,8 @@ where
installed_marketplace_root_for_source(codex_home, &install_root, &install_metadata)?
{
let marketplace_name = validate_marketplace_source_root(&existing_root)?;
validate_marketplace_name_for_add(managed_marketplace_name, &marketplace_name)
.map_err(MarketplaceAddError::InvalidRequest)?;
record_added_marketplace_entry(codex_home, &marketplace_name, &install_metadata)?;
return Ok(MarketplaceAddOutcome {
marketplace_name,
@@ -121,11 +133,8 @@ where
if let MarketplaceSource::Local { path } = &source {
let marketplace_name = validate_marketplace_source_root(path)?;
if is_openai_curated_marketplace_name(&marketplace_name) {
return Err(MarketplaceAddError::InvalidRequest(format!(
"marketplace '{marketplace_name}' is reserved and cannot be added from this source"
)));
}
validate_marketplace_name_for_add(managed_marketplace_name, &marketplace_name)
.map_err(MarketplaceAddError::InvalidRequest)?;
if find_marketplace_root_by_name(codex_home, &install_root, &marketplace_name)?.is_some() {
return Err(MarketplaceAddError::InvalidRequest(format!(
"marketplace '{marketplace_name}' is already added from a different source; remove it before adding this source"
@@ -165,11 +174,8 @@ where
stage_marketplace_source(&source, &sparse_paths, &staged_root, clone_source)?;
let marketplace_name = validate_marketplace_source_root(&staged_root)?;
if is_openai_curated_marketplace_name(&marketplace_name) {
return Err(MarketplaceAddError::InvalidRequest(format!(
"marketplace '{marketplace_name}' is reserved and cannot be added from this source"
)));
}
validate_marketplace_name_for_add(managed_marketplace_name, &marketplace_name)
.map_err(MarketplaceAddError::InvalidRequest)?;
let destination = install_root.join(safe_marketplace_dir_name(&marketplace_name)?);
ensure_marketplace_destination_is_inside_install_root(&install_root, &destination)?;
@@ -178,7 +184,6 @@ where
"marketplace '{marketplace_name}' is already added from a different source; remove it before adding this source"
)));
}
replace_marketplace_root(&staged_root, &destination).map_err(|err| {
MarketplaceAddError::Internal(format!(
"failed to install marketplace at {}: {err}",
@@ -213,9 +218,23 @@ where
mod tests {
use super::*;
use anyhow::Result;
use codex_config::RequirementSource;
use codex_config::RequirementsLayerEntry;
use codex_config::compose_requirements;
use pretty_assertions::assert_eq;
use std::cell::Cell;
use tempfile::TempDir;
fn requirements(requirements_toml: &str) -> ConfigRequirements {
let with_sources = compose_requirements([RequirementsLayerEntry::from_toml(
RequirementSource::Unknown,
requirements_toml,
)])
.expect("compose requirements")
.expect("requirements should be present");
ConfigRequirements::try_from(with_sources).expect("normalize requirements")
}
#[test]
fn add_marketplace_sync_installs_marketplace_and_updates_config() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -224,6 +243,7 @@ mod tests {
let result = add_marketplace_sync_with_cloner(
codex_home.path(),
&ConfigRequirements::default(),
MarketplaceAddRequest {
source: "https://github.com/owner/repo.git".to_string(),
ref_name: None,
@@ -253,6 +273,47 @@ mod tests {
Ok(())
}
#[test]
fn denied_git_marketplace_does_not_clone_or_create_install_root() {
let codex_home = TempDir::new().expect("create Codex home");
let requirements = requirements(
r#"
[marketplaces]
restrict_to_allowed_sources = true
[marketplaces.allowed_sources.company]
source = "git"
url = "https://github.com/example/allowed.git"
"#,
);
let cloner_called = Cell::new(false);
let err = add_marketplace_sync_with_cloner(
codex_home.path(),
&requirements,
MarketplaceAddRequest {
source: "https://github.com/example/blocked.git".to_string(),
ref_name: None,
sparse_paths: Vec::new(),
},
|_url, _ref_name, _sparse_paths, _destination| {
cloner_called.set(true);
Ok(())
},
)
.expect_err("blocked marketplace should fail");
assert!(err.to_string().contains("is not allowed by requirements"));
assert!(!cloner_called.get());
assert!(!marketplace_install_root(codex_home.path()).exists());
assert!(
!codex_home
.path()
.join(codex_config::CONFIG_TOML_FILE)
.exists()
);
}
#[test]
fn add_marketplace_sync_installs_local_directory_source_and_updates_config() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -261,6 +322,7 @@ mod tests {
let result = add_marketplace_sync_with_cloner(
codex_home.path(),
&ConfigRequirements::default(),
MarketplaceAddRequest {
source: source_root.path().display().to_string(),
ref_name: None,
@@ -305,6 +367,7 @@ mod tests {
let err = add_marketplace_sync_with_cloner(
codex_home.path(),
&ConfigRequirements::default(),
MarketplaceAddRequest {
source: source_root.path().display().to_string(),
ref_name: None,
@@ -341,16 +404,23 @@ mod tests {
ref_name: None,
sparse_paths: Vec::new(),
};
let first_result = add_marketplace_sync_with_cloner(codex_home.path(), request.clone(), {
let requirements = ConfigRequirements::default();
let first_result = add_marketplace_sync_with_cloner(
codex_home.path(),
&requirements,
request.clone(),
|_url, _ref_name, _sparse_paths, _destination| {
panic!("git cloner should not be called for local marketplace sources")
}
})?;
let second_result = add_marketplace_sync_with_cloner(codex_home.path(), request, {
},
)?;
let second_result = add_marketplace_sync_with_cloner(
codex_home.path(),
&requirements,
request,
|_url, _ref_name, _sparse_paths, _destination| {
panic!("git cloner should not be called for local marketplace sources")
}
})?;
},
)?;
assert!(!first_result.already_added);
assert!(second_result.already_added);
@@ -202,7 +202,7 @@ fn is_github_shorthand_segment(segment: &str) -> bool {
}
impl MarketplaceSource {
pub(super) fn display(&self) -> String {
pub(crate) fn display(&self) -> String {
match self {
Self::Git { url, ref_name } => match ref_name {
Some(ref_name) => format!("{url}#{ref_name}"),
@@ -0,0 +1,392 @@
use crate::OPENAI_API_CURATED_MARKETPLACE_NAME;
use crate::OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME;
use crate::OPENAI_BUNDLED_MARKETPLACE_NAME;
use crate::OPENAI_CURATED_MARKETPLACE_NAME;
use crate::OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME;
use crate::installed_marketplaces::marketplace_install_root;
use crate::installed_marketplaces::resolve_configured_marketplace_root;
use crate::is_openai_curated_marketplace_name;
use crate::marketplace::marketplace_root_dir;
use crate::marketplace_add::MarketplaceSource;
use crate::marketplace_add::parse_marketplace_source;
use crate::startup_sync::curated_plugins_api_marketplace_path;
use crate::startup_sync::curated_plugins_repo_path;
use codex_config::ConfigLayerStack;
use codex_config::ConfigRequirements;
use codex_config::MarketplaceAllowedSourceKind;
use codex_config::MarketplaceAllowedSourceToml;
use codex_config::RequirementSource;
use codex_config::types::MarketplaceConfig;
use codex_config::types::MarketplaceSourceType;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path::paths_match_after_normalization;
use regex::Regex;
use std::path::Path;
use std::path::PathBuf;
use url::Url;
enum AllowedMarketplaceSource {
GitUrl {
url: String,
ref_name: Option<String>,
},
GitHostPattern(Regex),
Local(AbsolutePathBuf),
}
pub(crate) struct MarketplacePolicy {
restricted: Option<RestrictedMarketplacePolicy>,
}
struct RestrictedMarketplacePolicy {
allowed_sources: Result<Vec<AllowedMarketplaceSource>, String>,
source: RequirementSource,
}
impl MarketplacePolicy {
pub(crate) fn from_requirements(requirements: &ConfigRequirements) -> Self {
let Some(requirements) = requirements.marketplaces.as_ref().filter(|requirements| {
requirements
.value
.restrict_to_allowed_sources
.unwrap_or(false)
}) else {
return Self { restricted: None };
};
let allowed_sources = requirements
.value
.allowed_sources
.iter()
.map(|(key, allowed_source)| {
compile_allowed_source(key, allowed_source, &requirements.source)
})
.collect();
Self {
restricted: Some(RestrictedMarketplacePolicy {
allowed_sources,
source: requirements.source.clone(),
}),
}
}
fn is_restricted(&self) -> bool {
self.restricted.is_some()
}
fn validate_source(&self, source: &MarketplaceSource) -> Result<(), String> {
let Some(RestrictedMarketplacePolicy {
allowed_sources,
source: requirement_source,
}) = &self.restricted
else {
return Ok(());
};
let allowed_sources = allowed_sources.as_ref().map_err(Clone::clone)?;
if allowed_sources
.iter()
.any(|allowed_source| allowed_source.matches(source))
{
return Ok(());
}
Err(format!(
"marketplace source `{}` is not allowed by requirements from {requirement_source}",
source.display()
))
}
pub(crate) fn validate_install(
&self,
config_layer_stack: &ConfigLayerStack,
codex_home: &Path,
marketplace_path: &AbsolutePathBuf,
marketplace_name: &str,
) -> Result<(), String> {
if !self.is_restricted() {
return Ok(());
}
let root = marketplace_root_dir(marketplace_path).map_err(|err| err.to_string())?;
if let Some(expected_name) = managed_marketplace_name(codex_home, marketplace_path, &root) {
return validate_expected_marketplace_name(expected_name, marketplace_name);
}
let user_config = config_layer_stack.effective_user_config().ok_or_else(|| {
format!(
"marketplace `{marketplace_name}` must be added to config before plugins can be installed while marketplace source restrictions are enabled"
)
})?;
let marketplace = user_config
.get("marketplaces")
.and_then(toml::Value::as_table)
.and_then(|marketplaces| marketplaces.get(marketplace_name))
.ok_or_else(|| {
format!(
"marketplace `{marketplace_name}` must be added to config before plugins can be installed while marketplace source restrictions are enabled"
)
})?;
self.validate_configured_marketplace(marketplace_name, marketplace)?;
let configured_root = resolve_configured_marketplace_root(
marketplace_name,
marketplace,
&marketplace_install_root(codex_home),
)
.ok_or_else(|| {
format!("configured marketplace `{marketplace_name}` does not have a usable root")
})?;
if !paths_match_after_normalization(&configured_root, root.as_path()) {
return Err(format!(
"marketplace path `{}` does not match configured marketplace `{marketplace_name}`",
root.as_path().display()
));
}
Ok(())
}
pub(crate) fn validate_git_source(
&self,
source: &str,
ref_name: Option<String>,
) -> Result<Option<MarketplaceSource>, String> {
if !self.is_restricted() {
return Ok(None);
}
let source = parse_marketplace_source(source, ref_name).map_err(|err| err.to_string())?;
if !matches!(source, MarketplaceSource::Git { .. }) {
return Err("configured Git marketplace source is not a Git URL".to_string());
}
self.validate_source(&source)?;
Ok(Some(source))
}
fn validate_configured_marketplace(
&self,
marketplace_name: &str,
marketplace: &toml::Value,
) -> Result<(), String> {
let source = configured_marketplace_source(marketplace_name, marketplace)?;
self.validate_source(&source)
}
}
impl AllowedMarketplaceSource {
fn matches(&self, source: &MarketplaceSource) -> bool {
match (self, source) {
(
Self::GitUrl {
url: allowed_url,
ref_name: allowed_ref,
},
MarketplaceSource::Git { url, ref_name },
) => {
allowed_url == url
&& allowed_ref
.as_ref()
.is_none_or(|allowed_ref| Some(allowed_ref) == ref_name.as_ref())
}
(Self::GitHostPattern(pattern), MarketplaceSource::Git { url, .. }) => {
git_hostname(url).is_some_and(|hostname| pattern.is_match(&hostname))
}
(Self::Local(allowed), MarketplaceSource::Local { path }) => {
paths_match_after_normalization(allowed.as_path(), path)
}
(Self::GitUrl { .. } | Self::GitHostPattern(_), MarketplaceSource::Local { .. })
| (Self::Local(_), MarketplaceSource::Git { .. }) => false,
}
}
}
pub(crate) fn validate_marketplace_source_for_add(
codex_home: &Path,
requirements: &ConfigRequirements,
source: &MarketplaceSource,
) -> Result<Option<&'static str>, String> {
let policy = MarketplacePolicy::from_requirements(requirements);
if !policy.is_restricted() {
return Ok(None);
}
if let MarketplaceSource::Local { path } = source
&& let Some(expected_name) = managed_local_marketplace_name(codex_home, path)
{
return Ok(Some(expected_name));
}
policy.validate_source(source)?;
Ok(None)
}
pub(crate) fn validate_marketplace_name_for_add(
expected_name: Option<&'static str>,
marketplace_name: &str,
) -> Result<(), String> {
if let Some(expected_name) = expected_name {
return validate_expected_marketplace_name(expected_name, marketplace_name);
}
if is_openai_curated_marketplace_name(marketplace_name) {
return Err(format!(
"marketplace `{marketplace_name}` is reserved and cannot be added from this source"
));
}
Ok(())
}
fn compile_allowed_source(
key: &str,
allowed_source: &MarketplaceAllowedSourceToml,
requirement_source: &RequirementSource,
) -> Result<AllowedMarketplaceSource, String> {
let invalid = |reason: &str| {
format!("invalid marketplace allowed source `{key}` in {requirement_source}: {reason}")
};
let source = allowed_source
.source
.ok_or_else(|| invalid("missing source"))?;
match source {
MarketplaceAllowedSourceKind::Git => {
let url = allowed_source
.url
.as_deref()
.map(str::trim)
.filter(|url| !url.is_empty())
.ok_or_else(|| invalid("missing url"))?;
let ref_name = match allowed_source.ref_name.as_deref() {
Some(ref_name) if ref_name.trim().is_empty() => {
return Err(invalid("ref must not be empty"));
}
Some(ref_name) => Some(ref_name.trim().to_string()),
None => None,
};
let source =
parse_marketplace_source(url, ref_name).map_err(|err| invalid(&err.to_string()))?;
let MarketplaceSource::Git { url, ref_name } = source else {
return Err(invalid("expected a Git URL"));
};
Ok(AllowedMarketplaceSource::GitUrl { url, ref_name })
}
MarketplaceAllowedSourceKind::HostPattern => {
let host_pattern = allowed_source
.host_pattern
.as_deref()
.map(str::trim)
.filter(|host_pattern| !host_pattern.is_empty())
.ok_or_else(|| invalid("missing host_pattern"))?;
Regex::new(host_pattern)
.map(AllowedMarketplaceSource::GitHostPattern)
.map_err(|err| invalid(&err.to_string()))
}
MarketplaceAllowedSourceKind::Local => {
let path = allowed_source
.path
.as_ref()
.filter(|path| !path.as_os_str().is_empty())
.ok_or_else(|| invalid("missing path"))?;
if !path.is_absolute() {
return Err(invalid("local path must be absolute"));
}
let path = AbsolutePathBuf::from_absolute_path_checked(path)
.map_err(|_| invalid("local path must be absolute"))?;
Ok(AllowedMarketplaceSource::Local(path))
}
}
}
fn configured_marketplace_source(
marketplace_name: &str,
marketplace: &toml::Value,
) -> Result<MarketplaceSource, String> {
let MarketplaceConfig {
source_type,
source,
ref_name,
..
} = marketplace
.clone()
.try_into()
.map_err(|err| format!("invalid config for marketplace `{marketplace_name}`: {err}"))?;
let source_type = source_type.ok_or_else(|| {
format!("configured marketplace `{marketplace_name}` is missing source_type")
})?;
let source = source
.ok_or_else(|| format!("configured marketplace `{marketplace_name}` is missing source"))?;
match source_type {
MarketplaceSourceType::Local => Ok(MarketplaceSource::Local {
path: PathBuf::from(source),
}),
MarketplaceSourceType::Git => {
let parsed = parse_marketplace_source(&source, ref_name).map_err(|err| {
format!("invalid source for marketplace `{marketplace_name}`: {err}")
})?;
if matches!(parsed, MarketplaceSource::Git { .. }) {
Ok(parsed)
} else {
Err(format!(
"configured marketplace `{marketplace_name}` source does not match source_type `git`"
))
}
}
}
}
fn validate_expected_marketplace_name(
expected_name: &str,
marketplace_name: &str,
) -> Result<(), String> {
(marketplace_name == expected_name)
.then_some(())
.ok_or_else(|| {
format!(
"marketplace manifest name `{marketplace_name}` does not match managed marketplace `{expected_name}`"
)
})
}
fn managed_marketplace_name(
codex_home: &Path,
marketplace_path: &AbsolutePathBuf,
root: &AbsolutePathBuf,
) -> Option<&'static str> {
if paths_match_after_normalization(
marketplace_path.as_path(),
curated_plugins_api_marketplace_path(codex_home),
) {
return Some(OPENAI_API_CURATED_MARKETPLACE_NAME);
}
if paths_match_after_normalization(root.as_path(), curated_plugins_repo_path(codex_home)) {
return Some(OPENAI_CURATED_MARKETPLACE_NAME);
}
managed_local_marketplace_name(codex_home, root.as_path())
}
fn managed_local_marketplace_name(codex_home: &Path, root: &Path) -> Option<&'static str> {
for marketplace_name in [
OPENAI_BUNDLED_MARKETPLACE_NAME,
OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME,
] {
let expected_root = codex_home
.join(".tmp/bundled-marketplaces")
.join(marketplace_name);
if paths_match_after_normalization(root, &expected_root) {
return Some(marketplace_name);
}
}
let runtime_root = dirs::cache_dir()?
.join("codex-runtimes/codex-primary-runtime/plugins")
.join(OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME);
paths_match_after_normalization(root, &runtime_root)
.then_some(OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME)
}
fn git_hostname(url: &str) -> Option<String> {
if let Ok(url) = Url::parse(url) {
return url.host_str().map(str::to_ascii_lowercase);
}
let (_, host_and_path) = url.split_once('@')?;
let (hostname, _) = host_and_path.split_once(':')?;
(!hostname.is_empty()).then(|| hostname.to_ascii_lowercase())
}
#[cfg(test)]
#[path = "marketplace_policy_tests.rs"]
mod tests;
@@ -0,0 +1,500 @@
use super::*;
use crate::marketplace_upgrade::upgrade_configured_git_marketplaces;
use codex_config::ConfigLayerEntry;
use codex_config::ConfigLayerSource;
use codex_config::RequirementSource;
use codex_config::RequirementsLayerEntry;
use codex_config::compose_requirements;
use pretty_assertions::assert_eq;
use std::fs;
use tempfile::TempDir;
fn config_layer_stack(requirements_toml: &str) -> ConfigLayerStack {
config_layer_stack_with_user_config(requirements_toml, /*user_config*/ None)
}
fn config_layer_stack_with_user_config(
requirements_toml: &str,
user_config: Option<(&str, AbsolutePathBuf)>,
) -> ConfigLayerStack {
let with_sources = compose_requirements([RequirementsLayerEntry::from_toml(
RequirementSource::Unknown,
requirements_toml,
)])
.expect("compose requirements")
.expect("requirements should be present");
let requirements_toml = with_sources.clone().into_toml();
let requirements =
codex_config::ConfigRequirements::try_from(with_sources).expect("normalize requirements");
let layers = user_config
.map(|(contents, file)| {
vec![ConfigLayerEntry::new(
ConfigLayerSource::User {
file,
profile: None,
},
toml::from_str(contents).expect("parse user config"),
)]
})
.unwrap_or_default();
ConfigLayerStack::new(layers, requirements, requirements_toml)
.expect("build config layer stack")
}
fn parse_source(source: &str, ref_name: Option<&str>) -> MarketplaceSource {
parse_marketplace_source(source, ref_name.map(str::to_string)).expect("parse source")
}
fn validate_source(stack: &ConfigLayerStack, source: &MarketplaceSource) -> Result<(), String> {
MarketplacePolicy::from_requirements(stack.requirements()).validate_source(source)
}
#[test]
fn exact_git_rule_matches_url_and_ref() {
let stack = config_layer_stack(
r#"
[marketplaces]
restrict_to_allowed_sources = true
[marketplaces.allowed_sources.company]
source = "git"
url = "https://github.com/example/plugins"
ref = "main"
"#,
);
assert_eq!(
validate_source(
&stack,
&parse_source("https://github.com/example/plugins.git", Some("main")),
),
Ok(())
);
for denied in [
parse_source("https://github.com/example/plugins.git", Some("release")),
parse_source("https://github.com/other/plugins.git", Some("main")),
] {
assert!(validate_source(&stack, &denied).is_err());
}
let normalized = MarketplacePolicy::from_requirements(stack.requirements())
.validate_git_source("example/plugins", Some("main".to_string()))
.expect("allowlisted shorthand should validate")
.expect("restricted policy should normalize the source");
assert_eq!(
normalized,
MarketplaceSource::Git {
url: "https://github.com/example/plugins.git".to_string(),
ref_name: Some("main".to_string()),
}
);
}
#[test]
fn git_rule_without_ref_allows_any_ref_for_the_same_repository() {
let stack = config_layer_stack(
r#"
[marketplaces]
restrict_to_allowed_sources = true
[marketplaces.allowed_sources.company]
source = "git"
url = "https://github.com/example/plugins"
"#,
);
assert_eq!(
validate_source(
&stack,
&parse_source("https://github.com/example/plugins.git", Some("release")),
),
Ok(())
);
}
#[test]
fn git_host_pattern_matches_https_and_ssh_sources() {
let stack = config_layer_stack(
r#"
[marketplaces]
restrict_to_allowed_sources = true
[marketplaces.allowed_sources.internal]
source = "host_pattern"
host_pattern = '^git\.example\.com$'
url = "https://github.com/example/ignored.git"
ref = "ignored"
"#,
);
for source in [
"https://git.example.com/team/plugins.git",
"ssh://git@git.example.com/team/plugins.git",
"git@git.example.com:team/plugins.git",
] {
assert_eq!(
validate_source(&stack, &parse_source(source, /*ref_name*/ None)),
Ok(())
);
}
assert!(
validate_source(
&stack,
&parse_source(
"https://github.com/example/plugins.git",
/*ref_name*/ None,
),
)
.is_err()
);
}
#[test]
fn exact_local_rule_rejects_other_directories() {
let allowed = TempDir::new().expect("create allowed marketplace directory");
let denied = TempDir::new().expect("create denied marketplace directory");
let allowed = allowed
.path()
.canonicalize()
.expect("canonical allowed path");
let denied = denied.path().canonicalize().expect("canonical denied path");
let stack = config_layer_stack(&format!(
r#"
[marketplaces]
restrict_to_allowed_sources = true
[marketplaces.allowed_sources.local]
source = "local"
path = {allowed:?}
"#
));
assert_eq!(
validate_source(
&stack,
&parse_source(allowed.to_string_lossy().as_ref(), /*ref_name*/ None),
),
Ok(())
);
assert!(
validate_source(
&stack,
&parse_source(denied.to_string_lossy().as_ref(), /*ref_name*/ None),
)
.is_err()
);
}
#[test]
fn restriction_flag_controls_empty_allowlist() {
for (restricted, expected_allowed) in [(true, false), (false, true)] {
let stack = config_layer_stack(&format!(
r#"
[marketplaces]
restrict_to_allowed_sources = {restricted}
"#
));
let result = validate_source(
&stack,
&parse_source(
"https://github.com/example/plugins.git",
/*ref_name*/ None,
),
);
assert_eq!(result.is_ok(), expected_allowed);
}
}
#[test]
fn strict_install_validates_configured_name_source_and_root() {
let codex_home = TempDir::new().expect("create Codex home");
let configured_root = TempDir::new().expect("create configured marketplace");
let other_root = TempDir::new().expect("create other marketplace");
let configured_root = configured_root
.path()
.canonicalize()
.expect("canonical configured root");
let other_root = other_root
.path()
.canonicalize()
.expect("canonical other root");
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
.expect("absolute config path");
let stack = config_layer_stack_with_user_config(
&format!(
r#"
[marketplaces]
restrict_to_allowed_sources = true
[marketplaces.allowed_sources.company]
source = "local"
path = {configured_root:?}
"#
),
Some((
&format!(
r#"
[marketplaces.company]
source_type = "local"
source = {configured_root:?}
"#
),
config_file,
)),
);
let policy = MarketplacePolicy::from_requirements(stack.requirements());
let configured_path =
AbsolutePathBuf::try_from(configured_root.join(".agents/plugins/marketplace.json"))
.expect("configured marketplace path");
let other_path = AbsolutePathBuf::try_from(other_root.join(".agents/plugins/marketplace.json"))
.expect("other marketplace path");
assert_eq!(
policy.validate_install(&stack, codex_home.path(), &configured_path, "company"),
Ok(())
);
assert!(
policy
.validate_install(&stack, codex_home.path(), &configured_path, "other")
.expect_err("unconfigured name should fail")
.contains("must be added to config")
);
assert!(
policy
.validate_install(&stack, codex_home.path(), &other_path, "company")
.expect_err("mismatched root should fail")
.contains("does not match configured marketplace")
);
}
#[test]
fn blocked_configured_source_is_not_installable() {
let codex_home = TempDir::new().expect("create Codex home");
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
.expect("absolute config path");
let stack = config_layer_stack_with_user_config(
r#"
[marketplaces]
restrict_to_allowed_sources = true
[marketplaces.allowed_sources.company]
source = "git"
url = "https://github.com/example/allowed.git"
"#,
Some((
r#"
[marketplaces.debug]
source_type = "git"
source = "https://github.com/example/blocked.git"
"#,
config_file,
)),
);
let marketplace_path = AbsolutePathBuf::try_from(
marketplace_install_root(codex_home.path()).join("debug/.agents/plugins/marketplace.json"),
)
.expect("absolute marketplace path");
let err = MarketplacePolicy::from_requirements(stack.requirements())
.validate_install(&stack, codex_home.path(), &marketplace_path, "debug")
.expect_err("blocked marketplace install should fail");
assert!(err.contains("is not allowed by requirements"));
}
#[test]
fn bare_relative_local_config_source_is_not_parsed_as_git_shorthand() {
let marketplace: toml::Value = toml::from_str(
r#"
source_type = "local"
source = "marketplaces/company"
"#,
)
.expect("parse marketplace config");
assert_eq!(
configured_marketplace_source("company", &marketplace),
Ok(MarketplaceSource::Local {
path: PathBuf::from("marketplaces/company"),
})
);
}
#[test]
fn curated_marketplace_requires_its_expected_name() {
let codex_home = TempDir::new().expect("create Codex home");
let stack = config_layer_stack(
r#"
[marketplaces]
restrict_to_allowed_sources = true
"#,
);
let marketplace_path = AbsolutePathBuf::try_from(
curated_plugins_repo_path(codex_home.path()).join(".agents/plugins/marketplace.json"),
)
.expect("absolute marketplace path");
let policy = MarketplacePolicy::from_requirements(stack.requirements());
assert_eq!(
policy.validate_install(
&stack,
codex_home.path(),
&marketplace_path,
crate::OPENAI_CURATED_MARKETPLACE_NAME,
),
Ok(())
);
assert!(
policy
.validate_install(
&stack,
codex_home.path(),
&marketplace_path,
crate::OPENAI_API_CURATED_MARKETPLACE_NAME,
)
.is_err()
);
}
#[test]
fn managed_bundled_source_is_bound_to_its_expected_name() {
let codex_home = TempDir::new().expect("create Codex home");
let bundled_root = codex_home
.path()
.join(".tmp/bundled-marketplaces")
.join(crate::OPENAI_BUNDLED_MARKETPLACE_NAME);
fs::create_dir_all(&bundled_root).expect("create bundled marketplace root");
let stack = config_layer_stack(
r#"
[marketplaces]
restrict_to_allowed_sources = true
"#,
);
let source = parse_source(
bundled_root.to_string_lossy().as_ref(),
/*ref_name*/ None,
);
let expected_name =
validate_marketplace_source_for_add(codex_home.path(), stack.requirements(), &source)
.expect("managed marketplace source should bypass restrictions");
assert_eq!(
validate_marketplace_name_for_add(expected_name, crate::OPENAI_BUNDLED_MARKETPLACE_NAME,),
Ok(())
);
assert!(validate_marketplace_name_for_add(expected_name, "other").is_err());
}
#[test]
fn blocked_upgrade_is_rejected_before_marketplace_installation() {
let codex_home = TempDir::new().expect("create Codex home");
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
.expect("absolute config path");
let stack = config_layer_stack_with_user_config(
r#"
[marketplaces]
restrict_to_allowed_sources = true
"#,
Some((
r#"
[marketplaces.debug]
source_type = "git"
source = "https://github.com/example/blocked.git"
"#,
config_file,
)),
);
let outcome = upgrade_configured_git_marketplaces(codex_home.path(), &stack, Some("debug"));
assert_eq!(outcome.selected_marketplaces, vec!["debug".to_string()]);
assert_eq!(outcome.upgraded_roots, Vec::new());
assert_eq!(outcome.errors.len(), 1);
assert!(
outcome.errors[0]
.message
.contains("is not allowed by requirements")
);
assert!(!marketplace_install_root(codex_home.path()).exists());
}
#[test]
fn invalid_active_rule_fails_closed_even_when_another_rule_matches() {
let stack = config_layer_stack(
r#"
[marketplaces]
restrict_to_allowed_sources = true
[marketplaces.allowed_sources.allowed]
source = "git"
url = "https://github.com/example/plugins.git"
[marketplaces.allowed_sources.invalid]
source = "host_pattern"
host_pattern = "("
"#,
);
let err = validate_source(
&stack,
&parse_source(
"https://github.com/example/plugins.git",
/*ref_name*/ None,
),
)
.expect_err("invalid active rule should fail closed");
assert!(err.contains("invalid marketplace allowed source `invalid`"));
}
#[test]
fn invalid_allowed_source_shapes_fail_closed() {
for (rule, expected_error) in [
(
r#"
[marketplaces.allowed_sources.invalid]
url = "https://github.com/example/plugins.git"
"#,
"missing source",
),
(
r#"
[marketplaces.allowed_sources.invalid]
source = "git"
"#,
"missing url",
),
(
r#"
[marketplaces.allowed_sources.invalid]
source = "git"
url = "https://github.com/example/plugins.git"
ref = " "
"#,
"ref must not be empty",
),
(
r#"
[marketplaces.allowed_sources.invalid]
source = "local"
path = "../plugins"
"#,
"local path must be absolute",
),
] {
let stack = config_layer_stack(&format!(
r#"
[marketplaces]
restrict_to_allowed_sources = true
{rule}
"#
));
let err = validate_source(
&stack,
&parse_source(
"https://github.com/example/plugins.git",
/*ref_name*/ None,
),
)
.expect_err("invalid rule should fail closed");
assert!(err.contains(expected_error), "{err}");
}
}
+109 -72
View File
@@ -6,8 +6,10 @@ use self::activation::installed_marketplace_metadata_matches;
use self::activation::write_installed_marketplace_metadata;
use self::git::clone_git_source;
use self::git::git_remote_revision;
use crate::marketplace::find_marketplace_manifest_path;
use crate::installed_marketplaces::marketplace_install_root;
use crate::marketplace::validate_marketplace_root;
use crate::marketplace_add::MarketplaceSource;
use crate::marketplace_policy::MarketplacePolicy;
use codex_config::CONFIG_TOML_FILE;
use codex_config::ConfigLayerStack;
use codex_config::MarketplaceConfigUpdate;
@@ -16,13 +18,9 @@ use codex_config::types::MarketplaceConfig;
use codex_config::types::MarketplaceSourceType;
use codex_plugin::validate_plugin_segment;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use tracing::warn;
const INSTALLED_MARKETPLACES_DIR: &str = ".tmp/marketplaces";
const MARKETPLACE_UPGRADE_GIT_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -47,6 +45,12 @@ struct ConfiguredGitMarketplace {
last_revision: Option<String>,
}
#[derive(Default)]
struct ConfiguredGitMarketplaceLoadOutcome {
marketplaces: Vec<ConfiguredGitMarketplace>,
errors: Vec<ConfiguredMarketplaceUpgradeError>,
}
impl ConfiguredMarketplaceUpgradeOutcome {
pub fn all_succeeded(&self) -> bool {
self.errors.is_empty()
@@ -54,7 +58,8 @@ impl ConfiguredMarketplaceUpgradeOutcome {
}
pub fn configured_git_marketplace_names(config_layer_stack: &ConfigLayerStack) -> Vec<String> {
let mut names = configured_git_marketplaces(config_layer_stack)
let mut names = load_configured_git_marketplaces(config_layer_stack)
.marketplaces
.into_iter()
.map(|marketplace| marketplace.name)
.collect::<Vec<_>>();
@@ -67,23 +72,49 @@ pub fn upgrade_configured_git_marketplaces(
config_layer_stack: &ConfigLayerStack,
marketplace_name: Option<&str>,
) -> ConfiguredMarketplaceUpgradeOutcome {
let marketplaces = configured_git_marketplaces(config_layer_stack)
let loaded = load_configured_git_marketplaces(config_layer_stack);
let marketplaces = loaded
.marketplaces
.into_iter()
.filter(|marketplace| marketplace_name.is_none_or(|name| marketplace.name.as_str() == name))
.collect::<Vec<_>>();
if marketplaces.is_empty() {
let mut errors = loaded
.errors
.into_iter()
.filter(|error| marketplace_name.is_none_or(|name| error.marketplace_name.as_str() == name))
.collect::<Vec<_>>();
if marketplaces.is_empty() && errors.is_empty() {
return ConfiguredMarketplaceUpgradeOutcome::default();
}
let install_root = marketplace_install_root(codex_home);
let selected_marketplaces = marketplaces
let mut selected_marketplaces = marketplaces
.iter()
.map(|marketplace| marketplace.name.clone())
.collect();
.chain(errors.iter().map(|error| error.marketplace_name.clone()))
.collect::<Vec<_>>();
selected_marketplaces.sort_unstable();
selected_marketplaces.dedup();
let mut upgraded_roots = Vec::new();
let mut errors = Vec::new();
let policy = MarketplacePolicy::from_requirements(config_layer_stack.requirements());
for marketplace in marketplaces {
match upgrade_configured_git_marketplace(codex_home, &install_root, &marketplace) {
let normalized_source =
match policy.validate_git_source(&marketplace.source, marketplace.ref_name.clone()) {
Ok(normalized_source) => normalized_source,
Err(message) => {
errors.push(ConfiguredMarketplaceUpgradeError {
marketplace_name: marketplace.name,
message,
});
continue;
}
};
match upgrade_configured_git_marketplace(
codex_home,
&install_root,
&marketplace,
normalized_source.as_ref(),
) {
Ok(Some(upgraded_root)) => upgraded_roots.push(upgraded_root),
Ok(None) => {}
Err(err) => {
@@ -102,42 +133,50 @@ pub fn upgrade_configured_git_marketplaces(
}
}
fn marketplace_install_root(codex_home: &Path) -> PathBuf {
codex_home.join(INSTALLED_MARKETPLACES_DIR)
}
fn configured_git_marketplaces(
fn load_configured_git_marketplaces(
config_layer_stack: &ConfigLayerStack,
) -> Vec<ConfiguredGitMarketplace> {
) -> ConfiguredGitMarketplaceLoadOutcome {
let Some(user_config) = config_layer_stack.effective_user_config() else {
return Vec::new();
return ConfiguredGitMarketplaceLoadOutcome::default();
};
let Some(marketplaces_value) = user_config.get("marketplaces") else {
return Vec::new();
};
let marketplaces = match marketplaces_value
.clone()
.try_into::<HashMap<String, MarketplaceConfig>>()
{
Ok(marketplaces) => marketplaces,
Err(err) => {
warn!("invalid marketplaces config while preparing auto-upgrade: {err}");
return Vec::new();
}
let Some(marketplaces) = user_config
.get("marketplaces")
.and_then(toml::Value::as_table)
else {
return ConfiguredGitMarketplaceLoadOutcome::default();
};
let mut configured = marketplaces
.into_iter()
.filter_map(|(name, marketplace)| configured_git_marketplace_from_config(name, marketplace))
.collect::<Vec<_>>();
configured.sort_unstable_by(|left, right| left.name.cmp(&right.name));
configured
let mut outcome = ConfiguredGitMarketplaceLoadOutcome::default();
for (name, marketplace) in marketplaces {
match parse_configured_git_marketplace(name, marketplace) {
Ok(Some(marketplace)) => outcome.marketplaces.push(marketplace),
Ok(None) => {}
Err(message) => outcome.errors.push(ConfiguredMarketplaceUpgradeError {
marketplace_name: name.clone(),
message,
}),
}
}
outcome
.marketplaces
.sort_unstable_by(|left, right| left.name.cmp(&right.name));
outcome
.errors
.sort_unstable_by(|left, right| left.marketplace_name.cmp(&right.marketplace_name));
outcome
}
fn configured_git_marketplace_from_config(
name: String,
marketplace: MarketplaceConfig,
) -> Option<ConfiguredGitMarketplace> {
fn parse_configured_git_marketplace(
name: &str,
marketplace: &toml::Value,
) -> Result<Option<ConfiguredGitMarketplace>, String> {
if marketplace.get("source_type").and_then(toml::Value::as_str) != Some("git") {
return Ok(None);
}
let marketplace = marketplace
.clone()
.try_into::<MarketplaceConfig>()
.map_err(|err| format!("invalid configured Git marketplace: {err}"))?;
let MarketplaceConfig {
last_updated: _,
last_revision,
@@ -147,37 +186,37 @@ fn configured_git_marketplace_from_config(
sparse_paths,
} = marketplace;
if source_type != Some(MarketplaceSourceType::Git) {
return None;
return Ok(None);
}
let Some(source) = source else {
warn!(
marketplace = name,
"ignoring configured Git marketplace without source"
);
return None;
};
Some(ConfiguredGitMarketplace {
name,
let source =
source.ok_or_else(|| "configured Git marketplace is missing source".to_string())?;
Ok(Some(ConfiguredGitMarketplace {
name: name.to_string(),
source,
ref_name,
sparse_paths: sparse_paths.unwrap_or_default(),
last_revision,
})
}))
}
fn upgrade_configured_git_marketplace(
codex_home: &Path,
install_root: &Path,
marketplace: &ConfiguredGitMarketplace,
normalized_source: Option<&MarketplaceSource>,
) -> Result<Option<AbsolutePathBuf>, String> {
validate_plugin_segment(&marketplace.name, "marketplace name")?;
let remote_revision = git_remote_revision(
&marketplace.source,
marketplace.ref_name.as_deref(),
MARKETPLACE_UPGRADE_GIT_TIMEOUT,
)?;
let (source, ref_name) = match normalized_source {
Some(MarketplaceSource::Git { url, ref_name }) => (url.as_str(), ref_name.as_deref()),
Some(MarketplaceSource::Local { .. }) => {
return Err("validated Git marketplace source resolved to a local path".to_string());
}
None => (marketplace.source.as_str(), marketplace.ref_name.as_deref()),
};
let remote_revision = git_remote_revision(source, ref_name, MARKETPLACE_UPGRADE_GIT_TIMEOUT)?;
let destination = install_root.join(&marketplace.name);
if find_marketplace_manifest_path(&destination).is_some()
if validate_marketplace_root(&destination)
.is_ok_and(|marketplace_name| marketplace_name == marketplace.name)
&& marketplace.last_revision.as_deref() == Some(remote_revision.as_str())
&& installed_marketplace_metadata_matches(&destination, marketplace, &remote_revision)
{
@@ -202,8 +241,8 @@ fn upgrade_configured_git_marketplace(
})?;
let activated_revision = clone_git_source(
&marketplace.source,
marketplace.ref_name.as_deref(),
source,
ref_name,
&marketplace.sparse_paths,
staged_dir.path(),
MARKETPLACE_UPGRADE_GIT_TIMEOUT,
@@ -280,18 +319,16 @@ fn read_configured_git_marketplace(
config_path.display()
)
})?;
let Some(marketplaces_value) = config.get("marketplaces") else {
let Some(marketplace) = config
.get("marketplaces")
.and_then(toml::Value::as_table)
.and_then(|marketplaces| marketplaces.get(marketplace_name))
else {
return Ok(None);
};
let mut marketplaces = marketplaces_value
.clone()
.try_into::<HashMap<String, MarketplaceConfig>>()
.map_err(|err| format!("invalid marketplaces config while checking auto-upgrade: {err}"))?;
let Some(marketplace) = marketplaces.remove(marketplace_name) else {
return Ok(None);
};
Ok(configured_git_marketplace_from_config(
marketplace_name.to_string(),
marketplace,
))
parse_configured_git_marketplace(marketplace_name, marketplace)
}
#[cfg(test)]
#[path = "marketplace_upgrade_tests.rs"]
mod tests;
@@ -0,0 +1,221 @@
use super::*;
use codex_config::ConfigLayerEntry;
use codex_config::ConfigLayerSource;
use codex_config::ConfigRequirements;
use codex_config::ConfigRequirementsToml;
use pretty_assertions::assert_eq;
use std::path::Path;
use std::process::Command;
use tempfile::TempDir;
#[test]
fn readback_ignores_unrelated_malformed_marketplace() {
let codex_home = TempDir::new().expect("create Codex home");
std::fs::write(
codex_home.path().join(CONFIG_TOML_FILE),
r#"
[marketplaces.bad]
source_type = "git"
source = 17
[marketplaces.good]
source_type = "git"
source = "https://github.com/example/good.git"
ref = "main"
sparse_paths = ["plugins"]
last_revision = "abc123"
"#,
)
.expect("write config");
assert_eq!(
read_configured_git_marketplace(codex_home.path(), "good")
.expect("read configured marketplace"),
Some(ConfiguredGitMarketplace {
name: "good".to_string(),
source: "https://github.com/example/good.git".to_string(),
ref_name: Some("main".to_string()),
sparse_paths: vec!["plugins".to_string()],
last_revision: Some("abc123".to_string()),
})
);
}
#[test]
fn one_upgrade_failure_does_not_block_another_marketplace() {
let codex_home = TempDir::new().expect("create Codex home");
let remote_repo = TempDir::new().expect("create remote repository");
init_marketplace_repo(remote_repo.path(), "good");
let good_url = url::Url::from_directory_path(remote_repo.path())
.expect("remote repository URL")
.to_string();
let missing_url = url::Url::from_directory_path(codex_home.path().join("missing-repository"))
.expect("missing repository URL")
.to_string();
let config = format!(
r#"
[marketplaces.bad]
source_type = "git"
source = {missing_url:?}
[marketplaces.good]
source_type = "git"
source = {good_url:?}
"#
);
std::fs::write(codex_home.path().join(CONFIG_TOML_FILE), &config).expect("write config");
let stack = config_layer_stack(codex_home.path(), &config);
let outcome = upgrade_configured_git_marketplaces(
codex_home.path(),
&stack,
/*marketplace_name*/ None,
);
assert_eq!(
outcome.selected_marketplaces,
vec!["bad".to_string(), "good".to_string()]
);
assert_eq!(outcome.errors.len(), 1);
assert_eq!(outcome.errors[0].marketplace_name, "bad");
assert_eq!(
outcome.upgraded_roots,
vec![
AbsolutePathBuf::try_from(marketplace_install_root(codex_home.path()).join("good"))
.expect("installed marketplace root")
]
);
}
#[test]
fn upgrade_uses_validated_source_for_git_operations() {
let codex_home = TempDir::new().expect("create Codex home");
let remote_repo = TempDir::new().expect("create remote repository");
init_marketplace_repo(remote_repo.path(), "good");
let normalized_url = url::Url::from_directory_path(remote_repo.path())
.expect("remote repository URL")
.to_string();
let raw_source = codex_home.path().join("missing-raw-source");
let raw_source = raw_source.to_string_lossy().into_owned();
let config = format!(
r#"
[marketplaces.good]
source_type = "git"
source = {raw_source:?}
ref = "missing-ref"
"#
);
std::fs::write(codex_home.path().join(CONFIG_TOML_FILE), config).expect("write config");
let marketplace = ConfiguredGitMarketplace {
name: "good".to_string(),
source: raw_source,
ref_name: Some("missing-ref".to_string()),
sparse_paths: Vec::new(),
last_revision: None,
};
let normalized_source = MarketplaceSource::Git {
url: normalized_url,
ref_name: Some("HEAD".to_string()),
};
let install_root = marketplace_install_root(codex_home.path());
let upgraded_root = upgrade_configured_git_marketplace(
codex_home.path(),
&install_root,
&marketplace,
Some(&normalized_source),
)
.expect("upgrade should use the validated source")
.expect("marketplace should be upgraded");
assert_eq!(
upgraded_root,
AbsolutePathBuf::try_from(install_root.join("good")).expect("installed marketplace root")
);
}
#[test]
fn up_to_date_fast_path_validates_marketplace_name() {
const REVISION: &str = "0123456789abcdef0123456789abcdef01234567";
let codex_home = TempDir::new().expect("create Codex home");
let install_root = marketplace_install_root(codex_home.path());
let destination = install_root.join("good");
let manifest_dir = destination.join(".agents/plugins");
std::fs::create_dir_all(&manifest_dir).expect("create marketplace manifest directory");
std::fs::write(
manifest_dir.join("marketplace.json"),
r#"{"name":"wrong","plugins":[]}"#,
)
.expect("write mismatched marketplace manifest");
let missing_source = codex_home.path().join("missing-source");
let missing_source = missing_source.to_string_lossy().into_owned();
let marketplace = ConfiguredGitMarketplace {
name: "good".to_string(),
source: missing_source.clone(),
ref_name: Some(REVISION.to_string()),
sparse_paths: Vec::new(),
last_revision: Some(REVISION.to_string()),
};
super::activation::write_installed_marketplace_metadata(&destination, &marketplace, REVISION)
.expect("write installed marketplace metadata");
let normalized_source = MarketplaceSource::Git {
url: missing_source,
ref_name: Some(REVISION.to_string()),
};
let err = upgrade_configured_git_marketplace(
codex_home.path(),
&install_root,
&marketplace,
Some(&normalized_source),
)
.expect_err("mismatched marketplace name must not use the up-to-date fast path");
assert!(err.contains("git clone marketplace source failed"));
}
fn config_layer_stack(codex_home: &Path, config: &str) -> ConfigLayerStack {
let config_file =
AbsolutePathBuf::try_from(codex_home.join(CONFIG_TOML_FILE)).expect("absolute config path");
ConfigLayerStack::new(
vec![ConfigLayerEntry::new(
ConfigLayerSource::User {
file: config_file,
profile: None,
},
toml::from_str(config).expect("parse config"),
)],
ConfigRequirements::default(),
ConfigRequirementsToml::default(),
)
.expect("build config layer stack")
}
fn init_marketplace_repo(repo: &Path, marketplace_name: &str) {
let manifest_dir = repo.join(".agents/plugins");
std::fs::create_dir_all(&manifest_dir).expect("create marketplace manifest directory");
std::fs::write(
manifest_dir.join("marketplace.json"),
format!(r#"{{"name":"{marketplace_name}","plugins":[]}}"#),
)
.expect("write marketplace manifest");
run_git(repo, &["init"]);
run_git(repo, &["config", "user.email", "codex-test@example.com"]);
run_git(repo, &["config", "user.name", "Codex Test"]);
run_git(repo, &["add", "."]);
run_git(repo, &["commit", "-m", "initial"]);
}
fn run_git(repo: &Path, args: &[&str]) {
let output = Command::new("git")
.arg("-C")
.arg(repo)
.args(args)
.output()
.expect("run git");
assert!(
output.status.success(),
"git {args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
+35 -47
View File
@@ -1,4 +1,4 @@
use crate::manifest::parse_plugin_manifest;
use crate::manifest::parse_plugin_manifest_uri;
use codex_exec_server::EnvironmentManager;
use codex_exec_server::ExecutorFileSystem;
use codex_plugin::PluginProvider;
@@ -6,23 +6,16 @@ use codex_plugin::ResolvedPlugin;
use codex_plugin::ResolvedPluginError;
use codex_protocol::capabilities::CapabilityRootLocation;
use codex_protocol::capabilities::SelectedCapabilityRoot;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use codex_utils_path_uri::PathUriParseError;
use codex_utils_plugins::DISCOVERABLE_PLUGIN_MANIFEST_PATHS;
use std::io;
use std::path::PathBuf;
use std::sync::Arc;
use thiserror::Error;
/// Failure to resolve an environment-owned capability root as a plugin package.
#[derive(Debug, Error)]
pub enum ExecutorPluginProviderError {
#[error("selected capability root `{root_id}` has invalid path `{path}`: {message}")]
InvalidRootPath {
root_id: String,
path: String,
message: String,
},
#[error(
"selected capability root `{root_id}` references unavailable environment `{environment_id}`"
)]
@@ -33,33 +26,40 @@ pub enum ExecutorPluginProviderError {
#[error("failed to inspect selected capability root `{root_id}` at {path}: {source}")]
InspectRoot {
root_id: String,
path: AbsolutePathBuf,
path: PathUri,
#[source]
source: io::Error,
},
#[error("selected capability root `{root_id}` path {path} is not a directory")]
RootNotDirectory {
RootNotDirectory { root_id: String, path: PathUri },
#[error(
"failed to resolve plugin manifest path `{relative_path}` below selected capability root `{root_id}` at {root}: {source}"
)]
InvalidManifestPath {
root_id: String,
path: AbsolutePathBuf,
root: PathUri,
relative_path: &'static str,
#[source]
source: PathUriParseError,
},
#[error("failed to inspect plugin manifest for `{root_id}` at {path}: {source}")]
InspectManifest {
root_id: String,
path: AbsolutePathBuf,
path: PathUri,
#[source]
source: io::Error,
},
#[error("failed to read plugin manifest for `{root_id}` at {path}: {source}")]
ReadManifest {
root_id: String,
path: AbsolutePathBuf,
path: PathUri,
#[source]
source: io::Error,
},
#[error("failed to parse plugin manifest for `{root_id}` at {path}: {source}")]
ParseManifest {
root_id: String,
path: AbsolutePathBuf,
path: PathUri,
#[source]
source: serde_json::Error,
},
@@ -110,7 +110,7 @@ impl ExecutorPluginProvider {
selected_root: &SelectedCapabilityRoot,
) -> Result<Option<ResolvedExecutorPlugin>, ExecutorPluginProviderError> {
let root_id = &selected_root.id;
let plugin_root = selected_plugin_root(selected_root)?;
let plugin_root = selected_plugin_root(selected_root);
let CapabilityRootLocation::Environment { environment_id, .. } = &selected_root.location;
let environment = self
.environment_manager
@@ -142,38 +142,20 @@ impl PluginProvider for ExecutorPluginProvider {
}
}
fn selected_plugin_root(
selected_root: &SelectedCapabilityRoot,
) -> Result<AbsolutePathBuf, ExecutorPluginProviderError> {
let root_id = &selected_root.id;
fn selected_plugin_root(selected_root: &SelectedCapabilityRoot) -> PathUri {
let CapabilityRootLocation::Environment { path, .. } = &selected_root.location;
let plugin_root = PathBuf::from(path);
if !plugin_root.is_absolute() {
return Err(ExecutorPluginProviderError::InvalidRootPath {
root_id: root_id.clone(),
path: path.clone(),
message: "executor path must be absolute".to_string(),
});
}
AbsolutePathBuf::from_absolute_path_checked(plugin_root).map_err(|err| {
ExecutorPluginProviderError::InvalidRootPath {
root_id: root_id.clone(),
path: path.clone(),
message: err.to_string(),
}
})
path.clone()
}
async fn resolve_plugin_root(
selected_root: &SelectedCapabilityRoot,
plugin_root: AbsolutePathBuf,
plugin_root: PathUri,
file_system: &dyn ExecutorFileSystem,
) -> Result<Option<ResolvedPlugin>, ExecutorPluginProviderError> {
let root_id = &selected_root.id;
let CapabilityRootLocation::Environment { environment_id, .. } = &selected_root.location;
let root_uri = PathUri::from_abs_path(&plugin_root);
let root_metadata = file_system
.get_metadata(&root_uri, /*sandbox*/ None)
.get_metadata(&plugin_root, /*sandbox*/ None)
.await
.map_err(|source| ExecutorPluginProviderError::InspectRoot {
root_id: root_id.clone(),
@@ -189,14 +171,20 @@ async fn resolve_plugin_root(
let mut manifest_path = None;
for relative_path in DISCOVERABLE_PLUGIN_MANIFEST_PATHS {
let candidate = plugin_root.join(relative_path);
let candidate_uri = PathUri::from_abs_path(&candidate);
let candidate_uri = plugin_root.join(relative_path).map_err(|source| {
ExecutorPluginProviderError::InvalidManifestPath {
root_id: root_id.clone(),
root: plugin_root.clone(),
relative_path,
source,
}
})?;
match file_system
.get_metadata(&candidate_uri, /*sandbox*/ None)
.await
{
Ok(metadata) if metadata.is_file => {
manifest_path = Some((candidate, candidate_uri));
manifest_path = Some(candidate_uri);
break;
}
Ok(_) => {}
@@ -204,13 +192,13 @@ async fn resolve_plugin_root(
Err(source) => {
return Err(ExecutorPluginProviderError::InspectManifest {
root_id: root_id.clone(),
path: candidate,
path: candidate_uri,
source,
});
}
}
}
let Some((manifest_path, manifest_uri)) = manifest_path else {
let Some(manifest_uri) = manifest_path else {
return Ok(None);
};
let contents = file_system
@@ -218,14 +206,14 @@ async fn resolve_plugin_root(
.await
.map_err(|source| ExecutorPluginProviderError::ReadManifest {
root_id: root_id.clone(),
path: manifest_path.clone(),
path: manifest_uri.clone(),
source,
})?;
let manifest =
parse_plugin_manifest(&plugin_root, &manifest_path, &contents).map_err(|source| {
parse_plugin_manifest_uri(&plugin_root, &manifest_uri, &contents).map_err(|source| {
ExecutorPluginProviderError::ParseManifest {
root_id: root_id.clone(),
path: manifest_path.clone(),
path: manifest_uri.clone(),
source,
}
})?;
@@ -234,7 +222,7 @@ async fn resolve_plugin_root(
root_id.clone(),
environment_id.clone(),
plugin_root,
manifest_path,
manifest_uri,
manifest,
)
.map_err(|source| ExecutorPluginProviderError::ConstructDescriptor {
+74 -46
View File
@@ -1,7 +1,7 @@
use super::ExecutorPluginProvider;
use super::ExecutorPluginProviderError;
use super::resolve_plugin_root;
use crate::manifest::parse_plugin_manifest;
use crate::manifest::parse_plugin_manifest_uri;
use codex_exec_server::CopyOptions;
use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::EnvironmentManager;
@@ -18,7 +18,6 @@ use codex_plugin::PluginProvider;
use codex_plugin::ResolvedPlugin;
use codex_protocol::capabilities::CapabilityRootLocation;
use codex_protocol::capabilities::SelectedCapabilityRoot;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use std::fs;
@@ -43,13 +42,13 @@ const MANIFEST_CONTENTS: &str = r#"{
#[derive(Debug, PartialEq, Eq)]
enum FileSystemCall {
Metadata(AbsolutePathBuf),
Read(AbsolutePathBuf),
Metadata(PathUri),
Read(PathUri),
}
struct SyntheticPluginFileSystem {
plugin_root: AbsolutePathBuf,
manifest_path: AbsolutePathBuf,
plugin_root: PathUri,
manifest_path: PathUri,
calls: Mutex<Vec<FileSystemCall>>,
}
@@ -77,12 +76,11 @@ impl ExecutorFileSystem for SyntheticPluginFileSystem {
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
Box::pin(async move {
let path = path.to_abs_path()?;
self.calls
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(FileSystemCall::Read(path.clone()));
if path == self.manifest_path {
if path == &self.manifest_path {
Ok(MANIFEST_CONTENTS.as_bytes().to_vec())
} else {
Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
@@ -122,14 +120,13 @@ impl ExecutorFileSystem for SyntheticPluginFileSystem {
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
Box::pin(async move {
let path = path.to_abs_path()?;
self.calls
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(FileSystemCall::Metadata(path.clone()));
let (is_directory, is_file) = if path == self.plugin_root {
let (is_directory, is_file) = if path == &self.plugin_root {
(true, false)
} else if path == self.manifest_path {
} else if path == &self.manifest_path {
(false, true)
} else {
return Err(io::Error::new(io::ErrorKind::NotFound, "not found"));
@@ -185,7 +182,17 @@ fn selected_root(id: &str, environment_id: &str, path: &Path) -> SelectedCapabil
id: id.to_string(),
location: CapabilityRootLocation::Environment {
environment_id: environment_id.to_string(),
path: path.to_string_lossy().into_owned(),
path: PathUri::from_host_native_path(path).expect("path URI"),
},
}
}
fn selected_root_uri(id: &str, environment_id: &str, path: PathUri) -> SelectedCapabilityRoot {
SelectedCapabilityRoot {
id: id.to_string(),
location: CapabilityRootLocation::Environment {
environment_id: environment_id.to_string(),
path,
},
}
}
@@ -195,22 +202,20 @@ async fn plugin_root_resolution_uses_supplied_executor_file_system() {
let temp_dir = tempdir().expect("tempdir");
let plugin_root = temp_dir.path().join("executor-only-plugin");
assert!(!plugin_root.exists());
let plugin_root =
AbsolutePathBuf::from_absolute_path_checked(plugin_root).expect("absolute plugin root");
let manifest_path = plugin_root.join(".codex-plugin/plugin.json");
let parsed_manifest = parse_plugin_manifest(
plugin_root.as_path(),
manifest_path.as_path(),
MANIFEST_CONTENTS,
)
.expect("parse manifest");
let plugin_root = PathUri::from_host_native_path(&plugin_root).expect("plugin root URI");
let manifest_path = plugin_root
.join(".codex-plugin/plugin.json")
.expect("manifest URI");
let parsed_manifest =
parse_plugin_manifest_uri(&plugin_root, &manifest_path, MANIFEST_CONTENTS)
.expect("parse manifest");
let file_system = SyntheticPluginFileSystem {
plugin_root: plugin_root.clone(),
manifest_path: manifest_path.clone(),
calls: Mutex::new(Vec::new()),
};
let resolved = resolve_plugin_root(
&selected_root("selected-demo", "executor-test", plugin_root.as_path()),
&selected_root_uri("selected-demo", "executor-test", plugin_root.clone()),
plugin_root.clone(),
&file_system,
)
@@ -243,6 +248,51 @@ async fn plugin_root_resolution_uses_supplied_executor_file_system() {
);
}
#[tokio::test]
async fn plugin_root_resolution_accepts_foreign_executor_file_uri() {
let plugin_root = PathUri::parse("file:///C:/plugins/foo").expect("Windows plugin root URI");
let manifest_path = plugin_root
.join(".codex-plugin/plugin.json")
.expect("manifest URI");
let parsed_manifest =
parse_plugin_manifest_uri(&plugin_root, &manifest_path, MANIFEST_CONTENTS)
.expect("parse manifest");
let file_system = SyntheticPluginFileSystem {
plugin_root: plugin_root.clone(),
manifest_path: manifest_path.clone(),
calls: Mutex::new(Vec::new()),
};
let selected_root = selected_root_uri("selected-demo", "executor-test", plugin_root.clone());
let resolved = resolve_plugin_root(&selected_root, plugin_root.clone(), &file_system)
.await
.expect("resolve executor plugin");
assert_eq!(
resolved,
Some(
ResolvedPlugin::from_environment(
"selected-demo".to_string(),
"executor-test".to_string(),
plugin_root.clone(),
manifest_path.clone(),
parsed_manifest,
)
.expect("valid expected descriptor")
)
);
assert_eq!(
*file_system
.calls
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
vec![
FileSystemCall::Metadata(plugin_root),
FileSystemCall::Metadata(manifest_path.clone()),
FileSystemCall::Read(manifest_path),
]
);
}
#[tokio::test]
async fn standalone_capability_root_is_not_a_plugin() {
let temp_dir = tempdir().expect("tempdir");
@@ -292,8 +342,8 @@ async fn malformed_preferred_manifest_does_not_fall_through_to_alternate() {
MANIFEST_CONTENTS,
);
let expected_path =
AbsolutePathBuf::from_absolute_path_checked(plugin_root.join(".codex-plugin/plugin.json"))
.expect("absolute manifest path");
PathUri::from_host_native_path(plugin_root.join(".codex-plugin/plugin.json"))
.expect("manifest URI");
let provider = ExecutorPluginProvider::new(Arc::new(EnvironmentManager::default_for_tests()));
let err = provider
@@ -318,25 +368,3 @@ async fn malformed_preferred_manifest_does_not_fall_through_to_alternate() {
("selected-demo".to_string(), expected_path)
);
}
#[tokio::test]
async fn executor_root_must_be_an_explicit_absolute_path() {
let provider = ExecutorPluginProvider::new(Arc::new(EnvironmentManager::default_for_tests()));
let selected_root = SelectedCapabilityRoot {
id: "selected-demo".to_string(),
location: CapabilityRootLocation::Environment {
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
path: "~/plugins/demo".to_string(),
},
};
let err = provider
.resolve(&selected_root)
.await
.expect_err("home-relative executor path should fail");
assert_eq!(
err.to_string(),
"selected capability root `selected-demo` has invalid path `~/plugins/demo`: executor path must be absolute"
);
}
+4
View File
@@ -166,6 +166,7 @@ pub struct RemoteInstalledPlugin {
pub struct RemotePluginSummary {
pub id: String,
pub remote_plugin_id: String,
pub local_version: Option<String>,
pub name: String,
pub share_context: Option<RemotePluginShareContext>,
pub installed: bool,
@@ -1045,6 +1046,7 @@ pub fn group_remote_installed_plugins_by_marketplaces(
let plugin_summary = RemotePluginSummary {
id: plugin_id.as_key(),
remote_plugin_id: plugin.id.clone(),
local_version: None,
name: plugin.name.clone(),
share_context: None,
installed: true,
@@ -1475,6 +1477,8 @@ fn build_remote_plugin_summary(
Ok(RemotePluginSummary {
id: plugin_id.as_key(),
remote_plugin_id: plugin.id.clone(),
local_version: installed_plugin
.and_then(|installed| installed.plugin.release.version.clone()),
name: plugin.name.clone(),
share_context: remote_plugin_share_context(plugin)?,
installed: installed_plugin.is_some(),
@@ -619,6 +619,7 @@ async fn list_remote_plugin_shares_fetches_created_workspace_plugins() {
summary: RemotePluginSummary {
id: "demo-plugin@workspace-shared-with-me".to_string(),
remote_plugin_id: "plugins_123".to_string(),
local_version: None,
name: "demo-plugin".to_string(),
share_context: Some(RemotePluginShareContext {
remote_plugin_id: "plugins_123".to_string(),
@@ -658,6 +659,7 @@ async fn list_remote_plugin_shares_fetches_created_workspace_plugins() {
summary: RemotePluginSummary {
id: "demo-plugin@workspace-shared-with-me".to_string(),
remote_plugin_id: "plugins_456".to_string(),
local_version: Some("0.1.0".to_string()),
name: "demo-plugin".to_string(),
share_context: Some(RemotePluginShareContext {
remote_plugin_id: "plugins_456".to_string(),
+48 -27
View File
@@ -34,6 +34,27 @@ const CURATED_PLUGINS_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
const CURATED_PLUGINS_BACKUP_ARCHIVE_TIMEOUT: Duration = Duration::from_secs(30);
// Keep this comfortably above a normal sync attempt so we do not race another Codex process.
const CURATED_PLUGINS_STALE_TEMP_DIR_MAX_AGE: Duration = Duration::from_secs(10 * 60);
// These variables can redirect Git away from the repository selected by `-C`,
// or inject command-scoped configuration into the sync commands.
const REPOSITORY_LOCAL_GIT_ENVIRONMENT_VARIABLES: &[&str] = &[
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
"GIT_CEILING_DIRECTORIES",
"GIT_COMMON_DIR",
"GIT_CONFIG",
"GIT_CONFIG_COUNT",
"GIT_CONFIG_PARAMETERS",
"GIT_DIR",
"GIT_DISCOVERY_ACROSS_FILESYSTEM",
"GIT_GRAFT_FILE",
"GIT_IMPLICIT_WORK_TREE",
"GIT_INDEX_FILE",
"GIT_NAMESPACE",
"GIT_OBJECT_DIRECTORY",
"GIT_PREFIX",
"GIT_REPLACE_REF_BASE",
"GIT_SHALLOW_FILE",
"GIT_WORK_TREE",
];
#[derive(Debug, Deserialize)]
struct GitHubRepositorySummary {
@@ -242,17 +263,14 @@ fn fetch_curated_plugins_commit_from(
context: &str,
) -> Result<(), String> {
let fetch_refspec = format!("+{source_revision}:{CURATED_PLUGINS_FETCH_REF}");
let output = run_git_command_with_timeout(
Command::new(git_binary)
.env("GIT_OPTIONAL_LOCKS", "0")
.arg("-C")
.arg(repo_path)
.args(["fetch", "--depth", "1", "--no-tags"])
.arg(source)
.arg(fetch_refspec),
context,
CURATED_PLUGINS_GIT_TIMEOUT,
)?;
let mut command = git_command(git_binary);
command
.arg("-C")
.arg(repo_path)
.args(["fetch", "--depth", "1", "--no-tags"])
.arg(source)
.arg(fetch_refspec);
let output = run_git_command_with_timeout(&mut command, context, CURATED_PLUGINS_GIT_TIMEOUT)?;
ensure_git_success(&output, context)
}
@@ -277,15 +295,9 @@ fn run_git_in_repo(
args: &[&str],
context: &str,
) -> Result<(), String> {
let output = run_git_command_with_timeout(
Command::new(git_binary)
.env("GIT_OPTIONAL_LOCKS", "0")
.arg("-C")
.arg(repo_path)
.args(args),
context,
CURATED_PLUGINS_GIT_TIMEOUT,
)?;
let mut command = git_command(git_binary);
command.arg("-C").arg(repo_path).args(args);
let output = run_git_command_with_timeout(&mut command, context, CURATED_PLUGINS_GIT_TIMEOUT)?;
ensure_git_success(&output, context)
}
@@ -583,12 +595,13 @@ fn read_local_git_or_sha_file(
}
fn git_ls_remote_head_sha(git_binary: &str) -> Result<String, String> {
let mut command = git_command(git_binary);
command
.arg("ls-remote")
.arg("https://github.com/openai/plugins.git")
.arg("HEAD");
let output = run_git_command_with_timeout(
Command::new(git_binary)
.env("GIT_OPTIONAL_LOCKS", "0")
.arg("ls-remote")
.arg("https://github.com/openai/plugins.git")
.arg("HEAD"),
&mut command,
"git ls-remote curated plugins repo",
CURATED_PLUGINS_GIT_TIMEOUT,
)?;
@@ -610,8 +623,7 @@ fn git_ls_remote_head_sha(git_binary: &str) -> Result<String, String> {
}
fn git_head_sha(repo_path: &Path, git_binary: &str) -> Result<String, String> {
let output = Command::new(git_binary)
.env("GIT_OPTIONAL_LOCKS", "0")
let output = git_command(git_binary)
.arg("-C")
.arg(repo_path)
.arg("rev-parse")
@@ -635,6 +647,15 @@ fn git_head_sha(repo_path: &Path, git_binary: &str) -> Result<String, String> {
Ok(sha)
}
fn git_command(git_binary: &str) -> Command {
let mut command = Command::new(git_binary);
command.env("GIT_OPTIONAL_LOCKS", "0");
for name in REPOSITORY_LOCAL_GIT_ENVIRONMENT_VARIABLES {
command.env_remove(name);
}
command
}
fn run_git_command_with_timeout(
command: &mut Command,
context: &str,
@@ -1,5 +1,6 @@
use super::*;
use pretty_assertions::assert_eq;
use std::ffi::OsStr;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
@@ -16,6 +17,22 @@ use zip::write::SimpleFileOptions;
const TEST_CURATED_PLUGIN_SHA: &str = "0123456789abcdef0123456789abcdef01234567";
#[test]
fn git_command_sanitizes_ambient_repository_environment() {
let command = git_command("git");
for name in REPOSITORY_LOCAL_GIT_ENVIRONMENT_VARIABLES {
assert_eq!(
command
.get_envs()
.find(|(key, _)| *key == OsStr::new(name))
.map(|(_, value)| value),
Some(None),
"{name} should be removed from startup sync Git commands"
);
}
}
fn write_file(path: &Path, contents: &str) {
std::fs::create_dir_all(path.parent().expect("file should have a parent")).unwrap();
std::fs::write(path, contents).unwrap();
@@ -2,7 +2,6 @@ use std::collections::HashMap;
use std::sync::Arc;
use std::sync::RwLock;
use codex_app_server_protocol::AuthMode;
use codex_core_skills::config_rules::SkillConfigRules;
use codex_plugin::AppDeclaration;
use codex_plugin::PluginCapabilitySummary;
@@ -10,6 +9,7 @@ use codex_plugin::PluginId;
use codex_plugin::PluginIdError;
use codex_plugin::app_connector_ids_from_declarations;
use codex_plugin::prompt_safe_plugin_description;
use codex_protocol::auth::AuthMode;
use codex_protocol::protocol::Product;
use tokio::sync::Semaphore;