Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

test(channels): pin which channel instances may decide an approval by reply

M3gA-Mindd068f39e006b
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
index 6c9b6712d5..208ef8b976 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
@@ -5,7 +5,7 @@
//! context scoping.
//! * [`admit`] — preparation, the received event, and the runtime-command and
//! approval-reply intercepts that run before any debounce.
-//! * [`try_route_approval_reply`] (in [`approval`]) — intercepts yes/no
+//! * [`consumes_approval_reply`] (in [`approval`]) — intercepts yes/no
//! approval replies before dispatching a fresh agent turn.
//! * [`process_channel_message`] — full per-message pipeline: typing, ACK
//! reaction, history, agent turn, draft updates, reply.
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/admit.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/admit.rs
index 4843f733d9..b10870345b 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/admit.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/admit.rs
@@ -10,7 +10,7 @@ use crate::util::truncate_with_ellipsis;
use std::sync::Arc;
use tinychannels_bus::ChannelInboundEnvelope;
-use super::approval::{channel_has_approval_surface, try_route_approval_reply};
+use super::approval::consumes_approval_reply;
use super::RuntimeChannelMessage;
/// A prepared inbound message that still needs an agent turn: not a runtime
@@ -91,11 +91,8 @@ pub(crate) async fn admit_runtime_message(
// A yes/no reply to an approval parked on this conversation decides it;
// a fresh turn would cancel the parked tool call.
- if target_channel
- .as_ref()
- .is_some_and(|channel| channel_has_approval_surface(&channel.capabilities()))
- && try_route_approval_reply(&msg, &history_key).await
- {
+ let gate = crate::security::approval::ApprovalGate::try_global();
+ if consumes_approval_reply(target_channel.as_ref(), gate.as_deref(), &msg, &history_key) {
return None;
}
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/approval.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/approval.rs
index 895c6dcfb8..bc49565a0a 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/approval.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/approval.rs
@@ -22,19 +22,34 @@ pub(crate) fn channel_has_approval_surface(
capabilities.chat_approvals
}
+/// Admission's approval intercept: a yes/no reply decides the approval parked
+/// on `thread_id`, but only on a channel instance that reports
+/// `chat_approvals`. A channel missing from the runtime map fails closed, so
+/// the reply goes out as a fresh turn.
+pub(super) fn consumes_approval_reply(
+ target_channel: Option<&std::sync::Arc<dyn crate::channels::Channel>>,
+ gate: Option<&crate::security::approval::ApprovalGate>,
+ msg: &traits::ChannelInboundEnvelope,
+ thread_id: &str,
+) -> bool {
+ target_channel.is_some_and(|channel| channel_has_approval_surface(&channel.capabilities()))
+ && route_approval_reply(gate, msg, thread_id)
+}
+
/// If the inbound message is a yes/no reply for a parked approval on
/// this thread, route it to [`ApprovalGate::decide`] and return `true`.
/// Otherwise return `false` so the caller can dispatch the message as a
/// fresh turn (which intentionally cancels any parked approval — the
/// user is redirecting). Mirrors the web channel intercept at
-/// `web_chat/`.
+/// `web_chat/`. With no gate installed nothing is intercepted.
///
/// [`ApprovalGate::decide`]: crate::security::approval::ApprovalGate::decide
-pub(super) async fn try_route_approval_reply(
+fn route_approval_reply(
+ gate: Option<&crate::security::approval::ApprovalGate>,
msg: &traits::ChannelInboundEnvelope,
thread_id: &str,
) -> bool {
- let Some(gate) = crate::security::approval::ApprovalGate::try_global() else {
+ let Some(gate) = gate else {
return false;
};
let Some(request_id) = gate.pending_for_thread(thread_id) else {
@@ -77,3 +92,7 @@ pub(super) async fn try_route_approval_reply(
}
}
}
+
+#[cfg(test)]
+#[path = "approval_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/approval_tests.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/approval_tests.rs
new file mode 100644
index 0000000000..0e77393d43
--- /dev/null
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/approval_tests.rs
@@ -0,0 +1,147 @@
+//! The approval-by-reply intercept: which channel instances may decide a
+//! parked approval with a chat reply, and which replies count.
+
+use super::consumes_approval_reply;
+use crate::channels::Channel;
+use crate::security::approval::{
+ ApprovalChatContext, ApprovalGate, ApprovalTurnContext, GateOutcome,
+};
+use crate::security::turn_origin::{self, AgentTurnOrigin};
+use std::sync::Arc;
+use tinychannels_bus as traits;
+
+struct Fake {
+ chat_approvals: bool,
+}
+
+#[async_trait::async_trait]
+impl Channel for Fake {
+ fn name(&self) -> &str {
+ "fake"
+ }
+ fn capabilities(&self) -> traits::ChannelCapabilities {
+ let mut capabilities = traits::ChannelCapabilities::unknown();
+ capabilities.chat_approvals = self.chat_approvals;
+ capabilities
+ }
+ #[allow(
+ deprecated,
+ reason = "TinyChannels v22 still requires the legacy send trait method"
+ )]
+ async fn send(&self, _message: &traits::SendMessage) -> anyhow::Result<()> {
+ Ok(())
+ }
+ #[allow(
+ deprecated,
+ reason = "TinyChannels v22 still requires the legacy listener trait method"
+ )]
+ async fn listen(
+ &self,
+ _tx: tokio::sync::mpsc::Sender<traits::ChannelMessage>,
+ ) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
+
+fn channel(chat_approvals: bool) -> Arc<dyn Channel> {
+ Arc::new(Fake { chat_approvals })
+}
+
+fn reply(text: &str) -> traits::ChannelInboundEnvelope {
+ traits::ChannelInboundEnvelope {
+ text: text.into(),
+ ..Default::default()
+ }
+}
+
+/// Park a tool call on `thread`; returns its request id once it is routed, and
+/// the parked call's task.
+async fn park(
+ gate: &Arc<ApprovalGate>,
+ thread: &str,
+) -> (
+ String,
+ tokio::task::JoinHandle<(GateOutcome, Option<String>)>,
+) {
+ let (g, t) = (Arc::clone(gate), thread.to_string());
+ let parked = tokio::spawn(async move {
+ let origin = AgentTurnOrigin::WebChat {
+ thread_id: t.clone(),
+ client_id: "c".into(),
+ request_id: None,
+ };
+ let chat = ApprovalChatContext {
+ thread_id: t,
+ client_id: "c".into(),
+ request_id: None,
+ };
+ turn_origin::with_origin(
+ origin,
+ g.intercept_audited(
+ &ApprovalTurnContext::chat(chat),
+ "shell",
+ "run it",
+ serde_json::json!({}),
+ ),
+ )
+ .await
+ });
+ for _ in 0..2_000 {
+ if let Some(request_id) = gate.pending_for_thread(thread) {
+ return (request_id, parked);
+ }
+ tokio::task::yield_now().await;
+ }
+ panic!("no approval parked on {thread}");
+}
+
+#[tokio::test]
+async fn only_a_chat_approvals_channel_decides_a_parked_approval() {
+ let dir = tempfile::tempdir().unwrap();
+ let gate = Arc::new(ApprovalGate::for_test(dir.path()));
+ let (request_id, parked) = park(&gate, "t-chan").await;
+ let yes = reply("yes");
+
+ // Fails closed: no channel instance, or one without chat approvals.
+ assert!(!consumes_approval_reply(None, Some(&gate), &yes, "t-chan"));
+ let off = channel(false);
+ assert!(!consumes_approval_reply(
+ Some(&off),
+ Some(&gate),
+ &yes,
+ "t-chan"
+ ));
+ // No gate installed, a reply that is not yes/no, or another thread.
+ let on = channel(true);
+ assert!(!consumes_approval_reply(Some(&on), None, &yes, "t-chan"));
+ assert!(!consumes_approval_reply(
+ Some(&on),
+ Some(&gate),
+ &reply("hello"),
+ "t-chan"
+ ));
+ assert!(!consumes_approval_reply(
+ Some(&on),
+ Some(&gate),
+ &yes,
+ "t-other"
+ ));
+ assert_eq!(gate.pending_for_thread("t-chan"), Some(request_id));
+
+ // A chat-approvals channel decides it, once.
+ assert!(consumes_approval_reply(
+ Some(&on),
+ Some(&gate),
+ &yes,
+ "t-chan"
+ ));
+ let (outcome, _) = parked.await.unwrap();
+ assert!(matches!(outcome, GateOutcome::Allow), "{outcome:?}");
+ assert!(gate.pending_for_thread("t-chan").is_none());
+ assert!(!consumes_approval_reply(
+ Some(&on),
+ Some(&gate),
+ &yes,
+ "t-chan"
+ ));
+}
diff --git a/crates/openhuman-core/src/security/approval/gate_setup.rs b/crates/openhuman-core/src/security/approval/gate_setup.rs
index 77a027b4cc..f4d8a29ce8 100644
--- a/crates/openhuman-core/src/security/approval/gate_setup.rs
+++ b/crates/openhuman-core/src/security/approval/gate_setup.rs
@@ -25,6 +25,18 @@ impl ApprovalGate {
GLOBAL_GATE.get().cloned()
}
+ /// A gate on its own store under `workspace`, for tests outside this
+ /// module that must not install the process-wide gate.
+ #[cfg(test)]
+ pub(crate) fn for_test(workspace: &std::path::Path) -> Self {
+ let config = Config {
+ workspace_dir: workspace.to_path_buf(),
+ ..Config::default()
+ };
+ let session = format!("session-{}", uuid::Uuid::new_v4());
+ Self::new(config, session, DEFAULT_APPROVAL_TTL)
+ }
+
fn new(config: Config, session_id: String, ttl: Duration) -> Self {
// Regression guard: the gate's session_id must be the per-launch
// UUID minted by `bootstrap_core_runtime` (shape:
@@ -93,7 +105,11 @@ impl ApprovalGate {
/// Whether `tool_name` is on the user's "Always allow" list. Prefers the agent or
/// process-global live policy (so a grant made this session is seen
/// immediately) and falls back to the gate's boot-time config snapshot.
- fn tool_is_auto_approved(&self, ctx: &crate::core::runtime::DispatchCtx, tool_name: &str) -> bool {
+ fn tool_is_auto_approved(
+ &self,
+ ctx: &crate::core::runtime::DispatchCtx,
+ tool_name: &str,
+ ) -> bool {
if let Some(policy) = crate::security::live_policy::effective_in(ctx) {
return policy.auto_approve.iter().any(|t| t == tool_name);
}