aKode fase 2b-1 (WIP): rimossi cloud-config, apps MCP ChatGPT, upload file, connectors-extension, rate limits backend; plugin remoti in corso (test non ancora compilanti)
Some checks failed
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled

This commit is contained in:
Andrea
2026-11-09 13:55:36 +01:00
parent 137106bf17
commit e4209e2755
166 changed files with 155 additions and 31558 deletions

View File

@@ -4,10 +4,6 @@ use crate::OPENAI_BUNDLED_MARKETPLACE_NAME;
use crate::PluginInstallRequest;
use crate::PluginsConfigInput;
use crate::PluginsManager;
use crate::remote::InstalledPluginDisplayAssets;
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
use crate::remote::RemotePluginServiceConfig;
use crate::remote::fetch_and_cache_global_remote_plugin_catalog;
use crate::startup_sync::curated_plugins_repo_path;
use crate::test_support::TEST_CURATED_PLUGIN_SHA;
use crate::test_support::load_plugins_config;
@@ -27,7 +23,6 @@ use codex_protocol::auth::AuthMode;
use codex_protocol::protocol::Product;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::HashSet;
use std::path::Path;
use std::sync::Arc;
@@ -35,13 +30,6 @@ use tempfile::tempdir;
use tracing::Level;
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_test::internal::MockWriter;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
use wiremock::matchers::query_param_is_missing;
#[tokio::test]
async fn returns_fallback_plugins_when_remote_disabled_for_codex_auth() {
@@ -839,238 +827,6 @@ source = "/tmp/{sales_marketplace_name}"
assert_eq!(discoverable_plugins, Vec::new());
}
#[tokio::test]
async fn cached_remote_discovery_requires_installed_cache_and_filters_candidates() {
assert_cached_remote_discovery_filters_candidates(InstalledPluginDisplayAssets::Include).await;
}
/// Tool suggestions need installed IDs even when display enrichment was skipped.
#[tokio::test]
async fn cached_remote_discovery_accepts_snapshot_without_display_assets() {
assert_cached_remote_discovery_filters_candidates(InstalledPluginDisplayAssets::Skip).await;
}
async fn assert_cached_remote_discovery_filters_candidates(
display_assets: InstalledPluginDisplayAssets,
) {
let codex_home = tempdir().expect("tempdir should succeed");
write_file(
&codex_home.path().join(CONFIG_TOML_FILE),
r#"[features]
plugins = true
"#,
);
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/list"))
.and(query_param("scope", "GLOBAL"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [
{
"id": "plugins~Plugin_remote_github",
"name": "github",
"scope": "GLOBAL",
"installation_policy": "AVAILABLE",
"authentication_policy": "ON_USE",
"status": "AVAILABLE",
"release": {
"display_name": "Remote GitHub",
"description": "Remote GitHub long",
"app_ids": ["github"],
"interface": {"short_description": "Remote GitHub short"},
"skills": [{
"name": "github",
"description": "Use GitHub",
"interface": null
}]
}
},
{
"id": "plugins~Plugin_remote_unlisted",
"name": "remote-unlisted",
"scope": "GLOBAL",
"installation_policy": "AVAILABLE",
"authentication_policy": "ON_USE",
"status": "AVAILABLE",
"release": {
"display_name": "Remote Unlisted",
"description": "Remote Unlisted long",
"app_ids": ["remote-unlisted-app"],
"interface": {
"short_description": "Remote Unlisted short",
"long_description": null,
"developer_name": null,
"category": null,
"capabilities": [],
"website_url": null,
"privacy_policy_url": null,
"terms_of_service_url": null,
"brand_color": null,
"default_prompt": null,
"composer_icon_url": null,
"logo_url": null,
"screenshot_urls": []
},
"skills": [
{
"name": "remote-unlisted",
"description": "Use unlisted remote plugin",
"interface": null
}
]
}
},
{
"id": "plugins~Plugin_remote_slack_not_available",
"name": "slack",
"scope": "GLOBAL",
"installation_policy": "NOT_AVAILABLE",
"authentication_policy": "ON_USE",
"status": "AVAILABLE",
"release": {
"display_name": "Remote Slack",
"description": "Remote Slack long",
"interface": {"short_description": "Remote Slack short"}
}
},
{
"id": "plugins~Plugin_remote_figma_admin_disabled",
"name": "figma",
"scope": "GLOBAL",
"installation_policy": "AVAILABLE",
"authentication_policy": "ON_USE",
"status": "DISABLED_BY_ADMIN",
"release": {
"display_name": "Remote Figma",
"description": "Remote Figma long",
"interface": {"short_description": "Remote Figma short"}
}
}
],
"pagination": {
"next_page_token": null
}
})))
.expect(1)
.mount(&server)
.await;
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let mut plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
plugins.chatgpt_base_url = format!("{}/backend-api", server.uri());
let plugins_manager = test_plugins_manager_with_options(
codex_home.path().to_path_buf(),
Some(Product::Codex),
Some(AuthMode::Chatgpt),
);
fetch_and_cache_global_remote_plugin_catalog(
codex_home.path(),
&RemotePluginServiceConfig::new(
plugins.chatgpt_base_url.clone(),
crate::test_support::test_http_client_factory(),
/*product_sku*/ None,
),
Some(&auth),
)
.await
.expect("remote plugin catalog cache should write");
assert_eq!(
list_discoverable_plugins(
&plugins_manager,
discovery_input(plugins.clone(), &[], &[], &["remote-unlisted-app"]),
Some(&auth),
)
.await,
Vec::new()
);
let installed_request = Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.and(query_param_is_missing("scope"))
.and(query_param_is_missing("includeDownloadUrls"));
let installed_request = match display_assets {
InstalledPluginDisplayAssets::Include => {
installed_request.and(query_param_is_missing("includeDisplayAssets"))
}
InstalledPluginDisplayAssets::Skip => {
installed_request.and(query_param("includeDisplayAssets", "false"))
}
};
installed_request
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [],
"pagination": {
"next_page_token": null
}
})))
.expect(1)
.mount(&server)
.await;
plugins_manager
.build_and_cache_remote_installed_plugin_marketplaces_with_display_assets(
&plugins,
Some(&auth),
&[REMOTE_GLOBAL_MARKETPLACE_NAME],
/*on_effective_plugins_changed*/ None,
display_assets,
)
.await
.expect("remote installed plugin cache should write");
let expected_github = ToolSuggestDiscoverablePlugin {
id: "github@openai-curated-remote".to_string(),
remote_plugin_id: Some("plugins~Plugin_remote_github".to_string()),
name: "Remote GitHub".to_string(),
description: Some("Remote GitHub short".to_string()),
has_skills: true,
mcp_server_names: Vec::new(),
app_connector_ids: vec!["github".to_string()],
};
assert_eq!(
list_discoverable_plugins(
&plugins_manager,
discovery_input(plugins.clone(), &[], &[], &[]),
Some(&auth),
)
.await,
vec![expected_github.clone()]
);
let discoverable_plugins = list_discoverable_plugins(
&plugins_manager,
discovery_input(plugins.clone(), &[], &[], &["remote-unlisted-app"]),
Some(&auth),
)
.await;
assert_eq!(
discoverable_plugins,
vec![
expected_github,
ToolSuggestDiscoverablePlugin {
id: "remote-unlisted@openai-curated-remote".to_string(),
remote_plugin_id: Some("plugins~Plugin_remote_unlisted".to_string()),
name: "Remote Unlisted".to_string(),
description: Some("Remote Unlisted short".to_string()),
has_skills: true,
mcp_server_names: Vec::new(),
app_connector_ids: vec!["remote-unlisted-app".to_string()],
},
]
);
assert_eq!(
list_discoverable_plugins(
&plugins_manager,
discovery_input(plugins, &[], &["github@openai-curated-remote"], &[]),
Some(&auth),
)
.await,
Vec::new()
);
}
fn discovery_input(
plugins: PluginsConfigInput,
configured_plugin_ids: &[&str],

View File

@@ -1,8 +1,5 @@
use codex_http_client::NetworkPolicy;
use codex_http_client::OutboundProxyPolicy;
use codex_http_client::RequestBuilder;
use codex_http_client::RouteAwareClientPool;
use http::Method;
use std::fmt::Debug;
use std::sync::Arc;
@@ -12,13 +9,6 @@ use std::sync::Arc;
/// client would let callers send a different URL than the one used for route selection.
pub(crate) trait HttpClientSelector: Debug + Send + Sync {
fn for_current_account(&self) -> Arc<dyn HttpClientSelector>;
fn request(&self, method: Method, url: &str) -> RequestBuilder;
fn request_for_account(
&self,
method: Method,
url: &str,
binding: &NetworkPolicy,
) -> Option<RequestBuilder>;
fn outbound_proxy_policy(&self) -> OutboundProxyPolicy;
}
@@ -27,19 +17,6 @@ impl HttpClientSelector for RouteAwareClientPool {
Arc::new(RouteAwareClientPool::for_current_account(self))
}
fn request(&self, method: Method, url: &str) -> RequestBuilder {
RouteAwareClientPool::request(self, method, url)
}
fn request_for_account(
&self,
method: Method,
url: &str,
binding: &NetworkPolicy,
) -> Option<RequestBuilder> {
Some(self.with_account_binding(binding)?.request(method, url))
}
fn outbound_proxy_policy(&self) -> OutboundProxyPolicy {
RouteAwareClientPool::outbound_proxy_policy(self)
}

View File

@@ -22,7 +22,6 @@ mod marketplace_staging;
pub mod marketplace_upgrade;
mod npm_source;
mod plugin_bundle_archive;
mod plugin_measurement_references;
mod plugin_metrics;
mod plugin_metrics_sidecar;
mod provider;
@@ -109,8 +108,6 @@ pub use marketplace_policy::allowed_configured_marketplace_names;
pub use marketplace_upgrade::ConfigLayerReload;
pub use marketplace_upgrade::ConfiguredMarketplaceUpgradeError as PluginMarketplaceUpgradeError;
pub use marketplace_upgrade::ConfiguredMarketplaceUpgradeOutcome as PluginMarketplaceUpgradeOutcome;
pub use plugin_measurement_references::PluginMeasurementReference;
pub use plugin_measurement_references::RemotePluginMeasurementCache;
pub use plugin_metrics::PluginMeasurementDefinition;
pub use plugin_metrics::PluginMetricsOperation;
pub use plugin_metrics::ResolvedPluginMetricsOperation;

View File

@@ -89,6 +89,7 @@ pub(super) fn marketplace_error_sub_error_type(err: &MarketplaceError) -> Option
fn remote_plugin_mutation_error_type(err: &RemotePluginMutationError) -> &'static str {
match err {
RemotePluginMutationError::Unavailable => "remote_mutation_unavailable",
RemotePluginMutationError::AuthRequired => "remote_mutation_auth_required",
RemotePluginMutationError::UnsupportedAuthMode => "remote_mutation_unsupported_auth_mode",
RemotePluginMutationError::AuthToken(_) => "remote_mutation_auth_token",

View File

@@ -17,7 +17,6 @@ use crate::marketplace::MarketplacePluginInstallPolicy;
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
use crate::remote::REMOTE_WORKSPACE_MARKETPLACE_NAME;
use crate::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME;
use crate::remote::RecommendedPlugin;
use crate::remote::RemoteInstalledPlugin;
use crate::startup_sync::curated_plugins_repo_path;
use crate::test_support::TEST_CURATED_PLUGIN_CACHE_VERSION;
@@ -65,16 +64,8 @@ use codex_utils_plugins::SkillDiscoveryMode;
use pretty_assertions::assert_eq;
use std::fs;
use std::path::Path;
use std::time::Duration;
use tempfile::TempDir;
use toml::Value;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
const MAX_CAPABILITY_SUMMARY_DESCRIPTION_LEN: usize = 1024;
@@ -6023,460 +6014,6 @@ enabled = true
);
}
#[tokio::test]
async fn featured_plugin_ids_for_config_uses_restriction_product_query_param() {
let tmp = tempfile::tempdir().unwrap();
write_file(
&tmp.path().join(CONFIG_TOML_FILE),
r#"[features]
plugins = true
"#,
);
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/backend-api/plugins/featured"))
.and(query_param("platform", "chat"))
.and(header("authorization", "Bearer Access Token"))
.and(header("chatgpt-account-id", "account_id"))
.respond_with(ResponseTemplate::new(200).set_body_string(r#"["chat-plugin"]"#))
.mount(&server)
.await;
let mut config = load_config(tmp.path(), tmp.path()).await;
config.chatgpt_base_url = format!("{}/backend-api/", server.uri());
let manager = test_plugins_manager_with_options(
tmp.path().to_path_buf(),
Some(Product::Chatgpt),
/*auth_mode*/ None,
);
let featured_plugin_ids = manager
.featured_plugin_ids_for_config(
&config,
Some(&CodexAuth::create_dummy_chatgpt_auth_for_testing()),
)
.await
.unwrap();
assert_eq!(featured_plugin_ids, vec!["chat-plugin".to_string()]);
}
#[tokio::test]
async fn featured_plugin_ids_for_config_defaults_query_param_to_codex() {
let tmp = tempfile::tempdir().unwrap();
write_file(
&tmp.path().join(CONFIG_TOML_FILE),
r#"[features]
plugins = true
"#,
);
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/backend-api/plugins/featured"))
.and(query_param("platform", "codex"))
.respond_with(ResponseTemplate::new(200).set_body_string(r#"["codex-plugin"]"#))
.mount(&server)
.await;
let mut config = load_config(tmp.path(), tmp.path()).await;
config.chatgpt_base_url = format!("{}/backend-api/", server.uri());
let manager = test_plugins_manager_with_options(
tmp.path().to_path_buf(),
/*restriction_product*/ None,
/*auth_mode*/ None,
);
let featured_plugin_ids = manager
.featured_plugin_ids_for_config(&config, /*auth*/ None)
.await
.unwrap();
assert_eq!(featured_plugin_ids, vec!["codex-plugin".to_string()]);
}
#[tokio::test]
async fn remote_plugin_caches_refresh_warms_recommended_plugins_cache() {
let tmp = tempfile::tempdir().unwrap();
write_file(
&tmp.path().join(CONFIG_TOML_FILE),
r#"[features]
plugins = true
"#,
);
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/ps/plugins/suggested/codex"))
.and(query_param("scope", "GLOBAL"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"enabled": true,
"plugins": []
})))
.expect(1)
.mount(&server)
.await;
let mut config = load_config(tmp.path(), tmp.path()).await;
config.chatgpt_base_url = server.uri();
let manager = std::sync::Arc::new(test_plugins_manager(tmp.path().to_path_buf()));
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let cache_key = recommended_plugins_cache_key(&config);
manager.maybe_start_remote_plugin_caches_refresh(
&config,
Some(auth.clone()),
/*on_effective_plugins_changed*/ None,
);
let mode = tokio::time::timeout(Duration::from_secs(2), async {
loop {
if let Some(mode) = manager.cached_recommended_plugins_mode(&cache_key) {
break mode;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("recommended plugins cache should be warmed");
assert_eq!(
mode,
RecommendedPluginsMode::Endpoint {
plugins: Vec::new()
}
);
assert_eq!(
manager
.recommended_plugins_mode_for_config(&config, Some(&auth))
.await,
mode
);
manager.clear_recommended_plugins_cache();
assert_eq!(manager.cached_recommended_plugins_mode(&cache_key), None);
}
#[tokio::test]
async fn recommended_plugins_mode_deduplicates_concurrent_cache_misses() {
let tmp = tempfile::tempdir().unwrap();
write_file(
&tmp.path().join(CONFIG_TOML_FILE),
r#"[features]
plugins = true
"#,
);
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/ps/plugins/suggested/codex"))
.and(query_param("scope", "GLOBAL"))
.and(header("authorization", "Bearer Access Token"))
.and(header("chatgpt-account-id", "account_id"))
.and(header("OAI-Product-Sku", "codex"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(serde_json::json!({
"enabled": true,
"plugins": [
{
"id": "plugin_slack",
"name": "slack",
"display_name": "Slack"
},
{
"id": "plugin_github",
"name": "github",
"display_name": "GitHub"
}
]
}))
.set_delay(Duration::from_millis(100)),
)
.expect(1)
.mount(&server)
.await;
let mut config = load_config(tmp.path(), tmp.path()).await;
config.chatgpt_base_url = server.uri();
let manager = test_plugins_manager(tmp.path().to_path_buf());
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let expected = RecommendedPluginsMode::Endpoint {
plugins: vec![
RecommendedPlugin {
config_id: "github@openai-curated-remote".to_string(),
remote_plugin_id: "plugin_github".to_string(),
display_name: "GitHub".to_string(),
},
RecommendedPlugin {
config_id: "slack@openai-curated-remote".to_string(),
remote_plugin_id: "plugin_slack".to_string(),
display_name: "Slack".to_string(),
},
],
};
let (left, right) = tokio::join!(
manager.recommended_plugins_mode_for_config(&config, Some(&auth)),
manager.recommended_plugins_mode_for_config(&config, Some(&auth)),
);
assert_eq!((left, right), (expected.clone(), expected.clone()));
assert_eq!(
manager
.recommended_plugins_mode_for_config(&config, Some(&auth))
.await,
expected
);
}
#[tokio::test]
async fn recommended_plugins_cache_clear_rejects_stale_fetch_completion() {
let tmp = tempfile::tempdir().unwrap();
write_file(
&tmp.path().join(CONFIG_TOML_FILE),
"[features]\nplugins = true\n",
);
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let server = MockServer::start().await;
let request_started = Arc::new(tokio::sync::Notify::new());
let started = Arc::clone(&request_started);
let (release_response, released) = std::sync::mpsc::channel();
let released = std::sync::Mutex::new(released);
let old_response = ResponseTemplate::new(200).set_body_json(serde_json::json!({
"enabled": true,
"plugins": [{"id": "plugin_old", "name": "old", "display_name": "Old"}]
}));
Mock::given(method("GET"))
.and(path("/ps/plugins/suggested/codex"))
.respond_with(move |_: &wiremock::Request| {
started.notify_one();
// Wiremock runs its own server thread. Dropping the sender also releases it.
let _ = released.lock().unwrap().recv();
old_response.clone()
})
.up_to_n_times(1)
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/ps/plugins/suggested/codex"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"enabled": true,
"plugins": []
})))
.expect(1)
.mount(&server)
.await;
let mut config = load_config(tmp.path(), tmp.path()).await;
config.chatgpt_base_url = server.uri();
let manager = test_plugins_manager(tmp.path().to_path_buf());
let old_lookup = manager.recommended_plugins_mode_for_config(&config, Some(&auth));
tokio::pin!(old_lookup);
tokio::select! {
biased;
_ = request_started.notified() => {}
mode = old_lookup.as_mut() => panic!("old fetch finished before release: {mode:?}"),
}
manager.clear_recommended_plugins_cache();
release_response
.send(())
.expect("release old HTTP response");
// Keep the old initializer unpolled until the new fetch publishes. An invalidated
// fetch must not overwrite the fresh result.
let new_mode = tokio::time::timeout(
Duration::from_secs(10),
manager.recommended_plugins_mode_for_config(&config, Some(&auth)),
)
.await
.expect("new lookup should finish independently of the invalidated fetch");
assert_eq!(
new_mode,
RecommendedPluginsMode::Endpoint {
plugins: Vec::new()
}
);
assert_eq!(
old_lookup.await,
RecommendedPluginsMode::Endpoint {
plugins: vec![RecommendedPlugin {
config_id: "old@openai-curated-remote".to_string(),
remote_plugin_id: "plugin_old".to_string(),
display_name: "Old".to_string(),
}]
}
);
assert_eq!(
manager
.recommended_plugins_mode_for_config(&config, Some(&auth))
.await,
new_mode
);
server.verify().await;
}
#[tokio::test]
async fn recommended_plugin_candidates_filter_installed_and_disabled_plugins() {
let tmp = tempfile::tempdir().unwrap();
write_file(
&tmp.path().join(CONFIG_TOML_FILE),
r#"[features]
plugins = true
"#,
);
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/ps/plugins/suggested/codex"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"enabled": true,
"plugins": [
{
"id": "plugin_linear",
"name": "linear",
"display_name": "Linear"
},
{
"id": "plugin_github",
"name": "github",
"display_name": "GitHub"
},
{
"id": "plugin_slack",
"name": "slack",
"display_name": "Slack"
}
]
})))
.expect(1)
.mount(&server)
.await;
let mut config = load_config(tmp.path(), tmp.path()).await;
config.chatgpt_base_url = server.uri();
let manager = test_plugins_manager(tmp.path().to_path_buf());
let mut installed_linear = remote_installed_plugin("linear");
installed_linear.id = "plugin_linear".to_string();
manager.write_remote_installed_plugins_cache(vec![installed_linear]);
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let disabled_tools = [ToolSuggestDisabledTool::plugin(
"github@openai-curated-remote",
)];
let loaded_plugins = manager.plugins_for_config(&config).await;
let candidates = manager
.recommended_plugin_candidates_for_config(RecommendedPluginCandidatesInput {
plugins_config: &config,
loaded_plugins: &loaded_plugins,
auth: Some(&auth),
disabled_tools: &disabled_tools,
app_server_client_name: None,
})
.await;
assert_eq!(
candidates,
Some(vec![DiscoverableTool::from(DiscoverablePluginInfo {
id: "slack@openai-curated-remote".to_string(),
remote_plugin_id: Some("plugin_slack".to_string()),
name: "Slack".to_string(),
description: None,
has_skills: false,
mcp_server_names: Vec::new(),
app_connector_ids: Vec::new(),
})])
);
}
#[tokio::test]
async fn recommended_plugins_mode_caches_explicit_false() {
let tmp = tempfile::tempdir().unwrap();
write_file(
&tmp.path().join(CONFIG_TOML_FILE),
r#"[features]
plugins = true
"#,
);
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/ps/plugins/suggested/codex"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"enabled": false,
"plugins": []
})))
.expect(1)
.mount(&server)
.await;
let mut config = load_config(tmp.path(), tmp.path()).await;
config.chatgpt_base_url = server.uri();
let manager = test_plugins_manager(tmp.path().to_path_buf());
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
assert_eq!(
manager
.recommended_plugins_mode_for_config(&config, Some(&auth))
.await,
RecommendedPluginsMode::Legacy
);
assert_eq!(
manager
.recommended_plugins_mode_for_config(&config, Some(&auth))
.await,
RecommendedPluginsMode::Legacy
);
}
#[tokio::test]
async fn recommended_plugins_mode_retries_after_fetch_failure() {
let tmp = tempfile::tempdir().unwrap();
write_file(
&tmp.path().join(CONFIG_TOML_FILE),
r#"[features]
plugins = true
"#,
);
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/ps/plugins/suggested/codex"))
.respond_with(ResponseTemplate::new(500).set_body_string("unavailable"))
.expect(1)
.mount(&server)
.await;
let mut config = load_config(tmp.path(), tmp.path()).await;
config.chatgpt_base_url = server.uri();
let manager = test_plugins_manager(tmp.path().to_path_buf());
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
assert_eq!(
manager
.recommended_plugins_mode_for_config(&config, Some(&auth))
.await,
RecommendedPluginsMode::Legacy
);
server.reset().await;
Mock::given(method("GET"))
.and(path("/ps/plugins/suggested/codex"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"enabled": true,
"plugins": []
})))
.expect(1)
.mount(&server)
.await;
assert_eq!(
manager
.recommended_plugins_mode_for_config(&config, Some(&auth))
.await,
RecommendedPluginsMode::Endpoint {
plugins: Vec::new()
}
);
}
#[test]
fn refresh_curated_plugin_cache_replaces_existing_local_version_with_short_sha_version() {
let tmp = tempfile::tempdir().unwrap();
@@ -7488,386 +7025,6 @@ fn remote_installed_plugins_cache_refresh_coalesces_materializations() {
);
}
#[tokio::test]
async fn background_remote_installed_bundle_sync_stays_deduped() {
let codex_home = TempDir::new().unwrap();
write_file(
&codex_home.path().join(CONFIG_TOML_FILE),
r#"[features]
plugins = true
remote_plugin = true
"#,
);
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.and(query_param("includeDownloadUrls", "true"))
.respond_with(
ResponseTemplate::new(200)
.set_delay(Duration::from_millis(200))
.set_body_json(serde_json::json!({
"plugins": [],
"pagination": {"next_page_token": null},
})),
)
.expect(1)
.mount(&server)
.await;
let mut config = load_config(codex_home.path(), codex_home.path()).await;
config.chatgpt_base_url = format!("{}/backend-api", server.uri());
let first_manager = std::sync::Arc::new(test_plugins_manager_with_options(
codex_home.path().to_path_buf(),
Some(Product::Codex),
Some(AuthMode::Chatgpt),
));
let second_manager = std::sync::Arc::new(test_plugins_manager_with_options(
codex_home.path().to_path_buf(),
Some(Product::Codex),
Some(AuthMode::Chatgpt),
));
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
first_manager.maybe_start_remote_installed_plugin_bundle_sync(
&config,
Some(auth.clone()),
/*on_effective_plugins_changed*/ None,
);
second_manager.maybe_start_remote_installed_plugin_bundle_sync(
&config,
Some(auth),
/*on_effective_plugins_changed*/ None,
);
let _guard = first_manager
.acquire_remote_installed_plugin_sync_guard()
.await
.expect("background bundle sync should finish");
server.verify().await;
}
#[tokio::test]
async fn reconcile_remote_installed_plugins_reports_cached_state_changes() {
let codex_home = TempDir::new().unwrap();
write_file(
&codex_home.path().join(CONFIG_TOML_FILE),
"[features]\nplugins = true\n",
);
write_cached_plugin(
codex_home.path(),
REMOTE_WORKSPACE_MARKETPLACE_NAME,
"linear",
);
let plugin_root = codex_home
.path()
.join("plugins/cache/workspace-directory/linear/local");
write_file(
&plugin_root.join(".mcp.json"),
r#"{"mcpServers":{"example":{"command":"unused"}}}"#,
);
write_file(
&plugin_root.join("hooks/hooks.json"),
r#"{"hooks":{"UserPromptSubmit":[{"hooks":[{"type":"command","command":"echo hook"}]}]}}"#,
);
let server = MockServer::start().await;
let mut config = load_config(codex_home.path(), codex_home.path()).await;
config.chatgpt_base_url = format!("{}/backend-api", server.uri());
let auth_manager = test_auth_manager(Some(AuthMode::Chatgpt));
let auth = auth_manager.auth_cached().expect("test ChatGPT auth");
let manager = test_plugins_manager_with_auth_manager(
codex_home.path().to_path_buf(),
Some(Product::Codex),
auth_manager,
);
let change = RemotePluginChange {
plugin_id: "linear@workspace-directory".to_string(),
capabilities: RemotePluginCapabilities {
has_mcps: true,
has_hooks: true,
has_skills: true,
..Default::default()
},
};
// None represents an uninstall. Reinstalling its retained bundle must report an
// activation even though the known previous snapshot has no entry for the plugin.
for (enabled, changes) in [
(Some(true), Vec::new()),
(Some(false), vec![change.clone()]),
(Some(false), Vec::new()),
(Some(true), vec![change.clone()]),
(None, vec![change.clone()]),
(Some(true), vec![change.clone()]),
(Some(true), Vec::new()),
] {
if enabled.is_none() {
// Fail cleanup before it reaches the bundle; removal hints must survive.
write_file(
&codex_home
.path()
.join("plugins/cache/openai-curated-remote"),
"not a directory",
);
}
let plugins = enabled
.into_iter()
.map(|enabled| {
serde_json::json!({
"id": "plugins~Plugin_linear",
"name": "linear",
"scope": "WORKSPACE",
"discoverability": "LISTED",
"installation_policy": "AVAILABLE",
"authentication_policy": "ON_USE",
"release": {
"version": "local",
"display_name": "Linear",
"description": "Test plugin",
"interface": {},
},
"enabled": enabled,
})
})
.collect::<Vec<_>>();
// No download URL: every installed pass must reuse the cached version.
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.and(query_param("includeDownloadUrls", "true"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"plugins": plugins,
"pagination": { "next_page_token": null },
})))
.expect(1)
.mount(&server)
.await;
assert_eq!(
manager
.reconcile_remote_installed_plugins(&config, Some(&auth))
.await
.expect("reconcile cached plugin state"),
RemoteInstalledPluginBundleSyncOutcome {
changed_plugins: changes,
..Default::default()
}
);
assert!(plugin_root.exists());
if enabled.is_none() {
assert_eq!(
manager.plugins_for_config(&config).await,
PluginLoadOutcome::default()
);
}
server.verify().await;
server.reset().await;
}
}
#[tokio::test]
async fn reconcile_remote_installed_plugins_rejects_incomplete_snapshot_without_cleanup() {
let codex_home = TempDir::new().unwrap();
write_file(
&codex_home.path().join(CONFIG_TOML_FILE),
r#"[features]
plugins = true
remote_plugin = true
"#,
);
write_cached_plugin(codex_home.path(), REMOTE_GLOBAL_MARKETPLACE_NAME, "linear");
write_cached_plugin(
codex_home.path(),
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME,
"malformed",
);
write_cached_plugin(
codex_home.path(),
REMOTE_WORKSPACE_MARKETPLACE_NAME,
"renamed-malformed",
);
let malformed_remote_plugin_id = "plugins~Plugin_malformed";
let malformed_plugin_id = PluginId::new(
"malformed".to_string(),
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME.to_string(),
)
.expect("valid malformed plugin id");
PluginStore::new(codex_home.path().to_path_buf())
.write_remote_plugin_id(&malformed_plugin_id, malformed_remote_plugin_id)
.expect("persist malformed plugin identity");
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.and(query_param("includeDownloadUrls", "true"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"plugins": [
{
"id": "plugins~Plugin_linear",
"name": "linear",
"scope": "GLOBAL",
"installation_policy": "AVAILABLE",
"authentication_policy": "ON_USE",
"status": "ENABLED",
"release": {
"version": "local",
"display_name": "",
"description": "Track work",
"interface": {},
},
"enabled": true,
},
{
"id": malformed_remote_plugin_id,
"name": "renamed-malformed",
"scope": "WORKSPACE",
"installation_policy": "AVAILABLE",
"authentication_policy": "ON_USE",
"status": "ENABLED",
"release": {
"version": "local",
"display_name": "Malformed",
"description": "Missing discoverability",
"interface": {},
},
"enabled": true,
},
],
"pagination": {"next_page_token": null},
})))
.expect(1)
.mount(&server)
.await;
let mut config = load_config(codex_home.path(), codex_home.path()).await;
config.chatgpt_base_url = format!("{}/backend-api", server.uri());
let auth_manager = test_auth_manager(Some(AuthMode::Chatgpt));
let auth = auth_manager.auth_cached().expect("test ChatGPT auth");
let manager = std::sync::Arc::new(test_plugins_manager_with_auth_manager(
codex_home.path().to_path_buf(),
Some(Product::Codex),
auth_manager,
));
let mut previous_malformed = remote_installed_plugin_in_marketplace(
"malformed",
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME,
);
previous_malformed.id = malformed_remote_plugin_id.to_string();
previous_malformed.version = Some("local".to_string());
previous_malformed.enabled = false;
manager.write_remote_installed_plugins_cache(vec![previous_malformed.clone()]);
let result = manager
.reconcile_remote_installed_plugins(&config, Some(&auth))
.await;
assert!(matches!(
result,
Err(RemoteInstalledPluginBundleSyncError::Catalog(
RemotePluginCatalogError::UnexpectedResponse(_)
))
));
server.verify().await;
assert_eq!(
manager
.remote_installed_plugins_cache
.read()
.expect("installed plugin cache lock")
.plugins
.clone(),
Some(vec![previous_malformed])
);
let plugin_cache_root = codex_home.path().join("plugins/cache");
let renamed_malformed_cache = plugin_cache_root
.join(REMOTE_WORKSPACE_MARKETPLACE_NAME)
.join("renamed-malformed");
let previous_malformed_cache = plugin_cache_root
.join(REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME)
.join("malformed");
let linear_metadata = plugin_cache_root
.join(REMOTE_GLOBAL_MARKETPLACE_NAME)
.join("linear")
.join(".codex-remote-plugin-install.json");
assert!(renamed_malformed_cache.exists());
assert!(previous_malformed_cache.exists());
assert!(!linear_metadata.exists());
}
#[tokio::test]
async fn failed_installed_plugin_pagination_preserves_inventory_and_releases_mutation_gate() {
let codex_home = TempDir::new().unwrap();
write_file(
&codex_home.path().join(CONFIG_TOML_FILE),
"[features]\nplugins = true\nremote_plugin = true\n",
);
write_cached_plugin(
codex_home.path(),
REMOTE_GLOBAL_MARKETPLACE_NAME,
"retained",
);
let server = MockServer::start().await;
// Both bundle sync and its metadata fallback must reject the incomplete inventory.
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"plugins": [],
"pagination": {"next_page_token": "next"},
})))
.expect(4)
.mount(&server)
.await;
let mut config = load_config(codex_home.path(), codex_home.path()).await;
config.chatgpt_base_url = format!("{}/backend-api", server.uri());
let auth_manager = test_auth_manager(Some(AuthMode::Chatgpt));
let auth = auth_manager.auth_cached().expect("test ChatGPT auth");
let manager = Arc::new(test_plugins_manager_with_auth_manager(
codex_home.path().to_path_buf(),
Some(Product::Codex),
auth_manager,
));
let previous_inventory = vec![remote_installed_plugin("retained")];
manager.write_remote_installed_plugins_cache(previous_inventory.clone());
manager.maybe_start_remote_installed_plugin_bundle_sync(
&config,
Some(auth),
/*on_effective_plugins_changed*/ None,
);
// Starting the sync acquires the gate synchronously, so this waits for its release.
let _guard = tokio::time::timeout(
Duration::from_secs(5),
manager.acquire_remote_installed_plugin_sync_guard(),
)
.await
.expect("failed pagination should promptly release the mutation gate")
.expect("mutation gate should remain available");
tokio::time::timeout(Duration::from_secs(5), async {
while manager
.remote_installed_plugins_cache_refresh_state
.read()
.expect("refresh state lock")
.in_flight
{
tokio::task::yield_now().await;
}
})
.await
.expect("fallback metadata refresh should finish");
assert_eq!(
manager
.remote_installed_plugins_cache
.read()
.expect("installed cache lock")
.plugins
.clone(),
Some(previous_inventory),
);
assert!(
codex_home
.path()
.join("plugins/cache/openai-curated-remote/retained")
.exists()
);
server.verify().await;
}
#[test]
fn reconciliation_fences_refresh_publication_and_recovers_after_cancellation() {
let codex_home = TempDir::new().unwrap();

View File

@@ -1,31 +1,11 @@
use crate::manifest::load_plugin_manifest;
use flate2::Compression;
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use std::fmt;
use std::fs;
use std::io;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use tar::Archive;
#[derive(Debug, thiserror::Error)]
pub(crate) enum PluginBundlePackError {
#[error("invalid plugin path `{path}`: {reason}")]
InvalidPluginPath { path: PathBuf, reason: String },
#[error("plugin archive would be {bytes} bytes, exceeding maximum size of {max_bytes} bytes")]
ArchiveTooLarge { bytes: usize, max_bytes: usize },
#[error("failed to archive plugin bundle: {source}")]
Io {
#[source]
source: io::Error,
},
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum PluginBundleUnpackError {
#[error(
@@ -50,80 +30,6 @@ impl PluginBundleUnpackError {
}
}
pub(crate) fn pack_plugin_bundle_tar_gz(
plugin_path: &Path,
max_bytes: usize,
) -> Result<Vec<u8>, PluginBundlePackError> {
if !plugin_path.is_dir() {
return Err(PluginBundlePackError::InvalidPluginPath {
path: plugin_path.to_path_buf(),
reason: "expected a plugin directory".to_string(),
});
}
if !plugin_path.join(".codex-plugin/plugin.json").is_file()
&& load_plugin_manifest(plugin_path).is_none()
{
return Err(PluginBundlePackError::InvalidPluginPath {
path: plugin_path.to_path_buf(),
reason: "missing .codex-plugin/plugin.json or valid Agent Plugin manifest".to_string(),
});
}
let encoder = GzEncoder::new(SizeLimitedBuffer::new(max_bytes), Compression::default());
let mut archive = tar::Builder::new(encoder);
append_plugin_tree(&mut archive, plugin_path, plugin_path).map_err(archive_io_error)?;
let encoder = archive.into_inner().map_err(archive_io_error)?;
encoder
.finish()
.map(SizeLimitedBuffer::into_inner)
.map_err(archive_io_error)
}
fn append_plugin_tree<W: Write>(
archive: &mut tar::Builder<W>,
plugin_root: &Path,
current: &Path,
) -> io::Result<()> {
let mut entries = fs::read_dir(current)?.collect::<Result<Vec<_>, io::Error>>()?;
entries.sort_by_key(fs::DirEntry::file_name);
for entry in entries {
let path = entry.path();
let file_type = entry.file_type()?;
let relative_path = path.strip_prefix(plugin_root).map_err(|err| {
io::Error::other(format!(
"failed to compute plugin archive path for `{}`: {err}",
path.display()
))
})?;
if file_type.is_dir() {
archive.append_dir(relative_path, &path)?;
append_plugin_tree(archive, plugin_root, &path)?;
} else if file_type.is_file() {
archive.append_path_with_name(&path, relative_path)?;
} else {
return Err(io::Error::other(format!(
"unsupported plugin archive entry type: {}",
path.display()
)));
}
}
Ok(())
}
fn archive_io_error(source: io::Error) -> PluginBundlePackError {
if let Some(limit) = source
.get_ref()
.and_then(|err| err.downcast_ref::<ArchiveSizeLimitExceeded>())
{
return PluginBundlePackError::ArchiveTooLarge {
bytes: limit.bytes,
max_bytes: limit.max_bytes,
};
}
PluginBundlePackError::Io { source }
}
pub(crate) fn unpack_plugin_bundle_tar_gz(
bytes: &[u8],
destination: &Path,
@@ -257,66 +163,3 @@ fn enforce_total_extracted_size(
Ok(())
}
struct SizeLimitedBuffer {
bytes: Vec<u8>,
max_bytes: usize,
}
impl SizeLimitedBuffer {
fn new(max_bytes: usize) -> Self {
Self {
bytes: Vec::new(),
max_bytes,
}
}
fn into_inner(self) -> Vec<u8> {
self.bytes
}
}
impl Write for SizeLimitedBuffer {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let next_len = self.bytes.len().checked_add(buf.len()).ok_or_else(|| {
io::Error::other(ArchiveSizeLimitExceeded {
bytes: usize::MAX,
max_bytes: self.max_bytes,
})
})?;
if next_len > self.max_bytes {
return Err(io::Error::other(ArchiveSizeLimitExceeded {
bytes: next_len,
max_bytes: self.max_bytes,
}));
}
self.bytes.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[derive(Debug)]
struct ArchiveSizeLimitExceeded {
bytes: usize,
max_bytes: usize,
}
impl fmt::Display for ArchiveSizeLimitExceeded {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"archive would be {} bytes, exceeding maximum size of {} bytes",
self.bytes, self.max_bytes
)
}
}
impl std::error::Error for ArchiveSizeLimitExceeded {}
#[cfg(test)]
#[path = "plugin_bundle_archive_tests.rs"]
mod tests;

View File

@@ -1,41 +0,0 @@
use super::*;
use tempfile::tempdir;
#[test]
fn portable_root_manifest_can_be_packed_and_unpacked() {
let source = tempdir().expect("source tempdir");
fs::write(
source.path().join("plugin.json"),
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"portable"}"#,
)
.expect("write portable manifest");
fs::create_dir_all(source.path().join("skills/demo")).expect("create skill directory");
fs::write(source.path().join("skills/demo/SKILL.md"), "# Demo\n").expect("write skill");
let archive =
pack_plugin_bundle_tar_gz(source.path(), 1024 * 1024).expect("pack portable plugin");
let destination = tempdir().expect("destination tempdir");
unpack_plugin_bundle_tar_gz(&archive, destination.path(), 1024 * 1024)
.expect("unpack portable plugin");
assert!(destination.path().join("plugin.json").is_file());
assert!(destination.path().join("skills/demo/SKILL.md").is_file());
}
#[test]
fn invalid_portable_manifest_is_rejected_before_packing() {
let source = tempdir().expect("source tempdir");
fs::write(
source.path().join("plugin.json"),
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"UPPER"}"#,
)
.expect("write invalid portable manifest");
let error = pack_plugin_bundle_tar_gz(source.path(), 1024 * 1024)
.expect_err("invalid Agent Plugin manifest should fail");
assert!(matches!(
error,
PluginBundlePackError::InvalidPluginPath { .. }
));
}

