Skip to content
Merged
37 changes: 26 additions & 11 deletions crates/openhuman-core/src/config/ops/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ pub async fn apply_autonomy_settings(
) -> Result<Outcome<serde_json::Value>, String> {
use crate::security::AutonomyLevel;

#[cfg(feature = "security-module")]
let before = config.autonomy.clone();
// Validate before changing anything, so a rejected patch leaves `config` as it was.
if let Some(root) = update
.trusted_roots
Expand All @@ -83,11 +85,9 @@ pub async fn apply_autonomy_settings(
root.path
));
}
if let Some(enabled) = update.enabled {
config.autonomy.enabled = enabled;
}
if let Some(level) = update.level {
config.autonomy.level = match level.trim().to_ascii_lowercase().as_str() {
let level = match update.level.map(|level| level.trim().to_ascii_lowercase()) {
None => None,
Some(level) => Some(match level.as_str() {
"readonly" | "read_only" | "read-only" => AutonomyLevel::ReadOnly,
"supervised" => AutonomyLevel::Supervised,
"full" => AutonomyLevel::Full,
Expand All @@ -96,7 +96,16 @@ pub async fn apply_autonomy_settings(
"invalid autonomy level '{other}' (expected readonly | supervised | full)"
));
}
};
}),
};
if update.max_actions_per_hour == Some(0) {
return Err("max_actions_per_hour must be at least 1 (got 0)".to_string());
}
if let Some(enabled) = update.enabled {
config.autonomy.enabled = enabled;
}
if let Some(level) = level {
config.autonomy.level = level;
}
if let Some(workspace_only) = update.workspace_only {
config.autonomy.workspace_only = workspace_only;
Expand All @@ -114,11 +123,6 @@ pub async fn apply_autonomy_settings(
config.autonomy.allow_tool_install = allow_tool_install;
}
if let Some(max_actions_per_hour) = update.max_actions_per_hour {
if max_actions_per_hour == 0 {
return Err(format!(
"max_actions_per_hour must be at least 1 (got {max_actions_per_hour})"
));
}
config.autonomy.max_actions_per_hour = max_actions_per_hour;
}
if let Some(auto_approve) = update.auto_approve {
Expand All @@ -127,6 +131,17 @@ pub async fn apply_autonomy_settings(
if let Some(auto_approve_all) = update.auto_approve_all {
config.autonomy.auto_approve_all = auto_approve_all;
}
// The host's TinySecurity client refuses an enabled policy the module
// contract cannot represent (relative forbidden paths, commands with
// arguments): `validate` runs before every call. Saved, such a policy would
// make every TinySecurity check fail closed until the file was edited by
// hand, so refuse it here and leave the settings as they were.
#[cfg(feature = "security-module")]
if let Err(error) = crate::modules::security::validate_policy(config) {
Comment thread
M3gA-Mind marked this conversation as resolved.
Resolved
log::debug!("[config][autonomy] patch rejected: {error}");
config.autonomy = before;
return Err(format!("autonomy settings not saved: {error}"));
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

config.save().await.map_err(super::config_save_error)?;

Expand Down
91 changes: 91 additions & 0 deletions crates/openhuman-core/src/config/ops_voice_and_autonomy_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,97 @@ async fn apply_autonomy_settings_rejects_zero() {
);
}

/// #8575: a bad level or a zero action budget is refused before any field of
/// the patch is applied, so a caller that keeps the `Config` can't save half
/// of a rejected patch.
#[tokio::test]
async fn apply_autonomy_settings_rejects_level_or_budget_before_changing_anything() {
let _g = ENV_LOCK.lock().await;
let tmp = tempdir().unwrap();
let mut cfg = tmp_config(&tmp);
let prior = toml::to_string(&cfg.autonomy).unwrap();
for (patch, expected) in [
(
AutonomySettingsPatch {
enabled: Some(true),
allowed_commands: Some(vec!["git".into()]),
max_actions_per_hour: Some(0),
..Default::default()
},
"max_actions_per_hour must be at least 1",
),
(
AutonomySettingsPatch {
enabled: Some(true),
allowed_commands: Some(vec!["git".into()]),
level: Some("sometimes".into()),
..Default::default()
},
"invalid autonomy level",
),
] {
let err = apply_autonomy_settings(&mut cfg, patch).await.unwrap_err();
assert!(err.contains(expected), "expected {expected:?}, got: {err}");
assert_eq!(
toml::to_string(&cfg.autonomy).unwrap(),
prior,
"a rejected patch leaves the settings as they were"
);
assert!(!cfg.config_path.exists(), "a rejected patch is not saved");
}
}

/// TS-E2E-015: an enabled policy TinySecurity cannot represent is refused at
/// save time, the file is not written and the settings stay as they were.
#[cfg(feature = "security-module")]
#[tokio::test]
async fn apply_autonomy_settings_rejects_a_policy_tinysecurity_cannot_represent() {
let _g = ENV_LOCK.lock().await;
let tmp = tempdir().unwrap();
let mut cfg = tmp_config(&tmp);
let prior = cfg.autonomy.clone();
for (patch, expected) in [
(
AutonomySettingsPatch {
enabled: Some(true),
forbidden_paths: Some(vec!["relative/forbidden".into()]),
..Default::default()
},
"forbidden paths must be absolute",
),
(
AutonomySettingsPatch {
enabled: Some(true),
allowed_commands: Some(vec!["git status".into()]),
..Default::default()
},
"argument-free command names",
),
] {
let err = apply_autonomy_settings(&mut cfg, patch).await.unwrap_err();
assert!(err.contains(expected), "expected {expected:?}, got: {err}");
assert_eq!(
toml::to_string(&cfg.autonomy).unwrap(),
toml::to_string(&prior).unwrap(),
"a rejected patch leaves the settings as they were"
);
assert!(!cfg.config_path.exists(), "a rejected patch is not saved");
}

apply_autonomy_settings(
&mut cfg,
AutonomySettingsPatch {
enabled: Some(true),
forbidden_paths: Some(vec![tmp.path().join("private").display().to_string()]),
allowed_commands: Some(vec!["git".into()]),
..Default::default()
},
)
.await
.expect("a representable enabled policy is saved");
assert!(cfg.autonomy.enabled);
}

#[tokio::test]
async fn apply_autonomy_settings_accepts_unlimited_sentinel() {
let _g = ENV_LOCK.lock().await;
Expand Down
1 change: 1 addition & 0 deletions crates/openhuman-core/src/modules/security/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ mod tests;
pub(crate) use client::SecurityProxy;
pub use client::{Client, SecurityError};
pub use policy::policy_config;
pub(crate) use policy::validate as validate_policy;
pub(super) use policy::{module_config, module_config_for_host, module_config_for_secret_scope};
pub(crate) use secret_cipher::Output as SecretCipherOutput;

Expand Down
26 changes: 20 additions & 6 deletions crates/openhuman-core/src/modules/security/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,32 @@ pub fn policy_config(config: &Config) -> tinysecurity_bus::PolicyConfig {
Vec::new()
},
forbidden_paths: if config.autonomy.enabled {
config
.autonomy
.forbidden_paths
.iter()
.map(|path| crate::config::expand_tilde(path))
.collect()
forbidden_paths(&config.autonomy.forbidden_paths, cfg!(windows))
Comment thread
M3gA-Mind marked this conversation as resolved.
Resolved
} else {
Vec::new()
},
}
}

/// The forbidden paths as the module receives them, `~` expanded. On Windows
/// a path rooted without a drive (`/etc`, `\usr`, the Unix roots in the
/// shipped defaults) is not absolute and names no system folder; the module
/// already ignores such entries there, and `validate` would otherwise refuse
/// the whole policy for them, so they are left out. Relative entries are
/// kept, so `validate` still refuses them.
fn forbidden_paths(paths: &[String], windows: bool) -> Vec<String> {
paths
.iter()
.filter(|path| !(windows && is_drive_less_root(path)))
.map(|path| crate::config::expand_tilde(path))
.collect()
}

/// `/x` or `\x`, but not a UNC path (`\\server`, `//server`).
fn is_drive_less_root(path: &str) -> bool {
path.starts_with(['/', '\\']) && !path.starts_with("\\\\") && !path.starts_with("//")
}

/// Reject enabled host policy that the published module contract cannot
/// represent. Disabled policy settings are inert and serialize empty above.
pub fn validate(config: &Config) -> Result<(), &'static str> {
Expand Down
48 changes: 46 additions & 2 deletions crates/openhuman-core/src/modules/security/policy_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,47 @@ fn enabled_policy_expands_home_relative_forbidden_paths() {
.all(|path| std::path::Path::new(path).is_absolute()));
}

/// TS-E2E-015 / #8575: the shipped defaults include Unix roots (`/etc`, …),
/// which have no drive on Windows. Enabling autonomy with the defaults must
/// still give the module a policy it accepts there.
#[test]
fn windows_policy_leaves_out_drive_less_unix_roots() {
let defaults = Config::default().autonomy.forbidden_paths;
assert!(defaults.iter().any(|path| path == "/etc"), "{defaults:?}");

// Every default is a Unix root or a `~` path; on Windows only the `~`
// paths remain (checked on the input: `~` expands to `/home/...` here).
let home: Vec<String> = defaults
.iter()
.filter(|path| path.starts_with('~'))
.map(|path| crate::config::expand_tilde(path))
.collect();
assert!(home.contains(&crate::config::expand_tilde("~/.ssh")));
assert_eq!(forbidden_paths(&defaults, true), home);
assert_eq!(forbidden_paths(&defaults, false).len(), defaults.len());

let kept = [
"C:\\Secrets",
"\\\\server\\share",
"//server/share",
"relative",
];
let kept: Vec<String> = kept.iter().map(|path| path.to_string()).collect();
assert_eq!(forbidden_paths(&kept, true), kept);
}

/// The untouched defaults, enabled, validate on this OS.
#[test]
fn enabled_default_policy_validates() {
let root = tempfile::tempdir().unwrap();
let mut config = Config::default();
config.action_dir = root.path().join("action");
config.workspace_dir = root.path().join("workspace");
config.autonomy.enabled = true;

assert_eq!(validate(&config), Ok(()));
}

#[test]
fn enabled_policy_still_refuses_relative_forbidden_paths() {
let mut config = Config::default();
Expand All @@ -40,10 +81,13 @@ fn enabled_policy_still_refuses_relative_forbidden_paths() {

#[test]
fn policy_translation_copies_effective_host_settings() {
// Absolute on every OS: a drive-less `/private` is left out on Windows.
let root = tempfile::tempdir().unwrap();
let private = root.path().join("private").display().to_string();
let mut config = Config::default();
config.autonomy.enabled = true;
config.autonomy.allowed_commands = vec!["pwd".into()];
config.autonomy.forbidden_paths = vec!["/private".into()];
config.autonomy.forbidden_paths = vec![private.clone()];

let translated = policy_config(&config);
assert!(translated.enabled);
Expand All @@ -56,7 +100,7 @@ fn policy_translation_copies_effective_host_settings() {
config.workspace_dir.display().to_string()
);
assert_eq!(translated.allowed_commands, ["pwd"]);
assert_eq!(translated.forbidden_paths, ["/private"]);
assert_eq!(translated.forbidden_paths, [private]);
}

#[test]
Expand Down
Loading