Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(auth): P1.3 multi-rung middleware + ActorContext injection
AkitaOnRails545a9543ac2e
diff --git a/crates/ai-memory-cli/src/auth.rs b/crates/ai-memory-cli/src/auth.rsindex 6a78070f..63092664 100644--- a/crates/ai-memory-cli/src/auth.rs+++ b/crates/ai-memory-cli/src/auth.rs@@ -44,6 +44,8 @@use std::sync::Arc;+use ai_memory_core::ActorContext;+use ai_memory_store::{ReaderPool, TokenPepper, WriterHandle, hash_token};use axum::extract::State;use axum::http::{Method, Request, StatusCode, header};use axum::middleware::Next;@@ -58,19 +60,84 @@ const AUTH_COOKIE: &str = "ai_memory_auth";/// the browser's credential prompt as "Server says: <realm>".const AUTH_REALM: &str = "ai-memory";+/// Optional multi-user resolver tier — token-hash lookup against the+/// `users` table. Populated only when both a per-server pepper and a+/// reader pool are available (i.e. after `ai-memory init` ran and a+/// store was opened). Single-user (rung-1) setups skip this entirely;+/// rung-0 (no auth) skips the whole middleware.+#[derive(Clone)]+pub struct MultiUserResolver {+ /// Hashes incoming tokens with the per-server pepper before the+ /// `users.token_hash` lookup.+ pub pepper: TokenPepper,+ /// Read-only pool used by the auth hot path+ /// (`find_active_user_by_token_hash`).+ pub reader: ReaderPool,+ /// Writer used by the fire-and-forget `last_seen_at` bump after a+ /// successful lookup — kept off the response's critical path via+ /// `tokio::spawn`. The bump is best-effort: an error is logged at+ /// `warn` and otherwise ignored.+ pub writer: WriterHandle,+}+/// Shared auth state. Cheap to clone — just an `Arc` wrapping the-/// optional configured token.-#[derive(Clone, Debug)]+/// optional configured token + the optional multi-user resolver ++/// the root actor template.+#[derive(Clone, Default)]pub struct AuthState {+ /// Bearer token that authenticates as **root**. `None` means+ /// "auth disabled at the wire level" — rung 0.expected: Option<String>,+ /// Actor template stamped onto requests that authenticate with the+ /// `expected` token. Populated from `[auth].root_username` /+ /// `root_email` / `root_name`. When all three are unset the root+ /// actor stays anonymous (rung-1 backward-compat: bearer+ /// authenticates but the audit log records nothing identifying).+ root_actor: ActorContext,+ /// Multi-user lookup tier. `None` until both pepper and reader+ /// are available — see [`Self::with_multiuser`].+ multiuser: Option<MultiUserResolver>,}impl AuthState {- /// Build state from the (optional) configured token. `None` means- /// "auth disabled, accept everything".+ /// Build state from the (optional) configured root token. `None`+ /// means "auth disabled, accept everything as anonymous".#[must_use]pub fn new(expected: Option<String>) -> Self {- Self { expected }+ Self {+ expected,+ ..Self::default()+ }+ }++ /// Attach the root actor template — see [`Self::root_actor`]. The+ /// auth middleware injects this on every request that authenticates+ /// with [`Self::expected`]; rung-2 (DB user) lookups override it+ /// with the row's identity, rung-0 (anonymous) leaves it empty.+ #[must_use]+ pub fn with_root_actor(mut self, actor: ActorContext) -> Self {+ self.root_actor = actor;+ self+ }++ /// Enable multi-user lookups: a bearer that doesn't match the root+ /// token is hashed with `pepper` and checked against the `users`+ /// table; a hit attributes the request to that user's identity.+ /// Without this attach, the middleware only knows about rung 0/1+ /// and rejects unknown bearers (closing the bypass).+ #[must_use]+ pub fn with_multiuser(+ mut self,+ pepper: TokenPepper,+ reader: ReaderPool,+ writer: WriterHandle,+ ) -> Self {+ self.multiuser = Some(MultiUserResolver {+ pepper,+ reader,+ writer,+ });+ self}/// True when a token is configured (i.e. the middleware is doing@@ -106,10 +173,14 @@ impl AuthState {/// challenge.pub async fn require_bearer(State(state): State<Arc<AuthState>>,- req: Request<axum::body::Body>,+ 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.let Some(expected) = state.expected.as_deref() else {+ req.extensions_mut().insert(ActorContext::anonymous());return next.run(req).await;};@@ -128,23 +199,83 @@ pub async fn require_bearer(.or(from_cookie.as_deref()).unwrap_or("");- if !bool::from(provided.as_bytes().ct_eq(expected.as_bytes())) {- debug!("auth rejected: invalid or missing token");- return unauthorized(is_get);+ // Rung 1: bearer matches the root token → attribute as root.+ if bool::from(provided.as_bytes().ct_eq(expected.as_bytes())) {+ let mut actor = state.root_actor.clone();+ // The agent field comes from the request layer (MCP client+ // info, hook payload) — not from config. Leave it for the+ // hook router / MCP server to overlay onto the actor.+ actor.agent = actor.agent.or(None);+ req.extensions_mut().insert(actor);++ // First successful Basic-auth hit (no cookie yet) → also stamp+ // the cookie so the user doesn't get the dialog again next+ // browser session. Subsequent navigations ride the cookie alone.+ if from_basic.is_some() && from_cookie.is_none() {+ let mut resp = next.run(req).await;+ if let Ok(cookie) = build_session_cookie(provided).parse() {+ resp.headers_mut().insert(header::SET_COOKIE, cookie);+ }+ return resp;+ }+ return next.run(req).await;}- // First successful Basic-auth hit (no cookie yet) → also stamp the- // cookie so the user doesn't get the dialog again next browser- // session. Subsequent navigations ride the cookie alone.- if from_basic.is_some() && from_cookie.is_none() {- let mut resp = next.run(req).await;- if let Ok(cookie) = build_session_cookie(provided).parse() {- resp.headers_mut().insert(header::SET_COOKIE, cookie);+ // Rung 2: bearer doesn't match root. If multi-user is enabled,+ // hash + look up the token against the `users` table.+ if let Some(mu) = state.multiuser.as_ref()+ && !provided.is_empty()+ {+ let hash = hash_token(provided, &mu.pepper);+ match mu.reader.find_active_user_by_token_hash(hash).await {+ Ok(Some(user)) => {+ // NEVER log the token itself; the username + agent is+ // safe and useful for "who hit /api/v1 last".+ debug!(actor.user = %user.username, "authenticated as DB user");+ let actor = ActorContext {+ user: Some(user.username.clone()),+ name: user.name.clone(),+ email: user.email.clone(),+ ..ActorContext::default()+ };+ req.extensions_mut().insert(actor);++ // Fire-and-forget last_seen_at bump. Errors are logged+ // but never block the response — middleware MUST stay+ // off the response's critical path. Same browser-cookie+ // dance as rung 1 above.+ let writer = mu.writer.clone();+ let user_id = user.id;+ tokio::spawn(async move {+ if let Err(e) = writer.touch_user_last_seen(user_id).await {+ tracing::warn!(error = %e, user_id = %user_id, "touch_user_last_seen failed");+ }+ });++ if from_basic.is_some() && from_cookie.is_none() {+ let mut resp = next.run(req).await;+ if let Ok(cookie) = build_session_cookie(provided).parse() {+ resp.headers_mut().insert(header::SET_COOKIE, cookie);+ }+ return resp;+ }+ return next.run(req).await;+ }+ Ok(None) => {+ // Bearer present + multi-user enabled + no match → fall+ // through to the 401 below. Critical for closing the+ // bypass: an unknown bearer MUST NOT pass even when+ // multi-user lookup is configured.+ }+ Err(e) => {+ tracing::error!(error = %e, "auth: users table lookup failed");+ return unauthorized(is_get);+ }}- return resp;}- next.run(req).await+ debug!("auth rejected: invalid or missing token");+ unauthorized(is_get)}fn extract_bearer_header(req: &Request<axum::body::Body>) -> Option<String> {@@ -544,4 +675,300 @@ mod tests {let t2 = generate_token_hex(32).unwrap();assert_ne!(t, t2);}++ // ── Extension<ActorContext> injection (P1.3 multi-rung resolution) ──++ use ai_memory_core::NewUser;+ use ai_memory_store::Store;+ use axum::Extension;+ use tempfile::TempDir;++ /// Route handler that echoes the injected `ActorContext` as JSON+ /// in the response body, so tests can verify which rung fired.+ async fn echo_actor(Extension(actor): Extension<ActorContext>) -> axum::Json<ActorContext> {+ axum::Json(actor)+ }++ fn router_with_state(state: AuthState) -> Router {+ Router::new()+ .route("/probe", get(echo_actor))+ .layer(axum::middleware::from_fn_with_state(+ Arc::new(state),+ require_bearer,+ ))+ }++ async fn body_as_actor(resp: Response) -> ActorContext {+ let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)+ .await+ .unwrap();+ serde_json::from_slice(&bytes).unwrap()+ }++ #[tokio::test]+ async fn rung0_anonymous_attaches_default_actor() {+ // No token configured → middleware is a no-op gate but still+ // injects an anonymous Extension<ActorContext> so handlers+ // always have one to read.+ let r = router_with_state(AuthState::new(None));+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let actor = body_as_actor(resp).await;+ assert!(!actor.has_any(), "rung 0 must inject anonymous actor");+ }++ #[tokio::test]+ async fn rung1_root_token_attributes_via_root_actor_template() {+ // Bearer matches config token → middleware stamps the+ // `[auth].root_*` template.+ let root = ActorContext {+ user: Some("boss".into()),+ email: Some("[email protected]".into()),+ name: Some("Boss".into()),+ ..ActorContext::default()+ };+ let state = AuthState::new(Some("the-root-token".into())).with_root_actor(root);+ let r = router_with_state(state);+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Bearer the-root-token")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let actor = body_as_actor(resp).await;+ assert_eq!(actor.user.as_deref(), Some("boss"));+ assert_eq!(actor.email.as_deref(), Some("[email protected]"));+ assert_eq!(actor.name.as_deref(), Some("Boss"));+ }++ #[tokio::test]+ async fn rung1_without_root_template_still_authenticates_anonymously() {+ // Backward-compat with existing single-user setups that have+ // bearer_token but no root_username/email/name configured.+ // Bearer matches → 200, but the actor stays anonymous.+ let state = AuthState::new(Some("plain-token".into()));+ let r = router_with_state(state);+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Bearer plain-token")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let actor = body_as_actor(resp).await;+ assert!(+ !actor.has_any(),+ "rung-1 sans template must still attribute anonymously"+ );+ }++ /// Fresh store + writer/reader + pre-loaded users row, ready to+ /// plug into [`AuthState::with_multiuser`]. Returns the raw+ /// plaintext token issued to the new user so tests can present it+ /// in the request and assert it routes correctly.+ async fn setup_multiuser(username: &str) -> (TempDir, AuthState, String) {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let pepper = TokenPepper::new("test-pepper");+ let token = ai_memory_store::generate_token().unwrap();+ let token_hash = ai_memory_store::hash_token(&token, &pepper);+ let mut new_user = NewUser {+ username: username.into(),+ name: Some(format!("{username} display")),+ email: Some(format!("{username}@example.com")),+ };+ new_user.validate().unwrap();+ store+ .writer+ .create_user(new_user, token_hash)+ .await+ .unwrap();++ let state = AuthState::new(Some("root-token-distinct-from-user-token".into()))+ .with_root_actor(ActorContext {+ user: Some("root".into()),+ ..ActorContext::default()+ })+ .with_multiuser(pepper, store.reader.clone(), store.writer.clone());+ (tmp, state, token)+ }++ #[tokio::test]+ async fn rung2_db_user_token_attributes_to_row() {+ // Bearer doesn't match root, multi-user is enabled, and the+ // token hashes to a `users` row → middleware injects that+ // user's identity (NOT the root template).+ let (_tmp, state, token) = setup_multiuser("alice").await;+ let r = router_with_state(state);+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", format!("Bearer {token}"))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let actor = body_as_actor(resp).await;+ assert_eq!(actor.user.as_deref(), Some("alice"));+ assert_eq!(actor.email.as_deref(), Some("[email protected]"));+ assert_eq!(actor.name.as_deref(), Some("alice display"));+ // NOT the root template — root_actor.user is "root".+ assert_ne!(actor.user.as_deref(), Some("root"));+ }++ #[tokio::test]+ async fn rung3_unknown_bearer_with_multiuser_returns_401_not_anonymous() {+ // The bypass guard: bearer present but matches NEITHER root+ // NOR any users row → MUST 401. Critical so a fat-fingered+ // operator (or compromised client) can't squeak through.+ let (_tmp, state, _token) = setup_multiuser("alice").await;+ let r = router_with_state(state);+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Bearer this-token-is-not-in-the-DB")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);+ }++ #[tokio::test]+ async fn rung2_expired_user_token_is_rejected() {+ // Expiring a user's token must immediately stop authenticating+ // (no 30s cache window or similar). Critical for `ai-memory+ // user expire` to be useful as an offboarding tool.+ let (_tmp, state, token) = setup_multiuser("alice").await;++ // Look up user id via the writer-side roundtrip (no public+ // find-by-username on WriterHandle, so use the reader pool).+ let user = state+ .multiuser+ .as_ref()+ .unwrap()+ .reader+ .find_user_by_username("alice".into())+ .await+ .unwrap()+ .unwrap();+ let writer = state.multiuser.as_ref().unwrap().writer.clone();+ writer.expire_user_token(user.id).await.unwrap();++ let r = router_with_state(state);+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", format!("Bearer {token}"))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(+ resp.status(),+ StatusCode::UNAUTHORIZED,+ "expired user token must not authenticate"+ );+ }++ #[tokio::test]+ async fn rung2_revived_user_token_authenticates_again() {+ let (_tmp, state, token) = setup_multiuser("alice").await;+ let user = state+ .multiuser+ .as_ref()+ .unwrap()+ .reader+ .find_user_by_username("alice".into())+ .await+ .unwrap()+ .unwrap();+ let writer = state.multiuser.as_ref().unwrap().writer.clone();+ writer.expire_user_token(user.id).await.unwrap();+ writer.revive_user_token(user.id).await.unwrap();++ let r = router_with_state(state);+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", format!("Bearer {token}"))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ }++ #[tokio::test]+ async fn root_token_wins_even_when_multiuser_is_enabled() {+ // Mixed setup: root token AND added users. Bearer = root token+ // → root_actor template (NOT a users-table lookup that wouldn't+ // find anything anyway).+ let (_tmp, state, _user_token) = setup_multiuser("alice").await;+ let r = router_with_state(state);+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header(+ "Authorization",+ "Bearer root-token-distinct-from-user-token",+ )+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let actor = body_as_actor(resp).await;+ assert_eq!(actor.user.as_deref(), Some("root"));+ }++ #[tokio::test]+ async fn rung1_setup_with_unknown_bearer_returns_401() {+ // Existing single-user setup (rung 1 only, no multi-user). An+ // unknown bearer must still 401 — same as pre-P1.3 behaviour.+ let state = AuthState::new(Some("right-token".into())).with_root_actor(ActorContext {+ user: Some("boss".into()),+ ..ActorContext::default()+ });+ let r = router_with_state(state);+ let resp = r+ .oneshot(+ Request::builder()+ .uri("/probe")+ .header("Authorization", "Bearer wrong-token")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);+ }}diff --git a/crates/ai-memory-cli/src/commands/init.rs b/crates/ai-memory-cli/src/commands/init.rsindex 6c9e5b98..92debbea 100644--- a/crates/ai-memory-cli/src/commands/init.rs+++ b/crates/ai-memory-cli/src/commands/init.rs@@ -6,6 +6,7 @@ use std::path::{Path, PathBuf};use anyhow::{Context, Result};+use crate::auth::generate_token_hex;use crate::cli::InitArgs;use crate::config::Config;@@ -13,6 +14,42 @@ const DEFAULT_CONFIG_TOML: &str = include_str!("../../templates/config.default.tconst SUBDIRS: &[&str] = &["wiki", "raw", "db", "models"];+/// Bytes of OS CSPRNG entropy used for the auto-generated+/// `[auth].token_pepper`. 32 bytes → 64 hex chars.+const TOKEN_PEPPER_BYTES: usize = 32;++/// Build the `[auth]` block appended to the freshly-rendered default+/// config on `ai-memory init`. The pepper is auto-generated so it's+/// stable from install onwards (rotating it invalidates every existing+/// user token — see `ai-memory-store::users` for the rationale).+fn render_default_auth_block(pepper: &str) -> String {+ format!(+ "+# Per-server token pepper. Keeps stolen `users.token_hash` rows useless+# to an offline attacker by mixing each token with this secret before+# hashing. Auto-generated on `ai-memory init`. **Do NOT change after+# the first user is added** — rotating invalidates every existing+# token. Only used when multi-user is enabled (at least one row in+# the `users` table); single-user / bearer-only setups don't read it.+[auth]+token_pepper = \"{pepper}\"++# Multi-user attribution (all optional).+#+# Without these, the bearer token authenticates the request but+# leaves it anonymous. Set them to label root-token writes in the+# audit log + page frontmatter.+#+# Add additional users with `ai-memory user add --username <name>`;+# each user gets their own token tied to a row in the `users` table.+#+# root_username = \"boss\"+# root_email = \"[email protected]\"+# root_name = \"Boss\"+"+ )+}+/// Run the `init` subcommand.////// Creates `<data_dir>/{wiki,raw,db,models}` (idempotent) and writes a default@@ -45,9 +82,20 @@ pub fn run(config: &Config, args: InitArgs, config_path: Option<&Path>) -> Resulfs::create_dir_all(parent).with_context(|| format!("creating config dir {}", parent.display()))?;}+ // Pepper is generated NOW (not at first server start) so it's+ // stable from install onwards: see comment in render_default_+ // auth_block. getrandom::Error doesn't impl `std::error::Error`+ // (anyhow's `with_context` would conflict), so map manually.+ let pepper = generate_token_hex(TOKEN_PEPPER_BYTES)+ .map_err(|e| anyhow::anyhow!("generating auth token_pepper: {e}"))?;+ let body = format!(+ "{}{}",+ DEFAULT_CONFIG_TOML,+ render_default_auth_block(&pepper)+ );let mut f = fs::File::create(&cfg_path).with_context(|| format!("creating {}", cfg_path.display()))?;- f.write_all(DEFAULT_CONFIG_TOML.as_bytes())+ f.write_all(body.as_bytes()).with_context(|| format!("writing {}", cfg_path.display()))?;tracing::info!(path = %cfg_path.display(), "wrote default config");}@@ -104,6 +152,93 @@ mod tests {assert_eq!(stamp, stamp2, "second init clobbered the config");}+ #[test]+ fn init_writes_token_pepper_into_auth_block() {+ let tmp = TempDir::new().unwrap();+ let config = cfg_in(tmp.path());+ run(&config, InitArgs { force: false }, None).unwrap();++ let body = std::fs::read_to_string(tmp.path().join("config.toml")).unwrap();+ assert!(+ body.contains("[auth]"),+ "rendered config must include the [auth] section"+ );+ assert!(+ body.contains("token_pepper = "),+ "rendered config must include the auto-generated token_pepper"+ );++ // Sanity: pepper is 64 hex chars (32 bytes).+ let pepper_line = body+ .lines()+ .find(|l| l.trim_start().starts_with("token_pepper"))+ .expect("token_pepper line present");+ let hex_value = pepper_line+ .split('"')+ .nth(1)+ .expect("quoted token_pepper value");+ assert_eq!(hex_value.len(), 64, "token_pepper must be 64 hex chars");+ assert!(hex_value.chars().all(|c| c.is_ascii_hexdigit()));+ }++ #[test]+ fn init_renders_config_that_parses_back_into_auth_settings() {+ // Regression guard: the appended [auth] block must be valid TOML+ // *and* round-trip into the same AuthSettings the server uses.+ // Catches a future drift between the template and the schema.+ // Uses the same figment pipeline `Config::load` runs in production+ // (Serialized defaults + Toml file merge) so the test exercises+ // the actual loader, not a parallel parser.+ use figment::Figment;+ use figment::providers::{Format as _, Serialized, Toml};++ let tmp = TempDir::new().unwrap();+ let cfg = cfg_in(tmp.path());+ run(&cfg, InitArgs { force: false }, None).unwrap();++ let cfg_path = tmp.path().join("config.toml");+ let loaded: Config = Figment::from(Serialized::defaults(Config::default()))+ .merge(Toml::file(&cfg_path))+ .extract()+ .expect("rendered config must round-trip via figment (full Config extract)");++ assert!(+ loaded+ .auth+ .token_pepper+ .as_deref()+ .is_some_and(|p| p.len() == 64),+ "parsed token_pepper must round-trip from the rendered template"+ );+ assert!(loaded.auth.bearer_token.is_none());+ assert!(loaded.auth.root_username.is_none());+ }++ #[test]+ fn init_generates_a_unique_pepper_per_run() {+ // Two fresh installs must not collide on the pepper. Anyone+ // hand-patching this to a constant for testing would break the+ // security model on every new server.+ let tmp_a = TempDir::new().unwrap();+ let tmp_b = TempDir::new().unwrap();+ run(&cfg_in(tmp_a.path()), InitArgs { force: false }, None).unwrap();+ run(&cfg_in(tmp_b.path()), InitArgs { force: false }, None).unwrap();+ let a = std::fs::read_to_string(tmp_a.path().join("config.toml")).unwrap();+ let b = std::fs::read_to_string(tmp_b.path().join("config.toml")).unwrap();+ let pa = a+ .lines()+ .find(|l| l.trim_start().starts_with("token_pepper"))+ .unwrap();+ let pb = b+ .lines()+ .find(|l| l.trim_start().starts_with("token_pepper"))+ .unwrap();+ assert_ne!(+ pa, pb,+ "two fresh inits must generate distinct peppers (got {pa})"+ );+ }+#[test]fn init_honors_explicit_config_path_outside_data_dir() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex f13f2512..10d20e6f 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -203,7 +203,39 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {bind: bind.clone(),bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),});- let auth_state = Arc::new(AuthState::new(config.auth.bearer_token.clone()));+ // Multi-rung auth assembly:+ // - rung 0 (no bearer_token configured) → AuthState::new+ // 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.+ 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()) {+ auth_state = auth_state.with_root_actor(ai_memory_core::ActorContext {+ user: root_user,+ name: config.auth.root_name.clone(),+ email: config.auth.root_email.clone(),+ ..ai_memory_core::ActorContext::default()+ });+ }+ if let Some(pepper) = config+ .auth+ .token_pepper+ .as_ref()+ .filter(|p| !p.trim().is_empty())+ {+ auth_state = auth_state.with_multiuser(+ ai_memory_store::TokenPepper::new(pepper.clone()),+ store.reader.clone(),+ store.writer.clone(),+ );+ }+ let auth_state = Arc::new(auth_state);let auth_enabled = auth_state.enabled();let router = axum::Router::new().nest_service("/mcp", mcp_service)diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex f357da08..684dd6f7 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -221,6 +221,31 @@ pub struct AuthSettings {/// `Authorization: Bearer <token>`. Generate one with/// `ai-memory generate-auth-token`.pub bearer_token: Option<String>,+ /// Username attributed to writes authenticated by the bearer+ /// token (rung 1: "identified single-user"). When set, the+ /// auth middleware injects an+ /// [`ai_memory_core::ActorContext`] with `user =+ /// Some(root_username)` on root-token requests, so audit_log+ /// and page frontmatter record the operator instead of+ /// staying anonymous. Omit (or leave empty) to keep the+ /// pre-multi-user behaviour — bearer authenticates but+ /// attributes anonymously.+ pub root_username: Option<String>,+ /// Optional email for the root user, surfaced alongside+ /// `root_username` in the web UI + `/api/v1` responses.+ pub root_email: Option<String>,+ /// Optional display name for the root user (e.g.+ /// `"Alice Smith"`); falls back to `root_username` in UIs.+ pub root_name: Option<String>,+ /// Per-server token pepper used by+ /// [`ai_memory_store::hash_token`] to keep stolen+ /// `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.+ pub token_pepper: Option<String>,}impl Default for Config {