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
fix(keyring): enforce private master key files
Steven Enamakel0d36c5e670b2
diff --git a/crates/openhuman-core/src/security/keyring/README.md b/crates/openhuman-core/src/security/keyring/README.mdindex ea5cffa180..512dd9b0e4 100644--- a/crates/openhuman-core/src/security/keyring/README.md+++ b/crates/openhuman-core/src/security/keyring/README.md@@ -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 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. A key file any user can read (Kubernetes' default `0644`, Docker's `0444`) is loaded with a `warn` naming the fix (`defaultMode: 0400`); group read alone (`0440`, from a pod `fsGroup`) is not warned about.+- `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. Key files must be owner-readable only (`0400` or `0600`); group/other permissions are rejected.- `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.diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rsindex a487f91e96..52cf952f8b 100644--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs@@ -256,35 +256,26 @@ fn master_key_from_env(/// Reads the file named by [`MASTER_KEY_FILE_ENV`].///-/// On Unix a file readable by any user on the host is accepted but logged at-/// `warn`, with how to tighten it. It is not refused: the deployments this-/// path exists for mount secrets read-only with modes the process cannot-/// change — Docker secrets `0444`, Kubernetes secret volumes `0644` unless-/// `defaultMode` is set — so refusing would break them out of the box.-/// Files writable by other users are refused because another local user could-/// replace the key and orphan the encrypted keyring on the next restart.-/// Group access alone is not warned about: a non-root pod reads a root-owned-/// secret through its `fsGroup`, and kubelet then grants group read, so-/// `defaultMode: 0400` lands as `0440` — the tightest mode that deployment-/// can have. The config loader treats a foreign-owned `0644` config the same-/// way (`config::schema::load`).+/// On Unix a key file must be owner-only readable (`0400` or `0600`). Any+/// group/other permission can expose the key that decrypts the whole store,+/// so it is rejected before the file is read. Container secret mounts must be+/// configured with an owner-only mode and matching uid/gid for the core.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 key_file_mode_is_world_accessible(mode) {- log::warn!(- "[keyring:encrypted_file] master key file ({MASTER_KEY_FILE_ENV}) has \- mode {mode:04o}, so every user on the host can read it; restrict it to \- 0400 or 0600 (Kubernetes: `defaultMode: 0400` on the secret volume; \- Docker Swarm: `mode: 0400` on the secret)"- );+ if key_file_mode_is_private(mode) {+ return Err(format!(+ "master key file ({MASTER_KEY_FILE_ENV}) has insecure permissions \+ {mode:04o}; restrict it to owner-readable 0400 or 0600"+ ));}if key_file_mode_is_other_writable(mode) {return Err(format!(- "master key file ({MASTER_KEY_FILE_ENV}) is writable by other users; + restrict it to a read-only secret mount"+ "master key file ({MASTER_KEY_FILE_ENV}) is writable by other users; \+ restrict it to a read-only secret mount"));}}@@ -292,11 +283,10 @@ fn read_master_key_file(path: &Path) -> Result<String, String> {std::fs::read_to_string(path).map_err(|e| format!("cannot read master key file: {e}"))}-/// Whether a master-key file's permission bits grant anything to "other"-/// users. See [`read_master_key_file`] for why group access is not counted.+/// Whether a master-key file has any group/other permission bits.#[cfg(unix)]-fn key_file_mode_is_world_accessible(mode: u32) -> bool {- mode & 0o007 != 0+fn key_file_mode_is_private(mode: u32) -> bool {+ mode & 0o077 != 0}#[cfg(unix)]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 f03b27810b..11ea8e9780 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@@ -245,6 +245,11 @@ 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();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();+ }let contents = read_master_key_file(&path).expect("readable file");assert_eq!(contents.trim(), hex_key(0x33));@@ -255,17 +260,15 @@ fn read_master_key_file_returns_contents_and_reports_a_missing_file() {#[cfg(unix)]#[test]-fn read_master_key_file_accepts_a_world_readable_secret_mount() {- // Docker secrets are mounted 0444 and Kubernetes secret volumes 0644 by- // default, read-only: permissive modes are warned about, never refused.+fn read_master_key_file_rejects_a_world_readable_secret_mount() {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));+ let err = read_master_key_file(&path).expect_err("world-readable key files are unsafe");+ assert!(err.contains("insecure permissions"), "{err}");}#[cfg(unix)]@@ -278,20 +281,17 @@ fn read_master_key_file_rejects_other_writable_files() {std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o602)).unwrap();let err = read_master_key_file(&path).expect_err("other-writable key files are unsafe");- assert!(err.contains("writable by other users"), "{err}");+ assert!(err.contains("insecure permissions"), "{err}");}#[cfg(unix)]#[test]-fn key_file_warning_covers_default_mounts_but_not_owner_or_fsgroup_modes() {- // Warned: the Kubernetes and Docker defaults, and anything world-accessible.- for mode in [0o644, 0o444, 0o604, 0o666, 0o602] {- assert!(key_file_mode_is_world_accessible(mode), "{mode:04o}");+fn key_file_permissions_require_owner_only_access() {+ for mode in [0o644, 0o444, 0o604, 0o666, 0o602, 0o440, 0o640] {+ assert!(key_file_mode_is_private(mode), "{mode:04o}");}- // Not warned: owner-only, and `defaultMode: 0400` under a pod `fsGroup`,- // which kubelet turns into 0440.- for mode in [0o400, 0o600, 0o440, 0o640] {- assert!(!key_file_mode_is_world_accessible(mode), "{mode:04o}");+ for mode in [0o400, 0o600] {+ assert!(!key_file_mode_is_private(mode), "{mode:04o}");}assert!(key_file_mode_is_other_writable(0o602));assert!(!key_file_mode_is_other_writable(0o644));@@ -360,6 +360,11 @@ 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();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();+ }let _env = crate::config::test_env::EnvVarGuard::locked().without(MASTER_KEY_ENV).with(MASTER_KEY_FILE_ENV, &path);@@ -400,6 +405,11 @@ fn a_secret_written_under_a_configured_key_reads_back_after_a_restart() {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();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&key_path, std::fs::Permissions::from_mode(0o600)).unwrap();+ }let _env = crate::config::test_env::EnvVarGuard::locked().without(MASTER_KEY_ENV).with(MASTER_KEY_FILE_ENV, &key_path);diff --git a/gitbooks/features/cloud-deploy.md b/gitbooks/features/cloud-deploy.mdindex 675a5e8724..e6c07516ac 100644--- a/gitbooks/features/cloud-deploy.md+++ b/gitbooks/features/cloud-deploy.md@@ -488,17 +488,14 @@ need before you start" (#6926). On a release that predates those variables, set`$OPENHUMAN_WORKSPACE/dev-keychain.json` (plaintext, `0600`); put the workspacevolume on encrypted storage and treat the host as the secret boundary.-Mount the key file owner-only. The usual secret mounts are readable by every-user in the container: Kubernetes secret volumes default to `0644` and Docker-secrets to `0444`. The core still loads such a file, because the mount is-read-only and it cannot fix the mode, but it logs a warning at every start.-Restrict it where the mount is declared:+Mount the key file owner-only. The core rejects group- or world-readable files+because any process able to read the file can decrypt the entire keyring.+Restrict the mode where the mount is declared:- Kubernetes: set `defaultMode: 0400` on the secret volume (or `mode: 0400` on- the item) and set `fsGroup` for the non-root core. Kubelet adds group read,- so the file is `0440` and the core can open it. Without `fsGroup` or- equivalent ownership/group access, the root-owned `0400` file is unreadable- by the core and key loading can fail at startup. This mode does not warn.+ the item), and set the secret item's `runAsUser`/`uid` to the core's user.+ Do not use `fsGroup` to grant access: kubelet can turn the file into `0440`,+ which the core rejects.- Docker Swarm: set `mode: 0400` (with `uid`/`gid` for a non-root user) on theservice's secret.- A plain file: `chmod 600` it, owned by the user the core runs as.diff --git a/tests/cli_model_overrides_e2e.rs b/tests/cli_model_overrides_e2e.rsindex 6191775f5f..733346d4af 100644--- a/tests/cli_model_overrides_e2e.rs+++ b/tests/cli_model_overrides_e2e.rs@@ -120,3 +120,57 @@ fn cli_rejects_a_missing_model_value() {assert!(!output.status.success());assert!(String::from_utf8_lossy(&output.stderr).contains("missing value for --model"));}++#[test]+fn core_boot_accepts_a_configured_master_key_from_either_source() {+ let key = "ab".repeat(32);+ let file_dir = tempfile::tempdir().expect("master-key directory");+ let key_path = file_dir.path().join("master.key");+ std::fs::write(&key_path, format!("{key}\n")).expect("write master key");+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&key_path, std::fs::Permissions::from_mode(0o600))+ .expect("restrict master key");+ }++ for (name, value) in [+ ("OPENHUMAN_KEYRING_MASTER_KEY", key.as_str()),+ (+ "OPENHUMAN_KEYRING_MASTER_KEY_FILE",+ key_path.to_str().expect("key path is UTF-8"),+ ),+ ] {+ let workspace = tempfile::tempdir().expect("workspace");+ let output = Command::new(env!("CARGO_BIN_EXE_openhuman-core"))+ .args(["config", "get"])+ .env("OPENHUMAN_APP_ENV", "staging")+ .env("OPENHUMAN_WORKSPACE", workspace.path())+ .env("OPENHUMAN_KEYRING_MASTER_KEY", "")+ .env("OPENHUMAN_KEYRING_MASTER_KEY_FILE", "")+ .env(name, value)+ .output()+ .expect("run OpenHuman core");+ assert!(+ output.status.success(),+ "{name} boot failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ }+}++#[test]+fn core_boot_rejects_a_malformed_configured_master_key() {+ let workspace = tempfile::tempdir().expect("workspace");+ let output = Command::new(env!("CARGO_BIN_EXE_openhuman-core"))+ .args(["config", "get"])+ .env("OPENHUMAN_APP_ENV", "staging")+ .env("OPENHUMAN_WORKSPACE", workspace.path())+ .env("OPENHUMAN_KEYRING_MASTER_KEY", "not-a-key")+ .output()+ .expect("run OpenHuman core");+ assert!(!output.status.success());+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(stderr.contains("OPENHUMAN_KEYRING_MASTER_KEY"), "{stderr}");+ assert!(!stderr.contains("not-a-key"), "{stderr}");+}