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
38 changes: 26 additions & 12 deletions crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ use super::super::types::OpenHumanSessionHost;
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
use crate::security::prompt_injection::{
enforce_prompt_input_in, PromptEnforcementAction, PromptEnforcementContext,
enforce_prompt_input_with_config, screening_config_in, PromptEnforcementAction,
PromptEnforcementContext,
};
use anyhow::Result;
use tinyagents_harness::agent_error::AgentError;
Expand Down Expand Up @@ -72,17 +73,30 @@ impl OpenHumanSessionHost {
crate::core::runtime::DispatchCtx::from_weak(self.host_env.core.as_ref())
.turn_origin_or_scoped()
});
let guard = enforce_prompt_input_in(
&crate::core::runtime::DispatchCtx::from_weak(self.host_env.core.as_ref()),
message,
PromptEnforcementContext {
source: "agent.runtime.run_single",
request_id: None,
user_id: Some(self.event_channel()),
session_id: Some(self.event_session_id()),
},
)
.await;
let dispatch = crate::core::runtime::DispatchCtx::from_weak(self.host_env.core.as_ref());
let owner_config = screening_config_in(&dispatch).await;
// A process with no core has no owner to load from; screen with the
// config this session was built with. An owner whose config fails to
// load stays held, and so does SaaS work that lost its tenant, as
// `DispatchCtx::ambient` keeps it.
let ownerless = dispatch.resolved().is_none() && !crate::core::runtime::is_saas();
let screen_config = if ownerless {
self.runtime_config.as_deref()
} else {
owner_config.as_ref()
};
let guard = dispatch
.enter(enforce_prompt_input_with_config(
message,
PromptEnforcementContext {
source: "agent.runtime.run_single",
request_id: None,
user_id: Some(self.event_channel()),
session_id: Some(self.event_session_id()),
},
screen_config,
))
.await;
// A host-only session reading untrusted data has opted out; see
// `set_untrusted_input`, which refuses any other session.
if !self.untrusted_input && !matches!(guard.action, PromptEnforcementAction::Allow) {
Expand Down
40 changes: 23 additions & 17 deletions crates/openhuman-core/src/agent_runs/agent_chat/guards_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,26 +239,32 @@ async fn agent_chat_origin_comes_from_the_turn_context_before_the_task_scope() {
assert_eq!(chat_thread(effective_agent_chat_origin(&bare)), "direct");
}

/// TS-E2E-030: the guard screens with the op's own config. A test process, like
/// a host booted `Normal` (the CLI's `serve`), has no boot-time embedder
/// snapshot; screening from that snapshot held every prompt as
/// "screen.unavailable", even when the config turned the screen off.
/// TS-E2E-030: the guard screens with the op's own config. Under a context
/// without a boot-time embedder snapshot, like a host booted `Normal` (the
/// CLI's `serve`), screening from that snapshot held every prompt as
/// "screen.unavailable", even when the config turned the screen off. The scope
/// keeps the premise independent of the process-default context other tests
/// may boot.
#[cfg(feature = "security-module")]
#[tokio::test]
async fn the_prompt_guard_screens_with_the_ops_config_not_the_boot_snapshot() {
assert!(
crate::core::runtime::CoreContext::current_embedder_config().is_none(),
"this test needs a process without a boot-time config snapshot"
);
let config = Config {
prompt_screen: crate::config::schema::PromptScreenConfig::off(),
..Config::default()
};
use crate::core::runtime::{CoreContext, DomainSet};
CoreContext::scope(CoreContext::for_test(DomainSet::full(), None), async {
assert!(
CoreContext::current_embedder_config().is_none(),
"this test needs a context without a boot-time config snapshot"
);
let config = Config {
prompt_screen: crate::config::schema::PromptScreenConfig::off(),
..Config::default()
};

let screened = enforce_user_prompt_or_reject(&config, "hello there", "unit-test").await;
let screened = enforce_user_prompt_or_reject(&config, "hello there", "unit-test").await;

assert!(
screened.is_ok(),
"a config that turns the screen off must be honoured: {screened:?}"
);
assert!(
screened.is_ok(),
"a config that turns the screen off must be honoured: {screened:?}"
);
})
.await;
}
61 changes: 45 additions & 16 deletions crates/openhuman-core/src/inbound/pinned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,27 +133,55 @@ pub fn render_prompt(
/// `inference.agent_chat` applies to the whole message, so one injected
/// event is left out instead of failing its batch; the reason is the guard's
/// verdict and rule codes, never the text.
///
/// The batch loads its configuration once, and screening counts against the
/// delivery budget: an event not screened by `deadline` is held as
/// `screen.timeout`, as is every event when the configuration is not loaded
/// by then (`screen.unavailable` when it fails to load).
async fn screen(
ctx: &DispatchCtx,
items: Vec<ExternalItem>,
deadline: tokio::time::Instant,
) -> (Vec<ExternalItem>, Vec<BlockedEvent>) {
use crate::security::prompt_injection::{
enforce_prompt_input_in, PromptEnforcementAction, PromptEnforcementContext,
enforce_prompt_input_with_config, screening_config_in, PromptEnforcementAction,
PromptEnforcementContext,
};
// With security off nothing is screened, so no config is loaded.
if crate::security::switch::disabled().is_some() {
return (items, Vec::new());
}
let config = tokio::time::timeout_at(deadline, screening_config_in(ctx)).await;
Comment thread
M3gA-Mind marked this conversation as resolved.
Resolved
let mut kept = Vec::with_capacity(items.len());
let mut blocked = Vec::new();
for item in items {
let decision = enforce_prompt_input_in(
ctx,
&item.text,
PromptEnforcementContext {
source: "inbound.pinned",
request_id: Some(&item.id),
user_id: None,
session_id: Some("inbound"),
},
)
.await;
let screened = match &config {
Ok(config) => tokio::time::timeout_at(
deadline,
ctx.enter(enforce_prompt_input_with_config(
&item.text,
PromptEnforcementContext {
source: "inbound.pinned",
request_id: Some(&item.id),
user_id: None,
session_id: Some("inbound"),
},
config.as_ref(),
)),
)
.await
.ok(),
Err(_) => None,
};
let Some(decision) = screened else {
let reason = "flagged for review: screen.timeout".to_owned();
tracing::info!(event_id = %item.id, reason = %reason, "[inbound] event kept out of the pinned prompt");
blocked.push(BlockedEvent {
event_id: item.id,
reason,
});
continue;
};
let verdict = match decision.action {
PromptEnforcementAction::Allow => {
kept.push(item);
Expand Down Expand Up @@ -258,8 +286,8 @@ impl Pinned {
}
}

/// Deliver `turn` of source `name` (configured as `source`), waiting for
/// its run at most `within`.
/// Deliver `turn` of source `name` (configured as `source`), screening its
/// events and waiting for its run within `within` in all.
pub async fn deliver(
&self,
ctx: &DispatchCtx,
Expand All @@ -268,6 +296,7 @@ impl Pinned {
source: &InboundSourceConfig,
within: Duration,
) -> Delivered {
let deadline = tokio::time::Instant::now() + within;
match self.results.get(&turn.turn_id) {
Ok(Some(stored)) if stored.result.status != ResultStatus::Running => {
tracing::info!(turn = %turn.turn_id, source = %name, "[inbound] pinned turn already finished; not running it again");
Expand All @@ -282,7 +311,7 @@ impl Pinned {
};
let items: Vec<ExternalItem> = turn.events.iter().filter_map(external_of).collect();
let event_ids: Vec<String> = items.iter().map(|item| item.id.clone()).collect();
let (items, blocked) = screen(ctx, items).await;
let (items, blocked) = screen(ctx, items, deadline).await;
let key = turn.events.first().map_or_else(
|| turn.conversation_key.clone(),
|e| e.conversation_key.clone(),
Expand Down Expand Up @@ -316,7 +345,7 @@ impl Pinned {
"[inbound] running the pinned agent"
);
let mut task = self.spawn_run(ctx, stored, claim);
match tokio::time::timeout(within, &mut task).await {
match tokio::time::timeout_at(deadline, &mut task).await {
Ok(Ok(Ok(()))) => Delivered::Done,
Ok(Ok(Err(error))) => Delivered::Failed(error),
Ok(Err(join)) => Delivered::Failed(format!("pinned run ended: {join}")),
Expand Down
24 changes: 20 additions & 4 deletions crates/openhuman-core/src/security/prompt_injection/detector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,8 @@ fn unscreened_decision(input: &str) -> PromptEnforcementDecision {
///
/// Reads only the boot-time embedder snapshot, which exists for a preloaded
/// config or a `SecretPreflight` boot. A host booted `Normal` (the CLI's
/// `serve`) has none, so every call here is held. Screen with the caller's
/// `serve`) without a preloaded config has none, so with security enabled
/// every call here is held. Screen with the caller's
/// dispatch ([`enforce_prompt_input_in`]) or config
/// ([`enforce_prompt_input_with_config`]) instead.
pub async fn enforce_prompt_input(
Expand All @@ -163,14 +164,29 @@ pub(crate) async fn enforce_prompt_input_in(
input: &str,
context: PromptEnforcementContext<'_>,
) -> PromptEnforcementDecision {
let config = screening_config_in(dispatch).await;
dispatch
.enter(enforce_prompt_input_with_config(
input,
context,
config.as_ref(),
))
.await
}

/// The configuration [`enforce_prompt_input_in`] screens `dispatch`'s input
/// with: its owner's, or none (a held decision) for an unbound dispatch. Load
/// it once to screen many inputs.
pub(crate) async fn screening_config_in(
dispatch: &crate::core::runtime::DispatchCtx,
) -> Option<crate::config::Config> {
dispatch
.enter(async {
let config = if dispatch.resolved().is_some() {
if dispatch.resolved().is_some() {
dispatch.load_config().await.ok()
} else {
None
};
enforce_prompt_input_with_config(input, context, config.as_ref()).await
}
})
.await
}
Expand Down
4 changes: 3 additions & 1 deletion crates/openhuman-core/src/security/prompt_injection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@

mod detector;

pub(crate) use detector::{enforce_prompt_input_in, enforce_prompt_input_with_config};
pub(crate) use detector::{
enforce_prompt_input_in, enforce_prompt_input_with_config, screening_config_in,
};

pub use detector::{
enforce_prompt_input, scan_tool_definition, PromptEnforcementAction, PromptEnforcementContext,
Expand Down
Loading