Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix: harden multi-user admin auth boundaries

AkitaOnRailsab477d5657ee
diff --git a/AGENTS.md b/AGENTS.md
index 04271b49..ffca4de2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -102,6 +102,10 @@ without disturbing the rest of the file.
search, embed, retention, and destructive paths must use no-create lookups
and fail closed on partial or missing scope; only explicit write/create
paths may create workspaces or projects.
+- Preserve auth boundaries at shared router/helper boundaries. In multi-user
+ mode, every `/admin/*` route is root-only; DB-user tokens are for normal
+ MCP/API read/write attribution and must not bypass admin gates or admission
+ webhooks.
- Prefer explicit fallbacks over `unwrap`, `expect`, or `unreachable!` in
runtime paths. Panics are acceptable in tests only.
- Do not use `unsafe` for performance work in this project unless profiling
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b7711577..3fe08f65 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+- Multi-user admin authorization is now enforced at the shared `/admin/*`
+ router boundary, including user-management routes, so DB-user tokens can use
+ normal MCP/API read-write surfaces for attribution but cannot reach any admin
+ endpoint. Added regression coverage for every admin route plus DB-user write
+ attribution.
+
## [1.0.4] - 2026-06-14
### Added
- `install-hooks --agent grok` (plus `setup-agent` / `uninstall` coverage) for
diff --git a/README.md b/README.md
index aeffa039..86d695e2 100644
--- a/README.md
+++ b/README.md
@@ -345,9 +345,8 @@ created via `ai-memory user add` get their own tokens that resolve to
their identity in audit logs (and, in subsequent milestones, page
frontmatter + the web UI). Data stays single-tenant — there is no
per-page RBAC — but once `[auth].token_pepper` enables multi-user
-mode, operational `/admin/*` endpoints such as backup, checkpoints,
-restore-page, purge, move, embed, and commit require the root token.
-Existing single-user installs
+mode, every `/admin/*` endpoint requires the root token, including
+status/search/read-page and user-management routes. Existing single-user installs
are not affected unless you opt in by setting `[auth].token_pepper`
(auto-generated for new installs by `ai-memory init`). See
[`docs/users.md`](docs/users.md) for the full walkthrough and the
diff --git a/crates/ai-memory-core/src/actor.rs b/crates/ai-memory-core/src/actor.rs
index 9ac39018..c7c5be40 100644
--- a/crates/ai-memory-core/src/actor.rs
+++ b/crates/ai-memory-core/src/actor.rs
@@ -93,10 +93,10 @@ pub struct ActorContext {
/// 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`.
+/// auth middleware runs. In multi-user mode every `/admin/*` route
+/// checks this against [`AuthLevel::Root`] and returns 403 for
+/// `User` / 401 for `Anonymous`; normal DB users are allowed on the
+/// MCP and read-only API surfaces where writes are attributed to them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthLevel {
/// Rung 0: no auth configured. Read-mostly setups; root-only
@@ -107,12 +107,12 @@ pub enum AuthLevel {
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.
+ /// refused on root-only admin routes.
User,
}
impl AuthLevel {
- /// `true` if this tier is allowed to perform user-management
+ /// `true` if this tier is allowed to perform root-only admin
/// operations (currently just `Root`). Centralises the
/// authorization check so handlers don't drift on what counts
/// as "root-only".
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 9d86d6ad..8b2a5c16 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -19,6 +19,7 @@
//! (copy latest pages via the write path, then purge the source).
//! - `POST /admin/write-page` — write or update a wiki page atomically.
//! - `GET /admin/read-page` — fetch the full body of a single wiki page by path.
+//! - `POST /admin/delete-page` — delete a single wiki page by path.
//!
//! The CLI is responsible for filesystem access (collecting sources from
//! the project repo, rendering output for humans); the server is
@@ -164,6 +165,8 @@ fn default_chunk_input_tokens() -> usize {
/// - `POST /admin/rename-project`
/// - `POST /admin/move-project`
/// - `POST /admin/write-page`
+/// - `POST /admin/delete-page`
+/// - user-management routes under `/admin/users*`
pub fn admin_router(state: AdminState) -> Router {
let state = Arc::new(state);
let operational = Router::new()
@@ -183,11 +186,7 @@ pub fn admin_router(state: AdminState) -> Router {
.route("/admin/rename-project", post(handle_rename_project))
.route("/admin/move-project", post(handle_move_project))
.route("/admin/write-page", post(handle_write_page))
- .route("/admin/delete-page", post(handle_delete_page))
- .route_layer(axum::middleware::from_fn_with_state(
- state.clone(),
- require_root_for_multiuser_admin,
- ));
+ .route("/admin/delete-page", post(handle_delete_page));
let users = Router::new()
.route(
"/admin/users",
@@ -199,7 +198,13 @@ pub fn admin_router(state: AdminState) -> Router {
"/admin/users/{username}/rotate-token",
post(handle_rotate_user_token),
);
- operational.merge(users).with_state(state)
+ operational
+ .merge(users)
+ .route_layer(axum::middleware::from_fn_with_state(
+ state.clone(),
+ require_root_for_multiuser_admin,
+ ))
+ .with_state(state)
}
async fn require_root_for_multiuser_admin(
@@ -227,7 +232,7 @@ async fn require_root_for_multiuser_admin(
StatusCode::FORBIDDEN,
"admin operation is root-only in multi-user mode",
),
- ai_memory_core::AuthLevel::Root => unreachable!("guarded above"),
+ ai_memory_core::AuthLevel::Root => return next.run(req).await,
};
(code, Json(serde_json::json!({ "error": msg }))).into_response()
}
@@ -3068,7 +3073,7 @@ fn require_root(
"user management requires authentication",
),
ai_memory_core::AuthLevel::User => (StatusCode::FORBIDDEN, "user management is root-only"),
- ai_memory_core::AuthLevel::Root => unreachable!("guarded above"),
+ ai_memory_core::AuthLevel::Root => return Ok(()),
};
Err((code, Json(serde_json::json!({ "error": msg }))))
}
@@ -3649,10 +3654,8 @@ mod tests {
.unwrap()
}
- #[tokio::test]
- async fn multiuser_operational_admin_routes_reject_db_user_tier() {
- let (_tmp, router) = user_admin_test_router("root-token");
- let routes = [
+ fn admin_route_samples() -> Vec<(&'static str, &'static str, serde_json::Value)> {
+ vec![
("POST", "/admin/backup", serde_json::Value::Null),
(
"POST",
@@ -3742,9 +3745,27 @@ mod tests {
"path": "notes/x.md"
}),
),
- ];
+ ("GET", "/admin/users", serde_json::Value::Null),
+ (
+ "POST",
+ "/admin/users",
+ serde_json::json!({"username": "alice"}),
+ ),
+ ("POST", "/admin/users/alice/expire", serde_json::Value::Null),
+ ("POST", "/admin/users/alice/revive", serde_json::Value::Null),
+ (
+ "POST",
+ "/admin/users/alice/rotate-token",
+ serde_json::Value::Null,
+ ),
+ ]
+ }
- for (method, uri, payload) in routes {
+ #[tokio::test]
+ async fn multiuser_admin_routes_reject_db_user_tier() {
+ let (_tmp, router) = user_admin_test_router("root-token");
+
+ for (method, uri, payload) in admin_route_samples() {
let mut builder = Request::builder()
.method(method)
.uri(uri)
@@ -3763,24 +3784,33 @@ mod tests {
assert_eq!(
resp.status(),
StatusCode::FORBIDDEN,
- "{method} {uri} must be root-only in multi-user mode"
+ "{method} {uri} must be root-only for DB users in multi-user mode"
);
}
}
#[tokio::test]
- async fn multiuser_operational_admin_routes_reject_anonymous() {
+ async fn multiuser_admin_routes_reject_anonymous() {
let (_tmp, router) = user_admin_test_router("root-token");
- let resp = router
- .oneshot(
- Request::builder()
- .uri("/admin/status")
- .body(Body::empty())
- .unwrap(),
- )
- .await
- .unwrap();
- assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+ for (method, uri, payload) in admin_route_samples() {
+ let mut builder = Request::builder().method(method).uri(uri);
+ let body = if payload.is_null() {
+ Body::empty()
+ } else {
+ builder = builder.header("content-type", "application/json");
+ Body::from(serde_json::to_vec(&payload).unwrap())
+ };
+ let resp = router
+ .clone()
+ .oneshot(builder.body(body).unwrap())
+ .await
+ .unwrap();
+ assert_eq!(
+ resp.status(),
+ StatusCode::UNAUTHORIZED,
+ "{method} {uri} must require authentication in multi-user mode"
+ );
+ }
}
#[tokio::test]
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 52651345..0cd0d22f 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -1956,7 +1956,10 @@ fn test_parts_default() -> axum::http::request::Parts {
#[cfg(test)]
mod tests {
use super::*;
- use ai_memory_core::{NewObservation, NewPage, NewSession, ObservationKind, PagePath, Tier};
+ use ai_memory_core::{
+ ActorContext, AuthLevel, NewObservation, NewPage, NewSession, NewUser, ObservationKind,
+ PagePath, Tier,
+ };
use ai_memory_store::Store;
use ai_memory_wiki::{Wiki, WritePageRequest};
use tempfile::TempDir;
@@ -3209,6 +3212,77 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn memory_write_page_as_db_user_records_author() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let token = ai_memory_store::generate_token().unwrap();
+ let pepper = ai_memory_store::TokenPepper::new("test-pepper-author");
+ let token_hash = ai_memory_store::hash_token(&token, &pepper);
+ let user_id = store
+ .writer
+ .create_user(
+ NewUser {
+ username: "alice".into(),
+ name: Some("Alice Smith".into()),
+ email: Some("[email protected]".into()),
+ },
+ token_hash,
+ )
+ .await
+ .unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
+ .with_wiki(wiki);
+ let mut parts = test_parts_default();
+ parts.extensions.insert(AuthLevel::User);
+ parts.extensions.insert(user_id);
+ parts.extensions.insert(ActorContext {
+ user: Some("alice".into()),
+ name: Some("Alice Smith".into()),
+ email: Some("[email protected]".into()),
+ ..ActorContext::default()
+ });
+
+ server
+ .memory_write_page(
+ Parameters(WritePageArgs {
+ path: "notes/user-attributed.md".into(),
+ body: "# User Attributed\n\nWritten by a normal DB user.".into(),
+ title: None,
+ tier: Some("semantic".into()),
+ tags: vec![],
+ pinned: false,
+ project: None,
+ workspace: None,
+ }),
+ rmcp::handler::server::tool::Extension(parts),
+ )
+ .await
+ .unwrap();
+
+ let meta = store
+ .reader
+ .page_meta("default", "scratch", "notes/user-attributed.md")
+ .await
+ .unwrap()
+ .expect("written page should have metadata");
+ let author = meta.author.expect("DB user write should carry author");
+ assert_eq!(author.username, "alice");
+ assert_eq!(author.name.as_deref(), Some("Alice Smith"));
+ assert_eq!(author.email.as_deref(), Some("[email protected]"));
+ }
+
#[tokio::test]
async fn memory_read_page_unknown_explicit_project_does_not_fallback() {
let tmp = TempDir::new().unwrap();
diff --git a/docs/users.md b/docs/users.md
index 3202e661..d2679429 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 group
permissions. What multi-user mode adds is *who-did-this*: every write
attributes to a named user, audit-log rows carry that identity, and the
web UI can show "Last edited by Alice Smith" instead of the anonymous
-default. Operational `/admin/*` endpoints stay root-only once
-multi-user mode is configured.
+default. Every `/admin/*` endpoint stays root-only once multi-user mode
+is configured, including read-only status/search/read-page helpers.
If you run ai-memory alone, you can skip this page — your install
keeps working unchanged.
@@ -49,7 +49,7 @@ Every HTTP request is resolved to one of four authentication tiers:
|---|---|---|
| **0 — Anonymous** | No `[auth].bearer_token` set. | Allowed, no identity. Same as pre-multi-user defaults. |
| **1 — Root** | Bearer matches `[auth].bearer_token`. | Allowed as **root**. When `[auth].root_username` is set, writes attribute to that name; otherwise attribution stays anonymous. |
-| **2 — DB user** | Bearer doesn't match root, matches a `users.token_hash` row (via SHA-256 of token + `[auth].token_pepper`). | Allowed as **that user** for normal read/write APIs. Operational `/admin/*` endpoints are root-only in multi-user mode. The audit log records the username/email/name. |
+| **2 — DB user** | Bearer doesn't match root, matches a `users.token_hash` row (via SHA-256 of token + `[auth].token_pepper`). | Allowed as **that user** for normal read/write APIs. All `/admin/*` endpoints are root-only in multi-user mode. The audit log records the username/email/name. |
| **3 — 401** | Bearer present but matches nothing. | Rejected. Closes the bypass — unknown bearers can't slip through as anonymous. |
The rungs are sticky: a request is matched at the lowest tier that
@@ -172,10 +172,10 @@ If you're upgrading from a pre-v0.8 ai-memory:
user-management endpoints return **503** with a clear
`multi-user not enabled` message. Existing installs never trip
this because they never call `user add`.
-- Operational `/admin/*` endpoints are open to the configured bearer
- token in single-user mode, matching historical behavior. After you
- configure `[auth].token_pepper`, those endpoints require the root
- token; DB-user tokens receive **403**.
+- `/admin/*` endpoints are open to the configured bearer token in
+ single-user mode, matching historical behavior. After you configure
+ `[auth].token_pepper`, every admin endpoint requires the root token;
+ DB-user tokens receive **403** and anonymous requests receive **401**.
### Migrating an existing single-user install
@@ -228,7 +228,7 @@ See `crates/ai-memory-store/src/users.rs` for the full rationale.
| Surface | Status |
|---|---|
| Auth middleware injects `Extension<ActorContext>` on every request | ✓ P1.3 |
-| Admin user-management routes gate on `Extension<AuthLevel>::Root` | ✓ P1.4 |
+| All `/admin/*` routes gate on `Extension<AuthLevel>::Root` in multi-user mode | ✓ P1.4 |
| `ai-memory user add/list/expire/revive/rotate-token` CLI | ✓ P1.5 |
| `pages.author_id` populated, frontmatter `last_modified_by` block | ✓ P1.6 |
| `/api/v1` page responses include `author: { username, name?, email? }` | ✓ P1.7 |
@@ -275,16 +275,16 @@ the bearer authenticates, attribution flows from the token's owner
## Limitations
- **No per-page RBAC.** Every authenticated user sees every page in
- the workspace. Operational `/admin/*` endpoints are still root-only
- in multi-user mode. If you need data isolation, run separate
+ the workspace. All `/admin/*` endpoints are still root-only in
+ multi-user mode. If you need data isolation, run separate
ai-memory servers (per-user data dirs) and front them with a reverse
proxy.
- **One token per user.** Rotation issues a new token and
invalidates the old in the same transaction. There's no
notion of multiple device-bound tokens per user.
- **Root token is single.** `[auth].bearer_token` is the admin token
- for operational `/admin/*` endpoints. DB users created with
- `user add` are normal users, not additional admins.
+ for every `/admin/*` endpoint. DB users created with `user add` are
+ normal users, not additional admins.
- **OIDC is hook authentication, not page authorization.** Native hooks can use
a per-developer OIDC device token, but ai-memory still has one shared wiki per
server and no per-page RBAC. If you need data isolation, run separate