Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 20 additions & 13 deletions crates/openhuman-core/src/integrations/composio/action_tool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ impl Tool for ComposioActionTool {

async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
let (config, outcome) =
Box::pin(self.execute_unredacted(&dispatch_ctx_for_tool(None), args, None)).await;
Box::pin(self.execute_unredacted(&dispatch_ctx_for_tool(None), args, None, None)).await;
super::tools::redact_composio_outcome(&config, outcome).await
}
async fn execute_with_context(
Expand All @@ -249,11 +249,16 @@ impl Tool for ComposioActionTool {
_options: ToolCallOptions,
context: Option<&dyn ToolRunContext>,
) -> anyhow::Result<ToolResult> {
let (config, outcome) = Box::pin(self.execute_unredacted(
&dispatch_ctx_for_tool(context),
args,
sandbox_mode_for_tool(context),
))
let (config, outcome) = Box::pin(
self.execute_unredacted(
&dispatch_ctx_for_tool(context),
args,
sandbox_mode_for_tool(context),
crate::agent::tinyagents::host::run_context::approval_for_tool(context)
.chat
.as_ref(),
),
)
.await;
super::tools::redact_composio_outcome(&config, outcome).await
}
Expand All @@ -269,6 +274,7 @@ impl ComposioActionTool {
ctx: &DispatchCtx,
args: Value,
sandbox_mode: Option<SandboxMode>,
chat: Option<&crate::security::approval::ApprovalChatContext>,
) -> (Box<Config>, anyhow::Result<ToolResult>) {
// Boxed from the moment it exists, not just at the return: this
// local is held across every await point below, and `Config` is a
Expand Down Expand Up @@ -397,14 +403,15 @@ impl ComposioActionTool {
// direct-mode toggle still takes effect immediately (#1710): the route
// is reconciled from `live_config` on the way through, rather than
// baked into a client this tool captured at construction.
let res = super::module_client::call::<_, super::types::ComposioExecuteResponse>(
// Through the shared dispatch, so the local-only egress policy
// applies to per-action tools as it does to `composio_execute`, and
// the transfer is disclosed in the turn's chat.
let res = super::execute_dispatch::execute_composio_action(
&live_config,
tinyconnectors_bus::names::methods::EXECUTE,
super::types::ComposioExecuteRequest {
tool: self.action_name.clone(),
arguments: args,
connection_id: effective_connection_id.map(str::to_string),
},
chat,
&self.action_name,
args,
effective_connection_id,
)
.await;
let elapsed_ms = started.elapsed().as_millis() as u64;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,7 @@ async fn deferred_instance_returns_live_config_for_redaction() {
&DispatchCtx::process_default(),
serde_json::json!({}),
None,
None,
))
.await;
let first = outcome.expect("contract-gate surface is Ok(error result)");
Expand Down Expand Up @@ -559,3 +560,82 @@ async fn configured_instance_resolves_live_config_not_the_stale_snapshot() {
);
});
}

