mirror of
https://github.com/openai/codex.git
synced 2026-12-04 00:51:02 +00:00
## Why A plugin's scripts can change without changing its hook declaration. Declaration-only approval therefore lets changed plugin code run under an existing hook approval. ## What changed - Fingerprint plugin bundle contents and include the content hash in the approval value returned by `hooks/list`. Persist it as `trusted_content_hash`, keeping `trusted_hash` compatible with older clients. - Verify contents before each command or MCP hook execution, within the hook's timeout, and require renewed approval when approved contents change. - Migrate legacy declaration-only approvals to a shared, immutable content baseline per plugin and config home. - Exclude generated Python bytecode, `.venv`, and `.egg-info` entries from fingerprints. Run app-server hook listing on blocking tasks. ## Testing Extend integration coverage for plugin upgrades and rollbacks requiring approval, same-turn script changes preventing further hook execution, shared legacy approval baselines, and generated Python artifacts preserving trust. GitOrigin-RevId: faaf7658210d8adb2534ddd614c72ec993920840
183 lines
6.2 KiB
Rust
183 lines
6.2 KiB
Rust
use std::sync::LazyLock;
|
|
use std::time::Duration;
|
|
use std::time::Instant;
|
|
|
|
use anyhow::Context;
|
|
use anyhow::Result;
|
|
use codex_protocol::models::ContentItemMetadata;
|
|
use regex::Regex;
|
|
use serde_json::Map;
|
|
use serde_json::Value;
|
|
|
|
use super::ConfiguredHandler;
|
|
use super::HandlerRunResult;
|
|
use super::HandlerSourcePath;
|
|
use crate::mcp::HookMcpCall;
|
|
use crate::mcp::HookMcpExecutor;
|
|
|
|
/// Expands an MCP argument template against this hook event and invokes the configured tool.
|
|
#[tracing::instrument(
|
|
name = "codex.hooks.mcp_tool",
|
|
level = "trace",
|
|
skip_all,
|
|
fields(
|
|
hook.server = server,
|
|
hook.tool = tool,
|
|
hook.timeout_sec = handler.timeout_sec,
|
|
)
|
|
)]
|
|
pub(crate) async fn run_mcp_tool(
|
|
executor: &dyn HookMcpExecutor,
|
|
handler: &ConfiguredHandler,
|
|
server: &str,
|
|
tool: &str,
|
|
argument_template: &Map<String, Value>,
|
|
hook_event_json: &str,
|
|
metadata: Option<&Map<String, Value>>,
|
|
) -> HandlerRunResult {
|
|
let started_at = chrono::Utc::now().timestamp();
|
|
let started = Instant::now();
|
|
let timeout_started = tokio::time::Instant::now();
|
|
let duration = Duration::from_secs(handler.timeout_sec);
|
|
let result = async {
|
|
if let Some(trust) = &handler.plugin_trust {
|
|
tokio::time::timeout(duration, trust.verify())
|
|
.await
|
|
.context("hook trust verification timed out")??;
|
|
}
|
|
let hook_event: Value =
|
|
serde_json::from_str(hook_event_json).context("failed to parse hook event input")?;
|
|
let input = expand_mcp_argument_template(argument_template, &hook_event)?;
|
|
let (environment_id, mut call_metadata) = match &handler.source_path {
|
|
HandlerSourcePath::Local(_) => (None, None),
|
|
HandlerSourcePath::ExecutorScoped {
|
|
environment_id,
|
|
mcp_environment_id,
|
|
mcp_metadata,
|
|
..
|
|
} => (
|
|
Some(
|
|
mcp_environment_id
|
|
.as_ref()
|
|
.unwrap_or(environment_id)
|
|
.clone(),
|
|
),
|
|
mcp_metadata.as_deref().cloned(),
|
|
),
|
|
};
|
|
if let Some(metadata) = metadata {
|
|
call_metadata
|
|
.get_or_insert_with(Map::new)
|
|
.extend(metadata.clone());
|
|
}
|
|
executor
|
|
.execute(HookMcpCall {
|
|
server: server.to_string(),
|
|
tool: tool.to_string(),
|
|
environment_id,
|
|
metadata: call_metadata,
|
|
input,
|
|
timeout: if handler.plugin_trust.is_some() {
|
|
duration.saturating_sub(timeout_started.elapsed())
|
|
} else {
|
|
Duration::from_secs(handler.timeout_sec)
|
|
},
|
|
})
|
|
.await
|
|
}
|
|
.await;
|
|
|
|
let (exit_code, stdout, error, source_tool_namespace) = match result {
|
|
Ok(output) => (Some(0), output.text, None, output.source_tool_namespace),
|
|
Err(error) => (None, String::new(), Some(error.to_string()), None),
|
|
};
|
|
HandlerRunResult {
|
|
context_metadata: ContentItemMetadata::tool(source_tool_namespace.map(Into::into)),
|
|
started_at,
|
|
completed_at: chrono::Utc::now().timestamp(),
|
|
duration_ms: started.elapsed().as_millis().try_into().unwrap_or(i64::MAX),
|
|
exit_code,
|
|
stdout,
|
|
stderr: String::new(),
|
|
error,
|
|
}
|
|
}
|
|
|
|
/// Recursively substitutes `${field.nested}` placeholders using values from a hook event.
|
|
///
|
|
/// A complete placeholder preserves its JSON type; a placeholder embedded in surrounding
|
|
/// text is rendered as a string. Missing fields fail the hook instead of passing unresolved
|
|
/// arguments to the server. For example, the template `{"count":"${tool_input.count}"}`
|
|
/// becomes `{"count":3}` when the event contains `{"tool_input":{"count":3}}`.
|
|
pub(crate) fn expand_mcp_argument_template(
|
|
argument_template: &Map<String, Value>,
|
|
hook_event: &Value,
|
|
) -> Result<Map<String, Value>> {
|
|
argument_template
|
|
.iter()
|
|
.map(|(key, value)| Ok((key.clone(), resolve_value(value, hook_event)?)))
|
|
.collect()
|
|
}
|
|
|
|
fn resolve_value(value: &Value, hook_event: &Value) -> Result<Value> {
|
|
match value {
|
|
Value::Object(input) => Ok(Value::Object(expand_mcp_argument_template(
|
|
input, hook_event,
|
|
)?)),
|
|
Value::Array(items) => items
|
|
.iter()
|
|
.map(|item| resolve_value(item, hook_event))
|
|
.collect::<Result<Vec<_>>>()
|
|
.map(Value::Array),
|
|
Value::String(text) => resolve_string(text, hook_event),
|
|
_ => Ok(value.clone()),
|
|
}
|
|
}
|
|
|
|
fn resolve_string(text: &str, hook_event: &Value) -> Result<Value> {
|
|
static PLACEHOLDER_PATTERN: LazyLock<Result<Regex, regex::Error>> =
|
|
LazyLock::new(|| Regex::new(r"\$\{([^{}]+)\}"));
|
|
let pattern = PLACEHOLDER_PATTERN.as_ref().map_err(Clone::clone)?;
|
|
let captures = pattern.captures_iter(text).collect::<Vec<_>>();
|
|
if captures.is_empty() {
|
|
return Ok(Value::String(text.to_string()));
|
|
}
|
|
|
|
if let [capture] = captures.as_slice()
|
|
&& let Some(placeholder) = capture.get(0)
|
|
&& placeholder.start() == 0
|
|
&& placeholder.end() == text.len()
|
|
{
|
|
return resolve_path(hook_event, &capture[1]).cloned();
|
|
}
|
|
|
|
let mut resolved = String::new();
|
|
let mut previous_end = 0;
|
|
for capture in captures {
|
|
let Some(placeholder) = capture.get(0) else {
|
|
continue;
|
|
};
|
|
resolved.push_str(&text[previous_end..placeholder.start()]);
|
|
let value = resolve_path(hook_event, &capture[1])?;
|
|
match value {
|
|
Value::String(value) => resolved.push_str(value),
|
|
_ => resolved.push_str(&serde_json::to_string(value)?),
|
|
}
|
|
previous_end = placeholder.end();
|
|
}
|
|
resolved.push_str(&text[previous_end..]);
|
|
Ok(Value::String(resolved))
|
|
}
|
|
|
|
fn resolve_path<'a>(hook_event: &'a Value, path: &str) -> Result<&'a Value> {
|
|
path.split('.').try_fold(hook_event, |value, field| {
|
|
value
|
|
.get(field)
|
|
.with_context(|| format!("hook input placeholder `${{{path}}}` was not found"))
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "mcp_runner_tests.rs"]
|
|
mod tests;
|