Auto-trust hooks from eligible remote plugins

This commit is contained in:
Abhinav Vedmala
2026-07-08 20:54:56 -07:00
parent 3fa90665fe
commit ed81bdad9b
14 changed files with 1209 additions and 24 deletions
@@ -492,9 +492,27 @@ impl PluginRequestProcessor {
tokio::spawn(async move {
thread_manager.plugins_manager().clear_cache();
thread_manager.skills_service().clear_cache();
if thread_manager.list_thread_ids().await.is_empty() {
let thread_ids = thread_manager.list_thread_ids().await;
if thread_ids.is_empty() {
return;
}
match config_manager
.load_latest_config(/*fallback_cwd*/ None)
.await
{
Ok(config) => {
for thread_id in thread_ids {
let Ok(thread) = thread_manager.get_thread(thread_id).await else {
continue;
};
thread.refresh_runtime_config(config.clone()).await;
}
}
Err(err) => warn!(
error = %err,
"failed to reload user config after effective plugins changed"
),
}
crate::mcp_refresh::queue_best_effort_refresh(&thread_manager, &config_manager).await;
});
}
@@ -1646,6 +1664,54 @@ impl PluginRequestProcessor {
remote_plugin_catalog_error_to_jsonrpc(err, "install remote plugin")
})?;
let auto_trust_hooks = if remote_detail.auto_trust_hooks {
match codex_core_plugins::remote::fetch_remote_plugin_detail_with_download_urls(
&remote_plugin_service_config,
auth.as_ref(),
&actual_remote_marketplace_name,
&remote_plugin_id,
)
.await
{
Ok(current_detail) => current_detail.auto_trust_hooks,
Err(err) => {
warn!(
remote_plugin_id = %remote_plugin_id,
plugin = %remote_plugin_name,
marketplace = %actual_remote_marketplace_name,
error = %err,
"remote plugin installed, but hook auto-trust eligibility could not be revalidated"
);
false
}
}
} else {
false
};
if auto_trust_hooks {
match codex_core_plugins::trust_installed_plugin_hooks(
config.codex_home.as_path(),
&config.config_layer_stack,
&result.plugin_id,
&result.installed_path,
)
.await
{
Ok(entries) if !entries.is_empty() => self.on_effective_plugins_changed(),
Ok(_) => {}
Err(err) => {
warn!(
remote_plugin_id = %remote_plugin_id,
plugin = %remote_plugin_name,
marketplace = %actual_remote_marketplace_name,
error = %err,
"remote plugin installed, but automatic hook trust could not be persisted"
);
}
}
}
self.thread_manager
.plugins_manager()
.maybe_start_remote_installed_plugins_cache_refresh_after_mutation(
@@ -305,6 +305,67 @@ async fn plugin_install_writes_remote_plugin_to_cloud_and_cache() -> Result<()>
Ok(())
}
#[tokio::test]
async fn user_remote_plugin_install_auto_trusts_bundled_hooks() -> Result<()> {
let codex_home = TempDir::new()?;
let server = MockServer::start().await;
let bundle_url = mount_remote_plugin_bundle(
&server,
/*status_code*/ 200,
remote_plugin_bundle_tar_gz_bytes_with_hook("linear")?,
)
.await;
configure_remote_plugin_test(codex_home.path(), &server)?;
mount_remote_plugin_detail_for_scope(
&server,
REMOTE_PLUGIN_ID,
"1.2.3",
Some(&bundle_url),
"USER",
/*discoverability*/ None,
)
.await;
mount_empty_remote_installed_plugins_for_scope(&server, "USER").await;
mount_remote_plugin_install(&server, REMOTE_PLUGIN_ID).await;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[(TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS, Some("1"))])
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let request_id = send_remote_plugin_install_request(&mut mcp, REMOTE_PLUGIN_ID).await?;
let response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let _: PluginInstallResponse = to_response(response)?;
let config: toml::Value = toml::from_str(&std::fs::read_to_string(
codex_home.path().join("config.toml"),
)?)?;
let hook_state = config
.get("hooks")
.and_then(|hooks| hooks.get("state"))
.and_then(toml::Value::as_table)
.expect("automatic hook trust state");
let (hook_key, state) = hook_state.iter().next().expect("trusted plugin hook");
assert_eq!(
hook_key,
"linear@created-by-me-remote:hooks/hooks.json:pre_tool_use:0:0"
);
assert!(
state
.get("trusted_hash")
.and_then(toml::Value::as_str)
.is_some_and(|hash| hash.starts_with("sha256:"))
);
Ok(())
}
#[tokio::test]
async fn plugin_install_uses_remote_apps_needing_auth_response() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -2282,6 +2343,54 @@ async fn mount_remote_plugin_detail_with_options(
status: PluginAvailability,
install_policy: &str,
app_manifest: Option<serde_json::Value>,
) {
mount_remote_plugin_detail_for_scope_with_options(
server,
remote_plugin_id,
release_version,
bundle_download_url,
status,
install_policy,
app_manifest,
"GLOBAL",
/*discoverability*/ None,
)
.await;
}
async fn mount_remote_plugin_detail_for_scope(
server: &MockServer,
remote_plugin_id: &str,
release_version: &str,
bundle_download_url: Option<&str>,
scope: &str,
discoverability: Option<&str>,
) {
mount_remote_plugin_detail_for_scope_with_options(
server,
remote_plugin_id,
release_version,
bundle_download_url,
PluginAvailability::Available,
"AVAILABLE",
/*app_manifest*/ None,
scope,
discoverability,
)
.await;
}
#[allow(clippy::too_many_arguments)]
async fn mount_remote_plugin_detail_for_scope_with_options(
server: &MockServer,
remote_plugin_id: &str,
release_version: &str,
bundle_download_url: Option<&str>,
status: PluginAvailability,
install_policy: &str,
app_manifest: Option<serde_json::Value>,
scope: &str,
discoverability: Option<&str>,
) {
let status = match status {
PluginAvailability::Available => "ENABLED",
@@ -2293,11 +2402,15 @@ async fn mount_remote_plugin_detail_with_options(
let app_manifest_field = app_manifest
.map(|manifest| format!(r#" "app_manifest": {manifest},"#))
.unwrap_or_default();
let discoverability_field = discoverability
.map(|value| format!(r#" "discoverability": "{value}","#))
.unwrap_or_default();
let detail_body = format!(
r#"{{
"id": "{remote_plugin_id}",
"name": "linear",
"scope": "GLOBAL",
"scope": "{scope}",
{discoverability_field}
"installation_policy": "{install_policy}",
"authentication_policy": "ON_USE",
"status": "{status}",
@@ -2327,9 +2440,13 @@ async fn mount_remote_plugin_detail_with_options(
}
async fn mount_empty_remote_installed_plugins(server: &MockServer) {
mount_empty_remote_installed_plugins_for_scope(server, "GLOBAL").await;
}
async fn mount_empty_remote_installed_plugins_for_scope(server: &MockServer, scope: &str) {
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.and(query_param("scope", "GLOBAL"))
.and(query_param("scope", scope))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
.respond_with(ResponseTemplate::new(200).set_body_string(
@@ -2612,6 +2729,38 @@ fn remote_plugin_bundle_tar_gz_bytes_with_entries(
plugin_manifest: &str,
app_manifest: Option<&str>,
mcp_config: Option<&str>,
) -> Result<Vec<u8>> {
remote_plugin_bundle_tar_gz_bytes_with_entries_and_hook(
plugin_manifest,
app_manifest,
mcp_config,
/*hook_config*/ None,
)
}
fn remote_plugin_bundle_tar_gz_bytes_with_hook(plugin_name: &str) -> Result<Vec<u8>> {
let manifest = format!(r#"{{"name":"{plugin_name}","hooks":"./hooks/hooks.json"}}"#);
let hook_config = r#"{
"hooks": {
"PreToolUse": [{
"matcher": "^shell$",
"hooks": [{"type": "command", "command": "echo trusted"}]
}]
}
}"#;
remote_plugin_bundle_tar_gz_bytes_with_entries_and_hook(
&manifest,
/*app_manifest*/ None,
/*mcp_config*/ None,
Some(hook_config),
)
}
fn remote_plugin_bundle_tar_gz_bytes_with_entries_and_hook(
plugin_manifest: &str,
app_manifest: Option<&str>,
mcp_config: Option<&str>,
hook_config: Option<&str>,
) -> Result<Vec<u8>> {
let skill = "# Plan Work\n\nTrack work in Linear.\n";
let encoder = GzEncoder::new(Vec::new(), Compression::default());
@@ -2634,6 +2783,13 @@ fn remote_plugin_bundle_tar_gz_bytes_with_entries(
if let Some(mcp_config) = mcp_config {
entries.push((".mcp.json", mcp_config.as_bytes(), /*mode*/ 0o644));
}
if let Some(hook_config) = hook_config {
entries.push((
"hooks/hooks.json",
hook_config.as_bytes(),
/*mode*/ 0o644,
));
}
for (path, contents, mode) in entries {
let mut header = tar::Header::new_gnu();
header.set_size(contents.len() as u64);
@@ -6,6 +6,8 @@ use app_test_support::ChatGptAuthFixture;
use app_test_support::TestAppServer;
use app_test_support::to_response;
use app_test_support::write_chatgpt_auth;
use codex_app_server_protocol::HookTrustStatus;
use codex_app_server_protocol::HooksListResponse;
use codex_app_server_protocol::JSONRPCResponse;
use codex_app_server_protocol::PluginAuthPolicy;
use codex_app_server_protocol::PluginInstallPolicy;
@@ -1615,6 +1617,112 @@ async fn app_server_startup_sync_downloads_remote_installed_plugin_bundles() ->
Ok(())
}
#[tokio::test]
async fn startup_sync_backfills_listed_workspace_plugin_hook_trust_once() -> Result<()> {
let codex_home = TempDir::new()?;
let server = MockServer::start().await;
write_remote_plugin_catalog_config(
codex_home.path(),
&format!("{}/backend-api/", server.uri()),
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
write_installed_plugin_with_hook(
&codex_home,
"workspace-directory",
"linear",
"1.2.3",
"echo locally modified",
)?;
let bundle_url = mount_remote_plugin_bundle(
&server,
"linear",
remote_plugin_bundle_tar_gz_bytes_with_hook("linear", "echo trusted remote")?,
)
.await;
let mut workspace_installed: serde_json::Value = serde_json::from_str(
&remote_installed_plugin_body(&bundle_url, "1.2.3", /*enabled*/ true),
)?;
workspace_installed["plugins"][0]["scope"] = serde_json::json!("WORKSPACE");
workspace_installed["plugins"][0]["discoverability"] = serde_json::json!("LISTED");
mount_remote_installed_plugins(&server, "GLOBAL", empty_remote_installed_plugins_body()).await;
mount_remote_installed_plugins(
&server,
"WORKSPACE",
&serde_json::to_string(&workspace_installed)?,
)
.await;
mount_empty_user_installed_plugins(&server).await;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_plugin_startup_tasks()
.with_env_overrides(&[(TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS, Some("1"))])
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
wait_for_config_to_contain(codex_home.path(), "trusted_hash").await?;
let installed_hook = codex_home
.path()
.join("plugins/cache/workspace-directory/linear/1.2.3/hooks/hooks.json");
assert!(std::fs::read_to_string(installed_hook)?.contains("echo trusted remote"));
wait_for_remote_plugin_request_count(&server, "/bundles/linear.tar.gz", 1).await?;
let hooks_request_id = mcp
.send_raw_request(
"hooks/list",
Some(serde_json::json!({"cwds": [codex_home.path()]})),
)
.await?;
let hooks: HooksListResponse = to_response(
timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(hooks_request_id)),
)
.await??,
)?;
assert_eq!(hooks.data.len(), 1);
assert_eq!(hooks.data[0].hooks.len(), 1);
assert_eq!(
hooks.data[0].hooks[0].trust_status,
HookTrustStatus::Trusted
);
let request_id = mcp
.send_plugin_installed_request(PluginInstalledParams {
cwds: None,
install_suggestion_plugin_names: None,
})
.await?;
let _: PluginInstalledResponse = to_response(
timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??,
)?;
wait_for_remote_installed_scope_request_count(&server, "WORKSPACE", 2).await?;
let requests = server.received_requests().await.expect("recorded requests");
assert_eq!(
requests
.iter()
.filter(|request| request.url.path().ends_with("/bundles/linear.tar.gz"))
.count(),
1,
"trusted same-version plugin should not be downloaded again"
);
Ok(())
}
#[tokio::test]
async fn plugin_list_sync_upgrades_and_removes_remote_installed_plugin_bundles() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -3786,19 +3894,45 @@ async fn wait_for_remote_plugin_request_count(
}
async fn wait_for_remote_installed_scope_request(server: &MockServer, scope: &str) -> Result<()> {
wait_for_remote_installed_scope_request_count(server, scope, 1).await
}
async fn wait_for_remote_installed_scope_request_count(
server: &MockServer,
scope: &str,
expected_count: usize,
) -> Result<()> {
timeout(DEFAULT_TIMEOUT, async {
loop {
let Some(requests) = server.received_requests().await else {
bail!("wiremock did not record requests");
};
if requests.iter().any(|request| {
request.method == "GET"
&& request.url.path().ends_with("/ps/plugins/installed")
&& request
.url
.query_pairs()
.any(|(name, value)| name == "scope" && value == scope)
}) {
let request_count = requests
.iter()
.filter(|request| {
request.method == "GET"
&& request.url.path().ends_with("/ps/plugins/installed")
&& request
.url
.query_pairs()
.any(|(name, value)| name == "scope" && value == scope)
})
.count();
if request_count >= expected_count {
return Ok::<(), anyhow::Error>(());
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await??;
Ok(())
}
async fn wait_for_config_to_contain(codex_home: &std::path::Path, needle: &str) -> Result<()> {
timeout(DEFAULT_TIMEOUT, async {
loop {
let config = std::fs::read_to_string(codex_home.join("config.toml"))?;
if config.contains(needle) {
return Ok::<(), anyhow::Error>(());
}
tokio::time::sleep(Duration::from_millis(10)).await;
@@ -4163,6 +4297,33 @@ fn remote_plugin_bundle_tar_gz_bytes(plugin_name: &str) -> Result<Vec<u8>> {
Ok(tar.into_inner()?.finish()?)
}
fn remote_plugin_bundle_tar_gz_bytes_with_hook(
plugin_name: &str,
command: &str,
) -> Result<Vec<u8>> {
let manifest = format!(r#"{{"name":"{plugin_name}","hooks":"./hooks/hooks.json"}}"#);
let hooks = format!(
r#"{{"hooks":{{"PreToolUse":[{{"matcher":"^shell$","hooks":[{{"type":"command","command":"{command}"}}]}}]}}}}"#
);
let encoder = GzEncoder::new(Vec::new(), Compression::default());
let mut tar = tar::Builder::new(encoder);
for (path, contents, mode) in [
(
".codex-plugin/plugin.json",
manifest.as_bytes(),
/*mode*/ 0o644,
),
("hooks/hooks.json", hooks.as_bytes(), /*mode*/ 0o644),
] {
let mut header = tar::Header::new_gnu();
header.set_size(contents.len() as u64);
header.set_mode(mode);
header.set_cksum();
tar.append_data(&mut header, path, contents)?;
}
Ok(tar.into_inner()?.finish()?)
}
fn write_installed_plugin(
codex_home: &TempDir,
marketplace_name: &str,
@@ -4192,6 +4353,34 @@ fn write_installed_plugin_with_version(
Ok(())
}
fn write_installed_plugin_with_hook(
codex_home: &TempDir,
marketplace_name: &str,
plugin_name: &str,
plugin_version: &str,
command: &str,
) -> Result<()> {
write_installed_plugin_with_version(codex_home, marketplace_name, plugin_name, plugin_version)?;
let plugin_root = codex_home
.path()
.join("plugins/cache")
.join(marketplace_name)
.join(plugin_name)
.join(plugin_version);
std::fs::write(
plugin_root.join(".codex-plugin/plugin.json"),
format!(r#"{{"name":"{plugin_name}","hooks":"./hooks/hooks.json"}}"#),
)?;
std::fs::create_dir_all(plugin_root.join("hooks"))?;
std::fs::write(
plugin_root.join("hooks/hooks.json"),
format!(
r#"{{"hooks":{{"PreToolUse":[{{"matcher":"^shell$","hooks":[{{"type":"command","command":"{command}"}}]}}]}}}}"#
),
)?;
Ok(())
}
fn write_plugin_sync_config(codex_home: &std::path::Path, base_url: &str) -> std::io::Result<()> {
std::fs::write(
codex_home.join("config.toml"),
+333
View File
@@ -0,0 +1,333 @@
use std::fs;
use std::io::ErrorKind;
use std::path::Path;
use codex_utils_path::resolve_symlink_write_paths;
use codex_utils_path::write_atomically;
use tokio::task;
use toml_edit::DocumentMut;
use toml_edit::Item as TomlItem;
use toml_edit::Table as TomlTable;
use toml_edit::value;
use crate::CONFIG_TOML_FILE;
const CONFIG_WRITE_MAX_RETRIES: usize = 4;
/// Upserts user-level trusted hashes for hooks in a single config write.
///
/// Existing hook state fields, such as `enabled`, are preserved. If the same
/// hook key appears more than once, the last hash in the input wins.
pub async fn upsert_user_hook_trusted_hashes(
codex_home: &Path,
trusted_hashes: Vec<(String, String)>,
) -> std::io::Result<()> {
upsert_hook_trusted_hashes(&codex_home.join(CONFIG_TOML_FILE), trusted_hashes).await
}
/// Upserts trusted hashes in the selected user config file.
pub async fn upsert_hook_trusted_hashes(
config_path: &Path,
trusted_hashes: Vec<(String, String)>,
) -> std::io::Result<()> {
if trusted_hashes.is_empty() {
return Ok(());
}
let config_path = config_path.to_path_buf();
task::spawn_blocking(move || upsert_hook_trusted_hashes_blocking(&config_path, trusted_hashes))
.await
.map_err(|err| std::io::Error::other(format!("config persistence task panicked: {err}")))?
}
fn upsert_hook_trusted_hashes_blocking(
config_path: &Path,
trusted_hashes: Vec<(String, String)>,
) -> std::io::Result<()> {
for _ in 0..CONFIG_WRITE_MAX_RETRIES {
let write_paths = resolve_symlink_write_paths(config_path)?;
let original = read_optional_string(write_paths.read_path.as_deref())?;
let mut doc = parse_or_create_document(original.as_deref())?;
let mut mutated = false;
for (hook_key, trusted_hash) in &trusted_hashes {
mutated |= set_hook_trusted_hash(&mut doc, hook_key, trusted_hash);
}
if !mutated {
return Ok(());
}
if read_optional_string(write_paths.read_path.as_deref())? != original {
continue;
}
return write_atomically(&write_paths.write_path, &doc.to_string());
}
Err(std::io::Error::new(
ErrorKind::WouldBlock,
"config changed repeatedly while persisting automatic hook trust",
))
}
fn read_optional_string(config_path: Option<&Path>) -> std::io::Result<Option<String>> {
let Some(config_path) = config_path else {
return Ok(None);
};
match fs::read_to_string(config_path) {
Ok(raw) => Ok(Some(raw)),
Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
Err(err) => Err(err),
}
}
fn parse_or_create_document(raw: Option<&str>) -> std::io::Result<DocumentMut> {
match raw {
Some(raw) => raw
.parse::<DocumentMut>()
.map_err(|err| std::io::Error::new(ErrorKind::InvalidData, err)),
None => Ok(DocumentMut::new()),
}
}
fn set_hook_trusted_hash(doc: &mut DocumentMut, hook_key: &str, trusted_hash: &str) -> bool {
let Some(hooks) = ensure_child_table(doc.as_table_mut(), "hooks") else {
return false;
};
let Some(state) = ensure_child_table(hooks, "state") else {
return false;
};
let Some(hook_state) = ensure_table_for_write(&mut state[hook_key]) else {
return false;
};
if hook_state.get("trusted_hash").and_then(TomlItem::as_str) == Some(trusted_hash) {
return false;
}
let mut replacement = value(trusted_hash);
if let Some(existing) = hook_state.get("trusted_hash") {
preserve_decor(existing, &mut replacement);
}
hook_state["trusted_hash"] = replacement;
true
}
fn ensure_child_table<'a>(table: &'a mut TomlTable, key: &str) -> Option<&'a mut TomlTable> {
if !table.contains_key(key) {
table.insert(key, TomlItem::Table(new_implicit_table()));
}
ensure_table_for_write(table.get_mut(key)?)
}
fn ensure_table_for_write(item: &mut TomlItem) -> Option<&mut TomlTable> {
match item {
TomlItem::Table(table) => Some(table),
TomlItem::Value(value) => {
let table = value
.as_inline_table()
.map_or_else(new_implicit_table, table_from_inline);
*item = TomlItem::Table(table);
item.as_table_mut()
}
TomlItem::None => {
*item = TomlItem::Table(new_implicit_table());
item.as_table_mut()
}
_ => None,
}
}
fn table_from_inline(inline: &toml_edit::InlineTable) -> TomlTable {
let mut table = new_implicit_table();
for (key, value) in inline.iter() {
let mut value = value.clone();
value.decor_mut().set_suffix("");
table.insert(key, TomlItem::Value(value));
}
table
}
fn new_implicit_table() -> TomlTable {
let mut table = TomlTable::new();
table.set_implicit(true);
table
}
fn preserve_decor(existing: &TomlItem, replacement: &mut TomlItem) {
if let (TomlItem::Value(existing_value), TomlItem::Value(replacement_value)) =
(existing, replacement)
{
replacement_value
.decor_mut()
.clone_from(existing_value.decor());
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
#[tokio::test]
async fn upserts_multiple_hook_trusted_hashes() {
let codex_home = TempDir::new().unwrap();
upsert_user_hook_trusted_hashes(
codex_home.path(),
vec![
(
"plugin:pre_tool_use:0".to_string(),
"sha256:first".to_string(),
),
("plugin:stop:0".to_string(), "sha256:second".to_string()),
],
)
.await
.unwrap();
let config = read_config(codex_home.path());
let expected: toml::Value = toml::from_str(
r#"
[hooks.state."plugin:pre_tool_use:0"]
trusted_hash = "sha256:first"
[hooks.state."plugin:stop:0"]
trusted_hash = "sha256:second"
"#,
)
.unwrap();
assert_eq!(config, expected);
}
#[tokio::test]
async fn preserves_existing_hook_state_fields_and_formatting() {
let codex_home = TempDir::new().unwrap();
let config_path = codex_home.path().join(CONFIG_TOML_FILE);
fs::write(
&config_path,
r#"# leading comment
model = "o3"
[hooks.state."plugin:stop:0"]
enabled = false # keep disabled
trusted_hash = "sha256:old" # trust hash
custom = "preserved"
"#,
)
.unwrap();
upsert_user_hook_trusted_hashes(
codex_home.path(),
vec![("plugin:stop:0".to_string(), "sha256:new".to_string())],
)
.await
.unwrap();
assert_eq!(
fs::read_to_string(config_path).unwrap(),
r#"# leading comment
model = "o3"
[hooks.state."plugin:stop:0"]
enabled = false # keep disabled
trusted_hash = "sha256:new" # trust hash
custom = "preserved"
"#
);
}
#[tokio::test]
async fn supports_existing_inline_hook_state() {
let codex_home = TempDir::new().unwrap();
fs::write(
codex_home.path().join(CONFIG_TOML_FILE),
r#"hooks = { state = { "plugin:stop:0" = { enabled = false } } }
"#,
)
.unwrap();
upsert_user_hook_trusted_hashes(
codex_home.path(),
vec![("plugin:stop:0".to_string(), "sha256:new".to_string())],
)
.await
.unwrap();
let config = read_config(codex_home.path());
let expected: toml::Value = toml::from_str(
r#"
[hooks.state."plugin:stop:0"]
enabled = false
trusted_hash = "sha256:new"
"#,
)
.unwrap();
assert_eq!(config, expected);
}
#[tokio::test]
async fn empty_batch_does_not_create_or_read_config() {
let codex_home = TempDir::new().unwrap();
let config_path = codex_home.path().join(CONFIG_TOML_FILE);
fs::write(&config_path, "not valid toml = [").unwrap();
upsert_user_hook_trusted_hashes(codex_home.path(), Vec::new())
.await
.unwrap();
assert_eq!(
fs::read_to_string(config_path).unwrap(),
"not valid toml = ["
);
}
#[tokio::test]
async fn matching_hash_does_not_rewrite_config() {
let codex_home = TempDir::new().unwrap();
let config_path = codex_home.path().join(CONFIG_TOML_FILE);
let original = r#"[hooks.state."plugin:stop:0"]
trusted_hash = "sha256:same"
"#;
fs::write(&config_path, original).unwrap();
upsert_user_hook_trusted_hashes(
codex_home.path(),
vec![("plugin:stop:0".to_string(), "sha256:same".to_string())],
)
.await
.unwrap();
assert_eq!(fs::read_to_string(config_path).unwrap(), original);
}
#[tokio::test]
#[cfg(unix)]
async fn follows_config_symlink() {
use std::os::unix::fs::symlink;
let codex_home = TempDir::new().unwrap();
let target_path = codex_home.path().join("target_config.toml");
symlink(&target_path, codex_home.path().join(CONFIG_TOML_FILE)).unwrap();
upsert_user_hook_trusted_hashes(
codex_home.path(),
vec![("plugin:stop:0".to_string(), "sha256:new".to_string())],
)
.await
.unwrap();
assert!(codex_home.path().join(CONFIG_TOML_FILE).is_symlink());
let config =
toml::from_str::<toml::Value>(&fs::read_to_string(target_path).unwrap()).unwrap();
let expected: toml::Value = toml::from_str(
r#"
[hooks.state."plugin:stop:0"]
trusted_hash = "sha256:new"
"#,
)
.unwrap();
assert_eq!(config, expected);
}
fn read_config(codex_home: &Path) -> toml::Value {
toml::from_str(&fs::read_to_string(codex_home.join(CONFIG_TOML_FILE)).unwrap()).unwrap()
}
}
+3
View File
@@ -7,6 +7,7 @@ mod constraint;
mod diagnostics;
mod fingerprint;
mod hook_config;
mod hook_edit;
mod host_name;
mod key_aliases;
pub mod loader;
@@ -106,6 +107,8 @@ pub use hook_config::HooksFile;
pub use hook_config::HooksToml;
pub use hook_config::ManagedHooksRequirementsToml;
pub use hook_config::MatcherGroup;
pub use hook_edit::upsert_hook_trusted_hashes;
pub use hook_edit::upsert_user_hook_trusted_hashes;
pub use host_name::host_name;
pub use marketplace_edit::MarketplaceConfigUpdate;
pub use marketplace_edit::RemoveMarketplaceConfigOutcome;
+94
View File
@@ -0,0 +1,94 @@
use crate::loader::load_plugin_hooks;
use crate::manifest::load_plugin_manifest;
use crate::store::PluginStore;
use crate::store::PluginStoreError;
use codex_config::ConfigLayerStack;
use codex_hooks::PluginHookTrustEntry;
use codex_plugin::PluginId;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::path::Path;
#[derive(Debug, thiserror::Error)]
pub enum PluginHookTrustError {
#[error("installed plugin `{plugin_id}` has a missing or invalid plugin.json")]
InvalidManifest { plugin_id: String },
#[error("failed to load hooks for installed plugin `{plugin_id}`: {warnings}")]
HookLoad { plugin_id: String, warnings: String },
#[error("{0}")]
Store(#[from] PluginStoreError),
#[error("failed to persist automatic plugin hook trust: {0}")]
Persist(#[from] std::io::Error),
}
/// Resolve canonical trust identities from a fully materialized plugin root.
pub fn installed_plugin_hook_trust_entries(
codex_home: &Path,
plugin_id: &PluginId,
installed_path: &AbsolutePathBuf,
) -> Result<Vec<PluginHookTrustEntry>, PluginHookTrustError> {
let manifest = load_plugin_manifest(installed_path.as_path()).ok_or_else(|| {
PluginHookTrustError::InvalidManifest {
plugin_id: plugin_id.as_key(),
}
})?;
let store = PluginStore::try_new(codex_home.to_path_buf())?;
let (hook_sources, warnings) = load_plugin_hooks(
installed_path,
plugin_id,
&store.plugin_data_root(plugin_id),
&manifest.paths,
);
if !warnings.is_empty() {
return Err(PluginHookTrustError::HookLoad {
plugin_id: plugin_id.as_key(),
warnings: warnings.join("; "),
});
}
Ok(codex_hooks::plugin_hook_trust_entries(&hook_sources))
}
/// True when every supported command hook already has durable user trust.
pub fn installed_plugin_hook_trust_is_current(
config_layer_stack: &ConfigLayerStack,
entries: &[PluginHookTrustEntry],
) -> bool {
let states = codex_hooks::persisted_user_hook_states_from_stack(Some(config_layer_stack));
entries.iter().all(|entry| {
states
.get(&entry.key)
.and_then(|state| state.trusted_hash.as_deref())
== Some(entry.current_hash.as_str())
})
}
/// Perform the ordinary user-level trust write for installed plugin hooks.
pub async fn trust_installed_plugin_hooks(
codex_home: &Path,
config_layer_stack: &ConfigLayerStack,
plugin_id: &PluginId,
installed_path: &AbsolutePathBuf,
) -> Result<Vec<PluginHookTrustEntry>, PluginHookTrustError> {
let entries = installed_plugin_hook_trust_entries(codex_home, plugin_id, installed_path)?;
codex_config::upsert_hook_trusted_hashes(
selected_user_config_path(codex_home, config_layer_stack).as_path(),
entries
.iter()
.map(|entry| (entry.key.clone(), entry.current_hash.clone()))
.collect(),
)
.await?;
Ok(entries)
}
pub(crate) fn selected_user_config_path(
codex_home: &Path,
config_layer_stack: &ConfigLayerStack,
) -> std::path::PathBuf {
config_layer_stack
.get_user_config_file()
.map(AbsolutePathBuf::to_path_buf)
.unwrap_or_else(|| codex_home.join(codex_config::CONFIG_TOML_FILE))
}
+5
View File
@@ -1,5 +1,6 @@
mod app_mcp_routing;
mod discoverable;
mod hook_trust;
pub mod installed_marketplaces;
pub mod loader;
mod manager;
@@ -39,6 +40,10 @@ pub type PluginLoadOutcome = codex_plugin::PluginLoadOutcome<codex_config::McpSe
pub use app_mcp_routing::apps_route_available;
pub use discoverable::ToolSuggestDiscoverablePlugin;
pub use discoverable::ToolSuggestPluginDiscoveryInput;
pub use hook_trust::PluginHookTrustError;
pub use hook_trust::installed_plugin_hook_trust_entries;
pub use hook_trust::installed_plugin_hook_trust_is_current;
pub use hook_trust::trust_installed_plugin_hooks;
pub use loader::PluginHookLoadOutcome;
pub use manager::ConfiguredMarketplace;
pub use manager::ConfiguredMarketplaceListOutcome;
+1
View File
@@ -998,6 +998,7 @@ impl PluginsManager {
crate::remote::maybe_start_remote_installed_plugin_bundle_sync(
self.codex_home.clone(),
remote_plugin_service_config(config),
config.config_layer_stack.clone(),
auth,
Some(on_local_cache_changed),
);
+23 -1
View File
@@ -209,6 +209,9 @@ pub struct RemotePluginDetail {
pub app_ids: Vec<String>,
pub app_templates: Vec<RemoteAppTemplate>,
pub mcp_servers: Vec<String>,
/// Whether Codex may write ordinary user hook trust for this authenticated
/// remote plugin after successfully materializing its bundle.
pub auto_trust_hooks: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -601,6 +604,16 @@ fn workspace_plugin_discoverability(
})
}
fn remote_plugin_hooks_are_auto_trusted(plugin: &RemotePluginDirectoryItem) -> bool {
match plugin.scope {
RemotePluginScope::User => true,
RemotePluginScope::Workspace => {
plugin.discoverability == Some(RemotePluginShareDiscoverability::Listed)
}
RemotePluginScope::Global => false,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
struct RemotePluginDirectorySharePrincipal {
principal_type: RemotePluginSharePrincipalType,
@@ -1262,6 +1275,7 @@ async fn build_remote_plugin_detail(
mcp_servers.sort_unstable();
mcp_servers.dedup();
let auto_trust_hooks = remote_plugin_hooks_are_auto_trusted(&plugin);
Ok(RemotePluginDetail {
marketplace_name,
marketplace_display_name: scope.marketplace_display_name().to_string(),
@@ -1290,6 +1304,7 @@ async fn build_remote_plugin_detail(
})
.collect(),
mcp_servers,
auto_trust_hooks,
})
}
@@ -1891,7 +1906,14 @@ async fn fetch_plugin_detail(
if include_download_urls {
request = request.query(&[("includeDownloadUrls", true)]);
}
send_and_decode(request, &url).await
let plugin: RemotePluginDirectoryItem = send_and_decode(request, &url).await?;
if plugin.id != plugin_id {
return Err(RemotePluginCatalogError::UnexpectedPluginId {
expected: plugin_id.to_string(),
actual: plugin.id,
});
}
Ok(plugin)
}
fn remote_plugin_skill_detail_url(
@@ -10,9 +10,14 @@ use super::RemotePluginServiceConfig;
use super::ensure_chatgpt_auth;
use super::fetch_installed_plugins_for_scope_with_download_url;
use super::remote_plugin_canonical_marketplace_name;
use super::remote_plugin_hooks_are_auto_trusted;
use crate::hook_trust::selected_user_config_path;
use crate::installed_plugin_hook_trust_entries;
use crate::installed_plugin_hook_trust_is_current;
use crate::store::PLUGINS_CACHE_DIR;
use crate::store::PluginStore;
use crate::store::PluginStoreError;
use codex_config::ConfigLayerStack;
use codex_login::CodexAuth;
use codex_plugin::PluginId;
use std::collections::BTreeMap;
@@ -38,6 +43,8 @@ static REMOTE_PLUGIN_CACHE_MUTATIONS_IN_FLIGHT: OnceLock<
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RemoteInstalledPluginBundleSyncOutcome {
pub installed_plugin_ids: Vec<String>,
pub trusted_hook_plugin_ids: Vec<String>,
pub reinstalled_for_hook_trust_plugin_ids: Vec<String>,
pub removed_cache_plugin_ids: Vec<String>,
pub failed_remote_plugin_ids: Vec<String>,
}
@@ -46,6 +53,10 @@ impl RemoteInstalledPluginBundleSyncOutcome {
pub fn changed_local_cache(&self) -> bool {
!self.installed_plugin_ids.is_empty() || !self.removed_cache_plugin_ids.is_empty()
}
pub fn changed_effective_plugins(&self) -> bool {
self.changed_local_cache() || !self.trusted_hook_plugin_ids.is_empty()
}
}
#[derive(Debug, thiserror::Error)]
@@ -82,6 +93,7 @@ pub struct RemotePluginCacheMutationGuard {
pub(crate) fn maybe_start_remote_installed_plugin_bundle_sync(
codex_home: PathBuf,
config: RemotePluginServiceConfig,
config_layer_stack: ConfigLayerStack,
auth: Option<CodexAuth>,
on_local_cache_changed: Option<Arc<dyn Fn() + Send + Sync + 'static>>,
) {
@@ -96,17 +108,24 @@ pub(crate) fn maybe_start_remote_installed_plugin_bundle_sync(
}
tokio::spawn(async move {
let result =
sync_remote_installed_plugin_bundles_once(codex_home, &config, Some(&auth)).await;
let result = sync_remote_installed_plugin_bundles_once_with_hook_trust(
codex_home,
&config,
Some(&auth),
Some(&config_layer_stack),
)
.await;
match result {
Ok(outcome) => {
if outcome.changed_local_cache()
if outcome.changed_effective_plugins()
&& let Some(on_local_cache_changed) = on_local_cache_changed
{
on_local_cache_changed();
}
info!(
installed_plugin_ids = ?outcome.installed_plugin_ids,
trusted_hook_plugin_ids = ?outcome.trusted_hook_plugin_ids,
reinstalled_for_hook_trust_plugin_ids = ?outcome.reinstalled_for_hook_trust_plugin_ids,
removed_cache_plugin_ids = ?outcome.removed_cache_plugin_ids,
failed_remote_plugin_ids = ?outcome.failed_remote_plugin_ids,
"completed remote installed plugin bundle sync"
@@ -127,6 +146,18 @@ pub async fn sync_remote_installed_plugin_bundles_once(
codex_home: PathBuf,
config: &RemotePluginServiceConfig,
auth: Option<&CodexAuth>,
) -> Result<RemoteInstalledPluginBundleSyncOutcome, RemoteInstalledPluginBundleSyncError> {
sync_remote_installed_plugin_bundles_once_with_hook_trust(
codex_home, config, auth, /*config_layer_stack*/ None,
)
.await
}
async fn sync_remote_installed_plugin_bundles_once_with_hook_trust(
codex_home: PathBuf,
config: &RemotePluginServiceConfig,
auth: Option<&CodexAuth>,
config_layer_stack: Option<&ConfigLayerStack>,
) -> Result<RemoteInstalledPluginBundleSyncOutcome, RemoteInstalledPluginBundleSyncError> {
let auth = ensure_chatgpt_auth(auth)?;
let global = async {
@@ -181,11 +212,26 @@ pub async fn sync_remote_installed_plugin_bundles_once(
),
]);
let mut installed_plugin_ids = BTreeSet::new();
let mut trusted_hook_plugin_ids = BTreeSet::new();
let mut reinstalled_for_hook_trust_plugin_ids = BTreeSet::new();
let mut failed_remote_plugin_ids = BTreeSet::new();
let mut pending_trust_updates = BTreeMap::<String, String>::new();
let mut pending_trust_remote_plugin_ids = BTreeSet::new();
let mut pending_trust_local_plugin_ids = BTreeSet::new();
for (_scope, installed_plugins) in [global, workspace, user] {
for (scope, installed_plugins) in [global, workspace, user] {
for installed_plugin in installed_plugins {
let plugin = installed_plugin.plugin;
if plugin.scope != scope {
warn!(
remote_plugin_id = %plugin.id,
requested_scope = ?scope,
returned_scope = ?plugin.scope,
"skipping remote installed plugin returned for the wrong scope"
);
failed_remote_plugin_ids.insert(plugin.id);
continue;
}
let marketplace_name = remote_plugin_canonical_marketplace_name(&plugin)?.to_string();
installed_plugin_names_by_marketplace
.entry(marketplace_name.clone())
@@ -211,7 +257,12 @@ pub async fn sync_remote_installed_plugin_bundles_once(
.as_deref()
.map(str::trim)
.filter(|version| !version.is_empty());
if store.active_plugin_version(&plugin_id).as_deref() == release_version {
let auto_trust_hooks =
config_layer_stack.is_some() && remote_plugin_hooks_are_auto_trusted(&plugin);
let same_version =
store.active_plugin_version(&plugin_id).as_deref() == release_version;
let mut reinstall_for_hook_trust = false;
if same_version {
if let Err(err) = store.write_remote_plugin_id(&plugin_id, &plugin.id) {
warn!(
remote_plugin_id = %plugin.id,
@@ -221,8 +272,42 @@ pub async fn sync_remote_installed_plugin_bundles_once(
"failed to persist identity for cached remote installed plugin"
);
failed_remote_plugin_ids.insert(plugin.id);
continue;
}
if auto_trust_hooks
&& let (Some(config_layer_stack), Some(installed_path)) =
(config_layer_stack, store.active_plugin_root(&plugin_id))
{
match installed_plugin_hook_trust_entries(
codex_home.as_path(),
&plugin_id,
&installed_path,
) {
Ok(entries)
if installed_plugin_hook_trust_is_current(
config_layer_stack,
&entries,
) =>
{
continue;
}
Ok(_) => {
reinstall_for_hook_trust = true;
}
Err(err) => {
warn!(
remote_plugin_id = %plugin.id,
plugin = %plugin.name,
marketplace = %marketplace_name,
error = %err,
"reinstalling remote plugin whose cached hooks could not be verified"
);
reinstall_for_hook_trust = true;
}
}
} else {
continue;
}
continue;
}
let bundle = match crate::remote_bundle::validate_remote_plugin_bundle(
@@ -254,7 +339,36 @@ pub async fn sync_remote_installed_plugin_bundles_once(
.await
{
Ok(result) => {
installed_plugin_ids.insert(result.plugin_id.as_key());
let local_plugin_id = result.plugin_id.as_key();
installed_plugin_ids.insert(local_plugin_id.clone());
if reinstall_for_hook_trust {
reinstalled_for_hook_trust_plugin_ids.insert(local_plugin_id.clone());
}
if auto_trust_hooks {
match installed_plugin_hook_trust_entries(
codex_home.as_path(),
&result.plugin_id,
&result.installed_path,
) {
Ok(entries) => {
for entry in entries {
pending_trust_updates.insert(entry.key, entry.current_hash);
}
pending_trust_remote_plugin_ids.insert(plugin.id.clone());
pending_trust_local_plugin_ids.insert(local_plugin_id);
}
Err(err) => {
warn!(
remote_plugin_id = %plugin.id,
plugin = %plugin.name,
marketplace = %marketplace_name,
error = %err,
"failed to discover freshly installed remote plugin hooks for automatic trust"
);
failed_remote_plugin_ids.insert(plugin.id.clone());
}
}
}
}
Err(err) => {
warn!(
@@ -270,17 +384,46 @@ pub async fn sync_remote_installed_plugin_bundles_once(
}
}
let codex_home_for_cleanup = codex_home.clone();
let removed_cache_plugin_ids = tokio::task::spawn_blocking(move || {
remove_stale_remote_plugin_caches(
codex_home.as_path(),
codex_home_for_cleanup.as_path(),
&installed_plugin_names_by_marketplace,
)
})
.await?
.map_err(RemoteInstalledPluginBundleSyncError::CacheRemove)?;
if !pending_trust_updates.is_empty() {
if let Some(config_layer_stack) = config_layer_stack {
let config_path = selected_user_config_path(codex_home.as_path(), config_layer_stack);
match codex_config::upsert_hook_trusted_hashes(
config_path.as_path(),
pending_trust_updates.into_iter().collect(),
)
.await
{
Ok(()) => trusted_hook_plugin_ids.extend(pending_trust_local_plugin_ids),
Err(err) => {
warn!(
error = %err,
"failed to persist automatic trust for remote plugin hooks"
);
failed_remote_plugin_ids.extend(pending_trust_remote_plugin_ids);
}
}
} else {
warn!("automatic hook trust updates had no user config layer stack");
failed_remote_plugin_ids.extend(pending_trust_remote_plugin_ids);
}
}
Ok(RemoteInstalledPluginBundleSyncOutcome {
installed_plugin_ids: installed_plugin_ids.into_iter().collect(),
trusted_hook_plugin_ids: trusted_hook_plugin_ids.into_iter().collect(),
reinstalled_for_hook_trust_plugin_ids: reinstalled_for_hook_trust_plugin_ids
.into_iter()
.collect(),
removed_cache_plugin_ids,
failed_remote_plugin_ids: failed_remote_plugin_ids.into_iter().collect(),
})
+24
View File
@@ -96,6 +96,30 @@ fn unknown_installation_policy_source_maps_to_none() {
assert_eq!(summary.install_policy_source, None);
}
#[test]
fn hook_auto_trust_is_limited_to_user_and_listed_workspace_plugins() {
let mut plugin = directory_plugin("plugin-linear", "linear");
plugin.scope = RemotePluginScope::User;
assert!(remote_plugin_hooks_are_auto_trusted(&plugin));
plugin.scope = RemotePluginScope::Workspace;
plugin.discoverability = Some(RemotePluginShareDiscoverability::Listed);
assert!(remote_plugin_hooks_are_auto_trusted(&plugin));
for discoverability in [
RemotePluginShareDiscoverability::Private,
RemotePluginShareDiscoverability::Unlisted,
] {
plugin.discoverability = Some(discoverability);
assert!(!remote_plugin_hooks_are_auto_trusted(&plugin));
}
plugin.scope = RemotePluginScope::Global;
plugin.discoverability = None;
assert!(!remote_plugin_hooks_are_auto_trusted(&plugin));
}
fn directory_plugin(id: &str, name: &str) -> RemotePluginDirectoryItem {
RemotePluginDirectoryItem {
id: id.to_string(),
+72 -4
View File
@@ -15,6 +15,31 @@ use codex_config::TomlValue;
/// state.
pub fn hook_states_from_stack(
config_layer_stack: Option<&ConfigLayerStack>,
) -> HashMap<String, HookStateToml> {
hook_states_from_stack_with_sources(config_layer_stack, |source| {
matches!(
source,
ConfigLayerSource::User { .. } | ConfigLayerSource::SessionFlags
)
})
}
/// Build persisted hook state from user config layers only.
///
/// Unlike [`hook_states_from_stack`], this excludes ephemeral session-flag
/// overrides and is suitable for background reconciliation against durable
/// user preferences.
pub fn persisted_user_hook_states_from_stack(
config_layer_stack: Option<&ConfigLayerStack>,
) -> HashMap<String, HookStateToml> {
hook_states_from_stack_with_sources(config_layer_stack, |source| {
matches!(source, ConfigLayerSource::User { .. })
})
}
fn hook_states_from_stack_with_sources(
config_layer_stack: Option<&ConfigLayerStack>,
include_source: impl Fn(&ConfigLayerSource) -> bool,
) -> HashMap<String, HookStateToml> {
let Some(config_layer_stack) = config_layer_stack else {
return HashMap::new();
@@ -25,10 +50,7 @@ pub fn hook_states_from_stack(
ConfigLayerStackOrdering::LowestPrecedenceFirst,
/*include_disabled*/ true,
) {
if !matches!(
layer.name,
ConfigLayerSource::User { .. } | ConfigLayerSource::SessionFlags
) {
if !include_source(&layer.name) {
continue;
}
@@ -159,6 +181,52 @@ mod tests {
);
}
#[test]
fn persisted_user_hook_states_excludes_session_flags() {
let key = "file:/tmp/hooks.json:pre_tool_use:0:0";
let stack = ConfigLayerStack::new(
vec![
ConfigLayerEntry::new(
ConfigLayerSource::User {
file: test_path_buf("/tmp/config.toml").abs(),
profile: None,
},
config_with_hook_state(
key,
HookStateToml {
enabled: Some(false),
trusted_hash: Some("sha256:user".to_string()),
},
),
),
ConfigLayerEntry::new(
ConfigLayerSource::SessionFlags,
config_with_hook_state(
key,
HookStateToml {
enabled: Some(true),
trusted_hash: Some("sha256:session".to_string()),
},
),
),
],
Default::default(),
Default::default(),
)
.expect("config layer stack");
assert_eq!(
persisted_user_hook_states_from_stack(Some(&stack)),
HashMap::from([(
key.to_string(),
HookStateToml {
enabled: Some(false),
trusted_hash: Some("sha256:user".to_string()),
},
)])
);
}
#[test]
fn hook_states_from_stack_ignores_malformed_hook_events() {
let key = "file:/tmp/hooks.json:pre_tool_use:0:0";
+78
View File
@@ -8,6 +8,13 @@ pub struct PluginHookDeclaration {
pub event_name: HookEventName,
}
/// Persisted trust identity for one supported executable plugin command hook.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginHookTrustEntry {
pub key: String,
pub current_hash: String,
}
/// Return the hook handlers declared by plugin bundles without projecting live runtime state.
pub fn plugin_hook_declarations(hook_sources: &[PluginHookSource]) -> Vec<PluginHookDeclaration> {
let mut declarations = Vec::new();
@@ -32,6 +39,26 @@ pub fn plugin_hook_declarations(hook_sources: &[PluginHookSource]) -> Vec<Plugin
declarations
}
/// Return trust identities for supported executable plugin command hooks.
///
/// This projects runtime discovery results so filtering, platform command
/// selection, normalization, and hashing stay identical to hook execution.
pub fn plugin_hook_trust_entries(hook_sources: &[PluginHookSource]) -> Vec<PluginHookTrustEntry> {
crate::engine::discovery::discover_handlers(
/*config_layer_stack*/ None,
hook_sources.to_vec(),
/*plugin_hook_load_warnings*/ Vec::new(),
/*bypass_hook_trust*/ false,
)
.hook_entries
.into_iter()
.map(|entry| PluginHookTrustEntry {
key: entry.key,
current_hash: entry.current_hash,
})
.collect()
}
pub(crate) fn plugin_hook_key_source(plugin_id: &str, source_relative_path: &str) -> String {
format!("{plugin_id}:{source_relative_path}")
}
@@ -98,4 +125,55 @@ mod tests {
]
);
}
#[test]
fn trust_entries_include_only_supported_executable_command_hooks() {
let plugin_root = test_path_buf("/tmp/plugin").abs();
let source_path = plugin_root.join("hooks/hooks.json");
let entries = plugin_hook_trust_entries(&[PluginHookSource {
plugin_id: PluginId::parse("demo@test").expect("plugin id"),
plugin_root: plugin_root.clone(),
plugin_data_root: plugin_root.join("data"),
source_path,
source_relative_path: "hooks/hooks.json".to_string(),
hooks: HookEventsToml {
pre_tool_use: vec![MatcherGroup {
matcher: Some("^Bash$".to_string()),
hooks: vec![
HookHandlerConfig::Command {
command: "echo supported".to_string(),
command_windows: None,
timeout_sec: None,
r#async: false,
status_message: None,
},
HookHandlerConfig::Command {
command: "echo async".to_string(),
command_windows: None,
timeout_sec: None,
r#async: true,
status_message: None,
},
HookHandlerConfig::Command {
command: " ".to_string(),
command_windows: None,
timeout_sec: None,
r#async: false,
status_message: None,
},
HookHandlerConfig::Prompt {},
HookHandlerConfig::Agent {},
],
}],
..Default::default()
},
}]);
assert_eq!(entries.len(), 1);
assert_eq!(
entries[0].key,
"demo@test:hooks/hooks.json:pre_tool_use:0:0"
);
assert!(!entries[0].current_hash.is_empty());
}
}
+3
View File
@@ -11,8 +11,11 @@ mod types;
use codex_protocol::protocol::HookEventName;
pub use config_rules::hook_states_from_stack;
pub use config_rules::persisted_user_hook_states_from_stack;
pub use declarations::PluginHookDeclaration;
pub use declarations::PluginHookTrustEntry;
pub use declarations::plugin_hook_declarations;
pub use declarations::plugin_hook_trust_entries;
pub use engine::HookListEntry;
pub use events::common::SubagentHookContext;
/// Hook event names as they appear in hooks JSON and config files.