Base: codex-main originale (prima del fork aKode)
This commit is contained in:
335
codex-rs/core-plugins/src/remote/catalog_cache.rs
Normal file
335
codex-rs/core-plugins/src/remote/catalog_cache.rs
Normal file
@@ -0,0 +1,335 @@
|
||||
use super::RemotePluginCatalogCacheMode;
|
||||
use super::RemotePluginDirectoryItem;
|
||||
use super::RemotePluginScope;
|
||||
use super::RemotePluginServiceConfig;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_login::CodexAuth;
|
||||
use serde::Deserialize;
|
||||
use serde::Deserializer;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::de::DeserializeSeed;
|
||||
use serde::de::IgnoredAny;
|
||||
use serde::de::MapAccess;
|
||||
use serde::de::SeqAccess;
|
||||
use serde::de::Visitor;
|
||||
use std::fmt;
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use tracing::warn;
|
||||
|
||||
// `plugin/list` and other callers that assume all plugins are available locally will be
|
||||
// deprecated soon. Remove this catalog cache when those callers migrate to on-demand fetching.
|
||||
const REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION: u8 = 1;
|
||||
const REMOTE_PLUGIN_CATALOG_DISK_CACHE_DIR: &str = "cache/remote_plugin_catalog";
|
||||
const REMOTE_PLUGIN_CATALOG_DISK_CACHE_TTL: Duration = Duration::from_secs(60 * 60 * 3);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
struct RemotePluginCatalogCacheKey {
|
||||
chatgpt_base_url: String,
|
||||
account_id: Option<String>,
|
||||
chatgpt_user_id: Option<String>,
|
||||
is_workspace_account: bool,
|
||||
// Global catalogs predate scoped cache keys and must keep their existing filenames.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
scope: Option<RemotePluginScope>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
collection: Option<String>,
|
||||
}
|
||||
|
||||
impl RemotePluginCatalogCacheKey {
|
||||
fn new(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
collection: Option<&str>,
|
||||
) -> Option<Self> {
|
||||
let cache_key = Self {
|
||||
chatgpt_base_url: config.chatgpt_base_url.clone(),
|
||||
account_id: auth.get_account_id(),
|
||||
chatgpt_user_id: auth.get_chatgpt_user_id(),
|
||||
is_workspace_account: auth.is_workspace_account(),
|
||||
scope: (scope != RemotePluginScope::Global).then_some(scope),
|
||||
collection: collection.map(str::to_owned),
|
||||
};
|
||||
// Preserve global catalog caching for existing header-auth clients, but never share
|
||||
// user or workspace catalogs when the auth mode cannot identify their owner.
|
||||
if !matches!(scope, RemotePluginScope::Global)
|
||||
&& cache_key.account_id.is_none()
|
||||
&& cache_key.chatgpt_user_id.is_none()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(cache_key)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct RemotePluginCatalogDiskCache<Plugins> {
|
||||
schema_version: u8,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
fetched_at: Option<DateTime<Utc>>,
|
||||
plugins: Plugins,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum RemotePluginCatalogCacheFreshness {
|
||||
Fresh,
|
||||
Stale,
|
||||
}
|
||||
|
||||
pub(super) struct CachedDirectoryPlugins<T> {
|
||||
pub plugins: Vec<T>,
|
||||
pub freshness: RemotePluginCatalogCacheFreshness,
|
||||
}
|
||||
|
||||
pub(super) fn has_cached_directory_plugins(
|
||||
codex_home: &Path,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
cache_mode: RemotePluginCatalogCacheMode,
|
||||
) -> bool {
|
||||
// Ignore each entry so Serde still requires `plugins` to be an array.
|
||||
load_cached_directory_plugins::<IgnoredAny>(
|
||||
codex_home, config, auth, scope, /*collection*/ None, cache_mode,
|
||||
)
|
||||
.is_some()
|
||||
}
|
||||
|
||||
pub(super) fn load_cached_directory_plugins<T: DeserializeOwned>(
|
||||
codex_home: &Path,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
collection: Option<&str>,
|
||||
cache_mode: RemotePluginCatalogCacheMode,
|
||||
) -> Option<CachedDirectoryPlugins<T>> {
|
||||
if cache_mode == RemotePluginCatalogCacheMode::ForceRefetch {
|
||||
return None;
|
||||
}
|
||||
let cache_key = RemotePluginCatalogCacheKey::new(config, auth, scope, collection)?;
|
||||
let cache_path = cache_path(codex_home, &cache_key);
|
||||
let bytes = match read_catalog_bytes(&cache_path, cache_mode) {
|
||||
Ok(bytes) => bytes?,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return None,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
cache_path = %cache_path.display(),
|
||||
"failed to read remote plugin catalog disk cache: {err}"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let cache: RemotePluginCatalogDiskCache<Vec<T>> = match serde_json::from_slice(&bytes) {
|
||||
Ok(cache) => cache,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
cache_path = %cache_path.display(),
|
||||
"failed to parse remote plugin catalog disk cache: {err}"
|
||||
);
|
||||
let _ = std::fs::remove_file(cache_path);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if cache.schema_version != REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION {
|
||||
let _ = std::fs::remove_file(cache_path);
|
||||
return None;
|
||||
}
|
||||
|
||||
let freshness = if is_fresh(cache.fetched_at, Utc::now()) {
|
||||
RemotePluginCatalogCacheFreshness::Fresh
|
||||
} else if cache_mode == RemotePluginCatalogCacheMode::PreferFreshCache {
|
||||
return None;
|
||||
} else {
|
||||
RemotePluginCatalogCacheFreshness::Stale
|
||||
};
|
||||
Some(CachedDirectoryPlugins {
|
||||
plugins: cache.plugins,
|
||||
freshness,
|
||||
})
|
||||
}
|
||||
|
||||
fn read_catalog_bytes(
|
||||
path: &Path,
|
||||
cache_mode: RemotePluginCatalogCacheMode,
|
||||
) -> io::Result<Option<Vec<u8>>> {
|
||||
let mut file = File::open(path)?;
|
||||
let mut bytes = Vec::new();
|
||||
if cache_mode == RemotePluginCatalogCacheMode::PreferFreshCache {
|
||||
const PREFIX_LEN: usize = 256;
|
||||
bytes.reserve_exact(PREFIX_LEN);
|
||||
file.by_ref()
|
||||
.take(PREFIX_LEN as u64)
|
||||
.read_to_end(&mut bytes)?;
|
||||
if bytes.len() < PREFIX_LEN {
|
||||
return Ok(Some(bytes));
|
||||
}
|
||||
if CatalogHeader::is_stale_prefix(&bytes, Utc::now()) {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
file.read_to_end(&mut bytes)?;
|
||||
Ok(Some(bytes))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct CatalogHeader {
|
||||
schema_version: Option<u8>,
|
||||
fetched_at: Option<DateTime<Utc>>,
|
||||
metadata_before_plugins: bool,
|
||||
}
|
||||
|
||||
impl CatalogHeader {
|
||||
fn is_stale_prefix(bytes: &[u8], now: DateTime<Utc>) -> bool {
|
||||
let mut header = Self::default();
|
||||
let mut json = serde_json::Deserializer::from_slice(bytes);
|
||||
// A bounded read can end inside the payload. Only fully decoded fields count.
|
||||
let parsed = json.deserialize_map(&mut header).and_then(|()| json.end());
|
||||
if parsed.is_err_and(|err| !err.is_eof()) {
|
||||
return false;
|
||||
}
|
||||
header.metadata_before_plugins && !is_fresh(header.fetched_at, now)
|
||||
}
|
||||
}
|
||||
|
||||
// Only the `plugins` field uses the seed. Serde calls `visit_seq` when it enters
|
||||
// that array, so a missing or wrongly typed payload still goes through the full reader.
|
||||
impl<'de> DeserializeSeed<'de> for &mut CatalogHeader {
|
||||
type Value = ();
|
||||
|
||||
fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<(), D::Error> {
|
||||
deserializer.deserialize_seq(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Visitor<'de> for &mut CatalogHeader {
|
||||
type Value = ();
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str("a plugin catalog object or its plugins array")
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(field_identifier, rename_all = "snake_case")]
|
||||
enum Field {
|
||||
SchemaVersion,
|
||||
FetchedAt,
|
||||
Plugins,
|
||||
#[serde(other)]
|
||||
Other,
|
||||
}
|
||||
|
||||
let mut saw_plugins = false;
|
||||
while let Some(field) = map.next_key()? {
|
||||
match field {
|
||||
Field::SchemaVersion if self.schema_version.is_none() => {
|
||||
self.schema_version = Some(map.next_value()?);
|
||||
}
|
||||
Field::FetchedAt if self.fetched_at.is_none() => {
|
||||
self.fetched_at = Some(map.next_value()?);
|
||||
}
|
||||
Field::Plugins if !saw_plugins => {
|
||||
saw_plugins = true;
|
||||
map.next_value_seed(&mut *self)?;
|
||||
}
|
||||
Field::SchemaVersion => {
|
||||
return Err(serde::de::Error::duplicate_field("schema_version"));
|
||||
}
|
||||
Field::FetchedAt => return Err(serde::de::Error::duplicate_field("fetched_at")),
|
||||
Field::Plugins => return Err(serde::de::Error::duplicate_field("plugins")),
|
||||
Field::Other => {
|
||||
map.next_value::<IgnoredAny>()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut plugins: A) -> Result<(), A::Error> {
|
||||
self.metadata_before_plugins = self.schema_version
|
||||
== Some(REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION)
|
||||
&& self.fetched_at.is_some();
|
||||
while plugins.next_element::<IgnoredAny>()?.is_some() {}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_cached_directory_plugins(
|
||||
codex_home: &Path,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
collection: Option<&str>,
|
||||
plugins: &[RemotePluginDirectoryItem],
|
||||
) {
|
||||
let Some(cache_key) = RemotePluginCatalogCacheKey::new(config, auth, scope, collection) else {
|
||||
return;
|
||||
};
|
||||
let cache_path = cache_path(codex_home, &cache_key);
|
||||
let Ok(contents) = serde_json::to_string_pretty(&RemotePluginCatalogDiskCache {
|
||||
schema_version: REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION,
|
||||
fetched_at: Some(Utc::now()),
|
||||
plugins,
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let _ = codex_utils_path::write_atomically(&cache_path, &contents);
|
||||
}
|
||||
|
||||
pub(crate) fn remove_cached_directory_plugins(
|
||||
codex_home: &Path,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
collection: Option<&str>,
|
||||
) {
|
||||
let Some(cache_key) = RemotePluginCatalogCacheKey::new(config, auth, scope, collection) else {
|
||||
return;
|
||||
};
|
||||
let cache_path = cache_path(codex_home, &cache_key);
|
||||
match std::fs::remove_file(&cache_path) {
|
||||
Ok(()) => {}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
cache_path = %cache_path.display(),
|
||||
"failed to remove remote plugin catalog disk cache: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cache_path(codex_home: &Path, cache_key: &RemotePluginCatalogCacheKey) -> PathBuf {
|
||||
let cache_key_json = serde_json::to_vec(cache_key).unwrap_or_default();
|
||||
let mut cache_key_hash = 0xcbf29ce484222325_u64;
|
||||
for byte in cache_key_json {
|
||||
cache_key_hash ^= u64::from(byte);
|
||||
cache_key_hash = cache_key_hash.wrapping_mul(0x100000001b3);
|
||||
}
|
||||
codex_home
|
||||
.join(REMOTE_PLUGIN_CATALOG_DISK_CACHE_DIR)
|
||||
.join(format!("{cache_key_hash:016x}.json"))
|
||||
}
|
||||
|
||||
fn is_fresh(fetched_at: Option<DateTime<Utc>>, now: DateTime<Utc>) -> bool {
|
||||
let Some(fetched_at) = fetched_at else {
|
||||
return false;
|
||||
};
|
||||
let Ok(ttl) = chrono::Duration::from_std(REMOTE_PLUGIN_CATALOG_DISK_CACHE_TTL) else {
|
||||
return false;
|
||||
};
|
||||
let age = now.signed_duration_since(fetched_at);
|
||||
age >= chrono::Duration::zero() && age <= ttl
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "catalog_cache_tests.rs"]
|
||||
mod tests;
|
||||
246
codex-rs/core-plugins/src/remote/catalog_cache_tests.rs
Normal file
246
codex-rs/core-plugins/src/remote/catalog_cache_tests.rs
Normal file
@@ -0,0 +1,246 @@
|
||||
use super::*;
|
||||
use chrono::TimeDelta;
|
||||
use codex_login::AuthHeaders;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn catalog_cache_freshness_honors_ttl() {
|
||||
let now = Utc::now();
|
||||
|
||||
assert!(!is_fresh(/*fetched_at*/ None, now));
|
||||
assert!(is_fresh(Some(now), now));
|
||||
assert!(is_fresh(Some(now - TimeDelta::hours(3)), now,));
|
||||
assert!(!is_fresh(
|
||||
Some(now - TimeDelta::hours(3) - TimeDelta::milliseconds(1)),
|
||||
now,
|
||||
));
|
||||
assert!(!is_fresh(Some(now + TimeDelta::milliseconds(1)), now));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_cache_paths_are_isolated_by_scope_and_collection() {
|
||||
let codex_home = Path::new("/tmp/codex-home");
|
||||
let cache_key_for_scope = |scope| RemotePluginCatalogCacheKey {
|
||||
chatgpt_base_url: "https://chatgpt.com/backend-api".to_string(),
|
||||
account_id: Some("account-id".to_string()),
|
||||
chatgpt_user_id: Some("user-id".to_string()),
|
||||
is_workspace_account: true,
|
||||
scope: (scope != RemotePluginScope::Global).then_some(scope),
|
||||
collection: None,
|
||||
};
|
||||
|
||||
let paths = [
|
||||
RemotePluginScope::Global,
|
||||
RemotePluginScope::User,
|
||||
RemotePluginScope::Workspace,
|
||||
]
|
||||
.map(|scope| cache_path(codex_home, &cache_key_for_scope(scope)));
|
||||
|
||||
assert_ne!(paths[0], paths[1]);
|
||||
assert_ne!(paths[0], paths[2]);
|
||||
assert_ne!(paths[1], paths[2]);
|
||||
|
||||
let mut collection_key = cache_key_for_scope(RemotePluginScope::Global);
|
||||
collection_key.collection = Some("vertical".to_string());
|
||||
assert!(!paths.contains(&cache_path(codex_home, &collection_key)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_catalog_cache_reuses_legacy_cache_file() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let config = RemotePluginServiceConfig::new(
|
||||
"https://chatgpt.com/backend-api".to_string(),
|
||||
crate::test_support::test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let auth = CodexAuth::Headers(AuthHeaders::new(http::HeaderMap::new()));
|
||||
let legacy_cache_path = codex_home
|
||||
.path()
|
||||
.join(REMOTE_PLUGIN_CATALOG_DISK_CACHE_DIR)
|
||||
.join("f22564d6f8ca89f6.json");
|
||||
let legacy_cache = serde_json::json!({
|
||||
"schema_version": REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION,
|
||||
"plugins": [],
|
||||
});
|
||||
codex_utils_path::write_atomically(&legacy_cache_path, &legacy_cache.to_string())
|
||||
.expect("write legacy cache");
|
||||
|
||||
let cached = load_cached_directory_plugins::<RemotePluginDirectoryItem>(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
RemotePluginScope::Global,
|
||||
/*collection*/ None,
|
||||
RemotePluginCatalogCacheMode::PreferCache,
|
||||
)
|
||||
.expect("load legacy global cache");
|
||||
assert!(cached.plugins.is_empty());
|
||||
assert_eq!(cached.freshness, RemotePluginCatalogCacheFreshness::Stale);
|
||||
|
||||
write_cached_directory_plugins(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
RemotePluginScope::Global,
|
||||
/*collection*/ None,
|
||||
&[],
|
||||
);
|
||||
assert!(has_cached_directory_plugins(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
RemotePluginScope::Global,
|
||||
RemotePluginCatalogCacheMode::PreferFreshCache,
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freshness_probe_defers_plugin_validation_until_full_read() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let config = RemotePluginServiceConfig::new(
|
||||
"https://chatgpt.com/backend-api".to_string(),
|
||||
crate::test_support::test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let auth = CodexAuth::Headers(AuthHeaders::new(http::HeaderMap::new()));
|
||||
let scope = RemotePluginScope::Global;
|
||||
let key = RemotePluginCatalogCacheKey::new(&config, &auth, scope, /*collection*/ None)
|
||||
.expect("global cache key");
|
||||
let path = cache_path(codex_home.path(), &key);
|
||||
let probe = |mode| has_cached_directory_plugins(codex_home.path(), &config, &auth, scope, mode);
|
||||
let version = REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION;
|
||||
let now = serde_json::to_string(&Utc::now()).expect("serialize timestamp");
|
||||
let expired_at = "2000-01-01T00:00:00Z";
|
||||
let padding = " ".repeat(512);
|
||||
for contents in [
|
||||
serde_json::json!({"schema_version": version + 1, "plugins": []}).to_string(),
|
||||
serde_json::json!({"schema_version": version}).to_string(),
|
||||
serde_json::json!({"schema_version": version, "plugins": {}}).to_string(),
|
||||
format!(r#"{{"schema_version":{version},"plugins":[{{"#),
|
||||
format!(r#"{{"schema_version":{version},"fetched_at":{now},"plugins":[{padding}"#),
|
||||
format!(
|
||||
r#"{{"details":{{"fetched_at":"{expired_at}"}},"schema_version":{version},"plugins":[{padding}"#
|
||||
),
|
||||
format!(
|
||||
r#"{{"schema_version":{version},"fetched_at":"{expired_at}","fetched_at":{now},"plugins":[{padding}"#
|
||||
),
|
||||
format!(
|
||||
r#"{{"schema_version":{version},"fetched_at":"{expired_at}","plugins":{{}}}}{padding}"#
|
||||
),
|
||||
] {
|
||||
codex_utils_path::write_atomically(&path, &contents).expect("write invalid cache");
|
||||
assert!(
|
||||
!probe(RemotePluginCatalogCacheMode::PreferFreshCache),
|
||||
"{contents}"
|
||||
);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
let expired = format!(
|
||||
r#"{{"note":"[","fetched\u005fat":"{expired_at}","schema_version":{version},"plugins":[{padding}"#
|
||||
);
|
||||
codex_utils_path::write_atomically(&path, &expired).expect("write expired cache");
|
||||
assert!(!probe(RemotePluginCatalogCacheMode::PreferFreshCache));
|
||||
assert!(path.exists());
|
||||
assert!(!probe(RemotePluginCatalogCacheMode::PreferCache));
|
||||
assert!(!path.exists());
|
||||
|
||||
let reordered =
|
||||
format!(r#"{{"plugins":[{padding}],"schema_version":{version},"fetched_at":{now}}}"#);
|
||||
codex_utils_path::write_atomically(&path, &reordered).expect("write reordered cache");
|
||||
assert!(probe(RemotePluginCatalogCacheMode::PreferFreshCache));
|
||||
|
||||
let contents = serde_json::json!({
|
||||
"schema_version": version,
|
||||
"fetched_at": Utc::now(),
|
||||
"plugins": [{}],
|
||||
});
|
||||
codex_utils_path::write_atomically(&path, &contents.to_string()).expect("write invalid plugin");
|
||||
assert!(probe(RemotePluginCatalogCacheMode::PreferFreshCache));
|
||||
assert!(
|
||||
load_cached_directory_plugins::<RemotePluginDirectoryItem>(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
scope,
|
||||
/*collection*/ None,
|
||||
RemotePluginCatalogCacheMode::PreferCache,
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_auth_does_not_cache_private_catalogs_without_a_stable_identity() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let config = RemotePluginServiceConfig::new(
|
||||
"https://chatgpt.com/backend-api".to_string(),
|
||||
crate::test_support::test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let auth = CodexAuth::Headers(AuthHeaders::new(http::HeaderMap::new()));
|
||||
|
||||
write_cached_directory_plugins(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
RemotePluginScope::Global,
|
||||
/*collection*/ None,
|
||||
&[],
|
||||
);
|
||||
assert!(
|
||||
load_cached_directory_plugins::<RemotePluginDirectoryItem>(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
RemotePluginScope::Global,
|
||||
/*collection*/ None,
|
||||
RemotePluginCatalogCacheMode::PreferCache,
|
||||
)
|
||||
.is_some()
|
||||
);
|
||||
|
||||
for scope in [RemotePluginScope::User, RemotePluginScope::Workspace] {
|
||||
let insecure_cache_key = RemotePluginCatalogCacheKey {
|
||||
chatgpt_base_url: config.chatgpt_base_url.clone(),
|
||||
account_id: None,
|
||||
chatgpt_user_id: None,
|
||||
is_workspace_account: false,
|
||||
scope: Some(scope),
|
||||
collection: None,
|
||||
};
|
||||
let insecure_cache_path = cache_path(codex_home.path(), &insecure_cache_key);
|
||||
|
||||
write_cached_directory_plugins(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
scope,
|
||||
/*collection*/ None,
|
||||
&[],
|
||||
);
|
||||
assert!(!insecure_cache_path.exists());
|
||||
|
||||
let insecure_cache = RemotePluginCatalogDiskCache {
|
||||
schema_version: REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION,
|
||||
fetched_at: Some(Utc::now()),
|
||||
plugins: Vec::<RemotePluginDirectoryItem>::new(),
|
||||
};
|
||||
let contents = serde_json::to_string_pretty(&insecure_cache).expect("serialize cache");
|
||||
codex_utils_path::write_atomically(&insecure_cache_path, &contents)
|
||||
.expect("write insecure cache");
|
||||
|
||||
assert!(
|
||||
load_cached_directory_plugins::<RemotePluginDirectoryItem>(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
scope,
|
||||
/*collection*/ None,
|
||||
RemotePluginCatalogCacheMode::PreferCache,
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
64
codex-rs/core-plugins/src/remote/plugin_capabilities.rs
Normal file
64
codex-rs/core-plugins/src/remote/plugin_capabilities.rs
Normal file
@@ -0,0 +1,64 @@
|
||||
//! Discovers best-effort runtime invalidation hints from locally cached plugin bundles.
|
||||
//!
|
||||
//! Discovery ignores runtime policy and does not prepare runtime directories. Repeated inclusion
|
||||
//! unions old and new declarations for updates; removals capture declarations before deletion.
|
||||
|
||||
use crate::loader::load_plugin_apps_from_manifest;
|
||||
use crate::loader::load_plugin_hooks;
|
||||
use crate::loader::load_plugin_mcp_servers_from_manifest_with_format;
|
||||
use crate::loader::plugin_skill_roots;
|
||||
use crate::manifest::PluginManifestFormat;
|
||||
use crate::store::PluginStore;
|
||||
use codex_hooks::plugin_hook_declarations;
|
||||
use codex_plugin::PluginId;
|
||||
|
||||
/// Runtime categories affected by a plugin change, before runtime policy filtering.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct RemotePluginCapabilities {
|
||||
pub has_mcps: bool,
|
||||
pub has_apps: bool,
|
||||
pub has_hooks: bool,
|
||||
pub has_skills: bool,
|
||||
}
|
||||
|
||||
impl RemotePluginCapabilities {
|
||||
pub(crate) async fn include_active_bundle(
|
||||
&mut self,
|
||||
store: &PluginStore,
|
||||
plugin_id: &PluginId,
|
||||
) {
|
||||
let Some(root) = store.active_plugin_root(plugin_id) else {
|
||||
return;
|
||||
};
|
||||
let Some(loaded) = store.manifest_cache.load(root.as_path()) else {
|
||||
return;
|
||||
};
|
||||
let paths = &loaded.manifest.paths;
|
||||
self.has_skills |= !plugin_skill_roots(&root, paths, loaded.format).is_empty();
|
||||
self.has_mcps |= !load_plugin_mcp_servers_from_manifest_with_format(
|
||||
root.as_path(),
|
||||
paths,
|
||||
/*plugin_policy*/ None,
|
||||
// Declaration discovery must not create runtime directories or depend on their readiness.
|
||||
/*plugin_data_root*/
|
||||
None,
|
||||
loaded.format,
|
||||
)
|
||||
.await
|
||||
.is_empty();
|
||||
// Agent Plugins can declare Apps through an OpenAI extension even when the local
|
||||
// runtime does not activate them. Refresh hints describe declarations, not activation.
|
||||
self.has_apps |= !load_plugin_apps_from_manifest(root.as_path(), paths)
|
||||
.await
|
||||
.is_empty();
|
||||
if loaded.format == PluginManifestFormat::Legacy {
|
||||
let (sources, _) =
|
||||
load_plugin_hooks(&root, plugin_id, &store.plugin_data_root(plugin_id), paths);
|
||||
self.has_hooks |= !plugin_hook_declarations(&sources).is_empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "plugin_capabilities_tests.rs"]
|
||||
mod tests;
|
||||
158
codex-rs/core-plugins/src/remote/plugin_capabilities_tests.rs
Normal file
158
codex-rs/core-plugins/src/remote/plugin_capabilities_tests.rs
Normal file
@@ -0,0 +1,158 @@
|
||||
//! 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() {
|
||||
let codex_home = TempDir::new().expect("Codex home");
|
||||
let store = PluginStore::new(codex_home.path().to_path_buf());
|
||||
let plugin_id = PluginId::parse("example@test").expect("plugin id");
|
||||
let root = store.plugin_root(&plugin_id, "1.0.0");
|
||||
write_file(
|
||||
root.join("plugin.json").as_path(),
|
||||
&json!({
|
||||
"$schema": AGENT_PLUGIN_SCHEMA_URI,
|
||||
"name": "example",
|
||||
"extensions": {"com.openai": {"apps": "./connectors.json"}},
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
write_file(
|
||||
root.join("mcp.json").as_path(),
|
||||
&json!({
|
||||
"$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
|
||||
"mcpServers": {"example": {"type": "stdio", "command": "echo"}},
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
write_file(
|
||||
root.join("connectors.json").as_path(),
|
||||
&json!({"apps": {"example": {"id": "connector_example"}}}).to_string(),
|
||||
);
|
||||
let data_root = store.mcp_data_root(&plugin_id, PluginManifestFormat::AgentPlugin);
|
||||
|
||||
for block_data_root in [false, true] {
|
||||
if block_data_root {
|
||||
write_file(data_root.as_path(), "not a directory");
|
||||
}
|
||||
let mut capabilities = RemotePluginCapabilities::default();
|
||||
capabilities.include_active_bundle(&store, &plugin_id).await;
|
||||
assert_eq!(
|
||||
capabilities,
|
||||
RemotePluginCapabilities {
|
||||
has_mcps: true,
|
||||
has_apps: true,
|
||||
// Agent Plugins declare a conventional skills root even if it is absent.
|
||||
has_skills: true,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(data_root.as_path().exists(), block_data_root);
|
||||
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(())
|
||||
}
|
||||
986
codex-rs/core-plugins/src/remote/remote_installed_plugin_sync.rs
Normal file
986
codex-rs/core-plugins/src/remote/remote_installed_plugin_sync.rs
Normal file
@@ -0,0 +1,986 @@
|
||||
use super::REMOTE_CREATED_BY_ME_MARKETPLACE_NAME;
|
||||
use super::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use super::REMOTE_WORKSPACE_MARKETPLACE_NAME;
|
||||
use super::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME;
|
||||
use super::REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME;
|
||||
use super::REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME;
|
||||
use super::RemoteInstalledPlugin;
|
||||
use super::RemoteInstalledPluginScope;
|
||||
use super::RemotePluginCapabilities;
|
||||
use super::RemotePluginCatalogError;
|
||||
use super::RemotePluginScope;
|
||||
use super::RemotePluginServiceConfig;
|
||||
use super::RemotePluginShareDiscoverability;
|
||||
use super::ensure_chatgpt_auth;
|
||||
use super::fetch_installed_plugins;
|
||||
use crate::remote::InstalledPluginDisplayAssets;
|
||||
use crate::store::PLUGINS_CACHE_DIR;
|
||||
use crate::store::PluginStore;
|
||||
use crate::store::PluginStoreError;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_plugin::PluginId;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::Weak;
|
||||
use tokio::fs;
|
||||
use tokio::sync::Semaphore;
|
||||
use tracing::warn;
|
||||
|
||||
static REMOTE_INSTALLED_PLUGIN_BUNDLE_SYNC_GATES: OnceLock<
|
||||
Mutex<HashMap<PathBuf, Weak<Semaphore>>>,
|
||||
> = OnceLock::new();
|
||||
static REMOTE_PLUGIN_CACHE_MUTATIONS_IN_FLIGHT: OnceLock<
|
||||
Mutex<HashMap<RemotePluginCacheMutationKey, usize>>,
|
||||
> = OnceLock::new();
|
||||
|
||||
/// A remote plugin bundle newly installed or updated from an authenticated snapshot.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RemotePluginMaterialization {
|
||||
pub plugin_id: PluginId,
|
||||
pub scope: RemotePluginScope,
|
||||
pub discoverability: Option<RemotePluginShareDiscoverability>,
|
||||
pub authenticated_account_id: Option<String>,
|
||||
}
|
||||
|
||||
/// A local plugin and the runtime categories affected by its bundle or installed-state change.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RemotePluginChange {
|
||||
pub plugin_id: String,
|
||||
pub capabilities: RemotePluginCapabilities,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct RemoteInstalledPluginBundleSyncOutcome {
|
||||
/// Internal provenance for materialization-owned hook trust, not runtime change reporting.
|
||||
pub materialized_remote_plugins: Vec<RemotePluginMaterialization>,
|
||||
/// Affected plugins with capabilities from either side of the change, including removals.
|
||||
/// Installed-state removals do not depend on cache cleanup succeeding.
|
||||
pub changed_plugins: Vec<RemotePluginChange>,
|
||||
pub failed_remote_plugin_ids: Vec<String>,
|
||||
/// Failures that leave an otherwise valid installed plugin unavailable locally.
|
||||
pub failed_materialization_remote_plugin_ids: Vec<String>,
|
||||
}
|
||||
|
||||
pub(crate) struct RemoteInstalledPluginBundleSyncResult {
|
||||
pub(crate) outcome: RemoteInstalledPluginBundleSyncOutcome,
|
||||
pub(crate) installed_plugins: Vec<RemoteInstalledPlugin>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RemoteInstalledPluginBundleSyncError {
|
||||
#[error("{0}")]
|
||||
Catalog(#[from] RemotePluginCatalogError),
|
||||
|
||||
#[error("{0}")]
|
||||
Store(#[from] PluginStoreError),
|
||||
|
||||
#[error("timed out waiting for another remote plugin cache mutation; retry")]
|
||||
LockTimeout,
|
||||
|
||||
#[error("remote plugin state changed during reconciliation; retry reconciliation")]
|
||||
Superseded,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
struct RemotePluginCacheMutationKey {
|
||||
plugin_cache_root: PathBuf,
|
||||
marketplace_name: String,
|
||||
plugin_name: String,
|
||||
}
|
||||
|
||||
pub struct RemotePluginCacheMutationGuard {
|
||||
key: RemotePluginCacheMutationKey,
|
||||
}
|
||||
|
||||
pub(crate) fn remote_installed_plugin_bundle_sync_gate(codex_home: &Path) -> Arc<Semaphore> {
|
||||
let plugin_cache_root = remote_plugin_cache_root(codex_home);
|
||||
let gates =
|
||||
REMOTE_INSTALLED_PLUGIN_BUNDLE_SYNC_GATES.get_or_init(|| Mutex::new(HashMap::new()));
|
||||
let mut gates = match gates.lock() {
|
||||
Ok(gates) => gates,
|
||||
Err(err) => err.into_inner(),
|
||||
};
|
||||
if let Some(gate) = gates.get(&plugin_cache_root).and_then(Weak::upgrade) {
|
||||
return gate;
|
||||
}
|
||||
let gate = Arc::new(Semaphore::new(/*permits*/ 1));
|
||||
gates.insert(plugin_cache_root, Arc::downgrade(&gate));
|
||||
gate
|
||||
}
|
||||
|
||||
pub async fn sync_remote_installed_plugin_bundles_once(
|
||||
codex_home: PathBuf,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> Result<RemoteInstalledPluginBundleSyncOutcome, RemoteInstalledPluginBundleSyncError> {
|
||||
let result = sync_remote_installed_plugin_bundles_once_with_snapshot(
|
||||
codex_home,
|
||||
config,
|
||||
auth,
|
||||
/*previous_plugin_ids*/ &[],
|
||||
)
|
||||
.await?;
|
||||
Ok(result.outcome)
|
||||
}
|
||||
|
||||
pub(crate) async fn sync_remote_installed_plugin_bundles_once_with_snapshot(
|
||||
codex_home: PathBuf,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
previous_plugin_ids: &[PluginId],
|
||||
) -> Result<RemoteInstalledPluginBundleSyncResult, RemoteInstalledPluginBundleSyncError> {
|
||||
let auth = ensure_chatgpt_auth(auth)?;
|
||||
let config = &config.for_current_account();
|
||||
let authenticated_account_id = auth.get_account_id();
|
||||
let fetched_installed_plugins = fetch_installed_plugins(
|
||||
config,
|
||||
auth,
|
||||
RemoteInstalledPluginScope::All,
|
||||
/*include_download_urls*/ true,
|
||||
InstalledPluginDisplayAssets::Include,
|
||||
)
|
||||
.await?;
|
||||
// `/installed` is an authoritative full snapshot. If any row cannot be
|
||||
// canonicalized to a local cache key, omitting it makes an installed plugin
|
||||
// indistinguishable from an uninstall, so reject the pass before downloads,
|
||||
// publication, or stale cleanup.
|
||||
let mut validated_installed_plugins = Vec::with_capacity(fetched_installed_plugins.len());
|
||||
for installed_plugin in fetched_installed_plugins {
|
||||
let cached_plugin = super::remote_installed_plugin_to_cache_entry(&installed_plugin)?;
|
||||
let plugin_id = PluginId::new(
|
||||
installed_plugin.plugin.name.clone(),
|
||||
cached_plugin.marketplace_name.clone(),
|
||||
)
|
||||
.map_err(|err| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"remote installed plugin `{}` has an invalid local cache id: {err}",
|
||||
installed_plugin.plugin.id
|
||||
))
|
||||
})?;
|
||||
validated_installed_plugins.push((installed_plugin, cached_plugin, plugin_id));
|
||||
}
|
||||
let store = PluginStore::try_new(codex_home.clone())?;
|
||||
let installed_plugin_ids = validated_installed_plugins
|
||||
.iter()
|
||||
.map(|(_, _, plugin_id)| plugin_id.as_key())
|
||||
.collect::<BTreeSet<_>>();
|
||||
let mut changed_plugins = BTreeMap::new();
|
||||
// Metadata publication removes these plugins even when cleanup fails or partially deletes
|
||||
// a bundle. Capture cached capabilities first so consumers can still invalidate runtimes;
|
||||
// plugins that were never available locally have no previous bundle to invalidate.
|
||||
for plugin_id in previous_plugin_ids {
|
||||
let key = plugin_id.as_key();
|
||||
if installed_plugin_ids.contains(&key) || store.active_plugin_root(plugin_id).is_none() {
|
||||
continue;
|
||||
}
|
||||
let mut capabilities = RemotePluginCapabilities::default();
|
||||
capabilities.include_active_bundle(&store, plugin_id).await;
|
||||
changed_plugins.insert(
|
||||
key.clone(),
|
||||
RemotePluginChange {
|
||||
plugin_id: key,
|
||||
capabilities,
|
||||
},
|
||||
);
|
||||
}
|
||||
let mut installed_plugin_names_by_marketplace =
|
||||
BTreeMap::<String, BTreeSet<String>>::from_iter([
|
||||
(REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(), BTreeSet::new()),
|
||||
(
|
||||
REMOTE_CREATED_BY_ME_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
]);
|
||||
let mut materialized_remote_plugins = BTreeMap::new();
|
||||
let mut failed_remote_plugin_ids = BTreeSet::new();
|
||||
let mut failed_materialization_remote_plugin_ids = BTreeSet::new();
|
||||
let mut installed_plugins = Vec::new();
|
||||
|
||||
for (installed_plugin, cached_plugin, plugin_id) in validated_installed_plugins {
|
||||
let marketplace_name = cached_plugin.marketplace_name.clone();
|
||||
let plugin = installed_plugin.plugin;
|
||||
let scope = plugin.scope;
|
||||
let discoverability = plugin.discoverability;
|
||||
installed_plugin_names_by_marketplace
|
||||
.entry(marketplace_name.clone())
|
||||
.or_default()
|
||||
.insert(plugin.name.clone());
|
||||
let release_version = plugin
|
||||
.release
|
||||
.version
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|version| !version.is_empty());
|
||||
if let Some(release_version) = release_version
|
||||
&& store.active_plugin_version(&plugin_id).as_deref() == Some(release_version)
|
||||
{
|
||||
if let Err(err) = store.write_remote_plugin_id(&plugin_id, &plugin.id) {
|
||||
warn!(
|
||||
remote_plugin_id = %plugin.id,
|
||||
plugin = %plugin.name,
|
||||
marketplace = %marketplace_name,
|
||||
error = %err,
|
||||
"failed to persist identity for cached remote installed plugin"
|
||||
);
|
||||
failed_remote_plugin_ids.insert(plugin.id);
|
||||
}
|
||||
installed_plugins.push(cached_plugin);
|
||||
continue;
|
||||
}
|
||||
|
||||
let bundle = match crate::remote_bundle::validate_remote_plugin_bundle(
|
||||
&plugin.id,
|
||||
&marketplace_name,
|
||||
&plugin.name,
|
||||
release_version,
|
||||
plugin.release.bundle_download_url.as_deref(),
|
||||
plugin.release.app_manifest.clone(),
|
||||
) {
|
||||
Ok(bundle) => bundle,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
remote_plugin_id = %plugin.id,
|
||||
plugin = %plugin.name,
|
||||
marketplace = %marketplace_name,
|
||||
error = %err,
|
||||
"skipping remote installed plugin bundle download"
|
||||
);
|
||||
failed_remote_plugin_ids.insert(plugin.id.clone());
|
||||
failed_materialization_remote_plugin_ids.insert(plugin.id);
|
||||
installed_plugins.push(cached_plugin);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// Read the old bundle before installation replaces it, including capabilities removed
|
||||
// by the new version. Unchanged bundles never reach this metadata-loading path.
|
||||
let mut capabilities = RemotePluginCapabilities::default();
|
||||
capabilities.include_active_bundle(&store, &plugin_id).await;
|
||||
match crate::remote_bundle::download_and_install_remote_plugin_bundle(
|
||||
config,
|
||||
codex_home.clone(),
|
||||
bundle,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(result) => {
|
||||
let plugin_id = result.plugin_id;
|
||||
capabilities.include_active_bundle(&store, &plugin_id).await;
|
||||
changed_plugins.insert(
|
||||
plugin_id.as_key(),
|
||||
RemotePluginChange {
|
||||
plugin_id: plugin_id.as_key(),
|
||||
capabilities,
|
||||
},
|
||||
);
|
||||
materialized_remote_plugins.insert(
|
||||
plugin_id.as_key(),
|
||||
RemotePluginMaterialization {
|
||||
plugin_id,
|
||||
scope,
|
||||
discoverability,
|
||||
authenticated_account_id: authenticated_account_id.clone(),
|
||||
},
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
remote_plugin_id = %plugin.id,
|
||||
plugin = %plugin.name,
|
||||
marketplace = %marketplace_name,
|
||||
error = %err,
|
||||
"failed to download remote installed plugin bundle"
|
||||
);
|
||||
failed_remote_plugin_ids.insert(plugin.id.clone());
|
||||
failed_materialization_remote_plugin_ids.insert(plugin.id);
|
||||
}
|
||||
}
|
||||
installed_plugins.push(cached_plugin);
|
||||
}
|
||||
|
||||
installed_plugins.sort_by(|left, right| {
|
||||
left.marketplace_name
|
||||
.cmp(&right.marketplace_name)
|
||||
.then_with(|| left.id.cmp(&right.id))
|
||||
});
|
||||
let mut removed_cache_plugins = Vec::new();
|
||||
if let Err(err) = remove_stale_remote_plugin_caches(
|
||||
&store,
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed_cache_plugins,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!(error = %err, "failed to remove stale remote plugin cache entries");
|
||||
}
|
||||
for plugin in removed_cache_plugins {
|
||||
changed_plugins
|
||||
.entry(plugin.plugin_id.clone())
|
||||
.or_insert(plugin);
|
||||
}
|
||||
|
||||
Ok(RemoteInstalledPluginBundleSyncResult {
|
||||
outcome: RemoteInstalledPluginBundleSyncOutcome {
|
||||
materialized_remote_plugins: materialized_remote_plugins.into_values().collect(),
|
||||
changed_plugins: changed_plugins.into_values().collect(),
|
||||
failed_remote_plugin_ids: failed_remote_plugin_ids.into_iter().collect(),
|
||||
failed_materialization_remote_plugin_ids: failed_materialization_remote_plugin_ids
|
||||
.into_iter()
|
||||
.collect(),
|
||||
},
|
||||
installed_plugins,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn mark_remote_plugin_cache_mutation_in_flight(
|
||||
codex_home: &Path,
|
||||
marketplace_name: &str,
|
||||
plugin_name: &str,
|
||||
) -> RemotePluginCacheMutationGuard {
|
||||
let key = RemotePluginCacheMutationKey {
|
||||
plugin_cache_root: remote_plugin_cache_root(codex_home),
|
||||
marketplace_name: marketplace_name.to_string(),
|
||||
plugin_name: plugin_name.to_string(),
|
||||
};
|
||||
let mutations =
|
||||
REMOTE_PLUGIN_CACHE_MUTATIONS_IN_FLIGHT.get_or_init(|| Mutex::new(HashMap::new()));
|
||||
let mut mutations = match mutations.lock() {
|
||||
Ok(mutations) => mutations,
|
||||
Err(err) => err.into_inner(),
|
||||
};
|
||||
*mutations.entry(key.clone()).or_default() += 1;
|
||||
RemotePluginCacheMutationGuard { key }
|
||||
}
|
||||
|
||||
impl Drop for RemotePluginCacheMutationGuard {
|
||||
fn drop(&mut self) {
|
||||
let Some(mutations) = REMOTE_PLUGIN_CACHE_MUTATIONS_IN_FLIGHT.get() else {
|
||||
return;
|
||||
};
|
||||
let mut mutations = match mutations.lock() {
|
||||
Ok(mutations) => mutations,
|
||||
Err(err) => err.into_inner(),
|
||||
};
|
||||
if let Some(count) = mutations.get_mut(&self.key) {
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
mutations.remove(&self.key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn remove_stale_remote_plugin_caches(
|
||||
store: &PluginStore,
|
||||
installed_plugin_names_by_marketplace: &BTreeMap<String, BTreeSet<String>>,
|
||||
removed_plugins: &mut Vec<RemotePluginChange>,
|
||||
) -> Result<(), String> {
|
||||
let codex_home = store.codex_home().as_path();
|
||||
for marketplace_name in [
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
REMOTE_CREATED_BY_ME_MARKETPLACE_NAME,
|
||||
REMOTE_WORKSPACE_MARKETPLACE_NAME,
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME,
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME,
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME,
|
||||
] {
|
||||
let marketplace_root = codex_home.join(PLUGINS_CACHE_DIR).join(marketplace_name);
|
||||
if !marketplace_root.exists() {
|
||||
continue;
|
||||
}
|
||||
let installed_plugin_names = installed_plugin_names_by_marketplace
|
||||
.get(marketplace_name)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut entries = fs::read_dir(&marketplace_root).await.map_err(|err| {
|
||||
format!(
|
||||
"failed to read remote plugin cache directory {}: {err}",
|
||||
marketplace_root.display()
|
||||
)
|
||||
})?;
|
||||
while let Some(entry) = entries.next_entry().await.map_err(|err| {
|
||||
format!(
|
||||
"failed to enumerate remote plugin cache directory {}: {err}",
|
||||
marketplace_root.display()
|
||||
)
|
||||
})? {
|
||||
let plugin_name = entry.file_name().into_string().map_err(|file_name| {
|
||||
format!(
|
||||
"remote plugin cache entry under {} is not valid UTF-8: {:?}",
|
||||
marketplace_root.display(),
|
||||
file_name
|
||||
)
|
||||
})?;
|
||||
if installed_plugin_names.contains(&plugin_name) {
|
||||
continue;
|
||||
}
|
||||
if is_remote_plugin_cache_mutation_in_flight(codex_home, marketplace_name, &plugin_name)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let cache_path = entry.path();
|
||||
let plugin_id = PluginId::new(plugin_name.clone(), marketplace_name.to_string());
|
||||
let mut capabilities = RemotePluginCapabilities::default();
|
||||
if let Ok(plugin_id) = &plugin_id {
|
||||
capabilities.include_active_bundle(store, plugin_id).await;
|
||||
}
|
||||
if cache_path.is_dir() {
|
||||
fs::remove_dir_all(&cache_path).await.map_err(|err| {
|
||||
format!(
|
||||
"failed to remove stale remote plugin cache entry {}: {err}",
|
||||
cache_path.display()
|
||||
)
|
||||
})?;
|
||||
} else {
|
||||
fs::remove_file(&cache_path).await.map_err(|err| {
|
||||
format!(
|
||||
"failed to remove stale remote plugin cache entry {}: {err}",
|
||||
cache_path.display()
|
||||
)
|
||||
})?;
|
||||
}
|
||||
let plugin_key = plugin_id
|
||||
.map(|plugin_id| plugin_id.as_key())
|
||||
.unwrap_or_else(|_| format!("{plugin_name}@{marketplace_name}"));
|
||||
removed_plugins.push(RemotePluginChange {
|
||||
plugin_id: plugin_key,
|
||||
capabilities,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remote_plugin_cache_root(codex_home: &Path) -> PathBuf {
|
||||
codex_home.join(PLUGINS_CACHE_DIR)
|
||||
}
|
||||
|
||||
fn is_remote_plugin_cache_mutation_in_flight(
|
||||
codex_home: &Path,
|
||||
marketplace_name: &str,
|
||||
plugin_name: &str,
|
||||
) -> bool {
|
||||
let Some(mutations) = REMOTE_PLUGIN_CACHE_MUTATIONS_IN_FLIGHT.get() else {
|
||||
return false;
|
||||
};
|
||||
let mutations = match mutations.lock() {
|
||||
Ok(mutations) => mutations,
|
||||
Err(err) => err.into_inner(),
|
||||
};
|
||||
mutations.contains_key(&RemotePluginCacheMutationKey {
|
||||
plugin_cache_root: remote_plugin_cache_root(codex_home),
|
||||
marketplace_name: marketplace_name.to_string(),
|
||||
plugin_name: plugin_name.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
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() {
|
||||
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"}"#)
|
||||
.expect("write cached plugin manifest");
|
||||
let installed_plugin_names_by_marketplace =
|
||||
BTreeMap::<String, BTreeSet<String>>::from_iter([
|
||||
(REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(), BTreeSet::new()),
|
||||
(
|
||||
REMOTE_WORKSPACE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
]);
|
||||
|
||||
let guard = mark_remote_plugin_cache_mutation_in_flight(
|
||||
codex_home.path(),
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
"linear",
|
||||
);
|
||||
let second_guard = mark_remote_plugin_cache_mutation_in_flight(
|
||||
codex_home.path(),
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
"linear",
|
||||
);
|
||||
let mut removed = Vec::new();
|
||||
remove_stale_remote_plugin_caches(
|
||||
&PluginStore::new(codex_home.path().to_path_buf()),
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed,
|
||||
)
|
||||
.await
|
||||
.expect("cleanup while install is guarded");
|
||||
assert_eq!(removed, Vec::<RemotePluginChange>::new());
|
||||
assert!(cached_manifest.is_file());
|
||||
|
||||
drop(guard);
|
||||
let mut removed = Vec::new();
|
||||
remove_stale_remote_plugin_caches(
|
||||
&PluginStore::new(codex_home.path().to_path_buf()),
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed,
|
||||
)
|
||||
.await
|
||||
.expect("cleanup while second install guard is still active");
|
||||
assert_eq!(removed, Vec::<RemotePluginChange>::new());
|
||||
assert!(cached_manifest.is_file());
|
||||
|
||||
drop(second_guard);
|
||||
let mut removed = Vec::new();
|
||||
remove_stale_remote_plugin_caches(
|
||||
&PluginStore::new(codex_home.path().to_path_buf()),
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed,
|
||||
)
|
||||
.await
|
||||
.expect("cleanup after install guard is dropped");
|
||||
assert_eq!(
|
||||
removed,
|
||||
vec![RemotePluginChange {
|
||||
plugin_id: "linear@openai-curated-remote".to_string(),
|
||||
capabilities: RemotePluginCapabilities::default(),
|
||||
}]
|
||||
);
|
||||
assert!(!cached_manifest.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stale_remote_plugin_cleanup_removes_stale_marketplace_caches_and_keeps_canonical_cache()
|
||||
{
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let created_by_me_cached_manifest = codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(REMOTE_CREATED_BY_ME_MARKETPLACE_NAME)
|
||||
.join("created-by-me-plugin")
|
||||
.join("1.2.3")
|
||||
.join(".codex-plugin")
|
||||
.join("plugin.json");
|
||||
std::fs::create_dir_all(
|
||||
created_by_me_cached_manifest
|
||||
.parent()
|
||||
.expect("manifest parent"),
|
||||
)
|
||||
.expect("create cached plugin manifest parent");
|
||||
std::fs::write(
|
||||
&created_by_me_cached_manifest,
|
||||
r#"{"name":"created-by-me-plugin"}"#,
|
||||
)
|
||||
.expect("write cached plugin manifest");
|
||||
let cached_manifest = codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME)
|
||||
.join("private-plugin")
|
||||
.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":"private-plugin"}"#)
|
||||
.expect("write cached plugin manifest");
|
||||
let canonical_cached_manifest = codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME)
|
||||
.join("shared-plugin")
|
||||
.join("1.2.3")
|
||||
.join(".codex-plugin")
|
||||
.join("plugin.json");
|
||||
std::fs::create_dir_all(canonical_cached_manifest.parent().expect("manifest parent"))
|
||||
.expect("create canonical cached plugin manifest parent");
|
||||
std::fs::write(&canonical_cached_manifest, r#"{"name":"shared-plugin"}"#)
|
||||
.expect("write canonical cached plugin manifest");
|
||||
let installed_plugin_names_by_marketplace =
|
||||
BTreeMap::<String, BTreeSet<String>>::from_iter([
|
||||
(REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(), BTreeSet::new()),
|
||||
(
|
||||
REMOTE_CREATED_BY_ME_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::from(["shared-plugin".to_string()]),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
]);
|
||||
|
||||
let mut removed = Vec::new();
|
||||
remove_stale_remote_plugin_caches(
|
||||
&PluginStore::new(codex_home.path().to_path_buf()),
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed,
|
||||
)
|
||||
.await
|
||||
.expect("cleanup private shared-with-me cache");
|
||||
|
||||
assert_eq!(
|
||||
removed,
|
||||
[
|
||||
"created-by-me-plugin@created-by-me-remote",
|
||||
"private-plugin@workspace-shared-with-me-private",
|
||||
]
|
||||
.map(|plugin_id| RemotePluginChange {
|
||||
plugin_id: plugin_id.to_string(),
|
||||
capabilities: RemotePluginCapabilities::default(),
|
||||
})
|
||||
.to_vec()
|
||||
);
|
||||
assert!(!created_by_me_cached_manifest.exists());
|
||||
assert!(!cached_manifest.exists());
|
||||
assert!(canonical_cached_manifest.is_file());
|
||||
}
|
||||
}
|
||||
91
codex-rs/core-plugins/src/remote/search.rs
Normal file
91
codex-rs/core-plugins/src/remote/search.rs
Normal file
@@ -0,0 +1,91 @@
|
||||
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)]
|
||||
pub struct RemotePluginSearchRequest<'a> {
|
||||
pub query: &'a str,
|
||||
pub scope: Option<RemotePluginScope>,
|
||||
pub limit: u32,
|
||||
pub page_token: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// One uncached page of remote plugin search results.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct RemotePluginSearchPage {
|
||||
pub plugins: Vec<RemotePluginSummary>,
|
||||
pub next_page_token: Option<String>,
|
||||
}
|
||||
|
||||
/// Searches plugin-service without reading or populating the remote catalog cache.
|
||||
#[instrument(
|
||||
level = "debug",
|
||||
skip_all,
|
||||
fields(plugin.scope = ?search.scope, plugin.limit = search.limit)
|
||||
)]
|
||||
pub async fn search_remote_plugins(
|
||||
config: &RemotePluginServiceConfig,
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "search_tests.rs"]
|
||||
mod tests;
|
||||
490
codex-rs/core-plugins/src/remote/search_tests.rs
Normal file
490
codex-rs/core-plugins/src/remote/search_tests.rs
Normal file
@@ -0,0 +1,490 @@
|
||||
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 { .. })
|
||||
));
|
||||
}
|
||||
536
codex-rs/core-plugins/src/remote/share.rs
Normal file
536
codex-rs/core-plugins/src/remote/share.rs
Normal file
@@ -0,0 +1,536 @@
|
||||
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)]
|
||||
pub struct RemotePluginShareSaveResult {
|
||||
pub remote_plugin_id: String,
|
||||
pub share_url: Option<String>,
|
||||
pub can_publish_to_workspace: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct RemotePluginShareAccessPolicy {
|
||||
pub discoverability: Option<RemotePluginShareDiscoverability>,
|
||||
pub share_targets: Option<Vec<RemotePluginShareTarget>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||
pub enum RemotePluginShareDiscoverability {
|
||||
Listed,
|
||||
Unlisted,
|
||||
Private,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||
pub enum RemotePluginShareUpdateDiscoverability {
|
||||
Listed,
|
||||
Unlisted,
|
||||
Private,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum RemotePluginSharePrincipalType {
|
||||
User,
|
||||
Group,
|
||||
Workspace,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct RemotePluginShareTarget {
|
||||
pub principal_type: RemotePluginSharePrincipalType,
|
||||
pub principal_id: String,
|
||||
pub role: RemotePluginShareTargetRole,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
pub struct RemotePluginSharePrincipal {
|
||||
pub principal_type: RemotePluginSharePrincipalType,
|
||||
pub principal_id: String,
|
||||
pub role: RemotePluginSharePrincipalRole,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum RemotePluginShareTargetRole {
|
||||
Reader,
|
||||
Editor,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum RemotePluginSharePrincipalRole {
|
||||
Reader,
|
||||
Editor,
|
||||
Owner,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RemotePluginShareUpdateTargetsResult {
|
||||
pub principals: Vec<RemotePluginSharePrincipal>,
|
||||
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>,
|
||||
codex_home: &Path,
|
||||
plugin_path: &AbsolutePathBuf,
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn list_remote_plugin_shares(
|
||||
config: &RemotePluginServiceConfig,
|
||||
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()
|
||||
}
|
||||
|
||||
pub fn load_plugin_share_remote_ids_by_local_path(
|
||||
codex_home: &Path,
|
||||
) -> io::Result<BTreeMap<AbsolutePathBuf, String>> {
|
||||
let local_paths = local_paths::load_plugin_share_local_paths(codex_home)?;
|
||||
local_paths
|
||||
.into_iter()
|
||||
.map(|(remote_plugin_id, local_plugin_path)| {
|
||||
if !is_valid_remote_plugin_id(&remote_plugin_id) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"invalid remote plugin id in share local path mapping: {remote_plugin_id}"
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok((local_plugin_path, remote_plugin_id))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn delete_remote_plugin_share(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
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(())
|
||||
}
|
||||
|
||||
pub async fn update_remote_plugin_share_targets(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
remote_plugin_id: &str,
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
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;
|
||||
472
codex-rs/core-plugins/src/remote/share/checkout.rs
Normal file
472
codex-rs/core-plugins/src/remote/share/checkout.rs
Normal file
@@ -0,0 +1,472 @@
|
||||
use super::super::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME;
|
||||
use super::super::REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME;
|
||||
use super::super::REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME;
|
||||
use super::super::RemotePluginCatalogError;
|
||||
use super::super::RemotePluginServiceConfig;
|
||||
use super::local_paths;
|
||||
use codex_app_server_protocol::PluginAuthPolicy;
|
||||
use codex_app_server_protocol::PluginInstallPolicy;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_plugin::validate_plugin_segment;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde_json::Value as JsonValue;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
|
||||
const PERSONAL_MARKETPLACE_NAME: &str = "codex-curated";
|
||||
const PERSONAL_MARKETPLACE_DISPLAY_NAME: &str = "Personal";
|
||||
const PERSONAL_MARKETPLACE_RELATIVE_PATH: &str = ".agents/plugins/marketplace.json";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RemotePluginShareCheckoutResult {
|
||||
pub remote_plugin_id: String,
|
||||
pub plugin_id: String,
|
||||
pub plugin_name: String,
|
||||
pub plugin_path: AbsolutePathBuf,
|
||||
pub marketplace_name: String,
|
||||
pub marketplace_path: AbsolutePathBuf,
|
||||
pub remote_version: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn checkout_remote_plugin_share(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
codex_home: &Path,
|
||||
remote_plugin_id: &str,
|
||||
) -> Result<RemotePluginShareCheckoutResult, RemotePluginCatalogError> {
|
||||
let config = &config.for_current_account();
|
||||
let detail = super::super::fetch_remote_plugin_detail_with_download_urls(
|
||||
config,
|
||||
auth,
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME,
|
||||
remote_plugin_id,
|
||||
)
|
||||
.await?;
|
||||
let plugin_name = detail.summary.name.clone();
|
||||
let remote_version = detail.release_version.clone();
|
||||
validate_plugin_segment(&plugin_name, "plugin name").map_err(|reason| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"remote plugin `{remote_plugin_id}` returned invalid plugin name: {reason}"
|
||||
))
|
||||
})?;
|
||||
if !is_checkout_supported_share_marketplace(&detail.marketplace_name)
|
||||
|| detail.summary.share_context.is_none()
|
||||
{
|
||||
return Err(RemotePluginCatalogError::PluginShareCheckoutNotAvailable {
|
||||
remote_plugin_id: remote_plugin_id.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let home = crate::marketplace::home_dir().ok_or_else(|| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(
|
||||
"could not determine home directory for personal plugin marketplace".to_string(),
|
||||
)
|
||||
})?;
|
||||
let home = AbsolutePathBuf::try_from(home).map_err(|err| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to resolve home directory for personal plugin marketplace: {err}"
|
||||
))
|
||||
})?;
|
||||
|
||||
let local_paths = load_share_local_paths_for_checkout(codex_home)?;
|
||||
let (local_plugin_path, already_checked_out) =
|
||||
editable_plugin_path_for_checkout(&home, &plugin_name, remote_plugin_id, &local_paths)?;
|
||||
|
||||
let mut created_checkout_path = false;
|
||||
if !already_checked_out {
|
||||
let bundle = crate::remote_bundle::validate_remote_plugin_bundle(
|
||||
remote_plugin_id,
|
||||
&detail.marketplace_name,
|
||||
&plugin_name,
|
||||
detail.release_version.as_deref(),
|
||||
detail.bundle_download_url.as_deref(),
|
||||
/*app_manifest*/ None,
|
||||
)
|
||||
.map_err(|err| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to prepare remote plugin bundle checkout: {err}"
|
||||
))
|
||||
})?;
|
||||
crate::remote_bundle::download_and_extract_remote_plugin_bundle_to_path(
|
||||
config,
|
||||
bundle,
|
||||
local_plugin_path.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to check out remote plugin bundle: {err}"
|
||||
))
|
||||
})?;
|
||||
created_checkout_path = true;
|
||||
}
|
||||
|
||||
let marketplace = match update_personal_marketplace(
|
||||
&home,
|
||||
&plugin_name,
|
||||
&local_plugin_path,
|
||||
detail.summary.install_policy,
|
||||
detail.summary.auth_policy,
|
||||
detail
|
||||
.summary
|
||||
.interface
|
||||
.as_ref()
|
||||
.and_then(|interface| interface.category.clone()),
|
||||
) {
|
||||
Ok(marketplace) => marketplace,
|
||||
Err(err) => {
|
||||
return Err(clean_up_created_checkout_path(
|
||||
created_checkout_path,
|
||||
&local_plugin_path,
|
||||
err,
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(err) = local_paths::record_plugin_share_local_path(
|
||||
codex_home,
|
||||
remote_plugin_id,
|
||||
local_plugin_path.clone(),
|
||||
) {
|
||||
let err = RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to record plugin share local path mapping: {err}"
|
||||
));
|
||||
return Err(clean_up_created_checkout_path(
|
||||
created_checkout_path,
|
||||
&local_plugin_path,
|
||||
err,
|
||||
));
|
||||
}
|
||||
|
||||
let plugin_id = PluginId::new(plugin_name.clone(), marketplace.name.clone())
|
||||
.map_err(|err| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to build checked out plugin id: {err}"
|
||||
))
|
||||
})?
|
||||
.as_key();
|
||||
|
||||
Ok(RemotePluginShareCheckoutResult {
|
||||
remote_plugin_id: remote_plugin_id.to_string(),
|
||||
plugin_id,
|
||||
plugin_name,
|
||||
plugin_path: local_plugin_path,
|
||||
marketplace_name: marketplace.name,
|
||||
marketplace_path: marketplace.path,
|
||||
remote_version,
|
||||
})
|
||||
}
|
||||
|
||||
fn is_checkout_supported_share_marketplace(marketplace_name: &str) -> bool {
|
||||
matches!(
|
||||
marketplace_name,
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME
|
||||
| REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME
|
||||
| REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME
|
||||
)
|
||||
}
|
||||
|
||||
fn load_share_local_paths_for_checkout(
|
||||
codex_home: &Path,
|
||||
) -> Result<BTreeMap<String, AbsolutePathBuf>, RemotePluginCatalogError> {
|
||||
match local_paths::load_plugin_share_local_paths(codex_home) {
|
||||
Ok(paths) => Ok(paths),
|
||||
Err(err) if err.kind() == io::ErrorKind::InvalidData => Ok(BTreeMap::new()),
|
||||
Err(err) => Err(RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to load plugin share local path mapping: {err}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn editable_plugin_path_for_checkout(
|
||||
home: &AbsolutePathBuf,
|
||||
plugin_name: &str,
|
||||
remote_plugin_id: &str,
|
||||
local_paths: &BTreeMap<String, AbsolutePathBuf>,
|
||||
) -> Result<(AbsolutePathBuf, bool), RemotePluginCatalogError> {
|
||||
if let Some(existing_path) = local_paths.get(remote_plugin_id)
|
||||
&& existing_path.as_path().exists()
|
||||
{
|
||||
ensure_path_can_be_listed_in_personal_marketplace(home, existing_path)?;
|
||||
return Ok((existing_path.clone(), true));
|
||||
}
|
||||
|
||||
let local_plugin_path = local_paths
|
||||
.get(remote_plugin_id)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| home.join("plugins").join(plugin_name));
|
||||
ensure_path_can_be_listed_in_personal_marketplace(home, &local_plugin_path)?;
|
||||
|
||||
if local_plugin_path.as_path().exists() {
|
||||
return Err(RemotePluginCatalogError::InvalidPluginPath {
|
||||
path: local_plugin_path.to_path_buf(),
|
||||
reason: format!(
|
||||
"cannot check out remote plugin `{remote_plugin_id}` because the local plugin path already exists"
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
Ok((local_plugin_path, false))
|
||||
}
|
||||
|
||||
fn clean_up_created_checkout_path(
|
||||
created_checkout_path: bool,
|
||||
local_plugin_path: &AbsolutePathBuf,
|
||||
original_err: RemotePluginCatalogError,
|
||||
) -> RemotePluginCatalogError {
|
||||
if !created_checkout_path {
|
||||
return original_err;
|
||||
}
|
||||
|
||||
match remove_created_checkout_path(local_plugin_path) {
|
||||
Ok(()) => original_err,
|
||||
Err(cleanup_err) => RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"{original_err}; additionally failed to clean up checked out plugin path `{}`: {cleanup_err}",
|
||||
local_plugin_path.display()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_created_checkout_path(local_plugin_path: &AbsolutePathBuf) -> io::Result<()> {
|
||||
if local_plugin_path.as_path().is_dir() {
|
||||
fs::remove_dir_all(local_plugin_path.as_path())
|
||||
} else {
|
||||
fs::remove_file(local_plugin_path.as_path())
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_path_can_be_listed_in_personal_marketplace(
|
||||
home: &AbsolutePathBuf,
|
||||
path: &AbsolutePathBuf,
|
||||
) -> Result<(), RemotePluginCatalogError> {
|
||||
personal_marketplace_relative_plugin_path(home, path).map(|_| ())
|
||||
}
|
||||
|
||||
struct PersonalMarketplaceUpdate {
|
||||
name: String,
|
||||
path: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
fn update_personal_marketplace(
|
||||
home: &AbsolutePathBuf,
|
||||
plugin_name: &str,
|
||||
local_plugin_path: &AbsolutePathBuf,
|
||||
install_policy: PluginInstallPolicy,
|
||||
auth_policy: PluginAuthPolicy,
|
||||
category: Option<String>,
|
||||
) -> Result<PersonalMarketplaceUpdate, RemotePluginCatalogError> {
|
||||
let marketplace_path = home.join(PERSONAL_MARKETPLACE_RELATIVE_PATH);
|
||||
let relative_plugin_path = personal_marketplace_relative_plugin_path(home, local_plugin_path)?;
|
||||
let mut marketplace = read_or_create_personal_marketplace(marketplace_path.as_path())?;
|
||||
let Some(marketplace_object) = marketplace.as_object_mut() else {
|
||||
return Err(invalid_marketplace_file(
|
||||
marketplace_path.as_path(),
|
||||
"personal marketplace file must contain a JSON object",
|
||||
));
|
||||
};
|
||||
let marketplace_name = marketplace_object
|
||||
.entry("name")
|
||||
.or_insert_with(|| json!(PERSONAL_MARKETPLACE_NAME))
|
||||
.as_str()
|
||||
.ok_or_else(|| {
|
||||
invalid_marketplace_file(
|
||||
marketplace_path.as_path(),
|
||||
"marketplace name must be a string",
|
||||
)
|
||||
})?
|
||||
.to_string();
|
||||
validate_plugin_segment(&marketplace_name, "marketplace name").map_err(|reason| {
|
||||
invalid_marketplace_file(
|
||||
marketplace_path.as_path(),
|
||||
&format!("marketplace name is invalid: {reason}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let plugins = marketplace_object
|
||||
.entry("plugins")
|
||||
.or_insert_with(|| json!([]))
|
||||
.as_array_mut()
|
||||
.ok_or_else(|| {
|
||||
invalid_marketplace_file(
|
||||
marketplace_path.as_path(),
|
||||
"marketplace plugins must be an array",
|
||||
)
|
||||
})?;
|
||||
|
||||
let new_entry = personal_marketplace_plugin_entry(
|
||||
plugin_name,
|
||||
&relative_plugin_path,
|
||||
install_policy,
|
||||
auth_policy,
|
||||
category,
|
||||
);
|
||||
|
||||
if let Some(existing_entry) = plugins
|
||||
.iter_mut()
|
||||
.find(|entry| entry.get("name").and_then(JsonValue::as_str) == Some(plugin_name))
|
||||
{
|
||||
let existing_path = existing_entry
|
||||
.get("source")
|
||||
.and_then(|source| source.get("path"))
|
||||
.and_then(JsonValue::as_str);
|
||||
if existing_path != Some(relative_plugin_path.as_str()) {
|
||||
return Err(invalid_marketplace_file(
|
||||
marketplace_path.as_path(),
|
||||
&format!(
|
||||
"marketplace already contains plugin `{plugin_name}` with a different source path"
|
||||
),
|
||||
));
|
||||
}
|
||||
*existing_entry = new_entry;
|
||||
} else {
|
||||
plugins.push(new_entry);
|
||||
}
|
||||
|
||||
let contents = serde_json::to_string_pretty(&marketplace)
|
||||
.map_err(|err| RemotePluginCatalogError::UnexpectedResponse(err.to_string()))?;
|
||||
write_json_atomically(marketplace_path.as_path(), &format!("{contents}\n")).map_err(|err| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to update personal plugin marketplace: {err}"
|
||||
))
|
||||
})?;
|
||||
|
||||
Ok(PersonalMarketplaceUpdate {
|
||||
name: marketplace_name,
|
||||
path: marketplace_path,
|
||||
})
|
||||
}
|
||||
|
||||
fn read_or_create_personal_marketplace(
|
||||
marketplace_path: &Path,
|
||||
) -> Result<JsonValue, RemotePluginCatalogError> {
|
||||
match std::fs::read_to_string(marketplace_path) {
|
||||
Ok(contents) => serde_json::from_str(&contents).map_err(|err| {
|
||||
invalid_marketplace_file(
|
||||
marketplace_path,
|
||||
&format!("failed to parse personal marketplace file: {err}"),
|
||||
)
|
||||
}),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(json!({
|
||||
"name": PERSONAL_MARKETPLACE_NAME,
|
||||
"interface": {
|
||||
"displayName": PERSONAL_MARKETPLACE_DISPLAY_NAME,
|
||||
},
|
||||
"plugins": [],
|
||||
})),
|
||||
Err(err) => Err(RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to read personal plugin marketplace: {err}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn personal_marketplace_plugin_entry(
|
||||
plugin_name: &str,
|
||||
relative_plugin_path: &str,
|
||||
install_policy: PluginInstallPolicy,
|
||||
auth_policy: PluginAuthPolicy,
|
||||
category: Option<String>,
|
||||
) -> JsonValue {
|
||||
let mut entry = json!({
|
||||
"name": plugin_name,
|
||||
"source": {
|
||||
"source": "local",
|
||||
"path": relative_plugin_path,
|
||||
},
|
||||
"policy": {
|
||||
"installation": plugin_install_policy_value(install_policy),
|
||||
"authentication": plugin_auth_policy_value(auth_policy),
|
||||
},
|
||||
});
|
||||
if let Some(category) = category
|
||||
&& !category.trim().is_empty()
|
||||
&& let Some(object) = entry.as_object_mut()
|
||||
{
|
||||
object.insert("category".to_string(), json!(category));
|
||||
}
|
||||
entry
|
||||
}
|
||||
|
||||
fn plugin_install_policy_value(policy: PluginInstallPolicy) -> &'static str {
|
||||
match policy {
|
||||
PluginInstallPolicy::NotAvailable => "NOT_AVAILABLE",
|
||||
PluginInstallPolicy::Available => "AVAILABLE",
|
||||
PluginInstallPolicy::InstalledByDefault => "INSTALLED_BY_DEFAULT",
|
||||
}
|
||||
}
|
||||
|
||||
fn plugin_auth_policy_value(policy: PluginAuthPolicy) -> &'static str {
|
||||
match policy {
|
||||
PluginAuthPolicy::OnInstall => "ON_INSTALL",
|
||||
PluginAuthPolicy::OnUse => "ON_USE",
|
||||
}
|
||||
}
|
||||
|
||||
fn personal_marketplace_relative_plugin_path(
|
||||
home: &AbsolutePathBuf,
|
||||
local_plugin_path: &AbsolutePathBuf,
|
||||
) -> Result<String, RemotePluginCatalogError> {
|
||||
let relative = local_plugin_path
|
||||
.as_path()
|
||||
.strip_prefix(home.as_path())
|
||||
.map_err(|_| RemotePluginCatalogError::InvalidPluginPath {
|
||||
path: local_plugin_path.to_path_buf(),
|
||||
reason: "local plugin path must be inside the home directory to be listed in the personal marketplace".to_string(),
|
||||
})?;
|
||||
let mut segments = Vec::new();
|
||||
for component in relative.components() {
|
||||
match component {
|
||||
Component::Normal(segment) => {
|
||||
let segment = segment.to_str().ok_or_else(|| {
|
||||
RemotePluginCatalogError::InvalidPluginPath {
|
||||
path: local_plugin_path.to_path_buf(),
|
||||
reason: "local plugin path contains non-UTF-8 segments".to_string(),
|
||||
}
|
||||
})?;
|
||||
segments.push(segment.to_string());
|
||||
}
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
|
||||
return Err(RemotePluginCatalogError::InvalidPluginPath {
|
||||
path: local_plugin_path.to_path_buf(),
|
||||
reason:
|
||||
"local plugin path cannot be represented as a personal marketplace path"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if segments.is_empty() {
|
||||
return Err(RemotePluginCatalogError::InvalidPluginPath {
|
||||
path: local_plugin_path.to_path_buf(),
|
||||
reason: "local plugin path must not be the home directory".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(format!("./{}", segments.join("/")))
|
||||
}
|
||||
|
||||
fn invalid_marketplace_file(path: &Path, message: &str) -> RemotePluginCatalogError {
|
||||
RemotePluginCatalogError::InvalidPluginPath {
|
||||
path: path.to_path_buf(),
|
||||
reason: message.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_json_atomically(write_path: &Path, contents: &str) -> io::Result<()> {
|
||||
let parent = write_path.parent().ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("path {} has no parent directory", write_path.display()),
|
||||
)
|
||||
})?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
|
||||
tmp.write_all(contents.as_bytes())?;
|
||||
tmp.persist(write_path).map_err(|err| err.error)?;
|
||||
Ok(())
|
||||
}
|
||||
124
codex-rs/core-plugins/src/remote/share/local_paths.rs
Normal file
124
codex-rs/core-plugins/src/remote/share/local_paths.rs
Normal file
@@ -0,0 +1,124 @@
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const PLUGIN_SHARE_LOCAL_PATHS_FILE: &str = ".tmp/plugin-share-local-paths-v1.json";
|
||||
static PLUGIN_SHARE_LOCAL_PATHS_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct PluginShareLocalPaths {
|
||||
#[serde(default)]
|
||||
local_plugin_paths_by_remote_plugin_id: BTreeMap<String, AbsolutePathBuf>,
|
||||
}
|
||||
|
||||
pub(crate) fn load_plugin_share_local_paths(
|
||||
codex_home: &Path,
|
||||
) -> io::Result<BTreeMap<String, AbsolutePathBuf>> {
|
||||
let _guard = lock_plugin_share_local_paths()?;
|
||||
read_plugin_share_local_paths(codex_home)
|
||||
}
|
||||
|
||||
pub(crate) fn record_plugin_share_local_path(
|
||||
codex_home: &Path,
|
||||
remote_plugin_id: &str,
|
||||
plugin_path: AbsolutePathBuf,
|
||||
) -> io::Result<()> {
|
||||
let _guard = lock_plugin_share_local_paths()?;
|
||||
let mut mapping = read_plugin_share_local_paths_for_update(codex_home)?;
|
||||
mapping.insert(remote_plugin_id.to_string(), plugin_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()
|
||||
.map_err(|err| io::Error::other(format!("plugin share local path lock poisoned: {err}")))
|
||||
}
|
||||
|
||||
fn read_plugin_share_local_paths(
|
||||
codex_home: &Path,
|
||||
) -> io::Result<BTreeMap<String, AbsolutePathBuf>> {
|
||||
let path = plugin_share_local_paths_path(codex_home);
|
||||
let contents = match std::fs::read_to_string(&path) {
|
||||
Ok(contents) => contents,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
|
||||
let mapping = serde_json::from_str::<PluginShareLocalPaths>(&contents).map_err(|err| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"failed to parse plugin share local path mapping {}: {err}",
|
||||
path.display()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
Ok(mapping.local_plugin_paths_by_remote_plugin_id)
|
||||
}
|
||||
|
||||
fn read_plugin_share_local_paths_for_update(
|
||||
codex_home: &Path,
|
||||
) -> io::Result<BTreeMap<String, AbsolutePathBuf>> {
|
||||
match read_plugin_share_local_paths(codex_home) {
|
||||
Ok(mapping) => Ok(mapping),
|
||||
// This is a best-effort cache under .tmp, so malformed state should not
|
||||
// permanently block future share saves or deletes.
|
||||
Err(err) if err.kind() == io::ErrorKind::InvalidData => Ok(BTreeMap::new()),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_plugin_share_local_paths(
|
||||
codex_home: &Path,
|
||||
mapping: BTreeMap<String, AbsolutePathBuf>,
|
||||
) -> io::Result<()> {
|
||||
let path = plugin_share_local_paths_path(codex_home);
|
||||
if mapping.is_empty() {
|
||||
match std::fs::remove_file(&path) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
let contents = serde_json::to_string_pretty(&PluginShareLocalPaths {
|
||||
local_plugin_paths_by_remote_plugin_id: mapping,
|
||||
})
|
||||
.map_err(io::Error::other)?;
|
||||
write_atomically(&path, &format!("{contents}\n"))
|
||||
}
|
||||
|
||||
fn write_atomically(write_path: &Path, contents: &str) -> io::Result<()> {
|
||||
let parent = write_path.parent().ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("path {} has no parent directory", write_path.display()),
|
||||
)
|
||||
})?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
|
||||
tmp.write_all(contents.as_bytes())?;
|
||||
tmp.persist(write_path).map_err(|err| err.error)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn plugin_share_local_paths_path(codex_home: &Path) -> std::path::PathBuf {
|
||||
codex_home.join(PLUGIN_SHARE_LOCAL_PATHS_FILE)
|
||||
}
|
||||
824
codex-rs/core-plugins/src/remote/share/tests.rs
Normal file
824
codex-rs/core-plugins/src/remote/share/tests.rs
Normal file
@@ -0,0 +1,824 @@
|
||||
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:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user