README: aKode (stato del lavoro, build, configurazione endpoint locale, licenza)
Some checks failed
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled
Some checks failed
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled
This commit is contained in:
@@ -1,472 +0,0 @@
|
||||
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(())
|
||||
}
|
||||
@@ -1,995 +0,0 @@
|
||||
use crate::error_subtype::http_status_sub_error_type;
|
||||
use crate::plugin_bundle_archive::PluginBundleUnpackError;
|
||||
use crate::plugin_bundle_archive::unpack_plugin_bundle_tar_gz;
|
||||
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use crate::remote::RemotePluginServiceConfig;
|
||||
use crate::store::PluginInstallResult;
|
||||
use crate::store::PluginStore;
|
||||
use crate::store::PluginStoreError;
|
||||
use crate::store::error_context_sub_error_type;
|
||||
use crate::store::validate_plugin_version_segment;
|
||||
use codex_http_client::RouteAwareRequestError;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_plugin::PluginIdError;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_plugins::AGENT_PLUGIN_MANIFEST_RELATIVE_PATH;
|
||||
use codex_utils_plugins::AgentPluginSchemaStatus;
|
||||
use codex_utils_plugins::agent_plugin_schema_status;
|
||||
use codex_utils_plugins::find_plugin_manifest_path;
|
||||
use http::StatusCode;
|
||||
use serde_json::Value as JsonValue;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use url::Host;
|
||||
use url::Url;
|
||||
|
||||
const REMOTE_PLUGIN_BUNDLE_MAX_DOWNLOAD_BYTES: u64 = 100 * 1024 * 1024;
|
||||
const REMOTE_PLUGIN_BUNDLE_MAX_EXTRACTED_BYTES: u64 = 512 * 1024 * 1024;
|
||||
const REMOTE_PLUGIN_INSTALL_STAGING_DIR: &str = "plugins/.remote-plugin-install-staging";
|
||||
#[cfg(debug_assertions)]
|
||||
const TEST_ALLOW_LOOPBACK_HTTP_REMOTE_PLUGIN_BUNDLES_ENV: &str =
|
||||
"CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ValidatedRemotePluginBundle {
|
||||
pub plugin_id: PluginId,
|
||||
pub plugin_version: String,
|
||||
remote_plugin_id: String,
|
||||
app_manifest: Option<JsonValue>,
|
||||
bundle_download_url: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ValidatedRemotePluginBundle {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("ValidatedRemotePluginBundle")
|
||||
.field("plugin_id", &self.plugin_id)
|
||||
.field("plugin_version", &self.plugin_version)
|
||||
.field("remote_plugin_id", &self.remote_plugin_id)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RemotePluginBundleInstallError {
|
||||
#[error("remote plugin bundles are not available in aKode")]
|
||||
Unavailable,
|
||||
|
||||
#[error("backend did not return a release version for remote plugin `{remote_plugin_id}`")]
|
||||
MissingReleaseVersion { remote_plugin_id: String },
|
||||
|
||||
#[error(
|
||||
"backend returned an invalid release version for remote plugin `{remote_plugin_id}`: {message}"
|
||||
)]
|
||||
InvalidReleaseVersion {
|
||||
remote_plugin_id: String,
|
||||
message: String,
|
||||
},
|
||||
|
||||
#[error("backend did not return a download URL for remote plugin `{remote_plugin_id}`")]
|
||||
MissingBundleDownloadUrl { remote_plugin_id: String },
|
||||
|
||||
#[error(
|
||||
"backend returned an invalid download URL for remote plugin `{remote_plugin_id}`: {source}"
|
||||
)]
|
||||
InvalidBundleDownloadUrl {
|
||||
remote_plugin_id: String,
|
||||
#[source]
|
||||
source: url::ParseError,
|
||||
},
|
||||
|
||||
#[error(
|
||||
"backend returned an unsupported download URL scheme for remote plugin `{remote_plugin_id}`: {scheme}"
|
||||
)]
|
||||
UnsupportedBundleDownloadUrlScheme {
|
||||
remote_plugin_id: String,
|
||||
scheme: String,
|
||||
},
|
||||
|
||||
#[error(
|
||||
"backend returned an invalid local plugin id for remote plugin `{remote_plugin_id}`: {source}"
|
||||
)]
|
||||
InvalidPluginId {
|
||||
remote_plugin_id: String,
|
||||
#[source]
|
||||
source: PluginIdError,
|
||||
},
|
||||
|
||||
#[error("failed to send remote plugin bundle download request to {host}: {source}")]
|
||||
DownloadRequest {
|
||||
host: String,
|
||||
#[source]
|
||||
source: RouteAwareRequestError,
|
||||
},
|
||||
|
||||
#[error("remote plugin bundle download from {host} failed with status {status}: {body}")]
|
||||
DownloadStatus {
|
||||
host: String,
|
||||
status: StatusCode,
|
||||
body: String,
|
||||
},
|
||||
|
||||
#[error("failed to read remote plugin bundle download response from {host}: {source}")]
|
||||
DownloadBody {
|
||||
host: String,
|
||||
#[source]
|
||||
source: codex_http_client::HttpError,
|
||||
},
|
||||
|
||||
#[error("remote plugin bundle download from {host} exceeded maximum size of {max_bytes} bytes")]
|
||||
DownloadTooLarge { host: String, max_bytes: u64 },
|
||||
|
||||
#[error(
|
||||
"remote plugin bundle download from {host} resolved to unsupported URL scheme {scheme}"
|
||||
)]
|
||||
UnsupportedBundleDownloadFinalUrl { host: String, scheme: String },
|
||||
|
||||
#[error(
|
||||
"remote plugin bundle extracted size would be {bytes} bytes, exceeding the maximum total size of {max_bytes} bytes"
|
||||
)]
|
||||
ExtractedBundleTooLarge { bytes: u64, max_bytes: u64 },
|
||||
|
||||
#[error("{context}: {source}")]
|
||||
Io {
|
||||
context: &'static str,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
|
||||
#[error("{0}")]
|
||||
InvalidBundle(String),
|
||||
|
||||
#[error("{0}")]
|
||||
Store(#[from] PluginStoreError),
|
||||
}
|
||||
|
||||
impl RemotePluginBundleInstallError {
|
||||
fn io(context: &'static str, source: io::Error) -> Self {
|
||||
Self::Io { context, source }
|
||||
}
|
||||
|
||||
pub fn sub_error_type(&self) -> Option<String> {
|
||||
match self {
|
||||
Self::Io { context, .. } => Some(error_context_sub_error_type(context)),
|
||||
Self::Store(err) => err.sub_error_type(),
|
||||
Self::DownloadStatus { status, .. } => {
|
||||
Some(http_status_sub_error_type(*status).to_string())
|
||||
}
|
||||
Self::Unavailable
|
||||
| Self::MissingReleaseVersion { .. }
|
||||
| Self::InvalidReleaseVersion { .. }
|
||||
| Self::MissingBundleDownloadUrl { .. }
|
||||
| Self::InvalidBundleDownloadUrl { .. }
|
||||
| Self::UnsupportedBundleDownloadUrlScheme { .. }
|
||||
| Self::InvalidPluginId { .. }
|
||||
| Self::DownloadRequest { .. }
|
||||
| Self::DownloadBody { .. }
|
||||
| Self::DownloadTooLarge { .. }
|
||||
| Self::UnsupportedBundleDownloadFinalUrl { .. }
|
||||
| Self::ExtractedBundleTooLarge { .. }
|
||||
| Self::InvalidBundle(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate_remote_plugin_bundle(
|
||||
remote_plugin_id: &str,
|
||||
remote_marketplace_name: &str,
|
||||
plugin_name: &str,
|
||||
release_version: Option<&str>,
|
||||
bundle_download_url: Option<&str>,
|
||||
app_manifest: Option<JsonValue>,
|
||||
) -> Result<ValidatedRemotePluginBundle, RemotePluginBundleInstallError> {
|
||||
let plugin_id = PluginId::new(plugin_name.to_string(), remote_marketplace_name.to_string())
|
||||
.map_err(|source| RemotePluginBundleInstallError::InvalidPluginId {
|
||||
remote_plugin_id: remote_plugin_id.to_string(),
|
||||
source,
|
||||
})?;
|
||||
let plugin_version = release_version
|
||||
.map(str::trim)
|
||||
.filter(|version| !version.is_empty())
|
||||
.ok_or_else(|| RemotePluginBundleInstallError::MissingReleaseVersion {
|
||||
remote_plugin_id: remote_plugin_id.to_string(),
|
||||
})?
|
||||
.to_string();
|
||||
validate_plugin_version_segment(&plugin_version).map_err(|message| {
|
||||
RemotePluginBundleInstallError::InvalidReleaseVersion {
|
||||
remote_plugin_id: remote_plugin_id.to_string(),
|
||||
message,
|
||||
}
|
||||
})?;
|
||||
let bundle_download_url = bundle_download_url
|
||||
.map(str::trim)
|
||||
.filter(|url| !url.is_empty())
|
||||
.ok_or_else(
|
||||
|| RemotePluginBundleInstallError::MissingBundleDownloadUrl {
|
||||
remote_plugin_id: remote_plugin_id.to_string(),
|
||||
},
|
||||
)?
|
||||
.to_string();
|
||||
let parsed_bundle_url = Url::parse(&bundle_download_url).map_err(|source| {
|
||||
RemotePluginBundleInstallError::InvalidBundleDownloadUrl {
|
||||
remote_plugin_id: remote_plugin_id.to_string(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
if !is_allowed_bundle_download_url(
|
||||
&parsed_bundle_url,
|
||||
allow_test_loopback_http_bundle_downloads(),
|
||||
) {
|
||||
return Err(
|
||||
RemotePluginBundleInstallError::UnsupportedBundleDownloadUrlScheme {
|
||||
remote_plugin_id: remote_plugin_id.to_string(),
|
||||
scheme: parsed_bundle_url.scheme().to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Ok(ValidatedRemotePluginBundle {
|
||||
plugin_id,
|
||||
plugin_version,
|
||||
remote_plugin_id: remote_plugin_id.to_string(),
|
||||
app_manifest,
|
||||
bundle_download_url,
|
||||
})
|
||||
}
|
||||
|
||||
fn allow_test_loopback_http_bundle_downloads() -> bool {
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
if let Ok(value) = std::env::var(TEST_ALLOW_LOOPBACK_HTTP_REMOTE_PLUGIN_BUNDLES_ENV) {
|
||||
return value == "1";
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn is_allowed_bundle_download_url(url: &Url, allow_loopback_http: bool) -> bool {
|
||||
match url.scheme() {
|
||||
"https" => true,
|
||||
"http" => allow_loopback_http && is_loopback_url(url),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_loopback_url(url: &Url) -> bool {
|
||||
match url.host() {
|
||||
Some(Host::Ipv4(addr)) => addr.is_loopback(),
|
||||
Some(Host::Ipv6(addr)) => addr.is_loopback(),
|
||||
Some(Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn download_and_install_remote_plugin_bundle(
|
||||
config: &RemotePluginServiceConfig,
|
||||
codex_home: PathBuf,
|
||||
bundle: ValidatedRemotePluginBundle,
|
||||
) -> Result<PluginInstallResult, RemotePluginBundleInstallError> {
|
||||
let bundle_bytes = download_remote_plugin_bundle(config, &bundle).await?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
install_remote_plugin_bundle(codex_home, bundle, bundle_bytes)
|
||||
})
|
||||
.await
|
||||
.map_err(|err| {
|
||||
RemotePluginBundleInstallError::InvalidBundle(format!(
|
||||
"failed to join remote plugin bundle install task: {err}"
|
||||
))
|
||||
})?
|
||||
}
|
||||
|
||||
pub(crate) async fn download_and_extract_remote_plugin_bundle_to_path(
|
||||
config: &RemotePluginServiceConfig,
|
||||
bundle: ValidatedRemotePluginBundle,
|
||||
destination: AbsolutePathBuf,
|
||||
) -> Result<AbsolutePathBuf, RemotePluginBundleInstallError> {
|
||||
let bundle_bytes = download_remote_plugin_bundle(config, &bundle).await?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
extract_remote_plugin_bundle_to_path(bundle, bundle_bytes, destination)
|
||||
})
|
||||
.await
|
||||
.map_err(|err| {
|
||||
RemotePluginBundleInstallError::InvalidBundle(format!(
|
||||
"failed to join remote plugin bundle extraction task: {err}"
|
||||
))
|
||||
})?
|
||||
}
|
||||
|
||||
pub(crate) async fn download_remote_plugin_bundle(
|
||||
config: &RemotePluginServiceConfig,
|
||||
bundle: &ValidatedRemotePluginBundle,
|
||||
) -> Result<Vec<u8>, RemotePluginBundleInstallError> {
|
||||
download_remote_plugin_bundle_with_limit(
|
||||
config,
|
||||
&bundle.bundle_download_url,
|
||||
/*max_bytes*/ REMOTE_PLUGIN_BUNDLE_MAX_DOWNLOAD_BYTES,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn download_remote_plugin_bundle_with_limit(
|
||||
config: &RemotePluginServiceConfig,
|
||||
bundle_download_url: &str,
|
||||
max_bytes: u64,
|
||||
) -> Result<Vec<u8>, RemotePluginBundleInstallError> {
|
||||
let _ = (config, bundle_download_url, max_bytes);
|
||||
Err(RemotePluginBundleInstallError::Unavailable)
|
||||
}
|
||||
|
||||
pub(crate) fn install_remote_plugin_bundle(
|
||||
codex_home: PathBuf,
|
||||
bundle: ValidatedRemotePluginBundle,
|
||||
bundle_bytes: Vec<u8>,
|
||||
) -> Result<PluginInstallResult, RemotePluginBundleInstallError> {
|
||||
let staging_root = codex_home.join(REMOTE_PLUGIN_INSTALL_STAGING_DIR);
|
||||
fs::create_dir_all(&staging_root).map_err(|source| {
|
||||
RemotePluginBundleInstallError::io(
|
||||
"failed to create remote plugin bundle staging directory",
|
||||
source,
|
||||
)
|
||||
})?;
|
||||
let extract_dir = tempfile::Builder::new()
|
||||
.prefix("remote-plugin-bundle-")
|
||||
.tempdir_in(&staging_root)
|
||||
.map_err(|source| {
|
||||
RemotePluginBundleInstallError::io(
|
||||
"failed to create remote plugin bundle extraction directory",
|
||||
source,
|
||||
)
|
||||
})?;
|
||||
|
||||
extract_plugin_bundle_tar_gz(&bundle_bytes, extract_dir.path())?;
|
||||
let plugin_root = find_extracted_plugin_root(extract_dir.path())?;
|
||||
prepare_extracted_remote_plugin_root(&plugin_root, &bundle)?;
|
||||
let plugin_root = AbsolutePathBuf::try_from(plugin_root).map_err(|err| {
|
||||
RemotePluginBundleInstallError::InvalidBundle(format!(
|
||||
"failed to resolve extracted remote plugin bundle root: {err}"
|
||||
))
|
||||
})?;
|
||||
|
||||
let store = PluginStore::try_new(codex_home)?;
|
||||
let remote_plugin_id = bundle.remote_plugin_id;
|
||||
let result = store
|
||||
.install_with_version(plugin_root, bundle.plugin_id, bundle.plugin_version)
|
||||
.map_err(RemotePluginBundleInstallError::from)?;
|
||||
store.write_remote_plugin_id(&result.plugin_id, &remote_plugin_id)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn extract_remote_plugin_bundle_to_path(
|
||||
bundle: ValidatedRemotePluginBundle,
|
||||
bundle_bytes: Vec<u8>,
|
||||
destination: AbsolutePathBuf,
|
||||
) -> Result<AbsolutePathBuf, RemotePluginBundleInstallError> {
|
||||
if destination.as_path().exists() {
|
||||
return Err(RemotePluginBundleInstallError::InvalidBundle(format!(
|
||||
"plugin checkout destination already exists: {}",
|
||||
destination.display()
|
||||
)));
|
||||
}
|
||||
|
||||
let parent = destination.as_path().parent().ok_or_else(|| {
|
||||
RemotePluginBundleInstallError::InvalidBundle(format!(
|
||||
"plugin checkout destination has no parent: {}",
|
||||
destination.display()
|
||||
))
|
||||
})?;
|
||||
fs::create_dir_all(parent).map_err(|source| {
|
||||
RemotePluginBundleInstallError::io("failed to create plugin checkout directory", source)
|
||||
})?;
|
||||
|
||||
let extract_dir = tempfile::Builder::new()
|
||||
.prefix("remote-plugin-checkout-")
|
||||
.tempdir_in(parent)
|
||||
.map_err(|source| {
|
||||
RemotePluginBundleInstallError::io(
|
||||
"failed to create remote plugin bundle extraction directory",
|
||||
source,
|
||||
)
|
||||
})?;
|
||||
|
||||
extract_plugin_bundle_tar_gz(&bundle_bytes, extract_dir.path())?;
|
||||
let plugin_root = find_extracted_plugin_root(extract_dir.path())?;
|
||||
let manifest = crate::manifest::load_plugin_manifest(&plugin_root).ok_or_else(|| {
|
||||
RemotePluginBundleInstallError::InvalidBundle(
|
||||
"remote plugin bundle did not contain a valid plugin.json".to_string(),
|
||||
)
|
||||
})?;
|
||||
if manifest.name != bundle.plugin_id.plugin_name {
|
||||
return Err(RemotePluginBundleInstallError::InvalidBundle(format!(
|
||||
"plugin.json name `{}` does not match remote plugin name `{}`",
|
||||
manifest.name, bundle.plugin_id.plugin_name
|
||||
)));
|
||||
}
|
||||
|
||||
let staged_path = extract_dir.keep();
|
||||
fs::rename(&staged_path, destination.as_path()).map_err(|source| {
|
||||
RemotePluginBundleInstallError::io(
|
||||
"failed to activate checked out plugin directory",
|
||||
source,
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(destination)
|
||||
}
|
||||
|
||||
fn prepare_extracted_remote_plugin_root(
|
||||
plugin_root: &Path,
|
||||
bundle: &ValidatedRemotePluginBundle,
|
||||
) -> Result<(), RemotePluginBundleInstallError> {
|
||||
if bundle.plugin_id.marketplace_name != REMOTE_GLOBAL_MARKETPLACE_NAME {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
overwrite_plugin_manifest_version(plugin_root, &bundle.plugin_version)?;
|
||||
if let Some(app_manifest) = &bundle.app_manifest {
|
||||
overwrite_plugin_app_manifest(plugin_root, app_manifest)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn overwrite_plugin_manifest_version(
|
||||
plugin_root: &Path,
|
||||
plugin_version: &str,
|
||||
) -> Result<(), RemotePluginBundleInstallError> {
|
||||
let manifest_path = find_plugin_manifest_path(plugin_root).ok_or_else(|| {
|
||||
RemotePluginBundleInstallError::InvalidBundle(
|
||||
"remote plugin bundle did not contain a valid plugin.json".to_string(),
|
||||
)
|
||||
})?;
|
||||
let contents = fs::read_to_string(&manifest_path).map_err(|source| {
|
||||
RemotePluginBundleInstallError::io("failed to read remote plugin manifest", source)
|
||||
})?;
|
||||
if manifest_path == plugin_root.join(AGENT_PLUGIN_MANIFEST_RELATIVE_PATH)
|
||||
&& agent_plugin_schema_status(&contents) == AgentPluginSchemaStatus::Supported
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let mut manifest: JsonValue = serde_json::from_str(&contents).map_err(|err| {
|
||||
RemotePluginBundleInstallError::InvalidBundle(format!(
|
||||
"failed to parse remote plugin manifest: {err}"
|
||||
))
|
||||
})?;
|
||||
let Some(manifest_object) = manifest.as_object_mut() else {
|
||||
return Err(RemotePluginBundleInstallError::InvalidBundle(
|
||||
"remote plugin manifest must be a JSON object".to_string(),
|
||||
));
|
||||
};
|
||||
manifest_object.insert(
|
||||
"version".to_string(),
|
||||
JsonValue::String(plugin_version.to_string()),
|
||||
);
|
||||
write_json_file(
|
||||
&manifest_path,
|
||||
&manifest,
|
||||
"failed to write remote plugin manifest",
|
||||
)
|
||||
}
|
||||
|
||||
fn overwrite_plugin_app_manifest(
|
||||
plugin_root: &Path,
|
||||
app_manifest: &JsonValue,
|
||||
) -> Result<(), RemotePluginBundleInstallError> {
|
||||
let app_manifest_path = crate::manifest::load_plugin_manifest(plugin_root)
|
||||
.and_then(|manifest| manifest.paths.apps.map(|path| path.to_path_buf()))
|
||||
.unwrap_or_else(|| plugin_root.join(".app.json"));
|
||||
write_json_file(
|
||||
&app_manifest_path,
|
||||
app_manifest,
|
||||
"failed to write remote plugin app manifest",
|
||||
)
|
||||
}
|
||||
|
||||
fn write_json_file(
|
||||
path: &Path,
|
||||
value: &JsonValue,
|
||||
context: &'static str,
|
||||
) -> Result<(), RemotePluginBundleInstallError> {
|
||||
let parent = path.parent().ok_or_else(|| {
|
||||
RemotePluginBundleInstallError::InvalidBundle(format!(
|
||||
"remote plugin output path has no parent: {}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|source| RemotePluginBundleInstallError::io(context, source))?;
|
||||
let mut contents = serde_json::to_vec_pretty(value).map_err(|err| {
|
||||
RemotePluginBundleInstallError::InvalidBundle(format!(
|
||||
"failed to serialize remote plugin JSON override: {err}"
|
||||
))
|
||||
})?;
|
||||
contents.push(b'\n');
|
||||
fs::write(path, contents).map_err(|source| RemotePluginBundleInstallError::io(context, source))
|
||||
}
|
||||
|
||||
fn extract_plugin_bundle_tar_gz(
|
||||
bytes: &[u8],
|
||||
destination: &Path,
|
||||
) -> Result<(), RemotePluginBundleInstallError> {
|
||||
extract_plugin_bundle_tar_gz_with_limits(
|
||||
bytes,
|
||||
destination,
|
||||
REMOTE_PLUGIN_BUNDLE_MAX_EXTRACTED_BYTES,
|
||||
)
|
||||
}
|
||||
|
||||
fn extract_plugin_bundle_tar_gz_with_limits(
|
||||
bytes: &[u8],
|
||||
destination: &Path,
|
||||
max_total_bytes: u64,
|
||||
) -> Result<(), RemotePluginBundleInstallError> {
|
||||
unpack_plugin_bundle_tar_gz(bytes, destination, max_total_bytes).map_err(|err| match err {
|
||||
PluginBundleUnpackError::ExtractedBundleTooLarge { bytes, max_bytes } => {
|
||||
RemotePluginBundleInstallError::ExtractedBundleTooLarge { bytes, max_bytes }
|
||||
}
|
||||
PluginBundleUnpackError::Io { context, source } => {
|
||||
RemotePluginBundleInstallError::io(context, source)
|
||||
}
|
||||
PluginBundleUnpackError::InvalidBundle(message) => {
|
||||
RemotePluginBundleInstallError::InvalidBundle(message)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn find_extracted_plugin_root(
|
||||
extraction_root: &Path,
|
||||
) -> Result<PathBuf, RemotePluginBundleInstallError> {
|
||||
if is_standard_plugin_root(extraction_root) {
|
||||
return Ok(extraction_root.to_path_buf());
|
||||
}
|
||||
|
||||
Err(RemotePluginBundleInstallError::InvalidBundle(
|
||||
"remote plugin bundle did not contain a standard plugin root with plugin.json".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
fn is_standard_plugin_root(path: &Path) -> bool {
|
||||
find_plugin_manifest_path(path).is_some()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use flate2::Compression;
|
||||
use flate2::write::GzEncoder;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io::Write;
|
||||
use tempfile::tempdir;
|
||||
|
||||
const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_00000000000000000000000000000000";
|
||||
|
||||
#[test]
|
||||
fn remote_version_normalization_preserves_portable_root_manifest() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let manifest_path = temp_dir.path().join("plugin.json");
|
||||
let original = r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"portable","version":"release-2026-07"}"#;
|
||||
fs::write(&manifest_path, original).expect("write portable manifest");
|
||||
|
||||
overwrite_plugin_manifest_version(temp_dir.path(), "1.2.3")
|
||||
.expect("prepare portable remote plugin");
|
||||
|
||||
assert_eq!(
|
||||
fs::read_to_string(manifest_path).expect("read portable manifest"),
|
||||
original
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_remote_plugin_bundle_uses_detail_name_for_local_plugin_id() {
|
||||
let bundle = validate_remote_plugin_bundle(
|
||||
REMOTE_PLUGIN_ID,
|
||||
"openai-curated-remote",
|
||||
"linear",
|
||||
Some("1.2.3"),
|
||||
Some("https://example.com/linear.tar.gz?sig=signed-token"),
|
||||
/*app_manifest*/ None,
|
||||
)
|
||||
.expect("valid install plan");
|
||||
|
||||
assert_eq!(bundle.plugin_id.plugin_name, "linear");
|
||||
assert_eq!(bundle.plugin_id.marketplace_name, "openai-curated-remote");
|
||||
assert_eq!(bundle.plugin_version, "1.2.3");
|
||||
assert_eq!(
|
||||
bundle.bundle_download_url.as_str(),
|
||||
"https://example.com/linear.tar.gz?sig=signed-token"
|
||||
);
|
||||
assert!(!format!("{bundle:?}").contains("signed-token"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_remote_plugin_bundle_rejects_missing_release_version() {
|
||||
let err = validate_remote_plugin_bundle(
|
||||
REMOTE_PLUGIN_ID,
|
||||
"openai-curated-remote",
|
||||
"linear",
|
||||
/*release_version*/ None,
|
||||
Some("https://example.com/linear.tar.gz"),
|
||||
/*app_manifest*/ None,
|
||||
)
|
||||
.expect_err("missing release version should be rejected");
|
||||
|
||||
assert!(matches!(
|
||||
err,
|
||||
RemotePluginBundleInstallError::MissingReleaseVersion { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_remote_plugin_bundle_rejects_invalid_release_version() {
|
||||
let err = validate_remote_plugin_bundle(
|
||||
REMOTE_PLUGIN_ID,
|
||||
"openai-curated-remote",
|
||||
"linear",
|
||||
Some("../1.2.3"),
|
||||
Some("https://example.com/linear.tar.gz"),
|
||||
/*app_manifest*/ None,
|
||||
)
|
||||
.expect_err("invalid release version should be rejected");
|
||||
|
||||
assert!(matches!(
|
||||
err,
|
||||
RemotePluginBundleInstallError::InvalidReleaseVersion { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_remote_plugin_bundle_rejects_missing_download_url() {
|
||||
let err = validate_remote_plugin_bundle(
|
||||
REMOTE_PLUGIN_ID,
|
||||
"openai-curated-remote",
|
||||
"linear",
|
||||
Some("1.2.3"),
|
||||
/*bundle_download_url*/ None,
|
||||
/*app_manifest*/ None,
|
||||
)
|
||||
.expect_err("missing bundle download URL should be rejected");
|
||||
|
||||
assert!(matches!(
|
||||
err,
|
||||
RemotePluginBundleInstallError::MissingBundleDownloadUrl { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_remote_plugin_bundle_rejects_unsupported_download_url_scheme() {
|
||||
let err = validate_remote_plugin_bundle(
|
||||
REMOTE_PLUGIN_ID,
|
||||
"openai-curated-remote",
|
||||
"linear",
|
||||
Some("1.2.3"),
|
||||
Some("http://example.com/linear.tar.gz"),
|
||||
/*app_manifest*/ None,
|
||||
)
|
||||
.expect_err("plain HTTP URLs should be rejected before cloud install");
|
||||
|
||||
assert!(matches!(
|
||||
err,
|
||||
RemotePluginBundleInstallError::UnsupportedBundleDownloadUrlScheme { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_rejects_invalid_tar_gz_bundle() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let bundle = valid_remote_plugin_bundle();
|
||||
|
||||
let err = install_remote_plugin_bundle(
|
||||
codex_home.path().to_path_buf(),
|
||||
bundle,
|
||||
b"not a tar.gz".to_vec(),
|
||||
)
|
||||
.expect_err("invalid tar.gz should be rejected");
|
||||
|
||||
assert!(format!("{err}").contains("failed to read plugin bundle tar"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_rejects_bundle_without_standard_plugin_root() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let bundle = valid_remote_plugin_bundle();
|
||||
|
||||
let err = install_remote_plugin_bundle(
|
||||
codex_home.path().to_path_buf(),
|
||||
bundle,
|
||||
tar_gz_bytes(&[("README.md", b"missing plugin manifest", /*mode*/ 0o644)]),
|
||||
)
|
||||
.expect_err("bundle without plugin root should be rejected");
|
||||
|
||||
assert!(
|
||||
format!("{err}").contains("did not contain a standard plugin root with plugin.json")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_persists_remote_plugin_install_metadata() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let bundle = valid_remote_plugin_bundle();
|
||||
|
||||
let result = install_remote_plugin_bundle(
|
||||
codex_home.path().to_path_buf(),
|
||||
bundle,
|
||||
tar_gz_bytes(&[(
|
||||
".codex-plugin/plugin.json",
|
||||
br#"{"name":"linear","version":"1.2.3"}"#,
|
||||
/*mode*/ 0o644,
|
||||
)]),
|
||||
)
|
||||
.expect("install bundle");
|
||||
let store = PluginStore::new(codex_home.path().to_path_buf());
|
||||
|
||||
assert_eq!(
|
||||
store.remote_plugin_id(&result.plugin_id).unwrap(),
|
||||
Some(REMOTE_PLUGIN_ID.to_string())
|
||||
);
|
||||
let metadata_path = store
|
||||
.plugin_base_root(&result.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"),
|
||||
serde_json::json!({
|
||||
"schema_version": 1,
|
||||
"remote_plugin_id": REMOTE_PLUGIN_ID,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_preserves_non_global_bundle_manifest_metadata() {
|
||||
let codex_home = tempdir().expect("tempdir");
|
||||
let bundle = validate_remote_plugin_bundle(
|
||||
REMOTE_PLUGIN_ID,
|
||||
"workspace-shared-with-me",
|
||||
"linear",
|
||||
Some("backend-version"),
|
||||
Some("https://example.com/linear.tar.gz"),
|
||||
Some(serde_json::json!({
|
||||
"apps": {
|
||||
"remote": {
|
||||
"id": "remote-app"
|
||||
}
|
||||
}
|
||||
})),
|
||||
)
|
||||
.expect("valid install plan");
|
||||
|
||||
let result = install_remote_plugin_bundle(
|
||||
codex_home.path().to_path_buf(),
|
||||
bundle,
|
||||
tar_gz_bytes(&[
|
||||
(
|
||||
".codex-plugin/plugin.json",
|
||||
br#"{"name":"linear","version":"bundle-version"}"#,
|
||||
/*mode*/ 0o644,
|
||||
),
|
||||
(
|
||||
".app.json",
|
||||
br#"{"apps":{"bundled":{"id":"bundled-app"}}}"#,
|
||||
/*mode*/ 0o644,
|
||||
),
|
||||
]),
|
||||
)
|
||||
.expect("install bundle");
|
||||
|
||||
assert_eq!(result.plugin_version, "backend-version");
|
||||
let installed_manifest: JsonValue = serde_json::from_str(
|
||||
&std::fs::read_to_string(
|
||||
result
|
||||
.installed_path
|
||||
.join(".codex-plugin/plugin.json")
|
||||
.as_path(),
|
||||
)
|
||||
.expect("read installed plugin manifest"),
|
||||
)
|
||||
.expect("parse installed plugin manifest");
|
||||
assert_eq!(
|
||||
installed_manifest,
|
||||
serde_json::json!({
|
||||
"name": "linear",
|
||||
"version": "bundle-version",
|
||||
})
|
||||
);
|
||||
let installed_app_manifest: JsonValue = serde_json::from_str(
|
||||
&std::fs::read_to_string(result.installed_path.join(".app.json").as_path())
|
||||
.expect("read installed app manifest"),
|
||||
)
|
||||
.expect("parse installed app manifest");
|
||||
assert_eq!(
|
||||
installed_app_manifest,
|
||||
serde_json::json!({
|
||||
"apps": {
|
||||
"bundled": {
|
||||
"id": "bundled-app",
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_extracted_plugin_root_uses_local_manifest_discovery() {
|
||||
let extraction_root = tempdir().expect("tempdir");
|
||||
std::fs::create_dir_all(extraction_root.path().join(".codex-plugin"))
|
||||
.expect("create manifest dir");
|
||||
std::fs::write(
|
||||
extraction_root.path().join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"linear"}"#,
|
||||
)
|
||||
.expect("write manifest");
|
||||
|
||||
assert_eq!(
|
||||
find_extracted_plugin_root(extraction_root.path()).expect("plugin root"),
|
||||
extraction_root.path()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_extracted_plugin_root_rejects_nested_plugin_root() {
|
||||
let extraction_root = tempdir().expect("tempdir");
|
||||
let plugin_root = extraction_root.path().join("linear");
|
||||
std::fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create manifest dir");
|
||||
std::fs::write(
|
||||
plugin_root.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"linear"}"#,
|
||||
)
|
||||
.expect("write manifest");
|
||||
|
||||
let err = find_extracted_plugin_root(extraction_root.path())
|
||||
.expect_err("nested plugin root should be rejected");
|
||||
|
||||
assert!(
|
||||
format!("{err}").contains("did not contain a standard plugin root with plugin.json")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extraction_rejects_tar_path_traversal() {
|
||||
let destination = tempdir().expect("tempdir");
|
||||
let err = extract_plugin_bundle_tar_gz(
|
||||
&tar_gz_bytes_with_raw_path("../evil.txt", b"evil", /*mode*/ 0o644),
|
||||
destination.path(),
|
||||
)
|
||||
.expect_err("tar path traversal should be rejected");
|
||||
|
||||
assert!(format!("{err}").contains("escapes extraction root"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extraction_rejects_total_size_over_limit() {
|
||||
let destination = tempdir().expect("tempdir");
|
||||
let err = extract_plugin_bundle_tar_gz_with_limits(
|
||||
&tar_gz_bytes(&[
|
||||
("a.txt", b"1234", /*mode*/ 0o644),
|
||||
("b.txt", b"5678", /*mode*/ 0o644),
|
||||
]),
|
||||
destination.path(),
|
||||
/*max_total_bytes*/ 6,
|
||||
)
|
||||
.expect_err("oversized extracted bundle should be rejected");
|
||||
|
||||
assert!(matches!(
|
||||
err,
|
||||
RemotePluginBundleInstallError::ExtractedBundleTooLarge { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extraction_supports_gnu_long_name_entries() {
|
||||
let destination = tempdir().expect("tempdir");
|
||||
let long_path = format!("{}/file.txt", ["segment"; 40].join("/"));
|
||||
|
||||
extract_plugin_bundle_tar_gz(
|
||||
&tar_gz_bytes(&[(long_path.as_str(), b"long", /*mode*/ 0o644)]),
|
||||
destination.path(),
|
||||
)
|
||||
.expect("extract bundle with GNU long name entry");
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read(destination.path().join(long_path)).expect("read extracted file"),
|
||||
b"long"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn extraction_preserves_executable_permissions() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let destination = tempdir().expect("tempdir");
|
||||
extract_plugin_bundle_tar_gz(
|
||||
&tar_gz_bytes(&[
|
||||
(
|
||||
".codex-plugin/plugin.json",
|
||||
b"{\"name\":\"linear\"}",
|
||||
/*mode*/ 0o644,
|
||||
),
|
||||
("bin/helper", b"#!/bin/sh\n", /*mode*/ 0o755),
|
||||
]),
|
||||
destination.path(),
|
||||
)
|
||||
.expect("extract bundle");
|
||||
|
||||
let mode = std::fs::metadata(destination.path().join("bin/helper"))
|
||||
.expect("helper metadata")
|
||||
.permissions()
|
||||
.mode()
|
||||
& 0o777;
|
||||
assert_eq!(mode, 0o755);
|
||||
}
|
||||
|
||||
fn valid_remote_plugin_bundle() -> ValidatedRemotePluginBundle {
|
||||
validate_remote_plugin_bundle(
|
||||
REMOTE_PLUGIN_ID,
|
||||
"openai-curated-remote",
|
||||
"linear",
|
||||
Some("1.2.3"),
|
||||
Some("https://example.com/linear.tar.gz"),
|
||||
/*app_manifest*/ None,
|
||||
)
|
||||
.expect("valid install plan")
|
||||
}
|
||||
|
||||
fn tar_gz_bytes(entries: &[(&str, &[u8], u32)]) -> Vec<u8> {
|
||||
let encoder = GzEncoder::new(Vec::new(), Compression::default());
|
||||
let mut tar = tar::Builder::new(encoder);
|
||||
for (path, contents, mode) in entries {
|
||||
append_tar_entry(&mut tar, tar::EntryType::Regular, path, contents, *mode);
|
||||
}
|
||||
finish_tar_gz(tar)
|
||||
}
|
||||
|
||||
fn tar_gz_bytes_with_raw_path(path: &str, contents: &[u8], mode: u32) -> Vec<u8> {
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_entry_type(tar::EntryType::Regular);
|
||||
header.set_size(contents.len() as u64);
|
||||
header.set_mode(mode);
|
||||
header.as_mut_bytes()[..path.len()].copy_from_slice(path.as_bytes());
|
||||
header.set_cksum();
|
||||
|
||||
let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
|
||||
encoder
|
||||
.write_all(header.as_bytes())
|
||||
.expect("write tar header");
|
||||
encoder.write_all(contents).expect("write tar contents");
|
||||
let padding = (512 - (contents.len() % 512)) % 512;
|
||||
encoder
|
||||
.write_all(&vec![0; padding])
|
||||
.expect("write tar padding");
|
||||
encoder.write_all(&[0; 1024]).expect("write tar terminator");
|
||||
encoder.finish().expect("finish gzip")
|
||||
}
|
||||
|
||||
fn append_tar_entry<W: std::io::Write>(
|
||||
tar: &mut tar::Builder<W>,
|
||||
entry_type: tar::EntryType,
|
||||
path: &str,
|
||||
contents: &[u8],
|
||||
mode: u32,
|
||||
) {
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_entry_type(entry_type);
|
||||
header.set_size(contents.len() as u64);
|
||||
header.set_mode(mode);
|
||||
header.set_cksum();
|
||||
if let Err(error) = tar.append_data(&mut header, path, contents) {
|
||||
panic!("failed to append tar test data: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_tar_gz(tar: tar::Builder<GzEncoder<Vec<u8>>>) -> Vec<u8> {
|
||||
let encoder = match tar.into_inner() {
|
||||
Ok(encoder) => encoder,
|
||||
Err(error) => panic!("failed to finish tar test data: {error}"),
|
||||
};
|
||||
match encoder.finish() {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) => panic!("failed to finish gzip test data: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user