View File

@@ -1,63 +0,0 @@
//! Selects one authenticated installed GLOBAL plugin without capability loading.
use super::*;
use crate::store::validate_plugin_version_segment;
use codex_utils_path_uri::PathConvention;
/// Fetches installation authorization and download metadata, but materializes no
/// other installed plugins and never publishes to the shared plugin catalog.
pub(crate) async fn fetch_measurement_reference_bundle(
config: &RemotePluginServiceConfig,
auth: &CodexAuth,
target: &crate::script_attribution::PluginMeasurementTarget,
) -> anyhow::Result<Option<(String, crate::remote_bundle::ValidatedRemotePluginBundle)>> {
ensure_chatgpt_auth(Some(auth))?;
let installed = fetch_installed_plugins(
config,
auth,
RemoteInstalledPluginScope::Single(RemotePluginScope::Global),
/*include_download_urls*/ true,
InstalledPluginDisplayAssets::Include,
)
.await?;
let mut matching = installed.into_iter().filter(|installed| {
let plugin = &installed.plugin;
let Some(version) = plugin.release.version.as_deref().map(str::trim) else {
return false;
};
if validate_plugin_version_segment(version).is_err() {
return false;
}
// Compare with the executor's path rules, retaining the catalog's
// spelling for the validated bundle and cache identity below.
let matches_target = match target.path_convention {
PathConvention::Windows => target
.plugin_id
.plugin_name
.eq_ignore_ascii_case(&plugin.name),
PathConvention::Posix => target.plugin_id.plugin_name == plugin.name,
};
installed.enabled
&& plugin.scope == RemotePluginScope::Global
&& matches_target
&& plugin.availability == PluginAvailability::Available
&& plugin.installation_policy != PluginInstallPolicy::NotAvailable
&& plugin.disabled_reason.is_none()
});
let Some(installed) = matching.next() else {
return Ok(None);
};
if matching.next().is_some() {
return Ok(None);
}
let plugin = installed.plugin;
let bundle = crate::remote_bundle::validate_remote_plugin_bundle(
&plugin.id,
REMOTE_GLOBAL_MARKETPLACE_NAME,
&plugin.name,
plugin.release.version.as_deref(),
plugin.release.bundle_download_url.as_deref(),
plugin.release.app_manifest,
)?;
Ok(Some((plugin.id, bundle)))
}

View File

@@ -1,244 +0,0 @@
//! Authenticated, immutable references for one executor plugin's measurements.
use crate::PluginsConfigInput;
use crate::TrustedPluginRoots;
use crate::manager::RemoteInstalledPluginsAuthIdentity;
use crate::remote::fetch_measurement_reference_bundle;
use crate::remote_bundle::download_remote_plugin_bundle;
use crate::remote_bundle::install_remote_plugin_bundle;
use crate::script_attribution::PluginMeasurementTarget;
use codex_features::RuntimeAuthMode;
use codex_login::CodexAuth;
use codex_plugin::PluginId;
use codex_runtime_agent_instance::RuntimeAuthSlot;
use codex_utils_path_uri::PathConvention;
use std::sync::Arc;
use tempfile::TempDir;
use tokio::sync::Mutex;
use tokio::sync::watch;
const MAX_CACHED_REFERENCES: usize = 4;
/// Owns the immutable files backing its roots. Keep the reference alive for the
/// full command/turn that consumes those roots, including asynchronous commands.
pub struct PluginMeasurementReference {
roots: TrustedPluginRoots,
home: Option<TempDir>,
}
impl Drop for PluginMeasurementReference {
fn drop(&mut self) {
let Some(home) = self.home.take() else {
return;
};
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
runtime.spawn_blocking(move || drop(home));
} else {
drop(home);
}
}
}
impl PluginMeasurementReference {
pub fn roots(&self) -> &TrustedPluginRoots {
&self.roots
}
}
#[derive(PartialEq, Eq)]
struct ReferenceKey {
actor: RemoteInstalledPluginsAuthIdentity,
endpoint: String,
remote_id: String,
plugin_id: PluginId,
version: String,
}
type ReferenceCell = Arc<watch::Receiver<Option<Arc<PluginMeasurementReference>>>>;
fn is_preparing(cell: &ReferenceCell) -> bool {
cell.has_changed().is_ok() && cell.borrow().is_none()
}
/// A thread-scoped cache, separate from the installed plugin/capability store.
/// Each version has its own store so installing a new version cannot remove
/// files still leased by an earlier turn. At most four entries are retained,
/// including active preparations; command-held leases can outlive eviction.
#[derive(Default)]
pub struct RemotePluginMeasurementCache {
references: Mutex<Vec<(ReferenceKey, ReferenceCell)>>,
}
impl RemotePluginMeasurementCache {
pub fn new() -> Self {
Self::default()
}
/// Rechecks current installation authorization, then prepares only the
/// requested version. Previously authenticated versions remain reusable after
/// a release update; a cache miss can download only the current release.
/// Callers apply analytics consent and product gates.
/// Concurrent callers share a download even if one caller is cancelled.
/// Returns no reference when all cache entries are actively preparing.
/// Failures omit authenticated URLs and response bodies from diagnostics.
pub async fn prepare(
&self,
config: &PluginsConfigInput,
auth: &CodexAuth,
target: &PluginMeasurementTarget,
runtime_auth: Option<(RuntimeAuthSlot, RuntimeAuthMode)>,
) -> anyhow::Result<Option<Arc<PluginMeasurementReference>>> {
if !config.plugins_enabled || !config.remote_plugin_enabled || !auth.uses_codex_backend() {
return Ok(None);
}
// Like normal remote loading, the authenticated installed catalog is
// authoritative for enabled state, including default installations.
// GLOBAL plugins have already passed server-side admission; local
// marketplace product policy and skill capability loading are separate.
let service = config
.remote_plugin_service_config(runtime_auth)
.for_current_account();
let Some((remote_id, bundle)) = fetch_measurement_reference_bundle(&service, auth, target)
.await
.map_err(|_| anyhow::anyhow!("plugin measurement catalog lookup failed"))?
else {
return Ok(None);
};
// The executor hint follows its filesystem's case rules. The cache and
// local store use the authenticated bundle's exact identity instead.
let plugin_id = bundle.plugin_id.clone();
let version = bundle.plugin_version.clone();
let current_version = match target.path_convention {
PathConvention::Windows => target.version.eq_ignore_ascii_case(&version),
PathConvention::Posix => target.version == version,
};
let key = ReferenceKey {
actor: RemoteInstalledPluginsAuthIdentity::from_auth(Some(auth)),
endpoint: config.chatgpt_base_url.clone(),
remote_id: remote_id.clone(),
plugin_id: plugin_id.clone(),
version: if current_version {
version.clone()
} else {
target.version.clone()
},
};
let (cell, initializer, retired) = {
let mut references = self.references.lock().await;
let mut retired = Vec::new();
// Keep active preparations admitted until they finish, even after an
// identity change; they can never match the new key.
for index in (0..references.len()).rev() {
let (existing, cell) = &references[index];
// A closed, empty result is a completed failure. Only a new
// caller can admit a retry; existing waiters observe that failure.
if (cell.has_changed().is_err() && cell.borrow().is_none())
|| (!is_preparing(cell)
&& (existing.actor != key.actor
|| existing.endpoint != key.endpoint
|| (existing.plugin_id == key.plugin_id
&& existing.remote_id != key.remote_id)))
{
retired.push(references.remove(index));
}
}
let mut initializer = None;
let mut matching = references.iter().enumerate().filter(|(_, (existing, _))| {
if current_version {
return existing == &key;
}
existing.actor == key.actor
&& existing.endpoint == key.endpoint
&& existing.remote_id == key.remote_id
&& existing.plugin_id == key.plugin_id
&& match target.path_convention {
PathConvention::Windows => {
existing.version.eq_ignore_ascii_case(&key.version)
}
PathConvention::Posix => existing.version == key.version,
}
});
// Historical Windows hints must not select between case-distinct releases.
let cached_index = match (matching.next(), matching.next()) {
(Some((index, _)), None) => Some(index),
_ => None,
};
let cell = if let Some(index) = cached_index {
let entry = references.remove(index);
let cell = Arc::clone(&entry.1);
references.push(entry);
Some(cell)
} else if !current_version {
// The catalog cannot supply a trusted historical bundle.
None
} else if references.len() < MAX_CACHED_REFERENCES {
let (sender, receiver) = watch::channel(None);
let cell = Arc::new(receiver);
initializer = Some(sender);
references.push((key, Arc::clone(&cell)));
Some(cell)
} else if let Some(index) = references.iter().position(|(_, cell)| !is_preparing(cell))
{
retired.push(references.remove(index));
let (sender, receiver) = watch::channel(None);
let cell = Arc::new(receiver);
initializer = Some(sender);
references.push((key, Arc::clone(&cell)));
Some(cell)
} else {
None
};
(cell, initializer, retired)
};
// Final reference drops schedule store cleanup outside the cache mutex.
drop(retired);
let Some(cell) = cell else {
return Ok(None);
};
if let Some(sender) = initializer {
// The cache keeps the receiver alive when individual callers cancel.
// Once the cache and all callers disappear, stop waiting/downloading.
tokio::spawn(async move {
let reference = tokio::select! {
biased;
_ = sender.closed() => return,
reference = async {
let bytes = download_remote_plugin_bundle(&service, &bundle).await?;
// Blocking extraction cannot be aborted once started. Its
// owner must keep the store alive even if this task stops.
tokio::task::spawn_blocking(move || {
let home = tempfile::tempdir()?;
install_remote_plugin_bundle(home.path().to_owned(), bundle, bytes)?;
let roots = TrustedPluginRoots::from_measurement_reference(
home.path(),
&plugin_id,
&version,
&remote_id,
)
.ok_or_else(|| anyhow::anyhow!("invalid plugin measurement reference"))?;
Ok::<_, anyhow::Error>(Arc::new(PluginMeasurementReference {
roots,
home: Some(home),
}))
}).await?
} => reference,
};
if let Ok(reference) = reference {
sender.send_replace(Some(reference));
}
// Closing an empty channel reports failure without retaining
// authenticated URLs or response bodies in the shared result.
});
}
let mut receiver = cell.as_ref().clone();
let reference = receiver
.wait_for(Option::is_some)
.await
.map_err(|_| anyhow::anyhow!("plugin measurement preparation failed"))?;
Ok(reference.clone())
}
}
#[cfg(test)]
#[path = "plugin_measurement_references_tests.rs"]
mod tests;

View File