/// A per-action call in a web-chat turn discloses its transfer in that chat:
/// the tool hands the turn's chat context to the shared dispatch, as
/// `composio_execute` does, so `ExternalTransferPending` carries the thread
/// (`web_chat/egress_surface.rs` drops an unrouted one).
#[tokio::test]
async fn per_action_transfer_is_routed_to_the_turns_chat() {
run_with_big_stack(|| async {
use crate::config::TEST_ENV_LOCK;
use crate::core::events::DomainEvent;
use crate::security::approval::{ApprovalChatContext, ApprovalTurnContext};
let _serialised = super::super::module_client::module_guard().await;
let _env_guard = TEST_ENV_LOCK.lock().await;
crate::core::bus::init().await.expect("bus init");
let mut rx = crate::core::bus::BUS.get().unwrap().receiver();

let tmp = tempfile::tempdir().expect("tempdir");
let _workspace_guard = EnvVarGuard::workspace_unlocked(tmp.path());
let mut config =
crate::integrations::composio::module_client::test_support::config_in(tmp.path());
config.composio.mode = crate::config::schema::COMPOSIO_MODE_DIRECT.to_string();
config.composio.api_key = Some("test-direct-key".to_string());
config.save().await.expect("save config to disk");

let slug = "GMAIL_TSE2E_ROUTED_FETCH";
let tool = ComposioActionTool::new(
Arc::new(config),
slug.to_string(),
"read-shaped slug".to_string(),
None,
);
let context = crate::agent::tinyagents::host::run_context::tool_context_with_approval(
ApprovalTurnContext::chat(ApprovalChatContext {
thread_id: "t-tse2e-008".into(),
client_id: "c-tse2e-008".into(),
request_id: None,
}),
);
// What `execute_with_context` runs, minus the result redaction, which
// in a one-process run may be served another test's workspace and
// would hide why no transfer was disclosed. The module call itself
// may fail with no provider; the disclosure is published before it.
let approval =
crate::agent::tinyagents::host::run_context::approval_for_tool(Some(&context));
let (_, outcome) = Box::pin(tool.execute_unredacted(
&DispatchCtx::process_default(),
serde_json::json!({}),
None,
approval.chat.as_ref(),
))
.await;

// In a one-process run the security module may serve another test's
// workspace and cannot confirm the egress, so the action is refused
// before anything is sent and there is no transfer to disclose.
if let Ok(result) = &outcome {
if result.is_error && error_text(result).contains("could not confirm") {
eprintln!("[test] egress unconfirmed in this process, nothing sent: skipping");
return;
}
}
let routed = tokio::time::timeout(std::time::Duration::from_secs(30), async {
loop {
match rx.recv().await {
Some(DomainEvent::ExternalTransferPending {
descriptor,
thread_id,
..
}) if descriptor.service == slug => return thread_id,
Some(_) => continue,
None => panic!("the bus closed before the transfer was disclosed"),
}
}
})
.await
.unwrap_or_else(|_| panic!("the per-action call disclosed no transfer: {outcome:?}"));
assert_eq!(routed.as_deref(), Some("t-tse2e-008"));
});
}
18 changes: 7 additions & 11 deletions crates/openhuman-core/src/integrations/composio/flow_backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,16 @@ pub(crate) async fn execute_for_connection(
args: Option<Value>,
connection_id: Option<&str>,
) -> Result<crate::integrations::composio::ComposioExecuteResponse, String> {
crate::integrations::composio::module_client::call::<
_,
crate::integrations::composio::ComposioExecuteResponse,
>(
// Through the shared dispatch, so a flow's tool_call is held to the
// local-only egress policy like the agent tool.
crate::integrations::composio::execute_dispatch::execute_composio_action(
config,
tinyconnectors_bus::names::methods::EXECUTE,
crate::integrations::composio::types::ComposioExecuteRequest {
tool: slug.to_string(),
arguments: args,
connection_id: connection_id.map(str::to_string),
},
None,
slug,
args,
connection_id,
)
.await
.map_err(|error| error.to_string())
}

#[async_trait]
Expand Down
23 changes: 5 additions & 18 deletions crates/openhuman-core/src/integrations/composio/ops/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@
use crate::config::Config;
use crate::core::Outcome;

use super::super::module_client::{self as connectors};
use super::super::types::{ComposioExecuteRequest, ComposioExecuteResponse};
use super::super::execute_dispatch::execute_composio_action;
use super::super::types::ComposioExecuteResponse;
use super::error_utils::{report_composio_op_error, OpResult};
use tinyconnectors_bus::names::methods;

/// The prefix the module puts on an error it has already classified.
///
Expand All @@ -23,11 +22,8 @@ const CLASSIFIED: &str = "[composio:error:";
/// the activity feed, the agent's own budget. The module has no bus of the
/// host's to publish on.
///
/// # What the caller must still do
///
/// Apply [`crate::security::egress`] *before* calling this. Local
/// only mode refusing an outbound tool call is policy about the user's data,
/// and the module cannot see the reasons behind it.
/// The call goes through [`execute_composio_action`], so the local-only
/// egress policy applies here as it does to the agent tool.
pub async fn composio_execute(
config: &Config,
tool: &str,
Expand All @@ -36,16 +32,7 @@ pub async fn composio_execute(
) -> OpResult<Outcome<ComposioExecuteResponse>> {
tracing::debug!(tool = %tool, connection_id = ?connection_id, "[composio] rpc execute");
let started = std::time::Instant::now();
let result = connectors::call::<_, ComposioExecuteResponse>(
config,
methods::EXECUTE,
ComposioExecuteRequest {
tool: tool.to_string(),
arguments,
connection_id: connection_id.map(str::to_string),
},
)
.await;
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 {
Expand Down
54 changes: 53 additions & 1 deletion tests/raw_coverage/composio_direct_tools_e2e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ use axum::{Json, Router};
use serde_json::{json, Value};
use tempfile::{Builder, TempDir};

use openhuman_core::config::Config;
use openhuman_core::config::{Config, PrivacyMode};
use openhuman_core::security::{live_policy, SecurityPolicy};
use openhuman_core::integrations::composio::ops::{
cached_active_integrations, composio_authorize, composio_execute, composio_list_connections,
composio_list_toolkits, composio_list_tools, fetch_connected_integrations_status,
Expand Down Expand Up @@ -263,6 +264,57 @@ async fn round25_direct_mode_ops_use_loopback_factory_for_tools_connections_and_
&& request.body["arguments"]["query"] == "label:INBOX"
&& request.body["entity_id"] == " entity-round25 "
}));

// 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
// security module serves the first workspace that calls it.
let _privacy = PrivacyScope::set(PrivacyMode::LocalOnly);
state.requests.lock().expect("requests").clear();
let refused = composio_execute(
&harness.config,
"GMAIL_FETCH_EMAILS",
Some(json!({ "query": "label:INBOX" })),
None,
)
.await;
let error = refused.expect_err("composio_execute ran under local-only privacy");
assert!(
error.to_lowercase().contains("privacy mode is active"),
"unexpected refusal: {error}"
);
let requests = state.requests.lock().expect("requests").clone();
assert!(
!requests
.iter()
.any(|request| request.path.contains("/tools/execute/")),
"Composio received an execute under local-only privacy: {requests:?}"
);
}

/// Holds the live privacy mode at `mode` for one test and puts the previous
/// mode back on drop: the aggregated raw-coverage binary shares one process.
struct PrivacyScope(PrivacyMode);

impl PrivacyScope {
fn set(mode: PrivacyMode) -> Self {
let previous = live_policy::current_privacy_mode();
if live_policy::reload_privacy(mode).is_err() {
let workspace = std::env::temp_dir();
live_policy::install(
Arc::new(SecurityPolicy::default().with_privacy_mode(mode)),
workspace.clone(),
workspace,
);
}
Self(previous)
}
}

impl Drop for PrivacyScope {
fn drop(&mut self) {
let _ = live_policy::reload_privacy(self.0);
}
}

async fn start_loopback(app: Router) -> String {
Expand Down
Loading