diff --git a/crates/openhuman-core/src/integrations/composio/flow_backend.rs b/crates/openhuman-core/src/integrations/composio/flow_backend.rs index 6eb7ba1d048..149605e4fe7 100644 --- a/crates/openhuman-core/src/integrations/composio/flow_backend.rs +++ b/crates/openhuman-core/src/integrations/composio/flow_backend.rs @@ -74,6 +74,9 @@ pub(crate) async fn invoke( if live.recovered_from_corruption { return Err(policy_refresh_error()); } + // The keys this call may send, read before it (and before any approval is + // recorded): redaction covers them even if the stored key changes meanwhile. + let keys = crate::integrations::composio::tools::composio_call_keys(&live).await?; // Keep the privacy-sensitive tier decision before curation so a read-only // caller cannot probe which actions are in scope. @@ -116,20 +119,30 @@ pub(crate) async fn invoke( tracing::debug!(target: "flows", %slug, mode = live.composio.mode.as_str(), "[flows] tool_call: no connection_ref — using the ambient signed-in account") } } - let response = execute_for_connection( + let executed = execute_for_connection( &live, slug, (!args.is_null()).then_some(args), connection_id, ) - .await - .and_then(|result| { - crate::integrations::composio::flow_gate::reject_unsuccessful_composio_response( - slug, result, - ) - .map_err(|error| error.to_string()) - }) - .and_then(|result| serde_json::to_value(result).map_err(|error| error.to_string())); + .await; + // The run output is stored and shown to the user: strip the Composio + // keys from it, as the agent tools do with their results. + let redacted = match executed { + Ok(result) => { + crate::integrations::composio::tools::redact_composio_response(&live, keys, result) + .await + } + Err(error) => Err(error), + }; + let response = redacted + .and_then(|result| { + crate::integrations::composio::flow_gate::reject_unsuccessful_composio_response( + slug, result, + ) + .map_err(|error| error.to_string()) + }) + .and_then(|result| serde_json::to_value(result).map_err(|error| error.to_string())); if let Some(audit_id) = audit_id { ctx.policy.record(&audit_id, &response); } diff --git a/crates/openhuman-core/src/integrations/composio/ops/execute.rs b/crates/openhuman-core/src/integrations/composio/ops/execute.rs index 68b50222c24..02bf972afd1 100644 --- a/crates/openhuman-core/src/integrations/composio/ops/execute.rs +++ b/crates/openhuman-core/src/integrations/composio/ops/execute.rs @@ -31,12 +31,38 @@ pub async fn composio_execute( connection_id: Option<&str>, ) -> OpResult> { tracing::debug!(tool = %tool, connection_id = ?connection_id, "[composio] rpc execute"); + // The keys this call may send, read before it: redaction covers them even + // if the stored key changes while it runs. + let keys = super::super::tools::composio_call_keys(config).await?; let started = std::time::Instant::now(); let result = execute_composio_action(config, None, tool, arguments, connection_id).await; let elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); match result { Ok(resp) => { + // The RPC result reaches the renderer and the RPC log: strip the + // Composio keys from it, as the agent tools do with their results. + let (successful, failed_with_text, cost_usd) = + (resp.successful, resp.error.is_some(), resp.cost_usd); + let resp = match super::super::tools::redact_composio_response(config, keys, resp).await + { + Ok(resp) => resp, + Err(withheld) => { + // The action ran and may have cost something: record it, + // without the provider's error text that could not be + // cleaned. + crate::core::bus::BUS.publish( + crate::core::events::DomainEvent::ComposioActionExecuted { + tool: tool.to_string(), + success: successful, + error: failed_with_text.then(|| withheld.clone()), + cost_usd, + elapsed_ms, + }, + ); + return Err(withheld); + } + }; // Note that this is reached for a *refused* action too: the module // reports a provider's refusal as a successful reply carrying // `successful: false`. The event records what happened, not whether diff --git a/crates/openhuman-core/src/integrations/composio/tools.rs b/crates/openhuman-core/src/integrations/composio/tools.rs index c0758b302ec..85f27d8faf4 100644 --- a/crates/openhuman-core/src/integrations/composio/tools.rs +++ b/crates/openhuman-core/src/integrations/composio/tools.rs @@ -44,7 +44,7 @@ mod tests; pub use execute::ComposioExecuteTool; pub(crate) use live_config::live_composio_config; -pub(crate) use redact::redact_composio_outcome; +pub(crate) use redact::{composio_call_keys, redact_composio_outcome, redact_composio_response}; pub use registry::all_composio_agent_tools; // Brought into this module's own namespace (private `use`, not `pub use`) diff --git a/crates/openhuman-core/src/integrations/composio/tools/redact.rs b/crates/openhuman-core/src/integrations/composio/tools/redact.rs index 2f65384d8c6..2e64a783d7b 100644 --- a/crates/openhuman-core/src/integrations/composio/tools/redact.rs +++ b/crates/openhuman-core/src/integrations/composio/tools/redact.rs @@ -3,6 +3,7 @@ use tinytools::ToolResult; use crate::config::Config; +use crate::integrations::composio::types::ComposioExecuteResponse; const MIN_SECRET_LEN: usize = 8; @@ -11,6 +12,13 @@ const MIN_SECRET_LEN: usize = 8; /// encoded forms are included because the provider may echo a key in a URL or /// encoded identifier. pub(crate) async fn composio_secrets(config: &Config) -> Vec { + collect_secrets(config, false).await.unwrap_or_default() +} + +/// [`composio_secrets`], or `Err` when `fail_closed` and the stored key +/// cannot be read: a key that dispatch may have sent but redaction cannot +/// see must not let a result through. +async fn collect_secrets(config: &Config, fail_closed: bool) -> Result, String> { let composio = &config.composio; let mut secrets: Vec = Vec::new(); if let Some(pinned) = composio.host_credential.as_ref() { @@ -22,9 +30,16 @@ pub(crate) async fn composio_secrets(config: &Config) -> Vec { if composio.host_credential.is_none() && composio.mode.trim() == crate::config::schema::COMPOSIO_MODE_DIRECT { - if let Ok(Some(stored)) = crate::integrations::composio::get_composio_api_key(config).await - { - secrets.push(stored); + match crate::integrations::composio::get_composio_api_key(config).await { + Ok(Some(stored)) => secrets.push(stored), + Ok(None) => {} + Err(error) if fail_closed => { + tracing::debug!("[composio][redact] stored key unreadable, failing closed"); + return Err(format!( + "failed to read the stored composio api key: {error}" + )); + } + Err(_) => {} } } let originals = secrets.clone(); @@ -39,7 +54,7 @@ pub(crate) async fn composio_secrets(config: &Config) -> Vec { secrets.retain(|s| s.len() >= MIN_SECRET_LEN); secrets.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.cmp(b))); secrets.dedup(); - secrets + Ok(secrets) } async fn redact_exact(config: &Config, text: &str, secrets: &[String]) -> Result { @@ -87,6 +102,64 @@ async fn redact_known_secrets(config: &Config, rendered: &str) -> String { } } +/// Withheld in place of anything the redactor could not clean. +const WITHHELD: &str = "Composio result withheld by security redactor"; + +/// `value` with every key in `secrets` removed, round-tripped through its JSON +/// form. `Err` when the module cannot answer or the result no longer parses. +async fn redact_serialized(config: &Config, value: &T, secrets: &[String]) -> Result +where + T: serde::Serialize + serde::de::DeserializeOwned, +{ + let encoded = serde_json::to_string(value).map_err(|_| { + tracing::debug!("[composio][redact] withheld: result does not encode"); + })?; + let redacted = redact_exact(config, &encoded, secrets) + .await + .map_err(|_| tracing::debug!("[composio][redact] withheld: TinySecurity did not redact"))?; + serde_json::from_str(&redacted).map_err(|_| { + tracing::debug!("[composio][redact] withheld: redacted result does not decode"); + }) +} + +/// The Composio keys an Execute on `config` may send, read just before the +/// call: pass them to [`redact_composio_response`] with its result. `Err` +/// when the stored key cannot be read, which dispatch would refuse too. +pub(crate) async fn composio_call_keys(config: &Config) -> Result, String> { + if crate::security::switch::disabled_for(Some(config)).is_some() { + return Ok(Vec::new()); + } + collect_secrets(config, true).await +} + +/// Redact an Execute response before it leaves the host through an RPC or a +/// flow, as the agent tools' results are, with the keys read before the call +/// (`before`, from [`composio_call_keys`]) and again now. Dispatch reads the +/// key between the two, so a key rotated during a slow call is still covered. +/// A module failure or an unreadable stored key withholds it. With security +/// disabled it is returned as is. +pub(crate) async fn redact_composio_response( + config: &Config, + before: Vec, + response: ComposioExecuteResponse, +) -> Result { + if crate::security::switch::disabled_for(Some(config)).is_some() { + return Ok(response); + } + let mut secrets = collect_secrets(config, true) + .await + .map_err(|_| WITHHELD.to_owned())?; + secrets.extend(before); + secrets.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.cmp(b))); + secrets.dedup(); + if secrets.is_empty() { + return Ok(response); + } + redact_serialized(config, &response, &secrets) + .await + .map_err(|()| WITHHELD.to_owned()) +} + /// Redact a tool result or error with call-specific credentials before it /// reaches the model. A malformed result or module failure is withheld. With /// security disabled the outcome is returned unredacted. @@ -102,15 +175,9 @@ pub(crate) async fn redact_composio_outcome( return outcome; } match outcome { - Ok(result) => { - let encoded = serde_json::to_string(&result) - .map_err(|_| anyhow::anyhow!("Composio result withheld by security redactor"))?; - let redacted = redact_exact(config, &encoded, &secrets) - .await - .map_err(|_| anyhow::anyhow!("Composio result withheld by security redactor"))?; - serde_json::from_str(&redacted) - .map_err(|_| anyhow::anyhow!("Composio result withheld by security redactor")) - } + Ok(result) => redact_serialized(config, &result, &secrets) + .await + .map_err(|()| anyhow::anyhow!(WITHHELD)), Err(error) => { let rendered = format!("{error:#}"); match redact_exact(config, &rendered, &secrets).await { diff --git a/crates/openhuman-core/src/integrations/composio/tools_host_credential_tests.rs b/crates/openhuman-core/src/integrations/composio/tools_host_credential_tests.rs index bf58793bc42..59e918ca610 100644 --- a/crates/openhuman-core/src/integrations/composio/tools_host_credential_tests.rs +++ b/crates/openhuman-core/src/integrations/composio/tools_host_credential_tests.rs @@ -313,3 +313,32 @@ async fn cache_key_is_stable_for_unpinned_direct_mode_when_nothing_rotates() { assert_eq!(cache_key(&base).await, cache_key(&base).await); } + +/// A key rotated while an Execute runs never comes back in its result: the +/// keys read before the call are redacted along with the current ones. +#[tokio::test] +async fn a_key_rotated_during_execute_is_still_redacted_from_its_result() { + use crate::integrations::composio::tools::{composio_call_keys, redact_composio_response}; + use crate::integrations::composio::types::ComposioExecuteResponse; + let tmp = tempfile::tempdir().unwrap(); + let base = shared_runtime_config(&tmp).await; + let before = composio_call_keys(&pinned(&base, KEY_A, "tenant-a", None)) + .await + .expect("keys before the call"); + let rotated = pinned(&base, KEY_B, "tenant-a", None); + let response = ComposioExecuteResponse { + data: json!({ "echo": KEY_A }), + successful: true, + error: None, + cost_usd: 0.0, + markdown_formatted: None, + }; + + // Redacted, or withheld when the module cannot answer (in a one-process + // run it may serve another test's workspace): either way, never key A. + let returned = match redact_composio_response(&rotated, before, response).await { + Ok(redacted) => serde_json::to_string(&redacted).unwrap(), + Err(withheld) => withheld, + }; + assert!(!returned.contains(KEY_A), "{returned}"); +} diff --git a/crates/openhuman-core/src/tools/schemas/composio.rs b/crates/openhuman-core/src/tools/schemas/composio.rs index 8dfb824b137..1d8a82d2a8b 100644 --- a/crates/openhuman-core/src/tools/schemas/composio.rs +++ b/crates/openhuman-core/src/tools/schemas/composio.rs @@ -19,6 +19,7 @@ pub(super) fn handle_composio_execute( let action_args = params.get("params").cloned(); let config = ctx.load_config().await?; + let keys = crate::integrations::composio::tools::composio_call_keys(&config).await?; // The connector module owns the mode split (backend proxy vs. the // user's personal direct tenant, #1710); this only supplies the config. let resp = crate::integrations::composio::execute_dispatch::execute_composio_action( @@ -31,6 +32,11 @@ pub(super) fn handle_composio_execute( ) .await .map_err(|e| format!("composio execute failed: {e}"))?; + // Strip the Composio keys before the result leaves over RPC, as the + // agent tools do with their results. + let resp = + crate::integrations::composio::tools::redact_composio_response(&config, keys, resp) + .await?; tracing::debug!( action = %action, successful = resp.successful, diff --git a/tests/raw_coverage/composio_direct_tools_e2e.rs b/tests/raw_coverage/composio_direct_tools_e2e.rs index 615ff3950be..f702d91b204 100644 --- a/tests/raw_coverage/composio_direct_tools_e2e.rs +++ b/tests/raw_coverage/composio_direct_tools_e2e.rs @@ -203,6 +203,12 @@ async fn round25_direct_mode_ops_use_loopback_factory_for_tools_connections_and_ Some(&json!("msg-round25")) ); assert_eq!(executed.cost_usd, 0.0); + // TS-E2E-009 (RD-12): the provider echoes the caller's key in every form; + // the RPC op's result carries none of them, as the agent tools' don't. + let returned = serde_json::to_string(&executed).expect("serialize result"); + for form in round25_key_forms() { + assert!(!returned.contains(&form), "the result carried the key as {form}"); + } let failed_execute = composio_execute( &harness.config, @@ -265,6 +271,40 @@ async fn round25_direct_mode_ops_use_loopback_factory_for_tools_connections_and_ && request.body["entity_id"] == " entity-round25 " })); + // An Execute whose result cannot be redacted is withheld, but still + // recorded as executed: the action ran and may have cost something. A key + // that is part of the result's own JSON leaves the redacted result + // undecodable. + openhuman_core::core::bus::init().await.expect("bus init"); + let mut events = openhuman_core::core::bus::BUS + .get() + .expect("bus initialized") + .receiver(); + let mut unredactable = harness.config.clone(); + unredactable.composio.api_key = Some("\"successful\":true".to_string()); + let withheld = composio_execute(&unredactable, "GMAIL_FETCH_EMAILS", None, None).await; + assert_eq!( + withheld.err().as_deref(), + Some("Composio result withheld by security redactor") + ); + let recorded = tokio::time::timeout(std::time::Duration::from_secs(30), async { + loop { + match events.recv().await { + Some(openhuman_core::core::events::DomainEvent::ComposioActionExecuted { + tool, + success, + error, + .. + }) if tool == "GMAIL_FETCH_EMAILS" => return (success, error), + Some(_) => continue, + None => panic!("the bus closed before the execute was recorded"), + } + } + }) + .await + .expect("the withheld execute was not recorded"); + assert_eq!(recorded, (true, None)); + // TS-E2E-008 (EG-16): the UI's `composio.execute` RPC op is held to the // local-only privacy mode like the agent tool, and refused before the // connector module dials Composio. Checked in this test because the @@ -317,6 +357,18 @@ impl Drop for PrivacyScope { } } +/// The direct-mode key `setup_direct_config` stores, and the encoded forms a +/// provider might echo it in. The mock's Execute echoes all four. +fn round25_key_forms() -> [String; 4] { + let key = "ck_round25_direct"; + [ + key.to_owned(), + urlencoding::encode(key).into_owned(), + base64::Engine::encode(&base64::engine::general_purpose::STANDARD, key), + hex::encode(key), + ] +} + async fn start_loopback(app: Router) -> String { let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await @@ -441,7 +493,8 @@ async fn composio_direct_handler(State(state): State, request: Reques "data": { "messages": [ { "id": "msg-round25", "subject": "Coverage" } - ] + ], + "echo": round25_key_forms(), } })) .into_response(),