The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(keyring): let headless deployments supply the encrypted_file master key
Federico Kamelhar7379e879a42c
diff --git a/.env.example b/.env.exampleindex 38eec596ea..1c6e202138 100644--- a/.env.example+++ b/.env.example@@ -91,6 +91,12 @@ OPENHUMAN_MODEL=# [optional] Workspace directory (default: ~/.openhuman or ~/.openhuman-staging when OPENHUMAN_APP_ENV=staging)# Leave commented out to use the default. Setting to empty string is treated as unset.# OPENHUMAN_WORKSPACE=+# [optional] Master key for the `encrypted_file` keyring used in staging/production,+# as 64 hex characters (`openssl rand -hex 32`). Headless/container deploys have no+# OS keychain to hold it; set exactly one of these two, injected from your secret+# manager. Losing the key orphans every secret encrypted under it.+# OPENHUMAN_KEYRING_MASTER_KEY=+# OPENHUMAN_KEYRING_MASTER_KEY_FILE=/run/secrets/openhuman_master_key# [optional] Default: 0.7OPENHUMAN_TEMPERATURE=0.7# [optional] Language for background LLM artifacts such as memory-tree summaries,diff --git a/crates/openhuman-core/src/security/keyring/README.md b/crates/openhuman-core/src/security/keyring/README.mdindex 45f73eae5b..628ce92858 100644--- a/crates/openhuman-core/src/security/keyring/README.md+++ b/crates/openhuman-core/src/security/keyring/README.md@@ -9,7 +9,7 @@ OS-keychain-backed secret storage with pluggable test and debug backends, plus a- Probe and cache backend availability (`is_available`) so callers (wallet guards, snapshot loops) can fall back to file storage without re-triggering OS keychain prompts.- Migrate a secret from a plaintext file into the active backend (`migrate_from_file`), verifying the write before deleting the source.- Encrypt and decrypt config-field secrets via `SecretStore` (ChaCha20-Poly1305, `enc2:` prefix), including migration of the legacy XOR `enc:` format.-- Load and cache a single app-scoped master encryption key from the OS keychain at startup (`init_master_key`) for the `encrypted_file` backend, reducing keychain access to one call per process.+- Load and cache a single app-scoped master encryption key at startup (`init_master_key`) for the `encrypted_file` backend: from `OPENHUMAN_KEYRING_MASTER_KEY` / `OPENHUMAN_KEYRING_MASTER_KEY_FILE` when an operator supplies one (headless deployments with no keychain, #6926), otherwise from the OS keychain, reducing keychain access to one call per process.- Migrate the legacy plaintext `dev-keychain.json` into the encrypted `secrets.enc` file on first use.## Key files@@ -36,7 +36,7 @@ Re-exported from `mod.rs`:- `KeyringBackend`: backend trait (`get`/`set`/`delete`/`name`).- `SecretStore`: config-field encrypt/decrypt; `encrypt`/`decrypt`/`decrypt_and_migrate`/`needs_migration`/`is_encrypted`/`new`.- `KeyringError`: error enum with `diagnostic()`.-- `init_master_key`: load the app master key from the OS keychain at startup (staging/prod only).+- `init_master_key`: load the app master key at startup (staging/prod only) — from the environment (`OPENHUMAN_KEYRING_MASTER_KEY` inline, or `OPENHUMAN_KEYRING_MASTER_KEY_FILE` naming a file; 64 hex characters, exactly one of the two) when set, otherwise from the OS keychain. A set-but-malformed variable is a boot error, not a fall-through; the source is logged at `info`, the value never.- `init_workspace`: register the workspace dir for file and encrypted-file backends.- `get`, `set`, `delete`, `get_or_create_random`, `is_available`, `migrate_from_file`, `MigrationOutcome`.- `force_backend_for_test`: `pub(crate)`, test-only.@@ -58,7 +58,7 @@ None. There is no `bus.rs`, and the module publishes and subscribes to no `DomaiSecret storage backend, selected once and frozen in a `OnceLock`:- `os` (production default outside staging/prod special-casing): native OS credential store, macOS Keychain, Windows Credential Manager, or Linux Secret Service, under service name `"openhuman"`.-- `encrypted_file` (staging/production, and via `OPENHUMAN_KEYRING_BACKEND=encrypted_file`): single ChaCha20-Poly1305 file `{workspace}/secrets.enc`, encrypted with a master key loaded once from the OS keychain (`openhuman` / `app:master_key`). Files are written `0600` on Unix via temp-file plus atomic rename.+- `encrypted_file` (staging/production, and via `OPENHUMAN_KEYRING_BACKEND=encrypted_file`): single ChaCha20-Poly1305 file `{workspace}/secrets.enc`, encrypted with a master key loaded once — from `OPENHUMAN_KEYRING_MASTER_KEY` / `OPENHUMAN_KEYRING_MASTER_KEY_FILE` when set, otherwise from the OS keychain (`openhuman` / `app:master_key`). Files are written `0600` on Unix via temp-file plus atomic rename.- `file` (dev default, `cfg(test)`, or `OPENHUMAN_KEYRING_BACKEND=file`): plaintext JSON `{workspace}/dev-keychain.json`. Not encrypted; test and debug use only.- `mock` (test-only): in-memory `HashMap`.diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rsindex c4e4d858e5..5e18148665 100644--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs@@ -1,9 +1,11 @@//! Encrypted-file keyring backend.//!//! Stores all secrets in a single ChaCha20-Poly1305-encrypted file on disk,-//! keyed by an app-scoped master key. The key is loaded from the OS keychain-//! once at core startup via [`init_master_key`] and cached in a process-wide-//! static. The backend itself never touches the OS keychain.+//! keyed by an app-scoped master key. The key is loaded once at core startup+//! via [`init_master_key`] — from the environment when an operator supplies+//! it ([`MASTER_KEY_ENV`] / [`MASTER_KEY_FILE_ENV`], for headless deployments+//! with no OS keychain), otherwise from the OS keychain — and cached in a+//! process-wide static. The backend itself never touches the OS keychain.//!//! This design reduces OS keychain access to exactly ONE call per process//! lifetime, avoiding the N-prompt problem where dev-signed macOS builds@@ -21,6 +23,17 @@ use crate::security::keyring::store::BackendKind;const KEYCHAIN_SERVICE: &str = "openhuman";const KEYCHAIN_MASTER_KEY_USERNAME: &str = "app:master_key";+/// Environment variable carrying the master key inline as `2 * KEY_LEN` hex+/// characters (`openssl rand -hex 32`). Lets a headless `openhuman-core+/// serve` — a container with no Secret Service or keychain — keep the+/// `encrypted_file` backend instead of falling back to the plaintext `file`+/// backend (#6926). Operators inject it from their secret manager the same+/// way they inject `OPENHUMAN_CORE_TOKEN`.+pub const MASTER_KEY_ENV: &str = "OPENHUMAN_KEYRING_MASTER_KEY";+/// Environment variable naming a file whose contents are the master key in+/// the same hex form (surrounding whitespace ignored), for Docker/Kubernetes+/// secret mounts. Mutually exclusive with [`MASTER_KEY_ENV`].+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";@@ -30,12 +43,15 @@ static MASTER_KEY: OnceLock<Option<[u8; KEY_LEN]>> = OnceLock::new();// ── Public API for core startup ──────────────────────────────────────────────/// Initialize the keyring subsystem: set the workspace directory and load-/// the master encryption key from the OS keychain (staging/production only).+/// the master encryption key (staging/production only) — from+/// [`MASTER_KEY_ENV`] or [`MASTER_KEY_FILE_ENV`] when an operator set one,+/// otherwise from the OS keychain.////// Call this once at core startup before any keyring operations. In dev/// environments the master key is not loaded (the plain file backend is/// used instead). The result is cached process-wide; subsequent calls are-/// no-ops.+/// no-ops. Which source supplied the key is logged at `info`; the key never+/// is.pub fn init_master_key() {// Ensure workspace dir is set for the backend before anything else.let dir = crate::security::keyring::store::workspace_dir_for_file_backend();@@ -55,8 +71,8 @@ pub fn init_master_key() {}match try_load_master_key() {- Ok(key) => {- log::info!("[keyring:encrypted_file] master key loaded from OS keychain");+ Ok((key, source)) => {+ log::info!("[keyring:encrypted_file] master key loaded from {source}");Some(key)}Err(e) => {@@ -96,10 +112,104 @@ impl MasterKeyEntry for keyring::Entry {}}-fn try_load_master_key() -> Result<[u8; KEY_LEN], String> {+/// Loads the master key, returning it with a human-readable description of+/// the source it came from (for the startup log; never the value).+///+/// The environment is consulted first so a headless deployment never touches+/// the OS keychain. An environment variable that is set but unusable is an+/// 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();+ if let Some(from_env) =+ master_key_from_env(inline.as_deref(), file.as_deref(), read_master_key_file)?+ {+ 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)+ load_or_mint_master_key(&entry).map(|key| (key, "OS keychain".to_string()))+}++/// Resolves an operator-supplied master key from the two environment+/// sources, given their raw values.+///+/// `Ok(None)` when neither is set (an empty or whitespace-only value counts+/// 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.+///+/// `read_file` is injected so the decision logic is testable without touching+/// the filesystem; production passes [`read_master_key_file`].+fn master_key_from_env(+ inline: Option<&str>,+ file: Option<&str>,+ read_file: impl FnOnce(&Path) -> Result<String, String>,+) -> Result<Option<([u8; KEY_LEN], String)>, String> {+ let inline = inline.map(str::trim).filter(|value| !value.is_empty());+ let file = file.map(str::trim).filter(|value| !value.is_empty());+ match (inline, file) {+ (None, None) => Ok(None),+ (Some(_), Some(_)) => Err(format!(+ "{MASTER_KEY_ENV} and {MASTER_KEY_FILE_ENV} are both set; set exactly one"+ )),+ (Some(hex), None) => parse_master_key_hex(hex)+ .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}"))?;+ parse_master_key_hex(contents.trim())+ .map(|key| Some((key, source.clone())))+ .map_err(|e| format!("{source}: {e}"))+ }+ }+}++/// Reads the file named by [`MASTER_KEY_FILE_ENV`]. On Unix a file readable+/// by group or others is accepted but logged at `warn`: Docker secrets mount+/// `0444` and Kubernetes secret volumes default to `0644`, so refusing would+/// break the very deployments this path exists for.+fn read_master_key_file(path: &Path) -> Result<String, String> {+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if let Ok(metadata) = std::fs::metadata(path) {+ 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()+ );+ }+ }+ }+ std::fs::read_to_string(path).map_err(|e| format!("cannot read master key file: {e}"))+}++/// Decodes a master key supplied as exactly `2 * KEY_LEN` hex characters.+/// The value never appears in the error.+fn parse_master_key_hex(hex: &str) -> Result<[u8; KEY_LEN], String> {+ let expected = 2 * KEY_LEN;+ let got = hex.chars().count();+ if got != expected {+ return Err(format!("expected {expected} hex characters, got {got}"));+ }+ // `hex_decode` slices by byte; a non-ASCII value of the right character+ // count would panic there instead of being rejected.+ if !hex.is_ascii() {+ return Err("value is not valid hex".to_string());+ }+ let bytes = crypto::hex_decode(hex).map_err(|_| "value is not valid hex".to_string())?;+ let mut key = [0u8; KEY_LEN];+ key.copy_from_slice(&bytes);+ Ok(key)}/// Load the existing master key, mint a fresh one, or fail safe.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.rsindex 5f08c21ae2..a71cdddf3f 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@@ -115,3 +115,151 @@ fn rejects_wrong_length_key_without_minting() {"must not overwrite on length mismatch");}++// ── Operator-supplied master key (#6926) ─────────────────────────────────────++fn hex_key(byte: u8) -> String {+ format!("{byte:02x}").repeat(KEY_LEN)+}++fn file_must_not_be_read(path: &Path) -> Result<String, String> {+ panic!("master key file {} must not be read", path.display())+}++#[test]+fn env_inline_key_is_used_and_names_its_source() {+ let hex = hex_key(0xab);+ let (key, source) = master_key_from_env(Some(&hex), None, file_must_not_be_read)+ .expect("valid inline key")+ .expect("inline key counts as supplied");+ assert_eq!(key, [0xabu8; KEY_LEN]);+ assert_eq!(source, MASTER_KEY_ENV);+}++#[test]+fn env_inline_key_tolerates_surrounding_whitespace_and_uppercase_hex() {+ let hex = format!(" {}\n", hex_key(0xcd).to_uppercase());+ let (key, _) = master_key_from_env(Some(&hex), None, file_must_not_be_read)+ .expect("trimmed key is valid")+ .expect("supplied");+ assert_eq!(key, [0xcdu8; KEY_LEN]);+}++#[test]+fn env_file_key_is_read_trimmed_and_names_the_path() {+ let hex = hex_key(0x11);+ let (key, source) =+ master_key_from_env(None, Some("/run/secrets/openhuman_master_key"), |path| {+ assert_eq!(path, Path::new("/run/secrets/openhuman_master_key"));+ Ok(format!("{hex}\n"))+ })+ .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}"+ );+}++#[test]+fn unreadable_env_file_is_an_error_that_names_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}");+}++#[test]+fn both_env_sources_set_is_rejected_before_reading_anything() {+ let hex = hex_key(0x22);+ let err = master_key_from_env(Some(&hex), Some("/run/secrets/key"), file_must_not_be_read)+ .expect_err("ambiguous configuration must be rejected");+ assert!(+ err.contains(MASTER_KEY_ENV) && err.contains(MASTER_KEY_FILE_ENV),+ "{err}"+ );+}++#[test]+fn malformed_env_key_is_rejected_without_leaking_the_value() {+ let too_short = "abcd";+ let err = master_key_from_env(Some(too_short), None, file_must_not_be_read)+ .expect_err("wrong length is rejected");+ assert!(err.contains("expected 64 hex characters, got 4"), "{err}");++ let not_hex = "zz".repeat(KEY_LEN);+ let err = master_key_from_env(Some(¬_hex), None, file_must_not_be_read)+ .expect_err("non-hex is rejected");+ assert!(err.contains("not valid hex"), "{err}");+ assert!(+ !err.contains(¬_hex),+ "error must not echo the value: {err}"+ );++ // Right character count, wrong bytes: must be rejected, not panic in the+ // byte-sliced hex decoder.+ let non_ascii = "é".repeat(KEY_LEN * 2);+ let err = master_key_from_env(Some(&non_ascii), None, file_must_not_be_read)+ .expect_err("non-ASCII is rejected");+ assert!(err.contains("not valid hex"), "{err}");++ // The same validation applies to a file's contents.+ let err = master_key_from_env(None, Some("/run/secrets/key"), |_| Ok("0123".to_string()))+ .expect_err("short file contents are rejected");+ assert!(+ err.contains(MASTER_KEY_FILE_ENV) && err.contains("got 4"),+ "{err}"+ );+}++#[test]+fn empty_env_values_fall_through_to_the_keychain() {+ assert!(master_key_from_env(None, None, file_must_not_be_read)+ .expect("nothing set is fine")+ .is_none());+ assert!(+ master_key_from_env(Some(""), Some(" "), file_must_not_be_read)+ .expect("empty values count as unset")+ .is_none()+ );+}++#[test]+fn read_master_key_file_returns_contents_and_reports_a_missing_file() {+ let tmp = tempfile::TempDir::new().unwrap();+ let path = tmp.path().join("master.key");+ std::fs::write(&path, format!("{}\n", hex_key(0x33))).unwrap();++ let contents = read_master_key_file(&path).expect("readable file");+ assert_eq!(contents.trim(), hex_key(0x33));++ let err = read_master_key_file(&tmp.path().join("missing.key")).expect_err("missing file");+ assert!(err.contains("cannot read master key file"), "{err}");+}++#[cfg(unix)]+#[test]+fn read_master_key_file_accepts_a_group_readable_secret_mount() {+ // Docker secrets are mounted 0444 and Kubernetes secret volumes 0644:+ // permissive modes are warned about, never refused.+ use std::os::unix::fs::PermissionsExt;+ let tmp = tempfile::TempDir::new().unwrap();+ let path = tmp.path().join("master.key");+ std::fs::write(&path, hex_key(0x44)).unwrap();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();++ let contents = read_master_key_file(&path).expect("permissive mode is accepted");+ assert_eq!(contents, hex_key(0x44));+}++#[test]+fn parse_master_key_hex_round_trips_an_encoded_key() {+ let key_bytes = crypto::generate_random_bytes(KEY_LEN);+ let parsed = parse_master_key_hex(&crypto::hex_encode(&key_bytes)).expect("valid");+ assert_eq!(parsed.as_slice(), key_bytes.as_slice());+}diff --git a/gitbooks/features/cloud-deploy.md b/gitbooks/features/cloud-deploy.mdindex 80c04b75e3..1ac27548dd 100644--- a/gitbooks/features/cloud-deploy.md+++ b/gitbooks/features/cloud-deploy.md@@ -114,14 +114,16 @@ URL with the typed token and reports `Connected ✓` / `Auth failed` /## What you need before you start-| Setting | Required | Notes |-| ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------- |-| `OPENHUMAN_CORE_TOKEN` | yes | Bearer token clients send to `/rpc`. Generate with `openssl rand -hex 32`. **Anyone with this token can drive the core.** |-| `BACKEND_URL` | yes | Tinyhumans backend the core talks to (`https://api.tinyhumans.ai` for prod). |-| `OPENHUMAN_APP_ENV` | no | `production` or `staging`. Defaults to `production`. |-| `OPENHUMAN_CORE_HOST` | no | Defaults to `0.0.0.0` in the container. |-| `OPENHUMAN_CORE_PORT` | no | Defaults to `7788`. |-| `RUST_LOG` | no | `info` is fine; `debug` for triage. |+| Setting | Required | Notes |+| ----------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `OPENHUMAN_CORE_TOKEN` | yes | Bearer token clients send to `/rpc`. Generate with `openssl rand -hex 32`. **Anyone with this token can drive the core.** |+| `BACKEND_URL` | yes | Tinyhumans backend the core talks to (`https://api.tinyhumans.ai` for prod). |+| `OPENHUMAN_APP_ENV` | no | `production` or `staging`. Defaults to `production`. |+| `OPENHUMAN_KEYRING_MASTER_KEY` | no | 64 hex characters (`openssl rand -hex 32`). Master key for the production `encrypted_file` keyring, so a container with no OS keychain can store provider keys encrypted. Inject it from your secret manager like the bearer token; **losing it orphans every stored secret.** |+| `OPENHUMAN_KEYRING_MASTER_KEY_FILE` | no | Path to a file holding the same value, for Docker/Kubernetes secret mounts. Set one of the two, not both. Without either, `encrypted_file` needs an OS keychain. |+| `OPENHUMAN_CORE_HOST` | no | Defaults to `0.0.0.0` in the container. |+| `OPENHUMAN_CORE_PORT` | no | Defaults to `7788`. |+| `RUST_LOG` | no | `info` is fine; `debug` for triage. |Endpoints exposed by the running container: