Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(admin): P1.4 user-management HTTP endpoints (root-gated)
AkitaOnRailsc2644622c96a
diff --git a/crates/ai-memory-cli/src/auth.rs b/crates/ai-memory-cli/src/auth.rsindex 63092664..c75d0e83 100644--- a/crates/ai-memory-cli/src/auth.rs+++ b/crates/ai-memory-cli/src/auth.rs@@ -44,7 +44,7 @@use std::sync::Arc;-use ai_memory_core::ActorContext;+use ai_memory_core::{ActorContext, AuthLevel};use ai_memory_store::{ReaderPool, TokenPepper, WriterHandle, hash_token};use axum::extract::State;use axum::http::{Method, Request, StatusCode, header};@@ -176,11 +176,12 @@ pub async fn require_bearer(mut req: Request<axum::body::Body>,next: Next,) -> Response {- // Rung 0: auth disabled. Inject anonymous actor (so downstream- // handlers that read Extension<ActorContext> always have one),- // then pass through.+ // Rung 0: auth disabled. Inject anonymous actor + anonymous+ // tier (so downstream handlers that read Extension<ActorContext>+ // and Extension<AuthLevel> always have one), then pass through.let Some(expected) = state.expected.as_deref() else {req.extensions_mut().insert(ActorContext::anonymous());+ req.extensions_mut().insert(AuthLevel::Anonymous);return next.run(req).await;};@@ -207,6 +208,7 @@ pub async fn require_bearer(// hook router / MCP server to overlay onto the actor.actor.agent = actor.agent.or(None);req.extensions_mut().insert(actor);+ req.extensions_mut().insert(AuthLevel::Root);// First successful Basic-auth hit (no cookie yet) → also stamp// the cookie so the user doesn't get the dialog again next@@ -239,6 +241,7 @@ pub async fn require_bearer(..ActorContext::default()};req.extensions_mut().insert(actor);+ req.extensions_mut().insert(AuthLevel::User);// Fire-and-forget last_seen_at bump. Errors are logged// but never block the response — middleware MUST staydiff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 10d20e6f..54ec594e 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -202,6 +202,12 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {db_path: store.db_path().to_path_buf(),bind: bind.clone(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: config+ .auth+ .token_pepper+ .as_ref()+ .filter(|p| !p.trim().is_empty())+ .map(|p| ai_memory_store::TokenPepper::new(p.clone())),});// Multi-rung auth assembly:// - rung 0 (no bearer_token configured) → AuthState::newdiff --git a/crates/ai-memory-core/src/actor.rs b/crates/ai-memory-core/src/actor.rsindex 082877e0..9ac39018 100644--- a/crates/ai-memory-core/src/actor.rs+++ b/crates/ai-memory-core/src/actor.rs@@ -85,6 +85,43 @@ pub struct ActorContext {pub client: Option<String>,}+/// Authorization tier the auth middleware resolved this request to.+///+/// Identity ([`ActorContext`]) carries *who* the request is from;+/// `AuthLevel` carries *what they're allowed to do*. The two are+/// distinct so a handler can guard on "must be root" without also+/// having to inspect or compare username strings against config.+///+/// Available as `Extension<AuthLevel>` on every request after the+/// auth middleware runs. Admin user-management endpoints+/// (`POST /admin/users`, expire / revive / rotate-token) check this+/// against [`AuthLevel::Root`] and return 403 for `User` /+/// 401 for `Anonymous`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum AuthLevel {+ /// Rung 0: no auth configured. Read-mostly setups; root-only+ /// routes refuse this tier (no root → no user management).+ Anonymous,+ /// Rung 1: authenticated as the configured root user.+ /// Allowed everywhere including user-management endpoints.+ Root,+ /// Rung 2: authenticated via the `users` table.+ /// Allowed on regular routes (write_page, query, etc.) but+ /// refused on the root-only admin user-management routes.+ User,+}++impl AuthLevel {+ /// `true` if this tier is allowed to perform user-management+ /// operations (currently just `Root`). Centralises the+ /// authorization check so handlers don't drift on what counts+ /// as "root-only".+ #[must_use]+ pub fn is_root(self) -> bool {+ matches!(self, AuthLevel::Root)+ }+}+impl ActorContext {/// `true` if at least one identity field is set.///diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex 37ce3407..35d8b97b 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -23,7 +23,7 @@ pub const DEFAULT_WORKSPACE_NAME: &str = "default";pub const DEFAULT_PROJECT_NAME: &str = "scratch";pub use active_project::ActiveProject;-pub use actor::ActorContext;+pub use actor::{ActorContext, AuthLevel};pub use error::{MemoryError, MemoryResult};pub use handoff::{Handoff, HandoffState, NewHandoff};pub use ids::{diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 02db1737..a1a34889 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -84,6 +84,13 @@ pub struct AdminState {/// handler so a second caller waits its turn (request stays open/// until the lock is acquired, then proceeds normally).pub bootstrap_lock: Arc<tokio::sync::Mutex<()>>,+ /// Per-server token pepper, used by the user-management endpoints+ /// (`POST /admin/users`, `…/rotate-token`) to hash freshly-issued+ /// tokens before they land in `users.token_hash`. `None` when the+ /// operator hasn't set `[auth].token_pepper` in config (single-user+ /// installs that predate v0.8); user-management endpoints then+ /// return 503 `multi-user not enabled`.+ pub token_pepper: Option<ai_memory_store::TokenPepper>,}/// JSON request body for `POST /admin/bootstrap`.@@ -149,6 +156,16 @@ pub fn admin_router(state: AdminState) -> Router {.route("/admin/purge-project", post(handle_purge_project)).route("/admin/rename-project", post(handle_rename_project)).route("/admin/write-page", post(handle_write_page))+ .route(+ "/admin/users",+ get(handle_list_users).post(handle_create_user),+ )+ .route("/admin/users/{username}/expire", post(handle_expire_user))+ .route("/admin/users/{username}/revive", post(handle_revive_user))+ .route(+ "/admin/users/{username}/rotate-token",+ post(handle_rotate_user_token),+ ).with_state(Arc::new(state))}@@ -1629,6 +1646,284 @@ async fn handle_write_page())}+// ---------------------------------------------------------------------+// user management (root-only)+// ---------------------------------------------------------------------++/// JSON request body for `POST /admin/users`.+#[derive(Debug, Deserialize)]+struct CreateUserRequest {+ username: String,+ #[serde(default)]+ name: Option<String>,+ #[serde(default)]+ email: Option<String>,+}++/// JSON response for `POST /admin/users` and `…/rotate-token`.+/// Carries the plaintext token EXACTLY once — the client (CLI or+/// admin browser) must surface it to the operator and never persist+/// it; only the SHA-256 digest is kept in the DB. Subsequent reads+/// (`GET /admin/users`) omit the token field entirely.+#[derive(Debug, Serialize)]+struct UserWithTokenResponse {+ user: ai_memory_core::User,+ token: String,+}++/// JSON response for `GET /admin/users` and lifecycle ops that don't+/// issue a new token (expire, revive).+#[derive(Debug, Serialize)]+struct UserResponse {+ user: ai_memory_core::User,+}++/// JSON response for `GET /admin/users`.+#[derive(Debug, Serialize)]+struct UserListResponse {+ users: Vec<ai_memory_core::User>,+}++/// Gate any handler in this section on a root-level request. Returns+/// the matching error response for the actor's tier (401 anonymous,+/// 403 user) or `Ok(())` for root.+fn require_root(+ level: ai_memory_core::AuthLevel,+) -> Result<(), (StatusCode, Json<serde_json::Value>)> {+ if level.is_root() {+ return Ok(());+ }+ let (code, msg) = match level {+ ai_memory_core::AuthLevel::Anonymous => (+ StatusCode::UNAUTHORIZED,+ "user management requires authentication",+ ),+ ai_memory_core::AuthLevel::User => (StatusCode::FORBIDDEN, "user management is root-only"),+ ai_memory_core::AuthLevel::Root => unreachable!("guarded above"),+ };+ Err((code, Json(serde_json::json!({ "error": msg }))))+}++/// Get the active token-pepper. Returns 503 when multi-user wasn't+/// configured — same shape as `/admin/embed` returns when no embedder+/// is wired.+fn require_pepper(+ state: &AdminState,+) -> Result<&ai_memory_store::TokenPepper, (StatusCode, Json<serde_json::Value>)> {+ state.token_pepper.as_ref().ok_or_else(|| {+ (+ StatusCode::SERVICE_UNAVAILABLE,+ Json(serde_json::json!({+ "error": "multi-user not enabled (set [auth].token_pepper in config or run `ai-memory init`)"+ })),+ )+ })+}++/// Handler for `POST /admin/users`.+///+/// Validates the input, generates a fresh 32-byte token, hashes it with+/// the per-server pepper, and inserts the row. Returns+/// `UserWithTokenResponse` so the caller can display the plaintext+/// token exactly once.+async fn handle_create_user(+ State(state): State<Arc<AdminState>>,+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,+ Json(req): Json<CreateUserRequest>,+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {+ require_root(level)?;+ let pepper = require_pepper(&state)?;++ let mut new_user = ai_memory_core::NewUser {+ username: req.username,+ name: req.name,+ email: req.email,+ };+ new_user+ .validate()+ .map_err(|e| validation_error(e.to_string()))?;++ let token = ai_memory_store::generate_token().map_err(|e| internal_err(e.to_string()))?;+ let token_hash = ai_memory_store::hash_token(&token, pepper);++ let user_id = state+ .writer+ .create_user(new_user.clone(), token_hash)+ .await+ .map_err(map_user_store_err)?;++ // Round-trip through the reader so we surface the same canonical+ // shape `GET /admin/users` returns (incl. created_at).+ let user = state+ .reader+ .find_user_by_id(user_id)+ .await+ .map_err(|e| internal_err(e.to_string()))?+ .ok_or_else(|| internal_err("created user vanished from store".to_string()))?;++ Ok((+ StatusCode::OK,+ Json(serde_json::to_value(UserWithTokenResponse { user, token }).unwrap_or_default()),+ ))+}++/// Handler for `GET /admin/users`. Includes users with expired tokens+/// (the response's `token_expired_at` field distinguishes them); the+/// CLI list renderer shows an "expired" flag.+async fn handle_list_users(+ State(state): State<Arc<AdminState>>,+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {+ require_root(level)?;+ let users = state+ .reader+ .list_users()+ .await+ .map_err(|e| internal_err(e.to_string()))?;+ Ok((+ StatusCode::OK,+ Json(serde_json::to_value(UserListResponse { users }).unwrap_or_default()),+ ))+}++/// Handler for `POST /admin/users/:username/expire`. Idempotent: the+/// first call stamps `token_expired_at = now()`, subsequent calls+/// leave the original timestamp untouched (via COALESCE in the store).+async fn handle_expire_user(+ State(state): State<Arc<AdminState>>,+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,+ axum::extract::Path(username): axum::extract::Path<String>,+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {+ require_root(level)?;+ let user = lookup_user_by_username(&state, &username).await?;+ state+ .writer+ .expire_user_token(user.id)+ .await+ .map_err(|e| internal_err(e.to_string()))?;+ // Re-read to surface the new token_expired_at in the response.+ let user = state+ .reader+ .find_user_by_id(user.id)+ .await+ .map_err(|e| internal_err(e.to_string()))?+ .ok_or_else(|| internal_err("user vanished after expire".to_string()))?;+ Ok((+ StatusCode::OK,+ Json(serde_json::to_value(UserResponse { user }).unwrap_or_default()),+ ))+}++/// Handler for `POST /admin/users/:username/revive`. Clears+/// `token_expired_at`. Idempotent (revive on an active user is a no-op).+async fn handle_revive_user(+ State(state): State<Arc<AdminState>>,+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,+ axum::extract::Path(username): axum::extract::Path<String>,+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {+ require_root(level)?;+ let user = lookup_user_by_username(&state, &username).await?;+ state+ .writer+ .revive_user_token(user.id)+ .await+ .map_err(|e| internal_err(e.to_string()))?;+ let user = state+ .reader+ .find_user_by_id(user.id)+ .await+ .map_err(|e| internal_err(e.to_string()))?+ .ok_or_else(|| internal_err("user vanished after revive".to_string()))?;+ Ok((+ StatusCode::OK,+ Json(serde_json::to_value(UserResponse { user }).unwrap_or_default()),+ ))+}++/// Handler for `POST /admin/users/:username/rotate-token`. Issues a+/// fresh token, hashes it with the server pepper, replaces the row's+/// `token_hash`, and implicitly clears `token_expired_at` (rotating+/// makes the new token usable immediately even if the prior one was+/// expired). Returns the plaintext token once.+async fn handle_rotate_user_token(+ State(state): State<Arc<AdminState>>,+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,+ axum::extract::Path(username): axum::extract::Path<String>,+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {+ require_root(level)?;+ let pepper = require_pepper(&state)?;+ let user = lookup_user_by_username(&state, &username).await?;++ let token = ai_memory_store::generate_token().map_err(|e| internal_err(e.to_string()))?;+ let token_hash = ai_memory_store::hash_token(&token, pepper);++ let updated = state+ .writer+ .rotate_user_token(user.id, token_hash)+ .await+ .map_err(|e| internal_err(e.to_string()))?;+ if !updated {+ return Err((+ StatusCode::NOT_FOUND,+ Json(serde_json::json!({ "error": "user vanished mid-rotation" })),+ ));+ }+ let user = state+ .reader+ .find_user_by_id(user.id)+ .await+ .map_err(|e| internal_err(e.to_string()))?+ .ok_or_else(|| internal_err("user vanished after rotate".to_string()))?;+ Ok((+ StatusCode::OK,+ Json(serde_json::to_value(UserWithTokenResponse { user, token }).unwrap_or_default()),+ ))+}++/// Shared lookup helper: 404 when the user doesn't exist, else returns+/// the row. Used by every per-username handler so error shapes stay+/// uniform across `expire` / `revive` / `rotate-token`.+async fn lookup_user_by_username(+ state: &AdminState,+ username: &str,+) -> Result<ai_memory_core::User, (StatusCode, Json<serde_json::Value>)> {+ let found = state+ .reader+ .find_user_by_username(username.to_string())+ .await+ .map_err(|e| internal_err(e.to_string()))?;+ found.ok_or_else(|| {+ (+ StatusCode::NOT_FOUND,+ Json(serde_json::json!({ "error": format!("no such user: {username}") })),+ )+ })+}++/// Convert a username/email validation error into a 400 response.+fn validation_error(msg: String) -> (StatusCode, Json<serde_json::Value>) {+ (+ StatusCode::BAD_REQUEST,+ Json(serde_json::json!({ "error": msg })),+ )+}++/// Map StoreError to the right HTTP status. UNIQUE violations on+/// username / email become 409; everything else is a 500.+fn map_user_store_err(e: ai_memory_store::StoreError) -> (StatusCode, Json<serde_json::Value>) {+ match e {+ ai_memory_store::StoreError::Duplicate(msg) => (+ StatusCode::CONFLICT,+ Json(serde_json::json!({ "error": msg })),+ ),+ ai_memory_store::StoreError::Memory(ai_memory_core::MemoryError::InvalidUsername(msg))+ | ai_memory_store::StoreError::Memory(ai_memory_core::MemoryError::InvalidEmail(msg)) => {+ validation_error(msg)+ }+ other => internal_err(other.to_string()),+ }+}+#[cfg(test)]mod tests {use super::*;@@ -1655,6 +1950,7 @@ mod tests {db_path: store.db_path().to_path_buf(),bind: "127.0.0.1:49374".to_string(),bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,});let resp = router@@ -1690,6 +1986,7 @@ mod tests {db_path: store.db_path().to_path_buf(),bind: "127.0.0.1:49374".to_string(),bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,});(tmp, router)}@@ -1799,4 +2096,341 @@ mod tests {assert_eq!(resp.status(), StatusCode::BAD_REQUEST);}++ // ── user-management endpoints (P1.4) ──────────────────────────++ /// Test router that has a token pepper configured (so user-management+ /// endpoints don't return 503), runs the standard auth middleware+ /// upstream so `Extension<AuthLevel>` is populated, and is reachable+ /// as Root via a fixed bearer token.+ fn user_admin_test_router(root_token: &'static str) -> (TempDir, Router) {+ 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 pepper = ai_memory_store::TokenPepper::new("test-pepper-admin");+ let router = admin_router(AdminState {+ writer: store.writer.clone(),+ reader: store.reader.clone(),+ wiki,+ llm: None,+ 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(),+ bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: Some(pepper),+ });+ // Wrap in a middleware that stamps the AuthLevel ourselves —+ // the real auth middleware lives in ai-memory-cli, and this+ // crate can't depend on it. The wrapper matches the Bearer+ // header against `root_token`: match → Root, present-but-no-+ // match → User (so we can test 403), absent → Anonymous.+ let router = router.layer(axum::middleware::from_fn(+ move |mut req: Request<Body>, next: axum::middleware::Next| async move {+ let bearer = req+ .headers()+ .get(axum::http::header::AUTHORIZATION)+ .and_then(|h| h.to_str().ok())+ .and_then(|s| s.strip_prefix("Bearer "))+ .map(str::to_string);+ let level = match bearer.as_deref() {+ Some(t) if t == root_token => ai_memory_core::AuthLevel::Root,+ Some(_) => ai_memory_core::AuthLevel::User,+ None => ai_memory_core::AuthLevel::Anonymous,+ };+ req.extensions_mut().insert(level);+ req.extensions_mut().insert(ActorContext::anonymous());+ next.run(req).await+ },+ ));+ (tmp, router)+ }++ async fn post_create_user(+ router: &Router,+ root_token: &str,+ body: serde_json::Value,+ ) -> axum::http::Response<Body> {+ router+ .clone()+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/admin/users")+ .header("content-type", "application/json")+ .header("authorization", format!("Bearer {root_token}"))+ .body(Body::from(serde_json::to_vec(&body).unwrap()))+ .unwrap(),+ )+ .await+ .unwrap()+ }++ #[tokio::test]+ async fn create_user_happy_path_returns_token_once() {+ let (_tmp, router) = user_admin_test_router("root-token");+ let resp = post_create_user(+ &router,+ "root-token",+ serde_json::json!({+ "username": "alice",+ "name": "Alice Smith",+ "email": "[email protected]"+ }),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::OK);+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(json["user"]["username"], "alice");+ // Email was normalised to lowercase by NewUser::validate.+ assert_eq!(json["user"]["email"], "[email protected]");+ assert_eq!(json["user"]["name"], "Alice Smith");+ // Plaintext token is surfaced exactly once — 43 chars (32 bytes+ // URL-safe-base64).+ let token = json["token"].as_str().unwrap();+ assert_eq!(token.len(), 43);+ }++ #[tokio::test]+ async fn create_user_rejects_duplicate_username_with_409() {+ let (_tmp, router) = user_admin_test_router("root-token");+ let _ = post_create_user(+ &router,+ "root-token",+ serde_json::json!({"username": "alice"}),+ )+ .await;+ let resp = post_create_user(+ &router,+ "root-token",+ serde_json::json!({"username": "alice"}),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::CONFLICT);+ }++ #[tokio::test]+ async fn create_user_rejects_invalid_email_with_400() {+ let (_tmp, router) = user_admin_test_router("root-token");+ let resp = post_create_user(+ &router,+ "root-token",+ serde_json::json!({"username": "alice", "email": "not-an-email"}),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);+ }++ #[tokio::test]+ async fn create_user_as_anonymous_returns_401() {+ let (_tmp, router) = user_admin_test_router("root-token");+ // No Authorization header → middleware stamps Anonymous tier.+ let resp = router+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/admin/users")+ .header("content-type", "application/json")+ .body(Body::from(+ serde_json::to_vec(&serde_json::json!({"username": "alice"})).unwrap(),+ ))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);+ }++ #[tokio::test]+ async fn create_user_as_user_tier_returns_403() {+ let (_tmp, router) = user_admin_test_router("root-token");+ let resp = post_create_user(+ &router,+ "not-the-root-token",+ serde_json::json!({"username": "alice"}),+ )+ .await;+ assert_eq!(resp.status(), StatusCode::FORBIDDEN);+ }++ #[tokio::test]+ async fn list_users_returns_added_users_in_insertion_order() {+ let (_tmp, router) = user_admin_test_router("root-token");+ for n in ["alice", "bob", "carol"] {+ let _ =+ post_create_user(&router, "root-token", serde_json::json!({"username": n})).await;+ }+ let resp = router+ .oneshot(+ Request::builder()+ .uri("/admin/users")+ .header("authorization", "Bearer root-token")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ let users = json["users"].as_array().unwrap();+ assert_eq!(users.len(), 3);+ assert_eq!(users[0]["username"], "alice");+ assert_eq!(users[1]["username"], "bob");+ assert_eq!(users[2]["username"], "carol");+ // Tokens are NEVER surfaced by the list endpoint.+ for u in users {+ assert!(u.get("token").is_none(), "list must not leak tokens");+ }+ }++ #[tokio::test]+ async fn expire_then_revive_round_trips() {+ let (_tmp, router) = user_admin_test_router("root-token");+ let _ = post_create_user(+ &router,+ "root-token",+ serde_json::json!({"username": "alice"}),+ )+ .await;++ // Expire.+ let resp = 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!(resp.status(), StatusCode::OK);+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert!(json["user"]["token_expired_at"].is_i64());++ // Revive.+ let resp = router+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/admin/users/alice/revive")+ .header("authorization", "Bearer root-token")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert!(json["user"]["token_expired_at"].is_null());+ }++ #[tokio::test]+ async fn expire_unknown_user_returns_404() {+ let (_tmp, router) = user_admin_test_router("root-token");+ let resp = router+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/admin/users/ghost/expire")+ .header("authorization", "Bearer root-token")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);+ }++ #[tokio::test]+ async fn rotate_token_issues_a_distinct_token() {+ let (_tmp, router) = user_admin_test_router("root-token");+ let create_resp = post_create_user(+ &router,+ "root-token",+ serde_json::json!({"username": "alice"}),+ )+ .await;+ let body = to_bytes(create_resp.into_body(), usize::MAX).await.unwrap();+ let original_token = serde_json::from_slice::<serde_json::Value>(&body).unwrap()["token"]+ .as_str()+ .unwrap()+ .to_string();++ let resp = router+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/admin/users/alice/rotate-token")+ .header("authorization", "Bearer root-token")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ let new_token = json["token"].as_str().unwrap();+ assert_eq!(new_token.len(), 43);+ assert_ne!(new_token, original_token, "rotate must change the token");+ }++ #[tokio::test]+ async fn create_user_returns_503_when_pepper_not_configured() {+ // Same as user_admin_test_router but with token_pepper = None,+ // covering the "rung 1-only" backward-compat install.+ 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 router = admin_router(AdminState {+ writer: store.writer.clone(),+ reader: store.reader.clone(),+ wiki,+ llm: None,+ 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(),+ bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,+ });+ // Inject a Root level so we're past the require_root gate;+ // the 503 must come from require_pepper.+ let router = router.layer(axum::middleware::from_fn(+ |mut req: Request<Body>, next: axum::middleware::Next| async move {+ req.extensions_mut().insert(ai_memory_core::AuthLevel::Root);+ req.extensions_mut().insert(ActorContext::anonymous());+ next.run(req).await+ },+ ));++ let resp = router+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/admin/users")+ .header("content-type", "application/json")+ .body(Body::from(+ serde_json::to_vec(&serde_json::json!({"username": "alice"})).unwrap(),+ ))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);+ let _ = tmp;+ }}diff --git a/crates/ai-memory-mcp/tests/admin_backup.rs b/crates/ai-memory-mcp/tests/admin_backup.rsindex 787ac431..39d29aca 100644--- a/crates/ai-memory-mcp/tests/admin_backup.rs+++ b/crates/ai-memory-mcp/tests/admin_backup.rs@@ -35,6 +35,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {db_path,bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,};(state, store)}diff --git a/crates/ai-memory-mcp/tests/admin_bootstrap.rs b/crates/ai-memory-mcp/tests/admin_bootstrap.rsindex 64894964..22edfbbf 100644--- a/crates/ai-memory-mcp/tests/admin_bootstrap.rs+++ b/crates/ai-memory-mcp/tests/admin_bootstrap.rs@@ -32,6 +32,7 @@ async fn make_admin_state(tmp: &TempDir) -> AdminState {db_path,bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,}}diff --git a/crates/ai-memory-mcp/tests/admin_phase3.rs b/crates/ai-memory-mcp/tests/admin_phase3.rsindex 0cf1a250..f8d56106 100644--- a/crates/ai-memory-mcp/tests/admin_phase3.rs+++ b/crates/ai-memory-mcp/tests/admin_phase3.rs@@ -43,6 +43,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {db_path,bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,};(state, store)}diff --git a/crates/ai-memory-mcp/tests/admin_purge.rs b/crates/ai-memory-mcp/tests/admin_purge.rsindex c84f7e38..8d27bbb9 100644--- a/crates/ai-memory-mcp/tests/admin_purge.rs+++ b/crates/ai-memory-mcp/tests/admin_purge.rs@@ -36,6 +36,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {data_dir: tmp.path().to_path_buf(),bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,db_path,};(state, store)@@ -348,6 +349,7 @@ async fn purge_project_idempotent_second_call_is_404() {db_path: store.db_path().to_path_buf(),bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,};seed_two_projects(&store, &state_a.wiki).await;diff --git a/crates/ai-memory-mcp/tests/admin_rename.rs b/crates/ai-memory-mcp/tests/admin_rename.rsindex 6d5d01fb..b4e3f4da 100644--- a/crates/ai-memory-mcp/tests/admin_rename.rs+++ b/crates/ai-memory-mcp/tests/admin_rename.rs@@ -34,6 +34,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {db_path,bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,};(state, store)}@@ -313,6 +314,7 @@ async fn rename_project_pages_still_searchable() {db_path: store.db_path().to_path_buf(),bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,};let rename_resp = post(diff --git a/crates/ai-memory-mcp/tests/admin_status_search.rs b/crates/ai-memory-mcp/tests/admin_status_search.rsindex e809f4ae..26f98a30 100644--- a/crates/ai-memory-mcp/tests/admin_status_search.rs+++ b/crates/ai-memory-mcp/tests/admin_status_search.rs@@ -29,6 +29,7 @@ async fn make_admin_state(tmp: &TempDir) -> (AdminState, Store) {db_path,bind: "127.0.0.1:49374".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,};(state, store)}diff --git a/crates/ai-memory-mcp/tests/admin_write_page.rs b/crates/ai-memory-mcp/tests/admin_write_page.rsindex 6f75541c..6b36ce79 100644--- a/crates/ai-memory-mcp/tests/admin_write_page.rs+++ b/crates/ai-memory-mcp/tests/admin_write_page.rs@@ -29,6 +29,7 @@ async fn make_state(tmp: &TempDir) -> AdminState {db_path,bind: "127.0.0.1:0".to_string(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,}}