Skip to content

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

refactor(keyring): move native providers into RPC hosts

Steven Enamakel4fdbc865a868
diff --git a/.github/workflows/test-reusable.yml b/.github/workflows/test-reusable.yml
index ab899bfeeb..544f8dd46e 100644
--- a/.github/workflows/test-reusable.yml
+++ b/.github/workflows/test-reusable.yml
@@ -232,6 +232,7 @@ jobs:
# `--features` names resolve against the package a command selects;
# naming a gate the package lacks is a hard error.
FEATURES="$(bash scripts/ci/product-features.sh)"
+ CORE_FEATURES="$(bash scripts/ci/product-features.sh --core)"
CLI_FEATURES="${FEATURES},bin-tools"
echo "[test-reusable] feature set: ${FEATURES} (cli: ${CLI_FEATURES})"
@@ -240,12 +241,12 @@ jobs:
# `required-features = ["http-server", "bin-tools"]`, so without it
# `--bins` silently skips it and this lane goes green having compiled
# none of it. Its tests would vanish too, with no error.
- bash scripts/ci-cancel-aware.sh cargo test -p openhuman --lib --features "${FEATURES}"
+ bash scripts/ci-cancel-aware.sh cargo test -p openhuman --lib --features "${CORE_FEATURES}"
# The core binary and developer bins live in the CLI crate.
bash scripts/ci-cancel-aware.sh cargo test -p openhuman-cli --bins --features "${CLI_FEATURES}"
- bash scripts/ci-cancel-aware.sh cargo test -p openhuman --doc --features "${FEATURES}"
- bash scripts/ci-cancel-aware.sh cargo test -p openhuman-embed --doc --features "${FEATURES}"
- RUSTDOCFLAGS="-D warnings" bash scripts/ci-cancel-aware.sh cargo doc -p openhuman-embed --no-deps --features "${FEATURES}"
+ bash scripts/ci-cancel-aware.sh cargo test -p openhuman --doc --features "${CORE_FEATURES}"
+ bash scripts/ci-cancel-aware.sh cargo test -p openhuman-embed --doc --features "${CORE_FEATURES}"
+ RUSTDOCFLAGS="-D warnings" bash scripts/ci-cancel-aware.sh cargo doc -p openhuman-embed --no-deps --features "${CORE_FEATURES}"
node scripts/run-embed-examples.mjs
while IFS= read -r target; do
diff --git a/Cargo.lock b/Cargo.lock
index 9877a4081b..c81edf2381 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4205,7 +4205,6 @@ dependencies = [
"hmac 0.13.0",
"hostname",
"iana-time-zone",
- "keyring",
"lettre",
"libc",
"log",
@@ -4408,6 +4407,8 @@ dependencies = [
"base64 0.22.1",
"chrono",
"futures",
+ "hex",
+ "keyring",
"log",
"once_cell",
"openhuman-tinyhumans",
@@ -4422,6 +4423,7 @@ dependencies = [
"tinyagents-harness",
"tinyagents-session",
"tinyinference-core",
+ "tinystoragedrivers",
"tokio",
"tokio-stream",
"tokio-util",
@@ -4431,6 +4433,7 @@ dependencies = [
"url",
"urlencoding",
"uuid",
+ "zeroize",
]
[[package]]
diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lock
index cd1c237da3..ab60e14a2c 100644
--- a/crates/openhuman-app/Cargo.lock
+++ b/crates/openhuman-app/Cargo.lock
@@ -4230,7 +4230,6 @@ dependencies = [
"hmac 0.13.0",
"hostname",
"iana-time-zone",
- "keyring",
"lettre",
"libc",
"log",
@@ -4406,6 +4405,8 @@ dependencies = [
"base64 0.22.1",
"chrono",
"futures",
+ "hex",
+ "keyring",
"log",
"once_cell",
"openhuman-tinyhumans",
@@ -4417,6 +4418,7 @@ dependencies = [
"tinyagents-harness",
"tinyagents-session",
"tinyinference-core",
+ "tinystoragedrivers",
"tokio",
"tokio-stream",
"tokio-util",
@@ -4424,6 +4426,7 @@ dependencies = [
"url",
"urlencoding",
"uuid",
+ "zeroize",
]
[[package]]
diff --git a/crates/openhuman-app/Cargo.toml b/crates/openhuman-app/Cargo.toml
index 5bac3f34f8..f95fe04bf5 100644
--- a/crates/openhuman-app/Cargo.toml
+++ b/crates/openhuman-app/Cargo.toml
@@ -71,6 +71,7 @@ serde_json = "1"
# embedded JSON-RPC server and `host::desktop`) and `jev` (the Jev-backed
# `tool_search` ranker the product ships).
openhuman-rpc = { path = "../openhuman-rpc", default-features = false, features = [
+ "os-keyring",
"http-client",
"server",
"jev",
diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.toml
index 284c0a9623..1fdff0f154 100644
--- a/crates/openhuman-cli/Cargo.toml
+++ b/crates/openhuman-cli/Cargo.toml
@@ -232,6 +232,10 @@ path = "../../tests/windows_sandbox_env_e2e.rs"
name = "inference_provider_e2e"
path = "../../tests/inference_provider_e2e.rs"
+[[test]]
+name = "keyring_headless_e2e"
+path = "../../tests/keyring_headless_e2e.rs"
+
[[test]]
name = "keyring_secretstore_e2e"
path = "../../tests/keyring_secretstore_e2e.rs"
@@ -348,11 +352,13 @@ wiremock = "0.6"
[features]
langfuse = ["openhuman-rpc/langfuse"]
+os-keyring = ["openhuman-rpc/os-keyring"]
# The contributor set: the core's `[features] default` gates (listed, because
# `openhuman-rpc`'s own default carries only its server and client) plus the
# Jev ranker. The product lanes pass `--features
# "$(scripts/ci/product-features.sh)"`; every product gate name resolves here.
default = [
+ "os-keyring",
"media",
"skills",
"flows",
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index 068bcc2987..f516e94ec4 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -159,7 +159,7 @@ tinyagents-registry = { path = "../../vendor/tinyagents/crates/tinyagents-regist
tinyagents-session = { path = "../../vendor/tinyagents/crates/tinyagents-session", features = ["storage-drivers"] }
# The storage ports and the URL-to-backend facade (`storage` domain). No driver
# by default: the `storage-*` features below add them.
-tinystoragedrivers = { path = "../../vendor/tinyagents/vendor/tinystoragedrivers/crates/tinystoragedrivers", default-features = false, features = ["blocking", "secrets", "keyring", "file"] }
+tinystoragedrivers = { path = "../../vendor/tinyagents/vendor/tinystoragedrivers/crates/tinystoragedrivers", default-features = false, features = ["blocking", "secrets", "file"] }
tinyagents-runtime = { path = "../../vendor/tinyagents/crates/tinyagents-runtime" }
tinyagents-orchestration = { path = "../../vendor/tinyagents/crates/tinyagents-orchestration" }
tinyagents-tasks = { path = "../../vendor/tinyagents/crates/tinyagents-tasks" }
@@ -403,7 +403,6 @@ walkdir = "2"
hostname = "0.4.2"
rustls = { version = "0.23", default-features = false, features = ["ring"] }
sysinfo = { version = "0.33", default-features = false, features = ["system"] }
-keyring = { version = "3", features = ["apple-native", "windows-native", "linux-native"] }
lettre = { version = "0.11.22", default-features = false, features = ["builder"], optional = true }
# HTTP server framework for the domain-owned routes (`/v1`, dictation, the MCP
# HTTP transport). Exclusive to the default-ON `http-server`
@@ -627,9 +626,8 @@ langfuse = ["tinyagents-harness/langfuse"]
# `storage-sqlite` is in the contributor set and the product: the small
# desktop stores (approvals, devices, notifications, task sources) keep their
# rows in it by default. `storage-mongodb` is in neither; a cloud build turns
-# it on. `storage-keyring` does not exist: the only tinystoragedrivers
-# `keyring` gate is `KeyringSecrets`, which the core does not use (its OS
-# keychain access is the `keyring` crate in `security/keyring`).
+# it on. OS keychain support belongs to openhuman-rpc's `os-keyring` feature,
+# not the core or its storage-driver feature set.
storage-sqlite = ["tinystoragedrivers/sqlite"]
storage-mongodb = ["tinystoragedrivers/mongodb"]
# Always on (the dependency enables `file`); kept so existing feature lists
diff --git a/crates/openhuman-core/src/core/runtime/context.rs b/crates/openhuman-core/src/core/runtime/context.rs
index 323a18ef8e..80e0fc6fc5 100644
--- a/crates/openhuman-core/src/core/runtime/context.rs
+++ b/crates/openhuman-core/src/core/runtime/context.rs
@@ -175,6 +175,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).
+ if let Some(config) = &preloaded_config {
+ crate::security::keyring::init_workspace(&config.workspace_dir);
+ }
crate::security::keyring::init_master_key().map_err(anyhow::Error::msg)?;
// 4. Seed the per-process RPC bearer. `Fixed` seeds the in-memory value
diff --git a/crates/openhuman-core/src/security/credentials/credential_ref.rs b/crates/openhuman-core/src/security/credentials/credential_ref.rs
index 996aba64f5..d4173cc0d8 100644
--- a/crates/openhuman-core/src/security/credentials/credential_ref.rs
+++ b/crates/openhuman-core/src/security/credentials/credential_ref.rs
@@ -197,7 +197,6 @@ pub fn preflight(
fn keyring_error_kind(e: &keyring::KeyringError) -> &'static str {
use keyring::KeyringError as E;
match e {
- E::Os { .. } => "os-backend",
E::InvalidUtf8 { .. } => "invalid-utf8",
E::Crypto(_) => "crypto",
E::VerifyFailed { .. }
diff --git a/crates/openhuman-core/src/security/credentials/credential_ref_tests.rs b/crates/openhuman-core/src/security/credentials/credential_ref_tests.rs
index b6b53aec14..dd34528a4a 100644
--- a/crates/openhuman-core/src/security/credentials/credential_ref_tests.rs
+++ b/crates/openhuman-core/src/security/credentials/credential_ref_tests.rs
@@ -288,13 +288,7 @@ fn keyring_error_kinds_are_fixed_labels_that_carry_no_key() {
let invalid_utf8 = String::from_utf8(vec![0xff]).expect_err("0xff is not utf-8");
let cases: Vec<(KeyringError, &str)> = vec![
- (
- KeyringError::Os {
- key: SECRET_NAME.to_string(),
- source: ::keyring::Error::NoEntry,
- },
- "os-backend",
- ),
+ (KeyringError::Backend(SECRET_NAME.to_string()), "backend"),
(
KeyringError::InvalidUtf8 {
key: SECRET_NAME.to_string(),
diff --git a/crates/openhuman-core/src/security/keyring/README.md b/crates/openhuman-core/src/security/keyring/README.md
index 78a8830ef2..bb431b009f 100644
--- a/crates/openhuman-core/src/security/keyring/README.md
+++ b/crates/openhuman-core/src/security/keyring/README.md
@@ -1,15 +1,15 @@
# keyring
-OS-keychain-backed secret storage with pluggable test and debug backends, plus a ChaCha20-Poly1305 encrypted secret store for config-field encryption. This is an infrastructure domain: it has no RPC controllers, no agent tools, and no event-bus subscribers. It provides a namespaced, user-scoped `get`/`set`/`delete` interface over a backend selected once per process, and a separate `SecretStore` type that other domains use to encrypt and decrypt secret values stored in config. All keys are scoped under a `user_id` so multiple users coexist without collision; the backend entry key format is `"{user_id}:{logical_key}"`.
+Host-installable secret storage with an encrypted-file default, plus a ChaCha20-Poly1305 encrypted secret store for config-field encryption. This is an infrastructure domain: it has no RPC controllers, no agent tools, and no event-bus subscribers. It provides a namespaced, user-scoped `get`/`set`/`delete` interface over a backend selected from a host install slot or cached per process, and a separate `SecretStore` type that other domains use to encrypt and decrypt secret values stored in config. All keys are scoped under a `user_id` so multiple users coexist without collision; the backend entry key format is `"{user_id}:{logical_key}"`.
## Responsibilities
- Provide `get` / `set` / `delete` / `get_or_create_random` over a process-global secret-storage backend.
-- Select the backend exactly once at first use (env override, then `cfg(test)`, then staging/prod vs dev) and freeze it in a `OnceLock`.
+- Resolve the host-installed backend first, then an explicit environment override, then the encrypted-file default. Cache the fallback in a `OnceLock`.
- 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 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.
+- 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 a host-installed `MasterKeySource`, then a private workspace key file.
- Migrate the legacy plaintext `dev-keychain.json` into the encrypted `secrets.enc` file on first use.
## Key files
@@ -19,12 +19,12 @@ OS-keychain-backed secret storage with pluggable test and debug backends, plus a
| `crates/openhuman-core/src/security/keyring/mod.rs` | Module docstring and exports only. Documents backend-selection priority and the Linux-headless availability note. Re-exports the public surface. |
| `crates/openhuman-core/src/security/keyring/ops.rs` | Core operations: `get`/`set`/`delete`/`is_available`/`get_or_create_random`/`migrate_from_file`, the `MigrationOutcome` enum, the `namespaced_key` helper, the cached availability probe, and `force_backend_for_test`. |
| `crates/openhuman-core/src/security/keyring/store.rs` | Backend selection and global state. Owns the `WORKSPACE_DIR` and `BACKEND` `OnceLock`s, `init_workspace`, `backend()`, `build_backend()`/`build_backend_at()`, and `workspace_dir_for_file_backend()` path derivation. Also the `cfg(test)`-only `test_scope` module (thread-scoped test workspaces). |
-| `crates/openhuman-core/src/security/keyring/backend.rs` | `KeyringBackend` trait plus `OsBackend` (native keychain through `tinystoragedrivers`' `KeyringSecrets` over the `Blocking` bridge, service name `"openhuman"`), `FileBackend` (plaintext `dev-keychain.json`, test/debug only), and test-only `MockBackend`. |
+| `crates/openhuman-core/src/security/keyring/backend.rs` | `KeyringBackend` trait plus `FileBackend` (plaintext `dev-keychain.json`, test/debug only), and test-only `MockBackend`. |
| `crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs` | `EncryptedFileBackend`: an adapter over `tinystoragedrivers`' `EncryptedFileSecrets` (format and `secrets.enc.lock` unchanged): all secrets in one ChaCha20-Poly1305 `secrets.enc` file keyed by an app master key; `init_master_key`; legacy `dev-keychain.json` migration; corrupt-file quarantine (a desktop policy kept here: the driver fails closed, this adapter moves the file aside as `secrets.enc.corrupt.<ts>` and continues, so a bad file never wedges sign-in). `adapter.rs` holds the shared error mapping and that policy; `fixtures/` holds bytes written by the pre-port code. |
| `crates/openhuman-core/src/security/keyring/encrypted_store.rs` | `SecretStore`: config-field encryption (`enc2:` ChaCha20-Poly1305, legacy `enc:` XOR migration), keychain-backed master key with legacy `.secret_key` file migration, process-wide key cache, Windows ACL repair (`icacls`). |
| `crates/openhuman-core/src/security/keyring/file_store.rs` | Shared secrets-file primitives for both file backends: the cross-process advisory write lock (`lock_for_write`, on a sidecar `<path>.lock`), the `0600` unique-temp-then-rename `write_atomic`, and `quarantine_corrupt`. |
| `crates/openhuman-core/src/security/keyring/crypto.rs` | Shared ChaCha20-Poly1305 helpers (`chacha20_encrypt`/`chacha20_decrypt`), random-byte generation, hex encode/decode. Used by both `encrypted_store` and `encrypted_file_backend`. |
-| `crates/openhuman-core/src/security/keyring/error.rs` | `KeyringError` (thiserror) with variants `Os`/`InvalidUtf8`/`MigrationReadFailed`/`VerifyFailed`/`MigrationDeleteFailed`/`RandomGeneration`/`Crypto`/`Backend`, plus a log-safe `diagnostic()` that preserves the `keyring::Error` variant and `OSStatus`. |
+| `crates/openhuman-core/src/security/keyring/error.rs` | `KeyringError` (thiserror) with variants `InvalidUtf8`/`MigrationReadFailed`/`VerifyFailed`/`MigrationDeleteFailed`/`RandomGeneration`/`Crypto`/`Backend`, plus a log-safe `diagnostic()`; native errors arrive as opaque `Backend` detail. |
| `crates/openhuman-core/src/security/keyring/keyring_tests.rs` | Module tests (backend isolation via `force_backend_for_test`). |
| `crates/openhuman-core/src/security/keyring/store_tests.rs`, [`store_tests_2_tests.rs`](./store_tests_2_tests.rs), [`store_test_scope_tests.rs`](./store_test_scope_tests.rs) | Test-isolation regressions: test builds ignore `OPENHUMAN_WORKSPACE`, production resolution still honours it, scoped workspaces do not share secrets, and a deleted scoped workspace cannot reset the default store. |
| `crates/openhuman-core/src/security/keyring/encrypted_store_tests.rs`, [`encrypted_store_crypto_migration_tests.rs`](./encrypted_store_crypto_migration_tests.rs), [`encrypted_store_key_management_tests.rs`](./encrypted_store_key_management_tests.rs) | `SecretStore` tests (wired via `#[path]` from [`encrypted_store.rs`](./encrypted_store.rs)). |
@@ -34,9 +34,11 @@ OS-keychain-backed secret storage with pluggable test and debug backends, plus a
Re-exported from [`mod.rs`](./mod.rs):
- `KeyringBackend`: backend trait (`get`/`set`/`delete`/`name`).
+- `install_keyring_backend`, `installed_keyring_backend`, `clear_keyring_backend`: host install slot; thread-local in unit tests.
+- `MasterKeySource` (`load`/`store`) and `install_master_key_source`, `installed_master_key_source`, `clear_master_key_source`: host key-source slot, with the same isolation.
- `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. Key files must not be group- or world-writable; read-only group/world access is supported for secret mounts, but any principal able to read the file can decrypt the keyring.
+- `init_master_key`: load the app master key at startup for encrypted storage, 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 host source or `keyring/master.key`. 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 not be group- or world-writable; read-only group/world access is supported for secret mounts, but any principal able to read the file can decrypt the keyring.
- `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.
@@ -55,11 +57,11 @@ None. There is no `bus.rs`, and the module publishes and subscribes to no `Domai
## Persistence
-Secret storage backend, selected once and frozen in a `OnceLock`:
+Secret storage backend: host install slot first, then a cached environment override or default. Native implementations live in `crates/openhuman-rpc/src/keyring/`, behind its `os-keyring` feature.
-- `os` (via `OPENHUMAN_KEYRING_BACKEND=os`): native OS credential store, macOS Keychain, Windows Credential Manager, or Linux Secret Service, under service name `"openhuman"`.
-- `encrypted_file` (default unless development mode or a backend override is explicit): 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` (explicit `OPENHUMAN_APP_ENV=dev`/`development`, `cfg(test)`, or `OPENHUMAN_KEYRING_BACKEND=file`): plaintext JSON `{workspace}/dev-keychain.json`. Not encrypted; test and debug use only.
+- `os` (via `OPENHUMAN_KEYRING_BACKEND=os`): host-installed native OS credential store, macOS Keychain, Windows Credential Manager, or Linux Secret Service, under service name `"openhuman"`.
+- `encrypted_file` (default unless a host backend or environment override is explicit): 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 a host `MasterKeySource`, then `{workspace}/keyring/master.key`. Files are written `0600` on Unix via temp-file plus atomic rename.
+- `file` (explicit `OPENHUMAN_KEYRING_BACKEND=file`): plaintext JSON `{workspace}/dev-keychain.json`. Not encrypted; test and debug use only.
- `mock` (test-only): in-memory `HashMap`.
`SecretStore` additionally manages a master encryption key: keychain-backed (slot `secretstore.master_key`) in normal builds with one-time migration from the legacy `{data_dir}/openhuman/.secret_key` file; the file path is retained only for unit tests. Decoded keys are cached process-wide, keyed by normalized path.
@@ -102,9 +104,9 @@ Discovered consumers (`crate::security::keyring::*`):
## Notes and gotchas
- Backend is frozen on first use in production. Selection order: `OPENHUMAN_KEYRING_BACKEND` (`os`/`file`/`encrypted_file`), then `cfg(test)` gives `file`, then staging/prod gives `encrypted_file`, and dev gives `file`. Once `BACKEND` is set it cannot change for the process lifetime. A process serves one workspace, so this `OnceLock` is a pure cache.
-- Test builds resolve the workspace per thread, not per process. `WORKSPACE_DIR` and `OPENHUMAN_WORKSPACE` are shared by every concurrently running test, so consulting them made the whole test binary share one credential store pinned to whichever workspace won the race. When the winner was a `TempDir` held by a test's env guard, that directory was deleted at the end of that test, and because `FileBackend::read_map` treats a missing file as an empty map, the next write silently reset the store, so unrelated tests read their own freshly-written secrets back as `None`. Under `cfg(test)`, `workspace_dir_for_file_backend()` therefore ignores both and uses `test_scope::current_workspace()`: a thread-local override when a test binds one with `test_scope::ScopedWorkspace`, otherwise a stable per-process directory under the system temp dir. Backends are then cached per resolved directory. Two consequences worth knowing: test runs never read or write the developer's real `~/.openhuman/dev-keychain.json`, and a test that wants a private credential store must use `ScopedWorkspace`, since setting `OPENHUMAN_WORKSPACE` no longer steers the keyring. Production selection is unchanged.
+- Test builds resolve the workspace per thread, not per process. `WORKSPACE_DIR` and `OPENHUMAN_WORKSPACE` are shared by every concurrently running test, so consulting them made the whole test binary share one credential store pinned to whichever workspace won the race. When the winner was a `TempDir` held by a test's env guard, that directory was deleted at the end of that test, and because `FileBackend::read_map` treats a missing file as an empty map, the next write silently reset the store, so unrelated tests read their own freshly-written secrets back as `None`. Under `cfg(test)`, `workspace_dir_for_file_backend()` therefore ignores both and uses `test_scope::current_workspace()`: a thread-local override when a test binds one with `test_scope::ScopedWorkspace`, otherwise a stable per-process directory under the system temp dir. Backends are then cached per resolved directory. Two consequences worth knowing: test runs never read or write the developer's real `~/.openhuman/dev-keychain.json`, and a test that wants a private credential store must use `ScopedWorkspace`, since setting `OPENHUMAN_WORKSPACE` no longer steers the keyring. Production also defaults to encrypted storage.
- Cleaning up historical leakage: `node scripts/prune-dev-keychain.mjs` reports (and with `--apply` removes, after taking a backup) `dev-keychain.json` entries keyed by dead `TempDir` basenames, left behind before the isolation fix. Dry run by default.
-- `is_available()` is cached after the first probe. The probe performs delete/set/get/delete round-trips on the `os` backend; running it per-call triggered repeated macOS permission dialogs and starved frequent pollers. Non-os backends short-circuit to `true`. A failed probe is logged at `warn` because it silently flips `use_keychain` off.
+- `is_available()` is cached after the first probe. The probe performs delete/set/get/delete round-trips on the `os` backend; running it per-call triggered repeated macOS permission dialogs and starved frequent pollers. Plaintext and mock backends short-circuit to `true`; encrypted storage requires an available master key. A failed probe is logged at `warn` because it silently flips `use_keychain` off.
- `is_available()` answers "is the active backend usable", never "are secrets in the OS keychain". Because the file backends short-circuit to `true`, availability says nothing about where secrets are, which is why `keyring_consent::policy::active_mode_for` derives `active_mode` from `backend_name()` and consults availability only for the `os` backend. Deriving it from `is_available()` alone was issue #6076: the shipped staging/production app told users their secrets were in the OS keychain while they were in `{workspace}/secrets.enc`. Consumers that genuinely want the usability answer (wallet guards, snapshot loops) read `available` and are unaffected.
- `force_backend_for_test` panics if `BACKEND` is already initialized. It must run before any keyring call in the same process (dedicated test binary or very top of a test).
- `migrate_from_file` never deletes the source unless the verified write succeeds, so failures are retryable.
@@ -113,7 +115,7 @@ Discovered consumers (`crate::security::keyring::*`):
- Mutations hold a cross-process lock, on `<secrets file>.lock` rather than the secrets file itself, because `write_atomic` replaces the file by rename, so a lock on the old inode would guard nothing. Callers must hold it across the read and the write.
- The `SecretStore` master-key file is write-once. On Windows it survives transient AV-scanner sharing violations via retry/backoff and attempts `icacls` ACL self-repair on permission errors. Decoded keys are cached so repeated decrypts (for example, snapshot polls) hit memory.
- Legacy formats: `SecretStore` migrates `enc:` (XOR) to `enc2:` (ChaCha20-Poly1305) on decrypt. `EncryptedFileBackend` writes `dev-keychain.json` into `secrets.enc`, reads back and verifies the encrypted map, then removes the plaintext source. It also removes older `.json.migrated` copies when their entries match the decrypted store. Invalid or divergent copies remain for manual recovery.
-- Errors never carry secret values, only namespaced keys. `diagnostic()` is safe to log and preserves the underlying `keyring::Error` variant and `OSStatus`.
+- Errors never carry secret values, only namespaced keys. `diagnostic()` is safe to log and preserves opaque backend diagnostics.
## Further reading
diff --git a/crates/openhuman-core/src/security/keyring/adapter.rs b/crates/openhuman-core/src/security/keyring/adapter.rs
index 4f2141b41a..95090efe70 100644
--- a/crates/openhuman-core/src/security/keyring/adapter.rs
+++ b/crates/openhuman-core/src/security/keyring/adapter.rs
@@ -16,28 +16,6 @@ pub(super) fn backend_error(error: StorageError) -> KeyringError {
KeyringError::Backend(format!("secret store: {error}"))
}
-/// A driver error as the [`KeyringError::Os`] the OS-keychain callers (and
-/// the credential-ref error classifier) have always seen. A locked or denied
-/// store keeps its `NoStorageAccess` identity; the driver's error rides along
-/// as the source (it never carries a secret value).
-pub(super) fn os_error(key: &str, error: StorageError) -> KeyringError {
- let source = if error.kind() == ErrorKind::Unavailable {
- keyring::Error::NoStorageAccess(Box::new(error))
- } else {
- keyring::Error::PlatformFailure(Box::new(error))
- };
- KeyringError::Os {
- key: key.to_string(),
- source,
- }
-}
-
-/// Whether the keychain refused access rather than failed: reads and deletes
-/// treat that as "nothing there", as they always have.
-pub(super) fn is_no_access(error: &StorageError) -> bool {
- error.kind() == ErrorKind::Unavailable
-}
-
/// Whether the driver reports the secrets file itself as unreadable
/// (undecryptable under this key, or not the expected JSON).
pub(super) fn is_corruption(error: &StorageError) -> bool {
diff --git a/crates/openhuman-core/src/security/keyring/adapter_tests.rs b/crates/openhuman-core/src/security/keyring/adapter_tests.rs
index dadac19dbc..622f4b3f7c 100644
--- a/crates/openhuman-core/src/security/keyring/adapter_tests.rs
+++ b/crates/openhuman-core/src/security/keyring/adapter_tests.rs
@@ -1,165 +1,8 @@
-//! The keyring backends over the `SecretStore` port: the OS backend against a
-//! persistent fake credential store (never the real keychain), the encrypted
-//! file backend's desktop corruption policy, and the legacy-file import.
-
+//! Encrypted-file corruption and import policy over the secret-store port.
use super::*;
-use std::any::Any;
-use std::collections::HashMap;
-use std::sync::{Arc, Mutex};
-
-use keyring::credential::{Credential, CredentialApi, CredentialBuilderApi};
-use tinystoragedrivers::secrets::{crypto, KeyringSecrets};
-
-use crate::security::keyring::backend::OsBackend;
use crate::security::keyring::encrypted_file_backend::EncryptedFileBackend;
-use crate::security::keyring::KeyringBackend;
-
-type Shared = Arc<Mutex<HashMap<(String, String), Vec<u8>>>>;
-
-/// A credential store shared by every credential the builder makes, so a set
-/// through one `Entry` is visible through the next, as on a real keychain.
-#[derive(Debug, Default)]
-struct FakeBuilder {
- store: Shared,
- locked: bool,
-}
-
-#[derive(Debug)]
-struct FakeCredential {
- store: Shared,
- id: (String, String),
- locked: bool,
-}
-
-impl CredentialBuilderApi for FakeBuilder {
- fn build(
- &self,
- _t: Option<&str>,
- service: &str,
- user: &str,
- ) -> keyring::Result<Box<Credential>> {
- Ok(Box::new(FakeCredential {
- store: Arc::clone(&self.store),
- id: (service.to_string(), user.to_string()),
- locked: self.locked,
- }))
- }
- fn as_any(&self) -> &dyn Any {
- self
- }
-}
-
-fn denied() -> keyring::Error {
- keyring::Error::NoStorageAccess(Box::new(std::io::Error::other("locked")))
-}
-
-impl CredentialApi for FakeCredential {
- fn set_secret(&self, secret: &[u8]) -> keyring::Result<()> {
- if self.locked {
- return Err(denied());
- }
- self.store
- .lock()
- .unwrap()
- .insert(self.id.clone(), secret.to_vec());
- Ok(())
- }
- fn get_secret(&self) -> keyring::Result<Vec<u8>> {
- if self.locked {
- return Err(denied());
- }
- self.store
- .lock()
- .unwrap()
- .get(&self.id)
- .cloned()
- .ok_or(keyring::Error::NoEntry)
- }
- fn delete_credential(&self) -> keyring::Result<()> {
- if self.locked {
- return Err(denied());
- }
- self.store
- .lock()
- .unwrap()
- .remove(&self.id)
- .map(|_| ())
- .ok_or(keyring::Error::NoEntry)
- }
- fn as_any(&self) -> &dyn Any {
- self
- }
-}
-
-/// A persistent fake OS keychain under the production service name.
-pub(crate) fn fake_os_backend() -> OsBackend {
- OsBackend::with_store(KeyringSecrets::with_credential_builder(
- "openhuman",
- Box::new(FakeBuilder::default()),
- ))
-}
-
-fn locked_os_backend() -> OsBackend {
- OsBackend::with_store(KeyringSecrets::with_credential_builder(
- "openhuman",
- Box::new(FakeBuilder {
- locked: true,
- ..Default::default()
- }),
- ))
-}
-
-// ── OsBackend ────────────────────────────────────────────────────────────────
-
-#[test]
-fn os_backend_round_trips_through_the_port() {
- let os = fake_os_backend();
- assert_eq!(os.get("u:k").unwrap(), None);
- os.set("u:k", "v1").unwrap();
- os.set("u:k", "v2").unwrap();
- assert_eq!(os.get("u:k").unwrap().as_deref(), Some("v2"));
- os.delete("u:k").unwrap();
- os.delete("u:k").unwrap();
- assert_eq!(os.get("u:k").unwrap(), None);
- assert_eq!(os.name(), "os");
-}
-
-#[test]
-fn os_backend_keeps_the_credential_layout() {
- // Service `openhuman`, user `{user_id}:{key}`, the password as the value:
- // what the previous direct `keyring::Entry` implementation wrote.
- let builder = FakeBuilder::default();
- let store = Arc::clone(&builder.store);
- let os = OsBackend::with_store(KeyringSecrets::with_credential_builder(
- "openhuman",
- Box::new(builder),
- ));
- os.set("alice:token", "s3cret").unwrap();
- let held = store.lock().unwrap();
- assert_eq!(
- held[&("openhuman".to_string(), "alice:token".to_string())],
- b"s3cret"
- );
-}
-
-#[test]
-fn a_locked_keychain_reads_empty_and_deletes_quietly_but_fails_a_write() {
- let os = locked_os_backend();
- assert_eq!(os.get("u:k").unwrap(), None);
- os.delete("u:k").unwrap();
- let error = os.set("u:k", "v").unwrap_err();
- assert!(
- matches!(
- error,
- KeyringError::Os {
- source: keyring::Error::NoStorageAccess(_),
- ..
- }
- ),
- "{error:?}"
- );
-}
-
+use std::collections::HashMap;
+use tinystoragedrivers::secrets::crypto;
// ── EncryptedFileBackend ─────────────────────────────────────────────────────
const KEY: [u8; 32] = [7; 32];
diff --git a/crates/openhuman-core/src/security/keyring/backend.rs b/crates/openhuman-core/src/security/keyring/backend.rs
index aa5cbc634e..eb40815ccd 100644
--- a/crates/openhuman-core/src/security/keyring/backend.rs
+++ b/crates/openhuman-core/src/security/keyring/backend.rs
@@ -1,23 +1,8 @@
-//! Backend implementations for the keyring module.
-//!
-//! Two concrete backends are provided:
-//!
-//! - [`OsBackend`]: Wraps the `keyring` crate to use the native OS credential
-//! store (macOS Keychain, Windows Credential Manager, Linux Secret Service).
-//! This is the production backend.
-//!
-//! - [`FileBackend`]: Stores secrets in a plain JSON file at
-//! `{workspace}/dev-keychain.json`. **This file is NOT encrypted** — it is a
-//! test/debug artifact only and must never be used in production.
-//!
-//! Backend selection happens once at first use (see [`super::selected_backend`]).
+//! Host-installable secret-storage contract and the explicit plaintext debug backend.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
-use tinystoragedrivers::secrets::KeyringSecrets;
-
-use crate::security::keyring::adapter;
use crate::security::keyring::error::KeyringError;
use crate::security::keyring::file_store;
@@ -26,7 +11,7 @@ use crate::security::keyring::file_store;
/// Abstraction over a secret-storage backend.
///
/// All implementations must be `Send + Sync` so they can live inside a
-/// `OnceLock<Box<dyn KeyringBackend>>`.
+/// the host install slot.
pub trait KeyringBackend: Send + Sync {
/// Retrieve a secret. Returns `Ok(None)` when no entry exists.
fn get(&self, namespaced_key: &str) -> Result<Option<String>, KeyringError>;
@@ -38,74 +23,6 @@ pub trait KeyringBackend: Send + Sync {
fn name(&self) -> &'static str;
}
-// ── OsBackend ─────────────────────────────────────────────────────────────────
-
-/// Production backend: the native OS credential store, through
-/// `tinystoragedrivers`' [`KeyringSecrets`] (the `SecretStore` port) over the
-/// synchronous bridge.
-///
-/// The layout is unchanged: service `openhuman`, one credential per
-/// `"{user_id}:{key}"`, so every entry written by the previous direct
-/// `keyring::Entry` implementation reads back.
-pub struct OsBackend {
- store: KeyringSecrets,
-}
-
-const SERVICE_NAME: &str = "openhuman";
-
-impl OsBackend {
- /// The backend over the platform credential store.
- pub fn new() -> Self {
- Self::with_store(KeyringSecrets::new(SERVICE_NAME))
- }
-
- /// The backend over an explicit store (a mock credential builder in tests).
- pub fn with_store(store: KeyringSecrets) -> Self {
- Self { store }
- }
-}
-
-impl Default for OsBackend {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl KeyringBackend for OsBackend {
- fn get(&self, namespaced_key: &str) -> Result<Option<String>, KeyringError> {
- use tinystoragedrivers::secrets::SecretStore as _;
- let (store, name) = (self.store.clone(), namespaced_key.to_string());
- match crate::storage::block_on(async move { store.get(&name).await }) {
- Ok(value) => adapter::utf8(namespaced_key, value),
- // A locked or denied store reads as "nothing there", as before.
- Err(e) if adapter::is_no_access(&e) => Ok(None),
- Err(e) => Err(adapter::os_error(namespaced_key, e)),
- }
- }
-
- fn set(&self, namespaced_key: &str, value: &str) -> Result<(), KeyringError> {
- use tinystoragedrivers::secrets::SecretStore as _;
- let (store, name) = (self.store.clone(), namespaced_key.to_string());
- let value = zeroize::Zeroizing::new(value.as_bytes().to_vec());
- crate::storage::block_on(async move { store.set(&name, &value).await })
- .map_err(|e| adapter::os_error(namespaced_key, e))
- }
-
- fn delete(&self, namespaced_key: &str) -> Result<(), KeyringError> {
- use tinystoragedrivers::secrets::SecretStore as _;
- let (store, name) = (self.store.clone(), namespaced_key.to_string());
- match crate::storage::block_on(async move { store.delete(&name).await.map(|_| ()) }) {
- Ok(()) => Ok(()),
- Err(e) if adapter::is_no_access(&e) => Ok(()),
- Err(e) => Err(adapter::os_error(namespaced_key, e)),
- }
- }
-
- fn name(&self) -> &'static str {
- "os"
- }
-}
-
// ── FileBackend ───────────────────────────────────────────────────────────────
/// Test/debug backend: plain JSON file at `{workspace}/dev-keychain.json`.
@@ -228,7 +145,7 @@ impl KeyringBackend for FileBackend {
// ── MockBackend (test only) ───────────────────────────────────────────────────
-/// In-memory backend used in tests and when `OPENHUMAN_KEYRING_BACKEND=mock`.
+/// In-memory backend used only in unit tests.
#[cfg(test)]
pub struct MockBackend {
store: std::sync::Mutex<HashMap<String, String>>,
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 267fb4a518..536e9df2bb 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
@@ -3,7 +3,7 @@
//! Stores all secrets in a single ChaCha20-Poly1305-encrypted file on disk,
//! keyed by an app-scoped master key loaded once by [`init_master_key`].
//! Headless deployments supply [`MASTER_KEY_ENV`] or [`MASTER_KEY_FILE_ENV`];
-//! otherwise initialization uses the OS keychain and caches the result.
+//! otherwise initialization uses a host source or a workspace key file.
//! The backend avoids repeated OS-keychain prompts in dev-signed macOS builds.
use std::path::{Path, PathBuf};
@@ -19,11 +19,9 @@ use tinystoragedrivers::secrets::EncryptedFileSecrets;
use zeroize::Zeroizing;
#[path = "encrypted_file_backend/key_source.rs"]
-mod key_source;
+pub mod key_source;
use key_source::{env_value, master_key_from_env};
-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
@@ -46,27 +44,28 @@ 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();
-/// Set when [`init_master_key`] found the OS keychain unable to provide the
+/// Set when [`init_master_key`] found the host source unable to provide the
/// key, so storage secrets reuse that outcome instead of retrying the
-/// keychain (and its prompt) on their first operation.
-static KEYCHAIN_UNAVAILABLE: OnceLock<()> = OnceLock::new();
+/// source (and any prompt) on their first operation.
+static HOST_KEY_UNAVAILABLE: OnceLock<()> = OnceLock::new();
// ── Public API for core startup ──────────────────────────────────────────────
/// Initialize the keyring subsystem: set the workspace directory and load
-/// the master encryption key (staging/production only) — from
+/// the master encryption key for encrypted storage — from
/// [`MASTER_KEY_ENV`] or [`MASTER_KEY_FILE_ENV`] when an operator set one,
-/// otherwise from the OS keychain.
+/// otherwise from a host source or `keyring/master.key`.
///
-/// 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
+/// Call this once at core startup before any keyring operations. Explicit
+/// plaintext or OS secret backends skip master-key loading. The result is
+/// cached process-wide; subsequent calls are
/// no-ops. Which source supplied the key is logged at `info`; the key never
/// is.
///
/// # Errors
///
-/// Returns `Err` only when an operator-supplied source ([`MASTER_KEY_ENV`] /
+/// Returns `Err` when the default workspace key cannot be read or created,
+/// or 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
@@ -76,6 +75,7 @@ static KEYCHAIN_UNAVAILABLE: OnceLock<()> = OnceLock::new();
/// 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> {
+ crate::security::keyring::store::validate_backend_selection()?;
// Ensure workspace dir is set for the backend before anything else.
let dir = crate::security::keyring::store::workspace_dir_for_file_backend();
log::info!(
@@ -100,22 +100,22 @@ pub fn init_master_key() -> Result<(), String> {
}
Err(MasterKeyError::Configured(e)) => {
log::error!(
- "[keyring:encrypted_file] operator-supplied master key rejected; refusing \
+ "[keyring:encrypted_file] master key source rejected; refusing \
to start with secrets unreadable. Cause: {e}"
);
Err(e)
}
- Err(MasterKeyError::Keychain(e)) => {
+ Err(MasterKeyError::Host(e)) => {
log::error!(
"[keyring:encrypted_file] master key load FAILED — refusing to mint a \
replacement (that would orphan existing secrets, #3311). Secrets are \
- inaccessible this session and recover once OS keychain access is \
+ inaccessible this session and recover once host key-source access is \
restored. Cause: {e}"
);
// 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);
- let _ = KEYCHAIN_UNAVAILABLE.set(());
+ let _ = HOST_KEY_UNAVAILABLE.set(());
Ok(None)
}
}
@@ -125,7 +125,7 @@ pub fn init_master_key() -> Result<(), String> {
/// The master key that encrypts secrets on a configured storage backend
/// ([`crate::storage::secrets`]): the key [`init_master_key`] loaded when
/// there is one, otherwise the same resolution run once for storage —
-/// [`MASTER_KEY_ENV`] / [`MASTER_KEY_FILE_ENV`] first, then the OS keychain.
+/// [`MASTER_KEY_ENV`] / [`MASTER_KEY_FILE_ENV`] first, then a host source or workspace key file.
///
/// # Errors
///
@@ -142,8 +142,8 @@ pub(crate) fn storage_master_key() -> Result<[u8; KEY_LEN], String> {
// `init_master_key` already tried the keychain this session and it
// failed: reuse that outcome, do not prompt again. (`Ok(None)` alone also
// means "backend needs no key / init skipped", which must still load.)
- if KEYCHAIN_UNAVAILABLE.get().is_some() {
- return Err("OS keychain master key unavailable this session".into());
+ if HOST_KEY_UNAVAILABLE.get().is_some() {
+ return Err("host master key unavailable this session".into());
}
if let Some(key) = STORAGE_MASTER_KEY.get() {
return Ok(*key);
@@ -153,7 +153,7 @@ pub(crate) fn storage_master_key() -> Result<[u8; KEY_LEN], String> {
log::info!("[keyring:storage] master key loaded from {source}");
Ok(*STORAGE_MASTER_KEY.get_or_init(|| key))
}
- Err(MasterKeyError::Configured(_) | MasterKeyError::Keychain(_)) => {
+ Err(MasterKeyError::Configured(_) | MasterKeyError::Host(_)) => {
// Fixed message: the underlying error can carry a path taken
// from `MASTER_KEY_FILE_ENV`.
log::error!("[keyring:storage] master key unavailable");
@@ -184,30 +184,9 @@ fn init_once(
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 host source 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.
-///
-/// Exists solely so the load-vs-mint decision in [`load_or_mint_master_key`]
-/// can be unit-tested against injected `keyring::Error` variants. A real
-/// `keyring::Entry` cannot be exercised non-interactively under `cargo test`
-/// (the first access blocks on a GUI permission prompt), so the decision logic
-/// is split out behind this trait and tested with a fake.
-trait MasterKeyEntry {
- fn get_password(&self) -> Result<String, keyring::Error>;
- fn set_password(&self, value: &str) -> Result<(), keyring::Error>;
-}
-
-impl MasterKeyEntry for keyring::Entry {
- fn get_password(&self) -> Result<String, keyring::Error> {
- keyring::Entry::get_password(self)
- }
- fn set_password(&self, value: &str) -> Result<(), keyring::Error> {
- keyring::Entry::set_password(self, value)
- }
+ Host(String),
}
/// Loads the master key, returning it with a human-readable description of
@@ -232,11 +211,15 @@ fn try_load_master_key() -> Result<([u8; KEY_LEN], String), MasterKeyError> {
{
return Ok(from_env);
}
- let entry = keyring::Entry::new(KEYCHAIN_SERVICE, KEYCHAIN_MASTER_KEY_USERNAME)
- .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)
+ let dir = crate::security::keyring::store::workspace_dir_for_file_backend();
+ if let Some(source) = key_source::installed_master_key_source() {
+ return key_source::load_or_mint_master_key(source.as_ref())
+ .map(|key| (*key, "host master key source".to_string()))
+ .map_err(|e| MasterKeyError::Host(e.to_string()));
+ }
+ key_source::workspace_master_key(&dir)
+ .map(|key| (*key, "workspace keyring/master.key".to_string()))
+ .map_err(|e| MasterKeyError::Configured(e.to_string()))
}
/// Reads the file named by [`MASTER_KEY_FILE_ENV`].
@@ -286,65 +269,12 @@ fn parse_master_key_hex(hex: &str) -> Result<[u8; KEY_LEN], String> {
Ok(key)
}
-/// Load the existing master key, mint a fresh one, or fail safe.
-///
-/// **Only a genuine absence (`NoEntry`) may mint a new key.** Every other error
-/// — access denied, keychain locked, platform failure — returns `Err` WITHOUT
-/// minting or calling `set_password`, leaving the keychain entry untouched.
-///
-/// This is the fix for #3311. A macOS app update can change the binary's
-/// code-signing identity (or the keychain item's ACL trust), so reading the
-/// *existing* master key fails with an access error rather than `NoEntry`. The
-/// previous code conflated the two and minted a brand-new key on access
-/// denial, orphaning every secret encrypted under the old key — a silent
-/// API-key wipe plus disconnected connectors, with no warning. Failing safe
-/// keeps the ciphertext intact so it recovers on the next launch once keychain
-/// access is restored. The catch-all `Err(e)` arm makes this independent of
-/// which exact `keyring` error variant macOS returns on the denial.
-fn load_or_mint_master_key<E: MasterKeyEntry>(entry: &E) -> Result<[u8; KEY_LEN], String> {
- match entry.get_password() {
- Ok(hex_str) => {
- let bytes = crypto::hex_decode(hex_str.trim())?;
- if bytes.len() != KEY_LEN {
- return Err(format!(
- "master key has wrong length ({} bytes, expected {KEY_LEN})",
- bytes.len()
- ));
- }
- let mut key = [0u8; KEY_LEN];
- key.copy_from_slice(&bytes);
- Ok(key)
- }
- Err(keyring::Error::NoEntry) => {
- let key_bytes = crypto::generate_random_bytes(KEY_LEN);
- let hex_value = crypto::hex_encode(&key_bytes);
- entry
- .set_password(&hex_value)
- .map_err(|e| format!("failed to store new master key in keychain: {e}"))?;
-
- let readback = entry
- .get_password()
- .map_err(|e| format!("master key readback failed: {e}"))?;
- if readback.trim() != hex_value {
- return Err("master key write verification failed".to_string());
- }
-
- let mut key = [0u8; KEY_LEN];
- key.copy_from_slice(&key_bytes);
- log::info!(
- "[keyring:encrypted_file] no existing master key — generated and stored a new one"
- );
- Ok(key)
- }
- Err(e) => Err(format!(
- "OS keychain access unavailable; refusing to mint a replacement master key so \
- existing secrets are preserved (#3311): {e}"
- )),
- }
-}
-
/// Get a reference to the cached master key, if available.
+#[cfg(not(test))]
fn master_key() -> Option<&'static [u8; KEY_LEN]> {
+ if MASTER_KEY.get().is_none() {
+ let _ = init_master_key();
+ }
MASTER_KEY
.get()
.and_then(|init| init.as_ref().ok())
@@ -352,7 +282,17 @@ fn master_key() -> Option<&'static [u8; KEY_LEN]> {
}
pub(super) fn master_key_available() -> bool {
- master_key().is_some()
+ #[cfg(test)]
+ {
+ key_source::workspace_master_key(
+ &crate::security::keyring::store::workspace_dir_for_file_backend(),
+ )
+ .is_ok()
+ }
+ #[cfg(not(test))]
+ {
+ master_key().is_some()
+ }
}
// ── Backend ──────────────────────────────────────────────────────────────────
@@ -365,7 +305,7 @@ pub(super) fn master_key_available() -> bool {
///
/// What stays here, because it is a desktop policy and not a storage format:
///
-/// - the master key (env, else OS keychain; see [`init_master_key`]);
+/// - the master key (env, host source, else workspace file; see [`init_master_key`]);
/// - the one-time import of a legacy plaintext `dev-keychain.json`;
/// - **corruption recovery**. The driver fails closed on a file that does not
/// decrypt or parse and leaves it untouched, which is right for a server
@@ -387,6 +327,20 @@ impl EncryptedFileBackend {
}
}
+ fn key(&self) -> Option<Zeroizing<[u8; KEY_LEN]>> {
+ #[cfg(test)]
+ {
+ if let Some(source) = key_source::installed_master_key_source() {
+ return key_source::load_or_mint_master_key(source.as_ref()).ok();
+ }
+ key_source::workspace_master_key(&self.workspace_dir).ok()
+ }
+ #[cfg(not(test))]
+ {
+ master_key().map(|key| Zeroizing::new(*key))
+ }
+ }
+
fn store(&self, key: &[u8; KEY_LEN]) -> EncryptedFileSecrets {
EncryptedFileSecrets::at_path(self.path.clone(), Zeroizing::new(*key))
}
@@ -651,28 +605,28 @@ impl EncryptedFileBackend {
impl KeyringBackend for EncryptedFileBackend {
fn get(&self, namespaced_key: &str) -> Result<Option<String>, KeyringError> {
- let Some(key) = master_key() else {
+ let Some(key) = self.key() else {
return Ok(None);
};
- self.get_with_key(key, namespaced_key)
+ self.get_with_key(&key, namespaced_key)
}
fn set(&self, namespaced_key: &str, value: &str) -> Result<(), KeyringError> {
- let Some(key) = master_key() else {
+ let Some(key) = self.key() else {
return Err(KeyringError::Backend(
"master key unavailable — cannot store secrets".to_string(),
));
};
- self.set_with_key(key, namespaced_key, value)
+ self.set_with_key(&key, namespaced_key, value)
}
fn delete(&self, namespaced_key: &str) -> Result<(), KeyringError> {
use tinystoragedrivers::secrets::SecretStore as _;
- let Some(key) = master_key() else {
+ let Some(key) = self.key() else {
return Ok(());
};
let name = namespaced_key.to_string();
- self.run(key, move |store| {
+ self.run(&key, move |store| {
let name = name.clone();
async move { store.delete(&name).await.map(|_| ()) }
})
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source.rs
index 6fe1841647..ea7f89193c 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source.rs
+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source.rs
@@ -1,9 +1,9 @@
-//! Resolve operator-supplied master keys from environment variables.
+//! Resolve environment, host-provided, and workspace-file master keys.
use super::*;
/// Only `NotPresent` means unset. Invalid Unicode must not fall through to the
-/// OS keychain, where a new key could orphan the encrypted secrets.
+/// next source, where a new key could orphan the encrypted secrets.
pub(super) fn env_value(
name: &str,
raw: Result<String, std::env::VarError>,
@@ -18,7 +18,7 @@ pub(super) fn env_value(
}
/// Resolve an operator-supplied master key from either supported environment
-/// source. Empty values fall through to the OS keychain; errors never include
+/// source. Empty values fall through to the next source; errors never include
/// secret values or paths. `read_file` keeps the decision testable.
pub(super) fn master_key_from_env(
inline: Option<&str>,
@@ -44,3 +44,87 @@ pub(super) fn master_key_from_env(
}
}
}
+
+/// Host-owned source for the encryption key. Only `Ok(None)` means absent;
+/// a locked or denied source must return an error so the core never replaces
+/// an inaccessible key with a new one.
+pub trait MasterKeySource: Send + Sync {
+ fn load(&self) -> Result<Option<Zeroizing<[u8; 32]>>, KeyringError>;
+ fn store(&self, key: &[u8; 32]) -> Result<(), KeyringError>;
+}
+
+#[path = "key_source_install.rs"]
+mod install;
+pub use install::{
+ clear_master_key_source, install_master_key_source, installed_master_key_source,
+};
+
+/// Mint only on genuine absence, and verify the published key before use.
+pub(super) fn load_or_mint_master_key(
+ source: &dyn MasterKeySource,
+) -> Result<Zeroizing<[u8; 32]>, KeyringError> {
+ if let Some(key) = source.load()? {
+ return Ok(key);
+ }
+ let bytes = Zeroizing::new(crypto::generate_random_bytes(KEY_LEN));
+ let mut key = Zeroizing::new([0; KEY_LEN]);
+ key.copy_from_slice(&bytes);
+ source.store(&key)?;
+ let readback = source
+ .load()?
+ .ok_or_else(|| KeyringError::Backend("master key readback missing".into()))?;
+ if *readback != *key {
+ return Err(KeyringError::Backend(
+ "master key write verification failed".into(),
+ ));
+ }
+ Ok(key)
+}
+
+/// Load or durably create the workspace key under the cross-process write
+/// lock. Never replace a malformed or unreadable existing key. The atomic
+/// file writer creates the key with Unix mode `0600` before publication.
+pub(super) fn workspace_master_key(workspace: &Path) -> Result<Zeroizing<[u8; 32]>, KeyringError> {
+ let path = workspace.join("keyring/master.key");
+ let _lock = file_store::lock_for_write(&path)?;
+ match std::fs::symlink_metadata(&path) {
+ Ok(metadata) => {
+ if !metadata.file_type().is_file() {
+ return Err(KeyringError::Backend(
+ "workspace master key must be a regular file".into(),
+ ));
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ if metadata.permissions().mode() & 0o077 != 0 {
+ return Err(KeyringError::Backend(
+ "workspace master key requires permissions 0600".into(),
+ ));
+ }
+ }
+ let text =
+ Zeroizing::new(std::fs::read_to_string(&path).map_err(|_| {
+ KeyringError::Backend("cannot read workspace master key".into())
+ })?);
+ parse_master_key_hex(text.trim())
+ .map(Zeroizing::new)
+ .map_err(KeyringError::Backend)
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ let bytes = Zeroizing::new(crypto::generate_random_bytes(KEY_LEN));
+ let mut key = Zeroizing::new([0; KEY_LEN]);
+ key.copy_from_slice(&bytes);
+ let hex = Zeroizing::new(crypto::hex_encode(&key[..]));
+ file_store::write_atomic(&path, hex.as_bytes())?;
+ Ok(key)
+ }
+ Err(_) => Err(KeyringError::Backend(
+ "cannot inspect workspace master key".into(),
+ )),
+ }
+}
+
+#[cfg(test)]
+#[path = "key_source_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source_install.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source_install.rs
new file mode 100644
index 0000000000..724b578141
--- /dev/null
+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source_install.rs
@@ -0,0 +1,35 @@
+//! Host install slot, process-wide in production and thread-local in unit tests.
+
+use super::MasterKeySource;
+use std::sync::{Arc, RwLock};
+
+#[cfg(not(test))]
+fn slot() -> &'static RwLock<Option<Arc<dyn MasterKeySource>>> {
+ static SLOT: std::sync::OnceLock<RwLock<Option<Arc<dyn MasterKeySource>>>> =
+ std::sync::OnceLock::new();
+ SLOT.get_or_init(|| RwLock::new(None))
+}
+
+#[cfg(test)]
+fn slot() -> &'static RwLock<Option<Arc<dyn MasterKeySource>>> {
+ thread_local! {
+ static SLOT: &'static RwLock<Option<Arc<dyn MasterKeySource>>> =
+ Box::leak(Box::new(RwLock::new(None)));
+ }
+ SLOT.with(|slot| *slot)
+}
+
+/// Install a host provider before core boot, replacing the previous provider.
+pub fn install_master_key_source(provider: Arc<dyn MasterKeySource>) {
+ *slot().write().unwrap_or_else(|e| e.into_inner()) = Some(provider);
+}
+
+/// The provider installed by the host, if any.
+pub fn installed_master_key_source() -> Option<Arc<dyn MasterKeySource>> {
+ slot().read().unwrap_or_else(|e| e.into_inner()).clone()
+}
+
+/// Remove the installed provider. Call only while the core is stopped.
+pub fn clear_master_key_source() {
+ *slot().write().unwrap_or_else(|e| e.into_inner()) = None;
+}
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source_tests.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source_tests.rs
new file mode 100644
index 0000000000..97bc3a5d55
--- /dev/null
+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source_tests.rs
@@ -0,0 +1,185 @@
+use super::*;
+use std::sync::{Arc, Mutex};
+
+#[derive(Default)]
+struct FakeSource {
+ key: Mutex<Option<[u8; 32]>>,
+ writes: Mutex<usize>,
+ denied: bool,
+ wrong_readback: bool,
+}
+impl MasterKeySource for FakeSource {
+ fn load(&self) -> Result<Option<Zeroizing<[u8; 32]>>, KeyringError> {
+ if self.denied {
+ return Err(KeyringError::Backend("access denied".into()));
+ }
+ let key = *self.key.lock().unwrap();
+ Ok(key.map(|key| Zeroizing::new(if self.wrong_readback { [9; 32] } else { key })))
+ }
+ fn store(&self, key: &[u8; 32]) -> Result<(), KeyringError> {
+ *self.writes.lock().unwrap() += 1;
+ *self.key.lock().unwrap() = Some(*key);
+ Ok(())
+ }
+}
+
+#[test]
+fn loads_existing_host_key_without_minting() {
+ let source = FakeSource {
+ key: Mutex::new(Some([0xab; 32])),
+ ..Default::default()
+ };
+ assert_eq!(*load_or_mint_master_key(&source).unwrap(), [0xab; 32]);
+ assert_eq!(*source.writes.lock().unwrap(), 0);
+}
+
+#[test]
+fn mints_and_verifies_only_on_genuine_absence() {
+ let source = FakeSource::default();
+ let first = load_or_mint_master_key(&source).unwrap();
+ assert_ne!(*first, [0; 32]);
+ assert_eq!(*source.writes.lock().unwrap(), 1);
+ assert_eq!(*first, *load_or_mint_master_key(&source).unwrap());
+}
+
+#[test]
+fn unavailable_host_source_never_mints_a_replacement() {
+ let source = FakeSource {
+ denied: true,
+ ..Default::default()
+ };
+ assert!(load_or_mint_master_key(&source).is_err());
+ assert_eq!(*source.writes.lock().unwrap(), 0);
+}
+
+#[test]
+fn host_key_write_requires_matching_readback() {
+ let source = FakeSource {
+ wrong_readback: true,
+ ..Default::default()
+ };
+ assert!(load_or_mint_master_key(&source)
+ .unwrap_err()
+ .to_string()
+ .contains("verification failed"));
+}
+
+#[test]
+fn workspace_key_is_created_private_and_reused() {
+ let dir = tempfile::tempdir().unwrap();
+ let first = workspace_master_key(dir.path()).unwrap();
+ assert_ne!(*first, [0; 32]);
+ let path = dir.path().join("keyring/master.key");
+ assert_eq!(
+ parse_master_key_hex(&std::fs::read_to_string(&path).unwrap()).unwrap(),
+ *first
+ );
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ assert_eq!(
+ std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ }
+ assert_eq!(*first, *workspace_master_key(dir.path()).unwrap());
+}
+
+#[test]
+fn concurrent_workspace_initialization_reuses_one_key() {
+ let dir = tempfile::tempdir().unwrap();
+ let keys = std::thread::scope(|scope| {
+ let handles: Vec<_> = (0..8)
+ .map(|_| scope.spawn(|| workspace_master_key(dir.path()).unwrap()))
+ .collect();
+ handles
+ .into_iter()
+ .map(|handle| handle.join().unwrap())
+ .collect::<Vec<_>>()
+ });
+ assert!(keys.iter().all(|key| **key == *keys[0]));
+}
+
+#[test]
+fn corrupt_workspace_key_is_never_replaced() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("keyring/master.key");
+ file_store::write_atomic(&path, b"invalid-key").unwrap();
+ assert!(workspace_master_key(dir.path()).is_err());
+ assert_eq!(std::fs::read(&path).unwrap(), b"invalid-key");
+}
+
+#[cfg(unix)]
+#[test]
+fn workspace_key_rejects_shared_permissions_and_symlinks() {
+ use std::os::unix::fs::{symlink, PermissionsExt};
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("keyring/master.key");
+ workspace_master_key(dir.path()).unwrap();
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
+ assert!(workspace_master_key(dir.path()).is_err());
+ std::fs::remove_file(&path).unwrap();
+ let other = dir.path().join("other");
+ std::fs::write(&other, "ab".repeat(32)).unwrap();
+ symlink(&other, &path).unwrap();
+ assert!(workspace_master_key(dir.path()).is_err());
+}
+
+#[test]
+fn installed_source_wins_over_workspace_file_and_does_not_leak_threads() {
+ let _env = crate::config::test_env::EnvVarGuard::locked()
+ .without(MASTER_KEY_ENV)
+ .without(MASTER_KEY_FILE_ENV);
+ let dir = tempfile::tempdir().unwrap();
+ let _workspace = crate::security::keyring::store::test_scope::ScopedWorkspace::new(dir.path());
+ install_master_key_source(Arc::new(FakeSource {
+ key: Mutex::new(Some([7; 32])),
+ ..Default::default()
+ }));
+ assert_eq!(super::super::try_load_master_key().unwrap().0, [7; 32]);
+ assert!(!dir.path().join("keyring/master.key").exists());
+ assert!(
+ std::thread::spawn(|| installed_master_key_source().is_none())
+ .join()
+ .unwrap()
+ );
+ clear_master_key_source();
+ assert!(super::super::try_load_master_key().is_ok());
+ assert!(dir.path().join("keyring/master.key").exists());
+}
+
+#[test]
+fn configured_env_key_precedes_host_source_and_errors_never_fall_through() {
+ let _env = crate::config::test_env::EnvVarGuard::locked()
+ .with(MASTER_KEY_ENV, "ab".repeat(32))
+ .without(MASTER_KEY_FILE_ENV);
+ let source = Arc::new(FakeSource {
+ denied: true,
+ ..Default::default()
+ });
+ install_master_key_source(source.clone());
+ assert_eq!(super::super::try_load_master_key().unwrap().0, [0xab; 32]);
+ let _bad = crate::config::test_env::EnvVarGuard::set(MASTER_KEY_ENV, "invalid");
+ assert!(matches!(
+ super::super::try_load_master_key(),
+ Err(super::super::MasterKeyError::Configured(_))
+ ));
+ assert_eq!(*source.writes.lock().unwrap(), 0);
+ clear_master_key_source();
+}
+
+#[test]
+fn denied_host_source_does_not_fall_back_to_workspace_key() {
+ let _env = crate::config::test_env::EnvVarGuard::locked()
+ .without(MASTER_KEY_ENV)
+ .without(MASTER_KEY_FILE_ENV);
+ let dir = tempfile::tempdir().unwrap();
+ let _workspace = crate::security::keyring::store::test_scope::ScopedWorkspace::new(dir.path());
+ install_master_key_source(Arc::new(FakeSource {
+ denied: true,
+ ..Default::default()
+ }));
+ assert!(super::super::try_load_master_key().is_err());
+ assert!(!dir.path().join("keyring/master.key").exists());
+ clear_master_key_source();
+}
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 2322a598ac..24d0bcd53e 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
@@ -1,5 +1,4 @@
use super::*;
-use std::cell::{Cell, RefCell};
use std::collections::HashMap;
fn legacy_secret_map() -> HashMap<String, String> {
@@ -131,121 +130,6 @@ fn older_plaintext_copy_is_removed_only_when_it_matches() {
assert_eq!(std::fs::read(&old_copy).unwrap(), b"invalid JSON");
}
-/// In-memory fake of the keychain entry, so [`load_or_mint_master_key`] can
-/// be exercised without a real OS keychain. `absent_error` is a fn pointer
-/// because `keyring::Error` is not `Clone` — we mint a fresh error per call.
-/// These tests touch no process-wide state (`load_or_mint_master_key` never
-/// reads `MASTER_KEY`), so no OnceLock reset seam is needed.
-struct FakeEntry {
- stored: RefCell<Option<String>>,
- absent_error: fn() -> keyring::Error,
- set_calls: Cell<usize>,
-}
-
-impl FakeEntry {
- fn with_stored(value: &str) -> Self {
- Self {
- stored: RefCell::new(Some(value.to_string())),
- absent_error: || keyring::Error::NoEntry,
- set_calls: Cell::new(0),
- }
- }
- fn absent(err: fn() -> keyring::Error) -> Self {
- Self {
- stored: RefCell::new(None),
- absent_error: err,
- set_calls: Cell::new(0),
- }
- }
-}
-
-impl MasterKeyEntry for FakeEntry {
- fn get_password(&self) -> Result<String, keyring::Error> {
- match &*self.stored.borrow() {
- Some(v) => Ok(v.clone()),
- None => Err((self.absent_error)()),
- }
- }
- fn set_password(&self, value: &str) -> Result<(), keyring::Error> {
- self.set_calls.set(self.set_calls.get() + 1);
- *self.stored.borrow_mut() = Some(value.to_string());
- Ok(())
- }
-}
-
-fn access_denied() -> keyring::Error {
- keyring::Error::NoStorageAccess(Box::new(std::io::Error::new(
- std::io::ErrorKind::PermissionDenied,
- "keychain access denied",
- )))
-}
-
-fn platform_failure() -> keyring::Error {
- keyring::Error::PlatformFailure(Box::new(std::io::Error::other("platform boom")))
-}
-
-#[test]
-fn loads_existing_key_without_minting() {
- let hex = "ab".repeat(KEY_LEN); // 32 bytes of 0xab
- let entry = FakeEntry::with_stored(&hex);
- let key = load_or_mint_master_key(&entry).expect("should load existing key");
- assert_eq!(key, [0xabu8; KEY_LEN]);
- assert_eq!(entry.set_calls.get(), 0, "must not overwrite existing key");
-}
-
-#[test]
-fn mints_only_on_no_entry() {
- let entry = FakeEntry::absent(|| keyring::Error::NoEntry);
- let key = load_or_mint_master_key(&entry).expect("should mint when genuinely absent");
- assert_ne!(key, [0u8; KEY_LEN], "minted key should be random, not zero");
- assert_eq!(
- entry.set_calls.get(),
- 1,
- "should store the freshly minted key"
- );
- // The key is now persisted, so a second load returns the same one.
- assert!(entry.stored.borrow().is_some());
-}
-
-#[test]
-fn does_not_mint_on_access_denied() {
- // The #3311 case: existing key unreadable due to post-update ACL change.
- let entry = FakeEntry::absent(access_denied);
- let result = load_or_mint_master_key(&entry);
- assert!(result.is_err(), "access denial must NOT mint a new key");
- assert_eq!(
- entry.set_calls.get(),
- 0,
- "must never call set_password on access denial — that orphans existing secrets"
- );
- assert!(
- entry.stored.borrow().is_none(),
- "keychain entry left untouched"
- );
-}
-
-#[test]
-fn does_not_mint_on_platform_failure() {
- // Variant-independence: any non-NoEntry error fails safe, not just
- // NoStorageAccess (the exact macOS denial variant is unconfirmed).
- let entry = FakeEntry::absent(platform_failure);
- let result = load_or_mint_master_key(&entry);
- assert!(result.is_err(), "platform failure must NOT mint a new key");
- assert_eq!(entry.set_calls.get(), 0);
-}
-
-#[test]
-fn rejects_wrong_length_key_without_minting() {
- let entry = FakeEntry::with_stored("abcd"); // 2 bytes, not KEY_LEN
- let result = load_or_mint_master_key(&entry);
- assert!(result.is_err(), "wrong-length stored key is an error");
- assert_eq!(
- entry.set_calls.get(),
- 0,
- "must not overwrite on length mismatch"
- );
-}
-
// ── Operator-supplied master key (#6926) ─────────────────────────────────────
fn hex_key(byte: u8) -> String {
diff --git a/crates/openhuman-core/src/security/keyring/error.rs b/crates/openhuman-core/src/security/keyring/error.rs
index 5dba27ff81..f826f79c96 100644
--- a/crates/openhuman-core/src/security/keyring/error.rs
+++ b/crates/openhuman-core/src/security/keyring/error.rs
@@ -1,16 +1,8 @@
use thiserror::Error;
-/// Errors that can occur during OS keychain operations.
+/// Errors that can occur during secret-storage operations.
#[derive(Debug, Error)]
pub enum KeyringError {
- /// The underlying OS keychain returned an error.
- #[error("OS keychain error for key '{key}': {source}")]
- Os {
- key: String,
- #[source]
- source: keyring::Error,
- },
-
/// The keychain returned a value but it was not valid UTF-8.
#[error("Keychain value for key '{key}' is not valid UTF-8: {source}")]
InvalidUtf8 {
@@ -55,19 +47,8 @@ pub enum KeyringError {
}
impl KeyringError {
- /// Diagnostic-rich, log-safe description for `warn!`/`error!` sites.
- ///
- /// The plain `Display` of the `Os` variant collapses to the underlying
- /// `keyring::Error`'s message, which on macOS hides the variant and
- /// `OSStatus` behind strings like "No matching entry found in secure
- /// storage" — exactly the gap that left us unable to tell a locked
- /// keychain from a denied prompt without Console.app. The `Debug` form
- /// preserves the `keyring::Error` variant (`NoEntry` / `PlatformFailure` /
- /// `NoStorageAccess` / …) and its boxed source chain, which for
- /// `PlatformFailure` carries the security-framework `OSStatus`.
- ///
- /// Safe to log: keyring errors never carry secret *values* — only the
- /// namespaced key, which `Display` already logs.
+ /// Log-safe diagnostic detail. Backend implementations must never include
+ /// secret values in errors.
pub fn diagnostic(&self) -> String {
format!("{self:?}")
}
diff --git a/crates/openhuman-core/src/security/keyring/install.rs b/crates/openhuman-core/src/security/keyring/install.rs
new file mode 100644
index 0000000000..32e9aa8c29
--- /dev/null
+++ b/crates/openhuman-core/src/security/keyring/install.rs
@@ -0,0 +1,37 @@
+//! Host install slot, process-wide in production and thread-local in unit tests.
+
+use super::backend::KeyringBackend;
+use std::sync::{Arc, RwLock};
+
+#[cfg(not(test))]
+fn slot() -> &'static RwLock<Option<Arc<dyn KeyringBackend>>> {
+ static SLOT: std::sync::OnceLock<RwLock<Option<Arc<dyn KeyringBackend>>>> =
+ std::sync::OnceLock::new();
+ SLOT.get_or_init(|| RwLock::new(None))
+}
+
+#[cfg(test)]
+fn slot() -> &'static RwLock<Option<Arc<dyn KeyringBackend>>> {
+ thread_local! {
+ static SLOT: &'static RwLock<Option<Arc<dyn KeyringBackend>>> =
+ Box::leak(Box::new(RwLock::new(None)));
+ }
+ SLOT.with(|slot| *slot)
+}
+
+/// Install a host provider before core boot, replacing the previous provider.
+pub fn install_keyring_backend(provider: Arc<dyn KeyringBackend>) {
+ *slot().write().unwrap_or_else(|e| e.into_inner()) = Some(provider);
+ super::reset_availability_cache();
+}
+
+/// The provider installed by the host, if any.
+pub fn installed_keyring_backend() -> Option<Arc<dyn KeyringBackend>> {
+ slot().read().unwrap_or_else(|e| e.into_inner()).clone()
+}
+
+/// Remove the installed provider. Call only while the core is stopped.
+pub fn clear_keyring_backend() {
+ *slot().write().unwrap_or_else(|e| e.into_inner()) = None;
+ super::reset_availability_cache();
+}
diff --git a/crates/openhuman-core/src/security/keyring/keyring_tests.rs b/crates/openhuman-core/src/security/keyring/keyring_tests.rs
index 22bdb16d33..4759d7864a 100644
--- a/crates/openhuman-core/src/security/keyring/keyring_tests.rs
+++ b/crates/openhuman-core/src/security/keyring/keyring_tests.rs
@@ -1,17 +1,7 @@
//! Unit tests for the keyring module.
//!
-//! Tests are structured in three groups:
-//!
-//! 1. **OS backend tests** — use the real OS keychain. On macOS / Windows
-//! these run unconditionally; on Linux they are skipped when the Secret
-//! Service daemon is not available. All test keys are prefixed with
-//! `__openhuman_test__` to make cleanup easy.
-//!
-//! 2. **FileBackend tests** — run against a temp directory. Always run,
-//! no OS dependency.
-//!
-//! 3. **Backend selection tests** — verify that `OPENHUMAN_KEYRING_BACKEND`
-//! is honoured and that the file backend round-trips correctly.
+//! File backends and namespaced operations. Native-keychain tests live with
+//! their host implementation in `openhuman-rpc/src/keyring/`.
use std::io::Write as _;
use tempfile::NamedTempFile;
@@ -20,31 +10,6 @@ use tempfile::TempDir;
use super::backend::{FileBackend, KeyringBackend};
use super::*;
-// ── OS backend helpers ────────────────────────────────────────────────────────
-
-/// Returns true ONLY when the user has explicitly opted into hitting the real
-/// OS keychain by setting `OPENHUMAN_TEST_OS_KEYCHAIN=1`.
-///
-/// Why opt-in instead of probe-first: on macOS, the first `keyring::Entry::set`
-/// from an unsigned/changing debug binary blocks on a GUI permission prompt —
-/// in non-interactive `cargo test` runs (CI, pre-push hook, agent shells) that
-/// hangs the suite indefinitely. We keep `cargo test` defaulting to the
-/// FileBackend path so it never touches the OS keychain.
-fn os_keychain_available() -> bool {
- if std::env::var("OPENHUMAN_TEST_OS_KEYCHAIN").as_deref() != Ok("1") {
- return false;
- }
- let b = backend::OsBackend::new();
- let probe_key = "__openhuman_probe_test__";
- let probe_val = "__probe_ok__";
- if b.set(probe_key, probe_val).is_err() {
- return false;
- }
- let ok = b.get(probe_key).ok().flatten().as_deref() == Some(probe_val);
- let _ = b.delete(probe_key);
- ok
-}
-
// ── FileBackend: round-trip ───────────────────────────────────────────────────
#[test]
@@ -386,56 +351,6 @@ fn file_backend_env_var_explicit_file() {
// ── OS backend tests (skipped when OS keychain unavailable) ───────────────────
-#[test]
-fn os_round_trip_get_set_delete() {
- if !os_keychain_available() {
- eprintln!("skip: OS keychain not available");
- return;
- }
- let b = backend::OsBackend::new();
- let nk = "__openhuman_test__rtgsd:round_trip_key_001";
- let _ = b.delete(nk);
-
- assert!(b.get(nk).unwrap().is_none(), "absent before set");
- b.set(nk, "my_secret_value").unwrap();
- assert_eq!(b.get(nk).unwrap().as_deref(), Some("my_secret_value"));
- b.delete(nk).unwrap();
- assert!(b.get(nk).unwrap().is_none(), "absent after delete");
-}
-
-#[test]
-fn os_delete_nonexistent_is_ok() {
- if !os_keychain_available() {
- eprintln!("skip: OS keychain not available");
- return;
- }
- backend::OsBackend::new()
- .delete("__openhuman_test__del_ne:__nonexistent__")
- .expect("idempotent delete");
-}
-
-#[test]
-fn os_user_id_isolation() {
- if !os_keychain_available() {
- eprintln!("skip: OS keychain not available");
- return;
- }
- let b = backend::OsBackend::new();
- let nk_a = "__openhuman_test__user_a_iso:__shared_key_iso__";
- let nk_b = "__openhuman_test__user_b_iso:__shared_key_iso__";
- let _ = b.delete(nk_a);
- let _ = b.delete(nk_b);
-
- b.set(nk_a, "value_for_a").unwrap();
- b.set(nk_b, "value_for_b").unwrap();
- assert_eq!(b.get(nk_a).unwrap().as_deref(), Some("value_for_a"));
- assert_eq!(b.get(nk_b).unwrap().as_deref(), Some("value_for_b"));
- assert_ne!(b.get(nk_a).unwrap(), b.get(nk_b).unwrap());
-
- let _ = b.delete(nk_a);
- let _ = b.delete(nk_b);
-}
-
// ── get_or_create_random (OS backend — skipped when unavailable) ──────────────
#[test]
@@ -464,65 +379,3 @@ fn get_or_create_random_idempotent_file_backend() {
let second = fb.get(&nk).unwrap().unwrap();
assert_eq!(first, second, "idempotent read-back");
}
-
-// ── is_available probe: idempotency (OS backend only) ─────────────────────────
-
-#[test]
-fn is_available_returns_true_on_repeated_calls_os_backend() {
- // End-to-end: the real `is_available()` must return true on consecutive
- // calls even when the OS backend retains the probe key between runs.
- // Guarded by OPENHUMAN_TEST_OS_KEYCHAIN=1 to avoid blocking CI on a
- // Keychain permission dialog.
- if !os_keychain_available() {
- eprintln!("skip: set OPENHUMAN_TEST_OS_KEYCHAIN=1 to run OS keychain tests");
- return;
- }
- // Use the OsBackend directly to simulate the cross-launch residue.
- let b = backend::OsBackend::new();
- let probe_key = "__probe__:__openhuman_keyring_probe__";
- // Pre-seed to mimic a leftover from a previous app launch.
- let _ = b.set(probe_key, "__probe_value__");
- // `is_available()` must still return true.
- assert!(
- super::ops::is_available(),
- "is_available must return true even with pre-existing probe key in OS keychain"
- );
- // Repeated call should also stay true (exercises the OnceLock cached path).
- assert!(
- super::ops::is_available(),
- "is_available must remain true on repeated calls (cached result)"
- );
- // Cleanup.
- let _ = b.delete(probe_key);
-}
-
-// ── migrate_from_file (via module functions, requires OS keychain or file backend) ──
-
-#[test]
-fn migrate_from_file_happy_path_os() {
- if !os_keychain_available() {
- eprintln!("skip: OS keychain not available");
- return;
- }
- let b = backend::OsBackend::new();
- let user_id = "__openhuman_test__mig_hp";
- let key = "__migrate_key_hp__";
- let nk = format!("{user_id}:{key}");
- let _ = b.delete(&nk);
-
- let mut tmp = NamedTempFile::new().expect("temp file");
- write!(tmp, " migrated_secret_value ").expect("write temp");
- let path = tmp.path().to_path_buf();
- let _ = tmp.keep();
-
- // Test the OsBackend directly.
- let value = std::fs::read_to_string(&path).unwrap();
- let value = value.trim();
- b.set(&nk, value).unwrap();
- assert_eq!(
- b.get(&nk).unwrap().as_deref(),
- Some("migrated_secret_value")
- );
- std::fs::remove_file(&path).unwrap();
- let _ = b.delete(&nk);
-}
diff --git a/crates/openhuman-core/src/security/keyring/mod.rs b/crates/openhuman-core/src/security/keyring/mod.rs
index 6fc6fcbc11..0ce42be221 100644
--- a/crates/openhuman-core/src/security/keyring/mod.rs
+++ b/crates/openhuman-core/src/security/keyring/mod.rs
@@ -1,42 +1,6 @@
-//! Encrypted secret storage with explicit OS-keychain and debug overrides.
-//!
-//! Wraps the [`keyring`] crate (or an explicit file backend override) to provide a
-//! namespaced, user-scoped interface to secret storage:
-//! - **Default**: encrypted file with a master key from the environment or OS keychain
-//! - **Explicit `os` override**: native OS credential store
-//! - **Tests / explicit `file` override**: JSON file at `{workspace}/dev-keychain.json`
-//!
-//! All keys are scoped under a `user_id` parameter so multiple users can
-//! coexist without collision. The backend entry key format is:
-//! `"{user_id}:{logical_key}"`.
-//!
-//! # Backend selection
-//!
-//! The backend is chosen **once** at first use, in this priority order:
-//!
-//! 1. `OPENHUMAN_KEYRING_BACKEND` env var: `"os"` | `"file"` | `"encrypted_file"`.
-//! 2. `cfg!(test)` → `file`.
-//! 3. Explicit `OPENHUMAN_APP_ENV=dev` or `development` → `file`.
-//! 4. Otherwise → `encrypted_file`.
-//!
-//! The selected backend is logged once with `[keyring] backend=<name> ...`.
-//!
-//! # Linux headless note
-//!
-//! On servers or CI without a Secret Service daemon, [`is_available`] returns
-//! `false` when the `os` backend is selected. Callers that opt out of keychain
-//! storage (file-encrypted JSON fallback) check this flag. The `file` backend
-//! always reports as available.
-//!
-//! # File backends hold every secret in one file
-//!
-//! Both file backends keep the whole secret set in a single file, so a `set` of
-//! one key rewrites all of them. More than one process routinely addresses the
-//! same workspace, so that cycle is guarded by the cross-process lock in
-//! [`file_store`] — see that module for the two ways an unguarded cycle destroys
-//! secrets. Under `cfg(test)` the file backends resolve to a per-process scratch
-//! directory rather than any real workspace, so test code cannot reach a
-//! developer's live store.
+//! User-scoped secret storage. Hosts may install a backend before boot.
+//! Otherwise an explicit environment override wins, followed by encrypted-file
+//! storage with an environment, host-provided, or workspace-file master key.
mod adapter;
pub mod backend;
@@ -45,6 +9,7 @@ pub mod encrypted_file_backend;
pub mod encrypted_store;
pub mod error;
pub mod file_store;
+mod install;
pub mod ops;
pub mod store;
@@ -52,8 +17,13 @@ pub mod store;
pub use backend::KeyringBackend;
pub use encrypted_file_backend::init_master_key;
+pub use encrypted_file_backend::key_source::{
+ clear_master_key_source, install_master_key_source, installed_master_key_source,
+ MasterKeySource,
+};
pub use encrypted_store::SecretStore;
pub use error::KeyringError;
+pub use install::{clear_keyring_backend, install_keyring_backend, installed_keyring_backend};
pub use ops::{
backend_name, delete, get, get_or_create_random, is_available, migrate_from_file,
reset_availability_cache, set, MigrationOutcome,
diff --git a/crates/openhuman-core/src/security/keyring/ops.rs b/crates/openhuman-core/src/security/keyring/ops.rs
index 217d567ae3..57790aae10 100644
--- a/crates/openhuman-core/src/security/keyring/ops.rs
+++ b/crates/openhuman-core/src/security/keyring/ops.rs
@@ -249,7 +249,7 @@ fn probe_availability() -> bool {
let b = backend();
if let Some(available) = backend_availability_without_probe(
b.name(),
- super::encrypted_file_backend::master_key_available(),
+ b.name() == "encrypted_file" && super::encrypted_file_backend::master_key_available(),
) {
log::debug!("[keyring] is_available={available} (non-os backend)");
return available;
@@ -449,7 +449,7 @@ pub(crate) fn force_backend_for_test(
b: Box<dyn crate::security::keyring::backend::KeyringBackend>,
) {
use crate::security::keyring::store::BACKEND;
- if BACKEND.set(b).is_err() {
+ if BACKEND.set(std::sync::Arc::from(b)).is_err() {
panic!("force_backend_for_test must be called before BACKEND initialization");
}
}
diff --git a/crates/openhuman-core/src/security/keyring/ops_adoption_tests.rs b/crates/openhuman-core/src/security/keyring/ops_adoption_tests.rs
index 7fd1555277..94641aacba 100644
--- a/crates/openhuman-core/src/security/keyring/ops_adoption_tests.rs
+++ b/crates/openhuman-core/src/security/keyring/ops_adoption_tests.rs
@@ -7,7 +7,7 @@ use std::sync::Arc;
use tinystoragedrivers::secrets::{DerivedKeys, SecretStore as _};
use zeroize::Zeroizing;
-use crate::security::keyring::adapter::tests::fake_os_backend;
+use crate::security::keyring::backend::MockBackend;
use crate::security::keyring::KeyringBackend;
use crate::storage::{MemoryStorage, Scope, StorageBackend};
@@ -44,7 +44,7 @@ fn storage_secrets_in(
#[test]
fn an_os_keyring_secret_is_adopted_into_storage_on_first_read() {
- let os = fake_os_backend();
+ let os = MockBackend::new();
os.set("alice:token", "from-the-os-keychain").unwrap();
let storage = MemoryStorage::new();
let secrets = storage_secrets_in(&storage, "local");
@@ -72,7 +72,7 @@ fn an_os_keyring_secret_is_adopted_into_storage_on_first_read() {
#[test]
fn a_secret_absent_everywhere_stays_absent_and_storage_wins_over_the_os() {
- let os = fake_os_backend();
+ let os = MockBackend::new();
let storage = MemoryStorage::new();
let secrets = storage_secrets_in(&storage, "local");
assert_eq!(
@@ -97,7 +97,7 @@ fn a_secret_absent_everywhere_stays_absent_and_storage_wins_over_the_os() {
#[test]
fn adopted_secrets_do_not_cross_scopes() {
- let os = fake_os_backend();
+ let os = MockBackend::new();
os.set("u:k", "v").unwrap();
let storage = MemoryStorage::new();
get_adopting(storage_secrets_in(&storage, "alice"), "u:k", "k", || {
diff --git a/crates/openhuman-core/src/security/keyring/store.rs b/crates/openhuman-core/src/security/keyring/store.rs
index ba79fd6d8a..a24170910c 100644
--- a/crates/openhuman-core/src/security/keyring/store.rs
+++ b/crates/openhuman-core/src/security/keyring/store.rs
@@ -5,7 +5,7 @@
//! - [`BACKEND`] — the selected backend, initialized on first use.
use std::path::{Path, PathBuf};
-use std::sync::OnceLock;
+use std::sync::{Arc, OnceLock};
use crate::security::keyring::backend::{self, KeyringBackend};
@@ -25,7 +25,7 @@ pub(super) enum BackendKind {
pub(super) static WORKSPACE_DIR: OnceLock<PathBuf> = OnceLock::new();
/// The selected backend, initialized on first use.
-pub(super) static BACKEND: OnceLock<Box<dyn KeyringBackend>> = OnceLock::new();
+pub(super) static BACKEND: OnceLock<Arc<dyn KeyringBackend>> = OnceLock::new();
// ── Initialization ────────────────────────────────────────────────────────────
@@ -47,8 +47,8 @@ pub fn init_workspace(workspace_dir: &Path) {
/// serves exactly one workspace, so the resolved path never changes and the
/// `OnceLock` is a pure cache.
#[cfg(not(test))]
-pub(super) fn backend() -> &'static dyn KeyringBackend {
- BACKEND.get_or_init(build_backend).as_ref()
+pub(super) fn backend() -> Arc<dyn KeyringBackend> {
+ super::installed_keyring_backend().unwrap_or_else(|| BACKEND.get_or_init(build_backend).clone())
}
/// Test builds resolve the backend **per workspace** instead of latching one
@@ -64,29 +64,35 @@ pub(super) fn backend() -> &'static dyn KeyringBackend {
/// [`super::ops::force_backend_for_test`] still pins [`BACKEND`] process-wide
/// and is honoured first.
#[cfg(test)]
-pub(super) fn backend() -> &'static dyn KeyringBackend {
+pub(super) fn backend() -> Arc<dyn KeyringBackend> {
+ if let Some(installed) = super::installed_keyring_backend() {
+ return installed;
+ }
if let Some(existing) = BACKEND.get() {
- return existing.as_ref();
+ return existing.clone();
}
test_scope::backend_for(&workspace_dir_for_file_backend())
}
-pub(super) fn build_backend() -> Box<dyn KeyringBackend> {
+pub(super) fn build_backend() -> Arc<dyn KeyringBackend> {
build_backend_at(&workspace_dir_for_file_backend())
}
/// Build a backend rooted at an explicit directory.
///
/// Split out of [`build_backend`] so test builds can construct one backend per
-/// workspace. Selection priority is unchanged.
-pub(super) fn build_backend_at(path: &Path) -> Box<dyn KeyringBackend> {
+/// workspace. An installed host provider takes precedence.
+pub(super) fn build_backend_at(path: &Path) -> Arc<dyn KeyringBackend> {
+ if let Some(installed) = super::installed_keyring_backend() {
+ return installed;
+ }
let path = path.to_path_buf();
- // Priority 1: explicit env var override.
+ // Explicit override after the host provider: explicit env var override.
if let Ok(env_val) = std::env::var("OPENHUMAN_KEYRING_BACKEND") {
match backend_kind_from_env_value(&env_val) {
Some(BackendKind::Os) => {
log::info!("[keyring] backend=os (OPENHUMAN_KEYRING_BACKEND override)");
- return Box::new(backend::OsBackend::new());
+ return Arc::new(UnavailableOsBackend);
}
Some(BackendKind::File) => {
log::info!(
@@ -94,14 +100,14 @@ pub(super) fn build_backend_at(path: &Path) -> Box<dyn KeyringBackend> {
path.display(),
path.display()
);
- return Box::new(backend::FileBackend::new(&path));
+ return Arc::new(backend::FileBackend::new(&path));
}
Some(BackendKind::EncryptedFile) => {
log::info!(
"[keyring] backend=encrypted_file path={} (OPENHUMAN_KEYRING_BACKEND override)",
path.display()
);
- return Box::new(super::encrypted_file_backend::EncryptedFileBackend::new(
+ return Arc::new(super::encrypted_file_backend::EncryptedFileBackend::new(
&path,
));
}
@@ -114,30 +120,47 @@ pub(super) fn build_backend_at(path: &Path) -> Box<dyn KeyringBackend> {
}
}
- // Priority 2: unit tests → file backend for deterministic isolation.
- if cfg!(test) {
- log::info!("[keyring] backend=file path={} (cfg(test))", path.display());
- return Box::new(backend::FileBackend::new(&path));
+ Arc::new(super::encrypted_file_backend::EncryptedFileBackend::new(
+ &path,
+ ))
+}
+
+const OS_BACKEND_UNAVAILABLE: &str =
+ "OPENHUMAN_KEYRING_BACKEND=os requires a host-installed OS keyring backend";
+
+struct UnavailableOsBackend;
+impl KeyringBackend for UnavailableOsBackend {
+ fn get(&self, _: &str) -> Result<Option<String>, super::KeyringError> {
+ Err(super::KeyringError::Backend(OS_BACKEND_UNAVAILABLE.into()))
+ }
+ fn set(&self, _: &str, _: &str) -> Result<(), super::KeyringError> {
+ Err(super::KeyringError::Backend(OS_BACKEND_UNAVAILABLE.into()))
+ }
+ fn delete(&self, _: &str) -> Result<(), super::KeyringError> {
+ Err(super::KeyringError::Backend(OS_BACKEND_UNAVAILABLE.into()))
+ }
+ fn name(&self) -> &'static str {
+ "unavailable_os"
}
+}
- // Priority 3: encrypt by default, including headless deployments where
- // OPENHUMAN_APP_ENV is unset. Plain files require an explicit dev mode.
- if default_to_encrypted_file(std::env::var("OPENHUMAN_APP_ENV").as_deref().ok()) {
- log::info!("[keyring] backend=encrypted_file path={}", path.display());
- Box::new(super::encrypted_file_backend::EncryptedFileBackend::new(
- &path,
- ))
- } else {
- log::info!(
- "[keyring] backend=file dir={} file={}/dev-keychain.json (dev environment)",
- path.display(),
- path.display()
- );
- Box::new(backend::FileBackend::new(&path))
+pub(super) fn validate_backend_selection() -> Result<(), String> {
+ if super::installed_keyring_backend().is_none()
+ && std::env::var("OPENHUMAN_KEYRING_BACKEND")
+ .ok()
+ .as_deref()
+ .and_then(backend_kind_from_env_value)
+ == Some(BackendKind::Os)
+ {
+ return Err(OS_BACKEND_UNAVAILABLE.into());
}
+ Ok(())
}
pub(super) fn effective_backend_kind() -> BackendKind {
+ if let Some(installed) = super::installed_keyring_backend() {
+ return backend_kind_from_env_value(installed.name()).unwrap_or(BackendKind::Os);
+ }
effective_backend_kind_for(
std::env::var("OPENHUMAN_APP_ENV").as_deref().ok(),
std::env::var("OPENHUMAN_KEYRING_BACKEND").as_deref().ok(),
@@ -146,21 +169,13 @@ pub(super) fn effective_backend_kind() -> BackendKind {
}
fn effective_backend_kind_for(
- app_env: Option<&str>,
+ _app_env: Option<&str>,
backend_override: Option<&str>,
- cfg_test: bool,
+ _cfg_test: bool,
) -> BackendKind {
- if let Some(kind) = backend_override.and_then(backend_kind_from_env_value) {
- return kind;
- }
- if cfg_test {
- return BackendKind::File;
- }
- if default_to_encrypted_file(app_env) {
- BackendKind::EncryptedFile
- } else {
- BackendKind::File
- }
+ backend_override
+ .and_then(backend_kind_from_env_value)
+ .unwrap_or(BackendKind::EncryptedFile)
}
fn backend_kind_from_env_value(value: &str) -> Option<BackendKind> {
@@ -172,10 +187,6 @@ fn backend_kind_from_env_value(value: &str) -> Option<BackendKind> {
}
}
-fn default_to_encrypted_file(app_env: Option<&str>) -> bool {
- !matches!(app_env.map(str::trim), Some("development") | Some("dev"))
-}
-
/// Derive the directory for keyring files (`secrets.enc`, `dev-keychain.json`).
///
/// Uses the registered value from [`init_workspace`] if set; otherwise falls
diff --git a/crates/openhuman-core/src/security/keyring/store_test_scope_tests.rs b/crates/openhuman-core/src/security/keyring/store_test_scope_tests.rs
index 0796b492c5..35ca57875b 100644
--- a/crates/openhuman-core/src/security/keyring/store_test_scope_tests.rs
+++ b/crates/openhuman-core/src/security/keyring/store_test_scope_tests.rs
@@ -1,7 +1,7 @@
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
-use std::sync::OnceLock;
+use std::sync::{Arc, OnceLock};
use parking_lot::Mutex;
@@ -18,7 +18,7 @@ static PROCESS_DEFAULT: OnceLock<PathBuf> = OnceLock::new();
/// One backend per resolved workspace directory.
#[allow(clippy::type_complexity)]
-static BACKENDS: OnceLock<Mutex<HashMap<PathBuf, &'static dyn KeyringBackend>>> = OnceLock::new();
+static BACKENDS: OnceLock<Mutex<HashMap<PathBuf, Arc<dyn KeyringBackend>>>> = OnceLock::new();
/// The keyring workspace for the calling thread.
pub(crate) fn current_workspace() -> PathBuf {
@@ -33,18 +33,19 @@ pub(crate) fn current_workspace() -> PathBuf {
}
/// The backend rooted at `dir`, built once per directory.
-pub(crate) fn backend_for(dir: &Path) -> &'static dyn KeyringBackend {
+pub(crate) fn backend_for(dir: &Path) -> Arc<dyn KeyringBackend> {
let registry = BACKENDS.get_or_init(|| Mutex::new(HashMap::new()));
- if let Some(existing) = registry.lock().get(dir).copied() {
+ if let Some(existing) = registry.lock().get(dir).cloned() {
return existing;
}
// Built outside the registry lock: backend construction can re-enter the
// keyring module, and holding the lock across it would deadlock.
- let candidate: &'static dyn KeyringBackend = Box::leak(build_backend_at(dir));
- *registry
+ let candidate = build_backend_at(dir);
+ registry
.lock()
.entry(dir.to_path_buf())
.or_insert(candidate)
+ .clone()
}
/// Binds the calling thread's keyring workspace for the guard's lifetime.
diff --git a/crates/openhuman-core/src/security/keyring/store_tests.rs b/crates/openhuman-core/src/security/keyring/store_tests.rs
index af37d54589..a66e8a8731 100644
--- a/crates/openhuman-core/src/security/keyring/store_tests.rs
+++ b/crates/openhuman-core/src/security/keyring/store_tests.rs
@@ -102,8 +102,8 @@ fn scoped_workspaces_do_not_share_secrets() {
);
}
- assert!(one.path().join("dev-keychain.json").exists());
- assert!(two.path().join("dev-keychain.json").exists());
+ assert!(one.path().join("secrets.enc").exists());
+ assert!(two.path().join("secrets.enc").exists());
}
/// The exact failure mode that produced the flake: a test binds a temp
diff --git a/crates/openhuman-core/src/security/keyring/store_tests_2_tests.rs b/crates/openhuman-core/src/security/keyring/store_tests_2_tests.rs
index 9572e22597..b9812909a1 100644
--- a/crates/openhuman-core/src/security/keyring/store_tests_2_tests.rs
+++ b/crates/openhuman-core/src/security/keyring/store_tests_2_tests.rs
@@ -41,12 +41,12 @@ fn unset_app_environment_defaults_to_encrypted_file() {
}
#[test]
-fn only_explicit_development_environments_default_to_plain_file() {
+fn development_environments_also_default_to_encrypted_file() {
for app_env in ["dev", "development", " dev "] {
assert_eq!(
effective_backend_kind_for(Some(app_env), None, false),
- BackendKind::File,
- "{app_env} should explicitly select the development default"
+ BackendKind::EncryptedFile,
+ "{app_env} must not implicitly select plaintext storage"
);
}
@@ -58,3 +58,65 @@ fn only_explicit_development_environments_default_to_plain_file() {
);
}
}
+
+#[test]
+fn headless_and_test_hosts_default_to_encrypted_storage() {
+ for app_env in [None, Some("development"), Some("dev")] {
+ for test_build in [false, true] {
+ assert_eq!(
+ effective_backend_kind_for(app_env, None, test_build),
+ BackendKind::EncryptedFile,
+ "a host without an installed backend must use encrypted storage"
+ );
+ }
+ }
+}
+
+#[test]
+fn installed_backend_takes_precedence_and_is_thread_local() {
+ use crate::security::keyring::KeyringBackend;
+ use crate::security::keyring::{self, backend::MockBackend};
+ use std::sync::Arc;
+ let _env = crate::config::test_env::EnvVarGuard::locked().without("OPENHUMAN_KEYRING_BACKEND");
+ let dir = tempfile::tempdir().unwrap();
+ let _workspace = super::test_scope::ScopedWorkspace::new(dir.path());
+ let installed = Arc::new(MockBackend::new());
+ keyring::install_keyring_backend(installed.clone());
+ let backend = super::build_backend_at(dir.path());
+ backend.set("user:key", "host-value").unwrap();
+ assert_eq!(
+ installed.get("user:key").unwrap().as_deref(),
+ Some("host-value")
+ );
+ assert_eq!(keyring::backend_name(), "mock");
+ assert!(keyring::is_available());
+ assert!(
+ !dir.path().join("keyring/master.key").exists(),
+ "probing a host backend must not initialize a file key"
+ );
+ assert!(
+ std::thread::spawn(|| keyring::installed_keyring_backend().is_none())
+ .join()
+ .unwrap()
+ );
+ keyring::clear_keyring_backend();
+ assert_eq!(super::build_backend_at(dir.path()).name(), "encrypted_file");
+}
+
+#[test]
+fn explicit_os_backend_requires_a_host_provider() {
+ let _env =
+ crate::config::test_env::EnvVarGuard::locked().with("OPENHUMAN_KEYRING_BACKEND", "os");
+ let dir = tempfile::tempdir().unwrap();
+ assert!(super::validate_backend_selection()
+ .unwrap_err()
+ .contains("host-installed OS"));
+ let backend = super::build_backend_at(dir.path());
+ assert!(backend
+ .get("user:key")
+ .unwrap_err()
+ .to_string()
+ .contains("host-installed OS"));
+ assert!(backend.set("user:key", "value").is_err());
+ assert!(backend.delete("user:key").is_err());
+}
diff --git a/crates/openhuman-embed/examples/support/mod.rs b/crates/openhuman-embed/examples/support/mod.rs
index cbcf31da33..9623037d8a 100644
--- a/crates/openhuman-embed/examples/support/mod.rs
+++ b/crates/openhuman-embed/examples/support/mod.rs
@@ -378,14 +378,9 @@ where
if offline() {
// Set before starting any worker; fixtures never use operator credentials.
std::env::set_var("OPENHUMAN_WORKSPACE", workspace);
+ std::env::remove_var("OPENHUMAN_KEYRING_MASTER_KEY");
std::env::remove_var("OPENHUMAN_KEYRING_MASTER_KEY_FILE");
std::env::remove_var("OPENHUMAN_KEYRING_BACKEND");
- let key = format!(
- "{}{}",
- uuid::Uuid::new_v4().simple(),
- uuid::Uuid::new_v4().simple()
- );
- std::env::set_var("OPENHUMAN_KEYRING_MASTER_KEY", key);
}
openhuman_embed::process::init_master_key()?;
if offline() {
diff --git a/crates/openhuman-embed/src/host_internals.rs b/crates/openhuman-embed/src/host_internals.rs
index 427dd29659..89018765c8 100644
--- a/crates/openhuman-embed/src/host_internals.rs
+++ b/crates/openhuman-embed/src/host_internals.rs
@@ -207,6 +207,14 @@ pub mod integrations {
/// tinyhumans (credentials for the hosted client) and rpc (server auth,
/// Socket.IO approvals, bind policy).
pub mod security {
+ /// Host-supplied secret storage and encryption-key sources.
+ pub mod keyring {
+ pub use openhuman_core::security::keyring::{
+ clear_keyring_backend, clear_master_key_source, install_keyring_backend,
+ install_master_key_source, installed_keyring_backend, installed_master_key_source,
+ is_available, KeyringBackend, KeyringError, MasterKeySource,
+ };
+ }
pub mod credentials {
pub use openhuman_core::security::credentials::{
channel_credential_provider, AuthService, APP_SESSION_PROVIDER,
@@ -283,8 +291,8 @@ pub mod platform {
pub mod storage {
pub use openhuman_core::storage::{
- block_on_anyhow, clear, configured_url, driver_is_shared, install, installed, open,
- url_from, StorageBackend, STORAGE_URL_VAR,
+ block_on, block_on_anyhow, clear, configured_url, driver_is_shared, install, installed,
+ open, url_from, StorageBackend, STORAGE_URL_VAR,
};
}
diff --git a/crates/openhuman-embed/tests/common/mod.rs b/crates/openhuman-embed/tests/common/mod.rs
index a5c1b2a6a0..292f3d1ae1 100644
--- a/crates/openhuman-embed/tests/common/mod.rs
+++ b/crates/openhuman-embed/tests/common/mod.rs
@@ -63,14 +63,12 @@ pub fn offline_config() -> Config {
/// sub-agent and aborts the whole process, so building it the documented way is
/// both what the test needs and a check that the documented way works.
pub fn runtime() -> tokio::runtime::Runtime {
- // Hosts initialize encryption before an API key is persisted by runtime
- // boot. The runner supplies a disposable master key for headless tests.
- if std::env::var_os("OPENHUMAN_KEYRING_MASTER_KEY").is_some() {
- static KEY_ROOT: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
- let root = KEY_ROOT.get_or_init(|| tempfile::tempdir().expect("fixture key root"));
- std::env::set_var("OPENHUMAN_WORKSPACE", root.path());
- openhuman_embed::process::init_master_key().expect("fixture master key initializes");
- }
+ // Retain one disposable key workspace for the lifetime of this process.
+ // The encrypted backend creates its own key without environment injection.
+ static KEY_ROOT: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
+ let root = KEY_ROOT.get_or_init(|| tempfile::tempdir().expect("fixture key root"));
+ std::env::set_var("OPENHUMAN_WORKSPACE", root.path());
+ openhuman_embed::process::init_master_key().expect("fixture master key initializes");
runtime_without_master_key()
}
diff --git a/crates/openhuman-embed/tests/headless_keys.rs b/crates/openhuman-embed/tests/headless_keys.rs
new file mode 100644
index 0000000000..0ba6d17fd0
--- /dev/null
+++ b/crates/openhuman-embed/tests/headless_keys.rs
@@ -0,0 +1,50 @@
+//! A library host initializes encryption in its supplied workspace without
+//! keyring environment setup or an OS provider.
+
+mod common;
+
+use common::{offline_config, runtime_without_master_key};
+use openhuman_embed::{RuntimeBuilder, ServiceSet, Workspace};
+
+#[test]
+fn embedded_key_initialization_uses_the_supplied_workspace() {
+ std::thread::Builder::new()
+ .stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .spawn(|| {
+ runtime_without_master_key().block_on(async {
+ let root = tempfile::tempdir().unwrap();
+ let mut config = offline_config();
+ config.workspace_dir = root.path().join("workspace");
+ config.config_path = root.path().join("config.toml");
+ let workspace = config.workspace_dir.clone();
+ let runtime = RuntimeBuilder::lean()
+ .workspace(Workspace::Dir(workspace.clone()))
+ .config(config)
+ .services(ServiceSet::none())
+ .build()
+ .await
+ .unwrap();
+ let key = workspace.join("keyring/master.key");
+ assert!(
+ key.is_file(),
+ "master key must live in the supplied workspace"
+ );
+ assert!(
+ !workspace.join("dev-keychain.json").exists(),
+ "the library default must encrypt its secret store"
+ );
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ assert_eq!(
+ std::fs::metadata(key).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ }
+ drop(runtime);
+ })
+ })
+ .expect("test thread")
+ .join()
+ .expect("test thread should not panic");
+}
diff --git a/crates/openhuman-rpc/Cargo.toml b/crates/openhuman-rpc/Cargo.toml
index 22b9ff8fa1..05c3e48cf9 100644
--- a/crates/openhuman-rpc/Cargo.toml
+++ b/crates/openhuman-rpc/Cargo.toml
@@ -12,7 +12,9 @@ publish = false
# hosts). `http-client`, `server` and `session-store` are this crate's own.
[features]
langfuse = ["openhuman-tinyhumans/langfuse"]
-default = ["http-client", "server"]
+default = ["http-client", "server", "os-keyring"]
+# Host-owned OS credential and master-key providers.
+os-keyring = ["dep:keyring", "dep:tinystoragedrivers", "dep:zeroize", "dep:hex"]
# Authenticated HTTP client for reaching a core's `/rpc` endpoint.
http-client = ["dep:reqwest"]
# The core's JSON-RPC server: HTTP router, Socket.IO, and the listener bind.
@@ -20,6 +22,7 @@ http-client = ["dep:reqwest"]
# handlers (the `/v1` inference router, the dictation WebSocket) the router
# mounts.
server = [
+ "os-keyring",
"http-server",
"dep:axum",
"dep:socketioxide",
@@ -75,6 +78,10 @@ scheduler-gate = ["openhuman-tinyhumans/scheduler-gate"]
e2e-test-support = ["openhuman-tinyhumans/e2e-test-support"]
[dependencies]
+keyring = { version = "3", features = ["apple-native", "windows-native", "linux-native"], optional = true }
+tinystoragedrivers = { path = "../../vendor/tinyagents/vendor/tinystoragedrivers/crates/tinystoragedrivers", default-features = false, features = ["secrets", "keyring"], optional = true }
+zeroize = { version = "1", optional = true }
+hex = { version = "0.4", optional = true }
# The only openhuman crate this layer depends on. Core internals the server
# needs come through embed's `#[doc(hidden)]` `__host` list (reached as
# `openhuman_tinyhumans::__host`, which tinyhumans forwards); there is no direct `openhuman-core`
diff --git a/crates/openhuman-rpc/src/host.rs b/crates/openhuman-rpc/src/host.rs
index edec84d5e6..054fe06412 100644
--- a/crates/openhuman-rpc/src/host.rs
+++ b/crates/openhuman-rpc/src/host.rs
@@ -89,20 +89,22 @@ pub fn cli(args: &[String]) -> anyhow::Result<()> {
args.first().map(String::as_str).unwrap_or("<none>"),
args.len()
);
+ // The preflight reads the URL before the dispatcher loads `.env`
+ // itself, so a URL supplied through the dotenv file must be loaded now.
+ if let Err(error) = crate::core_host::core::cli::load_dotenv_for_cli() {
+ log::warn!(
+ "[rpc:host] cli: early dotenv load failed ({error}); a host setting supplied only \
+ in that file will not be seen"
+ );
+ }
+ #[cfg(feature = "os-keyring")]
+ crate::keyring::install();
let mut builder = cli_builder();
if cli_command_uses_storage(args, |namespace| {
// `subsystems` only renders status; it never touches stored state.
namespace != "subsystems"
&& crate::core_host::core::all::cli_handler_for_namespace(namespace).is_some()
}) {
- // The preflight reads the URL before the dispatcher loads `.env`
- // itself, so a URL supplied through the dotenv file must be loaded now.
- if let Err(error) = crate::core_host::core::cli::load_dotenv_for_cli() {
- log::warn!(
- "[rpc:host] cli: early dotenv load failed ({error}); a storage url set only \
- in that file will not be seen"
- );
- }
// A one-shot command reads the same backend the server would: the
// configured storage URL, opened on the core's storage runtime so the
// backend outlives this call. No URL leaves the classic layout alone.
@@ -263,6 +265,8 @@ pub async fn desktop(
shutdown_token: CancellationToken,
ready_tx: tokio::sync::oneshot::Sender<EmbeddedReadySignal>,
) -> anyhow::Result<()> {
+ #[cfg(feature = "os-keyring")]
+ crate::keyring::install();
log::debug!("[rpc:host] desktop options={options:?}");
serve_desktop(desktop_builder(&options), shutdown_token, ready_tx).await
}
@@ -311,6 +315,8 @@ pub fn tui_builder() -> RuntimeBuilder {
/// could not be built.
#[cfg(feature = "session-store")]
pub async fn tui() -> anyhow::Result<openhuman_tinyhumans::embed::Runtime> {
+ #[cfg(feature = "os-keyring")]
+ crate::keyring::install();
log::debug!("[rpc:host] tui: building connected runtime");
let session_store = crate::session_store::provider_for_host().await?;
let runtime = tui_builder()
diff --git a/crates/openhuman-rpc/src/keyring/backend.rs b/crates/openhuman-rpc/src/keyring/backend.rs
new file mode 100644
index 0000000000..834762da04
--- /dev/null
+++ b/crates/openhuman-rpc/src/keyring/backend.rs
@@ -0,0 +1,97 @@
+//! Native OS secret storage, preserving service `openhuman` and `{user}:{key}`.
+
+use crate::core_host::security::keyring::{KeyringBackend, KeyringError};
+use tinystoragedrivers::secrets::KeyringSecrets;
+use tinystoragedrivers::{ErrorKind, StorageError};
+use zeroize::Zeroizing;
+
+// ── OsKeyringBackend ─────────────────────────────────────────────────────────────────
+
+/// Production backend: the native OS credential store, through
+/// `tinystoragedrivers`' [`KeyringSecrets`] (the `SecretStore` port) over the
+/// synchronous bridge.
+///
+/// The layout is unchanged: service `openhuman`, one credential per
+/// `"{user_id}:{key}"`, so every entry written by the previous direct
+/// `keyring::Entry` implementation reads back.
+pub struct OsKeyringBackend {
+ store: KeyringSecrets,
+}
+
+const SERVICE_NAME: &str = "openhuman";
+
+impl OsKeyringBackend {
+ /// The backend over the platform credential store.
+ pub fn new() -> Self {
+ Self::with_store(KeyringSecrets::new(SERVICE_NAME))
+ }
+
+ /// The backend over an explicit store (a mock credential builder in tests).
+ pub fn with_store(store: KeyringSecrets) -> Self {
+ Self { store }
+ }
+}
+
+impl Default for OsKeyringBackend {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl KeyringBackend for OsKeyringBackend {
+ fn get(&self, namespaced_key: &str) -> Result<Option<String>, KeyringError> {
+ use tinystoragedrivers::secrets::SecretStore as _;
+ let (store, name) = (self.store.clone(), namespaced_key.to_string());
+ match crate::core_host::storage::block_on(async move { store.get(&name).await }) {
+ Ok(value) => utf8(namespaced_key, value),
+ // A locked or denied store reads as "nothing there", as before.
+ Err(e) if is_no_access(&e) => Ok(None),
+ Err(e) => Err(os_error(namespaced_key, e)),
+ }
+ }
+
+ fn set(&self, namespaced_key: &str, value: &str) -> Result<(), KeyringError> {
+ use tinystoragedrivers::secrets::SecretStore as _;
+ let (store, name) = (self.store.clone(), namespaced_key.to_string());
+ let value = zeroize::Zeroizing::new(value.as_bytes().to_vec());
+ crate::core_host::storage::block_on(async move { store.set(&name, &value).await })
+ .map_err(|e| os_error(namespaced_key, e))
+ }
+
+ fn delete(&self, namespaced_key: &str) -> Result<(), KeyringError> {
+ use tinystoragedrivers::secrets::SecretStore as _;
+ let (store, name) = (self.store.clone(), namespaced_key.to_string());
+ match crate::core_host::storage::block_on(
+ async move { store.delete(&name).await.map(|_| ()) },
+ ) {
+ Ok(()) => Ok(()),
+ Err(e) if is_no_access(&e) => Ok(()),
+ Err(e) => Err(os_error(namespaced_key, e)),
+ }
+ }
+
+ fn name(&self) -> &'static str {
+ "os"
+ }
+}
+
+fn os_error(_key: &str, error: StorageError) -> KeyringError {
+ KeyringError::Backend(format!("OS keychain: {error}"))
+}
+fn is_no_access(error: &StorageError) -> bool {
+ error.kind() == ErrorKind::Unavailable
+}
+fn utf8(key: &str, value: Option<Zeroizing<Vec<u8>>>) -> Result<Option<String>, KeyringError> {
+ value
+ .map(|bytes| {
+ String::from_utf8(bytes.to_vec()).map_err(|source| KeyringError::InvalidUtf8 {
+ key: key.into(),
+ source,
+ })
+ })
+ .transpose()
+}
+
+#[cfg(test)]
+#[path = "backend_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-rpc/src/keyring/backend_tests.rs b/crates/openhuman-rpc/src/keyring/backend_tests.rs
new file mode 100644
index 0000000000..1c544fd454
--- /dev/null
+++ b/crates/openhuman-rpc/src/keyring/backend_tests.rs
@@ -0,0 +1,261 @@
+use super::*;
+use std::any::Any;
+use std::collections::HashMap;
+use std::io::Write as _;
+use std::sync::{Arc, Mutex};
+use tempfile::NamedTempFile;
+
+use keyring::credential::{Credential, CredentialApi, CredentialBuilderApi};
+use tinystoragedrivers::secrets::{crypto, KeyringSecrets};
+
+use crate::core_host::security::keyring::KeyringBackend;
+
+type Shared = Arc<Mutex<HashMap<(String, String), Vec<u8>>>>;
+
+/// A credential store shared by every credential the builder makes, so a set
+/// through one `Entry` is visible through the next, as on a real keychain.
+#[derive(Debug, Default)]
+struct FakeBuilder {
+ store: Shared,
+ locked: bool,
+}
+
+#[derive(Debug)]
+struct FakeCredential {
+ store: Shared,
+ id: (String, String),
+ locked: bool,
+}
+
+impl CredentialBuilderApi for FakeBuilder {
+ fn build(
+ &self,
+ _t: Option<&str>,
+ service: &str,
+ user: &str,
+ ) -> keyring::Result<Box<Credential>> {
+ Ok(Box::new(FakeCredential {
+ store: Arc::clone(&self.store),
+ id: (service.to_string(), user.to_string()),
+ locked: self.locked,
+ }))
+ }
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+}
+
+fn denied() -> keyring::Error {
+ keyring::Error::NoStorageAccess(Box::new(std::io::Error::other("locked")))
+}
+
+impl CredentialApi for FakeCredential {
+ fn set_secret(&self, secret: &[u8]) -> keyring::Result<()> {
+ if self.locked {
+ return Err(denied());
+ }
+ self.store
+ .lock()
+ .unwrap()
+ .insert(self.id.clone(), secret.to_vec());
+ Ok(())
+ }
+ fn get_secret(&self) -> keyring::Result<Vec<u8>> {
+ if self.locked {
+ return Err(denied());
+ }
+ self.store
+ .lock()
+ .unwrap()
+ .get(&self.id)
+ .cloned()
+ .ok_or(keyring::Error::NoEntry)
+ }
+ fn delete_credential(&self) -> keyring::Result<()> {
+ if self.locked {
+ return Err(denied());
+ }
+ self.store
+ .lock()
+ .unwrap()
+ .remove(&self.id)
+ .map(|_| ())
+ .ok_or(keyring::Error::NoEntry)
+ }
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+}
+
+/// A persistent fake OS keychain under the production service name.
+pub(crate) fn fake_os_backend() -> OsKeyringBackend {
+ OsKeyringBackend::with_store(KeyringSecrets::with_credential_builder(
+ "openhuman",
+ Box::new(FakeBuilder::default()),
+ ))
+}
+
+fn locked_os_backend() -> OsKeyringBackend {
+ OsKeyringBackend::with_store(KeyringSecrets::with_credential_builder(
+ "openhuman",
+ Box::new(FakeBuilder {
+ locked: true,
+ ..Default::default()
+ }),
+ ))
+}
+
+// ── OsKeyringBackend ────────────────────────────────────────────────────────────────
+
+#[test]
+fn os_backend_round_trips_through_the_port() {
+ let os = fake_os_backend();
+ assert_eq!(os.get("u:k").unwrap(), None);
+ os.set("u:k", "v1").unwrap();
+ os.set("u:k", "v2").unwrap();
+ assert_eq!(os.get("u:k").unwrap().as_deref(), Some("v2"));
+ os.delete("u:k").unwrap();
+ os.delete("u:k").unwrap();
+ assert_eq!(os.get("u:k").unwrap(), None);
+ assert_eq!(os.name(), "os");
+}
+
+#[test]
+fn os_backend_keeps_the_credential_layout() {
+ // Service `openhuman`, user `{user_id}:{key}`, the password as the value:
+ // what the previous direct `keyring::Entry` implementation wrote.
+ let builder = FakeBuilder::default();
+ let store = Arc::clone(&builder.store);
+ let os = OsKeyringBackend::with_store(KeyringSecrets::with_credential_builder(
+ "openhuman",
+ Box::new(builder),
+ ));
+ os.set("alice:token", "s3cret").unwrap();
+ let held = store.lock().unwrap();
+ assert_eq!(
+ held[&("openhuman".to_string(), "alice:token".to_string())],
+ b"s3cret"
+ );
+}
+
+#[test]
+fn a_locked_keychain_reads_empty_and_deletes_quietly_but_fails_a_write() {
+ let os = locked_os_backend();
+ assert_eq!(os.get("u:k").unwrap(), None);
+ os.delete("u:k").unwrap();
+ let error = os.set("u:k", "v").unwrap_err();
+ assert!(matches!(error, KeyringError::Backend(_)), "{error:?}");
+}
+
+#[test]
+fn os_round_trip_get_set_delete() {
+ if !os_keychain_available() {
+ eprintln!("skip: OS keychain not available");
+ return;
+ }
+ let b = OsKeyringBackend::new();
+ let nk = "__openhuman_test__rtgsd:round_trip_key_001";
+ let _ = b.delete(nk);
+
+ assert!(b.get(nk).unwrap().is_none(), "absent before set");
+ b.set(nk, "my_secret_value").unwrap();
+ assert_eq!(b.get(nk).unwrap().as_deref(), Some("my_secret_value"));
+ b.delete(nk).unwrap();
+ assert!(b.get(nk).unwrap().is_none(), "absent after delete");
+}
+
+#[test]
+fn os_delete_nonexistent_is_ok() {
+ if !os_keychain_available() {
+ eprintln!("skip: OS keychain not available");
+ return;
+ }
+ OsKeyringBackend::new()
+ .delete("__openhuman_test__del_ne:__nonexistent__")
+ .expect("idempotent delete");
+}
+
+#[test]
+fn os_user_id_isolation() {
+ if !os_keychain_available() {
+ eprintln!("skip: OS keychain not available");
+ return;
+ }
+ let b = OsKeyringBackend::new();
+ let nk_a = "__openhuman_test__user_a_iso:__shared_key_iso__";
+ let nk_b = "__openhuman_test__user_b_iso:__shared_key_iso__";
+ let _ = b.delete(nk_a);
+ let _ = b.delete(nk_b);
+
+ b.set(nk_a, "value_for_a").unwrap();
+ b.set(nk_b, "value_for_b").unwrap();
+ assert_eq!(b.get(nk_a).unwrap().as_deref(), Some("value_for_a"));
+ assert_eq!(b.get(nk_b).unwrap().as_deref(), Some("value_for_b"));
+ assert_ne!(b.get(nk_a).unwrap(), b.get(nk_b).unwrap());
+
+ let _ = b.delete(nk_a);
+ let _ = b.delete(nk_b);
+}
+
+#[test]
+fn availability_probe_handles_a_leftover_os_entry_and_caches_success() {
+ use crate::core_host::security::keyring::{
+ clear_keyring_backend, install_keyring_backend, is_available,
+ };
+ let b = Arc::new(fake_os_backend());
+ let probe_key = "__probe__:__openhuman_keyring_probe__";
+ b.set(probe_key, "__probe_value__").unwrap();
+ install_keyring_backend(b.clone());
+ assert!(is_available());
+ assert_eq!(
+ b.get(probe_key).unwrap(),
+ None,
+ "probe must remove its entry"
+ );
+ assert!(is_available());
+ clear_keyring_backend();
+}
+
+#[test]
+fn migrate_from_file_happy_path_os() {
+ if !os_keychain_available() {
+ eprintln!("skip: OS keychain not available");
+ return;
+ }
+ let b = OsKeyringBackend::new();
+ let user_id = "__openhuman_test__mig_hp";
+ let key = "__migrate_key_hp__";
+ let nk = format!("{user_id}:{key}");
+ let _ = b.delete(&nk);
+
+ let mut tmp = NamedTempFile::new().expect("temp file");
+ write!(tmp, " migrated_secret_value ").expect("write temp");
+ let path = tmp.path().to_path_buf();
+ let _ = tmp.keep();
+
+ // Test the OsBackend directly.
+ let value = std::fs::read_to_string(&path).unwrap();
+ let value = value.trim();
+ b.set(&nk, value).unwrap();
+ assert_eq!(
+ b.get(&nk).unwrap().as_deref(),
+ Some("migrated_secret_value")
+ );
+ std::fs::remove_file(&path).unwrap();
+ let _ = b.delete(&nk);
+}
+
+fn os_keychain_available() -> bool {
+ if std::env::var("OPENHUMAN_TEST_OS_KEYCHAIN").as_deref() != Ok("1") {
+ return false;
+ }
+ let b = OsKeyringBackend::new();
+ let probe_key = "__openhuman_probe_test__";
+ let probe_val = "__probe_ok__";
+ if b.set(probe_key, probe_val).is_err() {
+ return false;
+ }
+ let ok = b.get(probe_key).ok().flatten().as_deref() == Some(probe_val);
+ let _ = b.delete(probe_key);
+ ok
+}
diff --git a/crates/openhuman-rpc/src/keyring/master_key.rs b/crates/openhuman-rpc/src/keyring/master_key.rs
new file mode 100644
index 0000000000..199c21db2f
--- /dev/null
+++ b/crates/openhuman-rpc/src/keyring/master_key.rs
@@ -0,0 +1,74 @@
+//! The desktop master-key entry, with the existing service and account names.
+
+use crate::core_host::security::keyring::{KeyringError, MasterKeySource};
+use zeroize::Zeroizing;
+
+/// Native master-key source. The entry is created lazily, so installing the
+/// provider never prompts or accesses the OS credential store.
+#[derive(Default)]
+pub struct OsMasterKeySource {
+ entry: Option<std::sync::Arc<keyring::Entry>>,
+}
+
+impl OsMasterKeySource {
+ fn entry(&self) -> Result<std::sync::Arc<keyring::Entry>, KeyringError> {
+ if let Some(entry) = &self.entry {
+ return Ok(entry.clone());
+ }
+ keyring::Entry::new("openhuman", "app:master_key")
+ .map(std::sync::Arc::new)
+ .map_err(|error| native_error("OS master key entry", &error))
+ }
+}
+
+// Native errors can contain stored bytes or credential objects. Project only
+// their category into the core's diagnostic string, never their payload.
+fn native_error(context: &str, error: &keyring::Error) -> KeyringError {
+ let reason = match error {
+ keyring::Error::NoEntry => "entry does not exist",
+ keyring::Error::NoStorageAccess(_) => "credential store access denied or unavailable",
+ keyring::Error::PlatformFailure(_) => "platform credential store failure",
+ keyring::Error::BadEncoding(_) => "stored value is not UTF-8",
+ keyring::Error::TooLong(..) => "credential attribute exceeds the platform limit",
+ keyring::Error::Invalid(..) => "invalid credential attribute",
+ keyring::Error::Ambiguous(_) => "multiple matching credentials",
+ _ => "unknown native credential store error",
+ };
+ KeyringError::Backend(format!("{context}: {reason}"))
+}
+
+fn load_entry(entry: &keyring::Entry) -> Result<Option<Zeroizing<[u8; 32]>>, KeyringError> {
+ match entry.get_password() {
+ Ok(value) => {
+ let value = Zeroizing::new(value);
+ let mut key = Zeroizing::new([0; 32]);
+ hex::decode_to_slice(value.trim(), &mut key[..]).map_err(|_| {
+ KeyringError::Backend("OS master key must be 64 hex characters".into())
+ })?;
+ Ok(Some(key))
+ }
+ Err(keyring::Error::NoEntry) => Ok(None),
+ Err(error) => Err(native_error(
+ "OS master key unavailable; refusing to mint a replacement",
+ &error,
+ )),
+ }
+}
+
+impl MasterKeySource for OsMasterKeySource {
+ fn load(&self) -> Result<Option<Zeroizing<[u8; 32]>>, KeyringError> {
+ let entry = self.entry()?;
+ load_entry(&entry)
+ }
+ fn store(&self, key: &[u8; 32]) -> Result<(), KeyringError> {
+ let entry = self.entry()?;
+ let encoded = Zeroizing::new(hex::encode(key));
+ entry
+ .set_password(&encoded)
+ .map_err(|error| native_error("OS master key write", &error))
+ }
+}
+
+#[cfg(test)]
+#[path = "master_key_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-rpc/src/keyring/master_key_tests.rs b/crates/openhuman-rpc/src/keyring/master_key_tests.rs
new file mode 100644
index 0000000000..6609530eec
--- /dev/null
+++ b/crates/openhuman-rpc/src/keyring/master_key_tests.rs
@@ -0,0 +1,88 @@
+use super::*;
+
+fn entry() -> std::sync::Arc<keyring::Entry> {
+ std::sync::Arc::new(keyring::Entry::new_with_credential(Box::new(
+ keyring::mock::MockCredential::default(),
+ )))
+}
+
+fn source(entry: &std::sync::Arc<keyring::Entry>) -> OsMasterKeySource {
+ OsMasterKeySource {
+ entry: Some(entry.clone()),
+ }
+}
+
+#[test]
+fn missing_os_entry_is_the_only_absence() {
+ assert!(source(&entry()).load().unwrap().is_none());
+}
+
+#[test]
+fn existing_os_master_key_keeps_its_value() {
+ let entry = entry();
+ entry.set_password(&"ab".repeat(32)).unwrap();
+ assert_eq!(*source(&entry).load().unwrap().unwrap(), [0xab; 32]);
+}
+
+#[test]
+fn malformed_os_master_key_is_rejected_without_replacement() {
+ let entry = entry();
+ for value in ["abcd".to_string(), "zz".repeat(32), "é".repeat(64)] {
+ entry.set_password(&value).unwrap();
+ assert!(source(&entry).load().is_err());
+ assert_eq!(entry.get_password().unwrap(), value);
+ }
+}
+
+#[test]
+fn denied_and_platform_failed_entries_do_not_read_as_absent() {
+ for error in [
+ keyring::Error::NoStorageAccess(Box::new(std::io::Error::other("denied"))),
+ keyring::Error::PlatformFailure(Box::new(std::io::Error::other("failed"))),
+ ] {
+ let entry = entry();
+ entry
+ .get_credential()
+ .downcast_ref::<keyring::mock::MockCredential>()
+ .unwrap()
+ .set_error(error);
+ assert!(source(&entry).load().is_err());
+ }
+}
+
+#[test]
+fn master_key_source_stores_the_existing_hex_format_and_reads_it_back() {
+ let entry = entry();
+ let source = source(&entry);
+ source.store(&[0xcd; 32]).unwrap();
+ assert_eq!(entry.get_password().unwrap(), "cd".repeat(32));
+ assert_eq!(*source.load().unwrap().unwrap(), [0xcd; 32]);
+}
+
+#[test]
+fn denied_master_key_write_returns_an_error() {
+ let entry = entry();
+ entry
+ .get_credential()
+ .downcast_ref::<keyring::mock::MockCredential>()
+ .unwrap()
+ .set_error(keyring::Error::NoStorageAccess(Box::new(
+ std::io::Error::other("denied"),
+ )));
+ assert!(source(&entry).store(&[1; 32]).is_err());
+}
+
+#[test]
+fn invalid_encoded_master_key_errors_do_not_include_secret_bytes() {
+ let entry = entry();
+ let bytes = b"private-master-key-payload".to_vec();
+ let diagnostic_bytes = format!("{bytes:?}");
+ entry
+ .get_credential()
+ .downcast_ref::<keyring::mock::MockCredential>()
+ .unwrap()
+ .set_error(keyring::Error::BadEncoding(bytes));
+ let error = source(&entry).load().unwrap_err().to_string();
+ assert!(!error.contains(&diagnostic_bytes));
+ assert!(!error.contains("private-master-key-payload"));
+}
diff --git a/crates/openhuman-rpc/src/keyring/mod.rs b/crates/openhuman-rpc/src/keyring/mod.rs
new file mode 100644
index 0000000000..35c1b55481
--- /dev/null
+++ b/crates/openhuman-rpc/src/keyring/mod.rs
@@ -0,0 +1,27 @@
+//! OS keychain providers installed by desktop, CLI and TUI hosts before boot.
+//! Loading the RPC library or serving a SaaS gateway does not install them.
+
+mod backend;
+mod master_key;
+pub use backend::OsKeyringBackend;
+pub use master_key::OsMasterKeySource;
+
+/// Preserve encrypted-file storage by default, with its master key in the OS
+/// keychain. The explicit `os` override installs the native secret backend;
+/// explicit file backends retain their meaning in host boot as well.
+pub fn install() {
+ use crate::core_host::security::keyring::{
+ install_keyring_backend, install_master_key_source, installed_keyring_backend,
+ installed_master_key_source,
+ };
+ use std::sync::Arc;
+ if installed_master_key_source().is_none() {
+ install_master_key_source(Arc::new(OsMasterKeySource::default()));
+ }
+ if installed_keyring_backend().is_none()
+ && std::env::var("OPENHUMAN_KEYRING_BACKEND")
+ .is_ok_and(|v| v.trim().eq_ignore_ascii_case("os"))
+ {
+ install_keyring_backend(Arc::new(OsKeyringBackend::new()));
+ }
+}
diff --git a/crates/openhuman-rpc/src/lib.rs b/crates/openhuman-rpc/src/lib.rs
index 088cffbcb9..e23fb38583 100644
--- a/crates/openhuman-rpc/src/lib.rs
+++ b/crates/openhuman-rpc/src/lib.rs
@@ -71,6 +71,8 @@ mod envelope;
pub mod host;
#[cfg(feature = "server")]
pub mod http_host;
+#[cfg(feature = "os-keyring")]
+pub mod keyring;
mod origin;
#[cfg(feature = "server")]
pub mod server;
diff --git a/crates/openhuman-tui/Cargo.toml b/crates/openhuman-tui/Cargo.toml
index 3ca3711064..2a1bee5b2f 100644
--- a/crates/openhuman-tui/Cargo.toml
+++ b/crates/openhuman-tui/Cargo.toml
@@ -16,7 +16,9 @@ publish = false
# core's whole `default`.
[features]
langfuse = ["openhuman-rpc/langfuse"]
+os-keyring = ["openhuman-rpc/os-keyring"]
default = [
+ "os-keyring",
"crash-reporting",
"media",
"skills",
diff --git a/docs/RELEASE-MANUAL-SMOKE.md b/docs/RELEASE-MANUAL-SMOKE.md
index dfb6c50eab..9238921f6a 100644
--- a/docs/RELEASE-MANUAL-SMOKE.md
+++ b/docs/RELEASE-MANUAL-SMOKE.md
@@ -106,6 +106,8 @@ Use a disposable staging account/workspace and synthetic facts. Keep inference r
### Cross-platform
+- [ ] **Existing desktop secrets survive the keyring host migration (16.1.28)** — Upgrade a signed build with an existing profile containing a saved provider key and encrypted config secret. Expected: both remain usable after restart without re-entry, the `openhuman` / `app:master_key` entry remains unchanged, and no new corruption quarantine appears. Repeat on macOS, Windows and Linux with their native credential store available. Deny or lock keychain access and confirm the consent flow appears without replacing the existing master key. Restore access, restart, and confirm the secrets decrypt again. Do not export keys or capture secret values in the smoke evidence.
+
- [ ] **Embed capability report and storage configuration** — Run `openhuman-core embed info --json` from a headless install. Expected: versioned JSON lists compiled features and effective defaults without credentials, prompts, endpoint URLs or workspace paths. Run the Embed `storage` recipe with `storage-sqlite`: it writes, reads and deletes an item in its configured SQLite backend. For a release that includes `storage-mongodb`, repeat against an operator-provided test database using the recipe's explicit live settings; confirm the configured backend is reported as MongoDB without exposing its URL.
- [ ] **Embed agents remain independent during streaming** — Run the offline `runtime_events`, `custom_provider` and `approvals` recipes. Expected: per-agent model routes and hooks stay isolated, events identify the acting agent without user content, and dropping an approval subscription cancels its pending callback. Run the stream cancellation integration test: dropping or externally cancelling a stream releases its model even while the receiver remains unread.
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 7b5fedbb29..31550d7d3c 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -675,6 +675,7 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent
| 16.1.26 | Scoped usage observation and budget stop | RI | `crates/openhuman-embed/tests/usage_hooks.rs` | ✅ | Cumulative charged cost and tokens, known-zero versus unpriced calls, per-agent policy and per-turn observer isolation; no summary-repair model calls after a stop |
| 16.1.27 | Scoped builtin command environments | RI | `crates/openhuman-embed/tests/tool_environment.rs`, `crates/openhuman-embed/tests/tool_hook_context.rs` | ✅ | Overlapping subprocess maps exclude host inheritance on Unix; a real shell receives its turn's variables while excluding host HOME and preserving command-owned runtime/security additions |
| 16.1.20 | Host turn observer privacy and runtime propagation | RI | `crates/openhuman-embed/tests/turn_observers.rs`, `crates/openhuman-embed/tests/observed_turns.rs` | ✅ | Sanitized terminal failures, opt-in payloads, root runtime scope propagation, real model/tool callbacks and answering-model usage |
+| 16.1.28 | Host-installed key stores and headless encrypted secrets | RU+RI+MS | `crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source_tests.rs`, `crates/openhuman-core/src/security/keyring/store_tests_2_tests.rs`, `crates/openhuman-rpc/src/keyring/*_tests.rs`, `crates/openhuman-embed/tests/headless_keys.rs`, `tests/keyring_headless_e2e.rs` | 🟡 | Installed-provider precedence, denied-source preservation, private workspace-key creation/reuse, and restart persistence are automated. Existing native desktop profile decryption remains a cross-platform release smoke check. |
### 16.2 Dynamic runtime and agent configuration
diff --git a/gitbooks/features/os-keyring-and-secret-storage.md b/gitbooks/features/os-keyring-and-secret-storage.md
index 69f8f5631d..af28274481 100644
--- a/gitbooks/features/os-keyring-and-secret-storage.md
+++ b/gitbooks/features/os-keyring-and-secret-storage.md
@@ -7,7 +7,7 @@ icon: key
# OS keyring and secret storage
-OpenHuman uses your operating system's secure credential store to protect the secrets that must live on your device:
+The OpenHuman desktop app uses your operating system's secure credential store to protect the master key for local secrets:
- **macOS:** Keychain
- **Windows:** Credential Manager
@@ -19,7 +19,7 @@ This is the root of trust for local secrets. OpenHuman does not keep user creden
The keyring holds two kinds of secret.
-**Credential entries.** When a feature needs a local credential slot, OpenHuman stores it in the platform keyring instead of a normal config file. Examples are locally stored provider API keys, session and bearer tokens that must stay on the device, and wallet secret material where applicable. Entries sit under OpenHuman's own key namespace, so they do not collide with other apps.
+**Credential entries.** Locally stored provider API keys, session and bearer tokens, and wallet secret material use user-scoped credential slots. By default, these slots live in the encrypted `secrets.enc` file, protected by the master key in the OS keyring. The explicit `OPENHUMAN_KEYRING_BACKEND=os` setting stores the slots directly in the platform keyring, under OpenHuman's own namespace.
**The master encryption key.** Some sensitive values must live inside local files, because the app's configuration is file-based. OpenHuman splits the storage. The secret value is stored on disk as encrypted ciphertext. The master key that decrypts it lives in the OS keyring. Your config and state files can hold encrypted values without the decryption key sitting next to them.
@@ -75,9 +75,38 @@ Auth profiles, config secrets, the wallet mnemonic and the `secrets.enc` backend
| `ConsentRequired` | The keyring is unavailable and there is no consent yet. Block and prompt. |
| `Declined` | You refused local storage. Skip the secret operation. |
-## Platform note
-
-This page describes the desktop app (Tauri) on macOS, Windows and Linux. Development and test environments may use test-specific overrides so automated runs do not need an interactive keychain. That is a developer convenience, not the end-user security model.
+## Embedded and server hosts
+
+Desktop, CLI and TUI hosts install the OS keychain providers through
+`openhuman-rpc`'s `os-keyring` feature before starting the core. The service
+name (`openhuman`) and master-key account (`app:master_key`) are unchanged,
+so existing desktop workspaces continue to decrypt with the same key.
+
+The core and embedded library do not depend on an OS keychain. Without a
+host-installed provider, they use encrypted storage in `secrets.enc` and
+create a master key at `{workspace}/keyring/master.key` on first use. On
+Unix this key file has mode `0600`. Back up the key with the workspace;
+anyone who can read both can decrypt its secrets.
+
+An operator can supply `OPENHUMAN_KEYRING_MASTER_KEY` (64 hex characters)
+or `OPENHUMAN_KEYRING_MASTER_KEY_FILE` instead. Set exactly one. Environment
+keys take precedence over a host provider, which takes precedence over the
+workspace key file. An inaccessible host key never falls back to a newly
+created file key.
+
+`OPENHUMAN_KEYRING_BACKEND=file` remains an explicit plaintext debug option.
+`encrypted_file` selects encrypted storage. `os` requires a host-installed
+OS backend; a standalone core cannot enable native keychain access itself.
+Development mode also defaults to encrypted storage.
+
+### Moving a desktop workspace to a server
+
+A desktop workspace encrypted with an OS keychain key needs that same key
+when opened by a host without OS keychain support. Supply it through the
+master-key environment or file option before boot. A newly generated
+workspace key cannot decrypt the desktop ciphertext. Unreadable
+`secrets.enc` files are quarantined as `secrets.enc.corrupt.<timestamp>`
+for recovery rather than overwritten; keep the original key and backups.
## See also
diff --git a/scripts/__tests__/feature-forwarding.test.mjs b/scripts/__tests__/feature-forwarding.test.mjs
index cc0db31d11..f33f5baf06 100644
--- a/scripts/__tests__/feature-forwarding.test.mjs
+++ b/scripts/__tests__/feature-forwarding.test.mjs
@@ -277,7 +277,7 @@ test('the real product file and the real shell list are equal', () => {
// Guards the guard: empty input would make every assertion below vacuous.
assert.ok(productFeatures.length > 0, 'expected to parse at least one product gate');
assert.ok(coreFeatureNames.length > 0, 'expected to parse at least one core gate name');
- const result = checkProductForwarding({ productFeatures, coreFeatureNames, shell });
+ const result = checkProductForwarding({ productFeatures, coreFeatureNames, hostFeatureNames: parseCoreFeatureNames(readFileSync(resolve(REPO_ROOT, "crates/openhuman-rpc/Cargo.toml"), "utf8")), shell });
assert.deepEqual(result.missing, [], 'product gates the shell does not forward');
assert.deepEqual(result.unexpected, [], 'gates the shell forwards that the product omits');
assert.deepEqual(result.unknown, [], 'product gates that are not real core gates');
@@ -823,6 +823,7 @@ default = ["http-client", "server"]
http-client = ["dep:reqwest"]
server = ["http-server", "dep:axum", "session-store"]
session-store = ["dep:tinyagents-session"]
+os-keyring = ["dep:keyring"]
http-server = ["openhuman-tinyhumans/http-server"]
voice = ["openhuman-tinyhumans/voice"]
`);
@@ -895,3 +896,27 @@ test('the checker reports the chain and fails when a layer drops a gate', () =>
rmSync(dir, { recursive: true, force: true });
}
});
+
+test('product gates may be owned by a host crate while still requiring shell forwarding', () => {
+ const input = {
+ productFeatures: ['voice', 'os-keyring'],
+ coreFeatureNames: ['voice'],
+ hostFeatureNames: ['os-keyring'],
+ shell: { defaultFeatures: false, features: ['voice', 'os-keyring'] },
+ };
+ assert.ok(checkProductForwarding(input).ok);
+ assert.deepEqual(checkProductForwarding({ ...input, shell: { defaultFeatures: false, features: ['voice'] } }).missing, ['os-keyring']);
+ assert.deepEqual(checkProductForwarding({ ...input, hostFeatureNames: [] }).unknown, ['os-keyring']);
+});
+
+test('OS keychain is owned by RPC and must be forwarded by CLI and TUI', () => {
+ const rpc = parseFeatureTable('[features]\nos-keyring = ["dep:keyring"]\nserver = ["os-keyring"]\n');
+ assert.deepEqual(rpcForwardedGates(rpc), ['os-keyring']);
+});
+
+test('core product builds omit host-owned OS keychain features', () => {
+ const result = spawnSync('bash', ['scripts/ci/product-features.sh', '--core'], { cwd: REPO_ROOT, encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ assert.ok(result.stdout.trim().split(',').includes('storage-sqlite'));
+ assert.ok(!result.stdout.trim().split(',').includes('os-keyring'));
+});
diff --git a/scripts/ci/check-feature-forwarding.mjs b/scripts/ci/check-feature-forwarding.mjs
index 80359a90cd..11b44dc1af 100644
--- a/scripts/ci/check-feature-forwarding.mjs
+++ b/scripts/ci/check-feature-forwarding.mjs
@@ -134,7 +134,7 @@ if (coreFeatureNames.length === 0) {
}
// Assertions 1 + 2.
-const product = checkProductForwarding({ productFeatures, coreFeatureNames, shell });
+const product = checkProductForwarding({ productFeatures, coreFeatureNames, hostFeatureNames: parseCoreFeatureNames(rpcToml), shell });
console.log(formatProductReport(product, { productFeatures, shell }));
// Assertion 3. Still worth running: it is what catches a gate added to
diff --git a/scripts/ci/product-features.sh b/scripts/ci/product-features.sh
index 7835941627..d7dc7c7f94 100755
--- a/scripts/ci/product-features.sh
+++ b/scripts/ci/product-features.sh
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
-# Print the desktop product's core Cargo gates as a comma-separated list,
+# Print the desktop product's Cargo gates as a comma-separated list,
# ready to paste into `cargo --features "$(scripts/ci/product-features.sh)"`.
#
# Source of truth: scripts/ci/product-features.txt (one gate per line).
@@ -13,6 +13,13 @@
# crash-reporting — a silent loss of coverage over code that still ships.
set -euo pipefail
+# `--core` excludes host-owned gates for core/embed/tinyhumans package builds.
+CORE_ONLY=0
+if [ "${1:-}" = "--core" ]; then
+ CORE_ONLY=1
+ shift
+fi
+
# Optional argument: an alternative gate file. CI always uses the default; the
# override exists so the self-test can drive the empty-list path with a fixture
# instead of mutating the checked-in file.
@@ -40,4 +47,9 @@ if [[ -z "$LIST" ]]; then
exit 2
fi
+if [ "$CORE_ONLY" = "1" ]; then
+ # The OS keychain is owned by RPC. Core and the two library facades have
+ # no corresponding feature or dependency.
+ LIST="$(printf '%s' "$LIST" | tr ',' '\n' | sed '/^os-keyring$/d' | paste -sd, -)"
+fi
printf '%s\n' "$LIST"
diff --git a/scripts/ci/product-features.txt b/scripts/ci/product-features.txt
index eca8165f95..ebb090f179 100644
--- a/scripts/ci/product-features.txt
+++ b/scripts/ci/product-features.txt
@@ -1,4 +1,4 @@
-# DESKTOP_PRODUCT_FEATURES — the core Cargo gates the shipped desktop app has.
+# DESKTOP_PRODUCT_FEATURES — the Cargo gates the shipped desktop app has.
#
# This file is the single source of truth for "what OpenHuman the product is",
# as distinct from `[features] default` in Cargo.toml, which is now only the
@@ -106,3 +106,6 @@ tinymemes
# on first open. Also serves `sqlite:` in `[storage] url`. MongoDB is not part
# of the product.
storage-sqlite
+
+# OS keychain providers owned by the RPC host layer.
+os-keyring
diff --git a/scripts/ci/rust-coverage.sh b/scripts/ci/rust-coverage.sh
index d4229f0e86..38cf6d34c8 100755
--- a/scripts/ci/rust-coverage.sh
+++ b/scripts/ci/rust-coverage.sh
@@ -8,6 +8,7 @@ set -euo pipefail
OUT="${OUT:-lcov-core.info}"
PRODUCT_FEATURES="$(bash scripts/ci/product-features.sh)"
+CORE_PRODUCT_FEATURES="$(bash scripts/ci/product-features.sh --core)"
# Sandboxed acting-tool tests deliberately do not forward RUSTUP_HOME. The
# container installs Rust outside HOME, so its rustup proxy otherwise tries
@@ -33,7 +34,7 @@ llvm_cov() {
;;
*)
bash scripts/ci-cancel-aware.sh cargo llvm-cov \
- --features "${PRODUCT_FEATURES}" "$@"
+ --features "${CORE_PRODUCT_FEATURES}" "$@"
;;
esac
}
@@ -44,19 +45,11 @@ llvm_cov_package() {
llvm_cov_product_facade() {
bash scripts/ci-cancel-aware.sh cargo llvm-cov \
- --features "${PRODUCT_FEATURES}" "$@"
+ --features "${CORE_PRODUCT_FEATURES}" "$@"
}
llvm_cov_embed() {
- (
- # Embed's integration hosts persist fixture credentials with the real
- # encrypted backend. Supply only this suite a disposable master key;
- # core's missing-key regressions and the caller's environment stay intact.
- unset OPENHUMAN_KEYRING_MASTER_KEY_FILE
- OPENHUMAN_KEYRING_MASTER_KEY="$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')"
- export OPENHUMAN_KEYRING_MASTER_KEY
- llvm_cov_product_facade "$@"
- )
+ llvm_cov_product_facade "$@"
}
integration_test_targets() {
diff --git a/scripts/ci/self-hosted/lanes-plan.mjs b/scripts/ci/self-hosted/lanes-plan.mjs
index f841a3ffe8..fcbdd86bf8 100644
--- a/scripts/ci/self-hosted/lanes-plan.mjs
+++ b/scripts/ci/self-hosted/lanes-plan.mjs
@@ -67,7 +67,7 @@ export const HOSTED_GROUPS = [
{ group: "pester", lanes: ["pester"], maxParallel: 1, container: false },
];
-const PRODUCT = '"$(bash scripts/ci/product-features.sh)"';
+const CORE_PRODUCT = '"$(bash scripts/ci/product-features.sh --core)"';
// The storage-drivers lane: the drivers it turns on, the root e2e targets that
// run once per driver (tests/support/storage_drivers.rs), and the lib-test
@@ -405,7 +405,7 @@ export function buildPlan({ profile, areas, env = {}, isPullRequest = true }) {
{
name: "clippy-product",
when: core,
- run: `cargo clippy -p openhuman --features ${PRODUCT} -- -D warnings`,
+ run: `cargo clippy -p openhuman --features ${CORE_PRODUCT} -- -D warnings`,
},
// No separate `cargo clippy -p openhuman` (contributor set): clippy
// lints every workspace crate in the graph, and openhuman-embed's
diff --git a/scripts/lib/feature-forwarding.mjs b/scripts/lib/feature-forwarding.mjs
index f5f05a51bd..135a1a274e 100644
--- a/scripts/lib/feature-forwarding.mjs
+++ b/scripts/lib/feature-forwarding.mjs
@@ -57,7 +57,7 @@ export const INTENTIONALLY_NOT_FORWARDED = {
/**
* Gates the shell turns on on its `openhuman-rpc` dependency that are NOT
* core gates, mapped to why. They are rpc's (and, for `jev`, tinyhumans')
- * own, so they never appear in `scripts/ci/product-features.txt`, and the
+ * own. Some, such as `os-keyring`, are also product gates; the
* product assertion must not read them as "unexpected".
*/
export const SHELL_RPC_LOCAL_GATES = {
@@ -280,6 +280,7 @@ export function parseProductFeatures(text) {
export function checkProductForwarding({
productFeatures,
coreFeatureNames,
+ hostFeatureNames = [],
shell,
localGates = SHELL_RPC_LOCAL_GATES,
}) {
@@ -293,17 +294,18 @@ export function checkProductForwarding({
}
const forwarded = new Set(shell.features);
const product = new Set(productFeatures);
- const known = new Set(coreFeatureNames);
+ const known = new Set([...coreFeatureNames, ...hostFeatureNames]);
// In the product set, absent from the shell → compiled out of the shipped app.
const missing = productFeatures.filter(gate => !forwarded.has(gate));
// Forwarded by the shell but not in the product set → the product grew a
// gate without anyone editing the file that says what the product is.
// `openhuman-rpc`'s own gates (server, client, Jev ranker) are not core
- // gates and never belong in the product file; they are exempt by name.
+ // gates and are exempt by name. Host gates explicitly listed in the product
+ // file, such as os-keyring, still require shell forwarding.
const unexpected = shell.features.filter(
gate => !product.has(gate) && !Object.prototype.hasOwnProperty.call(localGates, gate)
);
- // Named in the product set but not declared by the core → typo, or a gate
+ // Named in the product set but not declared by core or a host → typo, or a gate
// renamed/deleted without updating this list.
const unknown = productFeatures.filter(gate => !known.has(gate));
return {
@@ -332,7 +334,7 @@ export function formatProductReport(result, { productFeatures, shell }) {
`Shell forwards (${shell.features.length}): ${shell.features.join(', ') || '(none)'}`,
];
if (result.unknown.length > 0) {
- lines.push('', 'Product gates that are not declared in the core `[features]` table:');
+ lines.push('', 'Product gates that are not declared in core or host `[features]` tables:');
for (const gate of result.unknown) lines.push(` - ${gate}`);
lines.push('Either the name is a typo or the gate was renamed/deleted.');
}
@@ -480,6 +482,7 @@ export const CHAIN_LOCAL_GATES = {
jev: 'This crate owns the gate: the Jev-backed `tool_search` ranker (`tinytools-jev` over the TinyHumans System One proxy).',
},
'openhuman-rpc': {
+ 'os-keyring': 'Host-owned native secret storage and master-key providers; the core exposes only install ports.',
'http-client':
'The authenticated JSON-RPC HTTP client (`post_json_rpc`); transport code this crate owns, with no core twin.',
server:
@@ -673,6 +676,6 @@ export function formatChainReport(result, { notForwarded = {} } = {}) {
export function rpcForwardedGates(rpcFeatures) {
const local = CHAIN_LOCAL_GATES['openhuman-rpc'] ?? {};
return [...rpcFeatures.keys()].filter(
- name => name !== 'default' && !Object.prototype.hasOwnProperty.call(local, name)
+ name => name !== 'default' && (name === 'os-keyring' || !Object.prototype.hasOwnProperty.call(local, name))
);
}
diff --git a/tests/agent_harness_e2e.rs b/tests/agent_harness_e2e.rs
index cf9d2cf185..7350bface5 100644
--- a/tests/agent_harness_e2e.rs
+++ b/tests/agent_harness_e2e.rs
@@ -44,7 +44,6 @@ const TEST_RPC_TOKEN: &str = "json-rpc-e2e-local-token";
// ─── Env serialization (same rationale as json_rpc_e2e.rs:61-79) ───────────
static AGENT_HARNESS_E2E_ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
-static AGENT_HARNESS_KEYRING_INIT: OnceLock<()> = OnceLock::new();
/// Initialise the global `AgentDefinitionRegistry` with built-ins exactly once
/// across all tests in this binary. Guard with OnceLock so repeated `boot_stack`
@@ -60,9 +59,7 @@ fn init_agent_def_registry() {
}
fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- AGENT_HARNESS_KEYRING_INIT.get_or_init(|| unsafe {
- std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file");
- });
+ env_guard::init_keyring_workspace();
let mutex = AGENT_HARNESS_E2E_ENV_LOCK.get_or_init(|| Mutex::new(()));
match mutex.lock() {
Ok(guard) => guard,
diff --git a/tests/in_process/agent_prompt_comprehension_e2e.rs b/tests/in_process/agent_prompt_comprehension_e2e.rs
index 47dae52037..6aeb923976 100644
--- a/tests/in_process/agent_prompt_comprehension_e2e.rs
+++ b/tests/in_process/agent_prompt_comprehension_e2e.rs
@@ -16,7 +16,7 @@
//! `env_lock()` across `.await` on purpose, as there.
#![allow(clippy::await_holding_lock)]
-use crate::env_guard::env_lock_with_file_keyring_async as env_lock_async;
+use crate::env_guard::env_lock_async as env_lock_async;
use crate::env_guard::EnvVarGuard;
use crate::rpc_auth::{ensure_rpc_auth, rpc_token};
use crate::scripted_stack::{
diff --git a/tests/in_process/config_auth_app_state_connectivity_e2e.rs b/tests/in_process/config_auth_app_state_connectivity_e2e.rs
index 88b9452651..081a26a3d7 100644
--- a/tests/in_process/config_auth_app_state_connectivity_e2e.rs
+++ b/tests/in_process/config_auth_app_state_connectivity_e2e.rs
@@ -3810,7 +3810,7 @@ fn credentials_profile_store_public_api_persists_updates_and_recovers_bad_files(
#[test]
fn credentials_auth_service_selects_active_default_and_requested_profiles() {
let _lock = env_lock();
- let _keyring_guard = EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "disabled");
+ let _keyring_guard = EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "encrypted_file");
let tmp = tempdir().expect("tempdir");
let service = AuthService::new(&tmp.path().join("auth-service"), false);
@@ -4081,7 +4081,7 @@ fn credentials_profile_store_recovers_dropped_entries_empty_files_and_datetime_e
#[test]
fn credentials_profile_store_round_trips_oauth_secret_fields_after_backend_selection() {
let _lock = env_lock();
- let _keyring_guard = EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "disabled");
+ let _keyring_guard = EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "encrypted_file");
let tmp = tempdir().expect("tempdir");
let state_dir = tmp.path().join("json-fallback");
let store = AuthProfilesStore::new(&state_dir, false);
diff --git a/tests/in_process/skill_registry_e2e.rs b/tests/in_process/skill_registry_e2e.rs
index 01d2e4b8f3..ded5e42b4b 100644
--- a/tests/in_process/skill_registry_e2e.rs
+++ b/tests/in_process/skill_registry_e2e.rs
@@ -7,7 +7,7 @@
//! The test uses a local fixture catalog and local SKILL.md download URL so CI
//! does not depend on the live Hermes API.
-use crate::env_guard::env_lock_with_file_keyring_async as env_lock_async;
+use crate::env_guard::env_lock_async as env_lock_async;
use crate::env_guard::EnvVarGuard;
use crate::rpc_auth::{ensure_rpc_auth, rpc_token};
use openhuman_core::core::auth::CORE_TOKEN_ENV_VAR;
diff --git a/tests/json_rpc_e2e.rs b/tests/json_rpc_e2e.rs
index 028b6a9a9a..8f30e24145 100644
--- a/tests/json_rpc_e2e.rs
+++ b/tests/json_rpc_e2e.rs
@@ -40,14 +40,11 @@ static JSON_RPC_AUTH_INIT: OnceLock<()> = OnceLock::new();
/// process-global, so parallel tests would clobber each other and hit the wrong `config.toml` or
/// inherited `VITE_BACKEND_URL`.
static JSON_RPC_E2E_ENV_LOCK: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
-static JSON_RPC_E2E_KEYRING_INIT: OnceLock<()> = OnceLock::new();
static CHAT_COMPLETION_MODELS: OnceLock<Mutex<Vec<String>>> = OnceLock::new();
static CHAT_COMPLETION_REQUESTS: OnceLock<Mutex<Vec<Value>>> = OnceLock::new();
async fn json_rpc_e2e_env_lock_async() -> tokio::sync::MutexGuard<'static, ()> {
- JSON_RPC_E2E_KEYRING_INIT.get_or_init(|| unsafe {
- std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file");
- });
+ env_guard::init_keyring_workspace();
let mutex = JSON_RPC_E2E_ENV_LOCK.get_or_init(|| tokio::sync::Mutex::new(()));
// A tokio mutex is never poisoned, so a panic in one test cannot cascade to the others.
mutex.lock().await
@@ -1024,7 +1021,6 @@ async fn wait_for_chat_completion_request_with_message(message: &str) -> Value {
}
async fn encrypt_test_mnemonic() -> String {
- let _keyring_backend_guard = EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file");
let config = openhuman_core::config::load_config_with_timeout()
.await
.expect("load config for encrypted test mnemonic");
@@ -1610,14 +1606,13 @@ async fn json_rpc_tool_registry_lists_and_gets_entries() {
}
#[tokio::test]
-async fn json_rpc_harness_init_status_returns_snapshot_envelope() {
+async fn json_rpc_removed_harness_init_status_is_not_found() {
let _env_lock = json_rpc_e2e_env_lock_async().await;
let (rpc_addr, rpc_join) = serve_on_ephemeral(build_core_http_router(false)).await;
let rpc_base = format!("http://{rpc_addr}");
- // status is read-only — no provisioning is triggered, so it is safe in CI
- // (we deliberately do NOT call `openhuman.harness_init_run`, which would
- // attempt real Python/Node/spaCy downloads).
+ // The obsolete provisioning flow was removed; its status method must not
+ // reappear through host controller registration.
let resp = post_json_rpc(
&rpc_base,
44_711,
@@ -1625,30 +1620,11 @@ async fn json_rpc_harness_init_status_returns_snapshot_envelope() {
json!({}),
)
.await;
- let result = assert_no_jsonrpc_error(&resp, "harness_init_status");
-
- let snapshot = result
- .get("snapshot")
- .expect("harness_init_status should return a snapshot object");
- let overall = snapshot
- .get("overall")
- .and_then(Value::as_str)
- .expect("snapshot.overall should be a string");
- assert!(
- ["idle", "running", "done", "failed"].contains(&overall),
- "overall should be a known lifecycle state, got {overall}"
- );
- let steps = snapshot
- .get("steps")
- .and_then(Value::as_array)
- .expect("snapshot.steps should be an array");
- let ids: Vec<&str> = steps
- .iter()
- .filter_map(|s| s.get("id").and_then(Value::as_str))
- .collect();
- assert!(
- ids.contains(&"python_runtime") && ids.contains(&"node_runtime"),
- "snapshot should list the registered steps, got {ids:?}"
+ let error = resp.get("error").expect("removed method must fail");
+ assert_eq!(error.get("code").and_then(Value::as_i64), Some(-32000));
+ assert_eq!(
+ error.get("message").and_then(Value::as_str),
+ Some("unknown method: openhuman.harness_init_status")
);
rpc_join.abort();
diff --git a/tests/keyring_headless_e2e.rs b/tests/keyring_headless_e2e.rs
new file mode 100644
index 0000000000..c2c51a339b
--- /dev/null
+++ b/tests/keyring_headless_e2e.rs
@@ -0,0 +1,80 @@
+//! A headless core persists both secret slots and config ciphertext across
+//! process restarts, without an OS provider or keyring environment overrides.
+
+use openhuman_core::security::keyring;
+use std::process::Command;
+
+#[test]
+fn headless_core_reuses_its_workspace_key_after_restart() {
+ const STAGE: &str = "OPENHUMAN_TEST_HEADLESS_KEYRING_STAGE";
+ if let Ok(stage) = std::env::var(STAGE) {
+ let workspace = std::path::PathBuf::from(std::env::var("OPENHUMAN_WORKSPACE").unwrap());
+ keyring::init_workspace(&workspace);
+ keyring::init_master_key().unwrap();
+ assert_eq!(keyring::backend_name(), "encrypted_file");
+ assert!(keyring::is_available());
+ let config_secrets = keyring::SecretStore::new(&workspace, true);
+ let ciphertext_path = workspace.join("config-secret.txt");
+ if stage == "write" {
+ keyring::set("test-user", "token", "persisted-token").unwrap();
+ std::fs::write(
+ &ciphertext_path,
+ config_secrets.encrypt("config-secret").unwrap(),
+ )
+ .unwrap();
+ } else {
+ assert_eq!(
+ keyring::get("test-user", "token").unwrap().as_deref(),
+ Some("persisted-token")
+ );
+ let ciphertext = std::fs::read_to_string(&ciphertext_path).unwrap();
+ assert!(ciphertext.starts_with("enc2:"));
+ assert_eq!(
+ config_secrets.decrypt(&ciphertext).unwrap(),
+ "config-secret"
+ );
+ }
+ return;
+ }
+
+ let dir = tempfile::tempdir().unwrap();
+ let key_path = dir.path().join("keyring/master.key");
+ let mut saved_key = None;
+ for stage in ["write", "read"] {
+ let result = Command::new(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ "headless_core_reuses_its_workspace_key_after_restart",
+ ])
+ .env(STAGE, stage)
+ .env("OPENHUMAN_WORKSPACE", dir.path())
+ .env("OPENHUMAN_APP_ENV", "development")
+ .env_remove("OPENHUMAN_KEYRING_BACKEND")
+ .env_remove("OPENHUMAN_KEYRING_MASTER_KEY")
+ .env_remove("OPENHUMAN_KEYRING_MASTER_KEY_FILE")
+ .env_remove("OPENHUMAN_STORAGE_URL")
+ .output()
+ .unwrap();
+ assert!(
+ result.status.success(),
+ "headless {stage} failed: {}\n{}",
+ String::from_utf8_lossy(&result.stdout),
+ String::from_utf8_lossy(&result.stderr)
+ );
+ let key = std::fs::read(&key_path).unwrap();
+ if let Some(previous) = &saved_key {
+ assert!(previous == &key, "restart must not change the master key");
+ }
+ saved_key = Some(key);
+ }
+ assert!(dir.path().join("secrets.enc").exists());
+ assert!(!dir.path().join("dev-keychain.json").exists());
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ assert_eq!(
+ std::fs::metadata(key_path).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ }
+}
diff --git a/tests/memory_v2_e2e.rs b/tests/memory_v2_e2e.rs
index 7ecad85eee..ac90433705 100644
--- a/tests/memory_v2_e2e.rs
+++ b/tests/memory_v2_e2e.rs
@@ -33,7 +33,7 @@ use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicI64, Ordering};
use std::time::{Duration, Instant};
-use env_guard::{env_lock_with_file_keyring_async, EnvVarGuard};
+use env_guard::{env_lock_async, EnvVarGuard};
use rpc_harness::{rpc, serve_rpc};
use serde_json::{json, Value};
@@ -194,7 +194,7 @@ struct Fixture {
impl Fixture {
/// Boots the stack; `signed_in` stores the mock session first.
async fn new(signed_in: bool) -> Self {
- let lock = env_lock_with_file_keyring_async().await;
+ let lock = env_lock_async().await;
tinyhumans_boot::boot();
let mock = MockBackend::start().await;
let home = tempfile::tempdir().expect("tempdir");
diff --git a/tests/raw_coverage/w4_shared/mod.rs b/tests/raw_coverage/w4_shared/mod.rs
index cefa830599..aac3b5623e 100644
--- a/tests/raw_coverage/w4_shared/mod.rs
+++ b/tests/raw_coverage/w4_shared/mod.rs
@@ -39,31 +39,25 @@ pub const SESSION_USER_ID: &str = "w4-user";
static AUTH_INIT: OnceLock<String> = OnceLock::new();
/// The crate-wide env mutex, not a private one — see the module note above.
static ENV_LOCK: &OnceLock<tokio::sync::Mutex<()>> = &crate::SHARED_ENV_LOCK;
-static KEYRING_INIT: OnceLock<()> = OnceLock::new();
/// Serializes every case that touches process-global env (`HOME`,
/// `OPENHUMAN_WORKSPACE`, the backend-URL overrides) against every other
/// aggregated suite. Poison is recovered so one panicking case cannot wedge the
/// binary.
pub fn env_lock() -> tokio::sync::MutexGuard<'static, ()> {
+ crate::env_guard::init_keyring_workspace();
let guard = ENV_LOCK
.get_or_init(|| tokio::sync::Mutex::new(()))
.blocking_lock();
- // Under the lock, so this `set_var` cannot race a concurrent env read.
- KEYRING_INIT.get_or_init(|| {
- std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file");
- });
guard
}
pub async fn env_lock_async() -> tokio::sync::MutexGuard<'static, ()> {
+ crate::env_guard::init_keyring_workspace();
let guard = ENV_LOCK
.get_or_init(|| tokio::sync::Mutex::new(()))
- .lock().await;
- // Under the lock, so this `set_var` cannot race a concurrent env read.
- KEYRING_INIT.get_or_init(|| {
- std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file");
- });
+ .lock()
+ .await;
guard
}
diff --git a/tests/support/env_guard.rs b/tests/support/env_guard.rs
index 65b40dde66..420179cdfa 100644
--- a/tests/support/env_guard.rs
+++ b/tests/support/env_guard.rs
@@ -60,7 +60,6 @@ impl Drop for EnvVarGuard {
}
static ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
-static FILE_KEYRING_INIT: OnceLock<()> = OnceLock::new();
/// The process-wide env lock for this target, taken from a synchronous test.
/// It is a `tokio::sync::Mutex` (never poisoned, so one panicking test cannot
@@ -68,30 +67,21 @@ static FILE_KEYRING_INIT: OnceLock<()> = OnceLock::new();
/// a tokio runtime: `#[tokio::test]` bodies use [`env_lock_async`] so the guard
/// can be held across `.await`.
pub fn env_lock() -> MutexGuard<'static, ()> {
+ init_keyring_workspace();
ENV_LOCK.blocking_lock()
}
/// Async form of [`env_lock`] for `#[tokio::test]` bodies.
pub async fn env_lock_async() -> MutexGuard<'static, ()> {
+ init_keyring_workspace();
ENV_LOCK.lock().await
}
-fn init_file_keyring() {
- FILE_KEYRING_INIT.get_or_init(|| {
- std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file");
- });
-}
-
-/// [`env_lock`] after pinning `OPENHUMAN_KEYRING_BACKEND=file` once per
-/// process (the suites that read or write secrets need the file keyring so
-/// they never touch the host's real one).
-pub fn env_lock_with_file_keyring() -> MutexGuard<'static, ()> {
- init_file_keyring();
- env_lock()
-}
-
-/// Async form of [`env_lock_with_file_keyring`] for `#[tokio::test]` bodies.
-pub async fn env_lock_with_file_keyring_async() -> MutexGuard<'static, ()> {
- init_file_keyring();
- env_lock_async().await
+/// Retain an isolated key workspace for the binary's lifetime. The core caches
+/// its key and backend process-wide, so a per-case TempDir must not own them.
+/// No backend or master-key environment override is needed.
+pub fn init_keyring_workspace() {
+ static WORKSPACE: OnceLock<tempfile::TempDir> = OnceLock::new();
+ let workspace = WORKSPACE.get_or_init(|| tempfile::tempdir().expect("test key workspace"));
+ openhuman_core::security::keyring::init_workspace(workspace.path());
}
diff --git a/tests/support/memory_engine_fixture.rs b/tests/support/memory_engine_fixture.rs
index 4b5f76fb65..70596960ec 100644
--- a/tests/support/memory_engine_fixture.rs
+++ b/tests/support/memory_engine_fixture.rs
@@ -412,14 +412,11 @@ impl Drop for EnvVarGuard {
}
pub static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
-pub static KEYRING_INIT: OnceLock<()> = OnceLock::new();
pub static AUTH_INIT: OnceLock<()> = OnceLock::new();
pub static SEAMS_INIT: OnceLock<()> = OnceLock::new();
pub fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- KEYRING_INIT.get_or_init(|| unsafe {
- std::env::set_var("OPENHUMAN_KEYRING_BACKEND", "file");
- });
+ openhuman_core::security::keyring::init_workspace(shared_workspace());
match ENV_LOCK.get_or_init(|| Mutex::new(())).lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),