Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(auth): reject restored API keys under a different pepper (#1495)
AkitaOnRailsd068c1bd9f30
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 12ae8ca6..376cd949 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,12 @@ version in [`docs/changelog/`](docs/changelog/):relay and wiki sync companions take the same `rustls-webpki` bump.### Fixed+- Bound native API-key hashes to their configured pepper with a persisted+ Argon2id verifier. A restored database with existing keys now refuses to+ serve under a different `[auth].token_pepper` instead of silently making+ every key return 401; pepper rotation remains allowed while no keys exist.+ ([#1495](https://github.com/akitaonrails/ai-memory/issues/1495))+- Defined `ai-memory backup` as an online data snapshot rather than a completehost image, documented the separately protected config, root credentials andraw ledgers a host move may require, and corrected the missing-token startupdiff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 2383101c..215963ca 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -313,6 +313,52 @@ fn validate_api_credential_pepper(api_credentials_exist: bool, auth: &AuthSettinOk(())}+/// Bind native API-key hashes to the pepper that produced them.+///+/// The Argon2id verifier travels with SQLite backups without storing the+/// pepper. A different pepper is safe to bind while no credentials exist;+/// once hashes exist, a mismatch means the restored database and config do+/// not belong together and serving would silently reject every key.+async fn validate_api_credential_pepper_binding(+ store: &Store,+ api_credentials_exist: bool,+ auth: &AuthSettings,+) -> Result<()> {+ validate_api_credential_pepper(api_credentials_exist, auth)?;+ let Some(pepper) = auth+ .token_pepper+ .as_deref()+ .filter(|value| !value.trim().is_empty())+ else {+ return Ok(());+ };++ if let Some(verifier) = store.reader.api_credential_pepper_verifier().await? {+ let matches = ai_memory_store::password::verify_password(pepper.to_owned(), verifier)+ .await+ .context("verifying the configured API credential pepper")?;+ if matches {+ return Ok(());+ }+ if api_credentials_exist {+ anyhow::bail!(+ "[auth].token_pepper does not match the pepper that hashed the restored API \+ credentials; restore the original external config or token_pepper before \+ serving (ai-memory backup does not archive config files outside the data dir)"+ );+ }+ }++ let verifier = ai_memory_store::password::hash_password(pepper.to_owned())+ .await+ .context("binding the configured API credential pepper")?;+ store+ .writer+ .set_api_credential_pepper_verifier(verifier)+ .await?;+ Ok(())+}+/// Validate the credentials that keep an existing multi-user installation/// closed. Bootstrap installs have no user rows yet and retain their historical/// compatibility behavior regardless of placeholder auth values.@@ -1225,7 +1271,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {}let api_credentials_exist = store.reader.api_credentials_exist().await?;- validate_api_credential_pepper(api_credentials_exist, &config.auth)?;+ validate_api_credential_pepper_binding(&store, api_credentials_exist, &config.auth).await?;let bootstrap_completed_before_start = store.reader.bootstrap_completed().await?;validate_configured_secret_collisions(&store, &config.auth, !bootstrap_completed_before_start).await?;@@ -3701,6 +3747,50 @@ mod tests {assert!(validate_api_credential_pepper(false, &missing).is_ok());}+ #[tokio::test]+ async fn api_key_pepper_binding_refuses_a_mismatch_once_credentials_exist() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let original = AuthSettings {+ token_pepper: Some("original-pepper-with-enough-entropy".into()),+ ..AuthSettings::default()+ };+ let replacement = AuthSettings {+ token_pepper: Some("replacement-pepper-with-enough-entropy".into()),+ ..AuthSettings::default()+ };++ validate_api_credential_pepper_binding(&store, false, &original)+ .await+ .unwrap();+ assert!(+ store+ .reader+ .api_credential_pepper_verifier()+ .await+ .unwrap()+ .is_some()+ );+ validate_api_credential_pepper_binding(&store, true, &original)+ .await+ .unwrap();++ let mismatch = validate_api_credential_pepper_binding(&store, true, &replacement)+ .await+ .unwrap_err();+ assert!(+ mismatch.to_string().contains("does not match"),+ "unexpected error: {mismatch:#}"+ );++ validate_api_credential_pepper_binding(&store, false, &replacement)+ .await+ .unwrap();+ validate_api_credential_pepper_binding(&store, true, &replacement)+ .await+ .unwrap();+ }+#[test]fn unauthenticated_non_loopback_http_requires_explicit_override() {let addresses = [diff --git a/crates/ai-memory-store/migrations/V84__api_credential_pepper_verifier.sql b/crates/ai-memory-store/migrations/V84__api_credential_pepper_verifier.sqlnew file mode 100644index 00000000..3d8b884c--- /dev/null+++ b/crates/ai-memory-store/migrations/V84__api_credential_pepper_verifier.sql@@ -0,0 +1,10 @@+-- Bind native API credential hashes to the config pepper that produced them.+-- The verifier is an Argon2id PHC string, not the pepper itself. Startup may+-- replace it only while api_credentials is empty; with any credential present,+-- a mismatch means a restored database and config do not belong together.++CREATE TABLE api_credential_pepper_state (+ singleton INTEGER NOT NULL PRIMARY KEY CHECK (singleton = 1),+ verifier TEXT NOT NULL,+ updated_at INTEGER NOT NULL+);diff --git a/crates/ai-memory-store/src/api_credentials.rs b/crates/ai-memory-store/src/api_credentials.rsindex 8b99ecde..bc7048fa 100644--- a/crates/ai-memory-store/src/api_credentials.rs+++ b/crates/ai-memory-store/src/api_credentials.rs@@ -260,6 +260,41 @@ pub fn api_credentials_exist(conn: &Connection) -> StoreResult<bool> {.map_err(StoreError::from)}+/// Return the Argon2id verifier bound to the native-key pepper, when one has+/// been recorded.+///+/// # Errors+/// SQL failures.+pub fn api_credential_pepper_verifier(conn: &Connection) -> StoreResult<Option<String>> {+ conn.query_row(+ "SELECT verifier FROM api_credential_pepper_state WHERE singleton = 1",+ [],+ |row| row.get(0),+ )+ .optional()+ .map_err(StoreError::from)+}++/// Insert or replace the verifier for the configured native-key pepper.+///+/// The caller decides whether replacement is allowed after checking whether+/// any credentials exist. Keeping that policy above this storage primitive+/// lets startup perform the expensive Argon2id verification off the writer+/// thread.+///+/// # Errors+/// SQL failures.+pub fn set_api_credential_pepper_verifier(conn: &Connection, verifier: &str) -> StoreResult<()> {+ conn.execute(+ "INSERT INTO api_credential_pepper_state (singleton, verifier, updated_at) \+ VALUES (1, ?1, ?2) \+ ON CONFLICT(singleton) DO UPDATE SET \+ verifier = excluded.verifier, updated_at = excluded.updated_at",+ params![verifier, Timestamp::now().as_microsecond()],+ )?;+ Ok(())+}+fn row_to_credential(row: &rusqlite::Row<'_>) -> rusqlite::Result<ApiCredential> {let id_bytes: Vec<u8> = row.get(0)?;let id = ApiCredentialId::from_slice(&id_bytes).map_err(|e| {@@ -433,7 +468,7 @@ mod tests {|row| row.get(0),).unwrap();- assert_eq!(version, 83, "update the pin when adding a migration");+ assert_eq!(version, 84, "update the pin when adding a migration");let cols: i64 = conn.query_row("SELECT COUNT(*) FROM pragma_table_info('users') \diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 7f79285d..4e96e9de 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -11774,6 +11774,15 @@ impl ReaderPool {.await}+ /// Argon2id verifier for the pepper that hashes native API credentials.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn api_credential_pepper_verifier(&self) -> StoreResult<Option<String>> {+ self.with_conn(crate::api_credentials::api_credential_pepper_verifier)+ .await+ }+/// True when any credential (active or revoked) stores this hash.////// # Errorsdiff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 0e5834e4..d56783c7 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -719,6 +719,10 @@ pub(crate) enum WriteCmd {id: ApiCredentialId,reply: oneshot::Sender<StoreResult<bool>>,},+ SetApiCredentialPepperVerifier {+ verifier: String,+ reply: oneshot::Sender<StoreResult<()>>,+ },TouchUserLastSeen {user_id: UserId,reply: oneshot::Sender<StoreResult<bool>>,@@ -3237,6 +3241,20 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Record the Argon2id verifier for the configured native-key pepper.+ ///+ /// # Errors+ /// Writer closed / SQL.+ pub async fn set_api_credential_pepper_verifier(&self, verifier: String) -> StoreResult<()> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::SetApiCredentialPepperVerifier {+ verifier,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+/// Update `last_seen_at = now()` for the user. Called fire-and-forget/// by the auth middleware on every authenticated request. Returns/// `false` when the user doesn't exist (caller authenticated against@@ -4765,6 +4783,10 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {let result = api_credentials::touch_api_credential(&conn, id);send_or_warn(reply, result, "touch_api_credential");}+ WriteCmd::SetApiCredentialPepperVerifier { verifier, reply } => {+ let result = api_credentials::set_api_credential_pepper_verifier(&conn, &verifier);+ send_or_warn(reply, result, "set_api_credential_pepper_verifier");+ }WriteCmd::TouchUserLastSeen { user_id, reply } => {let result = users::touch_user_last_seen(&conn, user_id);send_or_warn(reply, result, "touch_user_last_seen");diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex f4a661b5..962066ce 100644--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@ -1162,6 +1162,13 @@ and credentials match the new host. Treat both the ordinary snapshot and theseparate material as sensitive: wiki content and SQLite can contain privatesession data even though the archive excludes bearer files.+Current databases carry an Argon2id verifier for the API-key pepper. If a+restored database contains native API credentials but the destination loads a+different pepper, `serve` refuses instead of starting with keys that can never+authenticate. A database first opened by a version that predates this verifier+cannot prove which pepper created its existing hashes; for those older+snapshots, restoring the original external config remains mandatory.+Restoring a backup follows the inverse:```bashdiff --git a/docs/users.md b/docs/users.mdindex 7c53e4f3..44de5870 100644--- a/docs/users.md+++ b/docs/users.md@@ -419,8 +419,13 @@ passwords and sessions do not use it.sessions can operate without a machine-root bearer; native API-key lookupstill requires the original pepper. If `api_credentials` contains rows andthe pepper is missing or blank, `serve` refuses startup before applying-human bootstrap. Restore the original pepper from configuration backup-rather than deleting identities or keys.+human bootstrap. Current databases also keep an Argon2id verifier and refuse+a different pepper instead of starting with keys that can only return 401.+Restore the original pepper from a separately protected configuration backup+rather than deleting identities or keys: `ai-memory backup` includes only a+`config.toml` inside the data dir, while packaged systemd units load one from+outside it. Snapshots created before the verifier existed cannot be checked+and still require the original config.### 2. Add another human