Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(auth): preserve fresh-install admin access
AkitaOnRails91ae87909f82
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fa435077..68757971 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0via MCP `memory_handoff_accept`.### Changed+- `init`-generated token peppers no longer make operational `/admin/*` routes+ root-only before the first user is created. Admin mode now switches+ immediately and fail-closed from a store-backed user-row check; expired users+ still count. Servers refuse startup when user rows exist but either the+ non-empty `[auth].token_pepper` or static `[auth].bearer_token` is missing or+ blank, preventing accidental anonymous admin reopening ([#191]).- `install-hooks --agent devin` now infers the server URL and bearer token from`~/.devin/config.json` when flags and environment settings are absent, keepinghooks aligned with an existing Devin MCP registration.diff --git a/crates/ai-memory-cli/src/auth.rs b/crates/ai-memory-cli/src/auth.rsindex ef0234d3..b5136e10 100644--- a/crates/ai-memory-cli/src/auth.rs+++ b/crates/ai-memory-cli/src/auth.rs@@ -105,7 +105,10 @@ impl AuthState {#[must_use]pub fn new(expected: Option<String>) -> Self {Self {- expected,+ // A blank configured value must never turn an absent credential+ // into root authentication (`"" == ""`). Treat placeholders and+ // whitespace-only environment values as auth-disabled instead.+ expected: expected.filter(|token| !token.trim().is_empty()),..Self::default()}}@@ -693,6 +696,14 @@ mod tests {axum::Json(actor)}+ async fn echo_auth_level(Extension(level): Extension<AuthLevel>) -> &'static str {+ match level {+ AuthLevel::Anonymous => "anonymous",+ AuthLevel::Root => "root",+ AuthLevel::User => "user",+ }+ }+fn router_with_state(state: AuthState) -> Router {Router::new().route("/probe", get(echo_actor))@@ -954,6 +965,64 @@ mod tests {assert_eq!(actor.user.as_deref(), Some("root"));}+ #[tokio::test]+ async fn resolver_authenticates_user_added_after_router_construction() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let pepper = TokenPepper::new("test-pepper");+ let state = AuthState::new(Some("root-token".into())).with_multiuser(+ pepper.clone(),+ store.reader.clone(),+ store.writer.clone(),+ );+ let router = Router::new().route("/level", get(echo_auth_level)).layer(+ axum::middleware::from_fn_with_state(Arc::new(state), require_bearer),+ );++ let token = ai_memory_store::generate_token().unwrap();+ let mut user = NewUser {+ username: "alice".into(),+ name: None,+ email: None,+ };+ user.validate().unwrap();+ store+ .writer+ .create_user(user, ai_memory_store::hash_token(&token, &pepper))+ .await+ .unwrap();++ for (token, expected_status, expected_level) in [+ (token.as_str(), StatusCode::OK, Some("user")),+ ("root-token", StatusCode::OK, Some("root")),+ ("unknown-token", StatusCode::UNAUTHORIZED, None),+ ] {+ let response = router+ .clone()+ .oneshot(+ Request::builder()+ .uri("/level")+ .header("Authorization", format!("Bearer {token}"))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), expected_status, "token {token}");+ if let Some(expected_level) = expected_level {+ let body = axum::body::to_bytes(response.into_body(), 1024)+ .await+ .unwrap();+ assert_eq!(body.as_ref(), expected_level.as_bytes());+ }+ }+ }++ #[test]+ fn blank_root_token_is_not_enabled() {+ assert!(!AuthState::new(Some(" ".into())).enabled());+ }+#[tokio::test]async fn rung1_setup_with_unknown_bearer_returns_401() {// Existing single-user setup (rung 1 only, no multi-user). Andiff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex c91497d5..3ef3313e 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -41,7 +41,7 @@ use tracing::info;use crate::auth::{AuthState, require_bearer};use crate::cli::{ServeArgs, TransportKind};-use crate::config::{AutoImproveSettings, Config, MaintenanceSettings};+use crate::config::{AuthSettings, AutoImproveSettings, Config, MaintenanceSettings};/// 10 MB cap on inbound HTTP bodies. The /hook ingress accepts the/// agent's raw payload which can include a tool output excerpt@@ -56,6 +56,36 @@ const EMBEDDING_WRITE_BATCH: usize = 100;/// after client-side prune; keep hooks/MCP at [`MAX_BODY_BYTES`].const BOOTSTRAP_MAX_BODY_BYTES: usize = 32 * 1024 * 1024;+/// 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.+fn validate_existing_users_auth(users_exist: bool, auth: &AuthSettings) -> Result<()> {+ if !users_exist {+ return Ok(());+ }++ let pepper_present = auth+ .token_pepper+ .as_deref()+ .is_some_and(|value| !value.trim().is_empty());+ let bearer_present = auth+ .bearer_token+ .as_deref()+ .is_some_and(|value| !value.trim().is_empty());+ match (pepper_present, bearer_present) {+ (true, true) => Ok(()),+ (false, false) => anyhow::bail!(+ "users exist but [auth].token_pepper and [auth].bearer_token are missing or blank; restore both original secrets from configuration backup before serving"+ ),+ (false, true) => anyhow::bail!(+ "users exist but [auth].token_pepper is missing or blank; restore the original pepper from configuration backup before serving"+ ),+ (true, false) => anyhow::bail!(+ "users exist but [auth].bearer_token is missing or blank; configure the original static root bearer token before serving"+ ),+ }+}+struct ConsolidatorSetup {server: AiMemoryServer,consolidator: Option<Arc<Consolidator>>,@@ -95,6 +125,8 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {);}+ validate_existing_users_auth(store.reader.users_exist().await?, &config.auth)?;+// Run any outstanding wiki-structure migrations before the watcher starts// so file moves and renames are never raced by the reconciler.let wiki_root = config.data_dir.join("wiki");@@ -337,11 +369,10 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {// stays as-is, middleware injects anonymous actor.// - rung 1 (bearer_token set, no token_pepper) → root_actor// stamps writes with [auth].root_* identity.- // - rung 2 (bearer_token + token_pepper + users in DB) →- // unknown bearer routes through users-table lookup.- // The pepper is auto-generated by `ai-memory init`, so almost- // every operator-installed server reaches rung 2; the only- // rung-1-only setups are those whose config predates v0.8.+ // - token_pepper present → unknown bearers always route through+ // the users-table lookup, including before the first user is+ // created. Admin mode separately switches on a fresh+ // store-backed users-exist read.let mut auth_state = AuthState::new(config.auth.bearer_token.clone());let root_user = config.auth.root_username.clone();if root_user.as_deref().is_some_and(|s| !s.trim().is_empty()) {@@ -2016,6 +2047,37 @@ mod tests {use tempfile::TempDir;use tower::ServiceExt;+ #[test]+ fn existing_users_require_nonempty_pepper_and_root_bearer() {+ for users_exist in [false, true] {+ for (pepper_label, token_pepper) in [+ ("missing", None),+ ("blank", Some(" ")),+ ("present", Some("pepper")),+ ] {+ for (bearer_label, bearer_token) in [+ ("missing", None),+ ("blank", Some("\t")),+ ("present", Some("root-token")),+ ] {+ let auth = AuthSettings {+ token_pepper: token_pepper.map(str::to_string),+ bearer_token: bearer_token.map(str::to_string),+ ..AuthSettings::default()+ };+ let result = validate_existing_users_auth(users_exist, &auth);+ let should_pass =+ !users_exist || (pepper_label == "present" && bearer_label == "present");+ assert_eq!(+ result.is_ok(),+ should_pass,+ "users={users_exist}, pepper={pepper_label}, bearer={bearer_label}"+ );+ }+ }+ }+ }+struct PanicLlm;impl LlmProvider for PanicLlm {diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex d6776a37..f3a85898 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -308,9 +308,9 @@ pub struct AuthSettings {/// `users.token_hash` rows useless to an offline attacker./// Auto-generated by `ai-memory init` (32 bytes of OS CSPRNG,/// hex-encoded). MUST NOT change after the first user is added- /// — rotating it invalidates every existing token. Only used- /// when multi-user is enabled (at least one row in `users`);- /// rung-1 single-user setups don't read it.+ /// — rotating it invalidates every existing token. It enables DB-user+ /// token resolution even during first-user bootstrap; operational admin+ /// access becomes root-only once a user row exists.pub token_pepper: Option<String>,}diff --git a/crates/ai-memory-core/src/actor.rs b/crates/ai-memory-core/src/actor.rsindex 8f9253a1..5009715a 100644--- a/crates/ai-memory-core/src/actor.rs+++ b/crates/ai-memory-core/src/actor.rs@@ -170,10 +170,9 @@ impl AuthLevel {/// Check whether this auth tier can use `capability`.///- /// `multi_user_enabled` mirrors the configured `[auth].token_pepper` gate:- /// operational admin routes keep their historical single-user behavior- /// until multi-user mode is enabled, while user-management is always- /// root-only.+ /// `multi_user_enabled` is the store-backed presence of any user row:+ /// operational admin routes keep their historical bootstrap behavior until+ /// the first user is created, while user-management is always root-only.pub fn authorize(self,capability: Capability,diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 26c90232..9402ba6a 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -579,7 +579,23 @@ async fn require_root_for_multiuser_admin(.get::<ai_memory_core::AuthLevel>().copied().unwrap_or(ai_memory_core::AuthLevel::Anonymous);- match level.authorize(Capability::Admin, state.token_pepper.is_some()) {+ // Read this for every request rather than caching a post-creation flag: a+ // committed first user immediately closes bootstrap admin access, including+ // across concurrent requests and without a server restart.+ let multi_user_enabled = match state.reader.users_exist().await {+ Ok(exists) => exists,+ Err(error) => {+ tracing::error!(%error, "admin authorization could not determine whether users exist");+ return (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(serde_json::json!({+ "error": "admin authorization unavailable: could not verify user configuration"+ })),+ )+ .into_response();+ }+ };+ match level.authorize(Capability::Admin, multi_user_enabled) {Ok(()) => next.run(req).await,Err(e) => (authz_status(e),@@ -7241,6 +7257,12 @@ mod tests {#[tokio::test]async fn multiuser_admin_routes_reject_db_user_tier() {let (_tmp, router) = user_admin_test_router("root-token");+ post_create_user(+ &router,+ "root-token",+ serde_json::json!({"username": "alice"}),+ )+ .await;for (method, uri, payload) in admin_route_samples() {let mut builder = Request::builder()@@ -7269,6 +7291,12 @@ mod tests {#[tokio::test]async fn multiuser_admin_routes_reject_anonymous() {let (_tmp, router) = user_admin_test_router("root-token");+ post_create_user(+ &router,+ "root-token",+ serde_json::json!({"username": "alice"}),+ )+ .await;for (method, uri, payload) in admin_route_samples() {let mut builder = Request::builder().method(method).uri(uri);let body = if payload.is_null() {@@ -7306,6 +7334,124 @@ mod tests {assert_eq!(resp.status(), StatusCode::OK);}+ #[tokio::test]+ async fn admin_mode_switches_after_first_user_without_restart() {+ let (_tmp, router) = user_admin_test_router("root-token");++ let anonymous_before = router+ .clone()+ .oneshot(+ Request::builder()+ .uri("/admin/status")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(anonymous_before.status(), StatusCode::OK);++ let create = post_create_user(+ &router,+ "root-token",+ serde_json::json!({"username": "alice"}),+ )+ .await;+ assert_eq!(create.status(), StatusCode::OK);++ for (token, expected) in [+ (None, StatusCode::UNAUTHORIZED),+ (Some("db-user-token"), StatusCode::FORBIDDEN),+ (Some("root-token"), StatusCode::OK),+ ] {+ let mut request = Request::builder().uri("/admin/status");+ if let Some(token) = token {+ request = request.header("authorization", format!("Bearer {token}"));+ }+ let response = router+ .clone()+ .oneshot(request.body(Body::empty()).unwrap())+ .await+ .unwrap();+ assert_eq!(response.status(), expected, "token {token:?}");+ }++ let expire = router+ .clone()+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/admin/users/alice/expire")+ .header("authorization", "Bearer root-token")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(expire.status(), StatusCode::OK);++ let anonymous_after_expire = router+ .oneshot(+ Request::builder()+ .uri("/admin/status")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(anonymous_after_expire.status(), StatusCode::UNAUTHORIZED);+ }++ #[tokio::test]+ async fn admin_mode_store_read_failure_fails_closed() {+ use ai_memory_core::ActorContext;++ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let missing_db_reader =+ ai_memory_store::ReaderPool::new(&tmp.path().join("missing.sqlite"), 1).unwrap();+ let router = admin_router(AdminState {+ writer: store.writer.clone(),+ reader: missing_db_reader,+ wiki,+ llm: None,+ auto_improve_require_approval: false,+ auto_improve_review_config: Default::default(),+ embedder: None,+ provider_health: ProviderHealth::default(),+ decay_params: DecayParams::default(),+ data_dir: tmp.path().to_path_buf(),+ db_path: store.db_path().to_path_buf(),+ bind: "127.0.0.1:49374".to_string(),+ home_dir: None,+ bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: Some(ai_memory_store::TokenPepper::new("test-pepper-admin")),+ active_project: ai_memory_core::ActiveProject::new(),+ scope_invalidator: None,+ })+ .layer(axum::middleware::from_fn(+ |mut req: Request<Body>, next: axum::middleware::Next| async move {+ req.extensions_mut()+ .insert(ai_memory_core::AuthLevel::Anonymous);+ req.extensions_mut().insert(ActorContext::anonymous());+ next.run(req).await+ },+ ));++ let response = router+ .oneshot(+ Request::builder()+ .uri("/admin/status")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();+ assert!(String::from_utf8_lossy(&body).contains("could not verify user configuration"));+ }+#[tokio::test]async fn multiuser_workspace_admin_routes_reach_handler_for_root() {let (_tmp, router) = user_admin_test_router("root-token");diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex cdb33052..f200f33c 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -4327,6 +4327,16 @@ impl ReaderPool {pub async fn list_users(&self) -> StoreResult<Vec<User>> {self.with_conn(crate::users::list_users).await}++ /// Return whether any user row exists, including expired users. This cheap+ /// predicate is used at the admin authorization boundary to switch from+ /// bootstrap compatibility mode to root-only multi-user administration.+ ///+ /// # Errors+ /// Propagates any SQL or pool error so callers can fail closed.+ pub async fn users_exist(&self) -> StoreResult<bool> {+ self.with_conn(crate::users::users_exist).await+ }}/// Map a `(workspace, project, path, title, kind)` row to a [`HealthPage`].diff --git a/crates/ai-memory-store/src/users.rs b/crates/ai-memory-store/src/users.rsindex 51c5c8bf..3418f3a8 100644--- a/crates/ai-memory-store/src/users.rs+++ b/crates/ai-memory-store/src/users.rs@@ -288,6 +288,14 @@ pub fn list_users(conn: &Connection) -> StoreResult<Vec<User>> {Ok(rows)}+/// Return whether any user row exists, including users whose tokens have+/// expired. This is the multi-user admin-mode predicate, so it intentionally+/// does not filter on token activity or load user records.+pub fn users_exist(conn: &Connection) -> StoreResult<bool> {+ conn.query_row("SELECT EXISTS(SELECT 1 FROM users)", [], |row| row.get(0))+ .map_err(StoreError::from)+}+// ── helpers ────────────────────────────────────────────────────────fn row_to_user(row: &rusqlite::Row<'_>) -> rusqlite::Result<User> {@@ -619,6 +627,21 @@ mod tests {assert_eq!(usernames, vec!["alice", "bob", "carol"]);}+ #[test]+ fn users_exist_counts_expired_rows() {+ let conn = fresh_conn();+ assert!(!users_exist(&conn).unwrap());++ let p = pepper();+ let mut user = sample_new_user("alice");+ user.validate().unwrap();+ let id = insert_user(&conn, &user, &hash_token("token", &p)).unwrap();+ assert!(users_exist(&conn).unwrap());++ expire_user_token(&conn, id).unwrap();+ assert!(users_exist(&conn).unwrap());+ }+#[test]fn rotate_returns_false_for_unknown_user() {let conn = fresh_conn();diff --git a/docs/users.md b/docs/users.mdindex 26c4087c..667b188f 100644--- a/docs/users.md+++ b/docs/users.md@@ -11,8 +11,8 @@ there is no per-page RBAC, no per-user data scoping, no grouppermissions. What multi-user mode adds is *who-did-this*: every writeattributes to a named user, audit-log rows carry that identity, and theweb UI can show "Last edited by Alice Smith" instead of the anonymous-default. Every `/admin/*` endpoint stays root-only once multi-user mode-is configured, including read-only status/search/read-page helpers.+default. Every `/admin/*` endpoint stays root-only once at least one user+row exists, including read-only status/search/read-page helpers.If you run ai-memory alone, you can skip this page — your installkeeps working unchanged.@@ -31,10 +31,8 @@ You probably want multi-user mode when:You probably **don't** need it when:-- You're the sole human user of your install. Single-user mode- (`[auth].bearer_token` set, no `[auth].token_pepper`) is what- the project has shipped since v0.1 and continues to work- identically.+- You're the sole human user of your install. Single-user mode (no user rows)+ remains compatible whether or not `init` has generated `[auth].token_pepper`.- You need permissions / access control. v1 of ai-memory doesnot implement RBAC by design (see[`design-decisions.md`](design-decisions.md) §13). Attribution@@ -101,7 +99,14 @@ table useless to an offline attacker; an attacker with both theDB and the config has tokens at their disposal anyway, so thepepper's job is closed by the file-permission boundary.-Restart `ai-memory serve` for the changes to take effect.+`init` creates the pepper before any users exist. Until the first user is+added, operational admin endpoints retain single-user compatibility; creating+that first user switches them to root-only immediately, without a restart.+Expired user rows still keep admin mode root-only. If a database has users but+either the pepper or static root bearer is missing or blank, `serve` refuses+startup. Restore both original secrets from configuration backup (or set the+root bearer from the secret manager) rather than removing users; the root token+is required to administer the existing users.### 2. Add another user