Skip to content

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

fix(artifacts): trust only core-vouched files folders; protect artifact metadata

M3gA-Mind2eeebe599562
diff --git a/crates/openhuman-app/src/artifact_commands.rs b/crates/openhuman-app/src/artifact_commands.rs
index b66a9a3680..d81d7da545 100644
--- a/crates/openhuman-app/src/artifact_commands.rs
+++ b/crates/openhuman-app/src/artifact_commands.rs
@@ -29,12 +29,16 @@ use std::path::{Path, PathBuf};
/// Resolve an artifact id to the file the core's artifact store vouches for,
/// in the given workspace. Isolated from config loading for unit testing.
-async fn resolve_source(workspace_dir: &Path, artifact_id: &str) -> Result<PathBuf, String> {
+async fn resolve_source(
+ workspace_dir: &Path,
+ roots: &openhuman_core::agent::artifacts::FileRoots,
+ artifact_id: &str,
+) -> Result<PathBuf, String> {
let artifact_id = artifact_id.trim();
if artifact_id.is_empty() {
return Err("artifact_id must not be empty".to_string());
}
- openhuman_core::agent::artifacts::resolve_ready_file(workspace_dir, artifact_id).await
+ openhuman_core::agent::artifacts::resolve_ready_file(workspace_dir, roots, artifact_id).await
}
/// Copy `source` to `dest`, returning the byte count. Isolated so it is
@@ -59,7 +63,8 @@ pub async fn download_artifact_to_downloads(
return Err("artifact_id must not be empty".to_string());
}
let config = openhuman_core::config::rpc::load_config_with_timeout().await?;
- let source = resolve_source(&config.workspace_dir, &artifact_id).await?;
+ let roots = openhuman_core::agent::artifacts::FileRoots::from_config(&config);
+ let source = resolve_source(&config.workspace_dir, &roots, &artifact_id).await?;
if filename.trim().is_empty() {
return Err("filename must not be empty".to_string());
}
diff --git a/crates/openhuman-app/src/artifact_commands_tests.rs b/crates/openhuman-app/src/artifact_commands_tests.rs
index 42b0c33b44..0da3a9aec2 100644
--- a/crates/openhuman-app/src/artifact_commands_tests.rs
+++ b/crates/openhuman-app/src/artifact_commands_tests.rs
@@ -1,4 +1,5 @@
use super::*;
+use openhuman_core::agent::artifacts::FileRoots;
#[test]
fn sanitize_rejects_path_separators() {
@@ -42,7 +43,9 @@ async fn resolve_source_returns_the_file_in_the_files_folder() {
let files_dir = temp.path().join("Files");
let id = ready_artifact(temp.path(), &files_dir).await;
assert_eq!(
- resolve_source(temp.path(), &id).await.unwrap(),
+ resolve_source(temp.path(), &FileRoots::new(&files_dir), &id)
+ .await
+ .unwrap(),
files_dir.join("deck.pptx")
);
}
@@ -50,12 +53,24 @@ async fn resolve_source_returns_the_file_in_the_files_folder() {
#[tokio::test]
async fn resolve_source_rejects_unknown_ids_and_paths() {
let temp = tempfile::tempdir().unwrap();
- assert!(resolve_source(temp.path(), "").await.is_err());
- assert!(resolve_source(temp.path(), "no-such-artifact")
- .await
- .is_err());
+ assert!(
+ resolve_source(temp.path(), &FileRoots::new(temp.path()), "")
+ .await
+ .is_err()
+ );
+ assert!(resolve_source(
+ temp.path(),
+ &FileRoots::new(temp.path()),
+ "no-such-artifact"
+ )
+ .await
+ .is_err());
// A path is not an id: the store's id validation refuses separators.
- assert!(resolve_source(temp.path(), "/etc/passwd").await.is_err());
+ assert!(
+ resolve_source(temp.path(), &FileRoots::new(temp.path()), "/etc/passwd")
+ .await
+ .is_err()
+ );
}
#[tokio::test]
@@ -81,7 +96,47 @@ async fn resolve_source_refuses_a_file_the_store_does_not_vouch_for() {
let dir = temp.path().join("artifacts").join("tampered");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("meta.json"), serde_json::to_vec(&meta).unwrap()).unwrap();
- assert!(resolve_source(temp.path(), "tampered").await.is_err());
+ assert!(resolve_source(
+ temp.path(),
+ &FileRoots::new(temp.path().join("Files")),
+ "tampered"
+ )
+ .await
+ .is_err());
+}
+
+/// Download-by-id does not take a record's `file_root` on its own say-so: a
+/// record claiming a home-directory root for a private file inside it is
+/// refused because that root is not one of the vouched-for files folders.
+#[tokio::test]
+async fn resolve_source_refuses_a_record_that_claims_its_own_root() {
+ use openhuman_core::agent::artifacts::{ArtifactKind, ArtifactMeta, ArtifactStatus};
+ let temp = tempfile::tempdir().unwrap();
+ let home = temp.path().join("home");
+ std::fs::create_dir_all(&home).unwrap();
+ let private = home.join("private.pdf");
+ std::fs::write(&private, b"private").unwrap();
+ let meta = ArtifactMeta {
+ id: "claims-home".to_string(),
+ kind: ArtifactKind::Other,
+ title: "x".to_string(),
+ path: "private.pdf".to_string(),
+ file: Some(private.to_string_lossy().into_owned()),
+ file_root: Some(home.to_string_lossy().into_owned()),
+ size_bytes: 7,
+ status: ArtifactStatus::Ready,
+ created_at: chrono::Utc::now(),
+ error: None,
+ thread_id: None,
+ tool_call_id: None,
+ };
+ let dir = temp.path().join("artifacts").join("claims-home");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("meta.json"), serde_json::to_vec(&meta).unwrap()).unwrap();
+ let files = FileRoots::new(temp.path().join("Files"));
+ assert!(resolve_source(temp.path(), &files, "claims-home")
+ .await
+ .is_err());
}
#[tokio::test]
diff --git a/crates/openhuman-core/src/agent/artifacts/files.rs b/crates/openhuman-core/src/agent/artifacts/files.rs
index f2c13f0952..9d6aec0ccc 100644
--- a/crates/openhuman-core/src/agent/artifacts/files.rs
+++ b/crates/openhuman-core/src/agent/artifacts/files.rs
@@ -15,8 +15,10 @@
//! # The escape guard
//!
//! `meta.json` is data, so a record's `file` is checked before anything reads
-//! or copies it: it must be absolute, free of `..`, strictly inside the
-//! record's `file_root` (after resolving symlinks when it exists), and never a
+//! or copies it. Its `file_root` counts only when it is one of the folders the
+//! core vouches for ([`FileRoots`], built by the caller or from config — never
+//! taken from the record), and the file must be absolute, free of `..`,
+//! strictly inside that root (after resolving symlinks when it exists), and never a
//! path [`SecurityPolicy::is_always_forbidden`] rejects. That last check is the
//! same floor the agent's own file tools keep when the autonomy policy is off,
//! so a hand-edited record cannot reach further than the agent already could.
@@ -29,6 +31,80 @@ use super::store::{artifacts_root, get_artifact};
use super::types::{ArtifactMeta, ArtifactStatus};
use crate::security::SecurityPolicy;
+/// The files folders the core vouches for: where new files go, plus every
+/// folder an existing record may legitimately point into. A record's
+/// `file_root` is honoured only when it matches one of these, so a
+/// hand-edited `meta.json` cannot widen what Download and
+/// `read_artifact_bytes` will serve.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct FileRoots {
+ current: PathBuf,
+ trusted: Vec<PathBuf>,
+}
+
+impl FileRoots {
+ /// New files go to `current`, which is also the only trusted folder.
+ pub fn new(current: impl Into<PathBuf>) -> Self {
+ let current = current.into();
+ Self {
+ trusted: vec![current.clone()],
+ current,
+ }
+ }
+
+ /// Also trust `folders` for existing records.
+ pub fn with_trusted(mut self, folders: impl IntoIterator<Item = PathBuf>) -> Self {
+ for folder in folders {
+ if !self.trusted.contains(&folder) {
+ self.trusted.push(folder);
+ }
+ }
+ self
+ }
+
+ /// The folders for this host config.
+ pub fn from_config(_config: &crate::config::Config) -> Self {
+ Self::new(crate::config::default_files_dir())
+ }
+
+ /// Where new files are written.
+ pub fn current(&self) -> &Path {
+ &self.current
+ }
+
+ /// Whether `root` is one of the vouched-for folders, compared canonically
+ /// where the paths exist.
+ fn trusts(&self, root: &Path) -> bool {
+ let canon = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
+ let root = canon(root);
+ self.trusted.iter().any(|t| canon(t) == root)
+ }
+}
+
+impl From<PathBuf> for FileRoots {
+ fn from(current: PathBuf) -> Self {
+ Self::new(current)
+ }
+}
+
+impl From<&PathBuf> for FileRoots {
+ fn from(current: &PathBuf) -> Self {
+ Self::new(current.clone())
+ }
+}
+
+impl From<&Path> for FileRoots {
+ fn from(current: &Path) -> Self {
+ Self::new(current.to_path_buf())
+ }
+}
+
+impl From<&FileRoots> for FileRoots {
+ fn from(roots: &FileRoots) -> Self {
+ roots.clone()
+ }
+}
+
/// Collision suffixes tried before falling back to an id-tagged name.
const MAX_COLLISION_SUFFIX: u32 = 1000;
@@ -87,6 +163,7 @@ pub(crate) async fn reserve_file(
pub(crate) async fn resolve_file(
workspace_dir: &Path,
meta: &ArtifactMeta,
+ roots: &FileRoots,
) -> Result<PathBuf, String> {
let Some(file) = meta.file.as_deref() else {
let root = artifacts_root(workspace_dir).await?;
@@ -105,6 +182,12 @@ pub(crate) async fn resolve_file(
.as_deref()
.map(PathBuf::from)
.ok_or_else(|| format!("[artifacts] id={} has a file but no file_root", meta.id))?;
+ if !roots.trusts(&root) {
+ return Err(format!(
+ "[artifacts] file for id={} rejected by the escape guard: its folder is not a files folder",
+ meta.id
+ ));
+ }
check_within(&root, &file).map_err(|reason| {
format!(
"[artifacts] file for id={} rejected by the escape guard: {reason}",
@@ -164,6 +247,7 @@ fn check_within(root: &Path, file: &Path) -> Result<(), &'static str> {
/// its file was moved or deleted outside OpenHuman.
pub async fn resolve_ready_file(
workspace_dir: &Path,
+ roots: &FileRoots,
artifact_id: &str,
) -> Result<PathBuf, String> {
let meta = get_artifact(workspace_dir, artifact_id).await?;
@@ -173,7 +257,7 @@ pub async fn resolve_ready_file(
meta.status
));
}
- let path = resolve_file(workspace_dir, &meta).await?;
+ let path = resolve_file(workspace_dir, &meta, roots).await?;
if !tokio::fs::try_exists(&path).await.unwrap_or(false) {
return Err(missing_file_error(artifact_id, &path));
}
@@ -191,11 +275,15 @@ pub(crate) fn missing_file_error(artifact_id: &str, path: &Path) -> String {
/// A failed generation must not leave an empty file in the user's files
/// folder: drop the zero-byte placeholder `create_artifact` reserved. A file
/// with bytes (e.g. the previous output of a failed regenerate) is kept.
-pub(crate) async fn remove_empty_placeholder(workspace_dir: &Path, meta: &ArtifactMeta) {
+pub(crate) async fn remove_empty_placeholder(
+ workspace_dir: &Path,
+ meta: &ArtifactMeta,
+ roots: &FileRoots,
+) {
if meta.file.is_none() {
return;
}
- let Ok(path) = resolve_file(workspace_dir, meta).await else {
+ let Ok(path) = resolve_file(workspace_dir, meta, roots).await else {
return;
};
if matches!(tokio::fs::metadata(&path).await, Ok(m) if m.is_file() && m.len() == 0) {
diff --git a/crates/openhuman-core/src/agent/artifacts/files_tests.rs b/crates/openhuman-core/src/agent/artifacts/files_tests.rs
index 5c2c597e76..7827f0a35d 100644
--- a/crates/openhuman-core/src/agent/artifacts/files_tests.rs
+++ b/crates/openhuman-core/src/agent/artifacts/files_tests.rs
@@ -107,11 +107,15 @@ async fn a_repeated_title_gets_a_numbered_name_instead_of_overwriting() {
assert_eq!(first.path, "report.txt");
assert_eq!(second.path, "report (2).txt");
assert_eq!(
- read_artifact_bytes(tmp.path(), &first.id).await.unwrap(),
+ read_artifact_bytes(tmp.path(), &files_dir, &first.id)
+ .await
+ .unwrap(),
b"one"
);
assert_eq!(
- read_artifact_bytes(tmp.path(), &second.id).await.unwrap(),
+ read_artifact_bytes(tmp.path(), &files_dir, &second.id)
+ .await
+ .unwrap(),
b"two"
);
}
@@ -131,11 +135,11 @@ async fn two_accounts_share_the_files_folder_without_clobbering_or_leaking() {
assert_ne!(a.file, b.file);
assert_eq!(
- read_artifact_bytes(&ws_a, &a.id).await.unwrap(),
+ read_artifact_bytes(&ws_a, &files_dir, &a.id).await.unwrap(),
b"account a"
);
assert_eq!(
- read_artifact_bytes(&ws_b, &b.id).await.unwrap(),
+ read_artifact_bytes(&ws_b, &files_dir, &b.id).await.unwrap(),
b"account b"
);
@@ -189,7 +193,7 @@ async fn a_failed_generation_leaves_no_empty_file_behind() {
.unwrap();
assert!(path.is_file());
- fail_artifact(tmp.path(), &meta.id, "engine exploded")
+ fail_artifact(tmp.path(), &files_dir, &meta.id, "engine exploded")
.await
.unwrap();
@@ -203,7 +207,9 @@ async fn delete_removes_the_file_and_the_record() {
let meta = create_ready(tmp.path(), &files_dir, "Gone", b"bye").await;
let file = PathBuf::from(meta.file.clone().unwrap());
- delete_artifact(tmp.path(), &meta.id).await.unwrap();
+ delete_artifact(tmp.path(), &files_dir, &meta.id)
+ .await
+ .unwrap();
assert!(!file.exists());
assert!(!tmp.path().join("artifacts").join(&meta.id).exists());
@@ -216,9 +222,13 @@ async fn a_file_removed_outside_openhuman_is_reported_missing() {
let meta = create_ready(tmp.path(), &files_dir, "Moved", b"abc").await;
std::fs::remove_file(meta.file.as_deref().unwrap()).unwrap();
- let err = read_artifact_bytes(tmp.path(), &meta.id).await.unwrap_err();
+ let err = read_artifact_bytes(tmp.path(), &files_dir, &meta.id)
+ .await
+ .unwrap_err();
assert!(err.contains("file missing"), "{err}");
- let err = resolve_ready_file(tmp.path(), &meta.id).await.unwrap_err();
+ let err = resolve_ready_file(tmp.path(), &FileRoots::new(&files_dir), &meta.id)
+ .await
+ .unwrap_err();
assert!(err.contains("file missing"), "{err}");
}
@@ -227,7 +237,10 @@ async fn tampered(workspace: &Path, file: &Path, file_root: &Path) -> String {
meta.file = Some(file.to_string_lossy().into_owned());
meta.file_root = Some(file_root.to_string_lossy().into_owned());
save_artifact_meta(workspace, &meta).await.unwrap();
- read_artifact_bytes(workspace, "tampered")
+ // Trust the record's own root here so these cases exercise the checks
+ // *within* a root; `a_record_pointing_outside_the_files_folders_is_refused`
+ // covers a root the core does not vouch for.
+ read_artifact_bytes(workspace, file_root, "tampered")
.await
.unwrap_err()
}
@@ -284,7 +297,9 @@ async fn a_legacy_record_still_resolves_under_the_workspace() {
std::fs::write(tmp.path().join("artifacts/legacy-1/old.txt"), b"old").unwrap();
assert_eq!(
- read_artifact_bytes(tmp.path(), "legacy-1").await.unwrap(),
+ read_artifact_bytes(tmp.path(), tmp.path(), "legacy-1")
+ .await
+ .unwrap(),
b"old"
);
}
@@ -299,7 +314,7 @@ async fn a_legacy_path_with_parent_components_is_rejected() {
let meta = legacy_meta("legacy-2", "../../secret.txt");
save_artifact_meta(&workspace, &meta).await.unwrap();
- let err = read_artifact_bytes(&workspace, "legacy-2")
+ let err = read_artifact_bytes(&workspace, tmp.path(), "legacy-2")
.await
.unwrap_err();
assert!(err.contains("escapes artifacts root"), "{err}");
@@ -360,3 +375,53 @@ async fn a_recorded_file_that_does_not_exist_reads_as_missing() {
let err = tampered(tmp.path(), &files_dir.join("gone.txt"), &files_dir).await;
assert!(err.contains("file missing"), "{err}");
}
+
+/// The record's `file_root` is not trusted on its own say-so: a record that
+/// claims a home-directory root and points at a private file inside it passes
+/// every within-root check, and is still refused because that root is not one
+/// of the folders the core vouches for.
+#[tokio::test]
+async fn a_record_pointing_outside_the_files_folders_is_refused() {
+ let tmp = TempDir::new().unwrap();
+ let files_dir = tmp.path().join("Files");
+ std::fs::create_dir_all(&files_dir).unwrap();
+ let home = tmp.path().join("home");
+ let private = home.join("Documents").join("private.pdf");
+ std::fs::create_dir_all(private.parent().unwrap()).unwrap();
+ std::fs::write(&private, b"private").unwrap();
+
+ let mut meta = legacy_meta("claims-home", "private.pdf");
+ meta.file = Some(private.to_string_lossy().into_owned());
+ meta.file_root = Some(home.to_string_lossy().into_owned());
+ save_artifact_meta(tmp.path(), &meta).await.unwrap();
+
+ let err = read_artifact_bytes(tmp.path(), &files_dir, "claims-home")
+ .await
+ .unwrap_err();
+ assert!(err.contains("not a files folder"), "{err}");
+ let err = resolve_ready_file(tmp.path(), &FileRoots::new(&files_dir), "claims-home")
+ .await
+ .unwrap_err();
+ assert!(err.contains("not a files folder"), "{err}");
+}
+
+/// A folder the user moved away from stays trusted for the records made there.
+#[tokio::test]
+async fn a_previously_trusted_folder_still_resolves() {
+ let tmp = TempDir::new().unwrap();
+ let old = tmp.path().join("Old");
+ let meta = create_ready(tmp.path(), &old, "Kept", b"kept").await;
+
+ let roots = FileRoots::new(tmp.path().join("New")).with_trusted([old.clone()]);
+ assert_eq!(
+ read_artifact_bytes(tmp.path(), &roots, &meta.id)
+ .await
+ .unwrap(),
+ b"kept"
+ );
+ // Without the old folder in the trusted set, the same record is refused.
+ let err = read_artifact_bytes(tmp.path(), tmp.path().join("New"), &meta.id)
+ .await
+ .unwrap_err();
+ assert!(err.contains("not a files folder"), "{err}");
+}
diff --git a/crates/openhuman-core/src/agent/artifacts/migrate_tests.rs b/crates/openhuman-core/src/agent/artifacts/migrate_tests.rs
index f57632abee..22a89adda3 100644
--- a/crates/openhuman-core/src/agent/artifacts/migrate_tests.rs
+++ b/crates/openhuman-core/src/agent/artifacts/migrate_tests.rs
@@ -98,7 +98,10 @@ async fn moves_a_legacy_file_into_the_files_folder() {
Some(files_dir.to_string_lossy().as_ref())
);
assert_eq!(meta.path, "q3-deck.pptx");
- assert_eq!(read_artifact_bytes(&ws, "a1").await.unwrap(), b"deck bytes");
+ assert_eq!(
+ read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(),
+ b"deck bytes"
+ );
assert!(
!legacy_path(&ws, "a1", "q3-deck.pptx").exists(),
"legacy bytes removed"
@@ -121,7 +124,10 @@ async fn running_twice_changes_nothing() {
assert_eq!(second, MigrationReport::default());
assert_eq!(visible(&files_dir), vec!["notes.docx"]);
- assert_eq!(read_artifact_bytes(&ws, "a1").await.unwrap(), b"notes");
+ assert_eq!(
+ read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(),
+ b"notes"
+ );
}
#[tokio::test]
@@ -167,7 +173,7 @@ async fn a_name_already_in_the_folder_is_never_overwritten() {
"report (2).txt"
);
assert_eq!(
- read_artifact_bytes(&ws, "a1").await.unwrap(),
+ read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(),
b"agent report"
);
}
@@ -202,11 +208,11 @@ async fn two_accounts_migrate_into_the_shared_folder_without_clobbering() {
assert_eq!(visible(&files_dir), vec!["budget (2).xlsx", "budget.xlsx"]);
assert_eq!(
- read_artifact_bytes(&ws_a, "a1").await.unwrap(),
+ read_artifact_bytes(&ws_a, &files_dir, "a1").await.unwrap(),
b"a's budget"
);
assert_eq!(
- read_artifact_bytes(&ws_b, "b1").await.unwrap(),
+ read_artifact_bytes(&ws_b, &files_dir, "b1").await.unwrap(),
b"b's budget"
);
let (listed, total) = list_artifacts(&ws_b, 0, 50, None).await.unwrap();
@@ -224,14 +230,20 @@ async fn a_crash_after_the_copy_leaves_the_record_intact_and_is_redone() {
migrate_with(&ws, &files_dir, Some(CrashAfter::Copy)).await;
assert!(get_artifact(&ws, "a1").await.unwrap().file.is_none());
- assert_eq!(read_artifact_bytes(&ws, "a1").await.unwrap(), b"deck");
+ assert_eq!(
+ read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(),
+ b"deck"
+ );
assert_eq!(partials(&files_dir), 1);
let report = migrate_legacy_artifacts(&ws, &files_dir).await;
assert_eq!(report.moved, 1);
assert_eq!(partials(&files_dir), 0, "the stale partial is removed");
assert_eq!(visible(&files_dir), vec!["deck.pptx"]);
- assert_eq!(read_artifact_bytes(&ws, "a1").await.unwrap(), b"deck");
+ assert_eq!(
+ read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(),
+ b"deck"
+ );
}
#[tokio::test]
@@ -243,12 +255,18 @@ async fn a_crash_after_the_rename_loses_nothing_and_leaves_at_most_one_duplicate
migrate_with(&ws, &files_dir, Some(CrashAfter::Rename)).await;
assert!(get_artifact(&ws, "a1").await.unwrap().file.is_none());
- assert_eq!(read_artifact_bytes(&ws, "a1").await.unwrap(), b"deck");
+ assert_eq!(
+ read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(),
+ b"deck"
+ );
migrate_legacy_artifacts(&ws, &files_dir).await;
let meta = get_artifact(&ws, "a1").await.unwrap();
assert!(meta.file.is_some());
- assert_eq!(read_artifact_bytes(&ws, "a1").await.unwrap(), b"deck");
+ assert_eq!(
+ read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(),
+ b"deck"
+ );
assert!(visible(&files_dir).len() <= 2);
assert!(!legacy_path(&ws, "a1", "deck.pptx").exists());
}
@@ -266,7 +284,10 @@ async fn a_crash_after_the_meta_write_is_finished_by_the_next_run() {
legacy_path(&ws, "a1", "deck.pptx").exists(),
"legacy copy not yet removed"
);
- assert_eq!(read_artifact_bytes(&ws, "a1").await.unwrap(), b"deck");
+ assert_eq!(
+ read_artifact_bytes(&ws, &files_dir, "a1").await.unwrap(),
+ b"deck"
+ );
let report = migrate_legacy_artifacts(&ws, &files_dir).await;
assert_eq!(
diff --git a/crates/openhuman-core/src/agent/artifacts/mod.rs b/crates/openhuman-core/src/agent/artifacts/mod.rs
index 3635cc8cd6..9bd595dc02 100644
--- a/crates/openhuman-core/src/agent/artifacts/mod.rs
+++ b/crates/openhuman-core/src/agent/artifacts/mod.rs
@@ -6,7 +6,7 @@ pub mod store;
pub mod tools;
pub mod types;
-pub use files::resolve_ready_file;
+pub use files::{resolve_ready_file, FileRoots};
pub use migrate::{migrate_legacy_artifacts, MigrationReport};
pub use schemas::{
all_controller_schemas as all_artifacts_controller_schemas,
diff --git a/crates/openhuman-core/src/agent/artifacts/ops.rs b/crates/openhuman-core/src/agent/artifacts/ops.rs
index a329a0c9ad..d0a806b65f 100644
--- a/crates/openhuman-core/src/agent/artifacts/ops.rs
+++ b/crates/openhuman-core/src/agent/artifacts/ops.rs
@@ -83,7 +83,8 @@ pub async fn ai_get_artifact(config: &Config, artifact_id: &str) -> Result<Outco
// inside its recorded files folder, a legacy `meta.path` inside the
// artifacts root. A Ready record whose file was moved or deleted outside
// OpenHuman is an error rather than a path that points at nothing.
- let resolved = super::files::resolve_file(&config.workspace_dir, &meta).await?;
+ let roots = super::files::FileRoots::from_config(config);
+ let resolved = super::files::resolve_file(&config.workspace_dir, &meta, &roots).await?;
if matches!(meta.status, super::types::ArtifactStatus::Ready)
&& !tokio::fs::try_exists(&resolved).await.unwrap_or(false)
{
@@ -122,7 +123,12 @@ pub async fn ai_delete_artifact(
return Err("[artifacts] artifact_id must not be empty".to_string());
}
- store::delete_artifact(&config.workspace_dir, artifact_id).await?;
+ store::delete_artifact(
+ &config.workspace_dir,
+ super::files::FileRoots::from_config(config),
+ artifact_id,
+ )
+ .await?;
log::debug!("[artifacts] ai_delete_artifact: deleted id={artifact_id}");
let value = json!({
diff --git a/crates/openhuman-core/src/agent/artifacts/ops_tests.rs b/crates/openhuman-core/src/agent/artifacts/ops_tests.rs
index 54c6150cfb..f9b7edc7cf 100644
--- a/crates/openhuman-core/src/agent/artifacts/ops_tests.rs
+++ b/crates/openhuman-core/src/agent/artifacts/ops_tests.rs
@@ -310,13 +310,51 @@ async fn regenerate_reruns_producer_and_reuses_id() {
// ── #5505: files folder ─────────────────────────────────────────────────────
+/// Points the default files folder (`OPENHUMAN_PROJECTS_DIR/Files`) at a temp
+/// dir for one test, holding the shared env lock, and restores it on drop.
+struct DefaultFilesDir {
+ _lock: std::sync::MutexGuard<'static, ()>,
+ previous: Option<std::ffi::OsString>,
+ files_dir: std::path::PathBuf,
+}
+
+impl DefaultFilesDir {
+ fn under(tmp: &TempDir) -> Self {
+ let lock = crate::config::TEST_ENV_LOCK
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ let previous = std::env::var_os("OPENHUMAN_PROJECTS_DIR");
+ let projects = tmp.path().join("projects");
+ unsafe {
+ std::env::set_var("OPENHUMAN_PROJECTS_DIR", &projects);
+ }
+ Self {
+ _lock: lock,
+ previous,
+ files_dir: crate::config::default_files_dir(),
+ }
+ }
+}
+
+impl Drop for DefaultFilesDir {
+ fn drop(&mut self) {
+ unsafe {
+ match self.previous.take() {
+ Some(v) => std::env::set_var("OPENHUMAN_PROJECTS_DIR", v),
+ None => std::env::remove_var("OPENHUMAN_PROJECTS_DIR"),
+ }
+ }
+ }
+}
+
#[tokio::test]
async fn get_returns_the_files_folder_path() {
use crate::agent::artifacts::store::{create_artifact, finalize_artifact};
use crate::agent::artifacts::types::ArtifactKind;
let tmp = TempDir::new().unwrap();
let config = test_config(&tmp);
- let files_dir = tmp.path().join("Files");
+ let default = DefaultFilesDir::under(&tmp);
+ let files_dir = default.files_dir.clone();
let (meta, path) = create_artifact(
tmp.path(),
&files_dir,
@@ -347,9 +385,10 @@ async fn get_reports_a_ready_file_removed_outside_openhuman() {
use crate::agent::artifacts::types::ArtifactKind;
let tmp = TempDir::new().unwrap();
let config = test_config(&tmp);
+ let default = DefaultFilesDir::under(&tmp);
let (meta, path) = create_artifact(
tmp.path(),
- &tmp.path().join("Files"),
+ &default.files_dir,
ArtifactKind::Document,
"Plan",
"docx",
@@ -363,3 +402,46 @@ async fn get_reports_a_ready_file_removed_outside_openhuman() {
let err = ai_get_artifact(&config, &meta.id).await.unwrap_err();
assert!(err.contains("file missing"), "{err}");
}
+
+/// A record whose `file_root` is not a files folder the core vouches for is
+/// refused by get, and delete leaves the file it names alone.
+#[tokio::test]
+async fn get_and_delete_refuse_a_record_rooted_outside_the_files_folder() {
+ use crate::agent::artifacts::store::save_artifact_meta;
+ use crate::agent::artifacts::types::{ArtifactKind, ArtifactMeta, ArtifactStatus};
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let _default = DefaultFilesDir::under(&tmp);
+ let home = tmp.path().join("home");
+ let private = home.join("private.pdf");
+ std::fs::create_dir_all(&home).unwrap();
+ std::fs::write(&private, b"private").unwrap();
+ save_artifact_meta(
+ tmp.path(),
+ &ArtifactMeta {
+ id: "claims-home".to_string(),
+ kind: ArtifactKind::Document,
+ title: "x".to_string(),
+ path: "private.pdf".to_string(),
+ file: Some(private.to_string_lossy().into_owned()),
+ file_root: Some(home.to_string_lossy().into_owned()),
+ size_bytes: 7,
+ status: ArtifactStatus::Ready,
+ created_at: chrono::Utc::now(),
+ error: None,
+ thread_id: None,
+ tool_call_id: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ let err = ai_get_artifact(&config, "claims-home").await.unwrap_err();
+ assert!(err.contains("not a files folder"), "{err}");
+
+ ai_delete_artifact(&config, "claims-home").await.unwrap();
+ assert!(
+ private.exists(),
+ "the file outside the files folder is left alone"
+ );
+}
diff --git a/crates/openhuman-core/src/agent/artifacts/store.rs b/crates/openhuman-core/src/agent/artifacts/store.rs
index b06f1bce47..124826b53f 100644
--- a/crates/openhuman-core/src/agent/artifacts/store.rs
+++ b/crates/openhuman-core/src/agent/artifacts/store.rs
@@ -1,6 +1,6 @@
use std::path::{Path, PathBuf};
-use super::files;
+use super::files::{self, FileRoots};
use super::types::{ArtifactMeta, ArtifactStatus};
const ARTIFACTS_SUBDIR: &str = "artifacts";
@@ -332,10 +332,11 @@ pub(crate) async fn read_artifact_args(
/// guard, and reports a file removed outside OpenHuman as missing.
pub async fn read_artifact_bytes(
workspace_dir: &Path,
+ roots: impl Into<FileRoots>,
artifact_id: &str,
) -> Result<Vec<u8>, String> {
log::debug!("[artifacts] read_artifact_bytes: id={artifact_id}");
- let file_path = files::resolve_ready_file(workspace_dir, artifact_id).await?;
+ let file_path = files::resolve_ready_file(workspace_dir, &roots.into(), artifact_id).await?;
let bytes = tokio::fs::read(&file_path)
.await
.map_err(|e| format!("[artifacts] failed to read artifact bytes id={artifact_id}: {e}"))?;
@@ -349,7 +350,12 @@ pub async fn read_artifact_bytes(
/// Delete an artifact: its file in the files folder, then its metadata
/// directory. A file already gone, or one the escape guard rejects, is left
/// alone (logged) and the record is still removed.
-pub(crate) async fn delete_artifact(workspace_dir: &Path, artifact_id: &str) -> Result<(), String> {
+pub(crate) async fn delete_artifact(
+ workspace_dir: &Path,
+ roots: impl Into<FileRoots>,
+ artifact_id: &str,
+) -> Result<(), String> {
+ let roots = roots.into();
log::debug!("[artifacts] delete_artifact: id={artifact_id}");
validate_artifact_id(artifact_id)?;
let root = artifacts_root(workspace_dir).await?;
@@ -357,7 +363,7 @@ pub(crate) async fn delete_artifact(workspace_dir: &Path, artifact_id: &str) ->
assert_within_root(&root, &artifact_dir)?;
if let Ok(meta) = get_artifact(workspace_dir, artifact_id).await {
if meta.file.is_some() {
- match files::resolve_file(workspace_dir, &meta).await {
+ match files::resolve_file(workspace_dir, &meta, &roots).await {
Ok(file) => match tokio::fs::remove_file(&file).await {
Ok(()) => log::debug!(
"[artifacts] delete_artifact: removed file for id={artifact_id}"
@@ -452,12 +458,12 @@ fn sanitize_filename_stem(title: &str) -> String {
/// bridge silently drops the event for lack of a routing target.
pub async fn create_artifact(
workspace_dir: &Path,
- files_dir: &Path,
+ files: impl Into<FileRoots>,
kind: super::types::ArtifactKind,
title: &str,
extension: &str,
) -> Result<(ArtifactMeta, PathBuf), String> {
- create_artifact_for_call(workspace_dir, files_dir, kind, title, extension, None).await
+ create_artifact_for_call(workspace_dir, files, kind, title, extension, None).await
}
/// As [`create_artifact`], but also records the provider-assigned
@@ -468,12 +474,14 @@ pub async fn create_artifact(
/// exactly like [`create_artifact`].
pub async fn create_artifact_for_call(
workspace_dir: &Path,
- files_dir: &Path,
+ files: impl Into<FileRoots>,
kind: super::types::ArtifactKind,
title: &str,
extension: &str,
tool_call_id: Option<&str>,
) -> Result<(ArtifactMeta, PathBuf), String> {
+ let roots = files.into();
+ let files_dir = roots.current();
let trimmed_title = title.trim();
if trimmed_title.is_empty() {
return Err("[artifacts] create_artifact: title must not be empty".to_string());
@@ -537,7 +545,7 @@ pub async fn create_artifact_for_call(
.map(|prev| prev.created_at)
.unwrap_or_else(chrono::Utc::now);
let owned_file = match previous.as_ref().filter(|prev| prev.file.is_some()) {
- Some(prev) => match files::resolve_file(workspace_dir, prev).await {
+ Some(prev) => match files::resolve_file(workspace_dir, prev, &roots).await {
Ok(path) if tokio::fs::try_exists(&path).await.unwrap_or(false) => prev
.file_root
.clone()
@@ -657,6 +665,7 @@ pub async fn finalize_artifact(
/// rules as [`finalize_artifact`].
pub async fn fail_artifact(
workspace_dir: &Path,
+ roots: impl Into<FileRoots>,
artifact_id: &str,
reason: &str,
) -> Result<ArtifactMeta, String> {
@@ -664,7 +673,7 @@ pub async fn fail_artifact(
meta.status = ArtifactStatus::Failed;
meta.error = Some(reason.to_string());
save_artifact_meta(workspace_dir, &meta).await?;
- files::remove_empty_placeholder(workspace_dir, &meta).await;
+ files::remove_empty_placeholder(workspace_dir, &meta, &roots.into()).await;
// Log only the size of the reason — it can carry provider stderr
// / user-derived content, which we don't want flushed verbatim
// into structured logs. The full payload is still persisted on
diff --git a/crates/openhuman-core/src/agent/artifacts/store_tests.rs b/crates/openhuman-core/src/agent/artifacts/store_tests.rs
index 635eab5c2d..93d3ce29b2 100644
--- a/crates/openhuman-core/src/agent/artifacts/store_tests.rs
+++ b/crates/openhuman-core/src/agent/artifacts/store_tests.rs
@@ -105,7 +105,9 @@ async fn delete_removes_directory_and_meta() {
// Confirm it exists
get_artifact(tmp.path(), "del-id").await.unwrap();
- delete_artifact(tmp.path(), "del-id").await.unwrap();
+ delete_artifact(tmp.path(), tmp.path(), "del-id")
+ .await
+ .unwrap();
// Should now be gone
let err = get_artifact(tmp.path(), "del-id").await.unwrap_err();
@@ -118,7 +120,7 @@ async fn delete_removes_directory_and_meta() {
#[tokio::test]
async fn delete_nonexistent_returns_error() {
let tmp = TempDir::new().unwrap();
- let err = delete_artifact(tmp.path(), "nonexistent-id")
+ let err = delete_artifact(tmp.path(), tmp.path(), "nonexistent-id")
.await
.unwrap_err();
assert!(
@@ -449,7 +451,7 @@ async fn fail_artifact_fills_request_id_from_chat_context() {
)
.await
.expect("create_artifact succeeds");
- fail_artifact(tmp.path(), &meta.id, "boom")
+ fail_artifact(tmp.path(), tmp.path(), &meta.id, "boom")
.await
.expect("fail_artifact succeeds");
meta
diff --git a/crates/openhuman-core/src/media/generation/artifact_tool.rs b/crates/openhuman-core/src/media/generation/artifact_tool.rs
index 5446f90167..01c292b75c 100644
--- a/crates/openhuman-core/src/media/generation/artifact_tool.rs
+++ b/crates/openhuman-core/src/media/generation/artifact_tool.rs
@@ -170,13 +170,14 @@ impl<T: Tool> MediaArtifactTool<T> {
}
}
Err(err) => {
- let _ = fail_artifact(&self.workspace_dir, &meta.id, &err).await;
+ let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &err)
+ .await;
set_artifact_error(entry, &err);
}
}
}
Err(err) => {
- let _ = fail_artifact(&self.workspace_dir, &meta.id, &err).await;
+ let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &err).await;
tracing::warn!(
target: "media_generation",
err = %err,
diff --git a/crates/openhuman-core/src/security/policy/path_checks.rs b/crates/openhuman-core/src/security/policy/path_checks.rs
index 29f686a4d1..7d2409ef6d 100644
--- a/crates/openhuman-core/src/security/policy/path_checks.rs
+++ b/crates/openhuman-core/src/security/policy/path_checks.rs
@@ -1,7 +1,9 @@
use std::path::{Path, PathBuf};
use super::types::{SecurityPolicy, TrustedAccess, POLICY_BLOCKED_MARKER};
-use super::types::{WORKSPACE_INTERNAL_DIRS, WORKSPACE_INTERNAL_FILES};
+use super::types::{
+ ARTIFACTS_DIR, ARTIFACT_TOOL_RESULTS_DIR, WORKSPACE_INTERNAL_DIRS, WORKSPACE_INTERNAL_FILES,
+};
impl SecurityPolicy {
/// Expand a leading `~/` to the user's home directory. Delegates to
@@ -414,6 +416,18 @@ impl SecurityPolicy {
{
return true;
}
+ // Artifact metadata (#5505): `artifacts/<id>/meta.json` names the file
+ // an artifact owns and Download / `read_artifact_bytes` follow it, so
+ // every per-artifact directory is internal state. `artifacts/tool-
+ // results/` is not: the agent reads its own large tool outputs back
+ // from there.
+ if component == ARTIFACTS_DIR {
+ if let Some(std::path::Component::Normal(second)) = relative.components().nth(1) {
+ if second != ARTIFACT_TOOL_RESULTS_DIR {
+ return true;
+ }
+ }
+ }
// Check single-file entries (only if the relative path is exactly one component)
if relative.components().count() == 1
&& WORKSPACE_INTERNAL_FILES
diff --git a/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs b/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs
index 8082d0ad4c..674fa22537 100644
--- a/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs
+++ b/crates/openhuman-core/src/security/policy/policy_workspace_internal_tests.rs
@@ -91,6 +91,47 @@ fn is_path_string_allowed_blocks_workspace_internal() {
);
}
+/// #5505: an artifact's `meta.json` / `args.json` name the file Download and
+/// `read_artifact_bytes` follow, so the agent's file tools must not write them
+/// even through a trusted root that reaches the workspace, while the
+/// `artifacts/tool-results/` read-back stays reachable.
+#[tokio::test]
+async fn artifact_metadata_is_internal_but_tool_results_are_not() {
+ let tmp = tempfile::tempdir().expect("tempdir");
+ let ws = tmp.path().join("workspace");
+ let record = ws.join("artifacts").join("abc");
+ let results = ws.join("artifacts").join("tool-results").join("s1");
+ std::fs::create_dir_all(&record).expect("create record dir");
+ std::fs::create_dir_all(&results).expect("create tool-results dir");
+ std::fs::write(record.join("meta.json"), "{}").expect("write meta");
+ std::fs::write(results.join("call-1.txt"), "output").expect("write result");
+ let policy = SecurityPolicy {
+ workspace_dir: ws.clone(),
+ action_dir: ws.clone(),
+ workspace_only: false,
+ trusted_roots: vec![TrustedRoot {
+ path: ws.to_string_lossy().into_owned(),
+ access: TrustedAccess::ReadWrite,
+ }],
+ ..SecurityPolicy::default()
+ };
+
+ let meta = record.join("meta.json");
+ assert!(!policy.is_path_string_allowed(&meta.to_string_lossy()));
+ assert!(policy.validate_path(&meta.to_string_lossy()).await.is_err());
+ assert!(policy
+ .validate_parent_path(&record.join("args.json").to_string_lossy())
+ .await
+ .is_err());
+
+ let result = results.join("call-1.txt");
+ assert!(policy.is_path_string_allowed(&result.to_string_lossy()));
+ assert!(policy
+ .validate_path(&result.to_string_lossy())
+ .await
+ .is_ok());
+}
+
#[tokio::test]
async fn trusted_root_cannot_expose_workspace_internal_state() {
let tmp = tempfile::tempdir().expect("tempdir");
diff --git a/crates/openhuman-core/src/security/policy/types.rs b/crates/openhuman-core/src/security/policy/types.rs
index ed99a16dd9..661ccb4966 100644
--- a/crates/openhuman-core/src/security/policy/types.rs
+++ b/crates/openhuman-core/src/security/policy/types.rs
@@ -211,6 +211,13 @@ pub(super) const WORKSPACE_INTERNAL_DIRS: &[&str] = &[
"tinyplace",
];
+/// The artifact store under `workspace_dir`. Its per-artifact directories are
+/// internal state (see `is_workspace_internal_path`); only
+/// [`ARTIFACT_TOOL_RESULTS_DIR`] inside it stays agent-readable.
+pub(super) const ARTIFACTS_DIR: &str = "artifacts";
+/// Where oversized tool outputs are persisted for the agent to read back.
+pub(super) const ARTIFACT_TOOL_RESULTS_DIR: &str = "tool-results";
+
/// Files directly under `workspace_dir` that hold secrets or persona config
/// and must not be writable by agent tools.
pub(super) const WORKSPACE_INTERNAL_FILES: &[&str] = &[
diff --git a/crates/openhuman-core/src/tools/impl/document/mod.rs b/crates/openhuman-core/src/tools/impl/document/mod.rs
index 374fbcb178..d710fdffc4 100644
--- a/crates/openhuman-core/src/tools/impl/document/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/document/mod.rs
@@ -241,7 +241,13 @@ impl Tool for DocumentTool {
let bytes = match engine::generate(&input, GENERATION_TIMEOUT).await {
Ok(bytes) => bytes,
Err(err) => {
- let _ = fail_artifact(&self.workspace_dir, &meta.id, &err.to_string()).await;
+ let _ = fail_artifact(
+ &self.workspace_dir,
+ &self.files_dir,
+ &meta.id,
+ &err.to_string(),
+ )
+ .await;
tracing::warn!(
target: "document",
err = %err,
@@ -257,7 +263,7 @@ impl Tool for DocumentTool {
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let reason = format!("failed to write generated document ({filename}): {err}");
- let _ = fail_artifact(&self.workspace_dir, &meta.id, &reason).await;
+ let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await;
tracing::warn!(
target: "document",
err = %err,
@@ -278,7 +284,8 @@ impl Tool for DocumentTool {
// stuck `Pending` spinner. Fail-artifact errors are
// swallowed — they can only recur if the same ledger backend
// is unavailable.
- let _ = fail_artifact(&self.workspace_dir, &meta.id, &reason).await;
+ let _ =
+ fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await;
tracing::warn!(
target: "document",
err = %err,
diff --git a/crates/openhuman-core/src/tools/impl/presentation/mod.rs b/crates/openhuman-core/src/tools/impl/presentation/mod.rs
index 702c30ebcb..3508c1e2c4 100644
--- a/crates/openhuman-core/src/tools/impl/presentation/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/presentation/mod.rs
@@ -305,7 +305,13 @@ impl Tool for PresentationTool {
{
Ok(bytes) => bytes,
Err(err) => {
- let _ = fail_artifact(&self.workspace_dir, &meta.id, &err.to_string()).await;
+ let _ = fail_artifact(
+ &self.workspace_dir,
+ &self.files_dir,
+ &meta.id,
+ &err.to_string(),
+ )
+ .await;
tracing::warn!(
target: "presentation",
err = %err,
@@ -321,7 +327,7 @@ impl Tool for PresentationTool {
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let reason = format!("failed to write generated deck ({filename}): {err}");
- let _ = fail_artifact(&self.workspace_dir, &meta.id, &reason).await;
+ let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await;
tracing::warn!(
target: "presentation",
err = %err,
@@ -343,7 +349,8 @@ impl Tool for PresentationTool {
// errors are swallowed — they can only happen if the same
// ledger backend is unavailable, in which case nothing we
// do here will help.
- let _ = fail_artifact(&self.workspace_dir, &meta.id, &reason).await;
+ let _ =
+ fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await;
tracing::warn!(
target: "presentation",
err = %err,
@@ -428,7 +435,7 @@ impl PresentationTool {
async fn resolve_one_image(&self, image: &SlideImage) -> Result<ResolvedSlideImage, String> {
let bytes = match &image.source {
SlideImageSource::Artifact { artifact_id } => {
- read_artifact_bytes(&self.workspace_dir, artifact_id)
+ read_artifact_bytes(&self.workspace_dir, &self.files_dir, artifact_id)
.await
.map_err(|e| format!("artifact {artifact_id} unreadable: {e}"))?
}