Skip to content

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

fix: unblock full product Rust tests

Steven Enamakelc8209c4aa295
diff --git a/crates/openhuman-core/src/inference/provider/factory/credentials.rs b/crates/openhuman-core/src/inference/provider/factory/credentials.rs
index 6f9e91b687..1b252cc682 100644
--- a/crates/openhuman-core/src/inference/provider/factory/credentials.rs
+++ b/crates/openhuman-core/src/inference/provider/factory/credentials.rs
@@ -166,7 +166,10 @@ pub fn redact_endpoint(url: &str) -> String {
if let Some(rest) = trimmed.split_once("://") {
let scheme = rest.0;
let authority = rest.1.split('/').next().unwrap_or("");
- let host = authority.split('@').next_back().unwrap_or(authority);
+ if authority.contains('@') {
+ return "<redacted>".to_string();
+ }
+ let host = authority;
let host_no_query = host.split('?').next().unwrap_or(host);
return format!("{}://{}", scheme, host_no_query);
}
diff --git a/crates/openhuman-core/src/security/secret_storage/adapter.rs b/crates/openhuman-core/src/security/secret_storage/adapter.rs
index 97ac9fb817..24588184c4 100644
--- a/crates/openhuman-core/src/security/secret_storage/adapter.rs
+++ b/crates/openhuman-core/src/security/secret_storage/adapter.rs
@@ -45,9 +45,9 @@ pub(super) fn utf8(
/// never sign in again. Today's behaviour is kept instead: quarantine the
/// bytes (`secrets.enc.corrupt.<ts>`, never deleted) and log loudly.
///
-/// Under the same cross-process lock writers take, the file is probed again
-/// first: a concurrent writer may already have replaced it, and quarantining
-/// that replacement would destroy good secrets.
+/// The driver's probe takes the cross-process lock used by writers. A
+/// fingerprint before that probe is compared again under OpenHuman's lock
+/// before quarantine, so a concurrent writer's replacement stays untouched.
///
/// # Errors
///
@@ -58,7 +58,16 @@ pub(super) fn recover_corrupt_file(
key: &[u8; 32],
cause: &StorageError,
) -> Result<(), SecretStorageError> {
- let _guard = file_store::lock_for_write(path)?;
+ recover_corrupt_file_after_probe(path, key, cause, || {})
+}
+
+fn recover_corrupt_file_after_probe(
+ path: &Path,
+ key: &[u8; 32],
+ cause: &StorageError,
+ after_probe: impl FnOnce(),
+) -> Result<(), SecretStorageError> {
+ let before_probe = file_store::fingerprint(path)?;
let store = EncryptedFileSecrets::at_path(path, Zeroizing::new(*key));
match crate::storage::block_on(async move { store.list("").await }) {
Ok(_) => {
@@ -71,6 +80,16 @@ pub(super) fn recover_corrupt_file(
// about the file's contents: never move a possibly healthy file aside.
Err(error) => return Err(backend_error(error)),
}
+ after_probe();
+
+ // The driver holds this same sidecar lock while probing. Acquire
+ // OpenHuman's guard only after its probe returns, then ensure a concurrent
+ // writer did not replace the corrupt bytes with a healthy store.
+ let _guard = file_store::lock_for_write(path)?;
+ if file_store::fingerprint(path)? != before_probe {
+ log::info!("[keyring:encrypted_file] secrets file changed after the failed probe; not quarantining");
+ return Ok(());
+ }
log::error!(
"[keyring:encrypted_file] secrets file unreadable ({}): master key may have changed \
or the file is corrupt",
diff --git a/crates/openhuman-core/src/security/secret_storage/adapter_tests.rs b/crates/openhuman-core/src/security/secret_storage/adapter_tests.rs
index 5875d9ac8d..2428946cc9 100644
--- a/crates/openhuman-core/src/security/secret_storage/adapter_tests.rs
+++ b/crates/openhuman-core/src/security/secret_storage/adapter_tests.rs
@@ -7,9 +7,29 @@ use tinystoragedrivers::secrets::crypto;
const KEY: [u8; 32] = [7; 32];
+fn secrets_tempdir() -> tempfile::TempDir {
+ #[cfg(target_os = "macos")]
+ {
+ tempfile::tempdir_in("/private/tmp").expect("canonical macOS temp directory")
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ tempfile::tempdir().expect("tempdir")
+ }
+}
+
+fn write_private_file(path: &std::path::Path, bytes: &[u8]) {
+ std::fs::write(path, bytes).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap();
+ }
+}
+
#[test]
fn file_backend_round_trips_and_deletes() {
- let dir = tempfile::tempdir().unwrap();
+ let dir = secrets_tempdir();
let b = EncryptedFileBackend::new(dir.path());
assert_eq!(b.get_with_key(&KEY, "u:a").unwrap(), None);
b.set_with_key(&KEY, "u:a", "1").unwrap();
@@ -31,7 +51,7 @@ fn quarantined(dir: &std::path::Path) -> Vec<String> {
#[test]
fn a_file_under_another_key_is_quarantined_and_the_store_recovers() {
- let dir = tempfile::tempdir().unwrap();
+ let dir = secrets_tempdir();
let b = EncryptedFileBackend::new(dir.path());
b.set_with_key(&[9; 32], "u:old", "old-value").unwrap();
let original = std::fs::read(dir.path().join("secrets.enc")).unwrap();
@@ -54,12 +74,11 @@ fn a_file_under_another_key_is_quarantined_and_the_store_recovers() {
#[test]
fn a_garbage_file_does_not_wedge_writes() {
- let dir = tempfile::tempdir().unwrap();
- std::fs::write(
- dir.path().join("secrets.enc"),
+ let dir = secrets_tempdir();
+ write_private_file(
+ &dir.path().join("secrets.enc"),
b"definitely not a blob at all, no",
- )
- .unwrap();
+ );
let b = EncryptedFileBackend::new(dir.path());
b.set_with_key(&KEY, "u:a", "1").unwrap();
assert_eq!(b.get_with_key(&KEY, "u:a").unwrap().as_deref(), Some("1"));
@@ -69,9 +88,9 @@ fn a_garbage_file_does_not_wedge_writes() {
#[test]
fn an_undecodable_payload_is_quarantined_too() {
// Decrypts, but is not a json object of strings.
- let dir = tempfile::tempdir().unwrap();
+ let dir = secrets_tempdir();
let blob = crypto::encrypt(&KEY, b"[1,2,3]").unwrap();
- std::fs::write(dir.path().join("secrets.enc"), blob).unwrap();
+ write_private_file(&dir.path().join("secrets.enc"), &blob);
let b = EncryptedFileBackend::new(dir.path());
assert_eq!(b.get_with_key(&KEY, "u:a").unwrap(), None);
assert_eq!(quarantined(dir.path()).len(), 1);
@@ -79,7 +98,7 @@ fn an_undecodable_payload_is_quarantined_too() {
#[test]
fn a_legacy_dev_keychain_is_imported_once() {
- let dir = tempfile::tempdir().unwrap();
+ let dir = secrets_tempdir();
std::fs::write(
dir.path().join("dev-keychain.json"),
br#"{"u:legacy":"from-json"}"#,
@@ -100,7 +119,7 @@ fn recovery_never_quarantines_a_file_that_is_not_confirmed_corrupt() {
// The re-probe fails with an I/O error (the path is a directory), not a
// crypto/serialization one: nothing says the contents are bad, so nothing
// is moved and the error is surfaced.
- let dir = tempfile::tempdir().unwrap();
+ let dir = secrets_tempdir();
let path = dir.path().join("secrets.enc");
std::fs::create_dir(&path).unwrap();
let cause = tinystoragedrivers::StorageError::crypto("earlier failure");
@@ -111,10 +130,30 @@ fn recovery_never_quarantines_a_file_that_is_not_confirmed_corrupt() {
#[test]
fn recovery_leaves_a_file_that_became_readable() {
- let dir = tempfile::tempdir().unwrap();
+ let dir = secrets_tempdir();
let b = EncryptedFileBackend::new(dir.path());
b.set_with_key(&KEY, "u:a", "1").unwrap();
let cause = tinystoragedrivers::StorageError::crypto("stale failure");
recover_corrupt_file(&dir.path().join("secrets.enc"), &KEY, &cause).unwrap();
assert_eq!(b.get_with_key(&KEY, "u:a").unwrap().as_deref(), Some("1"));
}
+
+#[test]
+fn recovery_does_not_quarantine_a_valid_file_replaced_after_the_probe() {
+ let dir = secrets_tempdir();
+ let backend = EncryptedFileBackend::new(dir.path());
+ let path = dir.path().join("secrets.enc");
+ backend.set_with_key(&KEY, "u:a", "1").unwrap();
+ write_private_file(&path, b"corrupt before probe");
+ let valid_map = HashMap::from([("u:a".to_owned(), "1".to_owned())]);
+ let valid_blob = crypto::encrypt(&KEY, &serde_json::to_vec(&valid_map).unwrap()).unwrap();
+ let cause = tinystoragedrivers::StorageError::crypto("stale failure");
+
+ recover_corrupt_file_after_probe(&path, &KEY, &cause, || {
+ write_private_file(&path, &valid_blob);
+ })
+ .unwrap();
+
+ assert_eq!(backend.get_with_key(&KEY, "u:a").unwrap().as_deref(), Some("1"));
+ assert!(quarantined(dir.path()).is_empty());
+}
diff --git a/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_fixture_tests.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_fixture_tests.rs
index 27a16f843f..2ca30a0f1f 100644
--- a/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_fixture_tests.rs
+++ b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_fixture_tests.rs
@@ -15,8 +15,17 @@ const SECRETS_ENC: &[u8] = include_bytes!("fixtures/secrets_enc.bin");
const ENC2_VALUES: &str = include_str!("fixtures/enc2_values.txt");
fn fixture_dir() -> tempfile::TempDir {
+ #[cfg(target_os = "macos")]
+ let dir = tempfile::tempdir_in("/private/tmp").unwrap();
+ #[cfg(not(target_os = "macos"))]
let dir = tempfile::TempDir::new().unwrap();
- std::fs::write(dir.path().join("secrets.enc"), SECRETS_ENC).unwrap();
+ let path = dir.path().join("secrets.enc");
+ std::fs::write(&path, SECRETS_ENC).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap();
+ }
dir
}
diff --git a/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_tests.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_tests.rs
index ca80197250..c1af887e97 100644
--- a/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_tests.rs
+++ b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_tests.rs
@@ -1,6 +1,17 @@
use super::*;
use std::collections::HashMap;
+fn secrets_tempdir() -> tempfile::TempDir {
+ #[cfg(target_os = "macos")]
+ {
+ tempfile::tempdir_in("/private/tmp").expect("canonical macOS temp directory")
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ tempfile::tempdir().expect("tempdir")
+ }
+}
+
fn legacy_secret_map() -> HashMap<String, String> {
HashMap::from([("user:token".to_string(), "secret-value".to_string())])
}
@@ -15,7 +26,7 @@ fn write_secret(backend: &EncryptedFileBackend, key: &[u8; KEY_LEN], value: &str
#[test]
fn legacy_plaintext_is_removed_only_after_verified_encrypted_migration() {
- let dir = tempfile::tempdir().unwrap();
+ let dir = secrets_tempdir();
let legacy_path = dir.path().join(LEGACY_DEV_KEYCHAIN);
let expected = legacy_secret_map();
std::fs::write(&legacy_path, serde_json::to_vec(&expected).unwrap()).unwrap();
@@ -32,7 +43,7 @@ fn legacy_plaintext_is_removed_only_after_verified_encrypted_migration() {
#[test]
fn invalid_legacy_plaintext_is_preserved_for_recovery() {
- let dir = tempfile::tempdir().unwrap();
+ let dir = secrets_tempdir();
let legacy_path = dir.path().join(LEGACY_DEV_KEYCHAIN);
std::fs::write(&legacy_path, b"invalid JSON").unwrap();
@@ -46,7 +57,7 @@ fn invalid_legacy_plaintext_is_preserved_for_recovery() {
#[test]
fn encrypted_store_removes_only_matching_legacy_plaintext() {
- let dir = tempfile::tempdir().unwrap();
+ let dir = secrets_tempdir();
let backend = EncryptedFileBackend::new(dir.path());
let key = [0x42; KEY_LEN];
let encrypted = legacy_secret_map();
@@ -66,7 +77,7 @@ fn encrypted_store_removes_only_matching_legacy_plaintext() {
#[test]
fn encrypted_store_remains_readable_when_verified_plaintext_cannot_be_deleted() {
- let dir = tempfile::tempdir().unwrap();
+ let dir = secrets_tempdir();
let backend = EncryptedFileBackend::new(dir.path());
let key = [0x42; KEY_LEN];
let legacy_path = dir.path().join(LEGACY_DEV_KEYCHAIN);
@@ -82,7 +93,7 @@ fn encrypted_store_remains_readable_when_verified_plaintext_cannot_be_deleted()
#[test]
fn existing_encrypted_file_does_not_remove_plaintext_until_directory_sync_succeeds() {
- let dir = tempfile::tempdir().unwrap();
+ let dir = secrets_tempdir();
let backend = EncryptedFileBackend::new(dir.path());
let key = [0x42; KEY_LEN];
let expected = legacy_secret_map();
@@ -111,7 +122,7 @@ fn existing_encrypted_file_does_not_remove_plaintext_until_directory_sync_succee
#[test]
fn older_plaintext_copy_is_removed_only_when_it_matches() {
- let dir = tempfile::tempdir().unwrap();
+ let dir = secrets_tempdir();
let backend = EncryptedFileBackend::new(dir.path());
let key = [0x42; KEY_LEN];
let encrypted = legacy_secret_map();
@@ -415,8 +426,8 @@ fn try_load_master_key_reports_a_configured_source_error_as_configured() {
#[test]
fn a_secret_written_under_a_configured_key_reads_back_after_a_restart() {
- let workspace = tempfile::TempDir::new().unwrap();
- let key_dir = tempfile::TempDir::new().unwrap();
+ let workspace = secrets_tempdir();
+ let key_dir = secrets_tempdir();
let key_path = key_dir.path().join("master.key");
std::fs::write(&key_path, format!("{}\n", hex_key(0x88))).unwrap();
#[cfg(unix)]
diff --git a/crates/openhuman-core/src/security/secret_storage/file_store.rs b/crates/openhuman-core/src/security/secret_storage/file_store.rs
index 0f111040bc..a067257da8 100644
--- a/crates/openhuman-core/src/security/secret_storage/file_store.rs
+++ b/crates/openhuman-core/src/security/secret_storage/file_store.rs
@@ -26,11 +26,12 @@
//! the other.
use std::fs::{File, OpenOptions};
-use std::io::Write;
+use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use fs2::FileExt;
+use sha2::{Digest, Sha256};
use crate::security::secret_storage::error::SecretStorageError;
@@ -76,11 +77,14 @@ pub fn lock_for_write(path: &Path) -> Result<WriteLock, SecretStorageError> {
))
})?;
}
- let file = OpenOptions::new()
- .create(true)
- .read(true)
- .write(true)
- .truncate(false)
+ let mut options = OpenOptions::new();
+ options.create(true).read(true).write(true).truncate(false);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
+ }
+ let file = options
.open(&lock_path)
.map_err(|e| {
SecretStorageError::Backend(format!(
@@ -88,6 +92,34 @@ pub fn lock_for_write(path: &Path) -> Result<WriteLock, SecretStorageError> {
lock_path.display()
))
})?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::{MetadataExt, PermissionsExt};
+ let metadata = file.metadata().map_err(|error| {
+ SecretStorageError::Backend(format!(
+ "could not inspect the keyring lock at {}: {error}",
+ lock_path.display()
+ ))
+ })?;
+ // A lock owned by another user is not authority over this store. Old
+ // OpenHuman lock files may have inherited wider modes, so tighten an
+ // owned regular file before the stricter TinyDrivers sidecar opens it.
+ if !metadata.is_file() || metadata.uid() != unsafe { libc::geteuid() } {
+ return Err(SecretStorageError::Backend(format!(
+ "keyring lock at {} is not a regular file owned by this user",
+ lock_path.display()
+ )));
+ }
+ if metadata.permissions().mode() & 0o777 != 0o600 {
+ file.set_permissions(std::fs::Permissions::from_mode(0o600))
+ .map_err(|error| {
+ SecretStorageError::Backend(format!(
+ "could not restrict permissions on the keyring lock at {}: {error}",
+ lock_path.display()
+ ))
+ })?;
+ }
+ }
file.lock_exclusive().map_err(|e| {
SecretStorageError::Backend(format!(
"could not lock the keyring at {}: {e}",
@@ -104,6 +136,51 @@ pub fn lock_path_for(path: &Path) -> PathBuf {
path.with_file_name(name)
}
+/// Fingerprint the current regular file without retaining its contents.
+///
+/// Callers use this around a separately locked read to detect whether another
+/// writer replaced the file before they acquire [`lock_for_write`].
+pub fn fingerprint(path: &Path) -> Result<Option<[u8; 32]>, SecretStorageError> {
+ let metadata = match std::fs::symlink_metadata(path) {
+ Ok(metadata) => metadata,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => {
+ return Err(SecretStorageError::Backend(format!(
+ "could not inspect {} for the keyring: {error}",
+ path.display()
+ )));
+ }
+ };
+ if !metadata.file_type().is_file() {
+ return Err(SecretStorageError::Backend(format!(
+ "refusing to fingerprint a non-regular keyring file at {}",
+ path.display()
+ )));
+ }
+
+ let mut file = File::open(path).map_err(|error| {
+ SecretStorageError::Backend(format!(
+ "could not read {} for the keyring: {error}",
+ path.display()
+ ))
+ })?;
+ let mut hasher = Sha256::new();
+ let mut buffer = [0_u8; 8192];
+ loop {
+ let read = file.read(&mut buffer).map_err(|error| {
+ SecretStorageError::Backend(format!(
+ "could not fingerprint {} for the keyring: {error}",
+ path.display()
+ ))
+ })?;
+ if read == 0 {
+ break;
+ }
+ hasher.update(&buffer[..read]);
+ }
+ Ok(Some(hasher.finalize().into()))
+}
+
fn parent_dir(path: &Path) -> &Path {
path.parent()
.filter(|parent| !parent.as_os_str().is_empty())
diff --git a/crates/openhuman-core/src/security/secret_storage/file_store_tests.rs b/crates/openhuman-core/src/security/secret_storage/file_store_tests.rs
index 02186bedbe..c2ba11897b 100644
--- a/crates/openhuman-core/src/security/secret_storage/file_store_tests.rs
+++ b/crates/openhuman-core/src/security/secret_storage/file_store_tests.rs
@@ -4,10 +4,43 @@ use std::collections::VecDeque;
use std::path::Path;
use super::{
- lock_for_write, lock_path_for, quarantine_corrupt, reserve_temp_file, temp_path_for,
- write_atomic,
+ fingerprint, lock_for_write, lock_path_for, quarantine_corrupt, reserve_temp_file,
+ temp_path_for, write_atomic,
};
+#[test]
+fn fingerprint_tracks_the_file_contents_and_missing_files() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let path = dir.path().join("secrets.enc");
+ assert_eq!(fingerprint(&path).unwrap(), None);
+
+ write_atomic(&path, b"first ciphertext").unwrap();
+ let first = fingerprint(&path).unwrap();
+ assert!(first.is_some());
+
+ write_atomic(&path, b"replacement ciphertext").unwrap();
+ assert_ne!(fingerprint(&path).unwrap(), first);
+}
+
+#[cfg(unix)]
+#[test]
+fn write_lock_is_private_and_repairs_an_existing_lock() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let dir = tempfile::TempDir::new().unwrap();
+ let path = dir.path().join("secrets.enc");
+ let lock_path = lock_path_for(&path);
+ std::fs::write(&lock_path, b"").unwrap();
+ std::fs::set_permissions(&lock_path, std::fs::Permissions::from_mode(0o644)).unwrap();
+
+ let lock = lock_for_write(&path).unwrap();
+ assert_eq!(
+ std::fs::metadata(lock_path).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ drop(lock);
+}
+
#[cfg(unix)]
#[test]
fn durable_replace_syncs_parent_after_rename_and_propagates_failure() {
diff --git a/crates/openhuman-core/src/tools/impl/network/gitbooks_tests.rs b/crates/openhuman-core/src/tools/impl/network/gitbooks_tests.rs
index 50470b6fa1..3c5ed36058 100644
--- a/crates/openhuman-core/src/tools/impl/network/gitbooks_tests.rs
+++ b/crates/openhuman-core/src/tools/impl/network/gitbooks_tests.rs
@@ -94,7 +94,7 @@ async fn mock_module_client(
#[cfg(feature = "modules")]
#[tokio::test]
-async fn gitbooks_tools_use_confidential_one_shot_module_calls() {
+async fn gitbooks_tools_fail_closed_when_the_module_is_not_attested() {
let state = MockProviderState::default();
let (client, _service, module_calls) = mock_module_client(state).await;
let endpoint = "https://docs.example.test/path?token=secret".to_owned();
@@ -110,20 +110,21 @@ async fn gitbooks_tools_use_confidential_one_shot_module_calls() {
.await
.expect("page fetch executes");
- assert!(!search_result.is_error, "{}", search_result.output());
- assert!(search_result.output().contains("search fixture result"));
- assert!(!page_result.is_error, "{}", page_result.output());
- assert!(page_result.output().contains("page fixture markdown"));
- assert_eq!(
+ assert!(search_result.is_error, "{}", search_result.output());
+ assert!(search_result
+ .output()
+ .contains("MODULE_CALL_REPORTED: module transport failed"));
+ assert!(page_result.is_error, "{}", page_result.output());
+ assert!(page_result
+ .output()
+ .contains("MODULE_CALL_REPORTED: module transport failed"));
+ assert!(
module_calls
.calls
.lock()
.expect("provider request log")
- .as_slice(),
- [
- serde_json::json!({"tool": "searchDocumentation", "server": "openhuman-gitbooks", "endpoint": endpoint, "timeout_secs": 5, "arguments": {"query": "module migration"}}),
- serde_json::json!({"tool": "getPage", "server": "openhuman-gitbooks", "endpoint": endpoint, "timeout_secs": 5, "arguments": {"url": "https://docs.example.test/guide"}}),
- ]
+ .is_empty(),
+ "an unattested in-memory service must never receive confidential module calls"
);
}