Skip to content
7 changes: 4 additions & 3 deletions crates/openhuman-core/src/attachments/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,9 +202,10 @@ pub(crate) async fn thread_action_dir(
let Some(thread_id) = thread_id.filter(|id| !id.is_empty()) else {
return Ok(config.action_dir.clone());
};
let bound = crate::threads::ops::thread_working_dir(ctx, threads_dir.to_path_buf(), thread_id)
.await
.map_err(anyhow::Error::msg)?;
let bound =
crate::threads::ops::thread_working_dir(ctx, config, threads_dir.to_path_buf(), thread_id)
.await
.map_err(anyhow::Error::msg)?;
Ok(bound.unwrap_or_else(|| config.action_dir.clone()))
}

Expand Down
84 changes: 66 additions & 18 deletions crates/openhuman-core/src/config/ops/agent_paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,10 +200,9 @@ fn agent_paths_payload(config: &Config) -> serde_json::Value {
}

/// Validate a user-chosen files folder (#5505) and create it. Fail-closed:
/// the path must be absolute, not an existing file, not a protected location
/// (credential stores, OS directories), and not inside the OpenHuman data
/// directory — the point of the folder is that the user can see it, and the
/// data dir holds internal state.
/// the path must be absolute, not an existing file, and pass
/// [`refuse_protected_folder`] — the point of the folder is that the user can
/// see it, and the data dir holds internal state.
async fn validate_files_dir(raw: &str, config: &Config) -> Result<PathBuf, String> {
let expanded = expand_tilde(raw);
let candidate = PathBuf::from(&expanded);
Expand All @@ -217,24 +216,69 @@ async fn validate_files_dir(raw: &str, config: &Config) -> Result<PathBuf, Strin
"files_dir must be a folder, not a file: {expanded}"
));
}
if crate::security::SecurityPolicy::is_always_forbidden_async(&candidate).await {
refuse_protected_folder("files_dir", &candidate, &expanded, config).await?;
tokio::fs::create_dir_all(&candidate)
.await
.map_err(|e| format!("failed to create files_dir {expanded}: {e}"))?;
Ok(candidate)
}

