Skip to content

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

chore: files changed crates/openhuman-core/src/config/schema/load/branches.rs,crates/openhuman-core/

Steven Enamakelbde7e18f3026
diff --git a/crates/openhuman-core/src/config/schema/load/branches.rs b/crates/openhuman-core/src/config/schema/load/branches.rs
index 2001465c6b..07098b111c 100644
--- a/crates/openhuman-core/src/config/schema/load/branches.rs
+++ b/crates/openhuman-core/src/config/schema/load/branches.rs
@@ -8,7 +8,7 @@ use super::super::Config;
use super::dirs::{default_action_dir, resolve_action_dir, ConfigResolutionSource};
use super::env::EnvLookup;
use super::impl_load::{
- migration_source, parse_config_boxed, read_config_with_recovery_or_default,
+ migration_source, parse_config_boxed,
};
use super::migrate::{
migrate_cloud_provider_slugs, migrate_legacy_inference_url, migrate_legacy_memory_backend,
@@ -144,8 +144,10 @@ impl Config {
// (e.g. non-UTF-8 bytes), the corrupted file is renamed to
// `.corrupted.<timestamp>` and backup/defaults are attempted,
// with rate-limited error logging (#5167).
- let (contents, read_was_recovered) =
- read_config_with_recovery_or_default(&config_path).await?;
+ let super::source::ConfigRead {
+ contents,
+ recovered: read_was_recovered,
+ } = super::source::for_config(&config_path)?.read().await?;
// When `read_config_with_recovery_or_default` returned an empty
// string (both primary and backup were unreadable), skip the TOML
diff --git a/crates/openhuman-core/src/config/schema/load/impl_load.rs b/crates/openhuman-core/src/config/schema/load/impl_load.rs
index 6fd2d2610e..119d44e6bc 100644
--- a/crates/openhuman-core/src/config/schema/load/impl_load.rs
+++ b/crates/openhuman-core/src/config/schema/load/impl_load.rs
@@ -336,7 +336,10 @@ impl Config {
// `Config` temporary its own stack slot, so folding all three branches
// into this one state machine made the poll frame ~440 KB and stacked
// on top of the whole agent tower (#6379).
- if config_path.exists() {
+ // The first load of a process runs before any backend is installed, so
+ // it reads the file; later loads read the scope's config document on a
+ // shared backend.
+ if super::source::for_config(&config_path)?.exists().await? {
Box::pin(Self::load_existing_config(
openhuman_dir,
workspace_dir,
@@ -417,8 +420,8 @@ impl Config {
// scope's config document on a shared backend (bootstrap tables still
// come from the file). The first load of a process does not: see
// `source`.
- let source = super::source::for_config(&config_path);
- if !source.exists().await {
+ let source = super::source::for_config(&config_path)?;
+ if !source.exists().await? {
let mut config = Config {
config_path,
workspace_dir,
@@ -481,16 +484,20 @@ impl Config {
}
async fn save_inner(&self) -> Result<()> {
+ // Where the text lives is the source's business: the file (atomic
+ // replace with a `.bak`) or, on a shared backend, the config document.
+ let source = super::source::for_config(&self.config_path)?;
let mut config_to_save = self.clone();
super::super::cli_overrides::restore_persisted_inference_fields(&mut config_to_save);
- encrypt_config_secrets(&mut config_to_save)?;
+ // A document source seals the whole body under the scope's data key;
+ // the process-local field key would make it unreadable on another node.
+ if !source.encrypts_body() {
+ encrypt_config_secrets(&mut config_to_save)?;
+ }
let toml_str =
toml::to_string_pretty(&config_to_save).context("Failed to serialize config")?;
- // Where the text lives is the source's business: the file (atomic
- // replace with a `.bak`) or, on a shared backend, the config document.
- let source = super::source::for_config(&self.config_path);
tracing::debug!(source = source.label(), "[config] saving config");
source.write(&toml_str).await?;
diff --git a/crates/openhuman-core/src/config/schema/load/source/document.rs b/crates/openhuman-core/src/config/schema/load/source/document.rs
index c57afd5707..be4282546b 100644
--- a/crates/openhuman-core/src/config/schema/load/source/document.rs
+++ b/crates/openhuman-core/src/config/schema/load/source/document.rs
@@ -2,53 +2,89 @@
use std::sync::Arc;
-use anyhow::{Context, Result};
+use anyhow::{anyhow, Context, Result};
use async_trait::async_trait;
use serde_json::json;
+use tinystoragedrivers::secrets::{crypto, KeyProvider};
use tinystoragedrivers::{CollectionSpec, DocumentStore, Precondition};
use super::{apply_bootstrap, strip_bootstrap, ConfigRead, ConfigSource, FileConfigSource};
+use crate::storage::Scope;
/// The collection holding one config document per scope.
pub(crate) const CONFIG_COLLECTION: &str = "config";
-/// The document field holding the TOML body.
-const BODY_FIELD: &str = "toml";
+/// The document field holding the encrypted TOML body (`enc2:` hex).
+const BODY_FIELD: &str = "toml_enc";
/// A config kept as one document, `config/{scope}`, on the storage backend.
///
-/// The document body is the TOML text without its bootstrap tables
-/// ([`super::BOOTSTRAP_TABLES`]); reads re-apply those from the `file`
-/// fallback. When the scope has no document yet, reads fall back to the file
-/// (a first run seeds from the bootstrap file), and the next write creates it.
+/// The body is the TOML text without its bootstrap tables
+/// ([`super::BOOTSTRAP_TABLES`]), encrypted as a whole (`enc2:`) under the
+/// scope's data key from the storage [`KeyProvider`]: the same per-scope key
+/// the scope's other secrets use, derived from a master key every node of a
+/// deployment shares. Field-level encryption under the process-local config
+/// key would leave the document unreadable on any other node, so
+/// [`ConfigSource::encrypts_body`] tells `Config::save` to skip it. With no
+/// key the source fails closed.
+///
+/// Reads re-apply the bootstrap tables from the `file` fallback. When the
+/// scope has no document yet, reads fall back to the file (a first run seeds
+/// from it) and the next write creates the document.
pub(crate) struct DocumentConfigSource {
docs: Arc<dyn DocumentStore>,
- scope: String,
+ scope: Scope,
+ keys: Arc<dyn KeyProvider>,
file: FileConfigSource,
}
impl DocumentConfigSource {
- pub(crate) fn new(docs: Arc<dyn DocumentStore>, scope: String, file: FileConfigSource) -> Self {
- Self { docs, scope, file }
+ pub(crate) fn new(
+ docs: Arc<dyn DocumentStore>,
+ scope: Scope,
+ keys: Arc<dyn KeyProvider>,
+ file: FileConfigSource,
+ ) -> Self {
+ Self {
+ docs,
+ scope,
+ keys,
+ file,
+ }
}
- async fn stored_body(&self) -> Result<Option<String>> {
+ fn key(&self) -> Result<zeroize::Zeroizing<[u8; crypto::KEY_LEN]>> {
+ self.keys
+ .data_key(&self.scope)
+ .map_err(|error| anyhow!("no data key for the config document: {error}"))
+ }
+
+ /// The decrypted stored body, or `None` when the scope has no document.
+ async fn stored_body(&self) -> Result<Option<zeroize::Zeroizing<String>>> {
self.docs
.ensure_collection(&CollectionSpec::new(CONFIG_COLLECTION))
.await
.context("declare the config collection")?;
let stored = self
.docs
- .get(CONFIG_COLLECTION, &self.scope)
+ .get(CONFIG_COLLECTION, self.scope.as_str())
.await
.context("read the config document")?;
- Ok(stored.and_then(|versioned| {
+ let Some(sealed) = stored.and_then(|versioned| {
versioned
.doc
.get(BODY_FIELD)
.and_then(|body| body.as_str())
.map(str::to_string)
- }))
+ }) else {
+ return Ok(None);
+ };
+ let key = self.key()?;
+ let plain = crypto::decrypt_enc2(&key, &sealed)
+ .map_err(|error| anyhow!("the config document does not decrypt: {error}"))?;
+ let body = String::from_utf8(plain.to_vec())
+ .map_err(|_| anyhow!("the config document is not UTF-8"))?;
+ Ok(Some(zeroize::Zeroizing::new(body)))
}
}
@@ -58,40 +94,56 @@ impl ConfigSource for DocumentConfigSource {
"document"
}
- async fn exists(&self) -> bool {
- match self.stored_body().await {
- Ok(Some(_)) => true,
- _ => self.file.exists().await,
+ fn encrypts_body(&self) -> bool {
+ true
+ }
+
+ async fn exists(&self) -> Result<bool> {
+ // Existence is checked without decrypting: a document whose key is
+ // missing still exists, and the read then reports the real error.
+ self.docs
+ .ensure_collection(&CollectionSpec::new(CONFIG_COLLECTION))
+ .await
+ .context("declare the config collection")?;
+ let stored = self
+ .docs
+ .get(CONFIG_COLLECTION, self.scope.as_str())
+ .await
+ .context("read the config document")?;
+ if stored.is_some() {
+ return Ok(true);
}
+ self.file.exists().await
}
async fn read(&self) -> Result<ConfigRead> {
let Some(body) = self.stored_body().await? else {
- tracing::debug!(scope = %self.scope, "[config] no config document; reading the file");
+ tracing::debug!(scope = %self.scope.as_str(), "[config] no config document; reading the file");
return self.file.read().await;
};
// Bootstrap tables come from the file, whatever the document says.
- let file_text = tokio::fs::read_to_string(self.file.path()).await.ok();
- match apply_bootstrap(&body, file_text.as_deref()) {
- Ok(contents) => Ok(ConfigRead {
- contents,
- recovered: false,
- }),
+ let file_text = match tokio::fs::read_to_string(self.file.path()).await {
+ Ok(text) => Some(text),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
Err(error) => {
- // A body that does not parse is handed to the loader as-is so
- // its parse recovery (defaults, loud log) applies as it does to
- // a corrupt file; the document is not rewritten here.
- tracing::warn!(scope = %self.scope, error = %error, "[config] config document is not valid TOML");
- Ok(ConfigRead {
- contents: body,
- recovered: false,
- })
+ return Err(anyhow!(error).context("read the bootstrap config file"));
}
- }
+ };
+ let contents = apply_bootstrap(&body, file_text.as_deref())
+ .context("apply the bootstrap tables to the config document")?;
+ Ok(ConfigRead {
+ contents,
+ recovered: false,
+ })
}
async fn write(&self, toml: &str) -> Result<()> {
- let body = strip_bootstrap(toml).context("strip bootstrap tables from the config")?;
+ let body = zeroize::Zeroizing::new(
+ strip_bootstrap(toml).context("strip bootstrap tables from the config")?,
+ );
+ let key = self.key()?;
+ let sealed = crypto::encrypt_enc2(&key, body.as_bytes())
+ .map_err(|error| anyhow!("encrypt the config document: {error}"))?;
self.docs
.ensure_collection(&CollectionSpec::new(CONFIG_COLLECTION))
.await
@@ -99,13 +151,13 @@ impl ConfigSource for DocumentConfigSource {
self.docs
.put(
CONFIG_COLLECTION,
- &self.scope,
- json!({ BODY_FIELD: body }),
+ self.scope.as_str(),
+ json!({ BODY_FIELD: sealed }),
Precondition::None,
)
.await
.context("write the config document")?;
- tracing::debug!(scope = %self.scope, "[config] wrote the config document");
+ tracing::debug!(scope = %self.scope.as_str(), "[config] wrote the config document");
Ok(())
}
}