Skip to content

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

fix(keyring): reject invalid-Unicode master-key variables and fail startup on a bad configured key

Federico Kamelhar092787c1f893
diff --git a/crates/openhuman-core/src/core/runtime/context.rs b/crates/openhuman-core/src/core/runtime/context.rs
index 0900593897..281cdac8df 100644
--- a/crates/openhuman-core/src/core/runtime/context.rs
+++ b/crates/openhuman-core/src/core/runtime/context.rs
@@ -255,8 +255,9 @@ impl CoreContext {
// 2. Load the master encryption key before any config/credential op that
// needs to decrypt secrets. No-op if already called (e.g. from
- // run_core_from_args for the CLI).
- crate::security::keyring::init_master_key();
+ // run_core_from_args for the CLI). An operator-supplied key that is
+ // set but unusable is a configuration error worth failing startup on.
+ crate::security::keyring::init_master_key().map_err(anyhow::Error::msg)?;
// 4. Seed the per-process RPC bearer. `Fixed` seeds the in-memory value
// directly (never touches the env); `EnvOrFile` reads
diff --git a/crates/openhuman-core/src/lib.rs b/crates/openhuman-core/src/lib.rs
index b540aba55c..929054a663 100644
--- a/crates/openhuman-core/src/lib.rs
+++ b/crates/openhuman-core/src/lib.rs
@@ -112,6 +112,6 @@ pub use core::types::HostKind;
pub fn run_core_from_args(args: &[String]) -> anyhow::Result<()> {
core::cli::load_dotenv_for_cli()?;
platform::service::apply_startup_restart_delay_from_env();
- security::keyring::init_master_key();
+ security::keyring::init_master_key().map_err(anyhow::Error::msg)?;
core::cli::run_from_cli_args(args)
}
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
index 5e18148665..2ed393350a 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
@@ -52,7 +52,19 @@ static MASTER_KEY: OnceLock<Option<[u8; KEY_LEN]>> = OnceLock::new();
/// used instead). The result is cached process-wide; subsequent calls are
/// no-ops. Which source supplied the key is logged at `info`; the key never
/// is.
-pub fn init_master_key() {
+///
+/// # Errors
+///
+/// Returns `Err` only when an operator-supplied source ([`MASTER_KEY_ENV`] /
+/// [`MASTER_KEY_FILE_ENV`]) is set but unusable — both set, unreadable file,
+/// wrong length, not hex. That is a configuration error the process should
+/// not start with: continuing would run with secrets unreadable and fail
+/// later, on the first store, with a less specific message. An OS-keychain
+/// failure is **not** an error here: it keeps the #3311 behaviour (log,
+/// notify the frontend, run with secrets inaccessible until keychain access
+/// is restored). The outcome is cached process-wide, so a second call after
+/// a configuration error returns `Ok` with no master key loaded.
+pub fn init_master_key() -> Result<(), String> {
// Ensure workspace dir is set for the backend before anything else.
let dir = crate::security::keyring::store::workspace_dir_for_file_backend();
log::info!(
@@ -61,6 +73,7 @@ pub fn init_master_key() {
);
crate::security::keyring::init_workspace(&dir);
+ let mut configuration_error: Option<String> = None;
MASTER_KEY.get_or_init(|| {
let backend_kind = crate::security::keyring::store::effective_backend_kind();
if backend_kind != BackendKind::EncryptedFile {
@@ -75,7 +88,15 @@ pub fn init_master_key() {
log::info!("[keyring:encrypted_file] master key loaded from {source}");
Some(key)
}
- Err(e) => {
+ Err(MasterKeyError::Configured(e)) => {
+ log::error!(
+ "[keyring:encrypted_file] operator-supplied master key rejected; refusing \
+ to start with secrets unreadable. Cause: {e}"
+ );
+ configuration_error = Some(e);
+ None
+ }
+ Err(MasterKeyError::Keychain(e)) => {
log::error!(
"[keyring:encrypted_file] master key load FAILED — refusing to mint a \
replacement (that would orphan existing secrets, #3311). Secrets are \
@@ -89,6 +110,21 @@ pub fn init_master_key() {
}
}
});
+ match configuration_error {
+ Some(e) => Err(e),
+ None => Ok(()),
+ }
+}
+
+/// Why the master key could not be loaded. The two kinds are handled
+/// differently at startup — see [`init_master_key`].
+#[derive(Debug)]
+enum MasterKeyError {
+ /// An operator-supplied source is set but unusable. Fatal at startup.
+ Configured(String),
+ /// The OS keychain could not provide (or safely mint) the key. Not fatal:
+ /// the process runs with secrets inaccessible, as before.
+ Keychain(String),
}
/// Abstraction over the OS-keychain entry that holds the master key.
@@ -120,17 +156,43 @@ impl MasterKeyEntry for keyring::Entry {
/// error, not a fall-through: silently continuing to the keychain would mask
/// the misconfiguration and, in a container, fail later with a less specific
/// "master key unavailable".
-fn try_load_master_key() -> Result<([u8; KEY_LEN], String), String> {
- let inline = std::env::var(MASTER_KEY_ENV).ok();
- let file = std::env::var(MASTER_KEY_FILE_ENV).ok();
+fn try_load_master_key() -> Result<([u8; KEY_LEN], String), MasterKeyError> {
+ let inline = env_value(MASTER_KEY_ENV, std::env::var(MASTER_KEY_ENV))
+ .map_err(MasterKeyError::Configured)?;
+ let file = env_value(MASTER_KEY_FILE_ENV, std::env::var(MASTER_KEY_FILE_ENV))
+ .map_err(MasterKeyError::Configured)?;
if let Some(from_env) =
- master_key_from_env(inline.as_deref(), file.as_deref(), read_master_key_file)?
+ master_key_from_env(inline.as_deref(), file.as_deref(), read_master_key_file)
+ .map_err(MasterKeyError::Configured)?
{
return Ok(from_env);
}
let entry = keyring::Entry::new(KEYCHAIN_SERVICE, KEYCHAIN_MASTER_KEY_USERNAME)
- .map_err(|e| format!("keychain entry creation failed: {e}"))?;
- load_or_mint_master_key(&entry).map(|key| (key, "OS keychain".to_string()))
+ .map_err(|e| MasterKeyError::Keychain(format!("keychain entry creation failed: {e}")))?;
+ load_or_mint_master_key(&entry)
+ .map(|key| (key, "OS keychain".to_string()))
+ .map_err(MasterKeyError::Keychain)
+}
+
+/// Interprets one `std::env::var` result for a master-key variable.
+///
+/// Only `NotPresent` means unset. A value that is not valid Unicode is a
+/// misconfiguration and must not be treated as unset: that would fall
+/// through to the OS keychain, where [`load_or_mint_master_key`] could mint
+/// a different key and orphan every secret in `secrets.enc`. The rejected
+/// value is never formatted into the error (`VarError`'s `Display` would
+/// include it).
+fn env_value(
+ name: &str,
+ raw: Result<String, std::env::VarError>,
+) -> Result<Option<String>, String> {
+ match raw {
+ Ok(value) => Ok(Some(value)),
+ Err(std::env::VarError::NotPresent) => Ok(None),
+ Err(std::env::VarError::NotUnicode(_)) => {
+ Err(format!("{name} is set but is not valid Unicode"))
+ }
+ }
}
/// Resolves an operator-supplied master key from the two environment
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend_tests.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend_tests.rs
index a71cdddf3f..f23f6c6c28 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend_tests.rs
+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend_tests.rs
@@ -263,3 +263,85 @@ fn parse_master_key_hex_round_trips_an_encoded_key() {
let parsed = parse_master_key_hex(&crypto::hex_encode(&key_bytes)).expect("valid");
assert_eq!(parsed.as_slice(), key_bytes.as_slice());
}
+
+#[test]
+fn env_value_distinguishes_unset_from_invalid_unicode() {
+ use std::env::VarError;
+
+ assert_eq!(
+ env_value(MASTER_KEY_ENV, Ok("abc".to_string())).expect("set"),
+ Some("abc".to_string())
+ );
+ assert_eq!(
+ env_value(MASTER_KEY_ENV, Err(VarError::NotPresent)).expect("unset is not an error"),
+ None
+ );
+
+ // Invalid Unicode must be rejected, not treated as unset: falling through
+ // to the keychain could mint a different key and orphan `secrets.enc`.
+ let rejected = std::ffi::OsString::from("not-the-real-bytes");
+ let err = env_value(MASTER_KEY_FILE_ENV, Err(VarError::NotUnicode(rejected)))
+ .expect_err("invalid Unicode is a configuration error");
+ assert!(err.contains(MASTER_KEY_FILE_ENV), "{err}");
+ assert!(err.contains("not valid Unicode"), "{err}");
+ assert!(
+ !err.contains("not-the-real-bytes"),
+ "error must not echo the value: {err}"
+ );
+}
+
+// ── Wiring: the real env → `try_load_master_key` → key, no keychain ─────────
+
+#[test]
+fn try_load_master_key_prefers_the_inline_env_key_and_never_touches_the_keychain() {
+ let hex = hex_key(0x55);
+ let _env = crate::config::test_env::EnvVarGuard::locked()
+ .with(MASTER_KEY_ENV, &hex)
+ .without(MASTER_KEY_FILE_ENV);
+
+ // A real OS keychain cannot be exercised under `cargo test` (the first
+ // access blocks on a GUI prompt), so reaching the keychain here would hang
+ // or fail; returning means the env source short-circuited it.
+ let (key, source) = try_load_master_key().expect("inline env key loads");
+ assert_eq!(key, [0x55u8; KEY_LEN]);
+ assert_eq!(source, MASTER_KEY_ENV);
+}
+
+#[test]
+fn try_load_master_key_reads_the_file_source_and_is_stable_across_restarts() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let path = tmp.path().join("master.key");
+ std::fs::write(&path, format!("{}\n", hex_key(0x66))).unwrap();
+ let _env = crate::config::test_env::EnvVarGuard::locked()
+ .without(MASTER_KEY_ENV)
+ .with(MASTER_KEY_FILE_ENV, &path);
+
+ // Two loads stand in for two process starts: the same file must yield
+ // the same key, so a secret encrypted before a restart decrypts after it.
+ let (first, source) = try_load_master_key().expect("file key loads");
+ let (second, _) = try_load_master_key().expect("file key loads again");
+ assert_eq!(first, [0x66u8; KEY_LEN]);
+ assert_eq!(first, second);
+ assert!(source.contains(&path.display().to_string()), "{source}");
+
+ let blob = crypto::chacha20_encrypt(&first, b"sk-live-secret").expect("encrypt");
+ assert_eq!(
+ crypto::chacha20_decrypt(&second, &blob).expect("decrypt with the restarted key"),
+ b"sk-live-secret"
+ );
+}
+
+#[test]
+fn try_load_master_key_reports_a_configured_source_error_as_configured() {
+ let _env = crate::config::test_env::EnvVarGuard::locked()
+ .with(MASTER_KEY_ENV, "not-a-key")
+ .without(MASTER_KEY_FILE_ENV);
+
+ match try_load_master_key() {
+ Err(MasterKeyError::Configured(e)) => {
+ assert!(e.contains(MASTER_KEY_ENV), "{e}");
+ assert!(!e.contains("not-a-key"), "must not echo the value: {e}");
+ }
+ other => panic!("expected a configuration error, got {other:?}"),
+ }
+}
diff --git a/crates/openhuman-tui/src/runner.rs b/crates/openhuman-tui/src/runner.rs
index e7db569d3a..b1d81f1730 100644
--- a/crates/openhuman-tui/src/runner.rs
+++ b/crates/openhuman-tui/src/runner.rs
@@ -28,7 +28,7 @@ use openhuman_core::core::types::HostKind;
pub fn run_from_cli(args: &[String]) -> anyhow::Result<()> {
openhuman_core::core::cli::load_dotenv_for_cli()?;
openhuman_core::platform::service::apply_startup_restart_delay_from_env();
- openhuman_core::security::keyring::init_master_key();
+ openhuman_core::security::keyring::init_master_key().map_err(anyhow::Error::msg)?;
let mut thread_id: Option<String> = None;
let mut force_new = false;