Skip to content

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

fix(keyring): keep a configured master-key error across init calls and out of logs

fede-kamel22e6a609b50e
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 2ed393350a..d0607c954b 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
@@ -37,8 +37,13 @@ pub const MASTER_KEY_FILE_ENV: &str = "OPENHUMAN_KEYRING_MASTER_KEY_FILE";
const SECRETS_FILENAME: &str = "secrets.enc";
const LEGACY_DEV_KEYCHAIN: &str = "dev-keychain.json";
-/// Process-wide master key, set once by [`init_master_key`].
-static MASTER_KEY: OnceLock<Option<[u8; KEY_LEN]>> = OnceLock::new();
+/// Outcome of the one-time master-key initialization: the key (`None` when
+/// the backend needs none or the OS keychain could not provide it), or the
+/// configuration error that rejected an operator-supplied source.
+type MasterKeyInit = Result<Option<[u8; KEY_LEN]>, String>;
+
+/// Process-wide master-key outcome, set once by [`init_master_key`].
+static MASTER_KEY: OnceLock<MasterKeyInit> = OnceLock::new();
// ── Public API for core startup ──────────────────────────────────────────────
@@ -62,8 +67,8 @@ static MASTER_KEY: OnceLock<Option<[u8; KEY_LEN]>> = OnceLock::new();
/// 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.
+/// is restored). The outcome, error included, is cached process-wide, so
+/// every later call after a configuration error returns the same `Err`.
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();
@@ -73,28 +78,26 @@ pub fn init_master_key() -> Result<(), String> {
);
crate::security::keyring::init_workspace(&dir);
- let mut configuration_error: Option<String> = None;
- MASTER_KEY.get_or_init(|| {
+ init_once(&MASTER_KEY, || {
let backend_kind = crate::security::keyring::store::effective_backend_kind();
if backend_kind != BackendKind::EncryptedFile {
log::debug!(
"[keyring:encrypted_file] skipping master key init backend={backend_kind:?}"
);
- return None;
+ return Ok(None);
}
match try_load_master_key() {
Ok((key, source)) => {
log::info!("[keyring:encrypted_file] master key loaded from {source}");
- Some(key)
+ Ok(Some(key))
}
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(e)
}
Err(MasterKeyError::Keychain(e)) => {
log::error!(
@@ -106,13 +109,25 @@ pub fn init_master_key() -> Result<(), String> {
// Surface the denied state to the frontend instead of silently
// resetting — this is the "warn before reset" the issue asks for.
crate::security::keyring_consent::policy::notify_master_key_unavailable(&e);
- None
+ Ok(None)
}
}
- });
- match configuration_error {
- Some(e) => Err(e),
- None => Ok(()),
+ })
+}
+
+/// Runs `init` at most once per `cell` and reports its outcome on every call.
+///
+/// A configuration error is stored in the cell rather than leaving it empty
+/// or storing `None`: `OnceLock::get_or_init` never reruns its closure, so a
+/// later call (a second embedded boot in the same process) must still see the
+/// error instead of a silent `Ok` with no key loaded.
+fn init_once(
+ cell: &OnceLock<MasterKeyInit>,
+ init: impl FnOnce() -> MasterKeyInit,
+) -> Result<(), String> {
+ match cell.get_or_init(init) {
+ Ok(_) => Ok(()),
+ Err(e) => Err(e.clone()),
}
}
@@ -202,8 +217,9 @@ fn env_value(
/// as unset, matching how Compose passes an undefined `${VAR}`), so the
/// caller falls through to the OS keychain. `Err` when a source is set but
/// unusable: both set at once, an unreadable file, or a value that is not
-/// exactly `2 * KEY_LEN` hex characters. Error messages name the source and
-/// the problem but never include the value.
+/// exactly `2 * KEY_LEN` hex characters. Error messages and the returned
+/// source label name the variable and the problem but never include its
+/// value — not even the file path, which may be a mistakenly pasted key.
///
/// `read_file` is injected so the decision logic is testable without touching
/// the filesystem; production passes [`read_master_key_file`].
@@ -223,12 +239,14 @@ fn master_key_from_env(
.map(|key| Some((key, MASTER_KEY_ENV.to_string())))
.map_err(|e| format!("{MASTER_KEY_ENV}: {e}")),
(None, Some(path)) => {
- let path = Path::new(path);
- let source = format!("{MASTER_KEY_FILE_ENV} ({})", path.display());
- let contents = read_file(path).map_err(|e| format!("{source}: {e}"))?;
+ // Named by the variable, never by its value: an operator who puts
+ // the key itself in the `_FILE` variable would otherwise have it
+ // copied into the error and the startup log.
+ let contents =
+ read_file(Path::new(path)).map_err(|e| format!("{MASTER_KEY_FILE_ENV}: {e}"))?;
parse_master_key_hex(contents.trim())
- .map(|key| Some((key, source.clone())))
- .map_err(|e| format!("{source}: {e}"))
+ .map(|key| Some((key, MASTER_KEY_FILE_ENV.to_string())))
+ .map_err(|e| format!("{MASTER_KEY_FILE_ENV}: {e}"))
}
}
}
@@ -245,9 +263,8 @@ fn read_master_key_file(path: &Path) -> Result<String, String> {
let mode = metadata.permissions().mode() & 0o777;
if mode & 0o077 != 0 {
log::warn!(
- "[keyring:encrypted_file] master key file {} has mode {mode:04o}; \
- 0600 is recommended",
- path.display()
+ "[keyring:encrypted_file] master key file ({MASTER_KEY_FILE_ENV}) has \
+ mode {mode:04o}; 0600 is recommended"
);
}
}
@@ -333,7 +350,10 @@ fn load_or_mint_master_key<E: MasterKeyEntry>(entry: &E) -> Result<[u8; KEY_LEN]
/// Get a reference to the cached master key, if available.
fn master_key() -> Option<&'static [u8; KEY_LEN]> {
- MASTER_KEY.get().and_then(|k| k.as_ref())
+ MASTER_KEY
+ .get()
+ .and_then(|init| init.as_ref().ok())
+ .and_then(Option::as_ref)
}
// ── Backend ──────────────────────────────────────────────────────────────────
@@ -466,13 +486,13 @@ impl EncryptedFileBackend {
fn handle_corruption(&self) {
file_store::quarantine_corrupt(&self.path, "enc");
}
-}
-impl KeyringBackend for EncryptedFileBackend {
- fn get(&self, namespaced_key: &str) -> Result<Option<String>, KeyringError> {
- let Some(key) = master_key() else {
- return Ok(None);
- };
+ /// [`KeyringBackend::get`] under an explicit master key.
+ fn get_with_key(
+ &self,
+ key: &[u8; KEY_LEN],
+ namespaced_key: &str,
+ ) -> Result<Option<String>, KeyringError> {
// `read_map` can mutate the filesystem: it migrates a missing file and
// quarantines corrupt ciphertext. Hold the same lock as writers for
// either case so a delayed quarantine cannot rename a replacement a
@@ -482,12 +502,13 @@ impl KeyringBackend for EncryptedFileBackend {
Ok(map.get(namespaced_key).cloned())
}
- fn set(&self, namespaced_key: &str, value: &str) -> Result<(), KeyringError> {
- let Some(key) = master_key() else {
- return Err(KeyringError::Backend(
- "master key unavailable — cannot store secrets".to_string(),
- ));
- };
+ /// [`KeyringBackend::set`] under an explicit master key.
+ fn set_with_key(
+ &self,
+ key: &[u8; KEY_LEN],
+ namespaced_key: &str,
+ value: &str,
+ ) -> Result<(), KeyringError> {
// Held across the read as well as the write: taking it around the write
// alone would still let a stale map overwrite a concurrent one.
let _guard = file_store::lock_for_write(&self.path)?;
@@ -495,6 +516,24 @@ impl KeyringBackend for EncryptedFileBackend {
map.insert(namespaced_key.to_string(), value.to_string());
self.write_map(key, &map)
}
+}
+
+impl KeyringBackend for EncryptedFileBackend {
+ fn get(&self, namespaced_key: &str) -> Result<Option<String>, KeyringError> {
+ let Some(key) = master_key() else {
+ return Ok(None);
+ };
+ self.get_with_key(key, namespaced_key)
+ }
+
+ fn set(&self, namespaced_key: &str, value: &str) -> Result<(), KeyringError> {
+ let Some(key) = master_key() else {
+ return Err(KeyringError::Backend(
+ "master key unavailable — cannot store secrets".to_string(),
+ ));
+ };
+ self.set_with_key(key, namespaced_key, value)
+ }
fn delete(&self, namespaced_key: &str) -> Result<(), KeyringError> {
let Some(key) = master_key() else {
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 f23f6c6c28..3c1248f74d 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
@@ -146,7 +146,7 @@ fn env_inline_key_tolerates_surrounding_whitespace_and_uppercase_hex() {
}
#[test]
-fn env_file_key_is_read_trimmed_and_names_the_path() {
+fn env_file_key_is_read_trimmed_and_names_the_variable() {
let hex = hex_key(0x11);
let (key, source) =
master_key_from_env(None, Some("/run/secrets/openhuman_master_key"), |path| {
@@ -156,22 +156,33 @@ fn env_file_key_is_read_trimmed_and_names_the_path() {
.expect("file key is valid")
.expect("supplied");
assert_eq!(key, [0x11u8; KEY_LEN]);
- assert!(source.starts_with(MASTER_KEY_FILE_ENV), "{source}");
- assert!(
- source.contains("/run/secrets/openhuman_master_key"),
- "{source}"
- );
+ assert_eq!(source, MASTER_KEY_FILE_ENV);
}
#[test]
-fn unreadable_env_file_is_an_error_that_names_the_path() {
+fn unreadable_env_file_is_an_error_that_names_the_variable_not_the_path() {
let err = master_key_from_env(None, Some("/nonexistent/master.key"), |_| {
Err("cannot read master key file: boom".to_string())
})
.expect_err("unreadable file must not fall through to the keychain");
assert!(err.contains(MASTER_KEY_FILE_ENV), "{err}");
- assert!(err.contains("/nonexistent/master.key"), "{err}");
assert!(err.contains("cannot read"), "{err}");
+ assert!(!err.contains("/nonexistent/master.key"), "{err}");
+}
+
+#[test]
+fn a_key_pasted_into_the_file_variable_is_not_echoed() {
+ // The operator meant `MASTER_KEY=<hex>` but set `MASTER_KEY_FILE=<hex>`:
+ // the "path" is the secret, so the read error must not carry it into the
+ // startup log.
+ let pasted_key = hex_key(0x77);
+ let err = master_key_from_env(None, Some(&pasted_key), read_master_key_file)
+ .expect_err("a key is not a readable path");
+ assert!(err.contains(MASTER_KEY_FILE_ENV), "{err}");
+ assert!(
+ !err.contains(&pasted_key),
+ "error must not echo the key: {err}"
+ );
}
#[test]
@@ -322,7 +333,7 @@ fn try_load_master_key_reads_the_file_source_and_is_stable_across_restarts() {
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}");
+ assert_eq!(source, MASTER_KEY_FILE_ENV);
let blob = crypto::chacha20_encrypt(&first, b"sk-live-secret").expect("encrypt");
assert_eq!(
@@ -345,3 +356,83 @@ fn try_load_master_key_reports_a_configured_source_error_as_configured() {
other => panic!("expected a configuration error, got {other:?}"),
}
}
+
+#[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 key_path = key_dir.path().join("master.key");
+ std::fs::write(&key_path, format!("{}\n", hex_key(0x88))).unwrap();
+ let _env = crate::config::test_env::EnvVarGuard::locked()
+ .without(MASTER_KEY_ENV)
+ .with(MASTER_KEY_FILE_ENV, &key_path);
+
+ // First "process": load the configured key and store a secret through the
+ // same lock → read → encrypt → write path `KeyringBackend::set` uses.
+ // `MASTER_KEY` is a process-wide `OnceLock` that cannot be reset, so the
+ // key is passed explicitly instead of going through it.
+ {
+ let (key, _) = try_load_master_key().expect("configured key loads");
+ let backend = EncryptedFileBackend::new(workspace.path());
+ backend
+ .set_with_key(&key, "provider:openai", "sk-live-secret")
+ .expect("store under the configured key");
+ }
+ let on_disk = std::fs::read(workspace.path().join(SECRETS_FILENAME)).unwrap();
+ assert!(
+ !on_disk
+ .windows(b"sk-live-secret".len())
+ .any(|w| w == b"sk-live-secret"),
+ "secrets.enc must not hold the plaintext"
+ );
+
+ // Second "process": a fresh key load and a fresh backend over the same
+ // workspace read the secret back.
+ let (key, _) = try_load_master_key().expect("configured key loads after restart");
+ let backend = EncryptedFileBackend::new(workspace.path());
+ assert_eq!(
+ backend
+ .get_with_key(&key, "provider:openai")
+ .expect("read after restart")
+ .as_deref(),
+ Some("sk-live-secret")
+ );
+}
+
+// ── One-time init keeps a configuration error ───────────────────────────────
+
+#[test]
+fn init_once_returns_the_configuration_error_on_every_call() {
+ let cell = OnceLock::new();
+ let first = init_once(&cell, || {
+ Err(format!(
+ "{MASTER_KEY_ENV}: expected 64 hex characters, got 4"
+ ))
+ });
+ assert!(first.is_err(), "first call reports the error");
+
+ // `OnceLock` does not rerun the closure; the cached error must still
+ // surface rather than a silent `Ok` with no key loaded.
+ let second = init_once(&cell, || panic!("init must run at most once"));
+ assert_eq!(second, first);
+}
+
+#[test]
+fn init_once_caches_a_loaded_key_and_a_keychain_outage_as_ok() {
+ let loaded = OnceLock::new();
+ assert_eq!(init_once(&loaded, || Ok(Some([0x99u8; KEY_LEN]))), Ok(()));
+ assert_eq!(
+ init_once(&loaded, || panic!("init must run at most once")),
+ Ok(())
+ );
+ assert_eq!(loaded.get(), Some(&Ok(Some([0x99u8; KEY_LEN]))));
+
+ // No key (non-encrypted backend, or the #3311 keychain outage) is not a
+ // startup error.
+ let unavailable = OnceLock::new();
+ assert_eq!(init_once(&unavailable, || Ok(None)), Ok(()));
+ assert_eq!(
+ init_once(&unavailable, || panic!("init must run at most once")),
+ Ok(())
+ );
+}
diff --git a/crates/openhuman-tui/src/runner.rs b/crates/openhuman-tui/src/runner.rs
index b1d81f1730..9d08c35469 100644
--- a/crates/openhuman-tui/src/runner.rs
+++ b/crates/openhuman-tui/src/runner.rs
@@ -28,7 +28,6 @@ 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().map_err(anyhow::Error::msg)?;
let mut thread_id: Option<String> = None;
let mut force_new = false;
@@ -109,6 +108,9 @@ pub fn run_from_cli(args: &[String]) -> anyhow::Result<()> {
// File-only logging — never stderr while the TUI owns the terminal.
let data_dir = resolve_data_dir();
let log_dir = openhuman_core::core::logging::init_for_tui(&data_dir, verbose);
+ // After argument parsing so `--help` works while a configured master key
+ // is being fixed, and after logging so a rejection reaches the log file.
+ openhuman_core::security::keyring::init_master_key().map_err(anyhow::Error::msg)?;
log::info!(
"[tui] starting tabbed terminal UI (thread={:?} new={} logs={:?})",
thread_id,