Skip to content

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

refactor(secrets): default core storage to memory and isolate RPC keyring

Steven Enamakel85aa2d7486c0
diff --git a/.github/ci-paths-filter.yml b/.github/ci-paths-filter.yml
index 898531753b..e469db2e8a 100644
--- a/.github/ci-paths-filter.yml
+++ b/.github/ci-paths-filter.yml
@@ -232,7 +232,7 @@ storage:
- 'crates/openhuman-core/src/flows/**'
- 'crates/openhuman-core/src/security/approval/**'
- 'crates/openhuman-core/src/security/devices/**'
- - 'crates/openhuman-core/src/security/keyring/**'
+ - 'crates/openhuman-core/src/security/secret_storage/**'
- 'crates/openhuman-core/src/security/credentials/**'
- 'crates/openhuman-core/src/desktop/notifications/**'
- 'crates/openhuman-core/src/integrations/task_sources/**'
diff --git a/.github/workflows/storage-mongodb.yml b/.github/workflows/storage-mongodb.yml
index 3da00800b5..5ca0ba0ebd 100644
--- a/.github/workflows/storage-mongodb.yml
+++ b/.github/workflows/storage-mongodb.yml
@@ -37,7 +37,7 @@ on:
- "crates/openhuman-core/src/flows/**"
- "crates/openhuman-core/src/security/approval/**"
- "crates/openhuman-core/src/security/devices/**"
- - "crates/openhuman-core/src/security/keyring/**"
+ - "crates/openhuman-core/src/security/secret_storage/**"
- "crates/openhuman-core/src/security/credentials/**"
- "crates/openhuman-core/src/desktop/notifications/**"
- "crates/openhuman-core/src/integrations/task_sources/**"
diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lock
index ab60e14a2c..91adf625d6 100644
--- a/crates/openhuman-app/Cargo.lock
+++ b/crates/openhuman-app/Cargo.lock
@@ -527,12 +527,6 @@ dependencies = [
"digest 0.10.7",
]
-[[package]]
-name = "block"
-version = "0.1.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
-
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -867,21 +861,6 @@ version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
-[[package]]
-name = "cocoa"
-version = "0.22.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "667fdc068627a2816b9ff831201dd9864249d6ee8d190b9532357f1fc0f61ea7"
-dependencies = [
- "bitflags 1.3.2",
- "block",
- "core-foundation 0.9.4",
- "core-graphics 0.21.0",
- "foreign-types 0.3.2",
- "libc",
- "objc",
-]
-
[[package]]
name = "combine"
version = "4.6.8"
@@ -953,23 +932,13 @@ dependencies = [
"version_check",
]
-[[package]]
-name = "core-foundation"
-version = "0.7.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "57d24c7a13c43e870e37c1556b74555437870a04514f7685f5b354e090567171"
-dependencies = [
- "core-foundation-sys 0.7.0",
- "libc",
-]
-
[[package]]
name = "core-foundation"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
dependencies = [
- "core-foundation-sys 0.8.7",
+ "core-foundation-sys",
"libc",
]
@@ -979,46 +948,16 @@ version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
dependencies = [
- "core-foundation-sys 0.8.7",
+ "core-foundation-sys",
"libc",
]
-[[package]]
-name = "core-foundation-sys"
-version = "0.7.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b3a71ab494c0b5b860bdc8407ae08978052417070c2ced38573a9157ad75b8ac"
-
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
-[[package]]
-name = "core-graphics"
-version = "0.19.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b3889374e6ea6ab25dba90bb5d96202f61108058361f6dc72e8b03e6f8bbe923"
-dependencies = [
- "bitflags 1.3.2",
- "core-foundation 0.7.0",
- "foreign-types 0.3.2",
- "libc",
-]
-
-[[package]]
-name = "core-graphics"
-version = "0.21.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "52a67c4378cf203eace8fb6567847eb641fd6ff933c1145a115c6ee820ebb978"
-dependencies = [
- "bitflags 1.3.2",
- "core-foundation 0.9.4",
- "foreign-types 0.3.2",
- "libc",
-]
-
[[package]]
name = "core-graphics"
version = "0.25.0"
@@ -2709,7 +2648,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
dependencies = [
"android_system_properties",
- "core-foundation-sys 0.8.7",
+ "core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"log",
@@ -3470,15 +3409,6 @@ dependencies = [
"hashify",
]
-[[package]]
-name = "malloc_buf"
-version = "0.0.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb"
-dependencies = [
- "libc",
-]
-
[[package]]
name = "markup5ever"
version = "0.38.0"
@@ -3841,15 +3771,6 @@ dependencies = [
"syn 2.0.119",
]
-[[package]]
-name = "objc"
-version = "0.2.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"
-dependencies = [
- "malloc_buf",
-]
-
[[package]]
name = "objc2"
version = "0.6.4"
@@ -4299,7 +4220,7 @@ dependencies = [
"tinystoragedrivers",
"tinytools",
"tinytools-agent",
- "tinytools-std",
+ "tinytools-std 0.5.0",
"tinyvoice",
"tinyvoice-bus",
"tinywallet-bus",
@@ -5190,22 +5111,6 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
-[[package]]
-name = "rdev"
-version = "0.5.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "00552ca2dc2f93b84cd7b5581de49549411e4e41d89e1c691bcb93dc4be360c3"
-dependencies = [
- "cocoa",
- "core-foundation 0.7.0",
- "core-foundation-sys 0.7.0",
- "core-graphics 0.19.2",
- "lazy_static",
- "libc",
- "winapi",
- "x11",
-]
-
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -5555,7 +5460,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0"
dependencies = [
"core-foundation 0.10.1",
- "core-foundation-sys 0.8.7",
+ "core-foundation-sys",
"jni 0.22.4",
"log",
"once_cell",
@@ -5700,7 +5605,7 @@ checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"
dependencies = [
"bitflags 2.13.2",
"core-foundation 0.9.4",
- "core-foundation-sys 0.8.7",
+ "core-foundation-sys",
"libc",
"security-framework-sys",
]
@@ -5713,7 +5618,7 @@ checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags 2.13.2",
"core-foundation 0.10.1",
- "core-foundation-sys 0.8.7",
+ "core-foundation-sys",
"libc",
"security-framework-sys",
]
@@ -5724,7 +5629,7 @@ version = "2.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
dependencies = [
- "core-foundation-sys 0.8.7",
+ "core-foundation-sys",
"libc",
]
@@ -6488,7 +6393,7 @@ version = "0.33.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fc858248ea01b66f19d8e8a6d55f41deaf91e9d495246fd01368d99935c6c01"
dependencies = [
- "core-foundation-sys 0.8.7",
+ "core-foundation-sys",
"libc",
"memchr",
"ntapi",
@@ -6512,7 +6417,7 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
dependencies = [
- "core-foundation-sys 0.8.7",
+ "core-foundation-sys",
"libc",
]
@@ -6538,7 +6443,7 @@ dependencies = [
"bitflags 2.13.2",
"block2",
"core-foundation 0.10.1",
- "core-graphics 0.25.0",
+ "core-graphics",
"crossbeam-channel",
"dispatch2",
"dlopen2",
@@ -7130,7 +7035,7 @@ dependencies = [
"tinystoragedrivers-core",
"tinytools",
"tinytools-agent",
- "tinytools-std",
+ "tinytools-std 0.5.0",
"tokio",
"tracing",
"uuid",
@@ -7248,14 +7153,14 @@ dependencies = [
[[package]]
name = "tinybox-bus"
-version = "0.1.18"
+version = "0.1.19"
dependencies = [
"serde",
]
[[package]]
name = "tinybox-core"
-version = "0.1.18"
+version = "0.1.19"
dependencies = [
"async-trait",
"serde",
@@ -7265,7 +7170,7 @@ dependencies = [
[[package]]
name = "tinybox-docker"
-version = "0.1.18"
+version = "0.1.19"
dependencies = [
"async-trait",
"serde_json",
@@ -7276,7 +7181,7 @@ dependencies = [
[[package]]
name = "tinybox-jail"
-version = "0.1.18"
+version = "0.1.19"
dependencies = [
"landlock",
"log",
@@ -7708,7 +7613,7 @@ dependencies = [
[[package]]
name = "tinymcp"
-version = "0.6.0"
+version = "0.8.1"
dependencies = [
"anyhow",
"async-trait",
@@ -7716,6 +7621,7 @@ dependencies = [
"base64 0.23.1",
"dirs 7.0.0",
"futures-util",
+ "libc",
"parking_lot",
"reqwest 0.12.28",
"rusqlite",
@@ -7725,6 +7631,7 @@ dependencies = [
"thiserror 2.0.20",
"tinymcp-bus",
"tinytools",
+ "tinytools-std 0.5.0 (git+https://github.com/tinyhumansai/tinytools?rev=360721bc3c7a26221b61f6629f5f0415cfccb568)",
"tokio",
"tokio-stream",
"tracing",
@@ -7735,7 +7642,7 @@ dependencies = [
[[package]]
name = "tinymcp-bus"
-version = "0.6.0"
+version = "0.8.1"
dependencies = [
"schemars 1.2.2",
"serde",
@@ -7951,6 +7858,31 @@ dependencies = [
"walkdir",
]
+[[package]]
+name = "tinytools-std"
+version = "0.5.0"
+source = "git+https://github.com/tinyhumansai/tinytools?rev=360721bc3c7a26221b61f6629f5f0415cfccb568#360721bc3c7a26221b61f6629f5f0415cfccb568"
+dependencies = [
+ "anyhow",
+ "async-trait",
+ "base64 0.23.1",
+ "fs2",
+ "futures-util",
+ "glob",
+ "libc",
+ "log",
+ "parking_lot",
+ "regex",
+ "reqwest 0.12.28",
+ "rustix",
+ "serde_json",
+ "sha2 0.11.0",
+ "tinytools",
+ "tokio",
+ "tracing",
+ "walkdir",
+]
+
[[package]]
name = "tinyvec"
version = "1.13.3"
@@ -7959,13 +7891,11 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "tinyvoice"
-version = "0.1.12"
+version = "0.1.14"
dependencies = [
"cpal",
"log",
"parking_lot",
- "rdev",
- "serde",
"thiserror 2.0.20",
"tinyvoice-bus",
"tokio",
@@ -9812,16 +9742,6 @@ dependencies = [
"windows-version",
]
-[[package]]
-name = "x11"
-version = "2.21.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e"
-dependencies = [
- "libc",
- "pkg-config",
-]
-
[[package]]
name = "x11rb"
version = "0.13.2"
diff --git a/crates/openhuman-core/src/config/README.md b/crates/openhuman-core/src/config/README.md
index f09d2577a4..25f67a5aec 100644
--- a/crates/openhuman-core/src/config/README.md
+++ b/crates/openhuman-core/src/config/README.md
@@ -206,7 +206,7 @@ The `workspace` namespace (`file_read`, `file_write`, `file_reset`) is registere
## Boundaries
-- Secret encryption is done by `security::keyring::SecretStore`; this folder only decides which fields
+- Secret encryption is done by `security::secret_storage::SecretStore`; this folder only decides which fields
are secrets and when to encrypt or decrypt them.
- The autonomy policy is defined here as data (`AutonomyConfig`, `[autonomy] enabled = false` by
default) but enforced by [`crates/openhuman-core/src/security/`](../security/) (`SecurityPolicy::from_config`).
diff --git a/crates/openhuman-core/src/config/schema/README.md b/crates/openhuman-core/src/config/schema/README.md
index cdcfd099e5..86580838cc 100644
--- a/crates/openhuman-core/src/config/schema/README.md
+++ b/crates/openhuman-core/src/config/schema/README.md
@@ -117,7 +117,7 @@ sandbox policy contract described under Workspace/identity helpers below.
5. Run pending schema migrations ([`../migrations/`](../migrations/), via
`migrations::run_pending`), which bump `schema_version` and save as they go.
6. Decrypt at-rest secrets ([`load/secrets.rs`](./load/secrets.rs)); a legacy `enc:` (XOR) value is
- force-migrated to `enc2:` (ChaCha20-Poly1305 via `security::keyring`) and
+ force-migrated to `enc2:` (ChaCha20-Poly1305 via `security::secret_storage`) and
the config is saved again immediately.
A brand-new workspace is instead stamped at `CURRENT_SCHEMA_VERSION`, seeded
diff --git a/crates/openhuman-core/src/config/schema/load/secrets.rs b/crates/openhuman-core/src/config/schema/load/secrets.rs
index 5e2c4e5e74..35a76b8581 100644
--- a/crates/openhuman-core/src/config/schema/load/secrets.rs
+++ b/crates/openhuman-core/src/config/schema/load/secrets.rs
@@ -31,12 +31,12 @@ thread_local! {
/// from persisting indefinitely (see audit C8). Reading existing `enc:` values
/// still succeeds throughout the migration.
fn decrypt_optional_secret(
- store: &crate::security::keyring::SecretStore,
+ store: &crate::security::secret_storage::SecretStore,
value: &mut Option<String>,
field_name: &str,
) -> Result<()> {
if let Some(raw) = value.clone() {
- if crate::security::keyring::SecretStore::is_encrypted(&raw) {
+ if crate::security::secret_storage::SecretStore::is_encrypted(&raw) {
// Legacy `enc:` values are migrated to `enc2:` on read so they are
// rewritten on the next config save instead of lingering forever.
match store.decrypt_and_migrate(&raw) {
@@ -94,12 +94,12 @@ pub(super) fn decrypt_config_secrets_strict(
}
fn encrypt_optional_secret(
- store: &crate::security::keyring::SecretStore,
+ store: &crate::security::secret_storage::SecretStore,
value: &mut Option<String>,
field_name: &str,
) -> Result<()> {
if let Some(raw) = value.clone() {
- if !crate::security::keyring::SecretStore::is_encrypted(&raw) {
+ if !crate::security::secret_storage::SecretStore::is_encrypted(&raw) {
*value = Some(
store
.encrypt(&raw)
@@ -126,7 +126,7 @@ pub(super) fn decrypt_config_secrets(config: &mut Config, openhuman_dir: &Path)
}
// Reset the per-pass migration flag before decrypting any field.
migration_flag().store(false, Ordering::Relaxed);
- let store = crate::security::keyring::SecretStore::new(openhuman_dir, true);
+ let store = crate::security::secret_storage::SecretStore::new(openhuman_dir, true);
decrypt_optional_secret(&store, &mut config.api_key, "api_key")?;
// A MongoDB URL carries the database password.
@@ -250,7 +250,7 @@ pub(super) fn encrypt_config_secrets(config: &mut Config) -> Result<()> {
.config_path
.parent()
.context("Config path must have a parent directory")?;
- let store = crate::security::keyring::SecretStore::new(parent_dir, true);
+ let store = crate::security::secret_storage::SecretStore::new(parent_dir, true);
encrypt_optional_secret(&store, &mut config.api_key, "api_key")?;
// A MongoDB URL carries the database password.
diff --git a/crates/openhuman-core/src/config/schema/load/source/mod_tests.rs b/crates/openhuman-core/src/config/schema/load/source/mod_tests.rs
index b17484de42..f802f84a46 100644
--- a/crates/openhuman-core/src/config/schema/load/source/mod_tests.rs
+++ b/crates/openhuman-core/src/config/schema/load/source/mod_tests.rs
@@ -474,7 +474,7 @@ async fn a_document_save_never_nests_process_key_ciphertext() {
assert!(config.secrets.encrypt);
// A field still sealed under this node's key, as a file-seeded config
// holds it before the load decrypts.
- let sealed = crate::security::keyring::SecretStore::new(tmp.path(), true)
+ let sealed = crate::security::secret_storage::SecretStore::new(tmp.path(), true)
.encrypt("sk-node-local")
.unwrap();
assert!(sealed.starts_with("enc2:"));
@@ -503,7 +503,7 @@ async fn a_document_save_refuses_process_key_secrets_it_cannot_open() {
let mut config = config_at(tmp.path(), "m");
// Sealed under another node's key: this node cannot open it.
config.api_key = Some(
- crate::security::keyring::SecretStore::new(other_node.path(), true)
+ crate::security::secret_storage::SecretStore::new(other_node.path(), true)
.encrypt("sk-elsewhere")
.unwrap(),
);
diff --git a/crates/openhuman-core/src/core/runtime/context.rs b/crates/openhuman-core/src/core/runtime/context.rs
index 80e0fc6fc5..69e668edba 100644
--- a/crates/openhuman-core/src/core/runtime/context.rs
+++ b/crates/openhuman-core/src/core/runtime/context.rs
@@ -176,9 +176,9 @@ impl CoreContext {
// 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::secret_storage::init_workspace(&config.workspace_dir);
}
- crate::security::keyring::init_master_key().map_err(anyhow::Error::msg)?;
+ crate::security::secret_storage::init_master_key().map_err(anyhow::Error::msg)?;
// 4. Seed the per-process RPC bearer. `Fixed` seeds the in-memory value
// directly (never touches the env); `EnvOrFile` reads
@@ -624,7 +624,7 @@ impl StoreInitPlan {
pub async fn init_stores(cfg: &crate::config::Config, domains: crate::core::runtime::DomainSet) {
let plan = StoreInitPlan::for_domains(domains);
- let keyring_dir = crate::security::keyring::store::workspace_dir_for_file_backend();
+ let keyring_dir = crate::security::secret_storage::store::workspace_dir_for_file_backend();
// Keyring path log + credentials Sentry bind (below) are unguarded — they
// are core infra every DomainSet needs. Each workspace-bound store init is
// gated on its owning DomainGroup so an excluded domain's store stays
@@ -634,7 +634,7 @@ pub async fn init_stores(cfg: &crate::config::Config, domains: crate::core::runt
cfg.config_path.display(),
cfg.workspace_dir.display(),
keyring_dir.display(),
- crate::security::keyring::backend_name(),
+ crate::security::secret_storage::backend_name(),
domains,
);
if plan.memory {
diff --git a/crates/openhuman-core/src/core/runtime/saas.rs b/crates/openhuman-core/src/core/runtime/saas.rs
index e98107aad5..d2b098787a 100644
--- a/crates/openhuman-core/src/core/runtime/saas.rs
+++ b/crates/openhuman-core/src/core/runtime/saas.rs
@@ -346,8 +346,8 @@ pub async fn build(
}
// Root the keyring (the master key and every stored credential) under the
// operator directory, never the host's `~/.openhuman`.
- crate::security::keyring::init_workspace(&operator.workspace_dir);
- let keyring_dir = crate::security::keyring::store::workspace_dir_for_file_backend();
+ crate::security::secret_storage::init_workspace(&operator.workspace_dir);
+ let keyring_dir = crate::security::secret_storage::store::workspace_dir_for_file_backend();
if keyring_dir != operator.workspace_dir {
anyhow::bail!(
"[saas] the keyring is already rooted at {}; a SaaS core keeps it under {}",
diff --git a/crates/openhuman-core/src/core/runtime/subscribers.rs b/crates/openhuman-core/src/core/runtime/subscribers.rs
index 21eb2800f1..867cd6e1d3 100644
--- a/crates/openhuman-core/src/core/runtime/subscribers.rs
+++ b/crates/openhuman-core/src/core/runtime/subscribers.rs
@@ -196,7 +196,7 @@ pub(super) fn register_domain_subscribers(
"[auth] no session token at startup — scheduler gate set to signed_out \
(config_path={}, keyring_backend={})",
config.config_path.display(),
- crate::security::keyring::backend_name(),
+ crate::security::secret_storage::backend_name(),
);
crate::cron::scheduler_gate::set_signed_out(true);
}
@@ -205,7 +205,7 @@ pub(super) fn register_domain_subscribers(
"[auth] failed to read session token at startup ({err}) — assuming signed_out \
(config_path={}, keyring_backend={})",
config.config_path.display(),
- crate::security::keyring::backend_name(),
+ crate::security::secret_storage::backend_name(),
);
crate::cron::scheduler_gate::set_signed_out(true);
}
diff --git a/crates/openhuman-core/src/lib.rs b/crates/openhuman-core/src/lib.rs
index 9559ba3095..682d2b6a38 100644
--- a/crates/openhuman-core/src/lib.rs
+++ b/crates/openhuman-core/src/lib.rs
@@ -131,12 +131,12 @@ pub fn run_core_from_args_with(
) -> anyhow::Result<()> {
core::cli::load_dotenv_for_cli()?;
platform::service::apply_startup_restart_delay_from_env();
- // A SaaS boot roots the keyring under its operator directory
+ // A SaaS boot roots secret storage under its operator directory
// (`saas::build`), so it must not be latched to the home directory here.
if !core::cli::is_help_only(args)
&& !core::runtime::mode::requested_in(args, std::env::var("OPENHUMAN_MODE").ok().as_deref())
{
- security::keyring::init_master_key().map_err(anyhow::Error::msg)?;
+ security::secret_storage::init_master_key().map_err(anyhow::Error::msg)?;
}
core::cli::run_from_cli_args_with(args, host_boot)
}
diff --git a/crates/openhuman-core/src/memory/backfill.rs b/crates/openhuman-core/src/memory/backfill.rs
index e1f348306c..c1c59c6a58 100644
--- a/crates/openhuman-core/src/memory/backfill.rs
+++ b/crates/openhuman-core/src/memory/backfill.rs
@@ -123,8 +123,11 @@ fn write_file(workspace_dir: &Path, file: &BackfillFile) {
let result = serde_json::to_vec_pretty(file)
.map_err(|error| error.to_string())
.and_then(|json| {
- crate::security::keyring::file_store::write_atomic(&file_path(workspace_dir), &json)
- .map_err(|error| error.to_string())
+ crate::security::secret_storage::file_store::write_atomic(
+ &file_path(workspace_dir),
+ &json,
+ )
+ .map_err(|error| error.to_string())
});
if let Err(error) = result {
tracing::warn!(error = %error, "[memory:backfill] writing state failed");
diff --git a/crates/openhuman-core/src/memory/import.rs b/crates/openhuman-core/src/memory/import.rs
index 47a769a83e..4d6de9f46f 100644
--- a/crates/openhuman-core/src/memory/import.rs
+++ b/crates/openhuman-core/src/memory/import.rs
@@ -26,6 +26,7 @@ use tinymemory_integrations::cortex::is_insufficient_credits;
use tinymemory_integrations::import::{Checkpoint, ImportedItem};
use crate::config::Config;
+use crate::security::secret_storage::file_store::write_atomic;
use super::engine::{self, BoundEngine};
use super::error::{MemoryError, MemoryResult};
@@ -274,8 +275,7 @@ fn write_file(workspace_dir: &Path, file: &ImportFile) {
let result = serde_json::to_vec_pretty(file)
.map_err(|error| error.to_string())
.and_then(|json| {
- crate::security::keyring::file_store::write_atomic(&file_path(workspace_dir), &json)
- .map_err(|error| error.to_string())
+ write_atomic(&file_path(workspace_dir), &json).map_err(|error| error.to_string())
});
if let Err(error) = result {
tracing::warn!(error = %error, "[memory:import] writing import state failed");
diff --git a/crates/openhuman-core/src/security/credentials/README.md b/crates/openhuman-core/src/security/credentials/README.md
index a99d03a0a6..1375f7815d 100644
--- a/crates/openhuman-core/src/security/credentials/README.md
+++ b/crates/openhuman-core/src/security/credentials/README.md
@@ -86,7 +86,7 @@ inferred. API-key precedence and local-session behavior are unchanged.
`AuthProfilesStore` (`profiles.rs`) writes `auth-profiles.json` in the config state directory (parent of `config.config_path`, user-scoped after activation). Layout: `schema_version` (current = 1), `updated_at`, `active_profiles` (provider → profile-id), [`profiles`](./profiles) (id → profile). The `app-session` profile's metadata carries `user_id`, `user_json` (the host-supplied payload) and `session_expires_at` (the JWT `exp`, for the local expiry precheck). Secret handling:
-- **OS keychain** when available (`crate::security::keyring::is_available`): all token fields stored under key `auth:{profile_id}` namespaced by a per-user id derived from the state dir; JSON keeps no secret fields.
+- **OS keychain** when available (`crate::security::secret_storage::is_available`): all token fields stored under key `auth:{profile_id}` namespaced by a per-user id derived from the state dir; JSON keeps no secret fields.
- **Encrypted-JSON fallback** (headless/CI): token fields encrypted via `SecretStore` (ChaCha20-Poly1305).
- Loads migrate legacy `enc:`/`enc2:` cipher fields and promote secrets into the keychain; unrecoverable (un-decryptable / bad-`kind`) profiles are dropped rather than poisoning the whole store; unparseable files are quarantined to `auth-profiles.corrupt-<ts>.json` and reset to empty.
- Mutations are guarded by `auth-profiles.lock` (PID-stamped). Stale/leaked/malformed locks are reclaimed by liveness + age checks to avoid the "stuck on Initializing OpenHuman" hang.
@@ -105,7 +105,7 @@ across processes; the local file lock still serializes one host.
## Dependencies
- `crate::config`: `Config`, config load (`load_config_with_timeout`), user-dir activation (`default_root_openhuman_dir`, `user_openhuman_dir`, `read/write/clear_active_user`, `pre_login_user_dir`), onboarding state.
-- `crate::security::keyring`: `SecretStore` (encrypt/decrypt) and OS keychain `get`/`set`/`delete`/`is_available`.
+- `crate::security::secret_storage`: `SecretStore` (encrypt/decrypt) and OS keychain `get`/`set`/`delete`/`is_available`.
- `crate::cron::scheduler_gate`: signed-out override flipped on install/removal/expiry.
- `crate::memory::conversations`: purge pre-login threads, bind conversation persistence after activation.
- `crate::memory`: bind memory client to the active workspace after activation.
diff --git a/crates/openhuman-core/src/security/credentials/credential_ref.rs b/crates/openhuman-core/src/security/credentials/credential_ref.rs
index d4173cc0d8..a7a149918b 100644
--- a/crates/openhuman-core/src/security/credentials/credential_ref.rs
+++ b/crates/openhuman-core/src/security/credentials/credential_ref.rs
@@ -18,7 +18,7 @@
//!
//! ## Three refusals before the keychain is touched
//!
-//! Resolution is deliberately not a bare [`keyring::get`]:
+//! Resolution is deliberately not a bare [`secret_storage::get`]:
//!
//! 1. **Consent.** [`keyring_consent::policy::check_secret_access`] must return
//! [`PolicyDecision::Proceed`]. A prompt that has not been answered is not a
@@ -37,7 +37,7 @@
//! The order is enforced structurally, not by convention: [`preflight`] takes
//! availability as a **closure**, so a refused consent decision returns before
//! the probe can run. That matters because the probe is a real backend
-//! round-trip on its first call (`keyring::ops`' availability cache starts
+//! round-trip on its first call (`secret_storage::ops`' availability cache starts
//! empty) — evaluating it eagerly would touch the keychain on exactly the paths
//! this gate exists to stop.
//!
@@ -53,7 +53,7 @@
//! `subsystems_status` — pinned by
//! `fallback_reason_never_contains_credential_ref_or_endpoint`.
//!
-//! The sharp edge is [`KeyringError`](keyring::KeyringError), whose own
+//! The sharp edge is [`SecretStorageError`](secret_storage::SecretStorageError), whose own
//! `Display` interpolates the key (`"OS keychain error for key '{key}':
//! {source}"`) — and so does its `diagnostic()`, which is `{self:?}`.
//! Propagating or logging one verbatim would leak the very name this module
@@ -67,7 +67,7 @@
//! protecting the wrong half.
//!
//! **Scope of that promise.** It covers this module's errors, this module's
-//! logs, and the types it returns. It does **not** cover `keyring::get`, which
+//! logs, and the types it returns. It does **not** cover `secret_storage::get`, which
//! logs its `key=` argument at `debug` as the whole keyring surface has always
//! done for its fixed-name callers — a `credential_ref` is simply the first
//! *operator-configured* key to reach it. Narrowing that is a shared-kernel
@@ -77,8 +77,8 @@
use zeroize::Zeroizing;
-use crate::security::keyring;
use crate::security::keyring_consent::{policy, PolicyDecision};
+use crate::security::secret_storage;
/// Log prefix for this module's diagnostics.
const LOG_PREFIX: &str = "[security:credential-ref]";
@@ -141,7 +141,7 @@ pub enum CredentialRefError {
NotFound,
/// The keychain backend failed. Detail is logged, never rendered — see the
- /// module docs on [`KeyringError`](keyring::KeyringError).
+ /// module docs on [`SecretStorageError`](secret_storage::SecretStorageError).
#[error("keychain lookup failed")]
Backend,
}
@@ -159,7 +159,7 @@ pub enum CredentialRefError {
/// `keychain_available` is a **closure, not a `bool`**, so the order is a
/// property of the code rather than of the call site. Passing the probe's
/// result would evaluate it before this function is entered, and
-/// `keyring::is_available`'s first call is a real backend round-trip — the
+/// `secret_storage::is_available`'s first call is a real backend round-trip — the
/// keychain would be touched on precisely the paths consent just refused.
///
/// The decision is matched exhaustively rather than compared against
@@ -183,7 +183,7 @@ pub fn preflight(
None
}
-/// A fixed, name-free label for a [`KeyringError`](keyring::KeyringError).
+/// A fixed, name-free label for a [`SecretStorageError`](secret_storage::SecretStorageError).
///
/// Both that type's `Display` and its `diagnostic()` interpolate the key, so
/// neither may be logged from a path whose key is a credential reference. This
@@ -194,8 +194,8 @@ pub fn preflight(
/// rather than a silent fall-through to a wrong label. The five folded into
/// `"backend"` cannot arise from a `get`: they belong to `set`, migration and
/// random generation.
-fn keyring_error_kind(e: &keyring::KeyringError) -> &'static str {
- use keyring::KeyringError as E;
+fn keyring_error_kind(e: &secret_storage::SecretStorageError) -> &'static str {
+ use secret_storage::SecretStorageError as E;
match e {
E::InvalidUtf8 { .. } => "invalid-utf8",
E::Crypto(_) => "crypto",
@@ -211,7 +211,7 @@ fn keyring_error_kind(e: &keyring::KeyringError) -> &'static str {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CredentialRefScheme {
- /// `keychain:<name>` — resolved through [`keyring`].
+ /// `keychain:<name>` — resolved through [`secret_storage`].
Keychain,
}
@@ -389,10 +389,12 @@ impl CredentialRef {
}
fn resolve_keychain(&self, user_id: &str) -> Result<ResolvedSecret, CredentialRefError> {
- // `keyring::is_available` is passed unevaluated: a consent refusal must
+ // `secret_storage::is_available` is passed unevaluated: a consent refusal must
// return before the availability probe, whose first call is a real
// backend round-trip. See `preflight`.
- if let Some(refusal) = preflight(policy::check_secret_access(), keyring::is_available) {
+ if let Some(refusal) =
+ preflight(policy::check_secret_access(), secret_storage::is_available)
+ {
log::debug!(
"{LOG_PREFIX} keychain access refused before lookup user_id={user_id} \
refusal={refusal}"
@@ -400,7 +402,7 @@ impl CredentialRef {
return Err(refusal);
}
- match keyring::get(user_id, &self.name) {
+ match secret_storage::get(user_id, &self.name) {
Ok(Some(secret)) => {
log::debug!("{LOG_PREFIX} resolved credential_ref user_id={user_id}");
Ok(ResolvedSecret::new(secret))
@@ -409,7 +411,7 @@ impl CredentialRef {
log::debug!("{LOG_PREFIX} no keychain entry for credential_ref user_id={user_id}");
Err(CredentialRefError::NotFound)
}
- // Classified, never rendered: `KeyringError`'s `Display` — and its
+ // Classified, never rendered: `SecretStorageError`'s `Display` — and its
// `diagnostic()`, which is `{self:?}` — both interpolate the key.
// Formatting either here would write the credential name to a
// retained warn-level log, which is the leak this module's
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 dd34528a4a..2269106aee 100644
--- a/crates/openhuman-core/src/security/credentials/credential_ref_tests.rs
+++ b/crates/openhuman-core/src/security/credentials/credential_ref_tests.rs
@@ -282,23 +282,29 @@ fn preflight_never_reports_a_missing_entry() {
#[test]
fn keyring_error_kinds_are_fixed_labels_that_carry_no_key() {
// The classifier exists so a backend failure can be logged without
- // formatting a `KeyringError`, whose `Display` *and* `diagnostic()` both
+ // formatting a `SecretStorageError`, whose `Display` *and* `diagnostic()` both
// interpolate the key. Every label must therefore be free of it.
- use crate::security::keyring::KeyringError;
+ use crate::security::secret_storage::SecretStorageError;
let invalid_utf8 = String::from_utf8(vec![0xff]).expect_err("0xff is not utf-8");
- let cases: Vec<(KeyringError, &str)> = vec![
- (KeyringError::Backend(SECRET_NAME.to_string()), "backend"),
+ let cases: Vec<(SecretStorageError, &str)> = vec![
(
- KeyringError::InvalidUtf8 {
+ SecretStorageError::Backend(SECRET_NAME.to_string()),
+ "backend",
+ ),
+ (
+ SecretStorageError::InvalidUtf8 {
key: SECRET_NAME.to_string(),
source: invalid_utf8,
},
"invalid-utf8",
),
- (KeyringError::Crypto(SECRET_NAME.to_string()), "crypto"),
(
- KeyringError::VerifyFailed {
+ SecretStorageError::Crypto(SECRET_NAME.to_string()),
+ "crypto",
+ ),
+ (
+ SecretStorageError::VerifyFailed {
key: SECRET_NAME.to_string(),
},
"backend",
diff --git a/crates/openhuman-core/src/security/credentials/http_creds.rs b/crates/openhuman-core/src/security/credentials/http_creds.rs
index 51a09d7e50..81d3d245fa 100644
--- a/crates/openhuman-core/src/security/credentials/http_creds.rs
+++ b/crates/openhuman-core/src/security/credentials/http_creds.rs
@@ -4,7 +4,7 @@
//! `"http_cred:<name>"`. This module is the host-side store those names resolve
//! against: each record is an **injection template** (bearer token, HTTP basic
//! user:pass, or a raw custom header) whose secret material is encrypted at
-//! rest with the same [`SecretStore`](crate::security::keyring::SecretStore)
+//! rest with the same [`SecretStore`](crate::security::secret_storage::SecretStore)
//! (ChaCha20-Poly1305) the auth-profile store uses.
//!
//! **Security contract:** the secret value NEVER leaves this module except as
@@ -23,7 +23,7 @@ use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::config::Config;
-use crate::security::keyring::SecretStore;
+use crate::security::secret_storage::SecretStore;
const STORE_FILENAME: &str = "http-credentials.json";
const CURRENT_SCHEMA_VERSION: u32 = 1;
diff --git a/crates/openhuman-core/src/security/credentials/ops/secrets.rs b/crates/openhuman-core/src/security/credentials/ops/secrets.rs
index 126355cbbe..09bc86ed43 100644
--- a/crates/openhuman-core/src/security/credentials/ops/secrets.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/secrets.rs
@@ -2,7 +2,7 @@
use crate::config::Config;
use crate::core::Outcome;
-use crate::security::keyring::SecretStore;
+use crate::security::secret_storage::SecretStore;
pub(crate) fn secret_store_for_config(config: &Config) -> SecretStore {
let data_dir = config
diff --git a/crates/openhuman-core/src/security/credentials/profiles.rs b/crates/openhuman-core/src/security/credentials/profiles.rs
index 36d106c1f3..be10d29aeb 100644
--- a/crates/openhuman-core/src/security/credentials/profiles.rs
+++ b/crates/openhuman-core/src/security/credentials/profiles.rs
@@ -1,4 +1,4 @@
-use crate::security::keyring::SecretStore;
+use crate::security::secret_storage::SecretStore;
use crate::util::retry_with_backoff;
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
@@ -270,7 +270,7 @@ pub struct AuthProfilesStore {
/// ciphertext, leaving `.secret_key` as the only remaining control.
///
/// Same shape as the fix #2360 landed for the secret key in
-/// `keyring/encrypted_store.rs`: create with the mode already set rather than
+/// `secret_storage/encrypted_store.rs`: create with the mode already set rather than
/// widening then narrowing, so the file is never briefly world-readable.
///
/// `.mode()` only applies when the file is *created*, so a leftover tmp from an
diff --git a/crates/openhuman-core/src/security/credentials/profiles/keychain.rs b/crates/openhuman-core/src/security/credentials/profiles/keychain.rs
index 040318cd1b..f39829874c 100644
--- a/crates/openhuman-core/src/security/credentials/profiles/keychain.rs
+++ b/crates/openhuman-core/src/security/credentials/profiles/keychain.rs
@@ -24,7 +24,7 @@ impl AuthProfilesStore {
});
let payload = serde_json::to_string(&secrets)
.context("Failed to serialize auth secrets for keychain")?;
- crate::security::keyring::set(&self.user_id, &key, &payload).map_err(|e| {
+ crate::security::secret_storage::set(&self.user_id, &key, &payload).map_err(|e| {
anyhow::anyhow!(
"Keychain set failed for profile {}: {e} | detail={}",
profile.id,
@@ -47,7 +47,7 @@ impl AuthProfilesStore {
profile_id: &str,
) -> anyhow::Result<Option<KeychainSecrets>> {
let key = self.keychain_key_for_profile(profile_id);
- let payload = match crate::security::keyring::get(&self.user_id, &key) {
+ let payload = match crate::security::secret_storage::get(&self.user_id, &key) {
Ok(Some(p)) => p,
Ok(None) => {
log::debug!(
@@ -78,7 +78,7 @@ impl AuthProfilesStore {
/// Delete keychain secrets for a profile (called on profile removal).
pub(super) fn keychain_delete_secrets(&self, profile_id: &str) {
let key = self.keychain_key_for_profile(profile_id);
- if let Err(e) = crate::security::keyring::delete(&self.user_id, &key) {
+ if let Err(e) = crate::security::secret_storage::delete(&self.user_id, &key) {
log::warn!(
"[auth] keychain_delete_secrets error profile_id={profile_id} user_id={}: {e} | detail={}",
self.user_id,
diff --git a/crates/openhuman-core/src/security/credentials/profiles/store_core.rs b/crates/openhuman-core/src/security/credentials/profiles/store_core.rs
index 657e2359ca..19629e43f0 100644
--- a/crates/openhuman-core/src/security/credentials/profiles/store_core.rs
+++ b/crates/openhuman-core/src/security/credentials/profiles/store_core.rs
@@ -13,7 +13,7 @@ use super::{
is_lock_create_unwritable_fs, AuthProfile, AuthProfilesData, AuthProfilesStore,
PROFILES_FILENAME,
};
-use crate::security::keyring::SecretStore;
+use crate::security::secret_storage::SecretStore;
use super::LOCK_FILENAME;
@@ -22,7 +22,7 @@ impl AuthProfilesStore {
let user_id = super::user_id_from_state_dir(state_dir);
let policy = crate::security::keyring_consent::policy::check_secret_access();
let use_keychain = policy == crate::security::keyring_consent::PolicyDecision::Proceed
- && crate::security::keyring::is_available();
+ && crate::security::secret_storage::is_available();
log::debug!(
"[auth] AuthProfilesStore::new state_dir={} user_id={user_id} use_keychain={use_keychain} policy={policy:?}",
state_dir.display()
diff --git a/crates/openhuman-core/src/security/credentials/profiles_store_lock_tests.rs b/crates/openhuman-core/src/security/credentials/profiles_store_lock_tests.rs
index 2701025a75..7a97f62ca0 100644
--- a/crates/openhuman-core/src/security/credentials/profiles_store_lock_tests.rs
+++ b/crates/openhuman-core/src/security/credentials/profiles_store_lock_tests.rs
@@ -189,7 +189,7 @@ fn load_drops_profiles_whose_decryption_fails_under_rotated_key() {
// that the current key cannot decrypt.
let user_id = user_id_from_state_dir(tmp.path());
let keychain_key = format!("{KEYCHAIN_AUTH_PREFIX}{}", doomed.id);
- crate::security::keyring::delete(&user_id, &keychain_key)
+ crate::security::secret_storage::delete(&user_id, &keychain_key)
.expect("delete keychain entry for test setup");
let path = store.path().to_path_buf();
diff --git a/crates/openhuman-core/src/security/devices/README.md b/crates/openhuman-core/src/security/devices/README.md
index 7034a2da88..44905decdc 100644
--- a/crates/openhuman-core/src/security/devices/README.md
+++ b/crates/openhuman-core/src/security/devices/README.md
@@ -98,7 +98,7 @@ revives a device another process revoked. With no backend configured (the deskto
## Dependencies
- `crate::config` (`Config`, `config::rpc::load_config_with_timeout`): workspace paths and config loading for handlers.
-- `crate::security::keyring::SecretStore`: encrypt/decrypt the X25519 private key at rest.
+- `crate::security::secret_storage::SecretStore`: encrypt/decrypt the X25519 private key at rest.
- `crate::platform::socket::global_socket_manager`: reuse the shared backend Socket.IO connection to emit `tunnel:*` events (no second WebSocket).
- `crate::core::bus::BUS` (`.publish`, `.subscribe`) plus `crate::core::events::DomainEvent` and `tinybus::EventHandler`: pub/sub for device tunnel events.
- `crate::core::all` (`ControllerFuture`, `RegisteredController`) and `crate::core::{ControllerSchema, FieldSchema, TypeSchema}`: controller registry contract.
diff --git a/crates/openhuman-core/src/security/devices/rpc.rs b/crates/openhuman-core/src/security/devices/rpc.rs
index cc5a79dbd1..318ef0b568 100644
--- a/crates/openhuman-core/src/security/devices/rpc.rs
+++ b/crates/openhuman-core/src/security/devices/rpc.rs
@@ -21,7 +21,7 @@ use crate::security::devices::tunnel_client;
use crate::security::devices::types::{
CreatePairingResponse, ListDevicesResponse, PairingSession, RevokeDeviceResponse,
};
-use crate::security::keyring::SecretStore;
+use crate::security::secret_storage::SecretStore;
// ---------------------------------------------------------------------------
// In-memory state (module-level singletons)
diff --git a/crates/openhuman-core/src/security/encryption/README.md b/crates/openhuman-core/src/security/encryption/README.md
index 096ffaeeb7..ce1bf6f33b 100644
--- a/crates/openhuman-core/src/security/encryption/README.md
+++ b/crates/openhuman-core/src/security/encryption/README.md
@@ -27,7 +27,7 @@ AES-256-GCM at-rest crypto for AI memory storage and the encrypt/decrypt RPC sur
## Tests
-- This domain has no `*_tests.rs` siblings; the underlying crypto round-trips are exercised by `crates/openhuman-core/src/security/keyring/encrypted_store_tests.rs` and the credentials tests, which both cover encrypt/decrypt happy paths and tampered-ciphertext rejection.
+- This domain has no `*_tests.rs` siblings; the underlying crypto round-trips are exercised by `crates/openhuman-core/src/security/secret_storage/encrypted_store_tests.rs` and the credentials tests, which both cover encrypt/decrypt happy paths and tampered-ciphertext rejection.
## Further reading
diff --git a/crates/openhuman-core/src/security/keyring_consent/README.md b/crates/openhuman-core/src/security/keyring_consent/README.md
index 4f7ef95fec..c023689f41 100644
--- a/crates/openhuman-core/src/security/keyring_consent/README.md
+++ b/crates/openhuman-core/src/security/keyring_consent/README.md
@@ -2,7 +2,7 @@
Gates the fallback from the OS keyring to local encrypted storage behind
explicit user consent. All code that reads or writes secrets should call
-`policy::check_secret_access()` instead of `keyring::is_available()` directly,
+`policy::check_secret_access()` instead of `secret_storage::is_available()` directly,
so the app never silently drops to local storage without the user agreeing.
## Responsibilities
@@ -46,7 +46,7 @@ so the app never silently drops to local storage without the user agreeing.
`check_secret_access()`.
- `policy::check_secret_access() -> PolicyDecision`: the gate every secret
read/write path should call. Returns `Proceed` immediately if
- `keyring::is_available()`; otherwise consults the cached consent
+ `secret_storage::is_available()`; otherwise consults the cached consent
(`local_encrypted` → `Proceed`, `declined` → `Declined`, none → publishes
`KeyringConsentRequired` once and returns `ConsentRequired`).
- `policy::current_status() -> KeyringStatus`: snapshot for RPC/UI.
@@ -85,7 +85,7 @@ unchanged value are a silent no-op.
(`get`/`set`/`delete`, `SecretStore`, `encrypted_file_backend.rs`). This
domain never stores a secret itself. It only gates and reports on *which*
backend is active and whether the user consented to it. `active_mode_for`
-matches on `keyring::backend_name()`'s identifiers (`"os"`,
+matches on `secret_storage::backend_name()`'s identifiers (`"os"`,
`"encrypted_file"`, `"file"`, `"mock"`) to answer that question.
## Used by
diff --git a/crates/openhuman-core/src/security/keyring_consent/policy.rs b/crates/openhuman-core/src/security/keyring_consent/policy.rs
index 42e817c627..1be089c6f3 100644
--- a/crates/openhuman-core/src/security/keyring_consent/policy.rs
+++ b/crates/openhuman-core/src/security/keyring_consent/policy.rs
@@ -1,7 +1,7 @@
//! Unified keyring fallback policy gate.
//!
//! All code paths that read or write secrets should call [`check_secret_access`]
-//! instead of raw `keyring::is_available()`. This centralises the consent check
+//! instead of raw `secret_storage::is_available()`. This centralises the consent check
//! so the app never silently falls back to local encrypted storage without the
//! user's explicit agreement.
@@ -55,7 +55,7 @@ pub fn initialize(consent: Option<ConsentPreference>) -> bool {
/// Check whether the caller is allowed to proceed with secret storage.
pub fn check_secret_access() -> PolicyDecision {
- if crate::security::keyring::is_available() {
+ if crate::security::secret_storage::is_available() {
return PolicyDecision::Proceed;
}
@@ -81,9 +81,10 @@ pub fn check_secret_access() -> PolicyDecision {
}
}
-/// Backend identifiers as [`crate::security::keyring::backend_name`]
+/// Backend identifiers as [`crate::security::secret_storage::backend_name`]
/// reports them. Kept here rather than matched as bare literals so the mapping
/// below reads as a table and a rename upstream fails in one place.
+const BACKEND_MEMORY: &str = "memory";
const BACKEND_OS: &str = "os";
const BACKEND_ENCRYPTED_FILE: &str = "encrypted_file";
const BACKEND_FILE: &str = "file";
@@ -132,6 +133,7 @@ fn active_mode_for(
}
// Operator-configured backends. No consent was ever asked for, so the
// consent cache says nothing about where these secrets are.
+ BACKEND_MEMORY => StorageMode::InMemory,
BACKEND_ENCRYPTED_FILE => StorageMode::LocalEncryptedFile,
BACKEND_FILE | BACKEND_MOCK => StorageMode::LocalPlaintextFile,
// A backend added without extending this table. Reporting `os_keyring`
@@ -149,8 +151,8 @@ fn active_mode_for(
/// Build the current keyring status for RPC / snapshot consumption.
pub fn current_status() -> KeyringStatus {
- let available = crate::security::keyring::is_available();
- let backend_name = crate::security::keyring::backend_name();
+ let available = crate::security::secret_storage::is_available();
+ let backend_name = crate::security::secret_storage::backend_name();
let cached = CONSENT_CACHE.read().clone();
let active_mode = active_mode_for(available, &backend_name, cached.as_ref());
@@ -213,7 +215,7 @@ pub fn record_consent(mode: &str) -> ConsentPreference {
/// Reset the cached keyring probe and re-run it.
pub fn retry_probe() -> KeyringStatus {
info!("{LOG_PREFIX} retry_probe: resetting availability cache");
- crate::security::keyring::reset_availability_cache();
+ crate::security::secret_storage::reset_availability_cache();
CONSENT_EVENT_PUBLISHED.store(false, Ordering::SeqCst);
current_status()
}
diff --git a/crates/openhuman-core/src/security/keyring_consent/policy_tests.rs b/crates/openhuman-core/src/security/keyring_consent/policy_tests.rs
index 9e0f7bec56..24db7cd5db 100644
--- a/crates/openhuman-core/src/security/keyring_consent/policy_tests.rs
+++ b/crates/openhuman-core/src/security/keyring_consent/policy_tests.rs
@@ -225,3 +225,11 @@ fn status_payload_mode_and_backend_never_contradict() {
}
}
}
+
+#[test]
+fn memory_status_never_claims_disk_storage_or_pending_consent() {
+ let mode = active_mode_for(true, BACKEND_MEMORY, Some(&consent("local_encrypted")));
+ assert_eq!(mode, StorageMode::InMemory);
+ assert_eq!(serde_json::to_value(mode).unwrap(), "in_memory");
+ assert_eq!(mode.to_string(), "in_memory");
+}
diff --git a/crates/openhuman-core/src/security/keyring_consent/types.rs b/crates/openhuman-core/src/security/keyring_consent/types.rs
index 786703bc0a..3f277a0f9f 100644
--- a/crates/openhuman-core/src/security/keyring_consent/types.rs
+++ b/crates/openhuman-core/src/security/keyring_consent/types.rs
@@ -4,9 +4,10 @@ use serde::{Deserialize, Serialize};
/// Where the process's secrets actually live.
///
-/// The variants fall into three groups. They are named here rather than
+/// The variants fall into four groups. They are named here rather than
/// referred to by position, because position is what rots:
///
+/// - `InMemory` — the basic volatile library store, with no OS or disk storage.
/// - `OsKeyring` — no consent was ever needed; the `os` backend's probe
/// succeeded and secrets are in the OS credential store.
/// - `LocalEncrypted` / `ConsentPending` / `Declined` — **consent outcomes**,
@@ -14,7 +15,7 @@ use serde::{Deserialize, Serialize};
/// the user has either answered the consent prompt or not answered yet.
/// - `LocalEncryptedFile` / `LocalPlaintextFile` — **operator-configured
/// backends**: nobody was asked anything, `OPENHUMAN_KEYRING_BACKEND` (or
-/// the staging/production default) simply selected a different store.
+/// a product host's persistent default) simply selected a different store.
///
/// The last two groups must stay apart because they are not the same storage:
/// a consented `LocalEncrypted` fallback means per-field `SecretStore`
@@ -27,6 +28,8 @@ use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StorageMode {
+ /// Volatile, unencrypted values held only in process memory.
+ InMemory,
/// The `os` backend, probed and working: macOS Keychain, Windows
/// Credential Manager, or Linux Secret Service.
OsKeyring,
@@ -35,7 +38,7 @@ pub enum StorageMode {
LocalEncrypted,
/// Operator-configured `encrypted_file` backend — one ChaCha20-Poly1305
/// `{workspace}/secrets.enc`, unlocked by a master key held in the OS
- /// keychain. The staging/production default.
+ /// keychain. The product-host default.
LocalEncryptedFile,
/// Operator-configured `file` (or test-only `mock`) backend. `file` is a
/// **plaintext** `{workspace}/dev-keychain.json` with no encryption and no
@@ -50,6 +53,7 @@ pub enum StorageMode {
impl std::fmt::Display for StorageMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
+ Self::InMemory => write!(f, "in_memory"),
Self::OsKeyring => write!(f, "os_keyring"),
Self::LocalEncrypted => write!(f, "local_encrypted"),
Self::LocalEncryptedFile => write!(f, "local_encrypted_file"),
diff --git a/crates/openhuman-core/src/security/mod.rs b/crates/openhuman-core/src/security/mod.rs
index 1d6ecc4bf1..f9f3ec53a6 100644
--- a/crates/openhuman-core/src/security/mod.rs
+++ b/crates/openhuman-core/src/security/mod.rs
@@ -14,7 +14,6 @@ pub mod credentials;
pub mod devices;
pub mod egress;
pub mod encryption;
-pub mod keyring;
pub mod keyring_consent;
pub mod live_policy;
pub mod pairing;
@@ -22,10 +21,11 @@ pub mod pii;
pub mod policy;
pub mod prompt_injection;
pub mod scrub;
+pub mod secret_storage;
pub mod secrets;
#[allow(unused_imports)]
-pub use self::keyring::SecretStore;
+pub use self::secret_storage::SecretStore;
#[allow(unused_imports)]
pub use audit::{
get_or_create_workspace_audit_logger, AuditEvent, AuditEventType, AuditLogger,
diff --git a/crates/openhuman-core/src/security/keyring/README.md b/crates/openhuman-core/src/security/secret_storage/README.md
similarity index 56%
rename from crates/openhuman-core/src/security/keyring/README.md
rename to crates/openhuman-core/src/security/secret_storage/README.md
index bb431b009f..eab2288d46 100644
--- a/crates/openhuman-core/src/security/keyring/README.md
+++ b/crates/openhuman-core/src/security/secret_storage/README.md
@@ -1,43 +1,46 @@
-# keyring
+# Secret storage
-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}"`.
+Host-installable secret storage with an in-memory default, plus a ChaCha20-Poly1305 encrypted secret store for config-field encryption. Native keychains live in `openhuman-rpc::keyring`; this module has no OS credential-store dependency. 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.
-- Resolve the host-installed backend first, then an explicit environment override, then the encrypted-file default. Cache the fallback in a `OnceLock`.
+- Resolve the host-installed backend first, then an explicit environment override, then the in-memory 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.
+- Migrate a secret from a plaintext file into a persistent backend (`migrate_from_file`), verifying the write before deleting the source. Volatile providers reject migration and retain 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 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.
+`MemoryBackend` is a thread-safe map with no disk or OS access. Each instance owns its values; the default instance is cached process-wide. Install a custom `SecretBackend` before boot when an embedder needs persistence.
+
## Key files
| File | Role |
| --- | --- |
-| `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 `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 `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)). |
+| `crates/openhuman-core/src/security/secret_storage/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/secret_storage/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/secret_storage/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/secret_storage/memory_backend.rs` | Basic in-memory backend, default for core and embed; no key initialization or secret files. |
+| `crates/openhuman-core/src/security/secret_storage/backend.rs` | `SecretBackend` trait plus `FileBackend` (plaintext `dev-keychain.json`, test/debug only), and test-only `MockBackend`. |
+| `crates/openhuman-core/src/security/secret_storage/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/secret_storage/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/secret_storage/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/secret_storage/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/secret_storage/error.rs` | `SecretStorageError` (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/secret_storage/mod_tests.rs` | Module tests (backend isolation via `force_backend_for_test`). |
+| `crates/openhuman-core/src/security/secret_storage/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/secret_storage/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)). |
## Public surface
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.
+- `SecretBackend`: backend trait (`get`/`set`/`delete`/`name`).
+- `install_secret_backend`, `installed_secret_backend`, `clear_secret_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()`.
+- `SecretStorageError`: error enum with `diagnostic()`.
- `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`.
@@ -45,7 +48,7 @@ Re-exported from [`mod.rs`](./mod.rs):
## RPC / controllers
-None. The keyring domain exposes no `schemas.rs`, no `all_*_controller_schemas`, and no `openhuman.keyring_*` methods. It is consumed in-process by other domains.
+None. The secret-storage domain exposes no `schemas.rs`, no `all_*_controller_schemas`, and no `openhuman.keyring_*` methods. It is consumed in-process by other domains.
## Agent tools
@@ -60,11 +63,12 @@ None. There is no `bus.rs`, and the module publishes and subscribes to no `Domai
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`): 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.
+- `memory` (core/embed default): unencrypted values in a thread-safe in-memory map, lost when the process exits.
+- `encrypted_file` (explicit selection or RPC product-host default): 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.
+`SecretStore` additionally manages a master encryption key: on the active process backend (slot `secretstore.master_key`) in normal builds with one-time migration into persistent providers from the legacy `{data_dir}/openhuman/.secret_key` file; memory providers read existing legacy keys without deleting them and keep new keys only in memory. Unit tests also retain the legacy file path. Decoded keys are cached process-wide, keyed by normalized path.
The workspace dir resolves from `init_workspace`, else `OPENHUMAN_WORKSPACE`, else `~/.openhuman` (or `~/.openhuman-staging` under `OPENHUMAN_APP_ENV=staging`). In `cfg(test)` builds only, that rule is bypassed; see the test-isolation note below.
@@ -87,11 +91,11 @@ written by this module), used by `crypto.rs` and `SecretStore`.
## Dependencies
-Internal openhuman/core modules: none. The keyring module's own files only `use crate::security::keyring::*` (self-internal). It is a leaf infrastructure module. External crates: `keyring`, `chacha20poly1305`, `serde_json`, `parking_lot`, `thiserror`, `anyhow`, `chrono`, `dirs`.
+Internal modules: configuration and workspace resolution, storage-driver execution, and the core-owned secret-access consent policy. Native keychain providers are installed by RPC and accessed only through `SecretBackend` and `MasterKeySource`. File persistence uses `tinystoragedrivers::secrets`; encryption uses `chacha20poly1305`. This module has no `keyring` dependency.
## Used by
-Discovered consumers (`crate::security::keyring::*`):
+Discovered consumers (`crate::security::secret_storage::*`):
- `crates/openhuman-core/src/lib.rs` and `crates/openhuman-core/src/core/runtime/context.rs`: call `init_master_key()` at startup.
- `crates/openhuman-core/src/security/secrets.rs`, `crates/openhuman-core/src/security/mod.rs`: secret handling.
@@ -103,10 +107,10 @@ 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 also defaults to encrypted storage.
+- Installed providers take precedence, then `OPENHUMAN_KEYRING_BACKEND` (`memory`/`os`/`file`/`encrypted_file`), then `MemoryBackend`. The fallback is cached for the process lifetime. Memory secrets do not survive a restart. RPC product hosts explicitly install a persistent default; embedders can install their own backend before runtime boot.
+- 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. Library and standalone core defaults are in-memory; RPC product hosts explicitly select persistent 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. 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()` 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. Memory, 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.
diff --git a/crates/openhuman-core/src/security/keyring/adapter.rs b/crates/openhuman-core/src/security/secret_storage/adapter.rs
similarity index 83%
rename from crates/openhuman-core/src/security/keyring/adapter.rs
rename to crates/openhuman-core/src/security/secret_storage/adapter.rs
index 95090efe70..97ac9fb817 100644
--- a/crates/openhuman-core/src/security/keyring/adapter.rs
+++ b/crates/openhuman-core/src/security/secret_storage/adapter.rs
@@ -8,12 +8,12 @@ use tinystoragedrivers::secrets::{EncryptedFileSecrets, SecretStore as _};
use tinystoragedrivers::{ErrorKind, StorageError};
use zeroize::Zeroizing;
-use crate::security::keyring::error::KeyringError;
-use crate::security::keyring::file_store;
+use crate::security::secret_storage::error::SecretStorageError;
+use crate::security::secret_storage::file_store;
-/// A driver error as a [`KeyringError::Backend`], for the file store.
-pub(super) fn backend_error(error: StorageError) -> KeyringError {
- KeyringError::Backend(format!("secret store: {error}"))
+/// A driver error as a [`SecretStorageError::Backend`], for the file store.
+pub(super) fn backend_error(error: StorageError) -> SecretStorageError {
+ SecretStorageError::Backend(format!("secret store: {error}"))
}
/// Whether the driver reports the secrets file itself as unreadable
@@ -26,10 +26,10 @@ pub(super) fn is_corruption(error: &StorageError) -> bool {
pub(super) fn utf8(
key: &str,
value: Option<Zeroizing<Vec<u8>>>,
-) -> Result<Option<String>, KeyringError> {
+) -> Result<Option<String>, SecretStorageError> {
value
.map(|bytes| {
- String::from_utf8(bytes.to_vec()).map_err(|source| KeyringError::InvalidUtf8 {
+ String::from_utf8(bytes.to_vec()).map_err(|source| SecretStorageError::InvalidUtf8 {
key: key.to_string(),
source,
})
@@ -57,7 +57,7 @@ pub(super) fn recover_corrupt_file(
path: &Path,
key: &[u8; 32],
cause: &StorageError,
-) -> Result<(), KeyringError> {
+) -> Result<(), SecretStorageError> {
let _guard = file_store::lock_for_write(path)?;
let store = EncryptedFileSecrets::at_path(path, Zeroizing::new(*key));
match crate::storage::block_on(async move { store.list("").await }) {
@@ -77,7 +77,7 @@ pub(super) fn recover_corrupt_file(
cause.message()
);
if file_store::quarantine_corrupt(path, "enc").is_none() {
- return Err(KeyringError::Backend(
+ return Err(SecretStorageError::Backend(
"secrets file is unreadable and could not be moved aside".to_string(),
));
}
diff --git a/crates/openhuman-core/src/security/keyring/adapter_tests.rs b/crates/openhuman-core/src/security/secret_storage/adapter_tests.rs
similarity index 96%
rename from crates/openhuman-core/src/security/keyring/adapter_tests.rs
rename to crates/openhuman-core/src/security/secret_storage/adapter_tests.rs
index 622f4b3f7c..5875d9ac8d 100644
--- a/crates/openhuman-core/src/security/keyring/adapter_tests.rs
+++ b/crates/openhuman-core/src/security/secret_storage/adapter_tests.rs
@@ -1,6 +1,6 @@
//! Encrypted-file corruption and import policy over the secret-store port.
use super::*;
-use crate::security::keyring::encrypted_file_backend::EncryptedFileBackend;
+use crate::security::secret_storage::encrypted_file_backend::EncryptedFileBackend;
use std::collections::HashMap;
use tinystoragedrivers::secrets::crypto;
// ── EncryptedFileBackend ─────────────────────────────────────────────────────
@@ -105,7 +105,7 @@ fn recovery_never_quarantines_a_file_that_is_not_confirmed_corrupt() {
std::fs::create_dir(&path).unwrap();
let cause = tinystoragedrivers::StorageError::crypto("earlier failure");
let error = recover_corrupt_file(&path, &KEY, &cause).unwrap_err();
- assert!(matches!(error, KeyringError::Backend(_)), "{error:?}");
+ assert!(matches!(error, SecretStorageError::Backend(_)), "{error:?}");
assert!(path.is_dir(), "left in place");
}
diff --git a/crates/openhuman-core/src/security/keyring/backend.rs b/crates/openhuman-core/src/security/secret_storage/backend.rs
similarity index 83%
rename from crates/openhuman-core/src/security/keyring/backend.rs
rename to crates/openhuman-core/src/security/secret_storage/backend.rs
index eb40815ccd..22cb119a2a 100644
--- a/crates/openhuman-core/src/security/keyring/backend.rs
+++ b/crates/openhuman-core/src/security/secret_storage/backend.rs
@@ -3,22 +3,27 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
-use crate::security::keyring::error::KeyringError;
-use crate::security::keyring::file_store;
+use crate::security::secret_storage::error::SecretStorageError;
+use crate::security::secret_storage::file_store;
// ── Trait ─────────────────────────────────────────────────────────────────────
/// Abstraction over a secret-storage backend.
///
-/// All implementations must be `Send + Sync` so they can live inside a
+/// All implementations must be `Send + Sync` so they can live inside
/// the host install slot.
-pub trait KeyringBackend: Send + Sync {
+pub trait SecretBackend: Send + Sync {
/// Retrieve a secret. Returns `Ok(None)` when no entry exists.
- fn get(&self, namespaced_key: &str) -> Result<Option<String>, KeyringError>;
+ fn get(&self, namespaced_key: &str) -> Result<Option<String>, SecretStorageError>;
/// Store (or overwrite) a secret.
- fn set(&self, namespaced_key: &str, value: &str) -> Result<(), KeyringError>;
+ fn set(&self, namespaced_key: &str, value: &str) -> Result<(), SecretStorageError>;
/// Delete a secret. Must be idempotent (no error if the entry is absent).
- fn delete(&self, namespaced_key: &str) -> Result<(), KeyringError>;
+ fn delete(&self, namespaced_key: &str) -> Result<(), SecretStorageError>;
+ /// Whether verified writes survive a process restart. Volatile providers
+ /// must return false so migration never deletes their durable source.
+ fn is_persistent(&self) -> bool {
+ true
+ }
/// Human-readable name used in log lines.
fn name(&self) -> &'static str;
}
@@ -71,14 +76,15 @@ impl FileBackend {
/// - Writing (`true`): quarantine the bytes and fail. Returning empty here
/// is what turned a corrupt file into a *wipe*, because the write that
/// followed persisted a map holding nothing but the key being set.
- fn read_map(&self, for_write: bool) -> Result<HashMap<String, String>, KeyringError> {
+ fn read_map(&self, for_write: bool) -> Result<HashMap<String, String>, SecretStorageError> {
if !self.path.exists() {
return Ok(HashMap::new());
}
- let bytes = std::fs::read(&self.path).map_err(|e| KeyringError::MigrationReadFailed {
- path: self.path.display().to_string(),
- source: e,
- })?;
+ let bytes =
+ std::fs::read(&self.path).map_err(|e| SecretStorageError::MigrationReadFailed {
+ path: self.path.display().to_string(),
+ source: e,
+ })?;
if bytes.is_empty() {
return Ok(HashMap::new());
}
@@ -86,7 +92,7 @@ impl FileBackend {
Ok(map) => Ok(map),
Err(e) if for_write => {
file_store::quarantine_corrupt(&self.path, "json");
- Err(KeyringError::Backend(format!(
+ Err(SecretStorageError::Backend(format!(
"dev-keychain.json at {} could not be parsed ({e}); it was moved aside \
rather than overwritten",
self.path.display()
@@ -102,25 +108,25 @@ impl FileBackend {
}
}
- fn write_map(&self, map: &HashMap<String, String>) -> Result<(), KeyringError> {
+ fn write_map(&self, map: &HashMap<String, String>) -> Result<(), SecretStorageError> {
// Propagate serialization failure so callers are not silently fed empty
// data on a write error.
let json = serde_json::to_vec_pretty(map).map_err(|e| {
- KeyringError::Backend(format!("failed to serialize dev keychain map: {e}"))
+ SecretStorageError::Backend(format!("failed to serialize dev keychain map: {e}"))
})?;
file_store::write_atomic(&self.path, &json)
}
}
-impl KeyringBackend for FileBackend {
- fn get(&self, namespaced_key: &str) -> Result<Option<String>, KeyringError> {
+impl SecretBackend for FileBackend {
+ fn get(&self, namespaced_key: &str) -> Result<Option<String>, SecretStorageError> {
// No lock: `write_atomic` publishes by rename, so a reader sees either
// the whole previous file or the whole next one, never a mix.
let map = self.read_map(false)?;
Ok(map.get(namespaced_key).cloned())
}
- fn set(&self, namespaced_key: &str, value: &str) -> Result<(), KeyringError> {
+ fn set(&self, namespaced_key: &str, value: &str) -> Result<(), SecretStorageError> {
// Held across the read as well as the write: taking it around the write
// alone would still let a stale map overwrite a concurrent one.
let _guard = file_store::lock_for_write(&self.path)?;
@@ -129,7 +135,7 @@ impl KeyringBackend for FileBackend {
self.write_map(&map)
}
- fn delete(&self, namespaced_key: &str) -> Result<(), KeyringError> {
+ fn delete(&self, namespaced_key: &str) -> Result<(), SecretStorageError> {
let _guard = file_store::lock_for_write(&self.path)?;
let mut map = self.read_map(true)?;
if map.remove(namespaced_key).is_some() {
@@ -168,12 +174,12 @@ impl MockBackend {
}
#[cfg(test)]
-impl KeyringBackend for MockBackend {
- fn get(&self, namespaced_key: &str) -> Result<Option<String>, KeyringError> {
+impl SecretBackend for MockBackend {
+ fn get(&self, namespaced_key: &str) -> Result<Option<String>, SecretStorageError> {
Ok(self.store.lock().unwrap().get(namespaced_key).cloned())
}
- fn set(&self, namespaced_key: &str, value: &str) -> Result<(), KeyringError> {
+ fn set(&self, namespaced_key: &str, value: &str) -> Result<(), SecretStorageError> {
self.store
.lock()
.unwrap()
@@ -181,7 +187,7 @@ impl KeyringBackend for MockBackend {
Ok(())
}
- fn delete(&self, namespaced_key: &str) -> Result<(), KeyringError> {
+ fn delete(&self, namespaced_key: &str) -> Result<(), SecretStorageError> {
self.store.lock().unwrap().remove(namespaced_key);
Ok(())
}
diff --git a/crates/openhuman-core/src/security/keyring/crypto.rs b/crates/openhuman-core/src/security/secret_storage/crypto.rs
similarity index 100%
rename from crates/openhuman-core/src/security/keyring/crypto.rs
rename to crates/openhuman-core/src/security/secret_storage/crypto.rs
diff --git a/crates/openhuman-core/src/security/keyring/crypto_tests.rs b/crates/openhuman-core/src/security/secret_storage/crypto_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/security/keyring/crypto_tests.rs
rename to crates/openhuman-core/src/security/secret_storage/crypto_tests.rs
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend.rs
similarity index 89%
rename from crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
rename to crates/openhuman-core/src/security/secret_storage/encrypted_file_backend.rs
index 536e9df2bb..e5fec5dc43 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
+++ b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend.rs
@@ -9,12 +9,12 @@
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
-use crate::security::keyring::adapter;
-use crate::security::keyring::backend::KeyringBackend;
-use crate::security::keyring::crypto::{self, KEY_LEN};
-use crate::security::keyring::error::KeyringError;
-use crate::security::keyring::file_store;
-use crate::security::keyring::store::BackendKind;
+use crate::security::secret_storage::adapter;
+use crate::security::secret_storage::backend::SecretBackend;
+use crate::security::secret_storage::crypto::{self, KEY_LEN};
+use crate::security::secret_storage::error::SecretStorageError;
+use crate::security::secret_storage::file_store;
+use crate::security::secret_storage::store::BackendKind;
use tinystoragedrivers::secrets::EncryptedFileSecrets;
use zeroize::Zeroizing;
@@ -75,24 +75,22 @@ static HOST_KEY_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()?;
+ crate::security::secret_storage::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();
+ let dir = crate::security::secret_storage::store::workspace_dir_for_file_backend();
log::info!(
"[keyring] init_master_key: resolved workspace_dir={}",
dir.display()
);
- crate::security::keyring::init_workspace(&dir);
+ crate::security::secret_storage::init_workspace(&dir);
+ let backend_kind = crate::security::secret_storage::store::effective_backend_kind();
+ if backend_kind != BackendKind::EncryptedFile {
+ // Do not cache a no-key outcome: a later host may explicitly install
+ // persistent storage after an ephemeral runtime has stopped.
+ return Ok(());
+ }
init_once(&MASTER_KEY, || {
- let backend_kind = crate::security::keyring::store::effective_backend_kind();
- if backend_kind != BackendKind::EncryptedFile {
- log::debug!(
- "[keyring:encrypted_file] skipping master key init backend={backend_kind:?}"
- );
- return Ok(None);
- }
-
match try_load_master_key() {
Ok((key, source)) => {
log::info!("[keyring:encrypted_file] master key loaded from {source}");
@@ -211,7 +209,7 @@ fn try_load_master_key() -> Result<([u8; KEY_LEN], String), MasterKeyError> {
{
return Ok(from_env);
}
- let dir = crate::security::keyring::store::workspace_dir_for_file_backend();
+ let dir = crate::security::secret_storage::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()))
@@ -285,7 +283,7 @@ pub(super) fn master_key_available() -> bool {
#[cfg(test)]
{
key_source::workspace_master_key(
- &crate::security::keyring::store::workspace_dir_for_file_backend(),
+ &crate::security::secret_storage::store::workspace_dir_for_file_backend(),
)
.is_ok()
}
@@ -346,7 +344,7 @@ impl EncryptedFileBackend {
}
/// Run one driver call, recovering once from a corrupt file.
- fn run<T, F, Fut>(&self, key: &[u8; KEY_LEN], op: F) -> Result<T, KeyringError>
+ fn run<T, F, Fut>(&self, key: &[u8; KEY_LEN], op: F) -> Result<T, SecretStorageError>
where
T: Send + 'static,
F: Fn(EncryptedFileSecrets) -> Fut,
@@ -363,7 +361,7 @@ impl EncryptedFileBackend {
}
/// Import `dev-keychain.json` into a missing `secrets.enc`, once.
- fn import_legacy_dev_keychain(&self, key: &[u8; KEY_LEN]) -> Result<(), KeyringError> {
+ fn import_legacy_dev_keychain(&self, key: &[u8; KEY_LEN]) -> Result<(), SecretStorageError> {
let legacy_path = self.workspace_dir.join(LEGACY_DEV_KEYCHAIN);
let migrated_path = legacy_path.with_extension("json.migrated");
if !legacy_path.exists() && !migrated_path.exists() {
@@ -405,13 +403,13 @@ impl EncryptedFileBackend {
&migrated_path
};
let metadata = std::fs::symlink_metadata(source_path).map_err(|source| {
- KeyringError::MigrationReadFailed {
+ SecretStorageError::MigrationReadFailed {
path: source_path.display().to_string(),
source,
}
})?;
if !metadata.file_type().is_file() {
- return Err(KeyringError::Backend(format!(
+ return Err(SecretStorageError::Backend(format!(
"legacy {} is not a regular file; preserving it for recovery",
source_path.display()
)));
@@ -420,43 +418,43 @@ impl EncryptedFileBackend {
"[keyring:encrypted_file] found legacy {} — migrating to encrypted file",
source_path.display()
);
- let bytes =
- std::fs::read(source_path).map_err(|source| KeyringError::MigrationReadFailed {
+ let bytes = std::fs::read(source_path).map_err(|source| {
+ SecretStorageError::MigrationReadFailed {
path: source_path.display().to_string(),
source,
- })?;
+ }
+ })?;
let map: std::collections::BTreeMap<String, String> = if bytes.is_empty() {
Default::default()
} else {
serde_json::from_slice(&bytes).map_err(|e| {
- KeyringError::Backend(format!(
+ SecretStorageError::Backend(format!(
"legacy {} is invalid JSON; preserving it for recovery: {e}",
source_path.display()
))
})?
};
- let json = Zeroizing::new(
- serde_json::to_vec(&map)
- .map_err(|e| KeyringError::Backend(format!("failed to serialize secrets: {e}")))?,
- );
+ let json = Zeroizing::new(serde_json::to_vec(&map).map_err(|e| {
+ SecretStorageError::Backend(format!("failed to serialize secrets: {e}"))
+ })?);
{
let blob = crypto::chacha20_encrypt(key, &json)
- .map_err(|e| KeyringError::Backend(format!("encryption failed: {e}")))?;
+ .map_err(|e| SecretStorageError::Backend(format!("encryption failed: {e}")))?;
file_store::write_atomic(&self.path, &blob)?;
}
let verified = match self.remove_legacy_if_encrypted_copy_matches(key, source_path, &_guard)
{
Ok(verified) => verified,
- Err(error @ KeyringError::MigrationDeleteFailed { .. }) => {
+ Err(error @ SecretStorageError::MigrationDeleteFailed { .. }) => {
log::warn!("[keyring:encrypted_file] could not remove migrated plaintext: {error}");
true
}
Err(error) => return Err(error),
};
if !verified {
- return Err(KeyringError::Backend(
+ return Err(SecretStorageError::Backend(
"encrypted migration result did not verify against its plaintext source".into(),
));
}
@@ -479,7 +477,7 @@ impl EncryptedFileBackend {
key: &[u8; KEY_LEN],
legacy_path: &Path,
destination_lock: &file_store::WriteLock,
- ) -> Result<bool, KeyringError> {
+ ) -> Result<bool, SecretStorageError> {
self.remove_legacy_if_encrypted_copy_matches_with_sync(
key,
legacy_path,
@@ -493,13 +491,13 @@ impl EncryptedFileBackend {
key: &[u8; KEY_LEN],
legacy_path: &Path,
destination_lock: &file_store::WriteLock,
- sync_parent: impl FnOnce(&Path, &file_store::WriteLock) -> Result<(), KeyringError>,
- ) -> Result<bool, KeyringError> {
+ sync_parent: impl FnOnce(&Path, &file_store::WriteLock) -> Result<(), SecretStorageError>,
+ ) -> Result<bool, SecretStorageError> {
let metadata = match std::fs::symlink_metadata(legacy_path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(source) => {
- return Err(KeyringError::MigrationReadFailed {
+ return Err(SecretStorageError::MigrationReadFailed {
path: legacy_path.display().to_string(),
source,
});
@@ -508,11 +506,12 @@ impl EncryptedFileBackend {
if !metadata.file_type().is_file() {
return Ok(false);
}
- let bytes =
- std::fs::read(legacy_path).map_err(|source| KeyringError::MigrationReadFailed {
+ let bytes = std::fs::read(legacy_path).map_err(|source| {
+ SecretStorageError::MigrationReadFailed {
path: legacy_path.display().to_string(),
source,
- })?;
+ }
+ })?;
let legacy: std::collections::BTreeMap<String, String> = if bytes.is_empty() {
Default::default()
} else {
@@ -525,7 +524,7 @@ impl EncryptedFileBackend {
Ok(blob) => blob,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(source) => {
- return Err(KeyringError::MigrationReadFailed {
+ return Err(SecretStorageError::MigrationReadFailed {
path: self.path.display().to_string(),
source,
});
@@ -564,19 +563,19 @@ impl EncryptedFileBackend {
Ok(true)
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
- Err(source) => Err(KeyringError::MigrationDeleteFailed {
+ Err(source) => Err(SecretStorageError::MigrationDeleteFailed {
path: legacy_path.display().to_string(),
source,
}),
}
}
- /// [`KeyringBackend::get`] under an explicit master key.
+ /// [`SecretBackend::get`] under an explicit master key.
pub(super) fn get_with_key(
&self,
key: &[u8; KEY_LEN],
namespaced_key: &str,
- ) -> Result<Option<String>, KeyringError> {
+ ) -> Result<Option<String>, SecretStorageError> {
use tinystoragedrivers::secrets::SecretStore as _;
let name = namespaced_key.to_string();
let value = self.run(key, move |store| {
@@ -586,13 +585,13 @@ impl EncryptedFileBackend {
adapter::utf8(namespaced_key, value)
}
- /// [`KeyringBackend::set`] under an explicit master key.
+ /// [`SecretBackend::set`] under an explicit master key.
pub(super) fn set_with_key(
&self,
key: &[u8; KEY_LEN],
namespaced_key: &str,
value: &str,
- ) -> Result<(), KeyringError> {
+ ) -> Result<(), SecretStorageError> {
use tinystoragedrivers::secrets::SecretStore as _;
let name = namespaced_key.to_string();
let value = Zeroizing::new(value.as_bytes().to_vec());
@@ -603,24 +602,24 @@ impl EncryptedFileBackend {
}
}
-impl KeyringBackend for EncryptedFileBackend {
- fn get(&self, namespaced_key: &str) -> Result<Option<String>, KeyringError> {
+impl SecretBackend for EncryptedFileBackend {
+ fn get(&self, namespaced_key: &str) -> Result<Option<String>, SecretStorageError> {
let Some(key) = self.key() else {
return Ok(None);
};
self.get_with_key(&key, namespaced_key)
}
- fn set(&self, namespaced_key: &str, value: &str) -> Result<(), KeyringError> {
+ fn set(&self, namespaced_key: &str, value: &str) -> Result<(), SecretStorageError> {
let Some(key) = self.key() else {
- return Err(KeyringError::Backend(
+ return Err(SecretStorageError::Backend(
"master key unavailable — cannot store secrets".to_string(),
));
};
self.set_with_key(&key, namespaced_key, value)
}
- fn delete(&self, namespaced_key: &str) -> Result<(), KeyringError> {
+ fn delete(&self, namespaced_key: &str) -> Result<(), SecretStorageError> {
use tinystoragedrivers::secrets::SecretStore as _;
let Some(key) = self.key() else {
return Ok(());
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend/key_source.rs
similarity index 83%
rename from crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source.rs
rename to crates/openhuman-core/src/security/secret_storage/encrypted_file_backend/key_source.rs
index ea7f89193c..b2d2863c56 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source.rs
+++ b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend/key_source.rs
@@ -49,8 +49,8 @@ pub(super) fn master_key_from_env(
/// 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>;
+ fn load(&self) -> Result<Option<Zeroizing<[u8; 32]>>, SecretStorageError>;
+ fn store(&self, key: &[u8; 32]) -> Result<(), SecretStorageError>;
}
#[path = "key_source_install.rs"]
@@ -62,7 +62,7 @@ pub use install::{
/// 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> {
+) -> Result<Zeroizing<[u8; 32]>, SecretStorageError> {
if let Some(key) = source.load()? {
return Ok(key);
}
@@ -72,9 +72,9 @@ pub(super) fn load_or_mint_master_key(
source.store(&key)?;
let readback = source
.load()?
- .ok_or_else(|| KeyringError::Backend("master key readback missing".into()))?;
+ .ok_or_else(|| SecretStorageError::Backend("master key readback missing".into()))?;
if *readback != *key {
- return Err(KeyringError::Backend(
+ return Err(SecretStorageError::Backend(
"master key write verification failed".into(),
));
}
@@ -84,13 +84,15 @@ pub(super) fn load_or_mint_master_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> {
+pub(super) fn workspace_master_key(
+ workspace: &Path,
+) -> Result<Zeroizing<[u8; 32]>, SecretStorageError> {
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(
+ return Err(SecretStorageError::Backend(
"workspace master key must be a regular file".into(),
));
}
@@ -98,18 +100,17 @@ pub(super) fn workspace_master_key(workspace: &Path) -> Result<Zeroizing<[u8; 32
{
use std::os::unix::fs::PermissionsExt;
if metadata.permissions().mode() & 0o077 != 0 {
- return Err(KeyringError::Backend(
+ return Err(SecretStorageError::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())
- })?);
+ let text = Zeroizing::new(std::fs::read_to_string(&path).map_err(|_| {
+ SecretStorageError::Backend("cannot read workspace master key".into())
+ })?);
parse_master_key_hex(text.trim())
.map(Zeroizing::new)
- .map_err(KeyringError::Backend)
+ .map_err(SecretStorageError::Backend)
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
let bytes = Zeroizing::new(crypto::generate_random_bytes(KEY_LEN));
@@ -119,7 +120,7 @@ pub(super) fn workspace_master_key(workspace: &Path) -> Result<Zeroizing<[u8; 32
file_store::write_atomic(&path, hex.as_bytes())?;
Ok(key)
}
- Err(_) => Err(KeyringError::Backend(
+ Err(_) => Err(SecretStorageError::Backend(
"cannot inspect workspace master key".into(),
)),
}
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source_install.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend/key_source_install.rs
similarity index 100%
rename from crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source_install.rs
rename to crates/openhuman-core/src/security/secret_storage/encrypted_file_backend/key_source_install.rs
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source_tests.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend/key_source_tests.rs
similarity index 92%
rename from crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source_tests.rs
rename to crates/openhuman-core/src/security/secret_storage/encrypted_file_backend/key_source_tests.rs
index 97bc3a5d55..70b244f18f 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend/key_source_tests.rs
+++ b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend/key_source_tests.rs
@@ -9,14 +9,14 @@ struct FakeSource {
wrong_readback: bool,
}
impl MasterKeySource for FakeSource {
- fn load(&self) -> Result<Option<Zeroizing<[u8; 32]>>, KeyringError> {
+ fn load(&self) -> Result<Option<Zeroizing<[u8; 32]>>, SecretStorageError> {
if self.denied {
- return Err(KeyringError::Backend("access denied".into()));
+ return Err(SecretStorageError::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> {
+ fn store(&self, key: &[u8; 32]) -> Result<(), SecretStorageError> {
*self.writes.lock().unwrap() += 1;
*self.key.lock().unwrap() = Some(*key);
Ok(())
@@ -131,7 +131,8 @@ fn installed_source_wins_over_workspace_file_and_does_not_leak_threads() {
.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());
+ let _workspace =
+ crate::security::secret_storage::store::test_scope::ScopedWorkspace::new(dir.path());
install_master_key_source(Arc::new(FakeSource {
key: Mutex::new(Some([7; 32])),
..Default::default()
@@ -174,7 +175,8 @@ fn denied_host_source_does_not_fall_back_to_workspace_key() {
.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());
+ let _workspace =
+ crate::security::secret_storage::store::test_scope::ScopedWorkspace::new(dir.path());
install_master_key_source(Arc::new(FakeSource {
denied: true,
..Default::default()
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend_fixture_tests.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_fixture_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/security/keyring/encrypted_file_backend_fixture_tests.rs
rename to crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_fixture_tests.rs
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend_tests.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_tests.rs
similarity index 99%
rename from crates/openhuman-core/src/security/keyring/encrypted_file_backend_tests.rs
rename to crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_tests.rs
index 24d0bcd53e..ca80197250 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend_tests.rs
+++ b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend_tests.rs
@@ -95,7 +95,7 @@ fn existing_encrypted_file_does_not_remove_plaintext_until_directory_sync_succee
&key,
&legacy_path,
&destination_lock,
- |_, _| Err(KeyringError::Backend("directory sync failed".into())),
+ |_, _| Err(SecretStorageError::Backend("directory sync failed".into())),
);
assert!(result.is_err());
assert!(
@@ -429,7 +429,7 @@ fn a_secret_written_under_a_configured_key_reads_back_after_a_restart() {
.with(MASTER_KEY_FILE_ENV, &key_path);
// First "process": load the configured key and store a secret through the
- // same lock → read → encrypt → write path `KeyringBackend::set` uses.
+ // same lock → read → encrypt → write path `SecretBackend::set` uses.
// `get`/`set` read the key from the process-wide `MASTER_KEY`, which
// this test must not populate, so the key is passed explicitly.
{
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_store.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_store.rs
similarity index 95%
rename from crates/openhuman-core/src/security/keyring/encrypted_store.rs
rename to crates/openhuman-core/src/security/secret_storage/encrypted_store.rs
index 04124eda47..7f3531c4a3 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_store.rs
+++ b/crates/openhuman-core/src/security/secret_storage/encrypted_store.rs
@@ -194,19 +194,33 @@ impl SecretStore {
fn load_or_create_key_from_keyring(&self) -> Result<Zeroizing<Vec<u8>>> {
let user_id = self.keyring_user_id();
- match crate::security::keyring::migrate_from_file(
+ if !crate::security::secret_storage::store::backend().is_persistent() {
+ // A volatile provider must not absorb and delete a legacy disk key.
+ // Read existing keys without migration; new keys stay in memory.
+ if self.key_path.exists() {
+ return decode_key_hex(fs::read_to_string(&self.key_path)?.trim());
+ }
+ let key = crate::security::secret_storage::get_or_create_random(
+ &user_id,
+ KEYCHAIN_MASTER_KEY,
+ KEY_LEN,
+ )
+ .map_err(anyhow::Error::new)?;
+ return decode_key_hex(key.trim());
+ }
+ match crate::security::secret_storage::migrate_from_file(
&user_id,
KEYCHAIN_MASTER_KEY,
&self.key_path,
) {
- Ok(crate::security::keyring::MigrationOutcome::MigratedAndDeleted) => {
+ Ok(crate::security::secret_storage::MigrationOutcome::MigratedAndDeleted) => {
log::info!(
"[security] migrated legacy secret-store key into keychain from {}",
self.key_path.display()
);
}
- Ok(crate::security::keyring::MigrationOutcome::AlreadyMigrated)
- | Ok(crate::security::keyring::MigrationOutcome::NoSourceFile) => {}
+ Ok(crate::security::secret_storage::MigrationOutcome::AlreadyMigrated)
+ | Ok(crate::security::secret_storage::MigrationOutcome::NoSourceFile) => {}
Err(error) => {
log::warn!(
"[security] failed to migrate legacy secret-store key from {}: {error} | detail={}",
@@ -216,14 +230,17 @@ impl SecretStore {
}
}
- let hex_key =
- crate::security::keyring::get_or_create_random(&user_id, KEYCHAIN_MASTER_KEY, KEY_LEN)
- .map_err(|e| {
- anyhow::anyhow!(
- "Failed to load secret-store master key from keychain: {e} | detail={}",
- e.diagnostic()
- )
- })?;
+ let hex_key = crate::security::secret_storage::get_or_create_random(
+ &user_id,
+ KEYCHAIN_MASTER_KEY,
+ KEY_LEN,
+ )
+ .map_err(|e| {
+ anyhow::anyhow!(
+ "Failed to load secret-store master key from keychain: {e} | detail={}",
+ e.diagnostic()
+ )
+ })?;
decode_key_hex(hex_key.trim())
}
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_store_crypto_migration_tests.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_store_crypto_migration_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/security/keyring/encrypted_store_crypto_migration_tests.rs
rename to crates/openhuman-core/src/security/secret_storage/encrypted_store_crypto_migration_tests.rs
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_store_key_management_tests.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_store_key_management_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/security/keyring/encrypted_store_key_management_tests.rs
rename to crates/openhuman-core/src/security/secret_storage/encrypted_store_key_management_tests.rs
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_store_tests.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_store_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/security/keyring/encrypted_store_tests.rs
rename to crates/openhuman-core/src/security/secret_storage/encrypted_store_tests.rs
diff --git a/crates/openhuman-core/src/security/keyring/error.rs b/crates/openhuman-core/src/security/secret_storage/error.rs
similarity index 72%
rename from crates/openhuman-core/src/security/keyring/error.rs
rename to crates/openhuman-core/src/security/secret_storage/error.rs
index f826f79c96..8de47a62fa 100644
--- a/crates/openhuman-core/src/security/keyring/error.rs
+++ b/crates/openhuman-core/src/security/secret_storage/error.rs
@@ -2,9 +2,9 @@ use thiserror::Error;
/// Errors that can occur during secret-storage operations.
#[derive(Debug, Error)]
-pub enum KeyringError {
- /// The keychain returned a value but it was not valid UTF-8.
- #[error("Keychain value for key '{key}' is not valid UTF-8: {source}")]
+pub enum SecretStorageError {
+ /// The secret backend returned a value but it was not valid UTF-8.
+ #[error("Stored secret for key '{key}' is not valid UTF-8: {source}")]
InvalidUtf8 {
key: String,
#[source]
@@ -19,9 +19,9 @@ pub enum KeyringError {
source: std::io::Error,
},
- /// Writing to keychain succeeded but read-back verification failed.
+ /// Writing to the secret backend succeeded but read-back verification failed.
#[error(
- "Keychain write verification failed for key '{key}': wrote value did not match read-back"
+ "Secret write verification failed for key '{key}': wrote value did not match read-back"
)]
VerifyFailed { key: String },
@@ -38,15 +38,15 @@ pub enum KeyringError {
RandomGeneration(String),
/// Encryption or decryption of the secrets file failed.
- #[error("Keyring crypto error: {0}")]
+ #[error("Secret-storage crypto error: {0}")]
Crypto(String),
/// A backend-internal operation failed (e.g. serialization).
- #[error("Keyring backend error: {0}")]
+ #[error("Secret-storage backend error: {0}")]
Backend(String),
}
-impl KeyringError {
+impl SecretStorageError {
/// Log-safe diagnostic detail. Backend implementations must never include
/// secret values in errors.
pub fn diagnostic(&self) -> String {
diff --git a/crates/openhuman-core/src/security/keyring/file_store.rs b/crates/openhuman-core/src/security/secret_storage/file_store.rs
similarity index 90%
rename from crates/openhuman-core/src/security/keyring/file_store.rs
rename to crates/openhuman-core/src/security/secret_storage/file_store.rs
index eab7cc89e0..0f111040bc 100644
--- a/crates/openhuman-core/src/security/keyring/file_store.rs
+++ b/crates/openhuman-core/src/security/secret_storage/file_store.rs
@@ -32,7 +32,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
use fs2::FileExt;
-use crate::security::keyring::error::KeyringError;
+use crate::security::secret_storage::error::SecretStorageError;
/// Distinguishes concurrent temp files written by one process.
///
@@ -63,14 +63,14 @@ pub struct WriteLock {
///
/// # Errors
///
-/// Returns [`KeyringError::Backend`] when the lock file's directory cannot be
+/// Returns [`SecretStorageError::Backend`] when the lock file's directory cannot be
/// created, the lock file cannot be opened, or the lock cannot be taken. Failing
/// the operation is deliberate: proceeding unlocked is what loses secrets.
-pub fn lock_for_write(path: &Path) -> Result<WriteLock, KeyringError> {
+pub fn lock_for_write(path: &Path) -> Result<WriteLock, SecretStorageError> {
let lock_path = lock_path_for(path);
if let Some(parent) = lock_path.parent() {
std::fs::create_dir_all(parent).map_err(|e| {
- KeyringError::Backend(format!(
+ SecretStorageError::Backend(format!(
"could not create {} for the keyring lock: {e}",
parent.display()
))
@@ -83,13 +83,13 @@ pub fn lock_for_write(path: &Path) -> Result<WriteLock, KeyringError> {
.truncate(false)
.open(&lock_path)
.map_err(|e| {
- KeyringError::Backend(format!(
+ SecretStorageError::Backend(format!(
"could not open the keyring lock at {}: {e}",
lock_path.display()
))
})?;
file.lock_exclusive().map_err(|e| {
- KeyringError::Backend(format!(
+ SecretStorageError::Backend(format!(
"could not lock the keyring at {}: {e}",
lock_path.display()
))
@@ -121,12 +121,12 @@ fn parent_dir(path: &Path) -> &Path {
///
/// # Errors
///
-/// Returns [`KeyringError::Backend`] when the parent directory cannot be
+/// Returns [`SecretStorageError::Backend`] when the parent directory cannot be
/// created, or the temp file cannot be written or renamed.
-pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), KeyringError> {
+pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), SecretStorageError> {
let parent = parent_dir(path);
std::fs::create_dir_all(parent).map_err(|e| {
- KeyringError::Backend(format!(
+ SecretStorageError::Backend(format!(
"could not create {} for a keyring write: {e}",
parent.display()
))
@@ -151,7 +151,7 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), KeyringError> {
};
write().map_err(|e| {
let _ = std::fs::remove_file(&tmp_path);
- KeyringError::Backend(format!(
+ SecretStorageError::Backend(format!(
"could not stage a keyring write at {}: {e}",
tmp_path.display()
))
@@ -159,7 +159,7 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), KeyringError> {
replace_durably(&tmp_path, path).map_err(|e| {
let _ = std::fs::remove_file(&tmp_path);
- KeyringError::Backend(format!(
+ SecretStorageError::Backend(format!(
"could not replace the keyring file at {}: {e}",
path.display()
))
@@ -181,7 +181,10 @@ fn replace_durably(source: &Path, destination: &Path) -> std::io::Result<()> {
///
/// This retries an earlier publication that returned an error after the
/// destination had already appeared.
-pub fn sync_parent_dir(path: &Path, destination_lock: &WriteLock) -> Result<(), KeyringError> {
+pub fn sync_parent_dir(
+ path: &Path,
+ destination_lock: &WriteLock,
+) -> Result<(), SecretStorageError> {
#[cfg(unix)]
{
let _ = destination_lock;
@@ -189,7 +192,7 @@ pub fn sync_parent_dir(path: &Path, destination_lock: &WriteLock) -> Result<(),
File::open(parent)
.and_then(|directory| directory.sync_all())
.map_err(|error| {
- KeyringError::Backend(format!(
+ SecretStorageError::Backend(format!(
"could not sync keyring directory {}: {error}",
parent.display()
))
@@ -208,19 +211,20 @@ pub fn sync_parent_dir(path: &Path, destination_lock: &WriteLock) -> Result<(),
fn sync_parent_dir_with_republish(
path: &Path,
_destination_lock: &WriteLock,
- republish: impl FnOnce(&Path, &[u8]) -> Result<(), KeyringError>,
-) -> Result<(), KeyringError> {
- let expected = std::fs::read(path).map_err(|source| KeyringError::MigrationReadFailed {
- path: path.display().to_string(),
- source,
- })?;
+ republish: impl FnOnce(&Path, &[u8]) -> Result<(), SecretStorageError>,
+) -> Result<(), SecretStorageError> {
+ let expected =
+ std::fs::read(path).map_err(|source| SecretStorageError::MigrationReadFailed {
+ path: path.display().to_string(),
+ source,
+ })?;
republish(path, &expected)?;
- let actual = std::fs::read(path).map_err(|source| KeyringError::MigrationReadFailed {
+ let actual = std::fs::read(path).map_err(|source| SecretStorageError::MigrationReadFailed {
path: path.display().to_string(),
source,
})?;
if actual != expected {
- return Err(KeyringError::Backend(format!(
+ return Err(SecretStorageError::Backend(format!(
"durable keyring publication at {} failed verification",
path.display()
)));
@@ -273,7 +277,7 @@ compile_error!("keyring durable replacement requires a platform implementation")
/// Reserve a fresh temp file, advancing past leftovers from crashed writers.
fn reserve_temp_file(
mut next_path: impl FnMut() -> PathBuf,
-) -> Result<(PathBuf, File), KeyringError> {
+) -> Result<(PathBuf, File), SecretStorageError> {
loop {
let tmp_path = next_path();
match OpenOptions::new()
@@ -284,7 +288,7 @@ fn reserve_temp_file(
Ok(file) => break Ok((tmp_path, file)),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => {
- return Err(KeyringError::Backend(format!(
+ return Err(SecretStorageError::Backend(format!(
"could not stage a keyring write at {}: {e}",
tmp_path.display()
)));
diff --git a/crates/openhuman-core/src/security/keyring/file_store_tests.rs b/crates/openhuman-core/src/security/secret_storage/file_store_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/security/keyring/file_store_tests.rs
rename to crates/openhuman-core/src/security/secret_storage/file_store_tests.rs
diff --git a/crates/openhuman-core/src/security/keyring/fixtures/enc2_values.txt b/crates/openhuman-core/src/security/secret_storage/fixtures/enc2_values.txt
similarity index 100%
rename from crates/openhuman-core/src/security/keyring/fixtures/enc2_values.txt
rename to crates/openhuman-core/src/security/secret_storage/fixtures/enc2_values.txt
diff --git a/crates/openhuman-core/src/security/keyring/fixtures/secrets_enc.bin b/crates/openhuman-core/src/security/secret_storage/fixtures/secrets_enc.bin
similarity index 100%
rename from crates/openhuman-core/src/security/keyring/fixtures/secrets_enc.bin
rename to crates/openhuman-core/src/security/secret_storage/fixtures/secrets_enc.bin
diff --git a/crates/openhuman-core/src/security/keyring/install.rs b/crates/openhuman-core/src/security/secret_storage/install.rs
similarity index 62%
rename from crates/openhuman-core/src/security/keyring/install.rs
rename to crates/openhuman-core/src/security/secret_storage/install.rs
index 32e9aa8c29..99150382e8 100644
--- a/crates/openhuman-core/src/security/keyring/install.rs
+++ b/crates/openhuman-core/src/security/secret_storage/install.rs
@@ -1,37 +1,37 @@
//! Host install slot, process-wide in production and thread-local in unit tests.
-use super::backend::KeyringBackend;
+use super::backend::SecretBackend;
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>>>> =
+fn slot() -> &'static RwLock<Option<Arc<dyn SecretBackend>>> {
+ static SLOT: std::sync::OnceLock<RwLock<Option<Arc<dyn SecretBackend>>>> =
std::sync::OnceLock::new();
SLOT.get_or_init(|| RwLock::new(None))
}
#[cfg(test)]
-fn slot() -> &'static RwLock<Option<Arc<dyn KeyringBackend>>> {
+fn slot() -> &'static RwLock<Option<Arc<dyn SecretBackend>>> {
thread_local! {
- static SLOT: &'static RwLock<Option<Arc<dyn KeyringBackend>>> =
+ static SLOT: &'static RwLock<Option<Arc<dyn SecretBackend>>> =
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>) {
+pub fn install_secret_backend(provider: Arc<dyn SecretBackend>) {
*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>> {
+pub fn installed_secret_backend() -> Option<Arc<dyn SecretBackend>> {
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() {
+pub fn clear_secret_backend() {
*slot().write().unwrap_or_else(|e| e.into_inner()) = None;
super::reset_availability_cache();
}
diff --git a/crates/openhuman-core/src/security/secret_storage/memory_backend.rs b/crates/openhuman-core/src/security/secret_storage/memory_backend.rs
new file mode 100644
index 0000000000..173847e93e
--- /dev/null
+++ b/crates/openhuman-core/src/security/secret_storage/memory_backend.rs
@@ -0,0 +1,49 @@
+//! The basic process-local secret backend used by library hosts.
+
+use super::{SecretBackend, SecretStorageError};
+use parking_lot::RwLock;
+use std::collections::HashMap;
+
+/// Unencrypted secrets held in memory only, discarded when this backend drops.
+///
+/// No filesystem or OS keychain access occurs. Share one instance with `Arc`
+/// to share secrets across threads; separate instances have separate stores.
+#[derive(Default)]
+pub struct MemoryBackend {
+ values: RwLock<HashMap<String, String>>,
+}
+
+impl MemoryBackend {
+ /// Create an empty secret store.
+ pub fn new() -> Self {
+ Self::default()
+ }
+}
+
+impl SecretBackend for MemoryBackend {
+ fn get(&self, key: &str) -> Result<Option<String>, SecretStorageError> {
+ Ok(self.values.read().get(key).cloned())
+ }
+
+ fn set(&self, key: &str, value: &str) -> Result<(), SecretStorageError> {
+ self.values.write().insert(key.to_owned(), value.to_owned());
+ Ok(())
+ }
+
+ fn delete(&self, key: &str) -> Result<(), SecretStorageError> {
+ self.values.write().remove(key);
+ Ok(())
+ }
+
+ fn is_persistent(&self) -> bool {
+ false
+ }
+
+ fn name(&self) -> &'static str {
+ "memory"
+ }
+}
+
+#[cfg(test)]
+#[path = "memory_backend_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/security/secret_storage/memory_backend_tests.rs b/crates/openhuman-core/src/security/secret_storage/memory_backend_tests.rs
new file mode 100644
index 0000000000..5f469b958b
--- /dev/null
+++ b/crates/openhuman-core/src/security/secret_storage/memory_backend_tests.rs
@@ -0,0 +1,63 @@
+use super::*;
+
+#[test]
+fn memory_secrets_support_overwrite_and_idempotent_deletion() {
+ let backend = MemoryBackend::new();
+ assert_eq!(backend.get("user:token").unwrap(), None);
+ backend.set("user:token", "first").unwrap();
+ backend.set("user:token", "replacement").unwrap();
+ assert_eq!(
+ backend.get("user:token").unwrap().as_deref(),
+ Some("replacement")
+ );
+ backend.delete("user:token").unwrap();
+ backend.delete("user:token").unwrap();
+ assert_eq!(backend.get("user:token").unwrap(), None);
+}
+
+#[test]
+fn memory_instances_and_user_namespaces_are_independent() {
+ let backend = MemoryBackend::new();
+ backend.set("alice:token", "alice-secret").unwrap();
+ backend.set("bob:token", "bob-secret").unwrap();
+ backend.delete("alice:token").unwrap();
+ assert_eq!(
+ backend.get("bob:token").unwrap().as_deref(),
+ Some("bob-secret")
+ );
+ assert_eq!(MemoryBackend::new().get("bob:token").unwrap(), None);
+}
+
+#[test]
+fn memory_secrets_are_shared_across_threads_without_lost_writes() {
+ let backend = std::sync::Arc::new(MemoryBackend::new());
+ let workers: Vec<_> = (0..8)
+ .map(|worker| {
+ let backend = backend.clone();
+ std::thread::spawn(move || backend.set(&format!("user:{worker}"), "value").unwrap())
+ })
+ .collect();
+ for worker in workers {
+ worker.join().unwrap();
+ }
+ for worker in 0..8 {
+ assert_eq!(
+ backend.get(&format!("user:{worker}")).unwrap().as_deref(),
+ Some("value")
+ );
+ }
+}
+
+#[test]
+fn migration_to_memory_never_deletes_a_durable_source() {
+ let _env = crate::config::test_env::EnvVarGuard::locked().without("OPENHUMAN_KEYRING_BACKEND");
+ let dir = tempfile::tempdir().unwrap();
+ let _workspace =
+ crate::security::secret_storage::store::test_scope::ScopedWorkspace::new(dir.path());
+ let source = dir.path().join("legacy-secret");
+ std::fs::write(&source, "durable-value").unwrap();
+ let error =
+ crate::security::secret_storage::migrate_from_file("user", "token", &source).unwrap_err();
+ assert!(error.to_string().contains("persistent"));
+ assert_eq!(std::fs::read_to_string(&source).unwrap(), "durable-value");
+}
diff --git a/crates/openhuman-core/src/security/keyring/mod.rs b/crates/openhuman-core/src/security/secret_storage/mod.rs
similarity index 63%
rename from crates/openhuman-core/src/security/keyring/mod.rs
rename to crates/openhuman-core/src/security/secret_storage/mod.rs
index 0ce42be221..b198301d31 100644
--- a/crates/openhuman-core/src/security/keyring/mod.rs
+++ b/crates/openhuman-core/src/security/secret_storage/mod.rs
@@ -1,6 +1,8 @@
-//! 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.
+//! Platform-independent, user-scoped secret storage.
+//! Native keychains are host providers implemented in `openhuman-rpc::keyring`.
+//! Hosts may install a backend before boot.
+//! Otherwise an explicit environment override wins, followed by in-memory
+//! storage. Persistent hosts select an encrypted-file or native provider.
mod adapter;
pub mod backend;
@@ -10,20 +12,23 @@ pub mod encrypted_store;
pub mod error;
pub mod file_store;
mod install;
+mod memory_backend;
pub mod ops;
pub mod store;
// ── Public re-exports ─────────────────────────────────────────────────────────
-pub use backend::KeyringBackend;
+pub use backend::SecretBackend;
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_file_backend::EncryptedFileBackend;
pub use encrypted_store::SecretStore;
-pub use error::KeyringError;
-pub use install::{clear_keyring_backend, install_keyring_backend, installed_keyring_backend};
+pub use error::SecretStorageError;
+pub use install::{clear_secret_backend, install_secret_backend, installed_secret_backend};
+pub use memory_backend::MemoryBackend;
pub use ops::{
backend_name, delete, get, get_or_create_random, is_available, migrate_from_file,
reset_availability_cache, set, MigrationOutcome,
@@ -35,5 +40,5 @@ pub use store::init_workspace;
pub(crate) use ops::force_backend_for_test;
#[cfg(test)]
-#[path = "keyring_tests.rs"]
+#[path = "mod_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/security/keyring/keyring_tests.rs b/crates/openhuman-core/src/security/secret_storage/mod_tests.rs
similarity index 96%
rename from crates/openhuman-core/src/security/keyring/keyring_tests.rs
rename to crates/openhuman-core/src/security/secret_storage/mod_tests.rs
index 4759d7864a..1d6af398de 100644
--- a/crates/openhuman-core/src/security/keyring/keyring_tests.rs
+++ b/crates/openhuman-core/src/security/secret_storage/mod_tests.rs
@@ -7,7 +7,7 @@ use std::io::Write as _;
use tempfile::NamedTempFile;
use tempfile::TempDir;
-use super::backend::{FileBackend, KeyringBackend};
+use super::backend::{FileBackend, SecretBackend};
use super::*;
// ── FileBackend: round-trip ───────────────────────────────────────────────────
@@ -192,7 +192,7 @@ fn run_migrate(
user_id: &str,
key: &str,
src_path: Option<&std::path::Path>,
-) -> Result<MigrationOutcome, KeyringError> {
+) -> Result<MigrationOutcome, SecretStorageError> {
let nk = format!("{user_id}:{key}");
// -- Step 1: already migrated? --
@@ -207,10 +207,11 @@ fn run_migrate(
};
// -- Step 3: read --
- let content = std::fs::read_to_string(path).map_err(|e| KeyringError::MigrationReadFailed {
- path: path.display().to_string(),
- source: e,
- })?;
+ let content =
+ std::fs::read_to_string(path).map_err(|e| SecretStorageError::MigrationReadFailed {
+ path: path.display().to_string(),
+ source: e,
+ })?;
let value = content.trim().to_string();
// -- Step 4: write --
@@ -219,13 +220,13 @@ fn run_migrate(
// -- Step 5: verify --
let readback = fb.get(&nk)?;
if readback.as_deref() != Some(value.as_str()) {
- return Err(KeyringError::VerifyFailed {
+ return Err(SecretStorageError::VerifyFailed {
key: key.to_string(),
});
}
// -- Step 6: delete source file --
- std::fs::remove_file(path).map_err(|e| KeyringError::MigrationDeleteFailed {
+ std::fs::remove_file(path).map_err(|e| SecretStorageError::MigrationDeleteFailed {
path: path.display().to_string(),
source: e,
})?;
diff --git a/crates/openhuman-core/src/security/keyring/ops.rs b/crates/openhuman-core/src/security/secret_storage/ops.rs
similarity index 89%
rename from crates/openhuman-core/src/security/keyring/ops.rs
rename to crates/openhuman-core/src/security/secret_storage/ops.rs
index 57790aae10..73bce25a77 100644
--- a/crates/openhuman-core/src/security/keyring/ops.rs
+++ b/crates/openhuman-core/src/security/secret_storage/ops.rs
@@ -1,14 +1,14 @@
//! Core keyring operations: get, set, delete, probe, random generation, and migration.
//!
-//! All public functions delegate to the active backend selected by [`crate::security::keyring::store`].
+//! All public functions delegate to the active backend selected by [`crate::security::secret_storage::store`].
use std::path::Path;
use chacha20poly1305::aead::{rand_core::RngCore, OsRng};
use parking_lot::Mutex;
-use crate::security::keyring::error::KeyringError;
-use crate::security::keyring::store::backend;
+use crate::security::secret_storage::error::SecretStorageError;
+use crate::security::secret_storage::store::backend;
// Cached result of the keychain probe. A single Mutex<Option<bool>> is used
// instead of a separate AtomicBool + RwLock pair to eliminate the race where
@@ -47,13 +47,14 @@ pub enum MigrationOutcome {
// belong to this process, not to an agent.
/// The storage-backed secret store for this call, when one is configured.
-fn storage_secrets() -> Result<Option<tinystoragedrivers::secrets::DocumentSecrets>, KeyringError> {
+fn storage_secrets(
+) -> Result<Option<tinystoragedrivers::secrets::DocumentSecrets>, SecretStorageError> {
crate::storage::secrets::current()
- .map_err(|error| KeyringError::Backend(format!("storage secrets: {error}")))
+ .map_err(|error| SecretStorageError::Backend(format!("storage secrets: {error}")))
}
-fn storage_error(error: crate::storage::StorageError) -> KeyringError {
- KeyringError::Backend(format!("storage secrets: {error}"))
+fn storage_error(error: crate::storage::StorageError) -> SecretStorageError {
+ SecretStorageError::Backend(format!("storage secrets: {error}"))
}
/// Retrieve a secret: from the storage backend when one is configured,
@@ -61,7 +62,7 @@ fn storage_error(error: crate::storage::StorageError) -> KeyringError {
///
/// Returns `Ok(None)` when no entry exists for this user + key combination.
/// Never logs the secret value.
-pub fn get(user_id: &str, key: &str) -> Result<Option<String>, KeyringError> {
+pub fn get(user_id: &str, key: &str) -> Result<Option<String>, SecretStorageError> {
let Some(secrets) = storage_secrets()? else {
return process_get(user_id, key);
};
@@ -75,7 +76,7 @@ pub fn get(user_id: &str, key: &str) -> Result<Option<String>, KeyringError> {
/// authoritative once configured, so a failing legacy backend must not fail
/// the read; it is logged so a broken OS keychain does not look like
/// "nothing stored".
-fn legacy_or_warn(result: Result<Option<String>, KeyringError>) -> Option<String> {
+fn legacy_or_warn(result: Result<Option<String>, SecretStorageError>) -> Option<String> {
match result {
Ok(value) => value,
Err(error) => {
@@ -93,7 +94,7 @@ fn get_adopting(
name: &str,
key: &str,
legacy: impl FnOnce() -> Option<String>,
-) -> Result<Option<String>, KeyringError> {
+) -> Result<Option<String>, SecretStorageError> {
use tinystoragedrivers::secrets::SecretStore as _;
let write_back = secrets.clone();
let owned = name.to_string();
@@ -113,7 +114,7 @@ fn get_adopting(
};
String::from_utf8(value.to_vec())
.map(Some)
- .map_err(|source| KeyringError::InvalidUtf8 {
+ .map_err(|source| SecretStorageError::InvalidUtf8 {
key: key.to_string(),
source,
})
@@ -121,7 +122,7 @@ fn get_adopting(
/// Store a secret: in the storage backend when one is configured, else in
/// the process backend. Overwrites any existing entry. Never logs the value.
-pub fn set(user_id: &str, key: &str, value: &str) -> Result<(), KeyringError> {
+pub fn set(user_id: &str, key: &str, value: &str) -> Result<(), SecretStorageError> {
use tinystoragedrivers::secrets::SecretStore as _;
let Some(secrets) = storage_secrets()? else {
return process_set(user_id, key, value);
@@ -134,7 +135,7 @@ pub fn set(user_id: &str, key: &str, value: &str) -> Result<(), KeyringError> {
/// Delete a secret: from the storage backend when one is configured, else
/// from the process backend. Idempotent.
-pub fn delete(user_id: &str, key: &str) -> Result<(), KeyringError> {
+pub fn delete(user_id: &str, key: &str) -> Result<(), SecretStorageError> {
use tinystoragedrivers::secrets::SecretStore as _;
let Some(secrets) = storage_secrets()? else {
return process_delete(user_id, key);
@@ -156,7 +157,7 @@ pub fn delete(user_id: &str, key: &str) -> Result<(), KeyringError> {
///
/// Returns `Ok(None)` when no entry exists for this user + key combination.
/// Never logs the secret value.
-pub(crate) fn process_get(user_id: &str, key: &str) -> Result<Option<String>, KeyringError> {
+pub(crate) fn process_get(user_id: &str, key: &str) -> Result<Option<String>, SecretStorageError> {
log::debug!("[keyring] get");
let namespaced = namespaced_key(user_id, key);
let result = backend().get(&namespaced);
@@ -171,7 +172,7 @@ pub(crate) fn process_get(user_id: &str, key: &str) -> Result<Option<String>, Ke
/// Store a secret in the process backend.
///
/// Overwrites any existing entry for this user + key. Never logs the value.
-pub(crate) fn process_set(user_id: &str, key: &str, value: &str) -> Result<(), KeyringError> {
+pub(crate) fn process_set(user_id: &str, key: &str, value: &str) -> Result<(), SecretStorageError> {
log::debug!("[keyring] set");
let namespaced = namespaced_key(user_id, key);
let result = backend().set(&namespaced, value);
@@ -185,7 +186,7 @@ pub(crate) fn process_set(user_id: &str, key: &str, value: &str) -> Result<(), K
/// Delete a secret from the process backend.
///
/// Returns `Ok(())` even if no entry existed (idempotent).
-pub(crate) fn process_delete(user_id: &str, key: &str) -> Result<(), KeyringError> {
+pub(crate) fn process_delete(user_id: &str, key: &str) -> Result<(), SecretStorageError> {
log::debug!("[keyring] delete");
let namespaced = namespaced_key(user_id, key);
let result = backend().delete(&namespaced);
@@ -255,7 +256,7 @@ fn probe_availability() -> bool {
return available;
}
- let result = (|| -> Result<bool, KeyringError> {
+ let result = (|| -> Result<bool, SecretStorageError> {
// Delete any leftover probe key from a previous launch before writing.
// Without this, `set` fails with "item already exists" (-25299) on
// every launch after the first, causing `is_available` to incorrectly
@@ -288,7 +289,7 @@ fn probe_availability() -> bool {
fn backend_availability_without_probe(name: &str, encrypted_key_available: bool) -> Option<bool> {
match name {
- "file" | "mock" => Some(true),
+ "memory" | "file" | "mock" => Some(true),
"encrypted_file" => Some(encrypted_key_available),
_ => None,
}
@@ -304,11 +305,11 @@ pub fn get_or_create_random(
user_id: &str,
key: &str,
len_bytes: usize,
-) -> Result<String, KeyringError> {
+) -> Result<String, SecretStorageError> {
log::debug!("[keyring] get_or_create_random user_id={user_id} key={key} len_bytes={len_bytes}");
if len_bytes == 0 {
- return Err(KeyringError::Backend(
+ return Err(SecretStorageError::Backend(
"get_or_create_random requires len_bytes > 0".to_string(),
));
}
@@ -334,7 +335,7 @@ pub fn get_or_create_random(
log::warn!(
"[keyring] get_or_create_random write verification failed user_id={user_id} key={key}"
);
- return Err(KeyringError::VerifyFailed {
+ return Err(SecretStorageError::VerifyFailed {
key: key.to_string(),
});
}
@@ -351,13 +352,14 @@ pub fn get_or_create_random(
/// [`MigrationOutcome::MigratedAndDeleted`].
/// - If neither exists → [`MigrationOutcome::NoSourceFile`].
///
+/// Volatile backends reject migration and retain the durable source.
/// On any failure after the file has been read but before it can be deleted,
/// the file is **not** deleted and `Err` is returned so the caller can retry.
pub fn migrate_from_file(
user_id: &str,
key: &str,
path: &Path,
-) -> Result<MigrationOutcome, KeyringError> {
+) -> Result<MigrationOutcome, SecretStorageError> {
log::debug!(
"[keyring] migrate_from_file user_id={user_id} key={key} path={}",
path.display()
@@ -378,13 +380,19 @@ pub fn migrate_from_file(
return Ok(MigrationOutcome::NoSourceFile);
}
+ if !backend().is_persistent() {
+ return Err(SecretStorageError::Backend(
+ "file migration requires persistent secret storage; source retained".into(),
+ ));
+ }
+
// Step 3: read the file.
log::debug!(
"[keyring] migrate_from_file reading source file path={}",
path.display()
);
let file_content =
- std::fs::read_to_string(path).map_err(|e| KeyringError::MigrationReadFailed {
+ std::fs::read_to_string(path).map_err(|e| SecretStorageError::MigrationReadFailed {
path: path.display().to_string(),
source: e,
})?;
@@ -400,7 +408,7 @@ pub fn migrate_from_file(
log::warn!(
"[keyring] migrate_from_file verification failed user_id={user_id} key={key}; NOT deleting source file"
);
- return Err(KeyringError::VerifyFailed {
+ return Err(SecretStorageError::VerifyFailed {
key: key.to_string(),
});
}
@@ -410,7 +418,7 @@ pub fn migrate_from_file(
"[keyring] migrate_from_file deleting source file path={}",
path.display()
);
- std::fs::remove_file(path).map_err(|e| KeyringError::MigrationDeleteFailed {
+ std::fs::remove_file(path).map_err(|e| SecretStorageError::MigrationDeleteFailed {
path: path.display().to_string(),
source: e,
})?;
@@ -446,9 +454,9 @@ pub(crate) fn hex_encode(data: &[u8]) -> String {
/// (i.e. in a dedicated test binary or at the very start of a test).
#[cfg(test)]
pub(crate) fn force_backend_for_test(
- b: Box<dyn crate::security::keyring::backend::KeyringBackend>,
+ b: Box<dyn crate::security::secret_storage::backend::SecretBackend>,
) {
- use crate::security::keyring::store::BACKEND;
+ use crate::security::secret_storage::store::BACKEND;
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/secret_storage/ops_adoption_tests.rs
similarity index 93%
rename from crates/openhuman-core/src/security/keyring/ops_adoption_tests.rs
rename to crates/openhuman-core/src/security/secret_storage/ops_adoption_tests.rs
index 94641aacba..1505ed51a3 100644
--- a/crates/openhuman-core/src/security/keyring/ops_adoption_tests.rs
+++ b/crates/openhuman-core/src/security/secret_storage/ops_adoption_tests.rs
@@ -7,8 +7,8 @@ use std::sync::Arc;
use tinystoragedrivers::secrets::{DerivedKeys, SecretStore as _};
use zeroize::Zeroizing;
-use crate::security::keyring::backend::MockBackend;
-use crate::security::keyring::KeyringBackend;
+use crate::security::secret_storage::backend::MockBackend;
+use crate::security::secret_storage::SecretBackend;
use crate::storage::{MemoryStorage, Scope, StorageBackend};
#[test]
@@ -114,7 +114,7 @@ fn adopted_secrets_do_not_cross_scopes() {
#[test]
fn a_failing_legacy_backend_reads_as_nothing_to_adopt() {
assert_eq!(
- legacy_or_warn(Err(KeyringError::Backend("locked".into()))),
+ legacy_or_warn(Err(SecretStorageError::Backend("locked".into()))),
None
);
assert_eq!(legacy_or_warn(Ok(Some("v".into()))).as_deref(), Some("v"));
@@ -122,7 +122,7 @@ fn a_failing_legacy_backend_reads_as_nothing_to_adopt() {
let storage = MemoryStorage::new();
let secrets = storage_secrets_in(&storage, "local");
let read = get_adopting(secrets, "alice:k", "k", || {
- legacy_or_warn(Err(KeyringError::Backend("locked".into())))
+ legacy_or_warn(Err(SecretStorageError::Backend("locked".into())))
})
.unwrap();
assert_eq!(read, None);
diff --git a/crates/openhuman-core/src/security/keyring/store.rs b/crates/openhuman-core/src/security/secret_storage/store.rs
similarity index 81%
rename from crates/openhuman-core/src/security/keyring/store.rs
rename to crates/openhuman-core/src/security/secret_storage/store.rs
index a24170910c..1465faf8d4 100644
--- a/crates/openhuman-core/src/security/keyring/store.rs
+++ b/crates/openhuman-core/src/security/secret_storage/store.rs
@@ -1,4 +1,4 @@
-//! Backend selection and global-state management for the keyring module.
+//! Backend selection and global-state management for secret storage.
//!
//! Owns the two `OnceLock` singletons:
//! - [`WORKSPACE_DIR`] — the workspace directory provided at startup.
@@ -7,11 +7,12 @@
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
-use crate::security::keyring::backend::{self, KeyringBackend};
+use crate::security::secret_storage::backend::{self, SecretBackend};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum BackendKind {
- Os,
+ Host,
+ Memory,
File,
EncryptedFile,
}
@@ -25,7 +26,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<Arc<dyn KeyringBackend>> = OnceLock::new();
+pub(super) static BACKEND: OnceLock<Arc<dyn SecretBackend>> = OnceLock::new();
// ── Initialization ────────────────────────────────────────────────────────────
@@ -47,8 +48,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() -> Arc<dyn KeyringBackend> {
- super::installed_keyring_backend().unwrap_or_else(|| BACKEND.get_or_init(build_backend).clone())
+pub(super) fn backend() -> Arc<dyn SecretBackend> {
+ super::installed_secret_backend().unwrap_or_else(|| BACKEND.get_or_init(build_backend).clone())
}
/// Test builds resolve the backend **per workspace** instead of latching one
@@ -64,8 +65,8 @@ pub(super) fn backend() -> Arc<dyn KeyringBackend> {
/// [`super::ops::force_backend_for_test`] still pins [`BACKEND`] process-wide
/// and is honoured first.
#[cfg(test)]
-pub(super) fn backend() -> Arc<dyn KeyringBackend> {
- if let Some(installed) = super::installed_keyring_backend() {
+pub(super) fn backend() -> Arc<dyn SecretBackend> {
+ if let Some(installed) = super::installed_secret_backend() {
return installed;
}
if let Some(existing) = BACKEND.get() {
@@ -74,7 +75,7 @@ pub(super) fn backend() -> Arc<dyn KeyringBackend> {
test_scope::backend_for(&workspace_dir_for_file_backend())
}
-pub(super) fn build_backend() -> Arc<dyn KeyringBackend> {
+pub(super) fn build_backend() -> Arc<dyn SecretBackend> {
build_backend_at(&workspace_dir_for_file_backend())
}
@@ -82,17 +83,18 @@ pub(super) fn build_backend() -> Arc<dyn KeyringBackend> {
///
/// Split out of [`build_backend`] so test builds can construct one backend per
/// 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() {
+pub(super) fn build_backend_at(path: &Path) -> Arc<dyn SecretBackend> {
+ if let Some(installed) = super::installed_secret_backend() {
return installed;
}
let path = path.to_path_buf();
// 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) => {
+ Some(BackendKind::Memory) => return Arc::new(super::MemoryBackend::new()),
+ Some(BackendKind::Host) => {
log::info!("[keyring] backend=os (OPENHUMAN_KEYRING_BACKEND override)");
- return Arc::new(UnavailableOsBackend);
+ return Arc::new(MissingHostBackend);
}
Some(BackendKind::File) => {
log::info!(
@@ -120,24 +122,28 @@ pub(super) fn build_backend_at(path: &Path) -> Arc<dyn KeyringBackend> {
}
}
- Arc::new(super::encrypted_file_backend::EncryptedFileBackend::new(
- &path,
- ))
+ Arc::new(super::MemoryBackend::new())
}
-const OS_BACKEND_UNAVAILABLE: &str =
+const HOST_BACKEND_REQUIRED: &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()))
+struct MissingHostBackend;
+impl SecretBackend for MissingHostBackend {
+ fn get(&self, _: &str) -> Result<Option<String>, super::SecretStorageError> {
+ Err(super::SecretStorageError::Backend(
+ HOST_BACKEND_REQUIRED.into(),
+ ))
}
- fn set(&self, _: &str, _: &str) -> Result<(), super::KeyringError> {
- Err(super::KeyringError::Backend(OS_BACKEND_UNAVAILABLE.into()))
+ fn set(&self, _: &str, _: &str) -> Result<(), super::SecretStorageError> {
+ Err(super::SecretStorageError::Backend(
+ HOST_BACKEND_REQUIRED.into(),
+ ))
}
- fn delete(&self, _: &str) -> Result<(), super::KeyringError> {
- Err(super::KeyringError::Backend(OS_BACKEND_UNAVAILABLE.into()))
+ fn delete(&self, _: &str) -> Result<(), super::SecretStorageError> {
+ Err(super::SecretStorageError::Backend(
+ HOST_BACKEND_REQUIRED.into(),
+ ))
}
fn name(&self) -> &'static str {
"unavailable_os"
@@ -145,21 +151,21 @@ impl KeyringBackend for UnavailableOsBackend {
}
pub(super) fn validate_backend_selection() -> Result<(), String> {
- if super::installed_keyring_backend().is_none()
+ if super::installed_secret_backend().is_none()
&& std::env::var("OPENHUMAN_KEYRING_BACKEND")
.ok()
.as_deref()
.and_then(backend_kind_from_env_value)
- == Some(BackendKind::Os)
+ == Some(BackendKind::Host)
{
- return Err(OS_BACKEND_UNAVAILABLE.into());
+ return Err(HOST_BACKEND_REQUIRED.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);
+ if let Some(installed) = super::installed_secret_backend() {
+ return backend_kind_from_env_value(installed.name()).unwrap_or(BackendKind::Host);
}
effective_backend_kind_for(
std::env::var("OPENHUMAN_APP_ENV").as_deref().ok(),
@@ -175,12 +181,13 @@ fn effective_backend_kind_for(
) -> BackendKind {
backend_override
.and_then(backend_kind_from_env_value)
- .unwrap_or(BackendKind::EncryptedFile)
+ .unwrap_or(BackendKind::Memory)
}
fn backend_kind_from_env_value(value: &str) -> Option<BackendKind> {
match value.trim().to_ascii_lowercase().as_str() {
- "os" => Some(BackendKind::Os),
+ "memory" => Some(BackendKind::Memory),
+ "os" => Some(BackendKind::Host),
"file" => Some(BackendKind::File),
"encrypted_file" => Some(BackendKind::EncryptedFile),
_ => None,
diff --git a/crates/openhuman-core/src/security/keyring/store_test_scope_tests.rs b/crates/openhuman-core/src/security/secret_storage/store_test_scope_tests.rs
similarity index 91%
rename from crates/openhuman-core/src/security/keyring/store_test_scope_tests.rs
rename to crates/openhuman-core/src/security/secret_storage/store_test_scope_tests.rs
index 35ca57875b..1c9a92c2de 100644
--- a/crates/openhuman-core/src/security/keyring/store_test_scope_tests.rs
+++ b/crates/openhuman-core/src/security/secret_storage/store_test_scope_tests.rs
@@ -5,7 +5,7 @@ use std::sync::{Arc, OnceLock};
use parking_lot::Mutex;
-use super::{build_backend_at, KeyringBackend};
+use super::{build_backend_at, SecretBackend};
thread_local! {
/// Workspace bound by [`ScopedWorkspace`] on this thread, if any.
@@ -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, Arc<dyn KeyringBackend>>>> = OnceLock::new();
+static BACKENDS: OnceLock<Mutex<HashMap<PathBuf, Arc<dyn SecretBackend>>>> = OnceLock::new();
/// The keyring workspace for the calling thread.
pub(crate) fn current_workspace() -> PathBuf {
@@ -33,7 +33,7 @@ pub(crate) fn current_workspace() -> PathBuf {
}
/// The backend rooted at `dir`, built once per directory.
-pub(crate) fn backend_for(dir: &Path) -> Arc<dyn KeyringBackend> {
+pub(crate) fn backend_for(dir: &Path) -> Arc<dyn SecretBackend> {
let registry = BACKENDS.get_or_init(|| Mutex::new(HashMap::new()));
if let Some(existing) = registry.lock().get(dir).cloned() {
return existing;
diff --git a/crates/openhuman-core/src/security/keyring/store_tests.rs b/crates/openhuman-core/src/security/secret_storage/store_tests.rs
similarity index 86%
rename from crates/openhuman-core/src/security/keyring/store_tests.rs
rename to crates/openhuman-core/src/security/secret_storage/store_tests.rs
index a66e8a8731..4be057a2b7 100644
--- a/crates/openhuman-core/src/security/keyring/store_tests.rs
+++ b/crates/openhuman-core/src/security/secret_storage/store_tests.rs
@@ -21,7 +21,7 @@ use super::test_scope::ScopedWorkspace;
use super::{resolve_workspace_dir, workspace_dir_for_file_backend};
use crate::config::test_env::EnvVarGuard;
use crate::config::TEST_ENV_LOCK;
-use crate::security::keyring;
+use crate::security::secret_storage;
/// The root-cause pin: in test builds the keyring workspace must not be
/// steerable by a process-wide env var, because any test can set it while
@@ -82,28 +82,28 @@ fn scoped_workspaces_do_not_share_secrets() {
{
let _scope = ScopedWorkspace::new(one.path());
- keyring::set("user", "scoped-key", "value-one").expect("set in workspace one");
+ secret_storage::set("user", "scoped-key", "value-one").expect("set in workspace one");
}
{
let _scope = ScopedWorkspace::new(two.path());
assert_eq!(
- keyring::get("user", "scoped-key").expect("get in workspace two"),
+ secret_storage::get("user", "scoped-key").expect("get in workspace two"),
None,
"workspace two must not see workspace one's secrets"
);
- keyring::set("user", "scoped-key", "value-two").expect("set in workspace two");
+ secret_storage::set("user", "scoped-key", "value-two").expect("set in workspace two");
}
{
let _scope = ScopedWorkspace::new(one.path());
assert_eq!(
- keyring::get("user", "scoped-key").expect("re-read workspace one"),
+ secret_storage::get("user", "scoped-key").expect("re-read workspace one"),
Some("value-one".to_string()),
"workspace one's secret must be untouched by workspace two"
);
}
- assert!(one.path().join("secrets.enc").exists());
- assert!(two.path().join("secrets.enc").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
@@ -111,17 +111,17 @@ fn scoped_workspaces_do_not_share_secrets() {
/// disturb secrets belonging to the default (unscoped) store.
#[test]
fn a_deleted_scoped_workspace_does_not_reset_the_default_store() {
- keyring::set("isolation-regression", "session", "kept").expect("seed default store");
+ secret_storage::set("isolation-regression", "session", "kept").expect("seed default store");
{
let tmp = tempfile::tempdir().expect("tempdir");
let _scope = ScopedWorkspace::new(tmp.path());
- keyring::set("isolation-regression", "session", "discarded").expect("set in scope");
+ secret_storage::set("isolation-regression", "session", "discarded").expect("set in scope");
// `tmp` is dropped here — the directory and its dev-keychain.json vanish.
}
assert_eq!(
- keyring::get("isolation-regression", "session").expect("re-read default store"),
+ secret_storage::get("isolation-regression", "session").expect("re-read default store"),
Some("kept".to_string()),
"a vanished scoped workspace must not reset the default credential store"
);
diff --git a/crates/openhuman-core/src/security/keyring/store_tests_2_tests.rs b/crates/openhuman-core/src/security/secret_storage/store_tests_2_tests.rs
similarity index 52%
rename from crates/openhuman-core/src/security/keyring/store_tests_2_tests.rs
rename to crates/openhuman-core/src/security/secret_storage/store_tests_2_tests.rs
index b9812909a1..a312aa21c8 100644
--- a/crates/openhuman-core/src/security/keyring/store_tests_2_tests.rs
+++ b/crates/openhuman-core/src/security/secret_storage/store_tests_2_tests.rs
@@ -17,90 +17,73 @@ fn explicit_encrypted_file_backend_wins_in_dev_environment() {
}
#[test]
-fn staging_defaults_to_encrypted_file_without_override() {
- assert_eq!(
- effective_backend_kind_for(Some(" staging "), None, false),
- BackendKind::EncryptedFile
- );
+fn standalone_and_library_hosts_default_to_memory_in_every_environment() {
+ for app_env in [
+ None,
+ Some("development"),
+ Some("staging"),
+ Some("production"),
+ ] {
+ for test_build in [false, true] {
+ assert_eq!(
+ effective_backend_kind_for(app_env, None, test_build),
+ BackendKind::Memory
+ );
+ assert_eq!(
+ effective_backend_kind_for(app_env, Some("bogus"), test_build),
+ BackendKind::Memory
+ );
+ }
+ }
}
#[test]
-fn unknown_backend_override_falls_back_to_environment_default() {
+fn explicit_memory_backend_wins_in_every_environment() {
assert_eq!(
- effective_backend_kind_for(Some("production"), Some("bogus"), false),
- BackendKind::EncryptedFile
+ effective_backend_kind_for(Some("production"), Some(" MEMORY "), false),
+ BackendKind::Memory
);
}
#[test]
-fn unset_app_environment_defaults_to_encrypted_file() {
- assert_eq!(
- effective_backend_kind_for(None, None, false),
- BackendKind::EncryptedFile
- );
-}
-
-#[test]
-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::EncryptedFile,
- "{app_env} must not implicitly select plaintext storage"
- );
- }
-
- for app_env in ["", "production", "staging", "unknown"] {
- assert_eq!(
- effective_backend_kind_for(Some(app_env), None, false),
- BackendKind::EncryptedFile,
- "{app_env} must not silently select plaintext storage"
- );
- }
-}
-
-#[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"
- );
- }
- }
+fn default_memory_backend_needs_no_workspace_files_or_master_key() {
+ 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());
+ assert_eq!(super::build_backend_at(dir.path()).name(), "memory");
+ assert!(crate::security::secret_storage::is_available());
+ assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
}
#[test]
fn installed_backend_takes_precedence_and_is_thread_local() {
- use crate::security::keyring::KeyringBackend;
- use crate::security::keyring::{self, backend::MockBackend};
+ use crate::security::secret_storage::SecretBackend;
+ use crate::security::secret_storage::{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());
+ secret_storage::install_secret_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_eq!(secret_storage::backend_name(), "mock");
+ assert!(secret_storage::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())
+ std::thread::spawn(|| secret_storage::installed_secret_backend().is_none())
.join()
.unwrap()
);
- keyring::clear_keyring_backend();
- assert_eq!(super::build_backend_at(dir.path()).name(), "encrypted_file");
+ secret_storage::clear_secret_backend();
+ assert_eq!(super::build_backend_at(dir.path()).name(), "memory");
}
#[test]
diff --git a/crates/openhuman-core/src/security/secrets.rs b/crates/openhuman-core/src/security/secrets.rs
index 121de0555b..8413e4dc30 100644
--- a/crates/openhuman-core/src/security/secrets.rs
+++ b/crates/openhuman-core/src/security/secrets.rs
@@ -1 +1 @@
-pub use crate::security::keyring::encrypted_store::*;
+pub use crate::security::secret_storage::encrypted_store::*;
diff --git a/crates/openhuman-core/src/storage/README.md b/crates/openhuman-core/src/storage/README.md
index 1576d2dfe3..433186b470 100644
--- a/crates/openhuman-core/src/storage/README.md
+++ b/crates/openhuman-core/src/storage/README.md
@@ -189,7 +189,7 @@ without fencing).
`anyhow::Error` (a typed `FlowUpdateError` passes through unchanged).
- Approvals (`security::approval`), through `store_documents.rs`.
- Secrets (`storage::secrets`): the keyring's user secrets
- (`security::keyring::get` / `set` / `delete`) and the credential stores'
+ (`security::secret_storage::get` / `set` / `delete`) and the credential stores'
files (`auth-profiles.json`, `http-credentials.json`) become encrypted
documents (`DocumentSecrets`, `enc2:`) in the acting agent's scope. Each
scope's data key is derived with HKDF-SHA256 from the keyring master key
diff --git a/crates/openhuman-core/src/storage/secrets.rs b/crates/openhuman-core/src/storage/secrets.rs
index 9b16c0e61e..3540cc8961 100644
--- a/crates/openhuman-core/src/storage/secrets.rs
+++ b/crates/openhuman-core/src/storage/secrets.rs
@@ -1,7 +1,7 @@
//! Secrets on the installed storage backend.
//!
//! With a backend configured, the keyring's user secrets
-//! ([`crate::security::keyring::get`] / `set` / `delete`) and the credential
+//! ([`crate::security::secret_storage::get`] / `set` / `delete`) and the credential
//! stores' files live here instead of the OS keychain or `secrets.enc`: one
//! encrypted document per secret (`tinystoragedrivers` `DocumentSecrets`,
//! `enc2:` ChaCha20-Poly1305), under the acting agent's storage scope.
@@ -30,9 +30,10 @@ pub(crate) fn keys() -> Result<Arc<dyn KeyProvider>, StorageError> {
if let Some(keys) = KEYS.get() {
return Ok(Arc::clone(keys));
}
- let master = crate::security::keyring::encrypted_file_backend::storage_master_key().map_err(
- |error| StorageError::crypto(format!("no master key for storage secrets: {error}")),
- )?;
+ let master = crate::security::secret_storage::encrypted_file_backend::storage_master_key()
+ .map_err(|error| {
+ StorageError::crypto(format!("no master key for storage secrets: {error}"))
+ })?;
let built: Arc<dyn KeyProvider> = Arc::new(DerivedKeys::new(Zeroizing::new(master)));
Ok(Arc::clone(KEYS.get_or_init(|| built)))
}
diff --git a/crates/openhuman-core/src/web3/wallet/README.md b/crates/openhuman-core/src/web3/wallet/README.md
index 584dbfa4c4..8d14501b64 100644
--- a/crates/openhuman-core/src/web3/wallet/README.md
+++ b/crates/openhuman-core/src/web3/wallet/README.md
@@ -126,13 +126,13 @@ None. The module publishes or subscribes no `DomainEvent`s and has no `bus.rs`.
## Persistence
- `{workspace_dir}/state/wallet-state.json`: `StoredWalletState`, consent flag, source, mnemonic word count, accounts, `updated_at_ms`, and (only as fallback) the encrypted mnemonic. Written atomically (temp file + `sync_all` + dir fsync + `persist`), guarded by a process-wide `WALLET_STATE_FILE_LOCK`. Corrupt/unreadable/invalid files are quarantined to `...json.corrupted.<ts>`.
-- OS keychain: preferred home for the encrypted mnemonic under key `wallet.mnemonic`, scoped by a workspace-derived user id (`crate::security::keyring`), used only when `keyring_consent::policy::check_secret_access()` returns `Proceed` and the keyring is available. When available, the secret is stripped from JSON; load promotes any JSON-resident secret into the keychain.
+- OS keychain: preferred home for the encrypted mnemonic under key `wallet.mnemonic`, scoped by a workspace-derived user id (`crate::security::secret_storage`), used only when `keyring_consent::policy::check_secret_access()` returns `Proceed` and the keyring is available. When available, the secret is stripped from JSON; load promotes any JSON-resident secret into the keychain.
- In-memory quote store (instance-owned by the `WalletEngine`, `tinywallet_web3::quote::QuoteStore`): `PreparedTransaction`s, 5-minute TTL, cap 64, pruned on insert. Not persisted across restarts.
## Dependencies
- `crate::config` (`Config`, `config::rpc::load_config_with_timeout`): resolves workspace dir and config for state paths, keychain user id, and decryption.
-- `crate::security::keyring` (`is_available`/`get`/`set`): OS keychain storage for the encrypted mnemonic.
+- `crate::security::secret_storage` (`is_available`/`get`/`set`): OS keychain storage for the encrypted mnemonic.
- `crate::security::encryption::rpc` (`encrypt_secret`/`decrypt_secret`): `HostSigner` decrypts the recovery phrase before handing it to the wallet module.
- `crate::modules::wallet` (`derive_account`, `sign_transaction_in_module`, `sign_message`): the loaded `tinywallet` native module does every derivation and signature; the phrase is only sent after the module passes the attestation check (`modules::wallet::attested_proxy`).
- `crate::security::approval::APPROVAL_CHAT_CONTEXT`: task-local chat owner (`thread_id`/`client_id`), read by `TaskLocalScope`, used to bind quotes to their originating thread.
diff --git a/crates/openhuman-core/src/web3/wallet/ops/state.rs b/crates/openhuman-core/src/web3/wallet/ops/state.rs
index 34eda0d396..aa402e7e20 100644
--- a/crates/openhuman-core/src/web3/wallet/ops/state.rs
+++ b/crates/openhuman-core/src/web3/wallet/ops/state.rs
@@ -56,13 +56,13 @@ fn wallet_user_id(config: &Config) -> String {
pub(super) fn keychain_load_mnemonic(config: &Config) -> Option<String> {
let policy = crate::security::keyring_consent::policy::check_secret_access();
if policy != crate::security::keyring_consent::PolicyDecision::Proceed
- || !crate::security::keyring::is_available()
+ || !crate::security::secret_storage::is_available()
{
log::debug!("{LOG_PREFIX} keychain unavailable or consent pending, skipping mnemonic load policy={policy:?}");
return None;
}
let user_id = wallet_user_id(config);
- match crate::security::keyring::get(&user_id, KEYCHAIN_MNEMONIC_KEY) {
+ match crate::security::secret_storage::get(&user_id, KEYCHAIN_MNEMONIC_KEY) {
Ok(Some(val)) => {
log::debug!("{LOG_PREFIX} keychain mnemonic loaded user_id={user_id}");
Some(val)
@@ -84,13 +84,14 @@ pub(super) fn keychain_load_mnemonic(config: &Config) -> Option<String> {
fn keychain_save_mnemonic(config: &Config, encrypted_mnemonic: &str) -> bool {
let policy = crate::security::keyring_consent::policy::check_secret_access();
if policy != crate::security::keyring_consent::PolicyDecision::Proceed
- || !crate::security::keyring::is_available()
+ || !crate::security::secret_storage::is_available()
{
log::debug!("{LOG_PREFIX} keychain unavailable or consent pending, skipping mnemonic save policy={policy:?}");
return false;
}
let user_id = wallet_user_id(config);
- match crate::security::keyring::set(&user_id, KEYCHAIN_MNEMONIC_KEY, encrypted_mnemonic) {
+ match crate::security::secret_storage::set(&user_id, KEYCHAIN_MNEMONIC_KEY, encrypted_mnemonic)
+ {
Ok(()) => {
log::debug!("{LOG_PREFIX} keychain mnemonic saved user_id={user_id}");
true
@@ -106,13 +107,13 @@ fn keychain_save_mnemonic(config: &Config, encrypted_mnemonic: &str) -> bool {
pub(super) fn keychain_has_mnemonic(config: &Config) -> bool {
let policy = crate::security::keyring_consent::policy::check_secret_access();
if policy != crate::security::keyring_consent::PolicyDecision::Proceed
- || !crate::security::keyring::is_available()
+ || !crate::security::secret_storage::is_available()
{
return false;
}
let user_id = wallet_user_id(config);
matches!(
- crate::security::keyring::get(&user_id, KEYCHAIN_MNEMONIC_KEY),
+ crate::security::secret_storage::get(&user_id, KEYCHAIN_MNEMONIC_KEY),
Ok(Some(_))
)
}
diff --git a/crates/openhuman-embed/src/host_internals.rs b/crates/openhuman-embed/src/host_internals.rs
index 89018765c8..c92bbb5ab9 100644
--- a/crates/openhuman-embed/src/host_internals.rs
+++ b/crates/openhuman-embed/src/host_internals.rs
@@ -208,11 +208,12 @@ pub mod integrations {
/// 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 secret_storage {
+ pub use openhuman_core::security::secret_storage::{
+ clear_master_key_source, clear_secret_backend, init_workspace,
+ install_master_key_source, install_secret_backend, installed_master_key_source,
+ installed_secret_backend, is_available, store::workspace_dir_for_file_backend,
+ EncryptedFileBackend, MasterKeySource, SecretBackend, SecretStorageError,
};
}
pub mod credentials {
diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs
index 979ef8785f..150226287b 100644
--- a/crates/openhuman-embed/src/lib.rs
+++ b/crates/openhuman-embed/src/lib.rs
@@ -133,6 +133,7 @@ pub mod profiles;
/// Explicit ordered fallback and truncation policies.
pub mod routing;
mod runtime;
+pub mod secret_storage;
mod turn;
mod turn_cancellation;
mod turn_meter;
diff --git a/crates/openhuman-embed/src/process.rs b/crates/openhuman-embed/src/process.rs
index b1b99c6341..a76ac2b9f9 100644
--- a/crates/openhuman-embed/src/process.rs
+++ b/crates/openhuman-embed/src/process.rs
@@ -96,10 +96,10 @@ pub fn apply_startup_restart_delay_from_env() {
openhuman_core::platform::service::apply_startup_restart_delay_from_env();
}
-/// Load the master encryption key before anything decrypts a secret. A
-/// no-op once loaded; the core's boot calls it too.
+/// Load the master key when encrypted-file storage is selected. The default
+/// in-memory backend needs no key. Core boot also calls this helper.
pub fn init_master_key() -> anyhow::Result<()> {
- openhuman_core::security::keyring::init_master_key().map_err(|error| {
+ openhuman_core::security::secret_storage::init_master_key().map_err(|error| {
log::warn!("[embed][process] master key init failed");
anyhow::Error::msg(error)
})
diff --git a/crates/openhuman-embed/src/secret_storage.rs b/crates/openhuman-embed/src/secret_storage.rs
new file mode 100644
index 0000000000..53164fc486
--- /dev/null
+++ b/crates/openhuman-embed/src/secret_storage.rs
@@ -0,0 +1,13 @@
+//! Secret providers for the process's embedded runtime.
+//!
+//! Core and embed default to [`MemoryBackend`], which holds unencrypted values
+//! only in memory and loses them on process exit. No OS keychain or key file is
+//! required. To persist secrets, install a provider before building the runtime;
+//! providers are process-wide, matching embed's one-runtime-per-process rule.
+//! A persistent encrypted-file provider requires master-key initialization
+//! during core boot. Native OS providers belong to `openhuman-rpc::keyring`.
+
+pub use openhuman_core::security::secret_storage::{
+ install_secret_backend, installed_secret_backend, EncryptedFileBackend, MemoryBackend,
+ SecretBackend, SecretStorageError,
+};
diff --git a/crates/openhuman-embed/tests/common/mod.rs b/crates/openhuman-embed/tests/common/mod.rs
index 292f3d1ae1..dc0b890cae 100644
--- a/crates/openhuman-embed/tests/common/mod.rs
+++ b/crates/openhuman-embed/tests/common/mod.rs
@@ -63,12 +63,6 @@ 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 {
- // 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
index 0ba6d17fd0..de47a37a54 100644
--- a/crates/openhuman-embed/tests/headless_keys.rs
+++ b/crates/openhuman-embed/tests/headless_keys.rs
@@ -1,5 +1,4 @@
-//! A library host initializes encryption in its supplied workspace without
-//! keyring environment setup or an OS provider.
+//! Library secret storage needs no OS provider, environment setup or key files.
mod common;
@@ -7,7 +6,7 @@ use common::{offline_config, runtime_without_master_key};
use openhuman_embed::{RuntimeBuilder, ServiceSet, Workspace};
#[test]
-fn embedded_key_initialization_uses_the_supplied_workspace() {
+fn embedded_secrets_default_to_memory_without_key_files() {
std::thread::Builder::new()
.stack_size(openhuman_core::core::runtime::AGENT_WORKER_STACK_BYTES)
.spawn(|| {
@@ -24,23 +23,45 @@ fn embedded_key_initialization_uses_the_supplied_workspace() {
.build()
.await
.unwrap();
- let key = workspace.join("keyring/master.key");
- assert!(
- key.is_file(),
- "master key must live in the supplied workspace"
+ use openhuman_core::security::secret_storage;
+ use openhuman_embed::secret_storage as providers;
+ assert!(providers::installed_secret_backend().is_none());
+ assert_eq!(secret_storage::backend_name(), "memory");
+ assert!(secret_storage::is_available());
+ assert_eq!(
+ openhuman_core::security::keyring_consent::policy::current_status()
+ .active_mode
+ .to_string(),
+ "in_memory"
);
- assert!(
- !workspace.join("dev-keychain.json").exists(),
- "the library default must encrypt its secret store"
+ secret_storage::set("embed-user", "token", "memory-value").unwrap();
+ assert_eq!(
+ secret_storage::get("embed-user", "token")
+ .unwrap()
+ .as_deref(),
+ Some("memory-value")
);
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- assert_eq!(
- std::fs::metadata(key).unwrap().permissions().mode() & 0o777,
- 0o600
+ secret_storage::delete("embed-user", "token").unwrap();
+ assert_eq!(secret_storage::get("embed-user", "token").unwrap(), None);
+ for name in ["keyring/master.key", "secrets.enc", "dev-keychain.json"] {
+ assert!(
+ !workspace.join(name).exists(),
+ "in-memory storage must not write {name}"
);
}
+ let legacy_dir = workspace.join("legacy-secrets");
+ std::fs::create_dir_all(&legacy_dir).unwrap();
+ let legacy_key = legacy_dir.join(".secret_key");
+ let key_bytes = "01".repeat(32);
+ std::fs::write(&legacy_key, &key_bytes).unwrap();
+ let store = secret_storage::SecretStore::new(&legacy_dir, true);
+ let ciphertext = store.encrypt("legacy-compatible").unwrap();
+ assert_eq!(store.decrypt(&ciphertext).unwrap(), "legacy-compatible");
+ assert_eq!(
+ std::fs::read_to_string(&legacy_key).unwrap(),
+ key_bytes,
+ "volatile storage must leave a legacy durable key intact"
+ );
drop(runtime);
})
})
diff --git a/crates/openhuman-rpc/src/host.rs b/crates/openhuman-rpc/src/host.rs
index 054fe06412..253ec1325b 100644
--- a/crates/openhuman-rpc/src/host.rs
+++ b/crates/openhuman-rpc/src/host.rs
@@ -45,6 +45,9 @@ use tokio_util::sync::CancellationToken;
#[cfg(feature = "server")]
pub use crate::server::EmbeddedReadySignal;
+#[path = "host/secret_storage.rs"]
+mod secret_storage;
+
/// The CLI host's builder: the `cli` preset with this crate's server as the
/// `run` / `serve` launcher and the `http_host.*` controllers registered.
#[cfg(feature = "server")]
@@ -97,8 +100,7 @@ pub fn cli(args: &[String]) -> anyhow::Result<()> {
in that file will not be seen"
);
}
- #[cfg(feature = "os-keyring")]
- crate::keyring::install();
+ secret_storage::install();
let mut builder = cli_builder();
if cli_command_uses_storage(args, |namespace| {
// `subsystems` only renders status; it never touches stored state.
@@ -265,8 +267,7 @@ pub async fn desktop(
shutdown_token: CancellationToken,
ready_tx: tokio::sync::oneshot::Sender<EmbeddedReadySignal>,
) -> anyhow::Result<()> {
- #[cfg(feature = "os-keyring")]
- crate::keyring::install();
+ secret_storage::install();
log::debug!("[rpc:host] desktop options={options:?}");
serve_desktop(desktop_builder(&options), shutdown_token, ready_tx).await
}
@@ -315,8 +316,7 @@ 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();
+ secret_storage::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/host/secret_storage.rs b/crates/openhuman-rpc/src/host/secret_storage.rs
new file mode 100644
index 0000000000..639a6edf0c
--- /dev/null
+++ b/crates/openhuman-rpc/src/host/secret_storage.rs
@@ -0,0 +1,57 @@
+//! Persistent secret storage selected explicitly by product hosts.
+
+use crate::core_host::security::secret_storage::{
+ install_secret_backend, installed_secret_backend, workspace_dir_for_file_backend,
+ EncryptedFileBackend, SecretBackend, SecretStorageError,
+};
+use std::sync::{Arc, OnceLock};
+
+/// Preserve product-host persistence without changing the library default.
+/// Native support supplies the OS master key; explicit overrides and an
+/// embedder-installed provider retain precedence.
+pub(super) fn install() {
+ #[cfg(feature = "os-keyring")]
+ crate::keyring::install();
+ if installed_secret_backend().is_none()
+ && !std::env::var("OPENHUMAN_KEYRING_BACKEND").is_ok_and(|value| {
+ matches!(
+ value.trim().to_ascii_lowercase().as_str(),
+ "memory" | "file" | "encrypted_file" | "os"
+ )
+ })
+ {
+ install_secret_backend(Arc::new(PersistentBackend::default()));
+ }
+}
+
+// Resolve the directory on first operation, after core boot registers the
+// workspace. Constructing a file provider during host preflight would resolve
+// the default root before a supplied desktop workspace is available.
+#[derive(Default)]
+struct PersistentBackend(OnceLock<EncryptedFileBackend>);
+
+impl PersistentBackend {
+ fn backend(&self) -> &EncryptedFileBackend {
+ self.0
+ .get_or_init(|| EncryptedFileBackend::new(&workspace_dir_for_file_backend()))
+ }
+}
+
+impl SecretBackend for PersistentBackend {
+ fn get(&self, key: &str) -> Result<Option<String>, SecretStorageError> {
+ self.backend().get(key)
+ }
+ fn set(&self, key: &str, value: &str) -> Result<(), SecretStorageError> {
+ self.backend().set(key, value)
+ }
+ fn delete(&self, key: &str) -> Result<(), SecretStorageError> {
+ self.backend().delete(key)
+ }
+ fn name(&self) -> &'static str {
+ "encrypted_file"
+ }
+}
+
+#[cfg(test)]
+#[path = "secret_storage_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-rpc/src/host/secret_storage_tests.rs b/crates/openhuman-rpc/src/host/secret_storage_tests.rs
new file mode 100644
index 0000000000..ea49daf81d
--- /dev/null
+++ b/crates/openhuman-rpc/src/host/secret_storage_tests.rs
@@ -0,0 +1,48 @@
+use super::*;
+
+#[test]
+fn product_hosts_persist_secrets_in_the_workspace_registered_after_preflight() {
+ const STAGE: &str = "OPENHUMAN_TEST_PRODUCT_SECRET_STAGE";
+ if let Ok(stage) = std::env::var(STAGE) {
+ let dir =
+ std::path::PathBuf::from(std::env::var("OPENHUMAN_TEST_PRODUCT_SECRET_DIR").unwrap());
+ install();
+ assert!(!dir.join("secrets.enc").exists() || stage == "read");
+ crate::core_host::security::secret_storage::init_workspace(&dir);
+ let backend = installed_secret_backend().expect("persistent host default");
+ assert_eq!(backend.name(), "encrypted_file");
+ if stage == "write" {
+ backend.set("user:token", "first-value").unwrap();
+ backend.set("user:token", "saved-value").unwrap();
+ } else {
+ assert_eq!(
+ backend.get("user:token").unwrap().as_deref(),
+ Some("saved-value")
+ );
+ backend.delete("user:token").unwrap();
+ backend.delete("user:token").unwrap();
+ assert_eq!(backend.get("user:token").unwrap(), None);
+ }
+ assert!(dir.join("secrets.enc").is_file());
+ assert!(!dir.join("dev-keychain.json").exists());
+ return;
+ }
+ let dir = tempfile::tempdir().unwrap();
+ for stage in ["write", "read"] {
+ let result = std::process::Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", "host::secret_storage::tests::product_hosts_persist_secrets_in_the_workspace_registered_after_preflight"])
+ .env(STAGE, stage)
+ .env("OPENHUMAN_TEST_PRODUCT_SECRET_DIR", dir.path())
+ .env("OPENHUMAN_KEYRING_MASTER_KEY", "12".repeat(32))
+ .env_remove("OPENHUMAN_KEYRING_MASTER_KEY_FILE")
+ .env_remove("OPENHUMAN_KEYRING_BACKEND")
+ .env_remove("OPENHUMAN_STORAGE_URL")
+ .output().unwrap();
+ assert!(
+ result.status.success(),
+ "host {stage} failed: {}\n{}",
+ String::from_utf8_lossy(&result.stdout),
+ String::from_utf8_lossy(&result.stderr)
+ );
+ }
+}
diff --git a/crates/openhuman-rpc/src/keyring/backend.rs b/crates/openhuman-rpc/src/keyring/backend.rs
index 834762da04..498be609ed 100644
--- a/crates/openhuman-rpc/src/keyring/backend.rs
+++ b/crates/openhuman-rpc/src/keyring/backend.rs
@@ -1,6 +1,6 @@
//! Native OS secret storage, preserving service `openhuman` and `{user}:{key}`.
-use crate::core_host::security::keyring::{KeyringBackend, KeyringError};
+use crate::core_host::security::secret_storage::{SecretBackend, SecretStorageError};
use tinystoragedrivers::secrets::KeyringSecrets;
use tinystoragedrivers::{ErrorKind, StorageError};
use zeroize::Zeroizing;
@@ -38,8 +38,8 @@ impl Default for OsKeyringBackend {
}
}
-impl KeyringBackend for OsKeyringBackend {
- fn get(&self, namespaced_key: &str) -> Result<Option<String>, KeyringError> {
+impl SecretBackend for OsKeyringBackend {
+ fn get(&self, namespaced_key: &str) -> Result<Option<String>, SecretStorageError> {
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 }) {
@@ -50,7 +50,7 @@ impl KeyringBackend for OsKeyringBackend {
}
}
- fn set(&self, namespaced_key: &str, value: &str) -> Result<(), KeyringError> {
+ fn set(&self, namespaced_key: &str, value: &str) -> Result<(), SecretStorageError> {
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());
@@ -58,7 +58,7 @@ impl KeyringBackend for OsKeyringBackend {
.map_err(|e| os_error(namespaced_key, e))
}
- fn delete(&self, namespaced_key: &str) -> Result<(), KeyringError> {
+ fn delete(&self, namespaced_key: &str) -> Result<(), SecretStorageError> {
use tinystoragedrivers::secrets::SecretStore as _;
let (store, name) = (self.store.clone(), namespaced_key.to_string());
match crate::core_host::storage::block_on(
@@ -75,16 +75,19 @@ impl KeyringBackend for OsKeyringBackend {
}
}
-fn os_error(_key: &str, error: StorageError) -> KeyringError {
- KeyringError::Backend(format!("OS keychain: {error}"))
+fn os_error(_key: &str, error: StorageError) -> SecretStorageError {
+ SecretStorageError::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> {
+fn utf8(
+ key: &str,
+ value: Option<Zeroizing<Vec<u8>>>,
+) -> Result<Option<String>, SecretStorageError> {
value
.map(|bytes| {
- String::from_utf8(bytes.to_vec()).map_err(|source| KeyringError::InvalidUtf8 {
+ String::from_utf8(bytes.to_vec()).map_err(|source| SecretStorageError::InvalidUtf8 {
key: key.into(),
source,
})
diff --git a/crates/openhuman-rpc/src/keyring/backend_tests.rs b/crates/openhuman-rpc/src/keyring/backend_tests.rs
index 1c544fd454..9d6f63630c 100644
--- a/crates/openhuman-rpc/src/keyring/backend_tests.rs
+++ b/crates/openhuman-rpc/src/keyring/backend_tests.rs
@@ -6,9 +6,9 @@ use std::sync::{Arc, Mutex};
use tempfile::NamedTempFile;
use keyring::credential::{Credential, CredentialApi, CredentialBuilderApi};
-use tinystoragedrivers::secrets::{crypto, KeyringSecrets};
+use tinystoragedrivers::secrets::KeyringSecrets;
-use crate::core_host::security::keyring::KeyringBackend;
+use crate::core_host::security::secret_storage::SecretBackend;
type Shared = Arc<Mutex<HashMap<(String, String), Vec<u8>>>>;
@@ -144,7 +144,7 @@ fn a_locked_keychain_reads_empty_and_deletes_quietly_but_fails_a_write() {
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:?}");
+ assert!(matches!(error, SecretStorageError::Backend(_)), "{error:?}");
}
#[test]
@@ -199,13 +199,13 @@ fn os_user_id_isolation() {
#[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,
+ use crate::core_host::security::secret_storage::{
+ clear_secret_backend, install_secret_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());
+ install_secret_backend(b.clone());
assert!(is_available());
assert_eq!(
b.get(probe_key).unwrap(),
@@ -213,7 +213,7 @@ fn availability_probe_handles_a_leftover_os_entry_and_caches_success() {
"probe must remove its entry"
);
assert!(is_available());
- clear_keyring_backend();
+ clear_secret_backend();
}
#[test]
diff --git a/crates/openhuman-rpc/src/keyring/master_key.rs b/crates/openhuman-rpc/src/keyring/master_key.rs
index 199c21db2f..f4a65c66e2 100644
--- a/crates/openhuman-rpc/src/keyring/master_key.rs
+++ b/crates/openhuman-rpc/src/keyring/master_key.rs
@@ -1,6 +1,6 @@
//! The desktop master-key entry, with the existing service and account names.
-use crate::core_host::security::keyring::{KeyringError, MasterKeySource};
+use crate::core_host::security::secret_storage::{MasterKeySource, SecretStorageError};
use zeroize::Zeroizing;
/// Native master-key source. The entry is created lazily, so installing the
@@ -11,7 +11,7 @@ pub struct OsMasterKeySource {
}
impl OsMasterKeySource {
- fn entry(&self) -> Result<std::sync::Arc<keyring::Entry>, KeyringError> {
+ fn entry(&self) -> Result<std::sync::Arc<keyring::Entry>, SecretStorageError> {
if let Some(entry) = &self.entry {
return Ok(entry.clone());
}
@@ -23,7 +23,7 @@ impl OsMasterKeySource {
// 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 {
+fn native_error(context: &str, error: &keyring::Error) -> SecretStorageError {
let reason = match error {
keyring::Error::NoEntry => "entry does not exist",
keyring::Error::NoStorageAccess(_) => "credential store access denied or unavailable",
@@ -34,16 +34,16 @@ fn native_error(context: &str, error: &keyring::Error) -> KeyringError {
keyring::Error::Ambiguous(_) => "multiple matching credentials",
_ => "unknown native credential store error",
};
- KeyringError::Backend(format!("{context}: {reason}"))
+ SecretStorageError::Backend(format!("{context}: {reason}"))
}
-fn load_entry(entry: &keyring::Entry) -> Result<Option<Zeroizing<[u8; 32]>>, KeyringError> {
+fn load_entry(entry: &keyring::Entry) -> Result<Option<Zeroizing<[u8; 32]>>, SecretStorageError> {
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())
+ SecretStorageError::Backend("OS master key must be 64 hex characters".into())
})?;
Ok(Some(key))
}
@@ -56,11 +56,11 @@ fn load_entry(entry: &keyring::Entry) -> Result<Option<Zeroizing<[u8; 32]>>, Key
}
impl MasterKeySource for OsMasterKeySource {
- fn load(&self) -> Result<Option<Zeroizing<[u8; 32]>>, KeyringError> {
+ fn load(&self) -> Result<Option<Zeroizing<[u8; 32]>>, SecretStorageError> {
let entry = self.entry()?;
load_entry(&entry)
}
- fn store(&self, key: &[u8; 32]) -> Result<(), KeyringError> {
+ fn store(&self, key: &[u8; 32]) -> Result<(), SecretStorageError> {
let entry = self.entry()?;
let encoded = Zeroizing::new(hex::encode(key));
entry
diff --git a/crates/openhuman-rpc/src/keyring/mod.rs b/crates/openhuman-rpc/src/keyring/mod.rs
index 35c1b55481..d28669b05f 100644
--- a/crates/openhuman-rpc/src/keyring/mod.rs
+++ b/crates/openhuman-rpc/src/keyring/mod.rs
@@ -6,22 +6,23 @@ 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.
+/// Supply an OS master key for encrypted-file storage. The explicit `os`
+/// override also installs the native secret backend. Product host boot selects
+/// persistent storage separately; installing these sources alone leaves the
+/// basic library backend unchanged.
pub fn install() {
- use crate::core_host::security::keyring::{
- install_keyring_backend, install_master_key_source, installed_keyring_backend,
- installed_master_key_source,
+ use crate::core_host::security::secret_storage::{
+ install_master_key_source, install_secret_backend, installed_master_key_source,
+ installed_secret_backend,
};
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()
+ if installed_secret_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()));
+ install_secret_backend(Arc::new(OsKeyringBackend::new()));
}
}
diff --git a/crates/openhuman-rpc/src/lib.rs b/crates/openhuman-rpc/src/lib.rs
index e23fb38583..17fcaed4f1 100644
--- a/crates/openhuman-rpc/src/lib.rs
+++ b/crates/openhuman-rpc/src/lib.rs
@@ -53,9 +53,9 @@ pub mod tinyhumans {
pub mod embed {
pub use openhuman_tinyhumans::embed::modules;
pub use openhuman_tinyhumans::embed::{
- artifacts, chat_surface, config, process, schema_for_rpc_method, CoreRuntime,
- PickListenPortError, RuntimeBuilder, RuntimeInfo, ServiceSet, HTTP_SERVER_COMPILED_IN,
- VOICE_COMPILED_IN,
+ artifacts, chat_surface, config, process, schema_for_rpc_method, secret_storage,
+ CoreRuntime, PickListenPortError, RuntimeBuilder, RuntimeInfo, ServiceSet,
+ HTTP_SERVER_COMPILED_IN, VOICE_COMPILED_IN,
};
}
diff --git a/crates/openhuman-tinyhumans/src/lib.rs b/crates/openhuman-tinyhumans/src/lib.rs
index 1abbe34431..706280caa4 100644
--- a/crates/openhuman-tinyhumans/src/lib.rs
+++ b/crates/openhuman-tinyhumans/src/lib.rs
@@ -64,7 +64,8 @@ pub mod embed {
// The curated facades (each is an explicit list inside embed).
pub use openhuman_embed::modules;
pub use openhuman_embed::{
- artifacts, chat_surface, config, identity, memory, process, seams, session_store,
+ artifacts, chat_surface, config, identity, memory, process, seams, secret_storage,
+ session_store,
};
}
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 31550d7d3c..2202472cf8 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -675,7 +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.1.28 | Host-installed key stores and default in-memory library secrets | RU+RI+MS | `crates/openhuman-core/src/security/secret_storage/encrypted_file_backend/key_source_tests.rs`, `crates/openhuman-core/src/security/secret_storage/store_tests_2_tests.rs`, `crates/openhuman-core/src/security/secret_storage/memory_backend_tests.rs`, `crates/openhuman-rpc/src/keyring/*_tests.rs`, `crates/openhuman-embed/tests/headless_keys.rs`, `tests/keyring_headless_e2e.rs` | 🟡 | In-memory CRUD, isolation and threaded access, no-file embed defaults, installed-provider precedence, denied-source preservation, private workspace-key creation/reuse, and explicit encrypted-store 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/docs/gitbooks/en/developing/architecture/security.md b/docs/gitbooks/en/developing/architecture/security.md
index 1eb675a9ed..321aaa3696 100644
--- a/docs/gitbooks/en/developing/architecture/security.md
+++ b/docs/gitbooks/en/developing/architecture/security.md
@@ -28,7 +28,7 @@ It does not own the cross-domain `EncryptionEngine` (in `security/encryption/`)
| `SecurityPolicy` | `policy/types.rs` (path checks in `policy/path_checks.rs`, command classification in `policy/command_checks.rs`, gating in `policy/enforcement.rs`) | Assembles runtime policy from `AutonomyConfig` + workspace dir. |
| `AutonomyLevel` (`ReadOnly` / `Supervised` / `Full`) | `policy/types.rs` | Three-step autonomy ladder. |
| `CommandRiskLevel`, `ToolOperation`, `ActionTracker` | `policy/types.rs` | Risk classification and per-session counting. |
-| `SecretStore` | `keyring/encrypted_store.rs` (`secrets.rs` re-exports it) | OS-keychain / encrypted-file secret persistence with round-trip helpers. |
+| `SecretStore` | `secret_storage/encrypted_store.rs` (`secrets.rs` re-exports it) | OS-keychain / encrypted-file secret persistence with round-trip helpers. |
| `AuditLogger`, `AuditEventType`, `AuditEvent`, `Actor`, `Action`, `ExecutionResult`, `SecurityContext`, `CommandExecutionLog` | `audit.rs` | Append-only audit trail. |
| `PairingGuard`, `constant_time_eq`, `is_public_bind` | `pairing.rs` (`PairingGuard` and `constant_time_eq` are re-exported from `tinychannels_bus::security`) | Pairing-token check before binding the RPC server publicly. |
| `redact(value: &str) -> String` | `core.rs` | Uniform 4-char-prefix redaction for logs. |
@@ -64,7 +64,7 @@ One check never turns off. `is_always_forbidden` blocks credential stores (`~/.s
## Secret store
-`SecretStore` (implemented in `keyring/encrypted_store.rs`, re-exported through `secrets.rs`) encrypts config-field secrets with ChaCha20-Poly1305 (`enc2:` prefix) under a keychain-backed master key. It migrates the legacy XOR `enc:` format when it decrypts. Backend selection and the encrypted-file fallback are described in `crates/openhuman-core/src/security/keyring/README.md`.
+`SecretStore` (implemented in `security/secret_storage/encrypted_store.rs`, re-exported through `secrets.rs`) encrypts config-field secrets with ChaCha20-Poly1305 (`enc2:` prefix). It migrates the legacy XOR `enc:` format when it decrypts. Core owns the platform-independent secret-storage contracts, an in-memory default, and an optional encrypted-file backend. `openhuman-rpc::keyring` owns the native OS providers and installs them through those contracts before host boot. RPC product hosts explicitly select persistent storage; embed uses memory unless a provider or backend override is supplied. Backend selection and migration are described in `crates/openhuman-core/src/security/secret_storage/README.md`.
## `redact()`
@@ -77,7 +77,7 @@ One check never turns off. `is_always_forbidden` blocks credential stores (`~/.s
| `policy/` (`mod.rs`, `types.rs`, `path_checks.rs`, `command_checks.rs`, `enforcement.rs`, `policy_*_tests.rs`, `proptest_tests.rs`) | `SecurityPolicy`, `AutonomyLevel`, risk classification, path and command checks, action tracking. |
| `core.rs`, `core_tests.rs` | `redact()` + small shared helpers. |
| `audit.rs` | Append-only audit log types. |
-| `secrets.rs`, `keyring/` | `SecretStore` (implemented in `keyring/encrypted_store.rs`) + round-trip tests. |
+| `secrets.rs`, `secret_storage/` | `SecretStore` (implemented in `secret_storage/encrypted_store.rs`) + round-trip tests. |
| `pairing.rs`, `pairing_tests.rs` | `PairingGuard` + constant-time helpers. |
| `ops.rs` | RPC handler (`security_policy_info_for_config`). |
| `schemas.rs` | Controller schemas + handler dispatch. |
@@ -101,7 +101,7 @@ One check never turns off. `is_always_forbidden` blocks credential stores (`~/.s
## Tests
-- Unit: `pairing_tests.rs`, `policy/policy_tests*.rs`, `policy/proptest_tests.rs`, `keyring/encrypted_store_tests*.rs`.
+- Unit: `pairing_tests.rs`, `policy/policy_tests*.rs`, `policy/proptest_tests.rs`, `secret_storage/encrypted_store_tests*.rs`.
- `core_tests.rs` covers `redact()`.
## Related
diff --git a/gitbooks/developing/architecture/security.md b/gitbooks/developing/architecture/security.md
index 1eb675a9ed..321aaa3696 100644
--- a/gitbooks/developing/architecture/security.md
+++ b/gitbooks/developing/architecture/security.md
@@ -28,7 +28,7 @@ It does not own the cross-domain `EncryptionEngine` (in `security/encryption/`)
| `SecurityPolicy` | `policy/types.rs` (path checks in `policy/path_checks.rs`, command classification in `policy/command_checks.rs`, gating in `policy/enforcement.rs`) | Assembles runtime policy from `AutonomyConfig` + workspace dir. |
| `AutonomyLevel` (`ReadOnly` / `Supervised` / `Full`) | `policy/types.rs` | Three-step autonomy ladder. |
| `CommandRiskLevel`, `ToolOperation`, `ActionTracker` | `policy/types.rs` | Risk classification and per-session counting. |
-| `SecretStore` | `keyring/encrypted_store.rs` (`secrets.rs` re-exports it) | OS-keychain / encrypted-file secret persistence with round-trip helpers. |
+| `SecretStore` | `secret_storage/encrypted_store.rs` (`secrets.rs` re-exports it) | OS-keychain / encrypted-file secret persistence with round-trip helpers. |
| `AuditLogger`, `AuditEventType`, `AuditEvent`, `Actor`, `Action`, `ExecutionResult`, `SecurityContext`, `CommandExecutionLog` | `audit.rs` | Append-only audit trail. |
| `PairingGuard`, `constant_time_eq`, `is_public_bind` | `pairing.rs` (`PairingGuard` and `constant_time_eq` are re-exported from `tinychannels_bus::security`) | Pairing-token check before binding the RPC server publicly. |
| `redact(value: &str) -> String` | `core.rs` | Uniform 4-char-prefix redaction for logs. |
@@ -64,7 +64,7 @@ One check never turns off. `is_always_forbidden` blocks credential stores (`~/.s
## Secret store
-`SecretStore` (implemented in `keyring/encrypted_store.rs`, re-exported through `secrets.rs`) encrypts config-field secrets with ChaCha20-Poly1305 (`enc2:` prefix) under a keychain-backed master key. It migrates the legacy XOR `enc:` format when it decrypts. Backend selection and the encrypted-file fallback are described in `crates/openhuman-core/src/security/keyring/README.md`.
+`SecretStore` (implemented in `security/secret_storage/encrypted_store.rs`, re-exported through `secrets.rs`) encrypts config-field secrets with ChaCha20-Poly1305 (`enc2:` prefix). It migrates the legacy XOR `enc:` format when it decrypts. Core owns the platform-independent secret-storage contracts, an in-memory default, and an optional encrypted-file backend. `openhuman-rpc::keyring` owns the native OS providers and installs them through those contracts before host boot. RPC product hosts explicitly select persistent storage; embed uses memory unless a provider or backend override is supplied. Backend selection and migration are described in `crates/openhuman-core/src/security/secret_storage/README.md`.
## `redact()`
@@ -77,7 +77,7 @@ One check never turns off. `is_always_forbidden` blocks credential stores (`~/.s
| `policy/` (`mod.rs`, `types.rs`, `path_checks.rs`, `command_checks.rs`, `enforcement.rs`, `policy_*_tests.rs`, `proptest_tests.rs`) | `SecurityPolicy`, `AutonomyLevel`, risk classification, path and command checks, action tracking. |
| `core.rs`, `core_tests.rs` | `redact()` + small shared helpers. |
| `audit.rs` | Append-only audit log types. |
-| `secrets.rs`, `keyring/` | `SecretStore` (implemented in `keyring/encrypted_store.rs`) + round-trip tests. |
+| `secrets.rs`, `secret_storage/` | `SecretStore` (implemented in `secret_storage/encrypted_store.rs`) + round-trip tests. |
| `pairing.rs`, `pairing_tests.rs` | `PairingGuard` + constant-time helpers. |
| `ops.rs` | RPC handler (`security_policy_info_for_config`). |
| `schemas.rs` | Controller schemas + handler dispatch. |
@@ -101,7 +101,7 @@ One check never turns off. `is_always_forbidden` blocks credential stores (`~/.s
## Tests
-- Unit: `pairing_tests.rs`, `policy/policy_tests*.rs`, `policy/proptest_tests.rs`, `keyring/encrypted_store_tests*.rs`.
+- Unit: `pairing_tests.rs`, `policy/policy_tests*.rs`, `policy/proptest_tests.rs`, `secret_storage/encrypted_store_tests*.rs`.
- `core_tests.rs` covers `redact()`.
## Related
diff --git a/gitbooks/features/os-keyring-and-secret-storage.md b/gitbooks/features/os-keyring-and-secret-storage.md
index af28274481..a09b27e57c 100644
--- a/gitbooks/features/os-keyring-and-secret-storage.md
+++ b/gitbooks/features/os-keyring-and-secret-storage.md
@@ -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.** 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.
+**Credential entries.** In the desktop app, 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.
@@ -82,22 +82,36 @@ Desktop, CLI and TUI hosts install the OS keychain providers through
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.
+The core owns the platform-independent `security::secret_storage` module:
+user-scoped secret access, encrypted files, and master-key resolution. RPC owns
+`keyring`, the native OS providers, and installs them through core's `SecretBackend`
+and `MasterKeySource` contracts.
+
+The core and embedded library default to `MemoryBackend`: a thread-safe,
+unencrypted map held only in the process. It needs no OS keychain, master key,
+or secrets file. Secrets disappear when the process exits. Use it for ephemeral
+library runtimes; choose persistent storage when credentials must survive a restart.
+
+Embedders can install a provider before boot through
+`openhuman_embed::secret_storage::install_secret_backend(Arc::new(provider))`.
+The same facade exposes `MemoryBackend`, `EncryptedFileBackend`, `SecretBackend`
+and `SecretStorageError`. The provider is process-wide, matching the one-runtime
+contract; install it before building the runtime.
+
+CLI, desktop and TUI hosts explicitly retain encrypted-file storage by default.
+With native support enabled, its master key stays in the OS keychain. A host
+without that support creates `{workspace}/keyring/master.key` instead (Unix mode
+`0600`). Back up that key with the workspace.
+
+`OPENHUMAN_KEYRING_BACKEND=memory` selects the basic volatile backend explicitly;
+`file` selects the plaintext debug file, `encrypted_file` selects persistent
+encrypted storage, and `os` requires RPC's native provider. Installed providers
+win over environment selection.
+
+For encrypted storage, an operator can supply `OPENHUMAN_KEYRING_MASTER_KEY`
+(64 hex characters) or `OPENHUMAN_KEYRING_MASTER_KEY_FILE`. Set exactly one.
+Environment keys take precedence over a host source, then the workspace key file.
+An inaccessible host key never falls back to a newly created file key.
### Moving a desktop workspace to a server
diff --git a/scripts/ci/saas-ambient-baseline.json b/scripts/ci/saas-ambient-baseline.json
index 08289ea74d..b34298d2c8 100644
--- a/scripts/ci/saas-ambient-baseline.json
+++ b/scripts/ci/saas-ambient-baseline.json
@@ -890,7 +890,7 @@
},
{
"rule": "home-dir",
- "path": "crates/openhuman-core/src/security/keyring/store.rs",
+ "path": "crates/openhuman-core/src/security/secret_storage/store.rs",
"line": 231,
"text": "let home = dirs::home_dir().unwrap_or_else(|| {",
"occurrence": 1
diff --git a/scripts/ci/self-hosted/lanes-plan.mjs b/scripts/ci/self-hosted/lanes-plan.mjs
index fcbdd86bf8..212ac14d43 100644
--- a/scripts/ci/self-hosted/lanes-plan.mjs
+++ b/scripts/ci/self-hosted/lanes-plan.mjs
@@ -90,7 +90,7 @@ const STORAGE_LIB_FILTERS = [
"flows::",
"security::approval::",
"security::devices::",
- "security::keyring::",
+ "security::secret_storage::",
"security::credentials::",
"desktop::notifications::",
"integrations::task_sources::",
diff --git a/scripts/ci/storage-bypass-baseline.json b/scripts/ci/storage-bypass-baseline.json
index f93a64f801..2f4aa9b316 100644
--- a/scripts/ci/storage-bypass-baseline.json
+++ b/scripts/ci/storage-bypass-baseline.json
@@ -365,28 +365,28 @@
},
{
"rule": "json-write",
- "path": "crates/openhuman-core/src/security/keyring/encrypted_store.rs",
+ "path": "crates/openhuman-core/src/security/secret_storage/encrypted_store.rs",
"line": 316,
"text": "let open_result = fs::OpenOptions::new()",
"occurrence": 1
},
{
"rule": "json-write",
- "path": "crates/openhuman-core/src/security/keyring/encrypted_store.rs",
+ "path": "crates/openhuman-core/src/security/secret_storage/encrypted_store.rs",
"line": 348,
"text": "let open_result = fs::OpenOptions::new()",
"occurrence": 2
},
{
"rule": "json-write",
- "path": "crates/openhuman-core/src/security/keyring/file_store.rs",
+ "path": "crates/openhuman-core/src/security/secret_storage/file_store.rs",
"line": 79,
"text": "let file = OpenOptions::new()",
"occurrence": 1
},
{
"rule": "json-write",
- "path": "crates/openhuman-core/src/security/keyring/file_store.rs",
+ "path": "crates/openhuman-core/src/security/secret_storage/file_store.rs",
"line": 168,
"text": "match OpenOptions::new()",
"occurrence": 1
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 081a26a3d7..5c2f5709f6 100644
--- a/tests/in_process/config_auth_app_state_connectivity_e2e.rs
+++ b/tests/in_process/config_auth_app_state_connectivity_e2e.rs
@@ -4144,7 +4144,7 @@ fn credentials_profile_store_keychain_migration_and_fallback_paths_are_determini
let hit_dir = tmp.path().join("keychain-hit");
std::fs::create_dir_all(&hit_dir).expect("create keychain hit dir");
let hit_profile_id = "github:main";
- openhuman_core::security::keyring::set(
+ openhuman_core::security::secret_storage::set(
"keychain-hit",
&format!("auth:{hit_profile_id}"),
&json!({
@@ -4243,7 +4243,7 @@ fn credentials_profile_store_keychain_migration_and_fallback_paths_are_determini
.and_then(|profile| profile.token.as_deref()),
Some("plain-token-for-migration")
);
- let migrated_keychain = openhuman_core::security::keyring::get(
+ let migrated_keychain = openhuman_core::security::secret_storage::get(
"keychain-migrate",
&format!("auth:{migrate_profile_id}"),
)
@@ -4257,7 +4257,7 @@ fn credentials_profile_store_keychain_migration_and_fallback_paths_are_determini
let fallback_dir = tmp.path().join("keychain-fallback");
std::fs::create_dir_all(&fallback_dir).expect("create keychain fallback dir");
let fallback_profile_id = "slack:bot";
- openhuman_core::security::keyring::set(
+ openhuman_core::security::secret_storage::set(
"keychain-fallback",
&format!("auth:{fallback_profile_id}"),
"not-json",
@@ -4303,7 +4303,7 @@ fn credentials_profile_store_keychain_migration_and_fallback_paths_are_determini
"migrated profile should be removable"
);
assert!(
- openhuman_core::security::keyring::get(
+ openhuman_core::security::secret_storage::get(
"keychain-migrate",
&format!("auth:{migrate_profile_id}"),
)
diff --git a/tests/json_rpc_e2e.rs b/tests/json_rpc_e2e.rs
index 8f30e24145..8c18e03f56 100644
--- a/tests/json_rpc_e2e.rs
+++ b/tests/json_rpc_e2e.rs
@@ -1024,7 +1024,7 @@ async fn encrypt_test_mnemonic() -> String {
let config = openhuman_core::config::load_config_with_timeout()
.await
.expect("load config for encrypted test mnemonic");
- openhuman_core::security::keyring::init_workspace(&config.workspace_dir);
+ openhuman_core::security::secret_storage::init_workspace(&config.workspace_dir);
openhuman_core::security::encryption::rpc::encrypt_secret(
&config,
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
diff --git a/tests/keyring_headless_e2e.rs b/tests/keyring_headless_e2e.rs
index c2c51a339b..d8b65d3978 100644
--- a/tests/keyring_headless_e2e.rs
+++ b/tests/keyring_headless_e2e.rs
@@ -1,7 +1,7 @@
//! A headless core persists both secret slots and config ciphertext across
-//! process restarts, without an OS provider or keyring environment overrides.
+//! process restarts with explicit encrypted storage, without an OS provider or key injection.
-use openhuman_core::security::keyring;
+use openhuman_core::security::secret_storage;
use std::process::Command;
#[test]
@@ -9,14 +9,14 @@ 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);
+ secret_storage::init_workspace(&workspace);
+ secret_storage::init_master_key().unwrap();
+ assert_eq!(secret_storage::backend_name(), "encrypted_file");
+ assert!(secret_storage::is_available());
+ let config_secrets = secret_storage::SecretStore::new(&workspace, true);
let ciphertext_path = workspace.join("config-secret.txt");
if stage == "write" {
- keyring::set("test-user", "token", "persisted-token").unwrap();
+ secret_storage::set("test-user", "token", "persisted-token").unwrap();
std::fs::write(
&ciphertext_path,
config_secrets.encrypt("config-secret").unwrap(),
@@ -24,7 +24,9 @@ fn headless_core_reuses_its_workspace_key_after_restart() {
.unwrap();
} else {
assert_eq!(
- keyring::get("test-user", "token").unwrap().as_deref(),
+ secret_storage::get("test-user", "token")
+ .unwrap()
+ .as_deref(),
Some("persisted-token")
);
let ciphertext = std::fs::read_to_string(&ciphertext_path).unwrap();
@@ -49,7 +51,7 @@ fn 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("OPENHUMAN_KEYRING_BACKEND", "encrypted_file")
.env_remove("OPENHUMAN_KEYRING_MASTER_KEY")
.env_remove("OPENHUMAN_KEYRING_MASTER_KEY_FILE")
.env_remove("OPENHUMAN_STORAGE_URL")
diff --git a/tests/keyring_secretstore_e2e.rs b/tests/keyring_secretstore_e2e.rs
index 5ef131b674..9f511ce604 100644
--- a/tests/keyring_secretstore_e2e.rs
+++ b/tests/keyring_secretstore_e2e.rs
@@ -2,7 +2,7 @@
mod env_guard;
use env_guard::EnvVarGuard;
use openhuman_core::config::schema::{Config, StreamMode, TelegramConfig};
-use openhuman_core::security::keyring;
+use openhuman_core::security::secret_storage;
use std::sync::OnceLock;
async fn env_lock() -> tokio::sync::MutexGuard<'static, ()> {
@@ -22,7 +22,7 @@ async fn config_secrets_roundtrip_via_keyring_backed_master_key_migration() {
let _keyring_backend = EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file");
let _workspace_override = EnvVarGuard::set("OPENHUMAN_WORKSPACE", &openhuman_dir);
- keyring::init_workspace(&workspace_dir);
+ secret_storage::init_workspace(&workspace_dir);
let legacy_key_path = openhuman_dir.join(".secret_key");
std::fs::write(
diff --git a/tests/keyring_secretstore_fresh_e2e.rs b/tests/keyring_secretstore_fresh_e2e.rs
index 26175a5199..8b6220478e 100644
--- a/tests/keyring_secretstore_fresh_e2e.rs
+++ b/tests/keyring_secretstore_fresh_e2e.rs
@@ -2,7 +2,7 @@
mod env_guard;
use env_guard::EnvVarGuard;
use openhuman_core::config::schema::{Config, StreamMode, TelegramConfig};
-use openhuman_core::security::keyring;
+use openhuman_core::security::secret_storage;
use std::sync::OnceLock;
async fn env_lock_async() -> tokio::sync::MutexGuard<'static, ()> {
@@ -26,7 +26,7 @@ async fn config_secrets_create_master_key_in_keyring_on_fresh_install() {
let _keyring_backend = EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file");
let _workspace_override = EnvVarGuard::set("OPENHUMAN_WORKSPACE", &openhuman_dir);
- keyring::init_workspace(&workspace_dir);
+ secret_storage::init_workspace(&workspace_dir);
let legacy_key_path = openhuman_dir.join(".secret_key");
assert!(
diff --git a/tests/storage_secrets_e2e.rs b/tests/storage_secrets_e2e.rs
index 58e7a8b939..9b32f04e62 100644
--- a/tests/storage_secrets_e2e.rs
+++ b/tests/storage_secrets_e2e.rs
@@ -8,7 +8,7 @@
use openhuman_core::security::credentials::http_creds::{HttpCredential, HttpCredentialsStore};
use openhuman_core::security::credentials::profiles::{AuthProfile, AuthProfilesStore};
-use openhuman_core::security::keyring;
+use openhuman_core::security::secret_storage;
#[macro_use]
#[path = "support/storage_drivers.rs"]
@@ -46,7 +46,7 @@ fn a_configured_backend_holds_keyring_and_credential_secrets(case: Case) {
HttpCredentialsStore::new(&state, false)
.upsert(&HttpCredential::bearer("legacy-http", "ghp-legacy"))
.unwrap();
- keyring::set("legacy-user", "old_token", "old-value").unwrap();
+ secret_storage::set("legacy-user", "old_token", "old-value").unwrap();
let profiles_file = std::fs::read(state.join("auth-profiles.json")).unwrap();
let http_file = std::fs::read(state.join("http-credentials.json")).unwrap();
@@ -58,23 +58,31 @@ fn a_configured_backend_holds_keyring_and_credential_secrets(case: Case) {
case.install();
- keyring::set("user-1", "api_token", "tok-123").unwrap();
+ secret_storage::set("user-1", "api_token", "tok-123").unwrap();
assert_eq!(
- keyring::get("user-1", "api_token").unwrap().as_deref(),
+ secret_storage::get("user-1", "api_token")
+ .unwrap()
+ .as_deref(),
Some("tok-123")
);
- assert!(keyring::is_available());
- keyring::delete("user-1", "api_token").unwrap();
- assert!(keyring::get("user-1", "api_token").unwrap().is_none());
+ assert!(secret_storage::is_available());
+ secret_storage::delete("user-1", "api_token").unwrap();
+ assert!(secret_storage::get("user-1", "api_token")
+ .unwrap()
+ .is_none());
// A secret the process keyring held is adopted on first read, and a
// delete removes it from both places so it cannot resurface.
assert_eq!(
- keyring::get("legacy-user", "old_token").unwrap().as_deref(),
+ secret_storage::get("legacy-user", "old_token")
+ .unwrap()
+ .as_deref(),
Some("old-value")
);
- keyring::delete("legacy-user", "old_token").unwrap();
- assert!(keyring::get("legacy-user", "old_token").unwrap().is_none());
+ secret_storage::delete("legacy-user", "old_token").unwrap();
+ assert!(secret_storage::get("legacy-user", "old_token")
+ .unwrap()
+ .is_none());
let profiles = AuthProfilesStore::new(&state, false);
profiles
diff --git a/tests/support/env_guard.rs b/tests/support/env_guard.rs
index 420179cdfa..788c8c9080 100644
--- a/tests/support/env_guard.rs
+++ b/tests/support/env_guard.rs
@@ -83,5 +83,5 @@ pub async fn env_lock_async() -> MutexGuard<'static, ()> {
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());
+ openhuman_core::security::secret_storage::init_workspace(workspace.path());
}
diff --git a/tests/support/memory_engine_fixture.rs b/tests/support/memory_engine_fixture.rs
index 70596960ec..5a4b129eda 100644
--- a/tests/support/memory_engine_fixture.rs
+++ b/tests/support/memory_engine_fixture.rs
@@ -416,7 +416,7 @@ pub static AUTH_INIT: OnceLock<()> = OnceLock::new();
pub static SEAMS_INIT: OnceLock<()> = OnceLock::new();
pub fn env_lock() -> std::sync::MutexGuard<'static, ()> {
- openhuman_core::security::keyring::init_workspace(shared_workspace());
+ openhuman_core::security::secret_storage::init_workspace(shared_workspace());
match ENV_LOCK.get_or_init(|| Mutex::new(())).lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),