Skip to content

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

fix(attachments): harden historical media reads

Steven Enamakelfcd3bc4bad7f
diff --git a/crates/openhuman-core/src/agent/attachments/mod.rs b/crates/openhuman-core/src/agent/attachments/mod.rs
index a26e11009a..1204890abb 100644
--- a/crates/openhuman-core/src/agent/attachments/mod.rs
+++ b/crates/openhuman-core/src/agent/attachments/mod.rs
@@ -24,6 +24,7 @@ pub(crate) struct AttachmentAccessScope {
}
const REQUEST_SCOPE_KEY: &str = "__openhuman_attachment_access_scope";
+pub(super) const SOURCE_MISSING_MARKER: &str = "[attachment-source-missing]";
pub(crate) fn attach_request_scope(
request: &mut tinyinference_llm::model::ModelRequest,
@@ -182,19 +183,42 @@ pub(crate) async fn resolve_path(
.map_err(anyhow::Error::msg)
}
+pub(super) async fn is_missing_local_reference(
+ config: &Config,
+ reference: &str,
+ scope: &AttachmentAccessScope,
+) -> bool {
+ let root = action_root(config, scope);
+ let path_policy = policy(config, &root);
+ if !path_policy.is_path_string_allowed(reference) {
+ return false;
+ }
+ let requested = Path::new(reference);
+ let path = if requested.is_absolute() {
+ requested.to_path_buf()
+ } else {
+ root.join(requested)
+ };
+ matches!(
+ tokio::fs::symlink_metadata(path).await,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound
+ )
+}
+
fn filename(name: &str) -> String {
let leaf = name.rsplit(['/', '\\']).next().unwrap_or("attachment");
- let sanitized: String = leaf
- .chars()
- .take(180)
- .map(|c| {
- if c.is_alphanumeric() || matches!(c, '.' | '-' | '_') {
- c
- } else {
- '_'
- }
- })
- .collect();
+ let mut sanitized = String::new();
+ for c in leaf.chars() {
+ let c = if c.is_alphanumeric() || matches!(c, '.' | '-' | '_') {
+ c
+ } else {
+ '_'
+ };
+ if sanitized.len() + c.len_utf8() > 180 {
+ break;
+ }
+ sanitized.push(c);
+ }
if sanitized.is_empty() || sanitized == "." || sanitized == ".." {
"attachment".into()
} else {
diff --git a/crates/openhuman-core/src/agent/attachments/mod_tests.rs b/crates/openhuman-core/src/agent/attachments/mod_tests.rs
index b075d70dda..75092e9063 100644
--- a/crates/openhuman-core/src/agent/attachments/mod_tests.rs
+++ b/crates/openhuman-core/src/agent/attachments/mod_tests.rs
@@ -260,6 +260,9 @@ async fn repeated_names_do_not_overwrite_and_escape_names_are_sanitized() {
assert_ne!(a.path, b.path);
assert_eq!(a.name, "../../same.zip");
assert_eq!(Path::new(&a.path).file_name().unwrap(), "same.zip");
+ let unicode_name = filename(&"界".repeat(100));
+ assert!(unicode_name.len() <= 180);
+ assert!(unicode_name.len() >= 177);
assert!(safe_relative_path(&a.path));
assert_eq!(
tokio::fs::read(config.action_dir.join(a.path))
diff --git a/crates/openhuman-core/src/agent/attachments/provider.rs b/crates/openhuman-core/src/agent/attachments/provider.rs
index 86f6b0ff5e..e62de00338 100644
--- a/crates/openhuman-core/src/agent/attachments/provider.rs
+++ b/crates/openhuman-core/src/agent/attachments/provider.rs
@@ -90,6 +90,26 @@ struct AttachmentModel {
profile: ModelProfile,
fallback_cache: std::sync::Mutex<std::collections::HashMap<String, String>>,
}
+
+const MAX_HISTORICAL_MEDIA_BLOCKS: usize = 8;
+
+fn is_media_block(block: &ContentBlock) -> bool {
+ matches!(
+ block,
+ ContentBlock::Image(_)
+ | ContentBlock::Audio(_)
+ | ContentBlock::Video(_)
+ | ContentBlock::Document(_)
+ )
+}
+
+fn recoverable_historical_media_error(error: &tinyinference_llm::Error) -> bool {
+ let error = error.to_string();
+ error.contains(super::SOURCE_MISSING_MARKER)
+ || error.contains("attachments are disabled for this origin")
+ || error.contains("remote attachment fetch is disabled")
+}
+
impl AttachmentModel {
fn native(&self, modality: InputModality, mime: &str) -> bool {
let known = match modality {
@@ -129,8 +149,21 @@ impl AttachmentModel {
} else {
file_mb
};
- let metadata = tokio::fs::metadata(&path)
+ let root = tokio::fs::canonicalize(super::action_root(&self.config, scope))
.await
+ .map_err(|error| tinyinference_llm::Error::Model(error.to_string()))?;
+ let file = secure_open(&path, &root).map_err(|error| {
+ if error.kind() == std::io::ErrorKind::NotFound {
+ tinyinference_llm::Error::Model(format!(
+ "{} local attachment source disappeared",
+ super::SOURCE_MISSING_MARKER
+ ))
+ } else {
+ tinyinference_llm::Error::Model(error.to_string())
+ }
+ })?;
+ let metadata = file
+ .metadata()
.map_err(|e| tinyinference_llm::Error::Model(e.to_string()))?;
if !metadata.is_file() || metadata.len() > (mb * 1024 * 1024) as u64 {
return Err(tinyinference_llm::Error::Model(
@@ -138,9 +171,7 @@ impl AttachmentModel {
));
}
use tokio::io::AsyncReadExt;
- let file = tokio::fs::File::open(path)
- .await
- .map_err(|e| tinyinference_llm::Error::Model(e.to_string()))?;
+ let file = tokio::fs::File::from_std(file);
let mut bytes = Vec::new();
file.take((mb * 1024 * 1024 + 1) as u64)
.read_to_end(&mut bytes)
@@ -187,15 +218,66 @@ impl AttachmentModel {
));
}
}
- for message in &mut request.messages {
+ let latest_user_message = request
+ .messages
+ .iter()
+ .rposition(|message| matches!(message, Message::User(_)));
+ let mut historical_media_to_resolve = std::collections::HashSet::new();
+ let mut remaining_historical = MAX_HISTORICAL_MEDIA_BLOCKS;
+ for (message_index, message) in request.messages.iter().enumerate().rev() {
+ if Some(message_index) == latest_user_message {
+ continue;
+ }
+ let Message::User(user) = message else {
+ continue;
+ };
+ for (block_index, block) in user.content.iter().enumerate().rev() {
+ if is_media_block(block) && remaining_historical > 0 {
+ historical_media_to_resolve.insert((message_index, block_index));
+ remaining_historical -= 1;
+ }
+ }
+ }
+ if scope.external_channel
+ && request.messages.iter().any(|message| {
+ matches!(message, Message::User(user) if user.content.iter().any(is_media_block))
+ })
+ {
+ return Err(tinyinference_llm::Error::Model(
+ "attachment resolution is disabled for external channel input".into(),
+ ));
+ }
+ for (message_index, message) in request.messages.iter_mut().enumerate() {
let Message::User(user) = message else {
continue;
};
let mut out = Vec::new();
- for block in std::mem::take(&mut user.content) {
- let Some((modality, path, mut mime, bytes, recovered)) =
- self.resolve_block(&block, &scope).await?
- else {
+ for (block_index, block) in std::mem::take(&mut user.content).into_iter().enumerate() {
+ if Some(message_index) != latest_user_message
+ && is_media_block(&block)
+ && !historical_media_to_resolve.contains(&(message_index, block_index))
+ {
+ let hint = historical_source_hint(&block, &scope);
+ out.push(ContentBlock::Text(format!(
+ "[Earlier attachment omitted by history budget; workspace path: {hint}]"
+ )));
+ continue;
+ }
+ let resolved = match self.resolve_block(&block, &scope).await {
+ Ok(resolved) => resolved,
+ Err(error)
+ if Some(message_index) != latest_user_message
+ && recoverable_historical_media_error(&error) =>
+ {
+ let hint = historical_source_hint(&block, &scope);
+ out.push(ContentBlock::Text(format!(
+ "[Earlier attachment unavailable or omitted at workspace path: {hint}]"
+ )));
+ continue;
+ }
+ Err(error) => return Err(error),
+ };
+ let Some((modality, path, mut mime, bytes, recovered)) = resolved else {
out.push(block);
continue;
};
@@ -281,6 +363,48 @@ impl AttachmentModel {
Ok(request)
}
}
+
+fn historical_source_hint(block: &ContentBlock, scope: &AttachmentAccessScope) -> String {
+ let source = match block {
+ ContentBlock::Image(image) if is_local_reference(&image.url) => &image.url,
+ ContentBlock::Audio(MediaRef::Path { path, .. })
+ | ContentBlock::Video(MediaRef::Path { path, .. })
+ | ContentBlock::Document(MediaRef::Path { path, .. }) => path,
+ _ => return "remote or inline media omitted".into(),
+ };
+ let path = std::path::Path::new(source);
+ let source = if path.is_absolute() {
+ let root = scope.workspace.as_deref();
+ root.and_then(|root| {
+ path.strip_prefix(root)
+ .ok()
+ .map(std::path::Path::to_path_buf)
+ })
+ .or_else(|| path.file_name().map(std::path::PathBuf::from))
+ .unwrap_or_default()
+ .to_string_lossy()
+ .into_owned()
+ } else {
+ source.to_owned()
+ };
+ source.chars().take(180).collect()
+}
+
+fn is_local_reference(source: &str) -> bool {
+ let bytes = source.as_bytes();
+ let windows_drive_path = bytes.len() >= 3
+ && bytes[0].is_ascii_alphabetic()
+ && bytes[1] == b':'
+ && matches!(bytes[2], b'/' | b'\\');
+ windows_drive_path || url::Url::parse(source).is_err()
+}
+
+#[path = "provider_open.rs"]
+mod open;
+#[cfg(any(test, windows))]
+use open::normalize_windows_path_for_comparison;
+use open::secure_open;
+
#[async_trait]
impl ChatModel<()> for AttachmentModel {
fn profile(&self) -> Option<&ModelProfile> {
@@ -318,6 +442,14 @@ mod source;
#[path = "provider_tests.rs"]
mod tests;
+#[cfg(test)]
+#[path = "provider_history_tests.rs"]
+mod history_tests;
+
#[cfg(test)]
#[path = "provider_routing_tests.rs"]
mod routing_tests;
+
+#[cfg(test)]
+#[path = "provider_security_tests.rs"]
+mod security_tests;
diff --git a/crates/openhuman-core/src/agent/attachments/provider_history_tests.rs b/crates/openhuman-core/src/agent/attachments/provider_history_tests.rs
new file mode 100644
index 0000000000..2a7a65e82f
--- /dev/null
+++ b/crates/openhuman-core/src/agent/attachments/provider_history_tests.rs
@@ -0,0 +1,86 @@
+use super::tests::Probe;
+use super::*;
+
+#[tokio::test]
+async fn missing_historical_media_does_not_block_latest_valid_media() {
+ let temp = tempfile::tempdir().unwrap();
+ tokio::fs::write(
+ temp.path().join("latest.png"),
+ [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],
+ )
+ .await
+ .unwrap();
+ let mut config = Config::default();
+ config.action_dir = temp.path().into();
+ let probe = Arc::new(Probe::default());
+ let wrapper = wrap(probe.clone(), Arc::new(config), "gpt-4o", "openai");
+ let image = |path: &str| {
+ Message::User(tinyinference_llm::message::UserMessage {
+ content: vec![ContentBlock::Image(ImageRef {
+ url: path.into(),
+ mime_type: Some("image/png".into()),
+ })],
+ })
+ };
+ let signed_urls = [
+ "https://files.example.test/old.png?token=private-value",
+ "ftp://files.example.test/old.png?signature=also-private",
+ ];
+ let mut old_content = signed_urls
+ .iter()
+ .map(|url| {
+ ContentBlock::Image(ImageRef {
+ url: (*url).into(),
+ mime_type: Some("image/png".into()),
+ })
+ })
+ .collect::<Vec<_>>();
+ old_content.extend((0..8).map(|index| {
+ ContentBlock::Image(ImageRef {
+ url: format!("deleted-prior-upload-{index}.png"),
+ mime_type: Some("image/png".into()),
+ })
+ }));
+ let old_user = Message::User(tinyinference_llm::message::UserMessage {
+ content: old_content,
+ });
+ let request = ModelRequest::new(vec![old_user, image("latest.png")]);
+ let durable = request.clone();
+
+ assert!(wrapper.invoke(&(), request).await.is_err());
+ let captured = probe.requests.lock().unwrap().clone();
+ assert_eq!(captured.len(), 1);
+ let history = &captured[0].messages[0];
+ assert!(history
+ .text()
+ .contains("Earlier attachment omitted by history budget"));
+ assert!(history.text().contains("Earlier attachment unavailable"));
+ assert!(history.text().contains("deleted-prior-upload-0.png"));
+ assert!(!serde_json::to_string(history).unwrap().contains("base64"));
+ assert!(!serde_json::to_string(history)
+ .unwrap()
+ .contains("private-value"));
+ assert!(!serde_json::to_string(history)
+ .unwrap()
+ .contains("also-private"));
+ let durable_text = serde_json::to_string(&durable).unwrap();
+ assert!(signed_urls.iter().all(|url| durable_text.contains(url)));
+ assert!(serde_json::to_string(&captured[0].messages[1])
+ .unwrap()
+ .contains("data:image/png;base64,"));
+}
+
+#[tokio::test]
+async fn secure_open_refuses_replaced_final_symlink() {
+ use std::os::unix::fs::symlink;
+ let temp = tempfile::tempdir().unwrap();
+ let allowed = temp.path().join("allowed.txt");
+ let outside = temp.path().join("outside.txt");
+ tokio::fs::write(&allowed, b"allowed").await.unwrap();
+ tokio::fs::write(&outside, b"secret").await.unwrap();
+ tokio::fs::remove_file(&allowed).await.unwrap();
+ symlink(&outside, &allowed).unwrap();
+
+ let error = secure_open(&allowed, temp.path()).unwrap_err();
+ assert_eq!(error.raw_os_error(), Some(libc::ELOOP));
+}
diff --git a/crates/openhuman-core/src/agent/attachments/provider_open.rs b/crates/openhuman-core/src/agent/attachments/provider_open.rs
new file mode 100644
index 0000000000..80563ca4e3
--- /dev/null
+++ b/crates/openhuman-core/src/agent/attachments/provider_open.rs
@@ -0,0 +1,153 @@
+//! Platform-specific descriptor/handle-bound attachment opens.
+
+#[cfg(unix)]
+pub(super) fn secure_open(
+ path: &std::path::Path,
+ root: &std::path::Path,
+) -> std::io::Result<std::fs::File> {
+ use std::ffi::CString;
+ use std::os::fd::{AsRawFd, FromRawFd};
+ use std::os::unix::{ffi::OsStrExt, fs::OpenOptionsExt};
+
+ let (base_path, relative) = if let Ok(relative) = path.strip_prefix(root) {
+ (root, relative)
+ } else {
+ let relative = path.strip_prefix("/").map_err(|_| {
+ std::io::Error::new(std::io::ErrorKind::InvalidInput, "path is not absolute")
+ })?;
+ (std::path::Path::new("/"), relative)
+ };
+ let filesystem_root = std::fs::OpenOptions::new()
+ .read(true)
+ .custom_flags(libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW)
+ .open("/")?;
+ let mut current = filesystem_root;
+ for component in base_path
+ .strip_prefix("/")
+ .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "root is not absolute"))?
+ .components()
+ {
+ let std::path::Component::Normal(name) = component else {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::InvalidInput,
+ "attachment root contains an invalid component",
+ ));
+ };
+ let name = CString::new(name.as_bytes()).map_err(|_| {
+ std::io::Error::new(
+ std::io::ErrorKind::InvalidInput,
+ "attachment root contains NUL",
+ )
+ })?;
+ let fd = unsafe {
+ libc::openat(
+ current.as_raw_fd(),
+ name.as_ptr(),
+ libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
+ )
+ };
+ if fd < 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ current = unsafe { std::fs::File::from_raw_fd(fd) };
+ }
+ let components = relative.components().collect::<Vec<_>>();
+ if components.is_empty() {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::InvalidInput,
+ "attachment path names a directory",
+ ));
+ }
+ for (index, component) in components.iter().enumerate() {
+ let std::path::Component::Normal(name) = component else {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::InvalidInput,
+ "attachment path contains an invalid component",
+ ));
+ };
+ let name = CString::new(name.as_bytes()).map_err(|_| {
+ std::io::Error::new(
+ std::io::ErrorKind::InvalidInput,
+ "attachment path contains NUL",
+ )
+ })?;
+ let final_component = index + 1 == components.len();
+ let flags = libc::O_RDONLY
+ | libc::O_CLOEXEC
+ | libc::O_NOFOLLOW
+ | if final_component { libc::O_NONBLOCK } else { 0 }
+ | if final_component {
+ 0
+ } else {
+ libc::O_DIRECTORY
+ };
+ // Each lookup is relative to an already-open directory descriptor and
+ // refuses reparse/symlink traversal, so a path swap cannot redirect the
+ // eventual read after policy validation.
+ let fd = unsafe { libc::openat(current.as_raw_fd(), name.as_ptr(), flags) };
+ if fd < 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ current = unsafe { std::fs::File::from_raw_fd(fd) };
+ }
+ Ok(current)
+}
+
+#[cfg(windows)]
+pub(super) fn secure_open(
+ path: &std::path::Path,
+ _root: &std::path::Path,
+) -> std::io::Result<std::fs::File> {
+ use std::os::windows::io::AsRawHandle;
+ use windows_sys::Win32::Storage::FileSystem::{
+ GetFinalPathNameByHandleW, FILE_NAME_NORMALIZED, VOLUME_NAME_DOS,
+ };
+
+ use std::os::windows::ffi::OsStringExt;
+ let expected = path.to_path_buf();
+ let file = std::fs::File::open(path)?;
+ let handle = file.as_raw_handle();
+ let flags = FILE_NAME_NORMALIZED | VOLUME_NAME_DOS;
+ let required =
+ unsafe { GetFinalPathNameByHandleW(handle, std::ptr::null_mut(), 0, flags) } as usize;
+ if required == 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ let mut buffer = vec![0u16; required + 1];
+ let written = unsafe {
+ GetFinalPathNameByHandleW(handle, buffer.as_mut_ptr(), buffer.len() as u32, flags)
+ } as usize;
+ if written == 0 || written >= buffer.len() {
+ return Err(std::io::Error::last_os_error());
+ }
+ let opened = std::ffi::OsString::from_wide(&buffer[..written]);
+ if !normalize_windows_path_for_comparison(&opened.to_string_lossy()).eq_ignore_ascii_case(
+ &normalize_windows_path_for_comparison(&expected.to_string_lossy()),
+ ) {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::PermissionDenied,
+ "attachment path changed during secure open",
+ ));
+ }
+ Ok(file)
+}
+
+#[cfg(any(windows, test))]
+pub(super) fn normalize_windows_path_for_comparison(value: &str) -> String {
+ value
+ .strip_prefix("\\\\?\\UNC\\")
+ .map(|unc| format!("\\\\{unc}"))
+ .or_else(|| value.strip_prefix("\\\\?\\").map(str::to_owned))
+ .unwrap_or_else(|| value.to_owned())
+}
+
+#[cfg(not(any(unix, windows)))]
+pub(super) fn secure_open(
+ _path: &std::path::Path,
+ _root: &std::path::Path,
+) -> std::io::Result<std::fs::File> {
+ Err(std::io::Error::new(
+ std::io::ErrorKind::Unsupported,
+ "secure attachment reads are unsupported on this platform",
+ ))
+}
diff --git a/crates/openhuman-core/src/agent/attachments/provider_security_tests.rs b/crates/openhuman-core/src/agent/attachments/provider_security_tests.rs
new file mode 100644
index 0000000000..9ce72f2cb6
--- /dev/null
+++ b/crates/openhuman-core/src/agent/attachments/provider_security_tests.rs
@@ -0,0 +1,159 @@
+use super::*;
+
+#[test]
+fn windows_comparison_normalizes_dos_verbatim_and_unc_paths() {
+ assert_eq!(
+ normalize_windows_path_for_comparison(r"\\?\C:\workspace\uploads\file.png"),
+ r"C:\workspace\uploads\file.png"
+ );
+ assert_eq!(
+ normalize_windows_path_for_comparison(r"\\?\UNC\server\share\workspace\uploads\file.png"),
+ r"\\server\share\workspace\uploads\file.png"
+ );
+ assert_eq!(
+ normalize_windows_path_for_comparison(r"C:\workspace\uploads\file.png"),
+ r"C:\workspace\uploads\file.png"
+ );
+}
+
+#[cfg(unix)]
+#[tokio::test]
+async fn secure_open_rejects_parent_symlink_replaced_after_path_validation() {
+ use std::os::unix::fs::symlink;
+
+ let temp = tempfile::tempdir().unwrap();
+ let root = temp.path().join("workspace");
+ let nested = root.join("nested");
+ let outside = temp.path().join("outside");
+ tokio::fs::create_dir_all(&nested).await.unwrap();
+ tokio::fs::create_dir_all(&outside).await.unwrap();
+ tokio::fs::write(nested.join("file.png"), b"allowed")
+ .await
+ .unwrap();
+ tokio::fs::write(outside.join("file.png"), b"outside")
+ .await
+ .unwrap();
+
+ let mut config = crate::config::Config::default();
+ config.action_dir = root.clone();
+ config.workspace_dir = temp.path().join("internal");
+ let scope = AttachmentAccessScope {
+ external_channel: false,
+ workspace: Some(root.clone()),
+ };
+ let validated = crate::agent::attachments::resolve_path(&config, "nested/file.png", &scope)
+ .await
+ .unwrap();
+ let canonical_root = tokio::fs::canonicalize(&root).await.unwrap();
+
+ tokio::fs::rename(&nested, root.join("nested-original"))
+ .await
+ .unwrap();
+ symlink(&outside, &nested).unwrap();
+
+ let error = secure_open(&validated, &canonical_root).unwrap_err();
+ assert!(
+ matches!(
+ error.kind(),
+ std::io::ErrorKind::TooManyLinks | std::io::ErrorKind::NotADirectory
+ ),
+ "parent symlink replacement must be refused, got {error}"
+ );
+}
+
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn fifo_attachment_is_rejected_without_waiting_for_a_writer() {
+ use std::{
+ ffi::CString,
+ os::unix::ffi::OsStrExt,
+ sync::atomic::{AtomicBool, Ordering},
+ thread,
+ time::Duration,
+ };
+
+ #[derive(Default)]
+ struct NeverCalled(AtomicBool);
+
+ #[async_trait]
+ impl ChatModel<()> for NeverCalled {
+ fn supports_input(&self, _: InputModality, _: &str, _: InputSource) -> bool {
+ false
+ }
+
+ fn profile(&self) -> Option<&ModelProfile> {
+ None
+ }
+
+ async fn invoke(
+ &self,
+ _: &(),
+ _: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ self.0.store(true, Ordering::SeqCst);
+ Err(tinyinference_llm::Error::Model(
+ "unexpected model invocation".into(),
+ ))
+ }
+ }
+
+ let temp = tempfile::tempdir().unwrap();
+ let fifo = temp.path().join("attachment.png");
+ let fifo_c = CString::new(fifo.as_os_str().as_bytes()).unwrap();
+ let result = unsafe { libc::mkfifo(fifo_c.as_ptr(), 0o600) };
+ assert_eq!(
+ result,
+ 0,
+ "mkfifo failed: {}",
+ std::io::Error::last_os_error()
+ );
+
+ let mut config = Config::default();
+ config.action_dir = temp.path().to_path_buf();
+ config.workspace_dir = temp.path().join("internal");
+ let model = Arc::new(NeverCalled::default());
+ let wrapped = wrap_injected(model.clone(), Arc::new(config));
+ let request = ModelRequest::new(vec![Message::User(
+ tinyinference_llm::message::UserMessage {
+ content: vec![ContentBlock::Image(ImageRef {
+ url: "attachment.png".into(),
+ mime_type: Some("image/png".into()),
+ })],
+ },
+ )]);
+
+ let fifo_for_unblock = fifo.clone();
+ let mut handle = tokio::spawn(async move { wrapped.invoke(&(), request).await });
+ let timely = tokio::time::timeout(Duration::from_secs(2), &mut handle).await;
+ if timely.is_err() {
+ // If a regression blocks in `openat(O_RDONLY)`, pair it with a writer
+ // so the test process can still shut down cleanly after reporting it.
+ let writer = thread::spawn(move || {
+ let path = CString::new(fifo_for_unblock.as_os_str().as_bytes()).unwrap();
+ for _ in 0..100 {
+ let fd = unsafe {
+ libc::open(
+ path.as_ptr(),
+ libc::O_WRONLY | libc::O_NONBLOCK | libc::O_CLOEXEC,
+ )
+ };
+ if fd >= 0 {
+ unsafe { libc::close(fd) };
+ return;
+ }
+ thread::sleep(Duration::from_millis(10));
+ }
+ });
+ let _ = handle.await;
+ writer.join().unwrap();
+ panic!("opening a FIFO attachment must not block");
+ }
+ let error = timely.unwrap().unwrap().unwrap_err();
+ assert!(
+ error
+ .to_string()
+ .contains("attachment exceeds configured file limit"),
+ "non-regular attachment must be rejected before inference: {error}"
+ );
+ assert!(!model.0.load(Ordering::SeqCst));
+}
diff --git a/crates/openhuman-core/src/agent/attachments/provider_source.rs b/crates/openhuman-core/src/agent/attachments/provider_source.rs
index 44ef333c7e..8445ba7508 100644
--- a/crates/openhuman-core/src/agent/attachments/provider_source.rs
+++ b/crates/openhuman-core/src/agent/attachments/provider_source.rs
@@ -1,4 +1,5 @@
//! Resolve every admitted media source on a disposable provider request.
+use super::super::{is_missing_local_reference, SOURCE_MISSING_MARKER};
use super::AttachmentAccessScope;
use super::*;
use sha2::{Digest, Sha256};
@@ -37,6 +38,11 @@ impl AttachmentModel {
));
}
if is_local {
+ if is_missing_local_reference(&self.config, &source, scope).await {
+ return Err(tinyinference_llm::Error::Model(format!(
+ "{SOURCE_MISSING_MARKER} local attachment source is missing"
+ )));
+ }
// Old transcripts can point into the private host image stash.
// Publish only its validated managed originals into the acting
// workspace, and retain that stable path for metadata and caches.
@@ -45,6 +51,11 @@ impl AttachmentModel {
.map_err(|e| tinyinference_llm::Error::Model(e.to_string()))?;
let recovered = migrated.is_some();
let source = migrated.unwrap_or(source);
+ if is_missing_local_reference(&self.config, &source, scope).await {
+ return Err(tinyinference_llm::Error::Model(format!(
+ "{SOURCE_MISSING_MARKER} local attachment source is missing"
+ )));
+ }
let bytes = self.read(&source, modality, scope).await?;
return Ok(Some((
modality,
diff --git a/crates/openhuman-core/src/agent/attachments/provider_tests.rs b/crates/openhuman-core/src/agent/attachments/provider_tests.rs
index 515d8a8fb3..955be008b4 100644
--- a/crates/openhuman-core/src/agent/attachments/provider_tests.rs
+++ b/crates/openhuman-core/src/agent/attachments/provider_tests.rs
@@ -1,8 +1,8 @@
use super::*;
use std::sync::Mutex;
#[derive(Default)]
-struct Probe {
- requests: Mutex<Vec<ModelRequest>>,
+pub(super) struct Probe {
+ pub(super) requests: Mutex<Vec<ModelRequest>>,
profile: ModelProfile,
}
#[async_trait]
@@ -60,6 +60,8 @@ async fn local_native_resolution_changes_only_ephemeral_request() {
b"original-png"
);
}
+
+#[cfg(unix)]
#[tokio::test]
async fn blocked_attachment_fails_before_model_call() {
let mut config = Config::default();
diff --git a/crates/openhuman-core/src/agent/harness/graph.rs b/crates/openhuman-core/src/agent/harness/graph.rs
index 3f93d5e54f..23a566dcf6 100644
--- a/crates/openhuman-core/src/agent/harness/graph.rs
+++ b/crates/openhuman-core/src/agent/harness/graph.rs
@@ -92,16 +92,23 @@ pub(crate) async fn run_channel_turn_via_graph(
// Keep originals and durable references in every entry path. Resolution
// into provider bytes belongs to the model decorator, after snapshots.
let mut attachment_workspace = None;
+ let mut attachment_config = None;
for row in history.iter_mut().filter(|row| row.role == "user") {
if row.content.contains("[FILE:") || row.content.contains("[IMAGE:") {
if multimodal_files.max_files == 0 {
anyhow::bail!("attachments are disabled for this channel input");
}
- let mut config = crate::config::rpc::load_config_with_timeout()
- .await
- .map_err(anyhow::Error::msg)?;
- config.multimodal = multimodal.clone();
- config.multimodal_files = multimodal_files.clone();
+ if attachment_config.is_none() {
+ let mut config = crate::config::rpc::load_config_with_timeout()
+ .await
+ .map_err(anyhow::Error::msg)?;
+ config.multimodal = multimodal.clone();
+ config.multimodal_files = multimodal_files.clone();
+ attachment_config = Some(config);
+ }
+ let config = attachment_config
+ .as_ref()
+ .expect("config loaded for a marker-bearing history row");
let workspace = Some(config.action_dir.clone());
attachment_workspace = workspace.clone();
let scope = crate::agent::attachments::AttachmentAccessScope {
diff --git a/crates/openhuman-core/src/threads/ops/crud.rs b/crates/openhuman-core/src/threads/ops/crud.rs
index 43506a91d2..7dcea54608 100644
--- a/crates/openhuman-core/src/threads/ops/crud.rs
+++ b/crates/openhuman-core/src/threads/ops/crud.rs
@@ -152,16 +152,18 @@ pub async fn message_append(
request: AppendConversationMessageRequest,
) -> Result<Outcome<ApiEnvelope<ConversationMessageRecord>>, ThreadsError> {
let origin = crate::core::runtime::CoreContext::current_turn_origin();
- let config = crate::config::Config::load_or_init()
+ let config = crate::config::rpc::load_config_with_timeout()
.await
.map_err(|error| ThreadsError::Message(format!("load config: {error}")))?;
- message_append_with_config(request, &config, origin.as_ref()).await
+ let persistence_dir = workspace_dir().await.map_err(ThreadsError::Message)?;
+ message_append_with_config(request, &config, origin.as_ref(), &persistence_dir).await
}
async fn message_append_with_config(
mut request: AppendConversationMessageRequest,
config: &crate::config::Config,
origin: Option<&crate::agent::turn_origin::AgentTurnOrigin>,
+ persistence_dir: &std::path::Path,
) -> Result<Outcome<ApiEnvelope<ConversationMessageRecord>>, ThreadsError> {
if request.message.sender == "user" {
let raw_upload = request.message.content.contains("[IMAGE:")
@@ -261,9 +263,8 @@ async fn message_append_with_config(
}
}
}
- let dir = config.workspace_dir.clone();
let message = conversations::blocking::append_message(
- dir,
+ persistence_dir.to_path_buf(),
request.thread_id.clone(),
record_to_message(request.message),
)
diff --git a/crates/openhuman-core/src/threads/ops/crud_message_append_tests.rs b/crates/openhuman-core/src/threads/ops/crud_message_append_tests.rs
index 11356a3f46..325ccfa319 100644
--- a/crates/openhuman-core/src/threads/ops/crud_message_append_tests.rs
+++ b/crates/openhuman-core/src/threads/ops/crud_message_append_tests.rs
@@ -22,6 +22,14 @@ async fn setup() -> (tempfile::TempDir, crate::config::Config) {
(temp, config)
}
+async fn append_with_test_config(
+ request: AppendConversationMessageRequest,
+ config: &crate::config::Config,
+ origin: Option<&crate::agent::turn_origin::AgentTurnOrigin>,
+) -> Result<Outcome<ApiEnvelope<ConversationMessageRecord>>, ThreadsError> {
+ message_append_with_config(request, config, origin, &config.workspace_dir).await
+}
+
fn request(id: &str, content: &str, sender: &str) -> AppendConversationMessageRequest {
AppendConversationMessageRequest {
thread_id: "uploads".into(),
@@ -42,7 +50,7 @@ fn request(id: &str, content: &str, sender: &str) -> AppendConversationMessageRe
#[tokio::test]
async fn user_append_stages_original_strips_upload_bytes_and_reuses_returned_content() {
let (_temp, config) = setup().await;
- let first = message_append_with_config(
+ let first = append_with_test_config(
request(
"one",
"look [IMAGE:data:image/png;base64,iVBORw0KGgo=]",
@@ -74,7 +82,7 @@ async fn user_append_stages_original_strips_upload_bytes_and_reuses_returned_con
);
assert_eq!(first.extra_metadata["attachmentKinds"], json!(["image"]));
assert_eq!(first.extra_metadata["other"], "kept");
- let second = message_append_with_config(request("two", &first.content, "user"), &config, None)
+ let second = append_with_test_config(request("two", &first.content, "user"), &config, None)
.await
.unwrap()
.value
@@ -105,7 +113,7 @@ async fn user_append_stages_original_strips_upload_bytes_and_reuses_returned_con
async fn rejected_upload_never_appends_a_message() {
let (_temp, mut config) = setup().await;
config.multimodal_files.max_files = 0;
- assert!(message_append_with_config(
+ assert!(append_with_test_config(
request(
"disabled",
"[IMAGE:data:image/png;base64,iVBORw0KGgo=]",
@@ -117,7 +125,7 @@ async fn rejected_upload_never_appends_a_message() {
.await
.is_err());
config.multimodal_files.max_files = 3;
- assert!(message_append_with_config(
+ assert!(append_with_test_config(
request("bad", "[FILE:data:application/zip;base64,!]", "user"),
&config,
None,
@@ -125,7 +133,7 @@ async fn rejected_upload_never_appends_a_message() {
.await
.is_err());
assert!(
- message_append_with_config(request("missing", "image.png", "user"), &config, None)
+ append_with_test_config(request("missing", "image.png", "user"), &config, None)
.await
.is_err()
);
@@ -155,13 +163,11 @@ async fn external_origin_cannot_reuse_an_existing_attachment_marker() {
reply_target: "room".into(),
message_id: "message".into(),
};
- assert!(message_append_with_config(
- request("external", &staged, "user"),
- &config,
- Some(&origin)
- )
- .await
- .is_err());
+ assert!(
+ append_with_test_config(request("external", &staged, "user"), &config, Some(&origin))
+ .await
+ .is_err()
+ );
assert!(
conversations::blocking::get_messages(config.workspace_dir, "uploads".into())
.await
@@ -175,7 +181,7 @@ async fn ordinary_user_text_and_agent_images_are_preserved() {
let (_temp, config) = setup().await;
let mut user = request("text", "ordinary text", "user");
user.message.extra_metadata = json!({"other":"kept"});
- let stored = message_append_with_config(user, &config, None)
+ let stored = append_with_test_config(user, &config, None)
.await
.unwrap()
.value
@@ -189,7 +195,7 @@ async fn ordinary_user_text_and_agent_images_are_preserved() {
"assistant",
);
let expected = serde_json::to_value(&assistant.message).unwrap();
- let stored = message_append_with_config(assistant, &config, None)
+ let stored = append_with_test_config(assistant, &config, None)
.await
.unwrap()
.value
@@ -198,6 +204,45 @@ async fn ordinary_user_text_and_agent_images_are_preserved() {
assert_eq!(serde_json::to_value(stored).unwrap(), expected);
}
+#[tokio::test]
+async fn append_uses_host_persistence_workspace_separate_from_rpc_config() {
+ let (temp, config) = setup().await;
+ let persistence_dir = temp.path().join("host-thread-store");
+ conversations::blocking::ensure_thread(
+ persistence_dir.clone(),
+ conversations::CreateConversationThread {
+ id: "uploads".into(),
+ title: "Host thread store".into(),
+ created_at: "2026-10-04T00:00:00Z".into(),
+ parent_thread_id: None,
+ labels: None,
+ personality_id: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ message_append_with_config(
+ request("host-store", "saved in host workspace", "assistant"),
+ &config,
+ None,
+ &persistence_dir,
+ )
+ .await
+ .unwrap();
+
+ let persisted = conversations::blocking::get_messages(persistence_dir, "uploads".into())
+ .await
+ .unwrap();
+ assert_eq!(persisted.len(), 1);
+ assert!(
+ conversations::blocking::get_messages(config.workspace_dir, "uploads".into())
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
+
#[tokio::test]
async fn poster_only_user_metadata_is_rejected_before_persistence() {
let (_temp, config) = setup().await;
@@ -206,7 +251,7 @@ async fn poster_only_user_metadata_is_rejected_before_persistence() {
"attachmentNames": ["video.mp4"],
"attachmentPosters": ["data:image/png;base64,iVBORw0KGgo="]
});
- assert!(message_append_with_config(upload, &config, None)
+ assert!(append_with_test_config(upload, &config, None)
.await
.is_err());
assert!(