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

@@ -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:?}"
);
}
}