@@ -1,775 +0,0 @@
//! Real bundle preparation tests without mutating the parent test environment.
use super::*;
use crate::test_support::load_plugins_config;
use crate::test_support::write_file;
use anyhow::Context;
use anyhow::Result;
use codex_exec_server::LOCAL_FS;
use codex_utils_path_uri::PathConvention;
use codex_utils_path_uri::PathUri;
use flate2::Compression;
use flate2::write::GzEncoder;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::path::Path;
use std::process::Command;
use std::time::Duration;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::sync::Semaphore;
use tokio::sync::mpsc;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
const SCRIPT: &str = "console.log('installed');\n";
const ANALYTICS: &str = "version: 1\noperations:\n install:\n path: scripts/install.mjs\n measurements:\n duration_ms:\n dimensions:\n outcome: [success, error]\n";
fn isolated_bundle_test(name: &str) -> Result<bool> {
const CHILD: &str = "CODEX_MEASUREMENT_REFERENCE_TEST";
if std::env::var(CHILD).as_deref() == Ok(name) {
return Ok(true);
}
let output = Command::new(std::env::current_exe()?)
.args([
"--exact",
&format!("plugin_measurement_references::tests::{name}"),
"--nocapture",
])
.env(CHILD, name)
.env("CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS", "1")
.output()?;
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
Ok(false)
}
fn installed(server: &MockServer, version: &str) -> Value {
json!({
"id": "plugins~sites", "name": "sites", "scope": "GLOBAL", "enabled": true,
"installation_policy": "AVAILABLE", "authentication_policy": "ON_USE", "status": "ENABLED",
"release": {"version": version, "display_name": "Sites", "description": "",
"bundle_download_url": format!("{}/bundle/{version}", server.uri()), "interface": {}}
})
}
async fn catalog(server: &MockServer, plugins: Vec<Value>) {
Mock::given(method("GET"))
.and(path("/ps/plugins/installed"))
.and(query_param("scope", "GLOBAL"))
.and(query_param("includeDownloadUrls", "true"))
.respond_with(
ResponseTemplate::new(200).set_body_json(json!({"plugins": plugins, "pagination": {}})),
)
.mount(server)
.await;
}
fn archive(plugin_name: &str) -> Result<Vec<u8>> {
let mut archive = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::default()));
let manifest = json!({"name": plugin_name, "version": "1.0.0"}).to_string();
for (name, bytes) in [
(".codex-plugin/plugin.json", manifest.as_str()),
("scripts/install.mjs", SCRIPT),
("analytics.yaml", ANALYTICS),
// Invalid capability files must not be parsed by measurement preparation.
(".mcp.json", "invalid json"),
("skills/broken/SKILL.md", "invalid skill"),
] {
let mut header = tar::Header::new_gnu();
header.set_size(bytes.len() as u64);
header.set_mode(0o644);
header.set_cksum();
archive.append_data(&mut header, name, bytes.as_bytes())?;
}
Ok(archive.into_inner()?.finish()?)
}
async fn bundle(server: &MockServer, version: &str, count: u64) -> Result<()> {
Mock::given(method("GET"))
.and(path(format!("/bundle/{version}")))
.respond_with(ResponseTemplate::new(200).set_body_bytes(archive("sites")?))
.expect(count)
.mount(server)
.await;
Ok(())
}
async fn wait_until_removed(path: &Path) -> Result<()> {
tokio::time::timeout(Duration::from_secs(5), async {
while path.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await?;
Ok(())
}
fn named_plugin(server: &MockServer, name: &str) -> Result<(Value, PluginMeasurementTarget)> {
let mut plugin = installed(server, "1.0.0");
plugin["name"] = json!(name);
plugin["id"] = json!(format!("plugins~{name}"));
plugin["release"]["bundle_download_url"] = json!(format!("{}/bundle/{name}", server.uri()));
let target = PluginMeasurementTarget {
plugin_id: PluginId::new(name.to_owned(), "openai-curated-remote".to_owned())?,
version: "1.0.0".to_owned(),
path_convention: PathConvention::Posix,
};
Ok((plugin, target))
}
async fn target(
executor: &Path,
version: &str,
) -> Result<(PluginMeasurementTarget, Vec<String>, PathUri)> {
let script = executor.join(format!(
"plugins/cache/openai-curated-remote/sites/{version}/scripts/install.mjs"
));
write_file(&script, SCRIPT);
let command = vec!["node".to_owned(), script.to_string_lossy().into_owned()];
let cwd = PathUri::from_host_native_path(executor)?;
let target = PluginMeasurementTarget::from_command(&command, &cwd, LOCAL_FS.as_ref())
.await
.context("canonical plugin target")?;
Ok((target, command, cwd))
}
struct Fixture {
server: MockServer,
home: TempDir,
executor: TempDir,
config: PluginsConfigInput,
auth: CodexAuth,
cache: RemotePluginMeasurementCache,
}
impl Fixture {
async fn new() -> Result<Self> {
let server = MockServer::start().await;
let home = tempfile::tempdir()?;
let executor = tempfile::tempdir()?;
let mut config = load_plugins_config(home.path(), executor.path()).await;
config.chatgpt_base_url = server.uri();
Ok(Self {
server,
home,
executor,
config,
auth: CodexAuth::create_dummy_chatgpt_auth_for_testing(),
cache: RemotePluginMeasurementCache::new(),
})
}
async fn prepare(
&self,
target: &PluginMeasurementTarget,
) -> Result<Option<Arc<PluginMeasurementReference>>> {
self.cache
.prepare(&self.config, &self.auth, target, /*runtime_auth*/ None)
.await
}
async fn assert_request_count(&self, expected: usize) {
assert_eq!(
self.server
.received_requests()
.await
.expect("requests")
.len(),
expected
);
}
async fn wait_for_cached_reference(
&self,
ready: impl Fn(&ReferenceCell) -> bool,
) -> Result<()> {
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let is_ready = {
let references = self.cache.references.lock().await;
ready(&references[0].1)
};
if is_ready {
break;
}
tokio::task::yield_now().await;
}
})
.await?;
Ok(())
}
}
#[tokio::test]
async fn narrow_preparation_reuses_versions_and_keeps_old_leases_alive() -> Result<()> {
if !isolated_bundle_test("narrow_preparation_reuses_versions_and_keeps_old_leases_alive")? {
return Ok(());
}
let mut f = Fixture::new().await?;
let (first, command, cwd) = target(f.executor.path(), "1.0.0").await?;
let mut unrelated = installed(&f.server, "1.0.0");
unrelated["id"] = json!("plugins~unrelated");
unrelated["name"] = json!("unrelated");
unrelated["release"]["bundle_download_url"] = json!("invalid URL must never be examined");
catalog(&f.server, vec![unrelated, installed(&f.server, "1.0.0")]).await;
bundle(&f.server, "1.0.0", /*count*/ 1).await?;
let (left, right) = tokio::join!(f.prepare(&first), f.prepare(&first));
let first_ref = left?.context("first reference")?;
assert!(Arc::ptr_eq(
&first_ref,
&right?.context("parallel reference")?
));
let warm = f.prepare(&first).await?.context("warm reference")?;
assert!(Arc::ptr_eq(&first_ref, &warm));
let old_home = first_ref
.home
.as_ref()
.expect("reference store")
.path()
.to_owned();
let resolved = first_ref
.roots()
.resolve_metrics_operation_in_filesystem(&command, &cwd, LOCAL_FS.as_ref())
.await
.context("real resolver")?;
assert_eq!(resolved.operation.operation_name, "install");
f.server.verify().await;
f.server.reset().await;
let (second, _, _) = target(f.executor.path(), "2.0.0").await?;
catalog(&f.server, vec![installed(&f.server, "2.0.0")]).await;
assert!(Arc::ptr_eq(
&first_ref,
&f.prepare(&first).await?.context("reference after update")?
));
// A newer release cannot supply an older version's declaration on a cold cache.
assert!(
RemotePluginMeasurementCache::new()
.prepare(&f.config, &f.auth, &first, /*runtime_auth*/ None)
.await?
.is_none()
);
bundle(&f.server, "2.0.0", /*count*/ 1).await?;
let new_ref = f.prepare(&second).await?.context("new reference")?;
assert_ne!(
new_ref.home.as_ref().expect("reference store").path(),
old_home
);
assert!(Arc::ptr_eq(
&first_ref,
&f.prepare(&first).await?.context("retained older version")?
));
assert!(
first_ref
.roots()
.resolve_metrics_operation_in_filesystem(&command, &cwd, LOCAL_FS.as_ref())
.await
.is_some()
);
f.server.verify().await;
f.server.reset().await;
let mut disabled = installed(&f.server, "2.0.0");
disabled["enabled"] = json!(false);
let mut replaced = installed(&f.server, "2.0.0");
replaced["id"] = json!("plugins~replacement");
for plugins in [vec![], vec![disabled], vec![replaced]] {
catalog(&f.server, plugins).await;
assert!(f.prepare(&first).await?.is_none());
f.assert_request_count(/*expected*/ 1).await;
f.server.reset().await;
}
drop(warm);
drop(first_ref);
catalog(&f.server, vec![installed(&f.server, "2.0.0")]).await;
bundle(&f.server, "2.0.0", /*count*/ 1).await?;
f.auth = CodexAuth::from_external_chatgpt_tokens(
"header.e30.other",
"other-account",
/*chatgpt_plan_type*/ None,
)?;
let other_ref = f.prepare(&second).await?.context("other actor reference")?;
assert!(!Arc::ptr_eq(&new_ref, &other_ref));
assert!(f.prepare(&first).await?.is_none());
wait_until_removed(&old_home).await?;
f.server.verify().await;
f.server.reset().await;
let mut disabled = installed(&f.server, "2.0.0");
disabled["enabled"] = json!(false);
catalog(&f.server, vec![disabled]).await;
assert!(f.prepare(&second).await?.is_none());
Ok(())
}
#[tokio::test]
async fn preparation_preserves_catalog_spelling_and_executor_case_rules() -> Result<()> {
if !isolated_bundle_test("preparation_preserves_catalog_spelling_and_executor_case_rules")? {
return Ok(());
}
let f = Fixture::new().await?;
let mut plugin = installed(&f.server, "2.0.0-RC1");
plugin["name"] = json!("Sites");
plugin["release"]["version"] = json!(" 2.0.0-RC1\n");
catalog(&f.server, vec![plugin.clone()]).await;
Mock::given(method("GET"))
.and(path("/bundle/2.0.0-RC1"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(archive("Sites")?))
.expect(1)
.mount(&f.server)
.await;
// Drive and UNC preselection normalize these hints identically on every host.
let windows = PluginMeasurementTarget {
plugin_id: PluginId::parse("sites@openai-curated-remote")?,
version: "2.0.0-rc1".to_owned(),
path_convention: PathConvention::Windows,
};
let reference = f.prepare(&windows).await?.context("Windows reference")?;
let exact = PluginMeasurementTarget {
plugin_id: PluginId::parse("Sites@openai-curated-remote")?,
version: "2.0.0-RC1".to_owned(),
path_convention: PathConvention::Posix,
};
assert!(Arc::ptr_eq(
&reference,
&f.prepare(&exact)
.await?
.context("same authenticated bundle")?
));
let store = crate::store::PluginStore::new(
reference
.home
.as_ref()
.expect("reference store")
.path()
.to_owned(),
);
assert_eq!(
store.active_plugin_version(&exact.plugin_id),
Some(exact.version.clone())
);
let root = store.plugin_root(&exact.plugin_id, &exact.version);
let command = vec![
"node".to_owned(),
root.join("scripts/install.mjs")
.to_string_lossy()
.into_owned(),
];
let operation = reference
.roots()
.resolve_metrics_operation(&command, &root)
.context("trusted declaration retains the authenticated identity")?;
assert_eq!(
(operation.plugin_id, operation.operation.operation_name),
(exact.plugin_id.clone(), "install".to_owned())
);
for (name, version) in [("sites", "2.0.0-RC1"), ("Sites", "2.0.0-rc1")] {
let mismatch = PluginMeasurementTarget {
plugin_id: PluginId::new(name.to_owned(), "openai-curated-remote".to_owned())?,
version: version.to_owned(),
path_convention: PathConvention::Posix,
};
assert!(f.prepare(&mismatch).await?.is_none());
}
f.server.verify().await;
f.server.reset().await;
let mut ambiguous = installed(&f.server, "2.0.0-rc1");
ambiguous["id"] = json!("plugins~other-case");
catalog(&f.server, vec![plugin.clone(), ambiguous]).await;
assert!(f.prepare(&windows).await?.is_none());
f.assert_request_count(/*expected*/ 1).await;
// POSIX still selects its exact entry, even when another entry folds the same way.
assert!(Arc::ptr_eq(
&reference,
&f.prepare(&exact)
.await?
.context("exact POSIX catalog entry")?
));
f.server.reset().await;
plugin["release"]["version"] = json!("2.0.0-rc1");
catalog(&f.server, vec![plugin.clone()]).await;
Mock::given(method("GET"))
.and(path("/bundle/2.0.0-RC1"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(archive("Sites")?))
.expect(1)
.mount(&f.server)
.await;
let lower_case = f
.prepare(&windows)
.await?
.context("current catalog version")?;
assert!(!Arc::ptr_eq(&reference, &lower_case));
f.server.verify().await;
f.server.reset().await;
plugin["release"]["version"] = json!("3.0.0");
catalog(&f.server, vec![plugin]).await;
assert!(f.prepare(&windows).await?.is_none());
assert!(Arc::ptr_eq(
&reference,
&f.prepare(&exact)
.await?
.context("unambiguous historical version")?
));
Ok(())
}
#[tokio::test]
async fn preparation_requires_enabled_matching_installed_global_plugin() -> Result<()> {
if !isolated_bundle_test("preparation_requires_enabled_matching_installed_global_plugin")? {
return Ok(());
}
let mut f = Fixture::new().await?;
let (target, _, _) = target(f.executor.path(), "1.0.0").await?;
for (field, value) in [
("/enabled", json!(false)),
("/scope", json!("WORKSPACE")),
("/installation_policy", json!("NOT_AVAILABLE")),
("/status", json!("DISABLED_BY_ADMIN")),
("/name", json!("other")),
("/release/version", json!(" ")),
("/release/version", json!("../1.0.0")),
] {
let mut plugin = installed(&f.server, "1.0.0");
*plugin.pointer_mut(field).expect("catalog field") = value;
catalog(&f.server, vec![plugin]).await;
assert!(f.prepare(&target).await?.is_none(), "{field}");
f.assert_request_count(/*expected*/ 1).await;
f.server.reset().await;
}
catalog(&f.server, vec![installed(&f.server, "1.0.0"); 2]).await;
assert!(f.prepare(&target).await?.is_none());
f.server.reset().await;
for (enabled, auth) in [
(false, f.auth.clone()),
(true, CodexAuth::from_api_key("test")),
] {
f.config.remote_plugin_enabled = enabled;
f.auth = auth;
assert!(f.prepare(&target).await?.is_none());
}
f.assert_request_count(/*expected*/ 0).await;
write_file(
&f.home.path().join("config.toml"),
"[plugins.\"sites@openai-curated-remote\"]\nenabled = false\n",
);
f.config = load_plugins_config(f.home.path(), f.executor.path()).await;
f.config.chatgpt_base_url = f.server.uri();
f.auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let mut forced = installed(&f.server, "1.0.0");
forced["installation_policy"] = json!("INSTALLED_BY_DEFAULT");
catalog(&f.server, vec![forced]).await;
bundle(&f.server, "1.0.0", /*count*/ 1).await?;
assert!(f.prepare(&target).await?.is_some());
Ok(())
}
#[tokio::test]
async fn preparation_failures_do_not_expose_authenticated_urls_or_response_bodies() -> Result<()> {
if !isolated_bundle_test(
"preparation_failures_do_not_expose_authenticated_urls_or_response_bodies",
)? {
return Ok(());
}
let f = Fixture::new().await?;
let (target, _, _) = target(f.executor.path(), "1.0.0").await?;
for invalid_url in [true, false] {
let mut plugin = installed(&f.server, "1.0.0");
plugin["release"]["bundle_download_url"] = json!(if invalid_url {
"not a URL?sig=query-secret".to_owned()
} else {
format!("{}/bundle/1.0.0?sig=query-secret", f.server.uri())
});
catalog(&f.server, vec![plugin]).await;
Mock::given(method("GET"))
.and(path("/bundle/1.0.0"))
.respond_with(ResponseTemplate::new(500).set_body_string("response-body-secret"))
.expect(u64::from(!invalid_url))
.mount(&f.server)
.await;
let error = match f.prepare(&target).await {
Err(error) => error,
Ok(_) => anyhow::bail!("expected a preparation failure"),
};
for diagnostic in [
format!("{error}"),
format!("{error:#}"),
format!("{error:?}"),
format!("{error:#?}"),
]
.into_iter()
.chain(error.chain().map(ToString::to_string))
{
for secret in [
"query-secret",
"response-body-secret",
"sig=",
f.server.uri().as_str(),
] {
assert!(!diagnostic.contains(secret), "diagnostic exposed {secret}");
}
}
f.server.verify().await;
f.server.reset().await;
}
Ok(())
}
#[tokio::test]
async fn canceled_waiters_do_not_retry_a_failed_preparation() -> Result<()> {
if !isolated_bundle_test("canceled_waiters_do_not_retry_a_failed_preparation")? {
return Ok(());
}
let f = Arc::new(Fixture::new().await?);
let (target, _, _) = target(f.executor.path(), "1.0.0").await?;
let target = Arc::new(target);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
let mut plugin = installed(&f.server, "1.0.0");
plugin["release"]["bundle_download_url"] =
json!(format!("http://{}/bundle", listener.local_addr()?));
catalog(&f.server, vec![plugin]).await;
let release = Arc::new(Semaphore::new(0));
let (requested, mut requests) = mpsc::unbounded_channel();
let bundle_server = tokio::spawn({
let release = Arc::clone(&release);
async move {
for attempt in 0..2 {
let (socket, _) = listener.accept().await?;
let mut socket = tokio::io::BufReader::new(socket);
let mut line = String::new();
loop {
line.clear();
socket.read_line(&mut line).await?;
if line == "\r\n" || line.is_empty() {
break;
}
}
requested.send(attempt)?;
let (status, body) = if attempt == 0 {
release.acquire().await?.forget();
("500 Internal Server Error", Vec::new())
} else {
("200 OK", archive("sites")?)
};
socket
.write_all(
format!(
"HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
)
.as_bytes(),
)
.await?;
socket.write_all(&body).await?;
}
Ok::<_, anyhow::Error>(())
}
});
let mut callers = Vec::new();
for _ in 0..4 {
let f = Arc::clone(&f);
let target = Arc::clone(&target);
callers.push(tokio::spawn(async move { f.prepare(&target).await }));
}
assert_eq!(
tokio::time::timeout(Duration::from_secs(5), requests.recv()).await?,
Some(0)
);
// Wait until all four callers hold the cell alongside the cache before
// canceling the callers during the held download.
f.wait_for_cached_reference(|cell| Arc::strong_count(cell) >= 5)
.await?;
for caller in callers {
caller.abort();
assert!(matches!(caller.await, Err(error) if error.is_cancelled()));
}
release.add_permits(1);
// Observe all admitted workers finishing before checking the request count;
// an abandoned waiter must not become a second initializer after the failure.
f.wait_for_cached_reference(|cell| cell.has_changed().is_err())
.await?;
assert!(requests.try_recv().is_err(), "canceled caller retried");
let reference = tokio::time::timeout(Duration::from_secs(5), f.prepare(&target))
.await??
.context("a new caller can retry the failed preparation")?;
assert_eq!(requests.recv().await, Some(1));
assert!(Arc::ptr_eq(
&reference,
&f.prepare(&target).await?.context("retry is cached")?
));
bundle_server.await??;
Ok(())
}
#[tokio::test]
async fn cache_evicts_least_recently_used_bundles_without_invalidating_command_leases() -> Result<()>
{
if !isolated_bundle_test(
"cache_evicts_least_recently_used_bundles_without_invalidating_command_leases",
)? {
return Ok(());
}
let f = Fixture::new().await?;
let mut plugins = Vec::new();
let mut targets = Vec::new();
for index in 0..=MAX_CACHED_REFERENCES {
let name = format!("plugin-{index}");
let (plugin, target) = named_plugin(&f.server, &name)?;
plugins.push(plugin);
targets.push(target);
Mock::given(method("GET"))
.and(path(format!("/bundle/{name}")))
.respond_with(ResponseTemplate::new(200).set_body_bytes(archive(&name)?))
.expect(if index == 1 { 2 } else { 1 })
.mount(&f.server)
.await;
}
catalog(&f.server, plugins).await;
let mut leases = Vec::new();
for target in &targets[..MAX_CACHED_REFERENCES] {
leases.push(f.prepare(target).await?.context("initial reference")?);
}
// A concurrent warm reader must not make a completed entry unevictable.
let completed_reader = Arc::clone(&f.cache.references.lock().await[1].1);
assert!(Arc::ptr_eq(
&leases[0],
&f.prepare(&targets[0]).await?.context("recent reference")?
));
let extra = f
.prepare(&targets[MAX_CACHED_REFERENCES])
.await?
.context("new plugin")?;
let evicted_home = leases[1]
.home
.as_ref()
.expect("reference store")
.path()
.to_owned();
assert!(
evicted_home.exists(),
"command lease survives cache eviction"
);
assert!(Arc::ptr_eq(
&leases[0],
&f.prepare(&targets[0])
.await?
.context("retained recent reference")?
));
let replacement = f
.prepare(&targets[1])
.await?
.context("evicted plugin reload")?;
assert_ne!(
replacement.home.as_ref().expect("reference store").path(),
evicted_home
);
drop(completed_reader);
drop(leases.remove(1));
wait_until_removed(&evicted_home).await?;
assert!(
extra
.home
.as_ref()
.expect("reference store")
.path()
.exists()
);
f.server.verify().await;
Ok(())
}
#[tokio::test]
async fn dropping_the_cache_cancels_an_unused_download() -> Result<()> {
if !isolated_bundle_test("dropping_the_cache_cancels_an_unused_download")? {
return Ok(());
}
let f = Arc::new(Fixture::new().await?);
let (target, _, _) = target(f.executor.path(), "1.0.0").await?;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
let mut plugin = installed(&f.server, "1.0.0");
plugin["release"]["bundle_download_url"] =
json!(format!("http://{}/bundle", listener.local_addr()?));
catalog(&f.server, vec![plugin]).await;
let (requested, request) = tokio::sync::oneshot::channel();
let download = tokio::spawn(async move {
let (socket, _) = listener.accept().await?;
let mut socket = tokio::io::BufReader::new(socket);
let mut line = String::new();
loop {
line.clear();
socket.read_line(&mut line).await?;
if line == "\r\n" || line.is_empty() {
break;
}
}
requested.send(()).expect("test awaits bundle request");
// Hold the response until cancellation closes the download connection.
let mut remainder = Vec::new();
socket.read_to_end(&mut remainder).await?;
Ok::<_, anyhow::Error>(())
});
let caller = tokio::spawn({
let f = Arc::clone(&f);
async move { f.prepare(&target).await }
});
tokio::time::timeout(Duration::from_secs(5), request).await??;
caller.abort();
assert!(matches!(caller.await, Err(error) if error.is_cancelled()));
drop(f);
tokio::time::timeout(Duration::from_secs(5), download).await???;
Ok(())
}
#[test]
fn final_store_cleanup_runs_outside_the_async_worker() -> Result<()> {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.max_blocking_threads(1)
.build()?;
runtime.block_on(async {
let (started, ready) = tokio::sync::oneshot::channel();
let (release, wait) = std::sync::mpsc::channel::<()>();
let blocker = tokio::task::spawn_blocking(move || {
let _ = started.send(());
let _ = wait.recv();
});
ready.await?;
let home = tempfile::tempdir()?;
let path = home.path().to_owned();
drop(PluginMeasurementReference {
roots: TrustedPluginRoots::default(),
home: Some(home),
});
assert!(path.exists(), "cleanup must wait for the blocking worker");
release.send(())?;
blocker.await?;
wait_until_removed(&path).await
})?;
// References may also outlive their runtime and still need ordinary cleanup.
let home = tempfile::tempdir()?;
let path = home.path().to_owned();
drop(runtime);
drop(PluginMeasurementReference {
roots: TrustedPluginRoots::default(),
home: Some(home),
});
assert!(!path.exists());
Ok(())
}

View File

@@ -1,18 +1,10 @@
//! Verify connection reuse without retaining request metadata or crossing config lifetimes.
use super::PluginsConfigInput;
use crate::remote::fetch_recommended_plugins;
use crate::test_support::test_http_client_factory;
use codex_config::ConfigLayerStack;
use codex_login::CodexAuth;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[test]
fn repeated_service_configs_and_early_clones_share_one_lazy_pool() {
@@ -62,71 +54,3 @@ fn repeated_service_configs_and_early_clones_share_one_lazy_pool() {
(vec![true; 220], false)
);
}
#[tokio::test]
async fn reused_pool_uses_current_endpoint_product_and_authentication() {
let first_server = MockServer::start().await;
let second_server = MockServer::start().await;
for (server, token, account, product_sku) in [
(&first_server, "header.e30.first", "first-account", "codex"),
(
&second_server,
"header.e30.second",
"second-account",
"updated",
),
] {
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/suggested/codex"))
.and(header("authorization", format!("Bearer {token}")))
.and(header("chatgpt-account-id", account))
.and(header("oai-product-sku", product_sku))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"enabled": true,
"plugins": [],
})))
.expect(1)
.mount(server)
.await;
}
let mut input = PluginsConfigInput::new(
ConfigLayerStack::default(),
Default::default(),
"openai".to_string(),
/*plugins_enabled*/ true,
/*remote_plugin_enabled*/ true,
format!("{}/backend-api", first_server.uri()),
test_http_client_factory(),
/*product_sku*/ None,
);
let first = input.remote_plugin_service_config(/*runtime_auth*/ None);
let first_auth = CodexAuth::from_external_chatgpt_tokens(
"header.e30.first",
"first-account",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let first_result = fetch_recommended_plugins(&first, Some(&first_auth))
.await
.unwrap();
input.chatgpt_base_url = format!("{}/backend-api", second_server.uri());
input.product_sku = Some("updated".to_string());
let second = input.remote_plugin_service_config(/*runtime_auth*/ None);
let second_auth = CodexAuth::from_external_chatgpt_tokens(
"header.e30.second",
"second-account",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let second_result = fetch_recommended_plugins(&second, Some(&second_auth))
.await
.unwrap();
assert_eq!(
(
first_result,
Arc::ptr_eq(&first.http_clients, &second.http_clients),
),
(second_result, true)
);
}

View File

@@ -1,13 +1,8 @@
#[path = "plugin_measurement_catalog.rs"]
mod measurement_catalog;
pub(crate) use measurement_catalog::fetch_measurement_reference_bundle;
use crate::app_mcp_routing::apply_app_mcp_routing_policy;
use crate::error_subtype::http_status_sub_error_type;
use crate::http_client_selector::HttpClientSelector;
use crate::loader::plugin_app_declarations_from_value;
use crate::store::PLUGINS_CACHE_DIR;
use crate::store::PluginStore;
use chrono::DateTime;
use chrono::Utc;
use codex_app_server_protocol::JSONRPCErrorError;
@@ -22,11 +17,9 @@ use codex_app_server_protocol::SkillInterface;
use codex_features::RuntimeAuthMode;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_http_client::RequestBuilder;
use codex_http_client::RouteAwareClientPool;
use codex_http_client::RouteAwareRequestError;
use codex_login::CodexAuth;
use codex_login::default_client::default_headers;
use codex_plugin::AppConnectorId;
use codex_plugin::AppDeclaration;
use codex_plugin::PluginCapabilitySummary;
@@ -35,8 +28,6 @@ use codex_plugin::app_connector_ids_from_declarations;
use codex_plugin::prompt_safe_plugin_description;
use codex_runtime_agent_instance::RuntimeAuthSlot;
use codex_utils_absolute_path::AbsolutePathBuf;
use http::HeaderMap;
use http::Method;
use http::StatusCode;
use serde::Deserialize;
use serde::Serialize;
@@ -45,13 +36,11 @@ use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tracing::instrument;
use url::Url;
mod catalog_cache;
mod plugin_capabilities;
@@ -59,10 +48,6 @@ mod remote_installed_plugin_sync;
mod search;
mod share;
#[cfg(test)]
#[path = "remote_tests.rs"]
mod tests;
pub use plugin_capabilities::RemotePluginCapabilities;
pub use remote_installed_plugin_sync::RemoteInstalledPluginBundleSyncError;
pub use remote_installed_plugin_sync::RemoteInstalledPluginBundleSyncOutcome;
@@ -109,7 +94,6 @@ pub const REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_DISPLAY_NAME: &st
"Shared with me (unlisted)";
const OPENAI_CURATED_REMOTE_COLLECTION_KEY: &str = "vertical";
const OAI_PRODUCT_SKU_HEADER: &str = "OAI-Product-Sku";
pub(crate) const CODEX_PRODUCT_SKU: &str = "codex";
const REMOTE_PLUGIN_CATALOG_TIMEOUT: Duration = Duration::from_secs(30);
// Leave room within the 120-second mutation-gate wait even when successful pages keep arriving.
@@ -117,10 +101,6 @@ const REMOTE_INSTALLED_PLUGINS_FETCH_TIMEOUT: Duration = Duration::from_secs(60)
// Allow 20,000 installed plugins without unbounded cursor history.
const MAX_REMOTE_INSTALLED_PLUGIN_PAGES: usize = 100;
const RECOMMENDED_PLUGINS_TIMEOUT: Duration = Duration::from_secs(5);
const REMOTE_PLUGIN_LIST_PAGE_LIMIT: u32 = 200;
const MAX_RECOMMENDED_PLUGINS: usize = 50;
const MAX_RECOMMENDED_PLUGIN_NAME_LEN: usize = 64;
const MAX_RECOMMENDED_PLUGIN_DISPLAY_NAME_LEN: usize = 64;
const MAX_REMOTE_DEFAULT_PROMPT_COUNT: usize = 3;
const MAX_REMOTE_DEFAULT_PROMPT_LEN: usize = 128;
const INVALID_REQUEST_ERROR_CODE: i64 = -32600;
@@ -189,105 +169,6 @@ impl RemotePluginServiceConfig {
}
}
#[cfg(test)]
pub(crate) fn new_with_runtime_auth(
chatgpt_base_url: String,
http_client_factory: HttpClientFactory,
product_sku: Option<String>,
runtime_auth: (RuntimeAuthSlot, RuntimeAuthMode),
) -> Self {
if codex_http_client::classify_openai_api_url(&chatgpt_base_url)
== codex_http_client::OpenAiDestination::Other
{
return Self::new(chatgpt_base_url, http_client_factory, product_sku);
}
Self::new_with_selected_runtime_auth(
chatgpt_base_url,
http_client_factory,
product_sku,
runtime_auth,
)
}
#[cfg(test)]
pub(crate) fn new_with_selected_runtime_auth(
chatgpt_base_url: String,
http_client_factory: HttpClientFactory,
product_sku: Option<String>,
runtime_auth: (RuntimeAuthSlot, RuntimeAuthMode),
) -> Self {
let mut config = Self::new(
chatgpt_base_url,
http_client_factory.with_sensitive_header_protection(),
product_sku,
);
config.runtime_auth = Some(runtime_auth);
config
}
// Keep runtime registration out of callers' async stack frames.
pub(crate) fn authenticated_request<'a>(
&'a self,
method: Method,
url: &'a str,
auth: &'a CodexAuth,
) -> std::pin::Pin<
Box<
dyn std::future::Future<Output = Result<RequestBuilder, codex_api::AuthError>>
+ Send
+ 'a,
>,
> {
Box::pin(async move {
if self.runtime_auth.is_some() {
codex_model_provider::validate_runtime_destination(Some(&self.chatgpt_base_url))
.map_err(|error| codex_api::AuthError::Build(error.to_string()))?;
}
let runtime = self
.runtime_auth
.as_ref()
.map(|(slot, mode)| {
slot.get()
.map(|manager| (Arc::clone(manager), *mode))
.ok_or_else(|| {
codex_api::AuthError::Build(
"runtime authentication has not been initialized".to_string(),
)
})
})
.transpose()?;
let resolved = codex_model_provider::auth_provider_for_request(
auth,
runtime.as_ref(),
&HeaderMap::new(),
)
.await?;
let request = match &resolved.runtime {
Some(runtime) => self
.http_clients
.request_for_account(
method,
url,
runtime.http_client_factory().network_policy(),
)
.ok_or_else(|| {
codex_api::AuthError::Build(
"plugin credentials and transport must share the application network policy"
.to_string(),
)
})?,
None => self.http_clients.request(method, url),
};
let headers = resolved.auth.apply_auth_headers(HeaderMap::new()).await?;
Ok(request.headers(default_headers()).headers(headers))
})
}
pub(crate) fn http_request(&self, method: Method, url: &str) -> RequestBuilder {
self.http_clients
.request(method, url)
.headers(default_headers())
}
}
impl PartialEq for RemotePluginServiceConfig {
@@ -512,6 +393,9 @@ pub fn validate_remote_plugin_id(plugin_id: &str) -> Result<(), JSONRPCErrorErro
#[derive(Debug, thiserror::Error)]
pub enum RemotePluginCatalogError {
#[error("remote plugins are not available in aKode")]
Unavailable,
#[error("chatgpt authentication required for remote plugin catalog")]
AuthRequired,
@@ -613,7 +497,8 @@ impl RemotePluginCatalogError {
Self::UnexpectedStatus { status, .. } => {
Some(http_status_sub_error_type(*status).to_string())
}
Self::AuthRequired
Self::Unavailable
| Self::AuthRequired
| Self::UnsupportedAuthMode
| Self::AuthToken(_)
| Self::Request { .. }
@@ -713,13 +598,6 @@ struct RemotePluginSkillResponse {
interface: Option<RemotePluginSkillInterfaceResponse>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
struct RemotePluginSkillDetailResponse {
plugin_id: String,
name: String,
skill_md_contents: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
struct RemotePluginReleaseInterfaceResponse {
short_description: Option<String>,
@@ -897,32 +775,12 @@ struct RemotePluginListResponse {
pagination: RemotePluginPagination,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
struct RecommendedPluginsResponse {
enabled: bool,
plugins: Vec<RecommendedPluginItem>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
struct RecommendedPluginItem {
id: String,
name: String,
display_name: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
struct RemotePluginInstalledResponse {
plugins: Vec<RemotePluginInstalledItem>,
pagination: RemotePluginPagination,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
struct RemotePluginMutationResponse {
id: String,
enabled: bool,
app_ids_needing_auth: Option<Vec<String>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemotePluginInstallResult {
pub app_ids_needing_auth: Option<Vec<String>>,
@@ -1152,17 +1010,8 @@ pub async fn fetch_recommended_plugins(
config: &RemotePluginServiceConfig,
auth: Option<&CodexAuth>,
) -> Result<RecommendedPluginsMode, RemotePluginCatalogError> {
let auth = ensure_chatgpt_auth(auth)?;
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let mut url = Url::parse(&format!("{base_url}/ps/plugins/suggested/codex"))
.map_err(RemotePluginCatalogError::InvalidBaseUrl)?;
url.query_pairs_mut().append_pair("scope", "GLOBAL");
let url = url.to_string();
let request = authenticated_request(config, Method::GET, &url, auth)
.await?
.timeout(RECOMMENDED_PLUGINS_TIMEOUT);
let response: RecommendedPluginsResponse = send_and_decode(request, &url).await?;
Ok(recommended_plugins_mode(response))
let _ = (config, auth);
Err(RemotePluginCatalogError::Unavailable)
}
#[instrument(level = "trace", skip_all)]
@@ -1205,55 +1054,6 @@ pub(crate) async fn fetch_recommended_plugin_install_metadata(
Ok(Some(app_connector_ids))
}
fn recommended_plugins_mode(response: RecommendedPluginsResponse) -> RecommendedPluginsMode {
if !response.enabled {
return RecommendedPluginsMode::Legacy;
}
let mut plugins = BTreeMap::new();
for plugin in response.plugins {
if !is_valid_remote_plugin_id(&plugin.id)
|| plugin.name.chars().count() > MAX_RECOMMENDED_PLUGIN_NAME_LEN
{
continue;
}
let plugin_id = match PluginId::new(
plugin.name.clone(),
REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(),
) {
Ok(plugin_id) => plugin_id,
Err(err) => {
tracing::warn!(
plugin_name = plugin.name,
error = %err,
"ignoring invalid recommended plugin"
);
continue;
}
};
let display_name = non_empty_string(Some(&plugin.display_name))
.unwrap_or_else(|| plugin.name.clone())
.chars()
.take(MAX_RECOMMENDED_PLUGIN_DISPLAY_NAME_LEN)
.collect();
let config_id = plugin_id.as_key();
plugins
.entry(config_id.clone())
.or_insert(RecommendedPlugin {
config_id,
remote_plugin_id: plugin.id,
display_name,
});
}
RecommendedPluginsMode::Endpoint {
plugins: plugins
.into_values()
.take(MAX_RECOMMENDED_PLUGINS)
.collect(),
}
}
pub(crate) fn has_fresh_cached_remote_plugin_catalog(
codex_home: &Path,
config: &RemotePluginServiceConfig,
@@ -1523,32 +1323,8 @@ pub async fn fetch_remote_plugin_skill_detail(
plugin_id: &str,
skill_name: &str,
) -> Result<RemotePluginSkillDetail, RemotePluginCatalogError> {
let auth = ensure_chatgpt_auth(auth)?;
if RemotePluginScope::from_marketplace_name(marketplace_name).is_none() {
return Err(RemotePluginCatalogError::UnknownMarketplace {
marketplace_name: marketplace_name.to_string(),
});
}
let url = remote_plugin_skill_detail_url(config, plugin_id, skill_name)?;
let request = authenticated_request(config, Method::GET, &url, auth).await?;
let response: RemotePluginSkillDetailResponse = send_and_decode(request, &url).await?;
if response.plugin_id != plugin_id {
return Err(RemotePluginCatalogError::UnexpectedPluginId {
expected: plugin_id.to_string(),
actual: response.plugin_id,
});
}
if response.name != skill_name {
return Err(RemotePluginCatalogError::UnexpectedSkillName {
expected: skill_name.to_string(),
actual: response.name,
});
}
Ok(RemotePluginSkillDetail {
contents: response.skill_md_contents,
})
let _ = (config, auth, marketplace_name, plugin_id, skill_name);
Err(RemotePluginCatalogError::Unavailable)
}
async fn fetch_remote_plugin_detail_with_download_url_option(
@@ -1683,11 +1459,6 @@ fn effective_remote_plugin_apps_and_mcp_servers(
(app_ids, mcp_server_names)
}
#[derive(Serialize)]
struct RemotePluginInstallRequest<'a> {
install_attempt_id: &'a str,
}
pub async fn install_remote_plugin(
config: &RemotePluginServiceConfig,
auth: Option<&CodexAuth>,
@@ -1728,40 +1499,8 @@ async fn install_remote_plugin_inner(
plugin_id: &str,
install_attempt_id: Option<&str>,
) -> Result<RemotePluginInstallResult, RemotePluginCatalogError> {
let auth = ensure_chatgpt_auth(auth)?;
// Remote plugin IDs uniquely identify remote plugins, so the caller-provided
// marketplace name is not validated before sending the install mutation.
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let mut url = Url::parse(&format!("{base_url}/ps/plugins/{plugin_id}/install"))
.map_err(RemotePluginCatalogError::InvalidBaseUrl)?;
url.query_pairs_mut()
.append_pair("includeAppsNeedingAuth", "true");
let url = url.to_string();
let request = authenticated_request(config, Method::POST, &url, auth).await?;
let request = if let Some(install_attempt_id) = install_attempt_id {
request.json(&RemotePluginInstallRequest { install_attempt_id })
} else {
request
};
let response: RemotePluginMutationResponse = send_and_decode(request, &url).await?;
if response.id != plugin_id {
return Err(RemotePluginCatalogError::UnexpectedPluginId {
expected: plugin_id.to_string(),
actual: response.id,
});
}
if !response.enabled {
return Err(RemotePluginCatalogError::UnexpectedEnabledState {
plugin_id: plugin_id.to_string(),
expected_enabled: true,
actual_enabled: response.enabled,
});
}
Ok(RemotePluginInstallResult {
app_ids_needing_auth: response.app_ids_needing_auth,
})
let _ = (config, auth, plugin_id, install_attempt_id);
Err(RemotePluginCatalogError::Unavailable)
}
pub async fn resolve_remote_plugin_uninstall_target(
@@ -1820,90 +1559,8 @@ pub async fn uninstall_remote_plugin(
codex_home: PathBuf,
target: RemotePluginUninstallTarget,
) -> Result<(), RemotePluginCatalogError> {
let auth = ensure_chatgpt_auth(auth)?;
let RemotePluginUninstallTarget {
plugin_id,
remote_plugin_id,
fallback_capability_summary: _,
} = target;
let marketplace_name = plugin_id.marketplace_name.clone();
let plugin_name = plugin_id.plugin_name.clone();
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let url = format!("{base_url}/ps/plugins/{remote_plugin_id}/uninstall");
let request = authenticated_request(config, Method::POST, &url, auth).await?;
let response: RemotePluginMutationResponse = send_and_decode(request, &url).await?;
if response.id != remote_plugin_id {
return Err(RemotePluginCatalogError::UnexpectedPluginId {
expected: remote_plugin_id,
actual: response.id,
});
}
if response.enabled {
return Err(RemotePluginCatalogError::UnexpectedEnabledState {
plugin_id: response.id,
expected_enabled: false,
actual_enabled: response.enabled,
});
}
let legacy_plugin_id = response.id;
tokio::task::spawn_blocking(move || {
remove_remote_plugin_cache(codex_home, marketplace_name, plugin_name, legacy_plugin_id)
})
.await
.map_err(|err| {
RemotePluginCatalogError::CacheRemove(format!(
"failed to join remote plugin cache removal task: {err}"
))
})?
.map_err(RemotePluginCatalogError::CacheRemove)?;
Ok(())
}
fn remove_remote_plugin_cache(
codex_home: PathBuf,
marketplace_name: String,
plugin_name: String,
legacy_plugin_id: String,
) -> Result<(), String> {
let store = PluginStore::try_new(codex_home.clone())
.map_err(|err| format!("failed to resolve remote plugin cache root: {err}"))?;
let plugin_id =
PluginId::new(plugin_name.clone(), marketplace_name.clone()).map_err(|err| {
format!(
"invalid remote plugin cache id for `{plugin_name}` in `{marketplace_name}`: {err}"
)
})?;
let plugin_cache_root = store.plugin_base_root(&plugin_id);
store.uninstall(&plugin_id).map_err(|err| {
format!(
"failed to remove remote plugin cache entry {}: {err}",
plugin_cache_root.display()
)
})?;
let legacy_remote_plugin_cache_root = codex_home
.join(PLUGINS_CACHE_DIR)
.join(marketplace_name)
.join(legacy_plugin_id);
if legacy_remote_plugin_cache_root != plugin_cache_root.as_path()
&& legacy_remote_plugin_cache_root.exists()
{
let result = if legacy_remote_plugin_cache_root.is_dir() {
fs::remove_dir_all(&legacy_remote_plugin_cache_root)
} else {
fs::remove_file(&legacy_remote_plugin_cache_root)
};
result.map_err(|err| {
format!(
"failed to remove remote plugin cache entry {}: {err}",
legacy_remote_plugin_cache_root.display()
)
})?;
}
Ok(())
let _ = (config, auth, codex_home, target);
Err(RemotePluginCatalogError::Unavailable)
}
fn build_remote_plugin_summary(
@@ -2326,21 +1983,8 @@ async fn get_remote_plugin_list_page(
page_token: Option<&str>,
collection: Option<&str>,
) -> Result<RemotePluginListResponse, RemotePluginCatalogError> {
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let mut url = Url::parse(&format!("{base_url}/ps/plugins/list"))
.map_err(RemotePluginCatalogError::InvalidBaseUrl)?;
url.query_pairs_mut()
.append_pair("scope", scope.api_value())
.append_pair("limit", &REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string());
if let Some(collection) = collection {
url.query_pairs_mut().append_pair("collection", collection);
}
if let Some(page_token) = page_token {
url.query_pairs_mut().append_pair("pageToken", page_token);
}
let url = url.to_string();
let request = authenticated_request(config, Method::GET, &url, auth).await?;
send_and_decode(request, &url).await
let _ = (config, auth, scope, page_token, collection);
Err(RemotePluginCatalogError::Unavailable)
}
async fn get_remote_shared_workspace_plugins_page(
@@ -2348,17 +1992,8 @@ async fn get_remote_shared_workspace_plugins_page(
auth: &CodexAuth,
page_token: Option<&str>,
) -> Result<RemotePluginListResponse, RemotePluginCatalogError> {
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let mut url = Url::parse(&format!("{base_url}/ps/plugins/workspace/shared"))
.map_err(RemotePluginCatalogError::InvalidBaseUrl)?;
url.query_pairs_mut()
.append_pair("limit", &REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string());
if let Some(page_token) = page_token {
url.query_pairs_mut().append_pair("pageToken", page_token);
}
let url = url.to_string();
let request = authenticated_request(config, Method::GET, &url, auth).await?;
send_and_decode(request, &url).await
let _ = (config, auth, page_token);
Err(RemotePluginCatalogError::Unavailable)
}
async fn get_remote_plugin_installed_page(
@@ -2369,29 +2004,8 @@ async fn get_remote_plugin_installed_page(
include_download_urls: bool,
display_assets: InstalledPluginDisplayAssets,
) -> Result<RemotePluginInstalledResponse, RemotePluginCatalogError> {
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let mut url = Url::parse(&format!("{base_url}/ps/plugins/installed"))
.map_err(RemotePluginCatalogError::InvalidBaseUrl)?;
if let RemoteInstalledPluginScope::Single(scope) = scope {
url.query_pairs_mut()
.append_pair("scope", scope.api_value());
}
url.query_pairs_mut()
.append_pair("limit", &REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string());
if include_download_urls {
url.query_pairs_mut()
.append_pair("includeDownloadUrls", "true");
}
if display_assets == InstalledPluginDisplayAssets::Skip {
url.query_pairs_mut()
.append_pair("includeDisplayAssets", "false");
}
if let Some(page_token) = page_token {
url.query_pairs_mut().append_pair("pageToken", page_token);
}
let url = url.to_string();
let request = authenticated_request(config, Method::GET, &url, auth).await?;
send_and_decode(request, &url).await
let _ = (config, auth, scope, page_token, include_download_urls, display_assets);
Err(RemotePluginCatalogError::Unavailable)
}
async fn fetch_plugin_detail(
@@ -2417,39 +2031,8 @@ async fn fetch_plugin_detail_with_timeout(
include_download_urls: bool,
timeout: Duration,
) -> Result<RemotePluginDirectoryItem, RemotePluginCatalogError> {
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let mut url = Url::parse(&format!("{base_url}/ps/plugins/{plugin_id}"))
.map_err(RemotePluginCatalogError::InvalidBaseUrl)?;
if include_download_urls {
url.query_pairs_mut()
.append_pair("includeDownloadUrls", "true");
}
let url = url.to_string();
let request = authenticated_request(config, Method::GET, &url, auth)
.await?
.timeout(timeout);
send_and_decode(request, &url).await
}
fn remote_plugin_skill_detail_url(
config: &RemotePluginServiceConfig,
plugin_id: &str,
skill_name: &str,
) -> Result<String, RemotePluginCatalogError> {
let mut url = Url::parse(config.chatgpt_base_url.trim_end_matches('/'))
.map_err(RemotePluginCatalogError::InvalidBaseUrl)?;
{
let mut segments = url
.path_segments_mut()
.map_err(|()| RemotePluginCatalogError::InvalidBaseUrlPath)?;
segments.pop_if_empty();
segments.push("ps");
segments.push("plugins");
segments.push(plugin_id);
segments.push("skills");
segments.push(skill_name);
}
Ok(url.to_string())
let _ = (config, auth, plugin_id, include_download_urls, timeout);
Err(RemotePluginCatalogError::Unavailable)
}
fn ensure_chatgpt_auth(auth: Option<&CodexAuth>) -> Result<&CodexAuth, RemotePluginCatalogError> {
@@ -2461,55 +2044,3 @@ fn ensure_chatgpt_auth(auth: Option<&CodexAuth>) -> Result<&CodexAuth, RemotePlu
}
Ok(auth)
}
async fn authenticated_request(
config: &RemotePluginServiceConfig,
method: Method,
url: &str,
auth: &CodexAuth,
) -> Result<RequestBuilder, RemotePluginCatalogError> {
Ok(config
.authenticated_request(method, url, auth)
.await
.map_err(std::io::Error::other)
.map_err(RemotePluginCatalogError::AuthToken)?
.timeout(REMOTE_PLUGIN_CATALOG_TIMEOUT)
.header(OAI_PRODUCT_SKU_HEADER, &config.product_sku))
}
async fn send_and_decode<T: for<'de> Deserialize<'de>>(
request: RequestBuilder,
url: &str,
) -> Result<T, RemotePluginCatalogError> {
let response = request
.send()
.await
.map_err(|source| RemotePluginCatalogError::Request {
url: url.to_string(),
source,
})?;
let status = response.status();
let body = response
.text()
.await
.map_err(|source| RemotePluginCatalogError::Request {
url: url.to_string(),
source,
})?;
if !status.is_success() {
return Err(RemotePluginCatalogError::UnexpectedStatus {
url: url.to_string(),
status,
body,
});
}
serde_json::from_str(&body).map_err(|source| RemotePluginCatalogError::Decode {
url: url.to_string(),
source,
})
}
#[cfg(test)]
#[path = "remote_runtime_auth_tests.rs"]
mod runtime_auth_tests;

View File

@@ -1,22 +1,11 @@
//! Covers local capability accumulation and removal hints from the shared bundle sync.
use super::*;
use crate::remote::RemoteInstalledPluginBundleSyncOutcome;
use crate::remote::RemotePluginChange;
use crate::remote::RemotePluginServiceConfig;
use crate::remote::sync_remote_installed_plugin_bundles_once;
use crate::test_support::write_file;
use codex_login::CodexAuth;
use codex_utils_plugins::AGENT_PLUGIN_SCHEMA_URI;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
#[tokio::test]
async fn agent_plugin_capabilities_do_not_require_runtime_data_directory() {
@@ -67,92 +56,3 @@ async fn agent_plugin_capabilities_do_not_require_runtime_data_directory() {
assert!(!data_root.as_path().is_dir());
}
}
#[tokio::test]
async fn capabilities_union_cached_versions_and_sync_reports_removal() -> anyhow::Result<()> {
let codex_home = TempDir::new()?;
let store = PluginStore::new(codex_home.path().to_path_buf());
let plugin_id = PluginId::parse("example@openai-curated-remote")?;
let old_root = store.plugin_root(&plugin_id, "1.0.0");
for (path, contents) in [
(".codex-plugin/plugin.json", r#"{"name":"example"}"#),
(
".mcp.json",
r#"{"mcpServers":{"example":{"command":"unused"}}}"#,
),
(
"hooks/hooks.json",
r#"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"echo example"}]}]}}"#,
),
(
"skills/example/SKILL.md",
"---\nname: example\ndescription: Example skill\n---\nExample skill",
),
] {
write_file(old_root.join(path).as_path(), contents);
}
let mut capabilities = RemotePluginCapabilities::default();
capabilities.include_active_bundle(&store, &plugin_id).await;
// Accumulate the old and new declarations without involving bundle transport.
let new_root = store.plugin_root(&plugin_id, "2.0.0");
write_file(
new_root.join(".codex-plugin/plugin.json").as_path(),
r#"{"name":"example"}"#,
);
write_file(
new_root.join(".app.json").as_path(),
r#"{"apps":{"example":{"id":"connector_example"}}}"#,
);
capabilities.include_active_bundle(&store, &plugin_id).await;
assert_eq!(
capabilities,
RemotePluginCapabilities {
has_mcps: true,
has_apps: true,
has_hooks: true,
has_skills: true,
}
);
let server = MockServer::start().await;
let config = RemotePluginServiceConfig::new(
format!("{}/backend-api", server.uri()),
crate::test_support::test_http_client_factory(),
/*product_sku*/ None,
);
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.and(query_param("includeDownloadUrls", "true"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [],
"pagination": {"next_page_token": null},
})))
.expect(1)
.mount(&server)
.await;
// Removal describes only the active version, not the union accumulated above.
assert_eq!(
sync_remote_installed_plugin_bundles_once(
codex_home.path().to_path_buf(),
&config,
Some(&auth),
)
.await?,
RemoteInstalledPluginBundleSyncOutcome {
changed_plugins: vec![RemotePluginChange {
plugin_id: plugin_id.as_key(),
capabilities: RemotePluginCapabilities {
has_apps: true,
..Default::default()
},
}],
..Default::default()
}
);
assert!(!store.plugin_base_root(&plugin_id).as_path().exists());
server.verify().await;
Ok(())
}

View File

@@ -502,305 +502,6 @@ fn is_remote_plugin_cache_mutation_in_flight(
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
use wiremock::matchers::query_param_is_missing;
#[tokio::test]
async fn sync_same_version_backfills_metadata_and_missing_version_requires_materialization() {
let server = MockServer::start().await;
let codex_home = tempfile::tempdir().expect("create codex home");
let cached_manifest = codex_home
.path()
.join(PLUGINS_CACHE_DIR)
.join(REMOTE_GLOBAL_MARKETPLACE_NAME)
.join("linear")
.join("1.2.3")
.join(".codex-plugin")
.join("plugin.json");
std::fs::create_dir_all(cached_manifest.parent().expect("manifest parent"))
.expect("create cached plugin manifest parent");
std::fs::write(&cached_manifest, r#"{"name":"linear","version":"1.2.3"}"#)
.expect("write cached plugin manifest");
let remote_plugin_id = "plugins~Plugin_linear";
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.and(query_param_is_missing("scope"))
.and(query_param("limit", "200"))
.and(query_param("includeDownloadUrls", "true"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [
{
"id": remote_plugin_id,
"name": "linear",
"scope": "GLOBAL",
"installation_policy": "AVAILABLE",
"authentication_policy": "ON_USE",
"status": "ENABLED",
"release": {
"version": "1.2.3",
"display_name": "Linear",
"description": "Track work",
"interface": {},
},
"enabled": true,
},
{
"id": "plugins~Plugin_missing_version",
"name": "missing-version",
"scope": "GLOBAL",
"installation_policy": "AVAILABLE",
"authentication_policy": "ON_USE",
"status": "ENABLED",
"release": {
"display_name": "Missing version",
"description": "Needs materialization",
"interface": {},
},
"enabled": true,
},
],
"pagination": {"next_page_token": null},
})))
.expect(1)
.mount(&server)
.await;
let config = RemotePluginServiceConfig::new(
format!("{}/backend-api", server.uri()),
crate::test_support::test_http_client_factory(),
/*product_sku*/ None,
);
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let outcome = sync_remote_installed_plugin_bundles_once(
codex_home.path().to_path_buf(),
&config,
Some(&auth),
)
.await
.expect("sync current remote plugin bundle");
assert_eq!(
outcome,
RemoteInstalledPluginBundleSyncOutcome {
failed_remote_plugin_ids: vec!["plugins~Plugin_missing_version".to_string()],
failed_materialization_remote_plugin_ids: vec![
"plugins~Plugin_missing_version".to_string()
],
..RemoteInstalledPluginBundleSyncOutcome::default()
}
);
let plugin_id = PluginId::new(
"linear".to_string(),
REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(),
)
.expect("valid plugin id");
let metadata_path = PluginStore::new(codex_home.path().to_path_buf())
.plugin_base_root(&plugin_id)
.join(".codex-remote-plugin-install.json");
assert_eq!(
serde_json::from_str::<serde_json::Value>(
&std::fs::read_to_string(metadata_path.as_path())
.expect("read remote plugin install metadata")
)
.expect("parse remote plugin install metadata"),
json!({
"schema_version": 1,
"remote_plugin_id": remote_plugin_id,
})
);
assert!(
!codex_home
.path()
.join(PLUGINS_CACHE_DIR)
.join(REMOTE_GLOBAL_MARKETPLACE_NAME)
.join("missing-version")
.exists()
);
}
#[tokio::test]
async fn sync_all_scopes_paginates_and_reconciles_each_marketplace() {
let server = MockServer::start().await;
let codex_home = tempfile::tempdir().expect("create codex home");
let cached_plugins = [
(
REMOTE_GLOBAL_MARKETPLACE_NAME,
"global-plugin",
"GLOBAL",
None,
),
(
REMOTE_CREATED_BY_ME_MARKETPLACE_NAME,
"user-plugin",
"USER",
None,
),
(
REMOTE_WORKSPACE_MARKETPLACE_NAME,
"workspace-plugin",
"WORKSPACE",
Some("LISTED"),
),
(
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME,
"shared-plugin",
"WORKSPACE",
Some("PRIVATE"),
),
];
for (marketplace_name, plugin_name, _, _) in cached_plugins {
for cached_plugin_name in [plugin_name, "stale"] {
let manifest = codex_home
.path()
.join(PLUGINS_CACHE_DIR)
.join(marketplace_name)
.join(cached_plugin_name)
.join("1.2.3")
.join(".codex-plugin")
.join("plugin.json");
std::fs::create_dir_all(manifest.parent().expect("manifest parent"))
.expect("create cached plugin manifest parent");
std::fs::write(
&manifest,
format!(r#"{{"name":"{cached_plugin_name}","version":"1.2.3"}}"#),
)
.expect("write cached plugin manifest");
}
}
let installed_plugins = cached_plugins
.iter()
.map(|(_, plugin_name, scope, discoverability)| {
let mut plugin = json!({
"id": format!("plugins~Plugin_{plugin_name}"),
"name": plugin_name,
"scope": scope,
"installation_policy": "AVAILABLE",
"authentication_policy": "ON_USE",
"status": "ENABLED",
"release": {
"version": "1.2.3",
"display_name": plugin_name,
"description": "Installed plugin",
"interface": {},
},
"enabled": true,
});
if let Some(discoverability) = discoverability {
plugin["discoverability"] = json!(discoverability);
}
plugin
})
.collect::<Vec<_>>();
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.and(query_param_is_missing("scope"))
.and(query_param("limit", "200"))
.and(query_param("includeDownloadUrls", "true"))
.and(query_param_is_missing("pageToken"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": &installed_plugins[..2],
"pagination": {"next_page_token": "page-2"},
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.and(query_param_is_missing("scope"))
.and(query_param("limit", "200"))
.and(query_param("includeDownloadUrls", "true"))
.and(query_param("pageToken", "page-2"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": &installed_plugins[2..],
"pagination": {"next_page_token": null},
})))
.expect(1)
.mount(&server)
.await;
let (config, selected_urls) = crate::test_support::recording_remote_plugin_service_config(
format!("{}/backend-api", server.uri()),
);
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let outcome = sync_remote_installed_plugin_bundles_once(
codex_home.path().to_path_buf(),
&config,
Some(&auth),
)
.await
.expect("sync installed plugins across every marketplace");
let mut removed_cache_plugin_ids = cached_plugins
.iter()
.map(|(marketplace_name, _, _, _)| format!("stale@{marketplace_name}"))
.collect::<Vec<_>>();
removed_cache_plugin_ids.sort();
assert_eq!(
outcome,
RemoteInstalledPluginBundleSyncOutcome {
materialized_remote_plugins: Vec::new(),
changed_plugins: removed_cache_plugin_ids
.into_iter()
.map(|plugin_id| RemotePluginChange {
plugin_id,
capabilities: RemotePluginCapabilities::default(),
})
.collect(),
failed_remote_plugin_ids: Vec::new(),
failed_materialization_remote_plugin_ids: Vec::new(),
}
);
assert_eq!(
crate::test_support::recorded_http_client_urls(&selected_urls),
vec![
format!(
"{}/backend-api/ps/plugins/installed?limit=200&includeDownloadUrls=true",
server.uri()
),
format!(
"{}/backend-api/ps/plugins/installed?limit=200&includeDownloadUrls=true&pageToken=page-2",
server.uri()
),
]
);
for (marketplace_name, plugin_name, _, _) in cached_plugins {
let plugin_root = codex_home
.path()
.join(PLUGINS_CACHE_DIR)
.join(marketplace_name)
.join(plugin_name);
assert!(
plugin_root
.join("1.2.3/.codex-plugin/plugin.json")
.is_file()
);
assert_eq!(
serde_json::from_str::<serde_json::Value>(
&std::fs::read_to_string(plugin_root.join(".codex-remote-plugin-install.json"))
.expect("read remote plugin install metadata")
)
.expect("parse remote plugin install metadata"),
json!({
"schema_version": 1,
"remote_plugin_id": format!("plugins~Plugin_{plugin_name}"),
})
);
assert!(
!codex_home
.path()
.join(PLUGINS_CACHE_DIR)
.join(marketplace_name)
.join("stale")
.exists()
);
}
}
#[tokio::test]
async fn stale_remote_plugin_cleanup_skips_cache_mutations_in_progress() {

View File

@@ -1,16 +1,9 @@
use super::RemotePluginCatalogError;
use super::RemotePluginListResponse;
use super::RemotePluginScope;
use super::RemotePluginServiceConfig;
use super::RemotePluginSummary;
use super::authenticated_request;
use super::build_remote_plugin_summary;
use super::ensure_chatgpt_auth;
use super::send_and_decode;
use codex_login::CodexAuth;
use http::Method;
use tracing::instrument;
use url::Url;
/// Search parameters forwarded directly to plugin-service.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -39,53 +32,7 @@ pub async fn search_remote_plugins(
auth: Option<&CodexAuth>,
search: RemotePluginSearchRequest<'_>,
) -> Result<RemotePluginSearchPage, RemotePluginCatalogError> {
let auth = ensure_chatgpt_auth(auth)?;
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let mut url = Url::parse(&format!("{base_url}/ps/plugins/search"))
.map_err(RemotePluginCatalogError::InvalidBaseUrl)?;
// Search terms and page tokens can contain user data. Keep the queryless endpoint for
// diagnostics so neither value is exposed through errors or telemetry.
let url_for_error = url.to_string();
{
let mut query_pairs = url.query_pairs_mut();
query_pairs.append_pair("q", search.query);
if let Some(scope) = search.scope {
query_pairs.append_pair("scope", scope.api_value());
}
query_pairs.append_pair("limit", &search.limit.to_string());
if let Some(page_token) = search.page_token {
query_pairs.append_pair("pageToken", page_token);
}
}
let url = url.to_string();
let request = authenticated_request(config, Method::GET, &url, auth).await?;
let response: RemotePluginListResponse = send_and_decode(request, &url_for_error)
.await
.map_err(|error| match error {
RemotePluginCatalogError::Request { url, source } => {
RemotePluginCatalogError::Request {
url,
source: source.without_url(),
}
}
other => other,
})?;
let plugins = response
.plugins
.iter()
// Search intentionally does not join against `/ps/plugins/installed`, so these
// summaries always report `installed: false`.
.map(|plugin| build_remote_plugin_summary(plugin, /*installed_plugin*/ None))
.collect::<Result<Vec<_>, _>>()?;
Ok(RemotePluginSearchPage {
plugins,
next_page_token: response.pagination.next_page_token,
})
let _ = (config, auth, search);
Err(RemotePluginCatalogError::Unavailable)
}
#[cfg(test)]
#[path = "search_tests.rs"]
mod tests;

View File

@@ -1,490 +0,0 @@
use super::*;
use crate::remote::REMOTE_CREATED_BY_ME_MARKETPLACE_NAME;
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
use crate::remote::REMOTE_WORKSPACE_MARKETPLACE_NAME;
use crate::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME;
use crate::remote::RemotePluginShareDiscoverability;
use crate::test_support::recorded_http_client_urls;
use crate::test_support::recording_remote_plugin_service_config;
use codex_app_server_protocol::PluginAuthPolicy;
use codex_app_server_protocol::PluginAvailability;
use codex_app_server_protocol::PluginDisabledReason;
use codex_app_server_protocol::PluginInstallPolicy;
use codex_app_server_protocol::PluginInstallPolicySource;
use codex_app_server_protocol::PluginInterface;
use http::StatusCode;
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::header_exists;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
use wiremock::matchers::query_param_is_missing;
fn remote_plugin_json(remote_plugin_id: &str, plugin_name: &str, scope: &str) -> serde_json::Value {
let discoverability = (scope == "WORKSPACE").then_some("LISTED");
json!({
"id": remote_plugin_id,
"name": plugin_name,
"scope": scope,
"discoverability": discoverability,
"installation_policy": "AVAILABLE",
"authentication_policy": "ON_USE",
"release": {
"display_name": plugin_name,
"description": format!("{plugin_name} description"),
"interface": {},
},
})
}
#[tokio::test]
async fn search_remote_plugins_forwards_parameters_and_converts_results() {
let server = MockServer::start().await;
let remote_plugin = json!({
"id": "plugins~Plugin_linear",
"name": "linear",
"scope": "GLOBAL",
"installation_policy": "NOT_AVAILABLE",
"installation_policy_source": "WORKSPACE_SETTING",
"must_show_installation_interstitial": true,
"authentication_policy": "ON_INSTALL",
"status": "DISABLED_BY_ADMIN",
"disabled_reason": "plan_not_eligible",
"eligible_plan_types": ["pro"],
"release": {
"version": "1.2.3",
"display_name": "Linear",
"description": "Track issues",
"keywords": ["issues"],
"interface": {
"short_description": "Issue tracking",
"category": "Productivity",
"capabilities": ["Create issues"],
"logo_url": "https://example.com/linear.png",
},
},
});
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/search"))
.and(query_param("q", "linear & docs/+"))
.and(query_param("scope", "GLOBAL"))
.and(query_param("limit", "16"))
.and(query_param("pageToken", "next page/+"))
.and(header("authorization", "Bearer Access Token"))
.and(header("chatgpt-account-id", "account_id"))
.and(header("oai-product-sku", "codex"))
.and(header_exists("user-agent"))
.and(header_exists("originator"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [remote_plugin],
"pagination": {"next_page_token": "later page/+"},
})))
.expect(1)
.mount(&server)
.await;
let (config, selected_urls) =
recording_remote_plugin_service_config(format!("{}/backend-api/", server.uri()));
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let result = search_remote_plugins(
&config,
Some(&auth),
RemotePluginSearchRequest {
query: "linear & docs/+",
scope: Some(RemotePluginScope::Global),
limit: 16,
page_token: Some("next page/+"),
},
)
.await
.expect("plugin search should succeed");
assert_eq!(
result,
RemotePluginSearchPage {
plugins: vec![RemotePluginSummary {
id: format!("linear@{REMOTE_GLOBAL_MARKETPLACE_NAME}"),
remote_plugin_id: "plugins~Plugin_linear".to_string(),
version: Some("1.2.3".to_string()),
local_version: None,
name: "linear".to_string(),
share_context: None,
installed: false,
installed_at: None,
enabled: false,
install_policy: PluginInstallPolicy::NotAvailable,
install_policy_source: Some(PluginInstallPolicySource::WorkspaceSetting),
must_show_installation_interstitial: Some(true),
auth_policy: PluginAuthPolicy::OnInstall,
availability: PluginAvailability::DisabledByAdmin,
disabled_reason: Some(PluginDisabledReason::PlanNotEligible),
eligible_plan_types: Some(vec!["pro".to_string()]),
interface: Some(PluginInterface {
display_name: Some("Linear".to_string()),
short_description: Some("Issue tracking".to_string()),
long_description: None,
developer_name: None,
category: Some("Productivity".to_string()),
capabilities: vec!["Create issues".to_string()],
website_url: None,
privacy_policy_url: None,
terms_of_service_url: None,
default_prompt: None,
brand_color: None,
composer_icon: None,
composer_icon_url: None,
logo: None,
logo_dark: None,
logo_url: Some("https://example.com/linear.png".to_string()),
logo_url_dark: None,
screenshots: Vec::new(),
screenshot_urls: Vec::new(),
}),
keywords: vec!["issues".to_string()],
}],
next_page_token: Some("later page/+".to_string()),
}
);
assert_eq!(
recorded_http_client_urls(&selected_urls),
vec![format!(
"{}/backend-api/ps/plugins/search?q=linear+%26+docs%2F%2B&scope=GLOBAL&limit=16&pageToken=next+page%2F%2B",
server.uri()
)]
);
}
#[tokio::test]
async fn search_remote_plugins_omits_optional_scope_and_page_token() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/search"))
.and(query_param("q", "calendar"))
.and(query_param("limit", "25"))
.and(query_param_is_missing("scope"))
.and(query_param_is_missing("pageToken"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [],
"pagination": {"next_page_token": null},
})))
.expect(2)
.mount(&server)
.await;
let (config, _) =
recording_remote_plugin_service_config(format!("{}/backend-api", server.uri()));
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
for _ in 0..2 {
let result = search_remote_plugins(
&config,
Some(&auth),
RemotePluginSearchRequest {
query: "calendar",
scope: None,
limit: 25,
page_token: None,
},
)
.await
.expect("unscoped plugin search should succeed");
assert_eq!(
result,
RemotePluginSearchPage {
plugins: Vec::new(),
next_page_token: None,
}
);
}
}
#[tokio::test]
async fn search_remote_plugins_forwards_each_supported_scope() {
let server = MockServer::start().await;
let (config, _) =
recording_remote_plugin_service_config(format!("{}/backend-api", server.uri()));
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
for (scope, expected_scope) in [
(RemotePluginScope::Global, "GLOBAL"),
(RemotePluginScope::User, "USER"),
(RemotePluginScope::Workspace, "WORKSPACE"),
] {
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/search"))
.and(query_param("scope", expected_scope))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [],
"pagination": {"next_page_token": null},
})))
.expect(1)
.mount(&server)
.await;
search_remote_plugins(
&config,
Some(&auth),
RemotePluginSearchRequest {
query: "calendar",
scope: Some(scope),
limit: 16,
page_token: None,
},
)
.await
.expect("scoped plugin search should succeed");
}
}
#[tokio::test]
async fn search_remote_plugins_preserves_order_and_canonical_marketplaces() {
let server = MockServer::start().await;
let mut shared_plugin = remote_plugin_json("plugin-shared", "shared", "WORKSPACE");
shared_plugin["discoverability"] = json!("PRIVATE");
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/search"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [
remote_plugin_json("plugin-user", "personal", "USER"),
remote_plugin_json("plugin-global", "global", "GLOBAL"),
remote_plugin_json("plugin-workspace", "workspace", "WORKSPACE"),
shared_plugin,
],
"pagination": {"next_page_token": null},
})))
.expect(1)
.mount(&server)
.await;
let (config, _) =
recording_remote_plugin_service_config(format!("{}/backend-api", server.uri()));
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let result = search_remote_plugins(
&config,
Some(&auth),
RemotePluginSearchRequest {
query: "plugin",
scope: None,
limit: 16,
page_token: None,
},
)
.await
.expect("mixed-scope plugin search should succeed");
let identities = result
.plugins
.into_iter()
.map(|plugin| {
(
plugin.id,
plugin.remote_plugin_id,
plugin.share_context.map(|context| context.discoverability),
)
})
.collect::<Vec<_>>();
assert_eq!(
identities,
vec![
(
format!("personal@{REMOTE_CREATED_BY_ME_MARKETPLACE_NAME}"),
"plugin-user".to_string(),
None,
),
(
format!("global@{REMOTE_GLOBAL_MARKETPLACE_NAME}"),
"plugin-global".to_string(),
None,
),
(
format!("workspace@{REMOTE_WORKSPACE_MARKETPLACE_NAME}"),
"plugin-workspace".to_string(),
Some(RemotePluginShareDiscoverability::Listed),
),
(
format!("shared@{REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME}"),
"plugin-shared".to_string(),
Some(RemotePluginShareDiscoverability::Private),
),
]
);
}
#[tokio::test]
async fn search_remote_plugins_requires_chatgpt_authentication() {
let (config, selected_urls) =
recording_remote_plugin_service_config("https://chatgpt.example/backend-api".to_string());
let result = search_remote_plugins(
&config,
/*auth*/ None,
RemotePluginSearchRequest {
query: "calendar",
scope: None,
limit: 16,
page_token: None,
},
)
.await;
assert!(matches!(
result,
Err(RemotePluginCatalogError::AuthRequired)
));
assert_eq!(
recorded_http_client_urls(&selected_urls),
Vec::<String>::new()
);
}
#[tokio::test]
async fn search_remote_plugins_rejects_api_key_authentication() {
let (config, selected_urls) =
recording_remote_plugin_service_config("https://chatgpt.example/backend-api".to_string());
let auth = CodexAuth::from_api_key("test-api-key");
let result = search_remote_plugins(
&config,
Some(&auth),
RemotePluginSearchRequest {
query: "calendar",
scope: Some(RemotePluginScope::Global),
limit: 16,
page_token: None,
},
)
.await;
assert!(matches!(
result,
Err(RemotePluginCatalogError::UnsupportedAuthMode)
));
assert_eq!(
recorded_http_client_urls(&selected_urls),
Vec::<String>::new()
);
}
#[tokio::test]
async fn search_remote_plugins_redacts_sensitive_parameters_from_transport_errors() {
let listener = std::net::TcpListener::bind("127.0.0.1:0")
.expect("test listener should bind to a local port");
let address = listener
.local_addr()
.expect("test listener should have a local address");
let connection = std::thread::spawn(move || {
let (stream, _) = listener
.accept()
.expect("test listener should accept the plugin search request");
drop(stream);
});
let (config, _) =
recording_remote_plugin_service_config(format!("http://{address}/backend-api"));
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let error = search_remote_plugins(
&config,
Some(&auth),
RemotePluginSearchRequest {
query: "sensitive search term",
scope: Some(RemotePluginScope::Global),
limit: 16,
page_token: Some("sensitive pagination token"),
},
)
.await
.expect_err("closed connection should fail the plugin search request");
connection
.join()
.expect("test listener should close the accepted connection");
let error_message = error.to_string();
assert!(!error_message.contains("sensitive search term"));
assert!(!error_message.contains("sensitive pagination token"));
let RemotePluginCatalogError::Request { url, source } = error else {
panic!("expected transport request error");
};
assert_eq!(
url,
format!("http://{address}/backend-api/ps/plugins/search")
);
assert!(!source.to_string().contains("sensitive"));
}
#[tokio::test]
async fn search_remote_plugins_preserves_upstream_http_errors() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/search"))
.respond_with(ResponseTemplate::new(503).set_body_string("plugin search unavailable"))
.expect(1)
.mount(&server)
.await;
let (config, _) =
recording_remote_plugin_service_config(format!("{}/backend-api", server.uri()));
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let result = search_remote_plugins(
&config,
Some(&auth),
RemotePluginSearchRequest {
query: "sensitive search term",
scope: Some(RemotePluginScope::Global),
limit: 16,
page_token: Some("sensitive pagination token"),
},
)
.await;
let error = result.expect_err("upstream HTTP status should fail");
let error_message = error.to_string();
assert!(!error_message.contains("sensitive search term"));
assert!(!error_message.contains("sensitive pagination token"));
let RemotePluginCatalogError::UnexpectedStatus { url, status, body } = error else {
panic!("expected upstream HTTP status error");
};
assert_eq!(
(url, status, body),
(
format!("{}/backend-api/ps/plugins/search", server.uri()),
StatusCode::SERVICE_UNAVAILABLE,
"plugin search unavailable".to_string(),
)
);
}
#[tokio::test]
async fn search_remote_plugins_preserves_response_decode_errors() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/search"))
.respond_with(ResponseTemplate::new(200).set_body_string("not-json"))
.expect(1)
.mount(&server)
.await;
let (config, _) =
recording_remote_plugin_service_config(format!("{}/backend-api", server.uri()));
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let result = search_remote_plugins(
&config,
Some(&auth),
RemotePluginSearchRequest {
query: "calendar",
scope: None,
limit: 16,
page_token: None,
},
)
.await;
assert!(matches!(
result,
Err(RemotePluginCatalogError::Decode { .. })
));
}

View File

@@ -1,24 +1,15 @@
use super::*;
use crate::plugin_bundle_archive::PluginBundlePackError;
use crate::plugin_bundle_archive::pack_plugin_bundle_tar_gz;
use codex_http_client::RequestBuilder;
use codex_login::CodexAuth;
use codex_utils_absolute_path::AbsolutePathBuf;
use http::Method;
use http::StatusCode;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
use std::io;
use std::path::Path;
use tracing::warn;
use url::Url;
mod checkout;
mod local_paths;
const REMOTE_PLUGIN_SHARE_MAX_ARCHIVE_BYTES: usize = 50 * 1024 * 1024;
pub use checkout::checkout_remote_plugin_share;
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -94,52 +85,6 @@ pub struct RemotePluginShareUpdateTargetsResult {
pub discoverability: RemotePluginShareDiscoverability,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct RemoteWorkspacePluginUploadUrlRequest<'a> {
filename: &'a str,
mime_type: &'a str,
size_bytes: usize,
#[serde(skip_serializing_if = "Option::is_none")]
plugin_id: Option<&'a str>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
struct RemoteWorkspacePluginUploadUrlResponse {
file_id: String,
upload_url: String,
etag: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct RemoteWorkspacePluginCreateRequest {
file_id: String,
etag: String,
#[serde(skip_serializing_if = "Option::is_none")]
discoverability: Option<RemotePluginShareDiscoverability>,
#[serde(skip_serializing_if = "Option::is_none")]
share_targets: Option<Vec<RemotePluginShareTarget>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
struct RemoteWorkspacePluginCreateResponse {
plugin_id: String,
share_url: Option<String>,
#[serde(default)]
can_publish_to_workspace: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct RemotePluginShareUpdateTargetsRequest {
discoverability: RemotePluginShareUpdateDiscoverability,
targets: Vec<RemotePluginShareTarget>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
struct RemotePluginShareUpdateTargetsResponse {
principals: Vec<RemotePluginSharePrincipal>,
discoverability: RemotePluginShareDiscoverability,
}
pub async fn save_remote_plugin_share(
config: &RemotePluginServiceConfig,
auth: Option<&CodexAuth>,
@@ -148,65 +93,8 @@ pub async fn save_remote_plugin_share(
remote_plugin_id: Option<&str>,
access_policy: RemotePluginShareAccessPolicy,
) -> Result<RemotePluginShareSaveResult, RemotePluginCatalogError> {
let auth = ensure_chatgpt_auth(auth)?;
let config = &config.for_current_account();
let plugin_path_for_archive = plugin_path.as_path().to_path_buf();
let (filename, archive_bytes) = tokio::task::spawn_blocking(move || {
let filename = archive_filename(&plugin_path_for_archive)?;
let archive_bytes = archive_plugin_for_upload(&plugin_path_for_archive)?;
Ok::<_, RemotePluginCatalogError>((filename, archive_bytes))
})
.await
.map_err(RemotePluginCatalogError::ArchiveJoin)??;
let upload = create_workspace_plugin_upload(
config,
auth,
&filename,
archive_bytes.len(),
remote_plugin_id,
)
.await?;
let etag = upload
.etag
.ok_or(RemotePluginCatalogError::MissingUploadEtag)?;
put_workspace_plugin_upload(config, &upload.upload_url, archive_bytes).await?;
let share_targets = access_policy.share_targets;
let share_targets =
ensure_unlisted_workspace_target(auth, access_policy.discoverability, share_targets)?;
let response = finalize_workspace_plugin_upload(
config,
auth,
remote_plugin_id,
RemoteWorkspacePluginCreateRequest {
file_id: upload.file_id,
etag,
discoverability: access_policy.discoverability,
share_targets,
},
)
.await?;
if response.plugin_id.is_empty() {
return Err(RemotePluginCatalogError::UnexpectedResponse(
"workspace plugin create response did not include a plugin id".to_string(),
));
}
if let Err(err) = local_paths::record_plugin_share_local_path(
codex_home,
&response.plugin_id,
plugin_path.clone(),
) {
warn!(
remote_plugin_id = %response.plugin_id,
"failed to record plugin share local path mapping: {err}"
);
}
Ok(RemotePluginShareSaveResult {
remote_plugin_id: response.plugin_id,
share_url: response.share_url,
can_publish_to_workspace: response.can_publish_to_workspace,
})
let _ = (config, auth, codex_home, plugin_path, remote_plugin_id, access_policy);
Err(RemotePluginCatalogError::Unavailable)
}
pub async fn list_remote_plugin_shares(
@@ -214,47 +102,8 @@ pub async fn list_remote_plugin_shares(
auth: Option<&CodexAuth>,
codex_home: &Path,
) -> Result<Vec<RemotePluginShareSummary>, RemotePluginCatalogError> {
let auth = ensure_chatgpt_auth(auth)?;
let created_plugins = fetch_created_workspace_plugins(config, auth).await?;
if created_plugins.is_empty() {
return Ok(Vec::new());
}
let installed_by_id =
fetch_installed_plugins_for_scope(config, auth, RemotePluginScope::Workspace)
.await?
.into_iter()
.map(|plugin| (plugin.plugin.id.clone(), plugin))
.collect::<BTreeMap<_, _>>();
let local_plugin_paths =
local_paths::load_plugin_share_local_paths(codex_home).map_err(|err| {
RemotePluginCatalogError::UnexpectedResponse(format!(
"failed to load plugin share local path mapping: {err}"
))
})?;
created_plugins
.into_iter()
.map(|plugin| {
let summary = build_remote_plugin_summary(&plugin, installed_by_id.get(&plugin.id))?;
if summary
.share_context
.as_ref()
.and_then(|context| context.share_principals.as_ref())
.is_none()
{
return Err(RemotePluginCatalogError::UnexpectedResponse(format!(
"created workspace plugin `{}` did not include share_principals",
plugin.id
)));
}
let local_plugin_path = local_plugin_paths.get(&plugin.id).cloned();
Ok(RemotePluginShareSummary {
summary,
local_plugin_path,
})
})
.collect()
let _ = (config, auth, codex_home);
Err(RemotePluginCatalogError::Unavailable)
}
pub fn load_plugin_share_remote_ids_by_local_path(
@@ -283,18 +132,8 @@ pub async fn delete_remote_plugin_share(
codex_home: &Path,
remote_plugin_id: &str,
) -> Result<(), RemotePluginCatalogError> {
let auth = ensure_chatgpt_auth(auth)?;
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let url = format!("{base_url}/public/plugins/workspace/{remote_plugin_id}");
let request = authenticated_request(config, Method::DELETE, &url, auth).await?;
send_and_expect_status(request, &url, &[StatusCode::NO_CONTENT]).await?;
if let Err(err) = local_paths::remove_plugin_share_local_path(codex_home, remote_plugin_id) {
warn!(
remote_plugin_id = %remote_plugin_id,
"failed to remove plugin share local path mapping: {err}"
);
}
Ok(())
let _ = (config, auth, codex_home, remote_plugin_id);
Err(RemotePluginCatalogError::Unavailable)
}
pub async fn update_remote_plugin_share_targets(
@@ -304,233 +143,7 @@ pub async fn update_remote_plugin_share_targets(
targets: Vec<RemotePluginShareTarget>,
discoverability: RemotePluginShareUpdateDiscoverability,
) -> Result<RemotePluginShareUpdateTargetsResult, RemotePluginCatalogError> {
let auth = ensure_chatgpt_auth(auth)?;
let target_discoverability = match discoverability {
RemotePluginShareUpdateDiscoverability::Listed => RemotePluginShareDiscoverability::Listed,
RemotePluginShareUpdateDiscoverability::Unlisted => {
RemotePluginShareDiscoverability::Unlisted
}
RemotePluginShareUpdateDiscoverability::Private => {
RemotePluginShareDiscoverability::Private
}
};
let targets =
ensure_unlisted_workspace_target(auth, Some(target_discoverability), Some(targets))?
.unwrap_or_default();
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let url = format!("{base_url}/ps/plugins/{remote_plugin_id}/shares");
let request = authenticated_request(config, Method::PUT, &url, auth)
.await?
.json(&RemotePluginShareUpdateTargetsRequest {
discoverability,
targets,
});
let response: RemotePluginShareUpdateTargetsResponse = send_and_decode(request, &url).await?;
Ok(RemotePluginShareUpdateTargetsResult {
principals: response.principals,
discoverability: response.discoverability,
})
let _ = (config, auth, remote_plugin_id, targets, discoverability);
Err(RemotePluginCatalogError::Unavailable)
}
fn ensure_unlisted_workspace_target(
auth: &CodexAuth,
discoverability: Option<RemotePluginShareDiscoverability>,
targets: Option<Vec<RemotePluginShareTarget>>,
) -> Result<Option<Vec<RemotePluginShareTarget>>, RemotePluginCatalogError> {
if discoverability != Some(RemotePluginShareDiscoverability::Unlisted) {
return Ok(targets);
}
let account_id = auth.get_account_id().ok_or_else(|| {
RemotePluginCatalogError::UnexpectedResponse(
"workspace plugin share requires an account id".to_string(),
)
})?;
let mut targets = targets.unwrap_or_default();
if !targets.iter().any(|target| {
target.principal_type == RemotePluginSharePrincipalType::Workspace
&& target.principal_id == account_id
}) {
targets.push(RemotePluginShareTarget {
principal_type: RemotePluginSharePrincipalType::Workspace,
principal_id: account_id,
role: RemotePluginShareTargetRole::Reader,
});
}
Ok(Some(targets))
}
async fn fetch_created_workspace_plugins(
config: &RemotePluginServiceConfig,
auth: &CodexAuth,
) -> Result<Vec<RemotePluginDirectoryItem>, RemotePluginCatalogError> {
let mut plugins = Vec::new();
let mut page_token = None;
loop {
let response =
get_created_workspace_plugins_page(config, auth, page_token.as_deref()).await?;
plugins.extend(response.plugins);
let Some(next_page_token) = response.pagination.next_page_token else {
break;
};
page_token = Some(next_page_token);
}
Ok(plugins)
}
async fn get_created_workspace_plugins_page(
config: &RemotePluginServiceConfig,
auth: &CodexAuth,
page_token: Option<&str>,
) -> Result<RemotePluginListResponse, RemotePluginCatalogError> {
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let mut url = Url::parse(&format!("{base_url}/ps/plugins/workspace/created"))
.map_err(RemotePluginCatalogError::InvalidBaseUrl)?;
url.query_pairs_mut()
.append_pair("limit", &REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string());
if let Some(page_token) = page_token {
url.query_pairs_mut().append_pair("pageToken", page_token);
}
let url = url.to_string();
let request = authenticated_request(config, Method::GET, &url, auth).await?;
send_and_decode(request, &url).await
}
async fn create_workspace_plugin_upload(
config: &RemotePluginServiceConfig,
auth: &CodexAuth,
filename: &str,
size_bytes: usize,
remote_plugin_id: Option<&str>,
) -> Result<RemoteWorkspacePluginUploadUrlResponse, RemotePluginCatalogError> {
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let url = format!("{base_url}/public/plugins/workspace/upload-url");
let request = authenticated_request(config, Method::POST, &url, auth)
.await?
.json(&RemoteWorkspacePluginUploadUrlRequest {
filename,
mime_type: "application/gzip",
size_bytes,
plugin_id: remote_plugin_id,
});
send_and_decode(request, &url).await
}
async fn put_workspace_plugin_upload(
config: &RemotePluginServiceConfig,
upload_url: &str,
archive_bytes: Vec<u8>,
) -> Result<(), RemotePluginCatalogError> {
let request = config
.http_request(Method::PUT, upload_url)
.timeout(REMOTE_PLUGIN_CATALOG_TIMEOUT)
.header("x-ms-blob-type", "BlockBlob")
.header("Content-Type", "application/gzip")
.body(archive_bytes);
let response = request
.send()
.await
.map_err(|source| RemotePluginCatalogError::Request {
url: "workspace plugin upload URL".to_string(),
source,
})?;
let status = response.status();
let body = response
.text()
.await
.map_err(|source| RemotePluginCatalogError::Request {
url: "workspace plugin upload URL".to_string(),
source,
})?;
if ![StatusCode::OK, StatusCode::CREATED].contains(&status) {
return Err(RemotePluginCatalogError::UnexpectedStatus {
url: "workspace plugin upload URL".to_string(),
status,
body,
});
}
Ok(())
}
async fn finalize_workspace_plugin_upload(
config: &RemotePluginServiceConfig,
auth: &CodexAuth,
remote_plugin_id: Option<&str>,
body: RemoteWorkspacePluginCreateRequest,
) -> Result<RemoteWorkspacePluginCreateResponse, RemotePluginCatalogError> {
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let url = if let Some(remote_plugin_id) = remote_plugin_id {
format!("{base_url}/public/plugins/workspace/{remote_plugin_id}")
} else {
format!("{base_url}/public/plugins/workspace")
};
let request = authenticated_request(config, Method::POST, &url, auth)
.await?
.json(&body);
send_and_decode(request, &url).await
}
fn archive_filename(plugin_path: &Path) -> Result<String, RemotePluginCatalogError> {
let plugin_name = plugin_path
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| RemotePluginCatalogError::InvalidPluginPath {
path: plugin_path.to_path_buf(),
reason: "plugin path must end in a valid UTF-8 directory name".to_string(),
})?;
Ok(format!("{plugin_name}.tar.gz"))
}
fn archive_plugin_for_upload(plugin_path: &Path) -> Result<Vec<u8>, RemotePluginCatalogError> {
archive_plugin_for_upload_with_limit(plugin_path, REMOTE_PLUGIN_SHARE_MAX_ARCHIVE_BYTES)
}
fn archive_plugin_for_upload_with_limit(
plugin_path: &Path,
max_bytes: usize,
) -> Result<Vec<u8>, RemotePluginCatalogError> {
pack_plugin_bundle_tar_gz(plugin_path, max_bytes).map_err(|err| match err {
PluginBundlePackError::InvalidPluginPath { path, reason } => {
RemotePluginCatalogError::InvalidPluginPath { path, reason }
}
PluginBundlePackError::ArchiveTooLarge { bytes, max_bytes } => {
RemotePluginCatalogError::ArchiveTooLarge { bytes, max_bytes }
}
PluginBundlePackError::Io { source } => RemotePluginCatalogError::Archive {
path: plugin_path.to_path_buf(),
source,
},
})
}
async fn send_and_expect_status(
request: RequestBuilder,
url_for_error: &str,
expected_statuses: &[StatusCode],
) -> Result<(), RemotePluginCatalogError> {
let response = request
.send()
.await
.map_err(|source| RemotePluginCatalogError::Request {
url: url_for_error.to_string(),
source,
})?;
let status = response.status();
let body = response
.text()
.await
.map_err(|source| RemotePluginCatalogError::Request {
url: url_for_error.to_string(),
source,
})?;
if !expected_statuses.contains(&status) {
return Err(RemotePluginCatalogError::UnexpectedStatus {
url: url_for_error.to_string(),
status,
body,
});
}
Ok(())
}
#[cfg(test)]
mod tests;

View File

@@ -35,16 +35,6 @@ pub(crate) fn record_plugin_share_local_path(
write_plugin_share_local_paths(codex_home, mapping)
}
pub(crate) fn remove_plugin_share_local_path(
codex_home: &Path,
remote_plugin_id: &str,
) -> io::Result<()> {
let _guard = lock_plugin_share_local_paths()?;
let mut mapping = read_plugin_share_local_paths_for_update(codex_home)?;
mapping.remove(remote_plugin_id);
write_plugin_share_local_paths(codex_home, mapping)
}
fn lock_plugin_share_local_paths() -> io::Result<std::sync::MutexGuard<'static, ()>> {
PLUGIN_SHARE_LOCAL_PATHS_LOCK
.lock()

View File

@@ -1,824 +0,0 @@
use super::*;
use crate::test_support::recorded_http_client_urls;
use crate::test_support::recording_remote_plugin_service_config;
use codex_app_server_protocol::PluginAuthPolicy;
use codex_app_server_protocol::PluginInstallPolicy;
use codex_app_server_protocol::PluginInterface;
use codex_login::CodexAuth;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::BTreeMap;
use std::fs;
use std::io::Read;
use std::path::Path;
use std::path::PathBuf;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_json;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
use wiremock::matchers::query_param_is_missing;
fn test_config(server: &MockServer) -> RemotePluginServiceConfig {
RemotePluginServiceConfig::new(
format!("{}/backend-api", server.uri()),
crate::test_support::test_http_client_factory(),
/*product_sku*/ None,
)
}
fn test_auth() -> CodexAuth {
CodexAuth::create_dummy_chatgpt_auth_for_testing()
}
fn write_file(path: &Path, contents: &str) {
fs::create_dir_all(path.parent().expect("file should have a parent")).unwrap();
fs::write(path, contents).unwrap();
}
fn write_test_plugin(root: &Path, plugin_name: &str) -> PathBuf {
let plugin_path = root.join(plugin_name);
write_file(
&plugin_path.join(".codex-plugin/plugin.json"),
&format!(r#"{{"name":"{plugin_name}"}}"#),
);
write_file(
&plugin_path.join("skills/example/SKILL.md"),
"# Example\n\nA test skill.\n",
);
plugin_path
}
fn write_plugin_share_local_path_mapping(
codex_home: &Path,
remote_plugin_id: &str,
plugin_path: &AbsolutePathBuf,
) {
write_file(
&codex_home.join(".tmp/plugin-share-local-paths-v1.json"),
&format!(
"{}\n",
serde_json::to_string_pretty(&json!({
"localPluginPathsByRemotePluginId": {
remote_plugin_id: plugin_path,
},
}))
.unwrap()
),
);
}
fn archive_file_entries(archive_bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
let decoder = flate2::read::GzDecoder::new(archive_bytes);
let mut archive = tar::Archive::new(decoder);
archive
.entries()
.unwrap()
.filter_map(|entry| {
let mut entry = entry.unwrap();
if !entry.header().entry_type().is_file() {
return None;
}
let path = entry.path().unwrap().to_string_lossy().into_owned();
let mut contents = Vec::new();
entry.read_to_end(&mut contents).unwrap();
Some((path, contents))
})
.collect()
}
fn remote_plugin_json(plugin_id: &str) -> serde_json::Value {
json!({
"id": plugin_id,
"name": "demo-plugin",
"scope": "WORKSPACE",
"discoverability": "PRIVATE",
"installation_policy": "AVAILABLE",
"authentication_policy": "ON_USE",
"release": {
"version": "0.1.0",
"display_name": "Demo Plugin",
"description": "Demo plugin description",
"interface": {
"short_description": "A demo plugin",
"capabilities": ["Read", "Write"]
},
"skills": []
}
})
}
fn remote_plugin_json_with_share_url_and_principals(
plugin_id: &str,
share_url: Option<&str>,
share_principals: serde_json::Value,
) -> serde_json::Value {
let mut plugin = remote_plugin_json(plugin_id);
let serde_json::Value::Object(fields) = &mut plugin else {
unreachable!("plugin json should be an object");
};
fields.insert("discoverability".to_string(), json!("PRIVATE"));
fields.insert("share_url".to_string(), json!(share_url));
fields.insert("share_principals".to_string(), share_principals);
plugin
}
fn installed_remote_plugin_json(plugin_id: &str) -> serde_json::Value {
let mut plugin = remote_plugin_json(plugin_id);
let serde_json::Value::Object(fields) = &mut plugin else {
unreachable!("plugin json should be an object");
};
fields.insert("enabled".to_string(), json!(true));
fields.insert("disabled_skill_names".to_string(), json!([]));
plugin
}
fn empty_pagination_json() -> serde_json::Value {
json!({
"next_page_token": null
})
}
fn expected_plugin_interface() -> PluginInterface {
PluginInterface {
display_name: Some("Demo Plugin".to_string()),
short_description: Some("A demo plugin".to_string()),
long_description: None,
developer_name: None,
category: None,
capabilities: vec!["Read".to_string(), "Write".to_string()],
website_url: None,
privacy_policy_url: None,
terms_of_service_url: None,
default_prompt: None,
brand_color: None,
composer_icon: None,
composer_icon_url: None,
logo: None,
logo_dark: None,
logo_url: None,
logo_url_dark: None,
screenshots: Vec::new(),
screenshot_urls: Vec::new(),
}
}
#[tokio::test]
async fn save_remote_plugin_share_creates_workspace_plugin() {
let codex_home = TempDir::new().unwrap();
let temp_dir = TempDir::new().unwrap();
let plugin_path =
AbsolutePathBuf::try_from(write_test_plugin(temp_dir.path(), "demo-plugin")).unwrap();
let archive_size = archive_plugin_for_upload(plugin_path.as_path())
.unwrap()
.len();
let server = MockServer::start().await;
let (config, selected_urls) =
recording_remote_plugin_service_config(format!("{}/backend-api", server.uri()));
let auth = test_auth();
Mock::given(method("POST"))
.and(path("/backend-api/public/plugins/workspace/upload-url"))
.and(header("authorization", "Bearer Access Token"))
.and(header("chatgpt-account-id", "account_id"))
.and(body_json(json!({
"filename": "demo-plugin.tar.gz",
"mime_type": "application/gzip",
"size_bytes": archive_size,
})))
.respond_with(ResponseTemplate::new(201).set_body_json(json!({
"file_id": "file_123",
"upload_url": format!("{}/upload/file_123", server.uri()),
"etag": "\"upload_etag_123\"",
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("PUT"))
.and(path("/upload/file_123"))
.and(header("x-ms-blob-type", "BlockBlob"))
.and(header("content-type", "application/gzip"))
.respond_with(ResponseTemplate::new(201).insert_header("etag", "\"blob_etag_123\""))
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/backend-api/public/plugins/workspace"))
.and(header("authorization", "Bearer Access Token"))
.and(header("chatgpt-account-id", "account_id"))
.and(body_json(json!({
"file_id": "file_123",
"etag": "\"upload_etag_123\"",
"discoverability": "UNLISTED",
"share_targets": [
{
"principal_type": "user",
"principal_id": "user-1",
"role": "reader",
},
{
"principal_type": "workspace",
"principal_id": "account_id",
"role": "reader",
},
],
})))
.respond_with(ResponseTemplate::new(201).set_body_json(json!({
"plugin_id": "plugins_123",
"share_url": "https://chatgpt.example/plugins/share/share-key-1",
"can_publish_to_workspace": true,
})))
.expect(1)
.mount(&server)
.await;
let result = save_remote_plugin_share(
&config,
Some(&auth),
codex_home.path(),
&plugin_path,
/*remote_plugin_id*/ None,
RemotePluginShareAccessPolicy {
discoverability: Some(RemotePluginShareDiscoverability::Unlisted),
share_targets: Some(vec![RemotePluginShareTarget {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-1".to_string(),
role: RemotePluginShareTargetRole::Reader,
}]),
},
)
.await
.unwrap();
assert_eq!(
result,
RemotePluginShareSaveResult {
remote_plugin_id: "plugins_123".to_string(),
share_url: Some("https://chatgpt.example/plugins/share/share-key-1".to_string()),
can_publish_to_workspace: Some(true),
}
);
assert_eq!(
local_paths::load_plugin_share_local_paths(codex_home.path()).unwrap(),
BTreeMap::from([("plugins_123".to_string(), plugin_path)])
);
assert_eq!(
recorded_http_client_urls(&selected_urls),
vec![
format!(
"{}/backend-api/public/plugins/workspace/upload-url",
server.uri()
),
format!("{}/upload/file_123", server.uri()),
format!("{}/backend-api/public/plugins/workspace", server.uri()),
]
);
let requests = server.received_requests().await.unwrap_or_default();
let upload_request = requests
.iter()
.find(|request| request.method == "PUT" && request.url.path() == "/upload/file_123")
.unwrap();
let archive_files = archive_file_entries(&upload_request.body);
assert_eq!(
archive_files
.get(".codex-plugin/plugin.json")
.map(Vec::as_slice),
Some(br#"{"name":"demo-plugin"}"#.as_slice())
);
assert_eq!(
archive_files
.get("skills/example/SKILL.md")
.map(Vec::as_slice),
Some(b"# Example\n\nA test skill.\n".as_slice())
);
}
#[test]
fn archive_plugin_for_upload_rejects_archives_over_limit() {
let temp_dir = TempDir::new().unwrap();
let plugin_path = write_test_plugin(temp_dir.path(), "demo-plugin");
write_file(
&plugin_path.join("large.txt"),
&"0123456789abcdef".repeat(1024),
);
let err = archive_plugin_for_upload_with_limit(&plugin_path, /*max_bytes*/ 16)
.expect_err("oversized plugin archive should fail");
assert!(matches!(
err,
RemotePluginCatalogError::ArchiveTooLarge { .. }
));
}
#[test]
fn archive_plugin_for_upload_places_manifest_at_archive_root() {
let temp_dir = TempDir::new().unwrap();
let plugin_path = write_test_plugin(temp_dir.path(), "demo-plugin");
let archive_bytes = archive_plugin_for_upload(&plugin_path).unwrap();
let archive_files = archive_file_entries(&archive_bytes);
assert_eq!(
archive_files.keys().cloned().collect::<Vec<_>>(),
vec![
".codex-plugin/plugin.json".to_string(),
"skills/example/SKILL.md".to_string()
]
);
assert_eq!(
archive_files
.get(".codex-plugin/plugin.json")
.map(Vec::as_slice),
Some(br#"{"name":"demo-plugin"}"#.as_slice())
);
assert_eq!(
archive_files
.get("skills/example/SKILL.md")
.map(Vec::as_slice),
Some(b"# Example\n\nA test skill.\n".as_slice())
);
}
#[test]
fn archive_plugin_for_upload_round_trips_through_plugin_bundle_archive_with_long_paths() {
let temp_dir = TempDir::new().unwrap();
let plugin_path = write_test_plugin(temp_dir.path(), "demo-plugin");
let long_skill_path = Path::new("skills")
.join(["segment"; 40].join("/"))
.join("SKILL.md");
write_file(&plugin_path.join(&long_skill_path), "# Long path skill\n");
let archive_bytes = archive_plugin_for_upload(&plugin_path).unwrap();
let destination = TempDir::new().unwrap();
crate::plugin_bundle_archive::unpack_plugin_bundle_tar_gz(
&archive_bytes,
destination.path(),
/*max_total_bytes*/ 1024 * 1024,
)
.expect("extract shared plugin archive");
assert_eq!(
fs::read_to_string(destination.path().join(".codex-plugin/plugin.json")).unwrap(),
r#"{"name":"demo-plugin"}"#
);
assert_eq!(
fs::read_to_string(destination.path().join(long_skill_path)).unwrap(),
"# Long path skill\n"
);
}
#[tokio::test]
async fn save_remote_plugin_share_updates_existing_workspace_plugin() {
let codex_home = TempDir::new().unwrap();
let temp_dir = TempDir::new().unwrap();
let plugin_path =
AbsolutePathBuf::try_from(write_test_plugin(temp_dir.path(), "demo-plugin")).unwrap();
let archive_size = archive_plugin_for_upload(plugin_path.as_path())
.unwrap()
.len();
let server = MockServer::start().await;
let config = test_config(&server);
let auth = test_auth();
Mock::given(method("POST"))
.and(path("/backend-api/public/plugins/workspace/upload-url"))
.and(body_json(json!({
"filename": "demo-plugin.tar.gz",
"mime_type": "application/gzip",
"size_bytes": archive_size,
"plugin_id": "plugins_123",
})))
.respond_with(ResponseTemplate::new(201).set_body_json(json!({
"file_id": "file_456",
"upload_url": format!("{}/upload/file_456", server.uri()),
"etag": "\"upload_etag_456\"",
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("PUT"))
.and(path("/upload/file_456"))
.respond_with(ResponseTemplate::new(201).insert_header("etag", "\"blob_etag_456\""))
.expect(1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/backend-api/public/plugins/workspace/plugins_123"))
.and(body_json(json!({
"file_id": "file_456",
"etag": "\"upload_etag_456\"",
})))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugin_id": "plugins_123",
})))
.expect(1)
.mount(&server)
.await;
let result = save_remote_plugin_share(
&config,
Some(&auth),
codex_home.path(),
&plugin_path,
Some("plugins_123"),
RemotePluginShareAccessPolicy::default(),
)
.await
.unwrap();
assert_eq!(
result,
RemotePluginShareSaveResult {
remote_plugin_id: "plugins_123".to_string(),
share_url: None,
can_publish_to_workspace: None,
}
);
}
#[tokio::test]
async fn update_remote_plugin_share_targets_updates_targets() {
let server = MockServer::start().await;
let config = test_config(&server);
let auth = test_auth();
Mock::given(method("PUT"))
.and(path("/backend-api/ps/plugins/plugins_123/shares"))
.and(header("authorization", "Bearer Access Token"))
.and(header("chatgpt-account-id", "account_id"))
.and(body_json(json!({
"discoverability": "UNLISTED",
"targets": [
{
"principal_type": "user",
"principal_id": "user-1",
"role": "editor",
},
{
"principal_type": "group",
"principal_id": "group-1",
"role": "reader",
},
{
"principal_type": "workspace",
"principal_id": "account_id",
"role": "reader",
},
],
})))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"principals": [
{
"principal_type": "user",
"principal_id": "user-1",
"role": "editor",
"name": "Gavin",
},
{
"principal_type": "group",
"principal_id": "group-1",
"role": "reader",
"name": "Engineering",
},
],
"discoverability": "UNLISTED",
})))
.expect(1)
.mount(&server)
.await;
let result = update_remote_plugin_share_targets(
&config,
Some(&auth),
"plugins_123",
vec![
RemotePluginShareTarget {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-1".to_string(),
role: RemotePluginShareTargetRole::Editor,
},
RemotePluginShareTarget {
principal_type: RemotePluginSharePrincipalType::Group,
principal_id: "group-1".to_string(),
role: RemotePluginShareTargetRole::Reader,
},
],
RemotePluginShareUpdateDiscoverability::Unlisted,
)
.await
.unwrap();
assert_eq!(
result,
RemotePluginShareUpdateTargetsResult {
principals: vec![
RemotePluginSharePrincipal {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-1".to_string(),
role: RemotePluginSharePrincipalRole::Editor,
name: "Gavin".to_string(),
},
RemotePluginSharePrincipal {
principal_type: RemotePluginSharePrincipalType::Group,
principal_id: "group-1".to_string(),
role: RemotePluginSharePrincipalRole::Reader,
name: "Engineering".to_string(),
},
],
discoverability: RemotePluginShareDiscoverability::Unlisted,
}
);
}
#[tokio::test]
async fn list_remote_plugin_shares_fetches_created_workspace_plugins() {
let codex_home = TempDir::new().unwrap();
let local_plugin_path =
AbsolutePathBuf::try_from(codex_home.path().join("local-plugin")).unwrap();
write_plugin_share_local_path_mapping(codex_home.path(), "plugins_123", &local_plugin_path);
let server = MockServer::start().await;
let config = test_config(&server);
let auth = test_auth();
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/workspace/created"))
.and(header("authorization", "Bearer Access Token"))
.and(header("chatgpt-account-id", "account_id"))
.and(query_param(
"limit",
REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string(),
))
.and(query_param_is_missing("pageToken"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [remote_plugin_json_with_share_url_and_principals(
"plugins_123",
Some("https://chatgpt.example/plugins/share/share-key-1"),
json!([
{
"principal_type": "user",
"principal_id": "user-owner",
"role": "owner",
"name": "Owner",
},
{
"principal_type": "user",
"principal_id": "user-reader",
"role": "reader",
"name": "Reader",
},
]),
)],
"pagination": {
"next_page_token": "page-2"
},
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/workspace/created"))
.and(header("authorization", "Bearer Access Token"))
.and(header("chatgpt-account-id", "account_id"))
.and(query_param(
"limit",
REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string(),
))
.and(query_param("pageToken", "page-2"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [remote_plugin_json_with_share_url_and_principals(
"plugins_456",
/*share_url*/ None,
json!([
{
"principal_type": "user",
"principal_id": "user-owner",
"role": "owner",
"name": "Owner",
},
{
"principal_type": "user",
"principal_id": "user-editor",
"role": "editor",
"name": "Editor",
},
]),
)],
"pagination": empty_pagination_json(),
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.and(query_param("scope", "WORKSPACE"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [installed_remote_plugin_json("plugins_456")],
"pagination": empty_pagination_json(),
})))
.expect(1)
.mount(&server)
.await;
let result = list_remote_plugin_shares(&config, Some(&auth), codex_home.path())
.await
.unwrap();
assert_eq!(
result,
vec![
RemotePluginShareSummary {
summary: RemotePluginSummary {
id: "demo-plugin@workspace-shared-with-me".to_string(),
remote_plugin_id: "plugins_123".to_string(),
version: Some("0.1.0".to_string()),
local_version: None,
name: "demo-plugin".to_string(),
share_context: Some(RemotePluginShareContext {
remote_plugin_id: "plugins_123".to_string(),
remote_version: Some("0.1.0".to_string()),
discoverability: RemotePluginShareDiscoverability::Private,
share_url: Some(
"https://chatgpt.example/plugins/share/share-key-1".to_string(),
),
creator_account_user_id: None,
creator_name: None,
share_principals: Some(vec![
RemotePluginSharePrincipal {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-owner".to_string(),
role: RemotePluginSharePrincipalRole::Owner,
name: "Owner".to_string(),
},
RemotePluginSharePrincipal {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-reader".to_string(),
role: RemotePluginSharePrincipalRole::Reader,
name: "Reader".to_string(),
},
]),
can_publish_to_workspace: None,
}),
installed: false,
installed_at: None,
enabled: false,
install_policy: PluginInstallPolicy::Available,
install_policy_source: None,
must_show_installation_interstitial: None,
auth_policy: PluginAuthPolicy::OnUse,
availability: PluginAvailability::Available,
disabled_reason: None,
eligible_plan_types: None,
interface: Some(expected_plugin_interface()),
keywords: Vec::new(),
},
local_plugin_path: Some(local_plugin_path),
},
RemotePluginShareSummary {
summary: RemotePluginSummary {
id: "demo-plugin@workspace-shared-with-me".to_string(),
remote_plugin_id: "plugins_456".to_string(),
version: Some("0.1.0".to_string()),
local_version: Some("0.1.0".to_string()),
name: "demo-plugin".to_string(),
share_context: Some(RemotePluginShareContext {
remote_plugin_id: "plugins_456".to_string(),
remote_version: Some("0.1.0".to_string()),
discoverability: RemotePluginShareDiscoverability::Private,
share_url: None,
creator_account_user_id: None,
creator_name: None,
share_principals: Some(vec![
RemotePluginSharePrincipal {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-owner".to_string(),
role: RemotePluginSharePrincipalRole::Owner,
name: "Owner".to_string(),
},
RemotePluginSharePrincipal {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-editor".to_string(),
role: RemotePluginSharePrincipalRole::Editor,
name: "Editor".to_string(),
},
]),
can_publish_to_workspace: None,
}),
installed: true,
installed_at: None,
enabled: true,
install_policy: PluginInstallPolicy::Available,
install_policy_source: None,
must_show_installation_interstitial: None,
auth_policy: PluginAuthPolicy::OnUse,
availability: PluginAvailability::Available,
disabled_reason: None,
eligible_plan_types: None,
interface: Some(expected_plugin_interface()),
keywords: Vec::new(),
},
local_plugin_path: None,
}
]
);
}
#[tokio::test]
async fn delete_remote_plugin_share_deletes_workspace_plugin() {
let codex_home = TempDir::new().unwrap();
let local_plugin_path =
AbsolutePathBuf::try_from(codex_home.path().join("local-plugin")).unwrap();
write_plugin_share_local_path_mapping(codex_home.path(), "plugins_123", &local_plugin_path);
let server = MockServer::start().await;
let config = test_config(&server);
let auth = test_auth();
Mock::given(method("DELETE"))
.and(path("/backend-api/public/plugins/workspace/plugins_123"))
.and(header("authorization", "Bearer Access Token"))
.and(header("chatgpt-account-id", "account_id"))
.respond_with(ResponseTemplate::new(204))
.expect(1)
.mount(&server)
.await;
delete_remote_plugin_share(&config, Some(&auth), codex_home.path(), "plugins_123")
.await
.unwrap();
assert_eq!(
local_paths::load_plugin_share_local_paths(codex_home.path()).unwrap(),
BTreeMap::new()
);
}
#[tokio::test]
async fn revoked_success_body_is_a_request_error() {
for method in [Method::PUT, Method::POST] {
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/upload", listener.local_addr().unwrap());
let controller = codex_http_client::NetworkPolicyController::default();
let policy = controller.policy();
controller.publish(
policy.revision(),
codex_http_client::DestinationPolicy::Unrestricted,
);
let config = RemotePluginServiceConfig::new(
url.clone(),
crate::test_support::test_http_client_factory().with_network_policy(policy),
/*product_sku*/ None,
);
let server = async {
let (mut socket, _) = listener.accept().await.unwrap();
let mut headers = Vec::new();
while !headers.ends_with(b"\r\n\r\n") {
headers.push(socket.read_u8().await.unwrap());
}
socket
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\na")
.await
.unwrap();
// Let the client consume the successful headers and wait for the remaining body.
tokio::time::sleep(std::time::Duration::from_millis(/*millis*/ 50)).await;
controller.publish(
controller.policy().revision(),
codex_http_client::DestinationPolicy::Restricted {
allowed_hosts: Default::default(),
},
);
};
let operation = async {
if method == Method::PUT {
put_workspace_plugin_upload(&config, &url, Vec::new()).await
} else {
send_and_expect_status(config.http_request(method, &url), &url, &[StatusCode::OK])
.await
}
};
let (result, ()) =
tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 5), async {
tokio::join!(operation, server)
})
.await
.unwrap();
assert!(
matches!(
result,
Err(RemotePluginCatalogError::Request {
source: codex_http_client::RouteAwareRequestError::Policy(
codex_http_client::NetworkPolicyDenied::Revoked
),
..
})
),
"{result:?}"
);
}
}

View File

@@ -8,7 +8,6 @@ use crate::store::PluginStore;
use crate::store::PluginStoreError;
use crate::store::error_context_sub_error_type;
use crate::store::validate_plugin_version_segment;
use codex_http_client::HttpResponse;
use codex_http_client::RouteAwareRequestError;
use codex_plugin::PluginId;
use codex_plugin::PluginIdError;
@@ -17,20 +16,16 @@ use codex_utils_plugins::AGENT_PLUGIN_MANIFEST_RELATIVE_PATH;
use codex_utils_plugins::AgentPluginSchemaStatus;
use codex_utils_plugins::agent_plugin_schema_status;
use codex_utils_plugins::find_plugin_manifest_path;
use http::Method;
use http::StatusCode;
use serde_json::Value as JsonValue;
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use url::Host;
use url::Url;
const REMOTE_PLUGIN_BUNDLE_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(60);
const REMOTE_PLUGIN_BUNDLE_MAX_DOWNLOAD_BYTES: u64 = 100 * 1024 * 1024;
const REMOTE_PLUGIN_BUNDLE_ERROR_BODY_MAX_BYTES: u64 = 8 * 1024;
const REMOTE_PLUGIN_BUNDLE_MAX_EXTRACTED_BYTES: u64 = 512 * 1024 * 1024;
const REMOTE_PLUGIN_INSTALL_STAGING_DIR: &str = "plugins/.remote-plugin-install-staging";
#[cfg(debug_assertions)]
@@ -59,6 +54,9 @@ impl std::fmt::Debug for ValidatedRemotePluginBundle {
#[derive(Debug, thiserror::Error)]
pub enum RemotePluginBundleInstallError {
#[error("remote plugin bundles are not available in aKode")]
Unavailable,
#[error("backend did not return a release version for remote plugin `{remote_plugin_id}`")]
MissingReleaseVersion { remote_plugin_id: String },
@@ -159,7 +157,8 @@ impl RemotePluginBundleInstallError {
Self::DownloadStatus { status, .. } => {
Some(http_status_sub_error_type(*status).to_string())
}
Self::MissingReleaseVersion { .. }
Self::Unavailable
| Self::MissingReleaseVersion { .. }
| Self::InvalidReleaseVersion { .. }
| Self::MissingBundleDownloadUrl { .. }
| Self::InvalidBundleDownloadUrl { .. }
@@ -316,111 +315,8 @@ async fn download_remote_plugin_bundle_with_limit(
bundle_download_url: &str,
max_bytes: u64,
) -> Result<Vec<u8>, RemotePluginBundleInstallError> {
let response = config
.http_request(Method::GET, bundle_download_url)
.timeout(REMOTE_PLUGIN_BUNDLE_DOWNLOAD_TIMEOUT)
.send()
.await
.map_err(|source| RemotePluginBundleInstallError::DownloadRequest {
host: Url::parse(bundle_download_url)
.ok()
.and_then(|url| url.host_str().map(str::to_owned))
.unwrap_or_else(|| "unknown-host".to_string()),
source: source.without_url(),
})?;
let final_url = response.url().clone();
// Keep only the host in URL error fields.
let host = final_url.host_str().unwrap_or("unknown-host").to_string();
// The shared client has already followed redirects here. Reject an unsupported final scheme
// before caching a backend-issued bundle.
if !is_allowed_bundle_download_url(&final_url, allow_test_loopback_http_bundle_downloads()) {
return Err(
RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl {
host,
scheme: final_url.scheme().to_string(),
},
);
}
let status = response.status();
if !status.is_success() {
let mut response = response;
let mut body = Vec::new();
let mut body_truncated = false;
let mut body_read_error = None;
loop {
let chunk = match response.chunk().await {
Ok(Some(chunk)) => chunk,
Ok(None) => break,
Err(source) => {
body_read_error = Some(source.without_url());
break;
}
};
let remaining = REMOTE_PLUGIN_BUNDLE_ERROR_BODY_MAX_BYTES as usize - body.len();
if chunk.len() > remaining {
body.extend_from_slice(&chunk[..remaining]);
body_truncated = true;
break;
}
body.extend_from_slice(&chunk);
}
let mut body = String::from_utf8_lossy(&body).into_owned();
if body_truncated {
body.push_str(&format!(
"\n[response body truncated after {REMOTE_PLUGIN_BUNDLE_ERROR_BODY_MAX_BYTES} bytes]"
));
}
if let Some(source) = body_read_error {
body.push_str(&format!("\n[failed to read response body: {source}]"));
}
return Err(RemotePluginBundleInstallError::DownloadStatus { host, status, body });
}
read_response_body_with_limit(response, &host, max_bytes).await
}
async fn read_response_body_with_limit(
mut response: HttpResponse,
host: &str,
max_bytes: u64,
) -> Result<Vec<u8>, RemotePluginBundleInstallError> {
if let Some(content_length) = response.content_length() {
enforce_download_size_limit(host, content_length, max_bytes)?;
}
let mut body = Vec::new();
while let Some(chunk) =
response
.chunk()
.await
.map_err(|source| RemotePluginBundleInstallError::DownloadBody {
host: host.to_string(),
source: source.without_url(),
})?
{
let next_len = body.len() as u64 + chunk.len() as u64;
enforce_download_size_limit(host, next_len, max_bytes)?;
body.extend_from_slice(&chunk);
}
Ok(body)
}
fn enforce_download_size_limit(
host: &str,
bytes: u64,
max_bytes: u64,
) -> Result<(), RemotePluginBundleInstallError> {
if bytes > max_bytes {
return Err(RemotePluginBundleInstallError::DownloadTooLarge {
host: host.to_string(),
max_bytes,
});
}
Ok(())
let _ = (config, bundle_download_url, max_bytes);
Err(RemotePluginBundleInstallError::Unavailable)
}
pub(crate) fn install_remote_plugin_bundle(
@@ -657,19 +553,11 @@ fn is_standard_plugin_root(path: &Path) -> bool {
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::recorded_http_client_urls;
use crate::test_support::recording_remote_plugin_service_config;
use flate2::Compression;
use flate2::write::GzEncoder;
use pretty_assertions::assert_eq;
use std::io::Write;
use tempfile::tempdir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_00000000000000000000000000000000";
@@ -783,49 +671,6 @@ mod tests {
));
}
#[test]
fn download_size_limit_rejects_oversized_bundle() {
let err =
enforce_download_size_limit("example.com", /*bytes*/ 5, /*max_bytes*/ 4)
.expect_err("oversized bundle download should fail");
assert!(matches!(
err,
RemotePluginBundleInstallError::DownloadTooLarge { .. }
));
}
#[tokio::test]
async fn bundle_download_routes_the_backend_supplied_url() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/signed/plugin-bundle"))
.and(query_param("sig", "signed-token"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"bundle"))
.expect(1)
.mount(&server)
.await;
let (config, selected_urls) =
recording_remote_plugin_service_config(format!("{}/backend-api", server.uri()));
let download_url = format!("{}/signed/plugin-bundle?sig=signed-token", server.uri());
let err =
download_remote_plugin_bundle_with_limit(&config, &download_url, /*max_bytes*/ 64)
.await
.expect_err("plain HTTP final URL should remain unsupported");
assert!(matches!(
err,
RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { .. }
));
assert!(!err.to_string().contains("signed-token"));
assert!(!format!("{err:?}").contains("signed-token"));
assert_eq!(
recorded_http_client_urls(&selected_urls),
vec![download_url]
);
}
#[test]
fn install_rejects_invalid_tar_gz_bundle() {
let codex_home = tempdir().expect("tempdir");
@@ -1148,7 +993,3 @@ mod tests {
}
}
}
#[cfg(test)]
#[path = "remote_bundle_runtime_auth_tests.rs"]
mod runtime_auth_tests;

View File

@@ -1,55 +0,0 @@
//! Runtime-authenticated catalogs keep presigned bundle transfers unauthenticated.
use super::*;
use codex_features::RuntimeAuthMode;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use pretty_assertions::assert_eq;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::path;
#[tokio::test]
async fn runtime_bundle_download_follows_redirect_without_actor_auth() {
let origin = MockServer::start().await;
let destination = MockServer::start().await;
let final_url = format!("{}/bundle", destination.uri());
Mock::given(path("/bundle"))
.respond_with(ResponseTemplate::new(307).insert_header("location", &final_url))
.expect(1)
.mount(&origin)
.await;
Mock::given(path("/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"bundle"))
.expect(1)
.mount(&destination)
.await;
let config = RemotePluginServiceConfig::new_with_selected_runtime_auth(
origin.uri(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
/*product_sku*/ None,
(Default::default(), RuntimeAuthMode::AssertionOnly),
);
let error = download_remote_plugin_bundle_with_limit(
&config,
&format!("{}/bundle", origin.uri()),
/*max_bytes*/ 64,
)
.await
.expect_err("HTTP final URLs remain unsupported after following redirects");
assert!(
matches!(
&error,
RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { .. }
),
"expected rejection of the HTTP redirect destination: {error}"
);
let mut requests = origin.received_requests().await.unwrap();
requests.extend(destination.received_requests().await.unwrap());
assert_eq!(requests.len(), 2);
for request in requests {
assert!(!request.headers.contains_key("authorization"));
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
}
}

View File

@@ -3,14 +3,8 @@ use crate::remote::RemotePluginServiceConfig;
use codex_http_client::RouteAwareRequestError;
use codex_login::CodexAuth;
use codex_protocol::protocol::Product;
use http::Method;
use http::StatusCode;
use serde::Deserialize;
use std::time::Duration;
use url::Url;
const REMOTE_FEATURED_PLUGIN_FETCH_TIMEOUT: Duration = Duration::from_secs(10);
const REMOTE_PLUGIN_MUTATION_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -21,6 +15,9 @@ struct RemotePluginMutationResponse {
#[derive(Debug, thiserror::Error)]
pub enum RemotePluginMutationError {
#[error("remote plugins are not available in aKode")]
Unavailable,
#[error("chatgpt authentication required for remote plugin mutation")]
AuthRequired,
@@ -80,7 +77,8 @@ impl RemotePluginMutationError {
Self::UnexpectedStatus { status, .. } => {
Some(http_status_sub_error_type(*status).to_string())
}
Self::AuthRequired
Self::Unavailable
| Self::AuthRequired
| Self::UnsupportedAuthMode
| Self::AuthToken(_)
| Self::InvalidBaseUrl(_)
@@ -127,41 +125,8 @@ pub async fn fetch_remote_featured_plugin_ids(
auth: Option<&CodexAuth>,
product: Option<Product>,
) -> Result<Vec<String>, RemotePluginFetchError> {
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let mut url = Url::parse(&format!("{base_url}/plugins/featured"))
.map_err(RemotePluginFetchError::InvalidBaseUrl)?;
url.query_pairs_mut().append_pair(
"platform",
product.unwrap_or(Product::Codex).to_app_platform(),
);
let url = url.to_string();
let request = match auth.filter(|auth| auth.uses_codex_backend()) {
Some(auth) => config
.authenticated_request(Method::GET, &url, auth)
.await
.map_err(std::io::Error::other)
.map_err(RemotePluginFetchError::AuthToken)?,
None => config.http_request(Method::GET, &url),
}
.timeout(REMOTE_FEATURED_PLUGIN_FETCH_TIMEOUT);
let response = request
.send()
.await
.map_err(|source| RemotePluginFetchError::Request {
url: url.clone(),
source,
})?;
let status = response.status();
let body = response.text().await.unwrap_or_default();
if !status.is_success() {
return Err(RemotePluginFetchError::UnexpectedStatus { url, status, body });
}
serde_json::from_str(&body).map_err(|source| RemotePluginFetchError::Decode {
url: url.clone(),
source,
})
let _ = (config, auth, product);
Ok(Vec::new())
}
pub async fn enable_remote_plugin(
@@ -182,84 +147,12 @@ pub async fn uninstall_remote_plugin(
Ok(())
}
fn ensure_codex_backend_auth(
auth: Option<&CodexAuth>,
) -> Result<&CodexAuth, RemotePluginMutationError> {
let Some(auth) = auth else {
return Err(RemotePluginMutationError::AuthRequired);
};
if !auth.uses_codex_backend() {
return Err(RemotePluginMutationError::UnsupportedAuthMode);
}
Ok(auth)
}
async fn post_remote_plugin_mutation(
config: &RemotePluginServiceConfig,
auth: Option<&CodexAuth>,
plugin_id: &str,
action: &str,
) -> Result<RemotePluginMutationResponse, RemotePluginMutationError> {
let auth = ensure_codex_backend_auth(auth)?;
let url = remote_plugin_mutation_url(config, plugin_id, action)?;
let request = config
.authenticated_request(Method::POST, &url, auth)
.await
.map_err(std::io::Error::other)
.map_err(RemotePluginMutationError::AuthToken)?
.timeout(REMOTE_PLUGIN_MUTATION_TIMEOUT);
let response = request
.send()
.await
.map_err(|source| RemotePluginMutationError::Request {
url: url.clone(),
source,
})?;
let status = response.status();
let body = response.text().await.unwrap_or_default();
if !status.is_success() {
return Err(RemotePluginMutationError::UnexpectedStatus { url, status, body });
}
let parsed: RemotePluginMutationResponse =
serde_json::from_str(&body).map_err(|source| RemotePluginMutationError::Decode {
url: url.clone(),
source,
})?;
let expected_enabled = action == "enable";
if parsed.id != plugin_id {
return Err(RemotePluginMutationError::UnexpectedPluginId {
expected: plugin_id.to_string(),
actual: parsed.id,
});
}
if parsed.enabled != expected_enabled {
return Err(RemotePluginMutationError::UnexpectedEnabledState {
plugin_id: plugin_id.to_string(),
expected_enabled,
actual_enabled: parsed.enabled,
});
}
Ok(parsed)
}
fn remote_plugin_mutation_url(
config: &RemotePluginServiceConfig,
plugin_id: &str,
action: &str,
) -> Result<String, RemotePluginMutationError> {
let mut url = Url::parse(config.chatgpt_base_url.trim_end_matches('/'))
.map_err(RemotePluginMutationError::InvalidBaseUrl)?;
{
let mut segments = url
.path_segments_mut()
.map_err(|()| RemotePluginMutationError::InvalidBaseUrlPath)?;
segments.pop_if_empty();
segments.push("plugins");
segments.push(plugin_id);
segments.push(action);
}
Ok(url.to_string())
let _ = (config, auth, plugin_id, action);
Err(RemotePluginMutationError::Unavailable)
}

View File

@@ -22,9 +22,6 @@ use codex_plugin::PluginId;
use codex_plugin::PluginTelemetryMetadata;
use std::sync::Arc;
#[cfg(test)]
#[path = "remote_mutations_tests.rs"]
mod tests;
pub struct RemotePluginInstallRequest {
pub marketplace_name: String,

View File

@@ -1,473 +0,0 @@
//! Regression coverage for remote mutations and account-bound storage transfers.
use super::*;
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
use crate::test_support::load_plugins_config;
use crate::test_support::test_auth_manager;
use crate::test_support::test_plugins_manager_with_auth_manager;
use crate::test_support::write_file;
use codex_protocol::auth::AuthMode;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use tempfile::TempDir;
use tokio::sync::Notify;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[tokio::test]
async fn uninstall_serializes_backend_mutations_and_preserves_cache_on_failure() {
for uninstall_fails in [false, true] {
let home = TempDir::new().unwrap();
let server = MockServer::start().await;
let mut config = load_plugins_config(home.path(), home.path()).await;
config.chatgpt_base_url = format!("{}/backend-api", server.uri());
let auth_manager = test_auth_manager(Some(AuthMode::Chatgpt));
let auth = auth_manager.auth().await;
let manager = Arc::new(test_plugins_manager_with_auth_manager(
home.path().to_path_buf(),
/*restriction_product*/ None,
auth_manager,
));
let remote_id = "b1234567-89ab-4cde-8f01-234567890abc";
let plugin_id = PluginId::new(
"sample".to_string(),
REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(),
)
.unwrap();
let cache = manager.store.plugin_base_root(&plugin_id);
write_file(
cache.join("1.0.0/.codex-plugin/plugin.json").as_path(),
r#"{"name":"sample","version":"1.0.0"}"#,
);
Mock::given(method("GET"))
.and(path(format!("/backend-api/ps/plugins/{remote_id}")))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id": remote_id, "name": "sample", "scope": "GLOBAL",
"installation_policy": "AVAILABLE", "authentication_policy": "ON_USE",
"release": {"display_name": "Sample", "description": "Sample plugin", "interface": {}}
}))).mount(&server).await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(json!({"plugins": [], "pagination": {"next_page_token": null}})),
)
.expect(if uninstall_fails { 0 } else { 1 })
.mount(&server)
.await;
let gate_held = Arc::new(AtomicBool::new(false));
let gate_held_at_post = Arc::clone(&gate_held);
let manager_at_post = Arc::clone(&manager);
Mock::given(method("POST"))
.and(path(format!(
"/backend-api/ps/plugins/{remote_id}/uninstall"
)))
.respond_with(move |_: &wiremock::Request| {
gate_held_at_post.store(
manager_at_post
.remote_installed_plugin_bundle_sync_gate
.available_permits()
== 0,
Ordering::SeqCst,
);
ResponseTemplate::new(if uninstall_fails { 400 } else { 200 })
.set_body_json(json!({"id": remote_id, "enabled": false}))
})
.expect(1)
.mount(&server)
.await;
let refreshed = Arc::new(Notify::new());
let refreshed_callback = Arc::clone(&refreshed);
let outcome = manager
.uninstall_remote_plugin(
&config,
auth.as_ref(),
remote_id,
Some(Arc::new(move |_| refreshed_callback.notify_one())),
)
.await;
assert_eq!(
(
gate_held.load(Ordering::SeqCst),
manager
.remote_installed_plugin_bundle_sync_gate
.available_permits(),
cache.as_path().exists(),
outcome.is_err()
),
(true, 1, uninstall_fails, uninstall_fails),
);
if !uninstall_fails {
tokio::time::timeout(std::time::Duration::from_secs(5), refreshed.notified())
.await
.expect("successful uninstall should refresh installed state");
}
}
}
/// Switch only after metadata has been read, immediately before constructing the storage request.
/// Metadata-body cancellation would not exercise the separate request these tests protect.
#[derive(Clone)]
struct TransferHttpClients {
delegate: codex_http_client::RouteAwareClientPool,
controller: codex_http_client::NetworkPolicyController,
switch_before_storage: Arc<AtomicBool>,
api_origin: String,
storage_origin: String,
}
impl std::fmt::Debug for TransferHttpClients {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TransferHttpClients")
.finish_non_exhaustive()
}
}
impl crate::http_client_selector::HttpClientSelector for TransferHttpClients {
fn for_current_account(&self) -> Arc<dyn crate::http_client_selector::HttpClientSelector> {
Arc::new(Self {
delegate: self.delegate.for_current_account(),
..self.clone()
})
}
fn request(&self, method: http::Method, url: &str) -> codex_http_client::RequestBuilder {
if url.starts_with("https://storage.example/")
&& self.switch_before_storage.swap(false, Ordering::SeqCst)
{
let policy = self.controller.policy();
policy.invalidate();
assert!(self.controller.publish(
policy.revision(),
codex_http_client::DestinationPolicy::Unrestricted,
));
}
self.delegate.request(
method,
url.replace("https://storage.example", &self.storage_origin)
.replace("https://chatgpt.com", &self.api_origin),
)
}
fn request_for_account(
&self,
method: http::Method,
url: &str,
binding: &codex_http_client::NetworkPolicy,
) -> Option<codex_http_client::RequestBuilder> {
Some(
self.delegate
.with_account_binding(binding)?
.request(method, url.replace("https://chatgpt.com", &self.api_origin)),
)
}
fn outbound_proxy_policy(&self) -> codex_http_client::OutboundProxyPolicy {
self.delegate.outbound_proxy_policy()
}
}
struct PluginTransferTest {
api: MockServer,
storage: MockServer,
config: PluginsConfigInput,
manager: Arc<PluginsManager>,
auth: CodexAuth,
switch_before_storage: Arc<AtomicBool>,
}
impl PluginTransferTest {
async fn new(
home: &std::path::Path,
mode: codex_features::RuntimeAuthMode,
switch: bool,
) -> Self {
use base64::Engine;
use codex_http_client::ClientRouteClass;
use codex_http_client::DestinationPolicy;
use codex_http_client::HttpClientFactory;
use codex_http_client::NetworkPolicyController;
use codex_http_client::OutboundProxyPolicy;
use codex_http_client::RouteAwareClientPool;
use codex_runtime_agent_instance::AgentHostAuthorization;
use codex_runtime_agent_instance::RuntimeAuthManager;
use codex_runtime_agent_instance::RuntimeAuthSlot;
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
use codex_runtime_agent_instance::RuntimeRole;
let api = MockServer::start().await;
let storage = MockServer::start().await;
Mock::given(path("/agent/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": "runtime-plugins", "agent_host_id": "host-a",
"actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "account-a"},
})))
.expect(1)
.mount(&api)
.await;
let claims = json!({
"iss": "https://auth.openai.com/", "session_id": "login-a",
"https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "account-a"},
});
let token = format!(
"header.{}.signature",
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string()),
);
let auth = CodexAuth::from_external_chatgpt_tokens(
&token,
"account-a",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let credentials = codex_login::AuthManager::from_auth_for_testing(auth.clone());
let slot = RuntimeAuthSlot::default();
slot.set(Arc::new(RuntimeAuthManager::new(
Arc::clone(&credentials),
AgentHostAuthorization::InstallationId {
installation_id: uuid::Uuid::nil(),
},
RuntimeRegistrationMetadata {
harness: Some("codex".into()),
harness_version: None,
role: RuntimeRole::Orchestrator,
},
format!("{}/agent/register", api.uri()).parse().unwrap(),
)))
.unwrap();
let controller = NetworkPolicyController::default();
assert!(controller.publish(
controller.policy().revision(),
DestinationPolicy::Unrestricted
));
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_network_policy(controller.policy())
.with_sensitive_header_protection();
let switch_before_storage = Arc::new(AtomicBool::new(switch));
let clients = Arc::new(TransferHttpClients {
delegate: RouteAwareClientPool::with_chatgpt_cloudflare_cookies_without_request_logging(
factory.clone(),
ClientRouteClass::Api,
),
controller,
switch_before_storage: Arc::clone(&switch_before_storage),
api_origin: api.uri(),
storage_origin: storage.uri(),
});
let config = PluginsConfigInput::new(
Default::default(),
Default::default(),
"openai".into(),
/*plugins_enabled*/ true,
/*remote_plugin_enabled*/ true,
"https://chatgpt.com/backend-api".into(),
factory,
/*product_sku*/ None,
)
.with_runtime_auth_mode(Some(mode));
config.runtime_http_clients.set(clients).unwrap();
let manager = Arc::new(crate::PluginsManager::new_with_options(
home.to_path_buf(),
/*restriction_product*/ None,
credentials,
slot,
crate::test_support::test_skill_root_loader(),
));
Self {
api,
storage,
config,
manager,
auth,
switch_before_storage,
}
}
async fn verify(&self, account_changed: bool, mode: codex_features::RuntimeAuthMode) {
assert!(!self.switch_before_storage.load(Ordering::SeqCst));
self.api.verify().await;
let storage_requests = self.storage.received_requests().await.unwrap();
assert_eq!(storage_requests.len(), usize::from(!account_changed));
for request in storage_requests {
for name in [
"authorization",
"x-openai-agent-assertion",
"chatgpt-account-id",
] {
assert!(!request.headers.contains_key(name));
}
}
for request in self.api.received_requests().await.unwrap() {
if request.url.path() == "/agent/register" {
continue;
}
let authorization = request.headers["authorization"].to_str().unwrap();
match mode {
codex_features::RuntimeAuthMode::DualHeader => {
assert!(authorization.starts_with("Bearer "));
assert!(request.headers.contains_key("x-openai-agent-assertion"));
}
codex_features::RuntimeAuthMode::AssertionOnly => {
assert!(authorization.starts_with("AgentAssertion "));
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
}
}
}
}
}
#[tokio::test]
async fn plugin_share_keeps_account_binding_through_storage_upload() {
use codex_features::RuntimeAuthMode;
use codex_http_client::NetworkPolicyDenied;
use codex_http_client::RouteAwareRequestError;
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
for account_changed in [false, true] {
let home = TempDir::new().unwrap();
let fixture = PluginTransferTest::new(home.path(), mode, account_changed).await;
let plugin_path = home.path().join("sample");
write_file(
&plugin_path.join(".codex-plugin/plugin.json"),
r#"{"name":"sample"}"#,
);
Mock::given(method("POST"))
.and(path("/backend-api/public/plugins/workspace/upload-url"))
.respond_with(ResponseTemplate::new(201).set_body_json(json!({
"file_id": "file_123", "upload_url": "https://storage.example/upload",
"etag": "\"metadata-etag\"",
})))
.expect(1)
.mount(&fixture.api)
.await;
Mock::given(method("PUT"))
.and(path("/upload"))
.respond_with(ResponseTemplate::new(201))
.mount(&fixture.storage)
.await;
Mock::given(method("POST"))
.and(path("/backend-api/public/plugins/workspace"))
.respond_with(ResponseTemplate::new(201).set_body_json(json!({
"plugin_id": "plugins_123", "share_url": null,
})))
.expect(u64::from(!account_changed))
.mount(&fixture.api)
.await;
let result = remote::save_remote_plugin_share(
&fixture
.manager
.remote_plugin_service_config(&fixture.config),
Some(&fixture.auth),
home.path(),
&AbsolutePathBuf::try_from(plugin_path).unwrap(),
/*remote_plugin_id*/ None,
remote::RemotePluginShareAccessPolicy::default(),
)
.await;
if account_changed {
assert!(
matches!(
result,
Err(RemotePluginCatalogError::Request {
source: RouteAwareRequestError::Policy(NetworkPolicyDenied::Revoked),
..
})
),
"{result:?}"
);
} else {
assert_eq!(result.unwrap().remote_plugin_id, "plugins_123");
}
fixture.verify(account_changed, mode).await;
}
}
}
#[tokio::test]
async fn plugin_install_keeps_account_binding_through_storage_download() {
use codex_features::RuntimeAuthMode;
use codex_http_client::NetworkPolicyDenied;
use codex_http_client::RouteAwareRequestError;
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
for account_changed in [false, true] {
let home = TempDir::new().unwrap();
let fixture = PluginTransferTest::new(home.path(), mode, account_changed).await;
let remote_id = "b1234567-89ab-4cde-8f01-234567890abc";
Mock::given(method("GET"))
.and(path(format!("/backend-api/ps/plugins/{remote_id}")))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id": remote_id, "name": "sample", "scope": "GLOBAL",
"installation_policy": "AVAILABLE", "authentication_policy": "ON_USE",
"release": {
"version": "1.0.0", "display_name": "Sample",
"description": "Sample plugin", "interface": {},
"bundle_download_url": "https://storage.example/bundle",
}
})))
.expect(1)
.mount(&fixture.api)
.await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [], "pagination": {"next_page_token": null},
})))
.expect(1)
.mount(&fixture.api)
.await;
Mock::given(method("GET"))
.and(path("/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_string("bundle"))
.mount(&fixture.storage)
.await;
let result = fixture
.manager
.install_remote_plugin(
&fixture.config,
Some(&fixture.auth),
RemotePluginInstallRequest {
marketplace_name: REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(),
remote_plugin_id: remote_id.to_string(),
install_attempt_id: None,
},
/*on_effective_plugins_changed*/ None,
)
.await;
let error = result.err().expect("test transfer should fail");
if account_changed {
assert!(
matches!(
*error.kind,
RemotePluginOperationErrorKind::Bundle(
RemotePluginBundleInstallError::DownloadRequest {
source: RouteAwareRequestError::Policy(
NetworkPolicyDenied::Revoked
),
..
}
)
),
"{error:?}"
);
} else {
// The local HTTP control reaches storage, then fails the final-URL HTTPS check.
assert!(
matches!(
*error.kind,
RemotePluginOperationErrorKind::Bundle(
RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { .. }
)
),
"{error:?}"
);
}
fixture.verify(account_changed, mode).await;
}
}
}

View File

@@ -1,307 +0,0 @@
//! Exercise modern and legacy plugin requests with a shared, late-initialized runtime.
use super::*;
use base64::Engine;
use codex_features::RuntimeAuthMode;
use codex_http_client::DestinationPolicy;
use codex_http_client::NetworkPolicyController;
use codex_http_client::NetworkPolicyDenied;
use codex_http_client::OutboundProxyPolicy;
use codex_login::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use codex_login::AuthManager;
use codex_login::AuthRouteConfig;
use codex_runtime_agent_instance::AgentHostAuthorization;
use codex_runtime_agent_instance::RuntimeAuthManager;
use codex_runtime_agent_instance::RuntimeAuthSlot;
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
use codex_runtime_agent_instance::RuntimeRole;
use pretty_assertions::assert_eq;
use serde_json::json;
use uuid::Uuid;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::path;
#[tokio::test]
async fn plugin_runtime_auth_shares_registration_and_strips_cross_origin_auth() {
for (mode, pooled) in [
(RuntimeAuthMode::DualHeader, false),
(RuntimeAuthMode::AssertionOnly, false),
(RuntimeAuthMode::DualHeader, true),
(RuntimeAuthMode::AssertionOnly, true),
] {
let server = MockServer::start().await;
let destination = MockServer::start().await;
Mock::given(path("/"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"enabled": true, "plugins": [],
})))
.expect(1)
.mount(&destination)
.await;
Mock::given(path("/agent/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": "runtime-plugins", "agent_host_id": "host-a",
"actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "account-a"},
})))
.expect(1)
.mount(&server)
.await;
Mock::given(path("/backend-api/ps/plugins/list"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [], "pagination": {"next_page_token": null},
})))
.expect(2)
.mount(&server)
.await;
Mock::given(path("/backend-api/plugins/featured"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!([])))
.expect(1)
.mount(&server)
.await;
Mock::given(path("/backend-api/ps/plugins/suggested/codex"))
.respond_with(ResponseTemplate::new(307).insert_header("location", destination.uri()))
.expect(1)
.mount(&server)
.await;
let claims = json!({
"iss": "https://auth.openai.com/", "session_id": "login-a",
"https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "account-a"},
});
let token = format!(
"header.{}.signature",
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string())
);
let auth = CodexAuth::from_external_chatgpt_tokens(
&token,
"account-a",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let slot = RuntimeAuthSlot::default();
let controller = NetworkPolicyController::default();
let policy = controller.policy();
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_network_policy(policy.clone());
let home = tempfile::tempdir().unwrap();
codex_login::auth::login_with_chatgpt_auth_tokens(
home.path(),
&token,
"account-a",
/*chatgpt_plan_type*/ None,
)
.unwrap();
let credentials = Arc::new(
AuthManager::new(
home.path().to_path_buf(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::Ephemeral,
/*forced_chatgpt_workspace_id*/ None,
/*chatgpt_base_url*/ None,
AuthKeyringBackendKind::Direct,
AuthRouteConfig::from_http_client_factory(factory.clone()),
)
.await,
);
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
let mut config = if pooled {
crate::manager::PluginsConfigInput::new(
Default::default(),
Default::default(),
"openai".into(),
/*plugins_enabled*/ true,
/*remote_plugin_enabled*/ true,
"https://chatgpt.com/backend-api".into(),
factory,
/*product_sku*/ None,
)
.remote_plugin_service_config(Some((Arc::clone(&slot), mode)))
} else {
RemotePluginServiceConfig::new_with_selected_runtime_auth(
"https://chatgpt.com/backend-api".into(),
factory,
/*product_sku*/ None,
(Arc::clone(&slot), mode),
)
};
config.chatgpt_base_url = format!("{}/backend-api", server.uri());
// Enabled requests cannot silently fall back before the harness initializes the slot.
assert!(
fetch_recommended_plugins(&config, Some(&auth))
.await
.is_err()
);
assert!(server.received_requests().await.unwrap().is_empty());
slot.set(Arc::new(RuntimeAuthManager::new(
credentials,
AgentHostAuthorization::InstallationId {
installation_id: Uuid::nil(),
},
RuntimeRegistrationMetadata {
harness: Some("codex".into()),
harness_version: None,
role: RuntimeRole::Orchestrator,
},
format!("{}/agent/register", server.uri()).parse().unwrap(),
)))
.unwrap();
get_remote_plugin_list_page(
&config,
&auth,
RemotePluginScope::Global,
/*page_token*/ None,
/*collection*/ None,
)
.await
.unwrap();
crate::remote_legacy::fetch_remote_featured_plugin_ids(
&config,
Some(&auth),
/*product*/ None,
)
.await
.unwrap();
fetch_recommended_plugins(&config, Some(&auth))
.await
.unwrap();
let redirected = destination.received_requests().await.unwrap();
assert_eq!(redirected.len(), 1);
assert!(!redirected[0].headers.contains_key("authorization"));
assert!(
!redirected[0]
.headers
.contains_key("x-openai-agent-assertion")
);
destination.verify().await;
let url = format!("{}/backend-api/ps/plugins/list", server.uri());
let pending = config
.authenticated_request(Method::GET, &url, &auth)
.await
.unwrap();
policy.invalidate();
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
assert!(matches!(
pending.send().await,
Err(RouteAwareRequestError::Policy(NetworkPolicyDenied::Revoked))
));
let response = config
.authenticated_request(Method::GET, &url, &auth)
.await
.unwrap()
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let requests = server.received_requests().await.unwrap();
let mut proof_ids = HashSet::new();
for request in requests
.iter()
.filter(|r| r.url.path() != "/agent/register")
{
let authorization = request.headers["authorization"].to_str().unwrap();
let proof = match mode {
RuntimeAuthMode::DualHeader => {
assert_eq!(authorization, format!("Bearer {token}"));
request.headers["x-openai-agent-assertion"]
.to_str()
.unwrap()
}
RuntimeAuthMode::AssertionOnly => {
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
authorization.strip_prefix("AgentAssertion ").unwrap()
}
};
assert_eq!(request.headers["chatgpt-account-id"], "account-a");
let payload: JsonValue = serde_json::from_slice(
&base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(proof.split('.').nth(2).unwrap())
.unwrap(),
)
.unwrap();
assert_eq!(payload["runtime_agent_instance"], "runtime-plugins");
assert!(proof_ids.insert(payload["id"].as_str().unwrap().to_string()));
}
assert_eq!(proof_ids.len(), 4);
server.verify().await;
}
}
#[tokio::test]
async fn custom_plugin_backend_keeps_legacy_auth_with_runtime_enabled() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
Mock::given(path("/backend-api/plugins/featured"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!([])))
.expect(1)
.mount(&server)
.await;
let config = RemotePluginServiceConfig::new_with_runtime_auth(
format!("{}/backend-api", server.uri()),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
/*product_sku*/ None,
(RuntimeAuthSlot::default(), mode),
);
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
crate::remote_legacy::fetch_remote_featured_plugin_ids(
&config,
Some(&auth),
/*product*/ None,
)
.await
.unwrap();
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len(), 1);
assert!(
requests[0].headers["authorization"]
.to_str()
.unwrap()
.starts_with("Bearer ")
);
assert!(!requests[0].headers.contains_key("x-openai-agent-assertion"));
server.verify().await;
}
}
#[tokio::test]
async fn unsupported_openai_plugin_backend_fails_before_registration() {
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
let server = MockServer::start().await;
let auth = CodexAuth::from_api_key("key-a");
let runtime = (
Arc::new(std::sync::OnceLock::from(Arc::new(
RuntimeAuthManager::new(
AuthManager::from_auth_for_testing(auth.clone()),
AgentHostAuthorization::InstallationId {
installation_id: Uuid::nil(),
},
RuntimeRegistrationMetadata {
harness: Some("codex".into()),
harness_version: None,
role: RuntimeRole::Orchestrator,
},
format!("{}/register", server.uri()).parse().unwrap(),
),
))),
mode,
);
let config = RemotePluginServiceConfig::new_with_runtime_auth(
"https://future.openai.com/backend-api".to_string(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
/*product_sku*/ None,
runtime,
);
assert!(
config
.authenticated_request(
Method::GET,
"https://future.openai.com/backend-api/plugins/featured",
&auth,
)
.await
.is_err()
);
assert!(server.received_requests().await.unwrap().is_empty());
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -124,31 +124,6 @@ impl PluginMeasurementTarget {
}
impl TrustedPluginRoots {
/// Called only after the authenticated remote bundle installer has prepared
/// an isolated store. Read declarations without loading plugin capabilities.
pub(crate) fn from_measurement_reference(
codex_home: &Path,
plugin_id: &PluginId,
version: &str,
remote_id: &str,
) -> Option<Self> {
let store = PluginStore::try_new(codex_home.to_owned()).ok()?;
if store.active_plugin_version(plugin_id).as_deref() != Some(version)
|| store.remote_plugin_id(plugin_id).ok()?.as_deref() != Some(remote_id)
{
return None;
}
let root = store.plugin_root(plugin_id, version).canonicalize().ok()?;
let metrics_operations_by_path = load_plugin_metrics_operations(&root).unwrap_or_default();
Some(Self {
roots: vec![TrustedPluginRoot {
plugin_id: plugin_id.clone(),
version: version.to_owned(),
root,
metrics_operations_by_path,
}],
})
}
/// Adds already-trusted roots, preserving the existing root for each plugin and version.
/// Distinct versions remain eligible for exact executor-version matching.

View File

@@ -4,23 +4,17 @@ use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use crate::OPENAI_API_CURATED_MARKETPLACE_NAME;
use crate::OPENAI_CURATED_MARKETPLACE_NAME;
use crate::PluginsConfigInput;
use crate::PluginsManager;
use crate::http_client_selector::HttpClientSelector;
use crate::remote::RemotePluginServiceConfig;
use codex_config::LoaderOverrides;
use codex_config::NoopThreadConfigLoader;
use codex_config::loader::load_config_layers_state;
use codex_exec_server::LOCAL_FS;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_http_client::RequestBuilder;
use codex_http_client::RouteAwareClientPool;
use codex_login::AuthHeaders;
use codex_login::AuthManager;
use codex_login::CodexAuth;
@@ -47,7 +41,6 @@ use codex_utils_path_uri::PathUri;
use codex_utils_plugins::PluginSkillRoot;
use codex_utils_plugins::SkillDiscoveryMode;
use codex_utils_plugins::migrated_command_skills_root;
use http::Method;
use toml::Value;
pub(crate) const TEST_CURATED_PLUGIN_SHA: &str = "0123456789abcdef0123456789abcdef01234567";
@@ -323,85 +316,6 @@ pub(crate) fn test_http_client_factory() -> HttpClientFactory {
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
}
#[derive(Debug)]
pub(crate) struct RecordingHttpClientSelector {
selected_urls: Arc<Mutex<Vec<String>>>,
delegate: RouteAwareClientPool,
}
impl RecordingHttpClientSelector {
fn record_url(&self, url: &str) {
match self.selected_urls.lock() {
Ok(mut selected_urls) => selected_urls.push(url.to_string()),
Err(error) => panic!("selected URL recorder lock should not be poisoned: {error}"),
}
}
pub(crate) fn new() -> (Arc<Self>, Arc<Mutex<Vec<String>>>) {
let selected_urls = Arc::new(Mutex::new(Vec::new()));
let delegate = RouteAwareClientPool::with_chatgpt_cloudflare_cookies(
test_http_client_factory(),
ClientRouteClass::Api,
);
(
Arc::new(Self {
selected_urls: Arc::clone(&selected_urls),
delegate,
}),
selected_urls,
)
}
}
impl HttpClientSelector for RecordingHttpClientSelector {
fn for_current_account(&self) -> Arc<dyn HttpClientSelector> {
Arc::new(Self {
selected_urls: Arc::clone(&self.selected_urls),
delegate: self.delegate.for_current_account(),
})
}
fn request(&self, method: Method, url: &str) -> RequestBuilder {
self.record_url(url);
self.delegate.request(method, url)
}
fn request_for_account(
&self,
method: Method,
url: &str,
binding: &codex_http_client::NetworkPolicy,
) -> Option<RequestBuilder> {
self.record_url(url);
self.delegate.request_for_account(method, url, binding)
}
fn outbound_proxy_policy(&self) -> OutboundProxyPolicy {
self.delegate.outbound_proxy_policy()
}
}
pub(crate) fn recording_remote_plugin_service_config(
chatgpt_base_url: String,
) -> (RemotePluginServiceConfig, Arc<Mutex<Vec<String>>>) {
let (http_clients, selected_urls) = RecordingHttpClientSelector::new();
(
RemotePluginServiceConfig {
runtime_auth: None,
chatgpt_base_url,
product_sku: crate::remote::CODEX_PRODUCT_SKU.to_string(),
http_clients,
},
selected_urls,
)
}
pub(crate) fn recorded_http_client_urls(selected_urls: &Mutex<Vec<String>>) -> Vec<String> {
match selected_urls.lock() {
Ok(selected_urls) => selected_urls.clone(),
Err(error) => panic!("selected URL recorder lock should not be poisoned: {error}"),
}
}
pub(crate) fn write_file(path: &Path, contents: &str) {
fs::create_dir_all(path.parent().expect("file should have a parent")).unwrap();
fs::write(path, contents).unwrap();