/// Refuse a user-chosen agent folder (`kind` is `files_dir` or `action_dir`)
/// that is a protected location (credential stores, OS directories) or fails
/// [`refuse_data_folder`]. TinySecurity's floor is lexical, so it
/// is asked about the path as given and about its resolved form: a symlink
/// into `~/.ssh` is refused like `~/.ssh` itself.
async fn refuse_protected_folder(
kind: &str,
candidate: &Path,
expanded: &str,
config: &Config,
) -> Result<(), String> {
let resolved = canonical_prefix(candidate);
if crate::security::SecurityPolicy::is_always_forbidden_async(candidate).await
|| crate::security::SecurityPolicy::is_always_forbidden_async(&resolved).await
{
log::debug!("[config][agent_paths] {kind} refused: protected location");
return Err(format!(
"files_dir cannot be a protected system or credential folder: {expanded}"
"{kind} cannot be a protected system or credential folder: {expanded}"
));
}
let mut internal = vec![config.workspace_dir.clone()];
if let Ok(root) = crate::config::default_root_openhuman_dir() {
internal.push(root);
}
if internal.iter().any(|dir| path_within(&candidate, dir)) {
refuse_data_folder(kind, candidate, expanded, config)
}

/// Refuse an agent folder that sits inside OpenHuman's state (the workspace
/// or the data root) or contains it (also the folder holding this config,
/// whose credential files sit next to it). Fails closed when the data root
/// can't be resolved.
pub(crate) fn refuse_data_folder(
kind: &str,
candidate: &Path,
expanded: &str,
config: &Config,
) -> Result<(), String> {
let root = crate::config::default_root_openhuman_dir().map_err(|e| {
format!("{kind} can't be checked: the OpenHuman data folder is unknown: {e}")
})?;
let state = [config.workspace_dir.clone(), root];
let config_dir = config
.config_path
.parent()
.filter(|dir| !dir.as_os_str().is_empty());
let inside = state.iter().any(|dir| path_within(candidate, dir));
let contains = state
.iter()
.map(PathBuf::as_path)
.chain(config_dir)
.any(|dir| path_within(dir, candidate));
if inside || contains {
log::debug!(
"[config][agent_paths] {kind} refused: inside={inside} contains={contains} the data folder"
);
return Err(format!(
"files_dir must not be inside the OpenHuman data folder: {expanded}"
"{kind} must not be inside or contain the OpenHuman data folder: {expanded}"
));
}
tokio::fs::create_dir_all(&candidate)
.await
.map_err(|e| format!("failed to create files_dir {expanded}: {e}"))?;
Ok(candidate)
Ok(())
}

/// `path` equals or sits under `dir`, comparing canonical forms so a
Expand Down Expand Up @@ -265,9 +309,11 @@ pub(crate) fn canonical_prefix(path: &Path) -> PathBuf {
/// Applies an edit to the agent's `action_dir` sandbox root.
///
/// Validation (fail-closed): the path is trimmed and `~`-expanded; it must be
/// **absolute**; it must not be an existing *file*; and it must not equal
/// **absolute**; it must not be an existing *file*; it must not equal
/// `workspace_dir` (which holds memory DBs / tokens and must never become the
/// agent-writable root). A missing directory is auto-created (mirroring the
/// agent-writable root); and it must pass [`refuse_protected_folder`] (no
/// credential store or OS directory, even through a symlink, and nothing inside
/// the OpenHuman data folder). A missing directory is auto-created (mirroring the
/// startup auto-create in `channels/runtime/startup.rs`). An empty input clears
/// the override and reverts `action_dir` to the default.
///
Expand Down Expand Up @@ -317,6 +363,8 @@ pub async fn apply_agent_paths_settings(
);
}

refuse_protected_folder("action_dir", &candidate, &expanded, config).await?;
Comment thread
M3gA-Mind marked this conversation as resolved.
Resolved

if !candidate.exists() {
tokio::fs::create_dir_all(&candidate)
.await
Expand Down
1 change: 1 addition & 0 deletions crates/openhuman-core/src/config/ops/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ pub use agent::{
get_autonomy_settings, load_and_apply_agent_settings, load_and_apply_autonomy_settings,
AgentSettingsPatch, AutonomySettingsPatch,
};
pub(crate) use agent_paths::refuse_data_folder;
pub use agent_paths::{
apply_agent_paths_settings, ensure_agent_dirs, ensure_usable_cwd, expand_tilde,
get_agent_paths, load_and_apply_agent_paths_settings, redact_home, AgentPathsPatch,
Expand Down
95 changes: 95 additions & 0 deletions crates/openhuman-core/src/config/ops_agent_paths_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,101 @@ async fn apply_agent_paths_env_set_reports_source_env() {
}
}

/// The action_dir edit, expected to be refused without storing an override.
async fn action_dir_rejected(cfg: &mut Config, value: &std::path::Path) -> String {
let err = apply_agent_paths_settings(
cfg,
AgentPathsPatch {
action_dir: Some(value.to_string_lossy().to_string()),
files_dir: None,
},
)
.await
.expect_err("action_dir must be rejected");
assert!(
cfg.action_dir_override.is_none(),
"a rejected value is not stored"
);
err
}

/// TS-E2E-021: the agent's working folder becomes its read-write root, so a
/// credential store, an OS directory or a symlink to one must be refused.
#[tokio::test]
async fn apply_agent_paths_rejects_a_protected_action_dir() {
let _g = ENV_LOCK.lock().await;
unsafe {
std::env::remove_var("OPENHUMAN_ACTION_DIR");
}
let tmp = tempdir().unwrap();
let mut cfg = tmp_config(&tmp);
let ssh = tmp.path().join(".ssh");
std::fs::create_dir_all(&ssh).unwrap();

let err = action_dir_rejected(&mut cfg, &ssh).await;
assert!(err.contains("protected"), "{err}");
#[cfg(unix)]
{
let err = action_dir_rejected(&mut cfg, std::path::Path::new("/etc")).await;
assert!(err.contains("protected"), "{err}");
let link = tmp.path().join("projects-link");
std::os::unix::fs::symlink(&ssh, &link).unwrap();
let err = action_dir_rejected(&mut cfg, &link).await;
assert!(err.contains("protected"), "{err}");
}
}

/// TS-E2E-021: a folder inside the OpenHuman data folder holds internal state
/// and must not become the agent's working folder.
#[tokio::test]
async fn apply_agent_paths_rejects_an_action_dir_inside_the_data_folder() {
let _g = ENV_LOCK.lock().await;
unsafe {
std::env::remove_var("OPENHUMAN_ACTION_DIR");
}
let tmp = tempdir().unwrap();
let mut cfg = tmp_config(&tmp);
let inside = cfg.workspace_dir.join("vault");

let err = action_dir_rejected(&mut cfg, &inside).await;
assert!(err.contains("OpenHuman data folder"), "{err}");
assert!(!inside.exists(), "nothing is created for a rejected value");
}

/// An `OPENHUMAN_WORKSPACE` profile keeps `config.toml` and its credential
/// files beside the workspace, so the profile folder itself (or any folder
/// above it) must not become the agent's working folder. A sibling folder in
/// the profile reaches none of that state and stays allowed.
#[tokio::test]
async fn apply_agent_paths_rejects_an_action_dir_that_contains_the_profile() {
let _g = ENV_LOCK.lock().await;
unsafe {
std::env::remove_var("OPENHUMAN_ACTION_DIR");
}
let tmp = tempdir().unwrap();
let profile = tmp.path().join("profile");
let mut cfg = Config::default();
cfg.workspace_dir = profile.join("workspace");
cfg.config_path = profile.join("config.toml");
std::fs::create_dir_all(&cfg.workspace_dir).unwrap();

for root in [profile.as_path(), tmp.path()] {
let err = action_dir_rejected(&mut cfg, root).await;
assert!(err.contains("OpenHuman data folder"), "{err}");
}
let beside = profile.join("projects");
apply_agent_paths_settings(
&mut cfg,
AgentPathsPatch {
action_dir: Some(beside.to_string_lossy().to_string()),
files_dir: None,
},
)
.await
.expect("a folder beside the profile's state is allowed");
assert_eq!(cfg.action_dir_override.as_deref(), Some(beside.as_path()));
}

// --- #3353 regression tests -------------------------------------------------

#[test]
Expand Down
16 changes: 16 additions & 0 deletions crates/openhuman-core/src/config/ops_files_dir_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,22 @@ async fn a_symlinked_route_into_the_data_folder_is_rejected() {
assert!(err.contains("OpenHuman data folder"), "{err}");
}

/// TS-E2E-016: a symlink into a credential store is the credential store; the
/// floor is asked about the resolved path, not only the spelling.
#[cfg(unix)]
#[tokio::test]
async fn a_symlink_into_a_credential_folder_is_rejected() {
let tmp = tempdir().unwrap();
let mut cfg = tmp_config(&tmp);
let ssh = tmp.path().join(".ssh");
std::fs::create_dir_all(&ssh).unwrap();
let link = tmp.path().join("Documents-link");
std::os::unix::fs::symlink(&ssh, &link).unwrap();

let err = rejected(&mut cfg, &link.to_string_lossy()).await;
assert!(err.contains("protected"), "{err}");
}

/// Changing the folder affects new files only: a file made in the previous
/// folder keeps resolving, because that folder is recorded as trusted.
#[tokio::test]
Expand Down
12 changes: 10 additions & 2 deletions crates/openhuman-core/src/threads/ops/crud.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,16 @@ pub async fn thread_create_new(
request: CreateConversationThreadRequest,
) -> Result<Outcome<ApiEnvelope<ConversationThreadSummary>>, String> {
let dir = workspace_dir().await?;
let working_dir =
super::working_dir::validate_working_dir(request.action_dir.as_deref()).await?;
let config = ctx
.load_config()
.await
.map_err(|e| format!("load config: {e}"))?;
let working_dir = super::working_dir::validate_working_dir_for_store(
request.action_dir.as_deref(),
&config,
&dir,
)
.await?;
let id = format!("thread-{}", uuid::Uuid::new_v4());
let now = chrono::Local::now();
let title = format!("Chat {} {}", now.format("%b %-d"), now.format("%-I:%M %p"));
Expand Down
46 changes: 41 additions & 5 deletions crates/openhuman-core/src/threads/ops/working_dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
//! in another.

use super::support::{counts, envelope, thread_to_summary, workspace_dir};
use crate::config::Config;
use crate::core::runtime::DispatchCtx;
use crate::core::Outcome;
use crate::security::SecurityPolicy;
Expand All @@ -23,8 +24,12 @@ use std::path::{Path, PathBuf};
///
/// The folder must be an existing absolute directory outside the paths the
/// security policy never opens (credential stores, system roots), the same
/// floor that holds with the autonomy policy disabled.
pub(crate) async fn validate_working_dir(raw: Option<&str>) -> Result<Option<String>, String> {
/// floor that holds with the autonomy policy disabled. Like the global
/// `action_dir`, it must neither sit inside nor contain OpenHuman's own state.
pub(crate) async fn validate_working_dir(
raw: Option<&str>,
config: &Config,
) -> Result<Option<String>, String> {
let Some(raw) = raw.map(str::trim).filter(|raw| !raw.is_empty()) else {
return Ok(None);
};
Expand All @@ -44,19 +49,45 @@ pub(crate) async fn validate_working_dir(raw: Option<&str>) -> Result<Option<Str
if SecurityPolicy::is_always_forbidden_async(&canonical).await {
return Err("working folder is in a protected location".to_string());
}
crate::config::ops::refuse_data_folder("working folder", &canonical, raw, config)?;
Ok(Some(canonical.to_string_lossy().into_owned()))
}

/// [`validate_working_dir`], also refusing the workspace the thread store
/// uses. In single-user mode the store's `workspace_dir()` (the disk config)
/// can differ from the dispatch context's config.
pub(crate) async fn validate_working_dir_for_store(
raw: Option<&str>,
config: &Config,
store: &Path,
) -> Result<Option<String>, String> {
let validated = validate_working_dir(raw, config).await?;
if let Some(dir) = &validated {
if store != config.workspace_dir {
let mut store_config = config.clone();
store_config.workspace_dir = store.to_path_buf();
crate::config::ops::refuse_data_folder(
"working folder",
Path::new(dir),
dir,
&store_config,
)?;
}
}
Ok(validated)
}

/// The working folder bound to `thread_id`, if the thread exists and has one.
///
/// An unusable bound folder is an error, rather than a reason to run in the
/// global folder. This preserves the conversation's filesystem boundary.
pub(crate) async fn thread_working_dir(
ctx: &DispatchCtx,
config: &Config,
workspace_dir: PathBuf,
thread_id: &str,
) -> Result<Option<PathBuf>, String> {
let threads = conversations::blocking::list_threads(ctx.clone(), workspace_dir)
let threads = conversations::blocking::list_threads(ctx.clone(), workspace_dir.clone())
.await
.map_err(|err| format!("failed to load thread working folder: {err}"))?;
let bound = threads
Expand All @@ -66,7 +97,7 @@ pub(crate) async fn thread_working_dir(
let Some(bound) = bound else {
return Ok(None);
};
match validate_working_dir(Some(&bound)).await {
match validate_working_dir_for_store(Some(&bound), config, &workspace_dir).await {
Ok(Some(dir)) => Ok(Some(PathBuf::from(dir))),
Ok(None) => Ok(None),
Err(err) => Err(format!("thread working folder is unusable: {err}")),
Expand All @@ -79,7 +110,12 @@ pub async fn thread_update_working_dir(
request: UpdateConversationThreadWorkingDirRequest,
) -> Result<Outcome<ApiEnvelope<ConversationThreadSummary>>, ThreadsError> {
let dir = workspace_dir().await?;
let working_dir = validate_working_dir(Some(&request.action_dir)).await?;
let config = ctx
.load_config()
.await
.map_err(|e| format!("load config: {e}"))?;
let working_dir =
validate_working_dir_for_store(Some(&request.action_dir), &config, &dir).await?;
let Some(thread) = conversations::blocking::list_threads(ctx.clone(), dir.clone())
.await?
.into_iter()
Expand Down
Loading
Loading