Skip to content

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

feat(storage): migrate profile credentials into encrypted storage

Steven Enamakela69e4a6cfaac
diff --git a/crates/openhuman-core/src/security/credentials/http_creds.rs b/crates/openhuman-core/src/security/credentials/http_creds.rs
index bf1311bc28..9427050595 100644
--- a/crates/openhuman-core/src/security/credentials/http_creds.rs
+++ b/crates/openhuman-core/src/security/credentials/http_creds.rs
@@ -25,7 +25,7 @@ use serde::{Deserialize, Serialize};
use crate::config::Config;
use crate::security::secret_storage::SecretStore;
-const STORE_FILENAME: &str = "http-credentials.json";
+pub(crate) const STORE_FILENAME: &str = "http-credentials.json";
/// The HTTP credentials file a store over `state_dir` keeps.
pub(crate) fn store_file(state_dir: &Path) -> PathBuf {
state_dir.join(STORE_FILENAME)
@@ -439,7 +439,7 @@ impl HttpCredentialsStore {
/// The secret the store lives in on a storage backend
/// ([`crate::storage::secrets`]): the same JSON as the file, encrypted as one
/// secret in the acting agent's scope.
-const STORAGE_SECRET_NAME: &str = "file:http-credentials.json";
+pub(crate) const STORAGE_SECRET_NAME: &str = "file:http-credentials.json";
fn parse_scheme(raw: &str) -> Option<HttpCredentialScheme> {
match raw.trim().to_ascii_lowercase().as_str() {
diff --git a/crates/openhuman-core/src/security/credentials/profiles.rs b/crates/openhuman-core/src/security/credentials/profiles.rs
index 122e5ae1c1..52e4cb8bff 100644
--- a/crates/openhuman-core/src/security/credentials/profiles.rs
+++ b/crates/openhuman-core/src/security/credentials/profiles.rs
@@ -22,6 +22,7 @@ mod keychain;
mod lock;
mod migration;
mod persistence;
+pub(crate) use persistence::STORAGE_SECRET_NAME as PROFILES_SECRET_NAME;
mod store_core;
const CURRENT_SCHEMA_VERSION: u32 = 1;
@@ -38,7 +39,7 @@ struct KeychainSecrets {
#[serde(default)]
pub id_token: Option<String>,
}
-const PROFILES_FILENAME: &str = "auth-profiles.json";
+pub(crate) const PROFILES_FILENAME: &str = "auth-profiles.json";
/// The auth-profiles file a store over `state_dir` keeps.
pub(crate) fn profiles_file(state_dir: &Path) -> PathBuf {
state_dir.join(PROFILES_FILENAME)
diff --git a/crates/openhuman-core/src/security/credentials/profiles/persistence.rs b/crates/openhuman-core/src/security/credentials/profiles/persistence.rs
index 44eb936437..2cbf0f9d23 100644
--- a/crates/openhuman-core/src/security/credentials/profiles/persistence.rs
+++ b/crates/openhuman-core/src/security/credentials/profiles/persistence.rs
@@ -21,7 +21,7 @@ use super::{
/// The secret the profiles live in on a storage backend
/// ([`crate::storage::secrets`]): the same JSON as `auth-profiles.json`,
/// encrypted as one secret in the acting agent's scope.
-const STORAGE_SECRET_NAME: &str = "file:auth-profiles.json";
+pub(crate) const STORAGE_SECRET_NAME: &str = "file:auth-profiles.json";
impl AuthProfilesStore {
pub(super) fn save_locked(&self, data: &AuthProfilesData) -> Result<()> {
diff --git a/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend.rs b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend.rs
index b0e1d33cf7..710a871169 100644
--- a/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend.rs
+++ b/crates/openhuman-core/src/security/secret_storage/encrypted_file_backend.rs
@@ -160,6 +160,29 @@ pub(crate) fn storage_master_key() -> Result<[u8; KEY_LEN], String> {
}
}
+/// Whether the storage master key can be resolved without minting a new one:
+/// an operator key (env), a host key source, an already loaded key, or an
+/// existing workspace key file. A layout migration that deletes the plaintext
+/// credential files only imports them when this holds, because a key minted
+/// by an offline tool would not match the one the desktop later loads.
+pub(crate) fn storage_master_key_resolvable() -> bool {
+ let env_set = |name: &str| {
+ std::env::var_os(name).is_some_and(|v| !v.to_string_lossy().trim().is_empty())
+ };
+ let dir = crate::security::secret_storage::store::workspace_dir_for_file_backend();
+ resolvable(
+ matches!(MASTER_KEY.get(), Some(Ok(Some(_)))),
+ env_set(MASTER_KEY_ENV) || env_set(MASTER_KEY_FILE_ENV),
+ key_source::installed_master_key_source().is_some(),
+ dir.join("keyring/master.key").is_file(),
+ )
+}
+
+/// The pure decision behind [`storage_master_key_resolvable`].
+pub(crate) fn resolvable(loaded: bool, env: bool, host: bool, key_file: bool) -> bool {
+ loaded || env || host || key_file
+}
+
/// Runs `init` at most once per `cell` and reports its outcome on every call.
///
/// A configuration error is stored in the cell rather than leaving it empty
diff --git a/crates/openhuman-core/src/storage/layout/archive.rs b/crates/openhuman-core/src/storage/layout/archive.rs
index 6aa111123c..209139a74c 100644
--- a/crates/openhuman-core/src/storage/layout/archive.rs
+++ b/crates/openhuman-core/src/storage/layout/archive.rs
@@ -30,6 +30,8 @@ use super::state::LayoutError;
pub const MANIFEST_ENTRY: &str = "MANIFEST.json";
/// The prefix every archived path carries.
pub const ROOT: &str = "workspace";
+/// The prefix of profile-level files (beside `config.toml`) in the archive.
+pub const PROFILE_ROOT: &str = "profile";
const ZSTD_LEVEL: i32 = 3;
/// One archived file.
@@ -145,7 +147,12 @@ fn write_inner(
files: Vec::new(),
};
for source in sources {
- let root = format!("{ROOT}/{}", source.rel);
+ // A profile-level credential file (`@profile/<name>`) is archived as
+ // `profile/<name>` and restored beside `config.toml`.
+ let root = match source.rel.strip_prefix(super::credentials::PROFILE_PREFIX) {
+ Some(name) => format!("{PROFILE_ROOT}/{name}"),
+ None => format!("{ROOT}/{}", source.rel),
+ };
for item in WalkDir::new(&source.at)
.follow_links(false)
.sort_by_file_name()
@@ -338,9 +345,25 @@ pub fn restore(archive: &Path, profile_dir: &Path) -> Result<Manifest, LayoutErr
if path == Path::new(MANIFEST_ENTRY) {
continue;
}
+ if let Ok(name) = path.strip_prefix(PROFILE_ROOT) {
+ // Only a plain file name directly below `profile/`.
+ let mut parts = name.components();
+ let plain = matches!(
+ (parts.next(), parts.next()),
+ (Some(std::path::Component::Normal(_)), None)
+ );
+ if !plain {
+ return Err(LayoutError::Verify(format!(
+ "{} escapes the profile directory",
+ path.display()
+ )));
+ }
+ entry.unpack(profile_dir.join(name))?;
+ continue;
+ }
if !path.starts_with(ROOT) {
return Err(LayoutError::Verify(format!(
- "{} is outside {ROOT}/",
+ "{} is outside {ROOT}/ and {PROFILE_ROOT}/",
path.display()
)));
}
diff --git a/crates/openhuman-core/src/storage/layout/credentials.rs b/crates/openhuman-core/src/storage/layout/credentials.rs
new file mode 100644
index 0000000000..2ee8717cf9
--- /dev/null
+++ b/crates/openhuman-core/src/storage/layout/credentials.rs
@@ -0,0 +1,117 @@
+//! The credential fallback files a profile keeps beside `config.toml`.
+//!
+//! `auth-profiles.json` and `http-credentials.json` are the on-disk fallbacks
+//! the credential stores use when no storage backend holds them. Under layout
+//! v2 they live as encrypted secrets (`tsd.secrets`, `enc2:` ChaCha20-Poly1305,
+//! a per-scope key derived from the process master key) in the profile's
+//! `local` scope. Step 2 of the migration imports them there, verifies the
+//! read-back, and lists them in the plan as deleted entries so the archive
+//! holds them and the final step removes them. A file that is not imported
+//! (no usable master key, not valid JSON) is never classified, so it is left
+//! in place and the stores keep adopting it lazily.
+//!
+//! The process-level files stay where they are and are outside every profile's
+//! plan: `keyring/master.key` and the shared `secrets.enc` keyring (one file
+//! for all profiles, entries namespaced by user id, adopted per key on first
+//! read by `secret_storage::get`). The master key is never written into
+//! `storage.db`.
+
+use std::path::Path;
+
+use tinystoragedrivers::secrets::SecretStore as _;
+
+use super::state::LayoutError;
+use super::Target;
+use crate::security::credentials::http_creds::{STORAGE_SECRET_NAME, STORE_FILENAME};
+use crate::security::credentials::profiles::{PROFILES_FILENAME, PROFILES_SECRET_NAME};
+use crate::storage;
+
+/// The path prefix a profile-level plan entry carries (`@profile/<file>`),
+/// to tell it from an entry below `workspace/`.
+pub const PROFILE_PREFIX: &str = "@profile/";
+
+/// (file name beside `config.toml`, secret name on the storage backend).
+pub const FILES: [(&str, &str); 2] = [
+ (PROFILES_FILENAME, PROFILES_SECRET_NAME),
+ (STORE_FILENAME, STORAGE_SECRET_NAME),
+];
+
+/// Imports the credential files of `target` into the v1 database's `local`
+/// scope and returns the file names that are now safe to archive and delete.
+///
+/// A record already on the backend is authoritative (a v1 core with the
+/// backend installed adopts and then updates it there, so the file may be
+/// stale); it is only checked to be readable with the current key.
+///
+/// # Errors
+///
+/// A write that does not read back identically, or a stored record that does
+/// not decrypt with the current key. Nothing is deleted then.
+pub async fn import(target: &Target) -> Result<Vec<String>, LayoutError> {
+ let mut files = Vec::new();
+ for (file, secret) in FILES {
+ let path = target.profile_dir.join(file);
+ let Ok(meta) = std::fs::symlink_metadata(&path) else {
+ continue;
+ };
+ if !meta.is_file() {
+ tracing::warn!(target: "openhuman::storage", file, "[layout] credential entry is not a regular file; left in place");
+ continue;
+ }
+ let bytes = read(&path)?;
+ if serde_json::from_slice::<serde_json::Value>(&bytes).is_err() {
+ tracing::warn!(target: "openhuman::storage", file, "[layout] credential file is not valid JSON; left in place");
+ continue;
+ }
+ files.push((file, secret, bytes));
+ }
+ if files.is_empty() {
+ return Ok(Vec::new());
+ }
+ if !crate::security::secret_storage::encrypted_file_backend::storage_master_key_resolvable() {
+ tracing::warn!(
+ target: "openhuman::storage",
+ "[layout] no master key to encrypt the credential files with; left in place"
+ );
+ return Ok(Vec::new());
+ }
+ let keys = storage::secrets::keys()
+ .map_err(|e| LayoutError::Other(anyhow::anyhow!("master key for credentials: {e}")))?;
+ let backend = super::legacy::open_v1(target).await?;
+ let scoped = backend
+ .for_scope(&storage::tenant_scope(None))
+ .map_err(|e| LayoutError::Other(anyhow::anyhow!("open the local scope: {e}")))?;
+ let secrets = storage::secrets::over(&scoped, keys);
+ let mut imported = Vec::new();
+ for (file, secret, bytes) in files {
+ let stored = secrets.get(secret).await.map_err(|e| {
+ LayoutError::Verify(format!("stored credential record for {file}: {e}"))
+ })?;
+ if stored.is_none() {
+ secrets
+ .set(secret, &bytes)
+ .await
+ .map_err(|e| LayoutError::Other(anyhow::anyhow!("store {file}: {e}")))?;
+ let back = secrets.get(secret).await.map_err(|e| {
+ LayoutError::Verify(format!("read back {file}: {e}"))
+ })?;
+ if back.as_deref().map(|b| b.as_slice()) != Some(bytes.as_slice()) {
+ return Err(LayoutError::Verify(format!(
+ "{file} did not read back identically; refusing to delete it"
+ )));
+ }
+ }
+ tracing::info!(target: "openhuman::storage", file, "[layout] credential file imported");
+ imported.push(file.to_owned());
+ }
+ drop(backend);
+ Ok(imported)
+}
+
+fn read(path: &Path) -> Result<zeroize::Zeroizing<Vec<u8>>, LayoutError> {
+ Ok(zeroize::Zeroizing::new(std::fs::read(path)?))
+}
+
+#[cfg(test)]
+#[path = "credentials_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/storage/layout/credentials_tests.rs b/crates/openhuman-core/src/storage/layout/credentials_tests.rs
new file mode 100644
index 0000000000..619ecd6925
--- /dev/null
+++ b/crates/openhuman-core/src/storage/layout/credentials_tests.rs
@@ -0,0 +1,153 @@
+use super::*;
+use crate::security::secret_storage::{
+ clear_master_key_source, install_master_key_source, MasterKeySource, SecretStorageError,
+};
+use crate::storage::layout::test_fixtures::{v1_profile, write, Fixture};
+use crate::storage::layout::{migrate, restore, Options, Outcome};
+use std::sync::Arc;
+use tinystoragedrivers::secrets::{DerivedKeys, SecretStore as _};
+use zeroize::Zeroizing;
+
+const PROFILES: &str = r#"{"schema_version":1,"profiles":{"openai:default":{"token":"enc2:abcdef"}}}"#;
+const HTTP: &str = r#"{"credentials":{"gh":{"token":"enc2:012345"}}}"#;
+
+/// A host key source holding one fixed key, so no key is ever minted.
+struct FixedKey;
+impl MasterKeySource for FixedKey {
+ fn load(&self) -> Result<Option<Zeroizing<[u8; 32]>>, SecretStorageError> {
+ Ok(Some(Zeroizing::new([0x42; 32])))
+ }
+ fn store(&self, _: &[u8; 32]) -> Result<(), SecretStorageError> {
+ Ok(())
+ }
+}
+
+fn with_credentials() -> Fixture {
+ let fx = v1_profile();
+ write(&fx.target.profile_dir.join(PROFILES_FILENAME), PROFILES);
+ write(&fx.target.profile_dir.join(STORE_FILENAME), HTTP);
+ fx
+}
+
+async fn run(fx: &Fixture) -> Result<Outcome, LayoutError> {
+ migrate(&fx.target, &fx.config, &Options::default()).await
+}
+
+/// The decrypted `local`-scope record `secret` in the profile's `storage.db`.
+async fn stored(fx: &Fixture, secret: &str) -> Option<Vec<u8>> {
+ let url = format!("sqlite:{}", fx.target.storage_db().display());
+ let backend = storage::open(&url).await.unwrap();
+ let scoped = backend.for_scope(&storage::tenant_scope(None)).unwrap();
+ let secrets = storage::secrets::over(&scoped, storage::secrets::keys().unwrap());
+ secrets.get(secret).await.unwrap().map(|b| b.to_vec())
+}
+
+// Current-thread runtime: the key source slot is thread-local in unit tests.
+#[tokio::test(flavor = "current_thread")]
+async fn a_migration_moves_the_credential_files_into_encrypted_secrets() {
+ install_master_key_source(Arc::new(FixedKey));
+ let fx = with_credentials();
+ let Outcome::Migrated(report) = run(&fx).await.unwrap() else {
+ panic!("expected a migration");
+ };
+ clear_master_key_source();
+ for (file, secret) in FILES {
+ assert!(
+ !fx.target.profile_dir.join(file).exists(),
+ "{file} is deleted once archived"
+ );
+ assert!(report.deleted.contains(&format!("{PROFILE_PREFIX}{file}")));
+ let expected = if file == PROFILES_FILENAME { PROFILES } else { HTTP };
+ assert_eq!(stored(&fx, secret).await.unwrap(), expected.as_bytes());
+ }
+ // storage.db never holds the plaintext
+ let db = std::fs::read(fx.target.storage_db()).unwrap();
+ assert!(!db.windows(11).any(|w| w == b"openai:defa"));
+ assert!(!db.windows(6).any(|w| w == b"\"gh\":{"));
+
+ // the archive keeps them and a restore puts them back beside config.toml
+ restore(&fx.target, &report.archive).await.unwrap();
+ assert_eq!(
+ std::fs::read_to_string(fx.target.profile_dir.join(PROFILES_FILENAME)).unwrap(),
+ PROFILES
+ );
+ assert_eq!(
+ std::fs::read_to_string(fx.target.profile_dir.join(STORE_FILENAME)).unwrap(),
+ HTTP
+ );
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn a_stored_record_under_another_key_stops_the_migration_and_keeps_the_files() {
+ install_master_key_source(Arc::new(FixedKey));
+ let fx = with_credentials();
+ let url = super::super::legacy::v1_url(&fx.target);
+ let backend = storage::open(&url).await.unwrap();
+ let scoped = backend.for_scope(&storage::tenant_scope(None)).unwrap();
+ let other = Arc::new(DerivedKeys::new(Zeroizing::new([0x99; 32])));
+ storage::secrets::over(&scoped, other)
+ .set(PROFILES_SECRET_NAME, b"{}")
+ .await
+ .unwrap();
+ drop(backend);
+ let error = run(&fx).await.unwrap_err();
+ clear_master_key_source();
+ assert!(matches!(error, LayoutError::Verify(_)), "{error}");
+ assert!(fx.target.profile_dir.join(PROFILES_FILENAME).exists());
+ assert!(fx.target.profile_dir.join(STORE_FILENAME).exists());
+ assert!(!fx.target.profile_dir.join(".layout").exists());
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn a_record_already_on_the_backend_wins_over_a_stale_file() {
+ install_master_key_source(Arc::new(FixedKey));
+ let fx = with_credentials();
+ let url = super::super::legacy::v1_url(&fx.target);
+ let backend = storage::open(&url).await.unwrap();
+ let scoped = backend.for_scope(&storage::tenant_scope(None)).unwrap();
+ storage::secrets::over(&scoped, storage::secrets::keys().unwrap())
+ .set(PROFILES_SECRET_NAME, br#"{"newer":true}"#)
+ .await
+ .unwrap();
+ drop(backend);
+ run(&fx).await.unwrap();
+ clear_master_key_source();
+ assert_eq!(
+ stored(&fx, PROFILES_SECRET_NAME).await.unwrap(),
+ br#"{"newer":true}"#
+ );
+ assert!(!fx.target.profile_dir.join(PROFILES_FILENAME).exists());
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn a_file_that_is_not_json_is_left_in_place() {
+ install_master_key_source(Arc::new(FixedKey));
+ let fx = v1_profile();
+ write(&fx.target.profile_dir.join(PROFILES_FILENAME), "not json");
+ write(&fx.target.profile_dir.join(STORE_FILENAME), HTTP);
+ run(&fx).await.unwrap();
+ clear_master_key_source();
+ assert_eq!(
+ std::fs::read_to_string(fx.target.profile_dir.join(PROFILES_FILENAME)).unwrap(),
+ "not json"
+ );
+ assert!(!fx.target.profile_dir.join(STORE_FILENAME).exists());
+}
+
+#[test]
+fn a_key_is_resolvable_only_from_a_source_that_does_not_mint() {
+ use crate::security::secret_storage::encrypted_file_backend::resolvable;
+ assert!(!resolvable(false, false, false, false));
+ assert!(resolvable(true, false, false, false));
+ assert!(resolvable(false, true, false, false));
+ assert!(resolvable(false, false, true, false));
+ assert!(resolvable(false, false, false, true));
+}
+
+#[test]
+fn the_secret_names_match_the_stores_that_read_them() {
+ assert_eq!(PROFILES_SECRET_NAME, "file:auth-profiles.json");
+ assert_eq!(STORAGE_SECRET_NAME, "file:http-credentials.json");
+ assert_eq!(PROFILES_FILENAME, "auth-profiles.json");
+ assert_eq!(STORE_FILENAME, "http-credentials.json");
+}
diff --git a/crates/openhuman-core/src/storage/layout/legacy.rs b/crates/openhuman-core/src/storage/layout/legacy.rs
index 05636337a0..c49f0cda35 100644
--- a/crates/openhuman-core/src/storage/layout/legacy.rs
+++ b/crates/openhuman-core/src/storage/layout/legacy.rs
@@ -59,7 +59,7 @@ pub fn v1_db(target: &Target) -> std::path::PathBuf {
.join("storage.db")
}
-async fn open_v1(target: &Target) -> Result<Arc<dyn StorageBackend>, LayoutError> {
+pub(super) async fn open_v1(target: &Target) -> Result<Arc<dyn StorageBackend>, LayoutError> {
let url = v1_url(target);
storage::open(&url)
.await
diff --git a/crates/openhuman-core/src/storage/layout/mod.rs b/crates/openhuman-core/src/storage/layout/mod.rs
index 2d37451858..1d8277c943 100644
--- a/crates/openhuman-core/src/storage/layout/mod.rs
+++ b/crates/openhuman-core/src/storage/layout/mod.rs
@@ -38,6 +38,7 @@
//! core before migrating from the CLI.
pub mod archive;
+pub mod credentials;
pub mod db;
pub mod legacy;
pub mod plan;
diff --git a/crates/openhuman-core/src/storage/layout/plan.rs b/crates/openhuman-core/src/storage/layout/plan.rs
index ae29c9255e..2d3b8cd7d1 100644
--- a/crates/openhuman-core/src/storage/layout/plan.rs
+++ b/crates/openhuman-core/src/storage/layout/plan.rs
@@ -227,6 +227,35 @@ fn push(entries: &mut Vec<Entry>, path: String, abs: &Path, action: Action, reas
});
}
+/// The profile-level entries (beside `config.toml`) the credential import
+/// copied into the database, named `@profile/<file>` and classified
+/// [`Action::Delete`]. Only `imported` files that still exist are listed.
+pub fn scan_credentials(profile_dir: &Path, imported: &[String]) -> Vec<Entry> {
+ let mut entries = Vec::new();
+ for name in imported {
+ let abs = profile_dir.join(name);
+ if std::fs::symlink_metadata(&abs).is_ok() {
+ push(
+ &mut entries,
+ format!("{}{name}", super::credentials::PROFILE_PREFIX),
+ &abs,
+ Action::Delete,
+ "imported into encrypted storage secrets",
+ );
+ }
+ }
+ entries
+}
+
+/// Where plan entry `rel` is on disk: below `workspace` for a workspace
+/// entry, below `profile_dir` for an `@profile/` entry.
+pub fn locate(workspace: &Path, profile_dir: &Path, rel: &str) -> (PathBuf, PathBuf) {
+ match rel.strip_prefix(super::credentials::PROFILE_PREFIX) {
+ Some(name) => (profile_dir.to_path_buf(), profile_dir.join(name)),
+ None => (workspace.to_path_buf(), join(workspace, rel)),
+ }
+}
+
/// The path of a plan entry below `base` (`workspace/` or `files/`).
pub fn join(base: &Path, rel: &str) -> PathBuf {
rel.split('/')
diff --git a/crates/openhuman-core/src/storage/layout/run.rs b/crates/openhuman-core/src/storage/layout/run.rs
index 16a6dcd7ef..f6a6d9da6f 100644
--- a/crates/openhuman-core/src/storage/layout/run.rs
+++ b/crates/openhuman-core/src/storage/layout/run.rs
@@ -112,10 +112,16 @@ pub async fn migrate(
match step {
Step::Import => {
legacy::import(target, config).await?;
+ state.credentials = super::credentials::import(target).await?;
}
Step::Migrate => {
legacy::migrate(target).await?;
- let scanned = plan::scan(&target.workspace())?;
+ let mut scanned = plan::scan(&target.workspace())?;
+ scanned.entries.extend(plan::scan_credentials(
+ &target.profile_dir,
+ &state.credentials,
+ ));
+ scanned.entries.sort_by(|a, b| a.path.cmp(&b.path));
state.plan = Some(scanned);
}
Step::CopyDb => {
@@ -189,7 +195,16 @@ fn dry_run(target: &Target, resuming: bool) -> Result<DryRun, LayoutError> {
let state = LayoutState::load(&target.profile_dir)?;
let scanned = match state.as_ref().and_then(|s| s.plan.clone()) {
Some(plan) => plan,
- None => plan::scan(&target.workspace())?,
+ None => {
+ let mut plan = plan::scan(&target.workspace())?;
+ // What the import step would copy into encrypted secrets.
+ let candidates: Vec<String> =
+ super::credentials::FILES.iter().map(|(f, _)| (*f).to_owned()).collect();
+ plan.entries
+ .extend(plan::scan_credentials(&target.profile_dir, &candidates));
+ plan.entries.sort_by(|a, b| a.path.cmp(&b.path));
+ plan
+ }
};
let database_bytes = std::fs::metadata(legacy::v1_db(target))
.ok()
@@ -277,7 +292,7 @@ async fn write_archive(
let at = if entry.action == Action::Move && std::fs::symlink_metadata(&moved).is_ok() {
moved
} else {
- plan::join(&workspace, &entry.path)
+ plan::locate(&workspace, &target.profile_dir, &entry.path).1
};
if std::fs::symlink_metadata(&at).is_ok() {
sources.push(Source {
@@ -329,7 +344,8 @@ fn finish(target: &Target, state: &LayoutState, plan: &Plan) -> Result<(), Layou
LayoutVersion::mark_v2(&target.profile_dir)?;
let workspace = target.workspace();
for entry in plan.with(Action::Delete) {
- remove_within(&workspace, &plan::join(&workspace, &entry.path))?;
+ let (base, path) = plan::locate(&workspace, &target.profile_dir, &entry.path);
+ remove_within(&base, &path)?;
}
// Directories the deletions emptied.
let memory = workspace.join("memory");
diff --git a/crates/openhuman-core/src/storage/layout/state.rs b/crates/openhuman-core/src/storage/layout/state.rs
index fd83fb308b..d7f4521298 100644
--- a/crates/openhuman-core/src/storage/layout/state.rs
+++ b/crates/openhuman-core/src/storage/layout/state.rs
@@ -140,6 +140,10 @@ pub struct LayoutState {
/// entries have moved.
#[serde(default)]
pub plan: Option<Plan>,
+ /// Credential files (beside `config.toml`) the import step copied into
+ /// the database; only these are ever archived and deleted.
+ #[serde(default)]
+ pub credentials: Vec<String>,
}
impl LayoutState {
@@ -154,6 +158,7 @@ impl LayoutState {
archive: format!("{}-{stamp}.tar.zst", sanitize(user)),
done: Vec::new(),
plan: None,
+ credentials: Vec::new(),
}
}