Skip to content

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

Rust

feat(admin): add password sessions and separated API credentials (#533)

Djalma Júnior15178b885e77
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6378a499..5c4e7d0e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -283,6 +283,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
project, or worktree reads as absent rather than renamable. The Docker
wrapper routes the command through its native host client, since repository
identity is a host resource.
+- Human password login, web sessions, and native `aim_` API credentials, so the
+ console can use short-lived human sessions instead of a Bearer pasted into
+ the browser. `POST /auth/login` issues an `HttpOnly` `ai_memory_session`
+ cookie plus CSRF; `/mcp`, hooks, and workstreams stay Bearer-only. Greenfield
+ bootstrap consumes `AI_MEMORY_AUTH__INITIAL_ROOT_PASSWORD` once; break-glass
+ recovery uses `AI_MEMORY_AUTH__RECOVERY_TOKEN` and never opens a session.
+ `ai-memory user add-human|list|reset-password|disable|enable|patch` manages
+ people, while `ai-memory api-key add|list|rotate|revoke` manages machine
+ secrets. Existing 32-byte `users.token_hash` values copy losslessly into
+ `api_credentials`. The mirror triggers remain load-bearing for the deprecated
+ 1.x `user add|expire|revive|rotate-token` shims and may be removed only when
+ those shims are removed in 2.0. (#533)
+
+### Changed
+- `/admin/*` and `/api/v1/*` accept a human web session or a machine Bearer.
+ Custom SPA HTML at `/web` is public static; the builtin wiki browser stays
+ authenticated. Human auth is additive during 1.x: until a human password or
+ completed bootstrap exists, deprecated GET-only HTTP Basic and
+ `ai_memory_auth` cookie authentication continue to work. The transition to
+ human auth disables both legacy browser credentials immediately. (#533)
+- Preserved `ai-memory user add|expire|revive|rotate-token` and their admin
+ endpoints as deprecated 1.x compatibility paths backed by the reserved
+ `legacy-user-token` API credential. New automation should use
+ `api-key add|rotate|revoke`. (#533)
## [1.38.0] - 2026-08-30
diff --git a/Cargo.lock b/Cargo.lock
index 0d4aefc6..e397ec89 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -218,6 +218,7 @@ version = "1.38.0"
dependencies = [
"ai-memory-core",
"anyhow",
+ "argon2",
"base64",
"getrandom 0.3.4",
"jiff",
@@ -347,7 +348,7 @@ version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -358,7 +359,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -367,6 +368,18 @@ version = "1.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"
+[[package]]
+name = "argon2"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
+dependencies = [
+ "base64ct",
+ "blake2",
+ "cpufeatures 0.2.17",
+ "password-hash",
+]
+
[[package]]
name = "askama"
version = "0.12.1"
@@ -511,6 +524,12 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+[[package]]
+name = "base64ct"
+version = "1.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+
[[package]]
name = "basic-toml"
version = "0.1.10"
@@ -526,6 +545,15 @@ version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
+[[package]]
+name = "blake2"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
+dependencies = [
+ "digest",
+]
+
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -879,6 +907,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
+ "subtle",
]
[[package]]
@@ -947,7 +976,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
- "windows-sys 0.52.0",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -1600,7 +1629,7 @@ dependencies = [
"portable-atomic",
"portable-atomic-util",
"serde_core",
- "windows-sys 0.52.0",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -1966,7 +1995,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -2041,6 +2070,17 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "password-hash"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
+dependencies = [
+ "base64ct",
+ "rand_core 0.6.4",
+ "subtle",
+]
+
[[package]]
name = "pastey"
version = "0.2.3"
@@ -2284,6 +2324,15 @@ dependencies = [
"rand_core 0.9.5",
]
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom 0.2.17",
+]
+
[[package]]
name = "rand_core"
version = "0.9.5"
@@ -2610,7 +2659,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
- "windows-sys 0.52.0",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -2999,7 +3048,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"
dependencies = [
"libc",
- "windows-sys 0.60.2",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -3105,7 +3154,7 @@ dependencies = [
"getrandom 0.4.2",
"once_cell",
"rustix",
- "windows-sys 0.52.0",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -3781,7 +3830,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys 0.48.0",
+ "windows-sys 0.61.2",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index 51d2ae06..38044278 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -97,6 +97,9 @@ base64 = "0.22"
rusqlite = { version = "0.32", features = ["bundled", "backup"] }
refinery = { version = "0.8", features = ["rusqlite"] }
sha2 = "0.10"
+# Argon2id PHC for human passwords. Tokens stay SHA-256+pepper (hot-path
+# unique lookup); the slow KDF is reserved for the password class.
+argon2 = { version = "0.5", default-features = false, features = ["alloc", "password-hash", "std"] }
parking_lot = "0.12"
# Filesystem watcher + process inspection.
diff --git a/README.md b/README.md
index 5404f2c6..87fbe385 100644
--- a/README.md
+++ b/README.md
@@ -413,8 +413,8 @@ priors are at the [bottom](#influences-and-prior-art).
pages cleanly separated; the `/web` UI is reachable from a
browser anywhere on the LAN.
- **"Audit what landed before sharing with a teammate."** Browse
- the wiki at `http://<server>:49374/web` - HTTP Basic dialog if
- auth is on, paste the token as password. Per-project tree view,
+ the wiki at `http://<server>:49374/web` - sign in with username and
+ password when human auth is on. Per-project tree view,
rendered markdown, supersession chain visible per page.
- **"Undo one bad page edit without rolling back the whole server."**
`ai-memory checkpoints` shows recent wiki commits, then
@@ -717,12 +717,16 @@ ai-memory install-hooks --agent claude-code --apply \
--server-url "http://<server-ip>:49374" --auth-token "$TOKEN"
```
-Bearer auth protects `/mcp`, `/hook`, `/handoff`, `/admin/*`, and
-`/web/*`. Browser access to `/web` uses HTTP Basic auth with the token
-as the password. When `/web` is exposed through an HTTPS reverse proxy, set
-`AI_MEMORY_AUTH__SECURE_COOKIE=true`; it makes the browser cookie HTTPS-only.
-Close or redirect direct HTTP access to that hostname. Non-loopback binds should also set
-`AI_MEMORY_ALLOWED_HOSTS` to guard against DNS rebinding.
+Bearer auth protects `/mcp`, `/hook`, `/handoff`, `/workstream/*`, and
+machine calls to `/admin/*` and `/api/v1/*`. Humans sign in at
+`POST /auth/login`; the console uses an `HttpOnly` session cookie plus CSRF,
+not a Bearer in `localStorage`. Custom SPA HTML at `/web` is public static.
+When human auth listens beyond loopback,
+`AI_MEMORY_AUTH__SECURE_COOKIE=true` is required and signals that a trusted
+HTTPS reverse proxy owns the browser-facing edge. It makes the session cookie
+HTTPS-only. Close or redirect direct HTTP access to that hostname.
+Non-loopback binds should also set `AI_MEMORY_ALLOWED_HOSTS` to guard against
+DNS rebinding.
Busy shared hook servers can also set `AI_MEMORY_HOOK_RATE_PER_SEC` (tokens per
second per actor/session source) and optionally `AI_MEMORY_HOOK_RATE_BURST` to
@@ -770,12 +774,12 @@ path of single-user on loopback doesn't need TLS — that case is
called out explicitly in the guide so you don't add ceremony where
it doesn't earn its keep.
-**Multi-user attribution (v0.8, optional).** When more than one human
-shares a server, ai-memory can attribute each write to a named user.
-The bearer token continues to authenticate at the wire level; users
-created via `ai-memory user add` get their own tokens that resolve to
-their identity in audit logs, page frontmatter, `/api/v1` responses, and the
-page view UI. Data stays single-tenant — there is no per-page RBAC. A
+**Multi-user attribution (v0.8, optional) plus human login.** When more
+than one human shares a server, ai-memory attributes each write to a
+named user. Humans sign in with username/password; agents and CLIs use
+`Authorization: Bearer` (`AI_MEMORY_AUTH_TOKEN` for root automation, or
+an `aim_` key from `ai-memory api-key add`). Data stays single-tenant —
+there is no per-page RBAC. A
`[auth].token_pepper` is required for DB-user authentication, but creating the
first user row is what immediately switches every `/admin/*` endpoint to
root-only, including status/search/read-page and user-management routes.
@@ -1091,7 +1095,7 @@ diagram, crate breakdown, schema notes, and invariants.
| [`docs/windows.md`](docs/windows.md) | Windows install modes: full WSL2, native Windows with Docker Desktop, prebuilt native release zip, native source builds, and current hook/MCP harness caveats. |
| [`docs/mcp-install.md`](docs/mcp-install.md) | Per-client MCP and lifecycle notes, handoff-injection limits, and community bridge guidance. |
| [`docs/deploy.md`](docs/deploy.md) | Homelab deploy: bin/deploy, bearer-token auth, pointers to the TLS guide. |
-| [`docs/users.md`](docs/users.md) | **Multi-user attribution (v0.8).** Four-rung auth ladder, `ai-memory user add/list/expire/revive/rotate-token` walkthrough, backward-compat migration for pre-v0.8 installs, token storage rationale. |
+| [`docs/users.md`](docs/users.md) | **Multi-user attribution and human login.** Four-rung bearer ladder, password sessions, `ai-memory user` / `api-key` walkthrough, brownfield `aim_` migration. |
| [`docs/https-via-proxy.md`](docs/https-via-proxy.md) | **HTTPS via a reverse proxy.** When you need TLS (multi-user, non-loopback) and when you don't (loopback / stdio). Copy-paste docker compose templates for Caddy + Let's Encrypt, Caddy + internal CA (LAN-only), Cloudflare Tunnel (no open ports), and external cert files; plus native-Caddy + nginx recipes. The "thinking you're secure when you're not" failure modes explicitly called out. |
| [`docs/lifecycle-ops.md`](docs/lifecycle-ops.md) | **Read before running purge / rename / backup / restore / reset / reindex / restore-page.** Safety matrix for state-touching commands, per-project disk layout (how isolation actually works), checkpoint-based page recovery, and operator workflows for "fresh start", "snapshot before risky op", "drop one project", and rebuilding SQLite from wiki files. |
| [`docs/auto-improvement-loop.md`](docs/auto-improvement-loop.md) | Auto-improvement design notes: Hermes-inspired scheduled review, auto-approval default, manual review opt-in, pending proposal storage, and curator work. |
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 7873bb67..5fb97d91 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -199,13 +199,13 @@ pub enum Command {
Uninstall(UninstallArgs),
/// Manage optional upstream LLM provider authentication.
Auth(AuthArgs),
- /// Manage registered users for multi-user attribution. Each user
- /// has a stable username, optional name + email, and one current
- /// token. All subcommands require the root bearer token; non-root
- /// requests get 403. Existing single-user installs unaffected —
- /// these endpoints 503 until `[auth].token_pepper` is set
- /// (auto-generated by `ai-memory init`).
+ /// Manage human users and deprecated 1.x compatibility tokens. All
+ /// subcommands require the root bearer token.
User(UserArgs),
+ /// Manage native `aim_` API credentials. All subcommands require
+ /// the root bearer token and `[auth].token_pepper`.
+ #[command(name = "api-key")]
+ ApiKey(ApiKeyArgs),
/// Print a shell-completion script to stdout. Generated from this
/// binary's own command tree, so it never drifts from the real CLI
/// surface. See `docs/shell-completions.md` for install paths.
@@ -476,48 +476,69 @@ pub struct CompletionsArgs {
/// Subcommands for `user`.
#[derive(Debug, Subcommand)]
pub enum UserCommand {
- /// Create a new user and issue their initial token. The token is
- /// printed to stdout exactly once — store it now; only its SHA-256
- /// digest is kept in the DB.
+ /// Create a token-only compatibility user and print their token once.
Add(UserAddArgs),
- /// List every registered user. Tokens are NEVER surfaced (the row
- /// only stores the hash); the `expired` column shows whether the
- /// user's token currently authenticates.
+ /// Create a human user and print a temporary password once. The user must
+ /// change it on next login. Does not issue an API key.
+ #[command(name = "add-human")]
+ AddHuman(UserAddHumanArgs),
+ /// List every registered identity. Passwords and hashes are never
+ /// surfaced.
List(UserListArgs),
- /// Expire the user's current token. Auth requests with that token
- /// start returning 401 immediately. The user row stays put so
- /// historical attribution references survive.
+ /// Deprecated: expire the user's compatibility token.
Expire(UserExpireArgs),
- /// Re-activate a previously-expired token. No-op when the user's
- /// token is already active.
+ /// Deprecated: reactivate the user's compatibility token.
Revive(UserReviveArgs),
- /// Issue a fresh token, replacing the existing one. Implicitly
- /// revives an expired user — rotating a token makes it usable
- /// again. The new plaintext is printed exactly once.
+ /// Deprecated: replace and reactivate the user's compatibility token.
+ #[command(name = "rotate-token")]
RotateToken(UserRotateTokenArgs),
+ /// Replace the user's password with a new temporary one, revoke
+ /// their web sessions, and force a change on next login. Does not
+ /// revoke API credentials.
+ #[command(name = "reset-password")]
+ ResetPassword(UserResetPasswordArgs),
+ /// Disable human login and revoke web sessions. API credentials
+ /// stay valid.
+ Disable(UserDisableArgs),
+ /// Re-enable human login. Does not revive or revoke API credentials.
+ Enable(UserEnableArgs),
+ /// Update display name, email, and/or role (`root` or `user`).
+ Patch(UserPatchArgs),
}
/// Arguments for `user add`.
#[derive(Debug, Args)]
pub struct UserAddArgs {
- /// Stable username. Required. Validation rejects empty, internal
- /// whitespace, control chars, and the path/quoting separators
- /// `/ \ : ; , " ' \``. UTF-8 letters and emails-as-usernames
- /// (alice@home) are allowed.
+ /// Stable username.
#[arg(long)]
pub username: String,
- /// Display name (e.g. `"Alice Smith"`). Surfaced in the web UI +
- /// `/api/v1` responses alongside the username. Internal whitespace
- /// is fine — only the edges are trimmed.
+ /// Optional display name.
#[arg(long)]
pub name: Option<String>,
- /// Email. Basic validation: exactly one `@`, both sides non-empty,
- /// no whitespace. Intranet-style addresses (`alice@home`) are
- /// accepted. Lowercased before storage; case-insensitive unique.
+ /// Optional email.
#[arg(long)]
pub email: Option<String>,
- /// Emit the response as JSON instead of human-readable text. The
- /// token field is included in either case.
+ /// Emit JSON. The compatibility token is included exactly once.
+ #[arg(long)]
+ pub json: bool,
+}
+
+/// Arguments for `user add-human`.
+#[derive(Debug, Args)]
+pub struct UserAddHumanArgs {
+ /// Stable username.
+ #[arg(long)]
+ pub username: String,
+ /// Optional display name.
+ #[arg(long)]
+ pub name: Option<String>,
+ /// Optional email.
+ #[arg(long)]
+ pub email: Option<String>,
+ /// Role: `user` (default) or `root`.
+ #[arg(long)]
+ pub role: Option<String>,
+ /// Emit JSON. The temporary password is included exactly once.
#[arg(long)]
pub json: bool,
}
@@ -530,36 +551,151 @@ pub struct UserListArgs {
pub json: bool,
}
-/// Arguments for `user expire`.
+/// Arguments for deprecated `user expire`.
#[derive(Debug, Args)]
pub struct UserExpireArgs {
- /// Username to expire.
+ /// Username whose compatibility token to expire.
pub username: String,
/// Skip the interactive confirmation prompt.
#[arg(long)]
pub yes: bool,
}
-/// Arguments for `user revive`.
+/// Arguments for deprecated `user revive`.
#[derive(Debug, Args)]
pub struct UserReviveArgs {
- /// Username to revive.
+ /// Username whose compatibility token to revive.
pub username: String,
}
-/// Arguments for `user rotate-token`.
+/// Arguments for deprecated `user rotate-token`.
#[derive(Debug, Args)]
pub struct UserRotateTokenArgs {
- /// Username to rotate.
+ /// Username whose compatibility token to rotate.
+ pub username: String,
+ /// Skip the interactive confirmation prompt.
+ #[arg(long)]
+ pub yes: bool,
+ /// Emit JSON. The new token is included exactly once.
+ #[arg(long)]
+ pub json: bool,
+}
+
+/// Arguments for `user reset-password`.
+#[derive(Debug, Args)]
+pub struct UserResetPasswordArgs {
+ /// Username whose password to reset.
+ pub username: String,
+ /// Skip the interactive confirmation prompt.
+ #[arg(long)]
+ pub yes: bool,
+ /// Emit the response as JSON instead of human-readable text.
+ #[arg(long)]
+ pub json: bool,
+}
+
+/// Arguments for `user disable`.
+#[derive(Debug, Args)]
+pub struct UserDisableArgs {
+ /// Username whose human login to disable.
pub username: String,
/// Skip the interactive confirmation prompt.
#[arg(long)]
pub yes: bool,
+}
+
+/// Arguments for `user enable`.
+#[derive(Debug, Args)]
+pub struct UserEnableArgs {
+ /// Username whose human login to re-enable.
+ pub username: String,
+}
+
+/// Arguments for `user patch`.
+#[derive(Debug, Args)]
+pub struct UserPatchArgs {
+ /// Username to update.
+ pub username: String,
+ /// New display name. Empty string clears it.
+ #[arg(long)]
+ pub name: Option<String>,
+ /// New email. Empty string clears it.
+ #[arg(long)]
+ pub email: Option<String>,
+ /// New role: `root` or `user`.
+ #[arg(long)]
+ pub role: Option<String>,
/// Emit the response as JSON instead of human-readable text.
#[arg(long)]
pub json: bool,
}
+/// Arguments for `api-key`.
+#[derive(Debug, Args)]
+pub struct ApiKeyArgs {
+ /// API-credential action to run.
+ #[command(subcommand)]
+ pub command: ApiKeyCommand,
+}
+
+/// Subcommands for `api-key`.
+#[derive(Debug, Subcommand)]
+pub enum ApiKeyCommand {
+ /// Issue a native `aim_` credential and print the secret once.
+ Add(ApiKeyAddArgs),
+ /// List native API credentials (metadata only; secrets are never shown).
+ List(ApiKeyListArgs),
+ /// Replace the secret. The previous plaintext 401s immediately.
+ Rotate(ApiKeyRotateArgs),
+ /// Revoke the credential. Idempotent.
+ Revoke(ApiKeyRevokeArgs),
+}
+
+/// Arguments for `api-key add`.
+#[derive(Debug, Args)]
+pub struct ApiKeyAddArgs {
+ /// Username the credential authenticates as (`AuthLevel::User`).
+ #[arg(long)]
+ pub username: String,
+ /// Operator-facing label (e.g. `codex-laptop`).
+ #[arg(long)]
+ pub label: String,
+ /// Emit the response as JSON instead of human-readable text.
+ #[arg(long)]
+ pub json: bool,
+}
+
+/// Arguments for `api-key list`.
+#[derive(Debug, Args)]
+pub struct ApiKeyListArgs {
+ /// Emit the response as JSON instead of a human-readable table.
+ #[arg(long)]
+ pub json: bool,
+}
+
+/// Arguments for `api-key rotate`.
+#[derive(Debug, Args)]
+pub struct ApiKeyRotateArgs {
+ /// Credential id to rotate.
+ pub id: String,
+ /// Skip the interactive confirmation prompt.
+ #[arg(long)]
+ pub yes: bool,
+ /// Emit the response as JSON instead of human-readable text.
+ #[arg(long)]
+ pub json: bool,
+}
+
+/// Arguments for `api-key revoke`.
+#[derive(Debug, Args)]
+pub struct ApiKeyRevokeArgs {
+ /// Credential id to revoke.
+ pub id: String,
+ /// Skip the interactive confirmation prompt.
+ #[arg(long)]
+ pub yes: bool,
+}
+
/// Arguments for `auth`.
#[derive(Debug, Args)]
pub struct AuthArgs {
@@ -1835,15 +1971,15 @@ pub struct InstallHooksArgs {
pub auth_token: Option<String>,
/// Stamp the installed hooks with a registered username for operator
/// visibility. This flag is metadata: the server resolves attribution
- /// from the token passed via `--auth-token`. Recommended workflow:
+ /// from the API key passed via `--auth-token`. Recommended workflow:
///
/// ```bash
- /// # 1. create the user (prints the token once)
- /// ai-memory user add --username alice --email alice@home
+ /// # 1. issue a native API key for the user (prints the key once)
+ /// ai-memory api-key add --username alice --label claude-hooks
///
- /// # 2. wire alice's token into the agent's hooks
+ /// # 2. wire that API key into the agent's hooks
/// ai-memory install-hooks --apply --agent claude-code \
- /// --as-user alice --auth-token <alice-token>
+ /// --as-user alice --auth-token <alice-api-key>
/// ```
///
/// Without this flag, the installer omits the username label;
@@ -1990,11 +2126,10 @@ pub struct ServeArgs {
/// Project name within the workspace (auto-created).
#[arg(long, default_value_t = crate::config::DEFAULT_PROJECT.to_string())]
pub project: String,
- /// Mount the read-only wiki browser at /web. Off by default. When
- /// enabled, anyone who can reach the MCP endpoint can also browse
- /// the wiki and the read-only frontend API under /api/v1 — keep
- /// the bind loopback-only or front with a reverse proxy that
- /// handles its own auth if you expose it.
+ /// Mount the web surface at `/web`. Off by default. A custom SPA shell
+ /// is public so it can render password login; `/api/v1` and the built-in
+ /// server-rendered wiki remain protected by a web session or machine
+ /// Bearer.
#[arg(long)]
pub enable_web: bool,
/// Serve this static directory at /web instead of the built-in UI.
@@ -2950,6 +3085,48 @@ mod tests {
assert!(matches!(args.client, McpClient::Zed));
}
+ #[test]
+ fn deprecated_user_token_commands_and_additive_human_create_parse() {
+ for argv in [
+ vec!["ai-memory", "user", "expire", "alice", "--yes"],
+ vec!["ai-memory", "user", "revive", "alice"],
+ vec![
+ "ai-memory",
+ "user",
+ "rotate-token",
+ "alice",
+ "--yes",
+ "--json",
+ ],
+ vec![
+ "ai-memory",
+ "user",
+ "add-human",
+ "--username",
+ "alice",
+ "--role",
+ "root",
+ ],
+ ] {
+ Cli::try_parse_from(&argv)
+ .unwrap_or_else(|error| panic!("{argv:?} must remain parseable: {error}"));
+ }
+ }
+
+ #[test]
+ fn user_add_keeps_the_legacy_token_contract() {
+ let parsed =
+ Cli::try_parse_from(["ai-memory", "user", "add", "--username", "alice", "--json"])
+ .expect("legacy user add parses");
+ let Command::User(args) = parsed.command else {
+ panic!("expected user command");
+ };
+ assert!(
+ matches!(args.command, UserCommand::Add(_)),
+ "user add must remain the legacy token-issuing command"
+ );
+ }
+
#[test]
fn auth_login_openai_oauth_parses() {
let cli = Cli::try_parse_from([
diff --git a/crates/ai-memory-cli/src/commands/api_key.rs b/crates/ai-memory-cli/src/commands/api_key.rs
new file mode 100644
index 00000000..4318684e
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/api_key.rs
@@ -0,0 +1,195 @@
+//! `ai-memory api-key` — manage native `aim_` API credentials.
+//!
+//! Thin HTTP client over `/admin/api-credentials*`. Root bearer required.
+
+use std::io::{self, BufRead, Write};
+
+use anyhow::{Context, Result, bail};
+use serde::{Deserialize, Serialize};
+
+use crate::cli::{
+ ApiKeyAddArgs, ApiKeyArgs, ApiKeyCommand, ApiKeyListArgs, ApiKeyRevokeArgs, ApiKeyRotateArgs,
+};
+use crate::config::Config;
+use crate::http_client::{ServerEndpoint, get_json, post_json};
+
+#[derive(Debug, Deserialize, Serialize)]
+struct CredentialRow {
+ id: String,
+ user_id: String,
+ label: String,
+ #[serde(default)]
+ preview: Option<String>,
+ created_at: i64,
+ #[serde(default)]
+ last_used_at: Option<i64>,
+ #[serde(default)]
+ expires_at: Option<i64>,
+ #[serde(default)]
+ revoked_at: Option<i64>,
+}
+
+impl CredentialRow {
+ fn status(&self) -> &'static str {
+ if self.revoked_at.is_some() {
+ "revoked"
+ } else {
+ "active"
+ }
+ }
+}
+
+#[derive(Debug, Deserialize)]
+struct CredentialWithToken {
+ credential: CredentialRow,
+ token: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct CredentialList {
+ credentials: Vec<CredentialRow>,
+}
+
+/// Dispatch `ai-memory api-key`.
+///
+/// # Errors
+/// HTTP failure or malformed JSON.
+pub async fn run(config: &Config, args: ApiKeyArgs) -> Result<()> {
+ let ep = ServerEndpoint::from_config_resolving_auth(config).await;
+ match args.command {
+ ApiKeyCommand::Add(args) => add(&ep, args).await,
+ ApiKeyCommand::List(args) => list(&ep, args).await,
+ ApiKeyCommand::Rotate(args) => rotate(&ep, args).await,
+ ApiKeyCommand::Revoke(args) => revoke(&ep, args).await,
+ }
+}
+
+#[derive(Debug, Serialize)]
+struct CreateBody<'a> {
+ username: &'a str,
+ label: &'a str,
+}
+
+async fn add(ep: &ServerEndpoint, args: ApiKeyAddArgs) -> Result<()> {
+ let body = CreateBody {
+ username: args.username.trim(),
+ label: args.label.trim(),
+ };
+ let resp: CredentialWithToken = post_json(ep, "/admin/api-credentials", &body)
+ .await
+ .context("creating API credential")?;
+ print_token(&resp, args.json, "created")
+}
+
+async fn list(ep: &ServerEndpoint, args: ApiKeyListArgs) -> Result<()> {
+ let resp: CredentialList = get_json(ep, "/admin/api-credentials", &[])
+ .await
+ .context("listing API credentials")?;
+ if args.json {
+ println!("{}", serde_json::to_string_pretty(&resp.credentials)?);
+ return Ok(());
+ }
+ if resp.credentials.is_empty() {
+ println!("(no API credentials)");
+ return Ok(());
+ }
+ let id_w = resp
+ .credentials
+ .iter()
+ .map(|c| c.id.len())
+ .max()
+ .unwrap_or(8)
+ .max(8);
+ let label_w = resp
+ .credentials
+ .iter()
+ .map(|c| c.label.len())
+ .max()
+ .unwrap_or(5)
+ .max(5);
+ println!(
+ "{:<id_w$} {:<label_w$} {:<8} PREVIEW",
+ "ID",
+ "LABEL",
+ "STATUS",
+ id_w = id_w,
+ label_w = label_w,
+ );
+ for c in &resp.credentials {
+ println!(
+ "{:<id_w$} {:<label_w$} {:<8} {}",
+ c.id,
+ c.label,
+ c.status(),
+ c.preview.as_deref().unwrap_or("-"),
+ id_w = id_w,
+ label_w = label_w,
+ );
+ }
+ Ok(())
+}
+
+async fn rotate(ep: &ServerEndpoint, args: ApiKeyRotateArgs) -> Result<()> {
+ if !args.yes {
+ confirm(&format!(
+ "Rotate API key '{}'? Existing clients using the old secret will 401 immediately. (y/N) ",
+ args.id
+ ))?;
+ }
+ let path = format!("/admin/api-credentials/{}/rotate", args.id.trim());
+ let resp: CredentialWithToken = post_json(ep, &path, &serde_json::json!({}))
+ .await
+ .context("rotating API credential")?;
+ print_token(&resp, args.json, "rotated")
+}
+
+async fn revoke(ep: &ServerEndpoint, args: ApiKeyRevokeArgs) -> Result<()> {
+ if !args.yes {
+ confirm(&format!("Revoke API key '{}'? (y/N) ", args.id))?;
+ }
+ let path = format!("/admin/api-credentials/{}/revoke", args.id.trim());
+ let _: serde_json::Value = post_json(ep, &path, &serde_json::json!({}))
+ .await
+ .context("revoking API credential")?;
+ println!("✓ revoked API key '{}'", args.id);
+ Ok(())
+}
+
+fn print_token(resp: &CredentialWithToken, json: bool, verb: &str) -> Result<()> {
+ if json {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&serde_json::json!({
+ "credential": &resp.credential,
+ "token": &resp.token
+ }))?
+ );
+ } else {
+ let mut stderr = io::stderr().lock();
+ let _ = writeln!(
+ stderr,
+ "✓ {verb} API key '{}' ({})\n\n\
+ Store this token now — it will NOT be shown again.",
+ resp.credential.id, resp.credential.label
+ );
+ println!("{}", resp.token);
+ }
+ Ok(())
+}
+
+fn confirm(prompt: &str) -> Result<()> {
+ let mut stderr = io::stderr().lock();
+ let _ = write!(stderr, "{prompt}");
+ let _ = stderr.flush();
+ drop(stderr);
+ let mut buf = String::new();
+ let n = io::stdin().lock().read_line(&mut buf)?;
+ if n == 0 {
+ bail!("aborted (no input)");
+ }
+ let trimmed = buf.trim();
+ if !trimmed.eq_ignore_ascii_case("y") && !trimmed.eq_ignore_ascii_case("yes") {
+ bail!("aborted");
+ }
+ Ok(())
+}
diff --git a/crates/ai-memory-cli/src/commands/init.rs b/crates/ai-memory-cli/src/commands/init.rs
index 4137ec82..79cdc72b 100644
--- a/crates/ai-memory-cli/src/commands/init.rs
+++ b/crates/ai-memory-cli/src/commands/init.rs
@@ -23,16 +23,15 @@ 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).
+/// native API key — see `ai-memory-store::api_credentials`).
fn render_default_auth_block(pepper: &str) -> String {
format!(
"
-# Per-server token pepper. Keeps stolen `users.token_hash` rows useless
+# Per-server token pepper. Keeps stolen `api_credentials.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.
+# the first native API key is added** — rotating invalidates every key.
+# Human password login does not use this pepper.
token_pepper = \"{pepper}\"
# Multi-user attribution (all optional).
@@ -41,8 +40,8 @@ token_pepper = \"{pepper}\"
# 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.
+# Add human users with `ai-memory user add-human --username <name>`, then issue
+# programmatic access separately with `ai-memory api-key add`.
#
# root_username = \"boss\"
# root_email = \"[email protected]\"
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 06759643..388d38ec 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -337,8 +337,8 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {
let auth = auth_token_owned.as_deref();
// P1.8 multi-user attribution: `--as-user` is metadata only — the
// token stamped into the hook env block is whatever the operator
- // passed via `--auth-token` (typically the per-user token from
- // `ai-memory user add`). We surface the username to stderr so the
+ // passed via `--auth-token` (typically a native key from
+ // `ai-memory api-key add`). We surface the username to stderr so the
// operator can confirm which identity their writes will attribute
// to. Mismatch between `--as-user` and the actual token's owner is
// the operator's concern; we don't reach back to the server to
@@ -877,7 +877,7 @@ fn validate_as_user(as_user: Option<&str>, auth_token: Option<&str>) -> Result<(
if auth_token.map(str::trim).is_none_or(str::is_empty) {
anyhow::bail!(
"--as-user '{user}' requires --auth-token \
- (the token printed by `ai-memory user add --username {user}`)"
+ (issue one with `ai-memory api-key add --username {user} --label <label>`)"
);
}
Ok(())
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 1ac37c4a..a52de397 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -4,6 +4,7 @@ use anyhow::{Context, Result, anyhow, bail};
use crate::config::Config;
+pub mod api_key;
pub mod apply_shared;
pub mod audit_contamination;
pub mod auth;
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index e9510b9a..bbcd9e52 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -17,11 +17,16 @@ use ai_memory_hooks::{
workstream_router,
};
use ai_memory_llm::{Embedder, LlmProvider, ProviderHealth, build_embedder, build_provider};
+use ai_memory_mcp::human_auth::{Cidr, HumanAuthRuntime, LoginLimiter};
use ai_memory_mcp::{
AdminState, AiMemoryServer, ScopeInvalidation, admin_router_with_sweep_tuning,
+ expire_legacy_cookie_mw, internal_auth_router, public_auth_router, require_dual_auth,
+ session_auth_router,
};
-use ai_memory_store::{ReaderPool, Store, WriterHandle};
-use ai_memory_web::{WebMountSpec, mount_web_router, normalize_prefix, web_base_href};
+use ai_memory_store::{
+ ReaderPool, Store, TokenPepper, WriterHandle, hash_session_secret, hash_token,
+};
+use ai_memory_web::{WebMountSpec, normalize_prefix, split_web_routers, web_base_href};
use ai_memory_wiki::{WatcherHandle, Wiki, migrations, run_wiki_migrations};
use anyhow::{Context, Result};
use axum::body::Body;
@@ -34,6 +39,7 @@ use rmcp::transport::stdio;
use rmcp::transport::streamable_http_server::{
StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
};
+use secrecy::ExposeSecret;
use tokio_util::sync::CancellationToken;
use tracing::info;
@@ -61,14 +67,29 @@ const SESSION_CONSOLIDATION_POLL_INTERVAL: Duration = Duration::from_secs(15);
/// requests are expected to finish well inside this lease.
const SESSION_CONSOLIDATION_LEASE: Duration = Duration::from_secs(10 * 60);
+fn validate_api_credential_pepper(api_credentials_exist: bool, auth: &AuthSettings) -> Result<()> {
+ let pepper_present = auth
+ .token_pepper
+ .as_deref()
+ .is_some_and(|value| !value.trim().is_empty());
+ if api_credentials_exist && !pepper_present {
+ anyhow::bail!(
+ "api credentials exist but [auth].token_pepper is missing or blank; restore the original pepper from configuration backup before serving"
+ );
+ }
+ 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.
-fn validate_existing_users_auth(users_exist: bool, auth: &AuthSettings) -> Result<()> {
- if !users_exist {
- return Ok(());
- }
-
+fn validate_existing_users_auth(
+ users_exist: bool,
+ api_credentials_exist: bool,
+ human_mode: bool,
+ auth: &AuthSettings,
+) -> Result<()> {
+ validate_api_credential_pepper(api_credentials_exist, auth)?;
let pepper_present = auth
.token_pepper
.as_deref()
@@ -77,18 +98,206 @@ fn validate_existing_users_auth(users_exist: bool, auth: &AuthSettings) -> Resul
.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"
- ),
+ if users_exist && !human_mode {
+ return 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"
+ ),
+ };
+ }
+ Ok(())
+}
+
+fn secret_configured(secret: Option<&secrecy::SecretString>) -> bool {
+ secret.is_some_and(|s| !s.expose_secret().trim().is_empty())
+}
+
+fn parse_trusted_proxy_cidrs(auth: &AuthSettings) -> Result<Vec<Cidr>> {
+ auth.trusted_proxy_cidrs
+ .iter()
+ .map(|spec| {
+ Cidr::parse(spec).map_err(|e| {
+ anyhow::anyhow!("invalid [auth].trusted_proxy_cidrs entry {spec:?}: {e}")
+ })
+ })
+ .collect()
+}
+
+async fn maybe_bootstrap_root(store: &Store, auth: &AuthSettings) -> Result<()> {
+ if store.reader.bootstrap_completed().await? {
+ if secret_configured(auth.initial_root_password.as_ref()) {
+ tracing::warn!(
+ "[auth].initial_root_password is ignored because bootstrap already completed; unset AI_MEMORY_AUTH__INITIAL_ROOT_PASSWORD"
+ );
+ }
+ return Ok(());
+ }
+ let Some(password) = auth
+ .initial_root_password
+ .as_ref()
+ .map(|s| s.expose_secret().to_string())
+ .filter(|s| !s.trim().is_empty())
+ else {
+ return Ok(());
+ };
+ let username = auth
+ .root_username
+ .as_deref()
+ .filter(|s| !s.trim().is_empty())
+ .unwrap_or("root");
+ let recovery = auth
+ .recovery_token
+ .as_ref()
+ .map(ExposeSecret::expose_secret)
+ .filter(|s| !s.trim().is_empty());
+ let reserved: Vec<&str> = [
+ auth.bearer_token
+ .as_deref()
+ .filter(|s| !s.trim().is_empty()),
+ auth.actor_proxy_bearer_token
+ .as_deref()
+ .filter(|s| !s.trim().is_empty()),
+ recovery,
+ ]
+ .into_iter()
+ .flatten()
+ .collect();
+ ai_memory_core::validate_human_password(&password, Some(username), &reserved)
+ .context("initial root password does not meet policy")?;
+ if let Some(pepper) = auth
+ .token_pepper
+ .as_deref()
+ .filter(|p| !p.trim().is_empty())
+ {
+ let hash = hash_token(&password, &TokenPepper::new(pepper.to_string()));
+ if store.reader.token_hash_exists(hash).await? {
+ anyhow::bail!(
+ "[auth].initial_root_password collides with an existing API credential; choose a different password"
+ );
+ }
+ }
+ let phc = ai_memory_store::password::hash_password(password)
+ .await
+ .context("hashing initial root password")?;
+ store
+ .writer
+ .bootstrap_root(
+ username.to_string(),
+ auth.root_name.clone(),
+ auth.root_email.clone(),
+ phc,
+ )
+ .await
+ .context("bootstrapping root user")?;
+ tracing::warn!(
+ "root user bootstrapped; unset AI_MEMORY_AUTH__INITIAL_ROOT_PASSWORD so the plaintext is not kept in the process environment"
+ );
+ Ok(())
+}
+
+async fn validate_configured_secret_collisions(
+ store: &Store,
+ auth: &AuthSettings,
+ include_initial_password: bool,
+) -> Result<()> {
+ let Some(pepper) = auth
+ .token_pepper
+ .as_deref()
+ .filter(|value| !value.trim().is_empty())
+ .map(|value| TokenPepper::new(value.to_string()))
+ else {
+ return Ok(());
+ };
+ let mut secrets = Vec::new();
+ if let Some(value) = auth
+ .bearer_token
+ .as_deref()
+ .filter(|value| !value.trim().is_empty())
+ {
+ secrets.push(("[auth].bearer_token", value));
+ }
+ if let Some(value) = auth
+ .actor_proxy_bearer_token
+ .as_deref()
+ .filter(|value| !value.trim().is_empty())
+ {
+ secrets.push(("[auth].actor_proxy_bearer_token", value));
+ }
+ if let Some(value) = auth
+ .recovery_token
+ .as_ref()
+ .map(ExposeSecret::expose_secret)
+ .filter(|value| !value.trim().is_empty())
+ {
+ secrets.push(("[auth].recovery_token", value));
+ }
+ if include_initial_password
+ && let Some(value) = auth
+ .initial_root_password
+ .as_ref()
+ .map(ExposeSecret::expose_secret)
+ .filter(|value| !value.trim().is_empty())
+ {
+ secrets.push(("[auth].initial_root_password", value));
+ }
+ for (name, value) in secrets {
+ if store
+ .reader
+ .token_hash_exists(hash_token(value, &pepper))
+ .await?
+ {
+ anyhow::bail!(
+ "{name} collides with an existing API credential; configure a distinct secret"
+ );
+ }
+ }
+ Ok(())
+}
+
+fn human_auth_intended(auth: &AuthSettings, bootstrap_completed: bool, any_password: bool) -> bool {
+ bootstrap_completed
+ || any_password
+ || secret_configured(auth.initial_root_password.as_ref())
+ || secret_configured(auth.recovery_token.as_ref())
+}
+
+fn require_recoverable_root_or_recovery(
+ human_mode: bool,
+ recoverable_roots: i64,
+ recovery_configured: bool,
+) -> Result<()> {
+ if human_mode && recoverable_roots == 0 && !recovery_configured {
+ anyhow::bail!(
+ "human authentication is enabled but no recoverable root user exists; set [auth].recovery_token to rebuild root via POST /auth/recovery"
+ );
+ }
+ Ok(())
+}
+
+fn reserved_human_passwords(auth: &AuthSettings) -> Vec<String> {
+ let mut out = Vec::new();
+ if let Some(v) = auth
+ .bearer_token
+ .as_deref()
+ .filter(|s| !s.trim().is_empty())
+ {
+ out.push(v.to_string());
}
+ if let Some(v) = auth
+ .actor_proxy_bearer_token
+ .as_deref()
+ .filter(|s| !s.trim().is_empty())
+ {
+ out.push(v.to_string());
+ }
+ out
}
fn configured(value: Option<&String>) -> bool {
@@ -140,10 +349,22 @@ fn running_in_container() -> bool {
fn validate_http_exposure(
local_addr: SocketAddr,
auth_enabled: bool,
+ human_mode: bool,
+ secure_cookie: bool,
allow_insecure_no_auth: bool,
containerized: bool,
) -> Result<HttpExposure> {
- if local_addr.ip().is_loopback() || auth_enabled {
+ if local_addr.ip().is_loopback() {
+ return Ok(HttpExposure::Safe);
+ }
+ if human_mode && !secure_cookie {
+ anyhow::bail!(
+ "refusing human authentication on non-loopback plain HTTP address {local_addr}: \
+ passwords and session cookies require [auth].secure_cookie=true behind a trusted \
+ HTTPS reverse proxy. Non-Secure human cookies are allowed only on loopback."
+ );
+ }
+ if auth_enabled {
return Ok(HttpExposure::Safe);
}
if allow_insecure_no_auth {
@@ -428,8 +649,28 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
);
}
- validate_existing_users_auth(store.reader.users_exist().await?, &config.auth)?;
+ let api_credentials_exist = store.reader.api_credentials_exist().await?;
+ validate_api_credential_pepper(api_credentials_exist, &config.auth)?;
+ let bootstrap_completed_before_start = store.reader.bootstrap_completed().await?;
+ validate_configured_secret_collisions(&store, &config.auth, !bootstrap_completed_before_start)
+ .await?;
+ maybe_bootstrap_root(&store, &config.auth).await?;
+ let bootstrap_completed = store.reader.bootstrap_completed().await?;
+ let any_password = store.reader.any_password_hash().await?;
+ let human_mode = human_auth_intended(&config.auth, bootstrap_completed, any_password);
+ require_recoverable_root_or_recovery(
+ human_mode,
+ store.reader.count_recoverable_roots().await?,
+ secret_configured(config.auth.recovery_token.as_ref()),
+ )?;
+ validate_existing_users_auth(
+ store.reader.users_exist().await?,
+ api_credentials_exist,
+ human_mode,
+ &config.auth,
+ )?;
validate_trusted_proxy_auth(&config.auth)?;
+ let trusted_proxy_cidrs = parse_trusted_proxy_cidrs(&config.auth)?;
// Run any outstanding wiki-structure migrations before the watcher starts
// so file moves and renames are never raced by the reconciler.
@@ -777,14 +1018,50 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
store.writer.clone(),
);
}
+ let recovery_token_hash = config
+ .auth
+ .recovery_token
+ .as_ref()
+ .map(ExposeSecret::expose_secret)
+ .filter(|s| !s.trim().is_empty())
+ .map(hash_session_secret);
+ let root_username = config
+ .auth
+ .root_username
+ .clone()
+ .filter(|value| !value.trim().is_empty())
+ .unwrap_or_else(|| "root".to_string());
+ auth_state = auth_state.with_human_runtime(
+ HumanAuthRuntime {
+ reader: store.reader.clone(),
+ writer: store.writer.clone(),
+ recovery_token_hash,
+ root_username,
+ root_name: config.auth.root_name.clone(),
+ root_email: config.auth.root_email.clone(),
+ reserved_passwords: reserved_human_passwords(&config.auth),
+ trusted_proxy_cidrs: trusted_proxy_cidrs.clone(),
+ limiter: Arc::new(LoginLimiter::default()),
+ },
+ human_mode,
+ );
let auth_state = Arc::new(auth_state);
let auth_enabled = auth_state.enabled();
- let router = axum::Router::new()
+ let machine = axum::Router::new()
.nest_service("/mcp", mcp_service)
.merge(hooks)
.merge(workstreams)
.layer(DefaultBodyLimit::max(MAX_BODY_BYTES))
- .merge(admin.layer(DefaultBodyLimit::max(BOOTSTRAP_MAX_BODY_BYTES)));
+ .layer(axum::middleware::from_fn_with_state(
+ auth_state.clone(),
+ require_bearer,
+ ));
+ let admin = admin
+ .layer(DefaultBodyLimit::max(BOOTSTRAP_MAX_BODY_BYTES))
+ .layer(axum::middleware::from_fn_with_state(
+ auth_state.clone(),
+ require_dual_auth,
+ ));
let base_path = normalize_prefix(&args.base_path);
if base_path.is_empty() && !args.base_path.trim_matches('/').trim().is_empty() {
tracing::warn!(
@@ -805,8 +1082,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
);
}
let base_href = web_base_href(&args.base_path, &args.web_slug);
- let router = mount_web_router(
- router,
+ let web = split_web_routers(
args.enable_web,
store.reader.clone(),
wiki.clone(),
@@ -818,7 +1094,20 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
base_path: &base_path,
},
)?;
- let router = apply_http_layers(router, auth_state, config.allowed_hosts.clone());
+ let router = machine
+ .merge(admin)
+ .merge(public_auth_router(auth_state.clone()))
+ .merge(session_auth_router(auth_state.clone()))
+ .merge(internal_auth_router(auth_state.clone()))
+ .merge(web.protected.layer(axum::middleware::from_fn_with_state(
+ auth_state.clone(),
+ require_dual_auth,
+ )))
+ .merge(web.public.layer(axum::middleware::from_fn_with_state(
+ auth_state.clone(),
+ expire_legacy_cookie_mw,
+ )));
+ let router = apply_host_layer(router, config.allowed_hosts.clone());
// Host the entire surface under the configured base path. Empty
// base = root (unchanged). The auth/host layers are already
// attached to `router`, so they run for every nested route.
@@ -848,6 +1137,8 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
let exposure = validate_http_exposure(
local_addr,
auth_enabled,
+ human_mode,
+ config.auth.secure_cookie,
args.allow_insecure_no_auth,
running_in_container(),
)?;
@@ -876,29 +1167,31 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
);
} else if auth_enabled && !local_addr.ip().is_loopback() {
// Auth IS configured but the server is reachable from
- // the network on plain HTTP. The bearer token (and
- // multi-user per-user tokens from `ai-memory user
- // add`) ride cleartext — sniffable on the LAN. Advise
- // the operator to front with a TLS proxy. One-shot
- // log at startup, not refusal to serve (operators may
- // be testing, behind their own proxy already, etc.).
+ // the network on plain HTTP. Machine bearer credentials
+ // ride cleartext — sniffable on the LAN. Advise the
+ // operator to front with a TLS proxy. One-shot log at
+ // startup, not refusal to serve (operators may be testing,
+ // behind their own proxy already, etc.).
tracing::warn!(
%local_addr,
- "AI_MEMORY_AUTH_TOKEN is set but the server is bound to a \
- non-loopback address on plain HTTP — bearer tokens travel \
+ "authentication is enabled but the server is bound to a \
+ non-loopback address on plain HTTP — bearer credentials travel \
cleartext on the network. Front ai-memory with a TLS-terminating \
reverse proxy (Caddy, Cloudflare Tunnel, nginx). See \
docs/https-via-proxy.md for copy-paste templates."
);
}
let shutdown_cancel = cancel.clone();
- let serve_result = axum::serve(listener, router)
- .with_graceful_shutdown(async move {
- let _ = tokio::signal::ctrl_c().await;
- info!("ctrl-c received; shutting down");
- shutdown_cancel.cancel();
- })
- .await;
+ let serve_result = axum::serve(
+ listener,
+ router.into_make_service_with_connect_info::<SocketAddr>(),
+ )
+ .with_graceful_shutdown(async move {
+ let _ = tokio::signal::ctrl_c().await;
+ info!("ctrl-c received; shutting down");
+ shutdown_cancel.cancel();
+ })
+ .await;
cancel.cancel();
if let Some(task) = session_consolidation_task
&& let Err(error) = task.await
@@ -1611,20 +1904,11 @@ fn llm_retry_hint(provider: &str, model: &str, base_url: Option<&str>) -> String
command
}
-fn apply_http_layers(
- router: axum::Router,
- auth_state: Arc<AuthState>,
- allowed_hosts: Vec<String>,
-) -> axum::Router {
- router
- .layer(axum::middleware::from_fn_with_state(
- auth_state,
- require_bearer,
- ))
- .layer(axum::middleware::from_fn_with_state(
- Arc::new(allowed_hosts),
- require_allowed_host,
- ))
+fn apply_host_layer(router: axum::Router, allowed_hosts: Vec<String>) -> axum::Router {
+ router.layer(axum::middleware::from_fn_with_state(
+ Arc::new(allowed_hosts),
+ require_allowed_host,
+ ))
}
async fn require_allowed_host(
@@ -1670,12 +1954,13 @@ fn host_without_port(host: &str) -> &str {
mod tests {
use super::*;
use ai_memory_core::{
- AgentKind, NewObservation, NewSession, ObservationKind, PagePath, Sanitized, Sanitizer,
- SessionId, Tier,
+ AgentKind, ApiCredentialId, NewObservation, NewSession, NewUser, ObservationKind, PagePath,
+ Sanitized, Sanitizer, SessionId, Tier,
};
use ai_memory_llm::{ChatRequest, ChatResponse, LlmResult, SyntheticEmbedder};
use ai_memory_wiki::WritePageRequest;
use axum::http::Request;
+ use secrecy::SecretString;
use std::future::Future;
use std::pin::Pin;
use tempfile::TempDir;
@@ -1721,7 +2006,8 @@ mod tests {
bearer_token: bearer_token.map(str::to_string),
..AuthSettings::default()
};
- let result = validate_existing_users_auth(users_exist, &auth);
+ let result =
+ validate_existing_users_auth(users_exist, users_exist, false, &auth);
let should_pass =
!users_exist || (pepper_label == "present" && bearer_label == "present");
assert_eq!(
@@ -1734,6 +2020,19 @@ mod tests {
}
}
+ #[test]
+ fn native_api_key_pepper_preflight_is_independent_of_human_mode() {
+ let missing = AuthSettings::default();
+ assert!(validate_api_credential_pepper(true, &missing).is_err());
+
+ let configured = AuthSettings {
+ token_pepper: Some("pepper".into()),
+ ..AuthSettings::default()
+ };
+ assert!(validate_api_credential_pepper(true, &configured).is_ok());
+ assert!(validate_api_credential_pepper(false, &missing).is_ok());
+ }
+
#[test]
fn unauthenticated_non_loopback_http_requires_explicit_override() {
let addresses = [
@@ -1753,8 +2052,15 @@ mod tests {
// the operator overrode it.
let allowed = loopback || auth_enabled || allow_override;
assert_eq!(
- validate_http_exposure(local_addr, auth_enabled, allow_override, false)
- .is_ok(),
+ validate_http_exposure(
+ local_addr,
+ auth_enabled,
+ false,
+ false,
+ allow_override,
+ false,
+ )
+ .is_ok(),
allowed,
"address={address}, auth={auth_enabled}, override={allow_override}"
);
@@ -1763,6 +2069,23 @@ mod tests {
}
}
+ #[test]
+ fn human_auth_non_loopback_requires_secure_cookie_posture() {
+ let remote: SocketAddr = "192.168.1.90:49374".parse().unwrap();
+ assert!(validate_http_exposure(remote, true, true, false, false, false).is_err());
+ assert!(validate_http_exposure(remote, true, true, false, true, true).is_err());
+ assert_eq!(
+ validate_http_exposure(remote, true, true, true, false, false).unwrap(),
+ HttpExposure::Safe
+ );
+
+ let loopback: SocketAddr = "127.0.0.1:49374".parse().unwrap();
+ assert_eq!(
+ validate_http_exposure(loopback, true, true, false, false, false).unwrap(),
+ HttpExposure::Safe
+ );
+ }
+
/// Regression for #407. The published image binds `0.0.0.0` because that
/// is the only way `-p` publishing works, so the host-side rule above
/// refused every container started from the documented Quick Start and
@@ -1773,32 +2096,36 @@ mod tests {
// The exact Quick Start shape: no token, no override, in a container.
assert_eq!(
- validate_http_exposure(quick_start, false, false, true).expect("must not refuse"),
+ validate_http_exposure(quick_start, false, false, false, false, true)
+ .expect("must not refuse"),
HttpExposure::UndeterminedInContainer,
);
// Identical inputs on a host still refuse — the carve-out is scoped
// to the container case and does not soften the host rule.
- assert!(validate_http_exposure(quick_start, false, false, false).is_err());
+ assert!(validate_http_exposure(quick_start, false, false, false, false, false).is_err());
- // A container is not a blanket downgrade: with auth configured the
- // verdict is Safe, so the operator gets no spurious warning.
+ // A container is not a blanket downgrade: with machine auth configured
+ // the verdict is Safe, so the operator gets no spurious warning.
assert_eq!(
- validate_http_exposure(quick_start, true, false, true).expect("auth is fine"),
+ validate_http_exposure(quick_start, true, false, false, false, true)
+ .expect("auth is fine"),
HttpExposure::Safe,
);
// An explicit override still reports as an override, not as the
// container case, so the startup log keeps naming the real reason.
assert_eq!(
- validate_http_exposure(quick_start, false, true, true).expect("override is fine"),
+ validate_http_exposure(quick_start, false, false, false, true, true)
+ .expect("override is fine"),
HttpExposure::InsecureByOverride,
);
// Loopback inside a container is plain Safe.
let loopback: SocketAddr = "127.0.0.1:49374".parse().expect("valid test address");
assert_eq!(
- validate_http_exposure(loopback, false, false, true).expect("loopback is fine"),
+ validate_http_exposure(loopback, false, false, false, false, true)
+ .expect("loopback is fine"),
HttpExposure::Safe,
);
}
@@ -2776,13 +3103,22 @@ mod tests {
validate_web_ui_args(true, Some(ui.path())).unwrap();
}
+ #[test]
+ fn human_mode_does_not_require_root_bearer() {
+ let auth = AuthSettings {
+ token_pepper: Some("pepper".into()),
+ bearer_token: None,
+ ..AuthSettings::default()
+ };
+ assert!(validate_existing_users_auth(true, false, true, &auth).is_ok());
+ }
+
#[tokio::test]
async fn web_routes_are_inside_auth_layer() {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path()).unwrap();
let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
- let router = mount_web_router(
- axum::Router::new(),
+ let web = split_web_routers(
true,
store.reader.clone(),
wiki,
@@ -2795,9 +3131,12 @@ mod tests {
},
)
.unwrap();
- let router = apply_http_layers(
- router,
- Arc::new(AuthState::new(Some("secret".to_string()))),
+ let auth = Arc::new(AuthState::new(Some("secret".to_string())));
+ let router = apply_host_layer(
+ web.protected.layer(axum::middleware::from_fn_with_state(
+ auth,
+ require_dual_auth,
+ )),
vec!["localhost".to_string()],
);
@@ -2815,6 +3154,205 @@ mod tests {
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
+ #[tokio::test]
+ async fn custom_spa_is_public_while_api_stays_authenticated() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let ui = TempDir::new().unwrap();
+ std::fs::write(
+ ui.path().join("index.html"),
+ "<html><body>spa</body></html>",
+ )
+ .unwrap();
+ let web = split_web_routers(
+ true,
+ store.reader.clone(),
+ wiki,
+ WebMountSpec {
+ web_ui_dir: Some(ui.path()),
+ cors_origins: &[],
+ web_slug: "/web",
+ base_href: "/web/",
+ base_path: "",
+ },
+ )
+ .unwrap();
+ let auth = Arc::new(AuthState::new(Some("secret".to_string())));
+ let router = apply_host_layer(
+ web.public
+ .merge(web.protected.layer(axum::middleware::from_fn_with_state(
+ auth,
+ require_dual_auth,
+ ))),
+ vec!["localhost".to_string()],
+ );
+
+ let spa = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/web")
+ .header("Host", "localhost")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(spa.status(), StatusCode::OK);
+
+ let api = router
+ .oneshot(
+ Request::builder()
+ .uri("/api/v1/projects")
+ .header("Host", "localhost")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(api.status(), StatusCode::UNAUTHORIZED);
+ }
+
+ #[tokio::test]
+ async fn custom_spa_root_fallback_preserves_host_owned_routes() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let ui = TempDir::new().unwrap();
+ std::fs::write(
+ ui.path().join("index.html"),
+ "<html><head></head><body>root spa shell</body></html>",
+ )
+ .unwrap();
+ let web = split_web_routers(
+ true,
+ store.reader.clone(),
+ wiki,
+ WebMountSpec {
+ web_ui_dir: Some(ui.path()),
+ cors_origins: &[],
+ web_slug: "/",
+ base_href: "/",
+ base_path: "",
+ },
+ )
+ .unwrap();
+
+ let mut protected_host = axum::Router::new();
+ for path in [
+ "/admin/status",
+ "/mcp",
+ "/hook",
+ "/handoff",
+ "/workstream/runs",
+ ] {
+ protected_host = protected_host.route(
+ path,
+ axum::routing::any(|| async { StatusCode::UNAUTHORIZED }),
+ );
+ }
+ let public_auth = axum::Router::new().route(
+ "/auth/login",
+ axum::routing::post(|| async { StatusCode::NO_CONTENT }),
+ );
+ let auth = Arc::new(AuthState::new(Some("secret".to_string())));
+ let router = protected_host
+ .merge(public_auth)
+ .merge(web.protected.layer(axum::middleware::from_fn_with_state(
+ auth,
+ require_dual_auth,
+ )))
+ .merge(web.public)
+ .merge(ai_memory_web::favicon_router());
+
+ // Mutation captured: dropping any host-owned route merge lets the root SPA
+ // wildcard return its HTML shell instead of the reserved route response.
+ for (method, path) in [
+ (axum::http::Method::GET, "/admin/status"),
+ (axum::http::Method::POST, "/mcp"),
+ (axum::http::Method::POST, "/hook"),
+ (axum::http::Method::GET, "/handoff"),
+ (axum::http::Method::POST, "/workstream/runs"),
+ ] {
+ let response = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method(method)
+ .uri(path)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.status(),
+ StatusCode::UNAUTHORIZED,
+ "{path} must reach its authenticated host route"
+ );
+ }
+
+ let api = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/api/v1/projects")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(api.status(), StatusCode::UNAUTHORIZED);
+
+ let auth = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method(axum::http::Method::POST)
+ .uri("/auth/login")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(auth.status(), StatusCode::NO_CONTENT);
+
+ let favicon = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/favicon.ico")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(favicon.status(), StatusCode::OK);
+ assert_eq!(
+ favicon.headers().get(header::CONTENT_TYPE),
+ Some(&header::HeaderValue::from_static("image/png"))
+ );
+
+ let shell = router
+ .oneshot(
+ Request::builder()
+ .uri("/login")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(shell.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(shell.into_body(), 4096).await.unwrap();
+ assert!(
+ std::str::from_utf8(&body)
+ .unwrap()
+ .contains("root spa shell"),
+ "/login must still use the root SPA fallback"
+ );
+ }
+
#[tokio::test]
async fn reranker_without_llm_provider_fails_server_setup() {
let tmp = TempDir::new().unwrap();
@@ -2912,6 +3450,301 @@ mod tests {
);
}
+ #[test]
+ fn human_auth_intended_from_bootstrap_password_or_recovery() {
+ let empty = AuthSettings::default();
+ assert!(!human_auth_intended(&empty, false, false));
+ assert!(human_auth_intended(&empty, true, false));
+ assert!(human_auth_intended(&empty, false, true));
+ let recovery = AuthSettings {
+ recovery_token: Some(SecretString::from("break-glass-recovery-token-32chr")),
+ ..AuthSettings::default()
+ };
+ assert!(human_auth_intended(&recovery, false, false));
+ let initial = AuthSettings {
+ initial_root_password: Some(SecretString::from("twelve-chars!!")),
+ ..AuthSettings::default()
+ };
+ assert!(human_auth_intended(&initial, false, false));
+ }
+
+ #[test]
+ fn human_mode_fails_closed_without_recoverable_root_or_recovery() {
+ let err = require_recoverable_root_or_recovery(true, 0, false).unwrap_err();
+ assert!(err.to_string().contains("no recoverable root"));
+ require_recoverable_root_or_recovery(true, 0, true).unwrap();
+ require_recoverable_root_or_recovery(true, 1, false).unwrap();
+ require_recoverable_root_or_recovery(false, 0, false).unwrap();
+ }
+
+ #[tokio::test]
+ async fn maybe_bootstrap_root_is_one_shot() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let first = AuthSettings {
+ initial_root_password: Some(SecretString::from("twelve-chars!!")),
+ ..AuthSettings::default()
+ };
+ maybe_bootstrap_root(&store, &first).await.unwrap();
+ assert!(store.reader.bootstrap_completed().await.unwrap());
+ assert_eq!(store.reader.count_recoverable_roots().await.unwrap(), 1);
+ let second = AuthSettings {
+ initial_root_password: Some(SecretString::from("different-pass!!")),
+ ..AuthSettings::default()
+ };
+ maybe_bootstrap_root(&store, &second).await.unwrap();
+ let login = store
+ .reader
+ .find_login_user_by_username("root".into())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(
+ ai_memory_store::password::verify_password(
+ "twelve-chars!!".into(),
+ login.password_hash.clone().unwrap(),
+ )
+ .await
+ .unwrap()
+ );
+ assert!(
+ !ai_memory_store::password::verify_password(
+ "different-pass!!".into(),
+ login.password_hash.unwrap(),
+ )
+ .await
+ .unwrap()
+ );
+ }
+
+ #[tokio::test]
+ async fn maybe_bootstrap_root_fails_closed_on_api_credential_collision() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let mut user = NewUser {
+ username: "legacy".into(),
+ name: None,
+ email: None,
+ };
+ user.validate().unwrap();
+ let user_id = store
+ .writer
+ .create_human_user(user, ai_memory_core::UserRole::User, None, false)
+ .await
+ .unwrap();
+ let pepper = TokenPepper::new("pepper");
+ let password = "twelve-chars!!";
+ store
+ .writer
+ .create_api_credential(
+ ApiCredentialId::new(),
+ user_id,
+ "legacy".into(),
+ hash_token(password, &pepper),
+ None,
+ )
+ .await
+ .unwrap();
+ let auth = AuthSettings {
+ token_pepper: Some("pepper".into()),
+ initial_root_password: Some(SecretString::from(password)),
+ ..AuthSettings::default()
+ };
+ let err = maybe_bootstrap_root(&store, &auth).await.unwrap_err();
+ assert!(
+ err.to_string()
+ .contains("collides with an existing API credential"),
+ "{err}"
+ );
+ assert!(!store.reader.bootstrap_completed().await.unwrap());
+
+ let state =
+ AuthState::new(None).with_multiuser(pepper, store.reader.clone(), store.writer.clone());
+ let mut machine_request = Request::builder()
+ .header("authorization", format!("Bearer {password}"))
+ .body(Body::empty())
+ .unwrap();
+ assert!(matches!(
+ ai_memory_mcp::auth::authenticate_bearer(&state, &mut machine_request)
+ .await
+ .unwrap(),
+ ai_memory_mcp::auth::BearerAuth::Authenticated
+ ));
+ assert_eq!(
+ machine_request
+ .extensions()
+ .get::<ai_memory_core::AuthLevel>(),
+ Some(&ai_memory_core::AuthLevel::User)
+ );
+
+ let login = public_auth_router(Arc::new(state))
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/auth/login")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ serde_json::json!({
+ "username": "legacy",
+ "password": password,
+ })
+ .to_string(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(login.status(), StatusCode::UNAUTHORIZED);
+ }
+
+ #[tokio::test]
+ async fn internal_session_introspect_is_inside_host_guard_not_require_bearer() {
+ let state = std::sync::Arc::new(
+ AuthState::new(Some("root-bearer".into()))
+ .with_trusted_proxy_bearer("proxy-bearer-token"),
+ );
+ let router = apply_host_layer(internal_auth_router(state), vec!["memory.example".into()]);
+ let body = Body::from(r#"{"session":"","method":"GET"}"#);
+
+ let missing_host = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/internal/auth/session-introspect")
+ .header("authorization", "Bearer proxy-bearer-token")
+ .header("content-type", "application/json")
+ .body(body)
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(missing_host.status(), StatusCode::BAD_REQUEST);
+ let text = String::from_utf8(
+ axum::body::to_bytes(missing_host.into_body(), 4096)
+ .await
+ .unwrap()
+ .to_vec(),
+ )
+ .unwrap();
+ assert!(text.contains("missing Host"), "{text}");
+
+ let bad_host = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/internal/auth/session-introspect")
+ .header("Host", "evil.example")
+ .header("authorization", "Bearer proxy-bearer-token")
+ .header("content-type", "application/json")
+ .body(Body::from(r#"{"session":"","method":"GET"}"#))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(bad_host.status(), StatusCode::FORBIDDEN);
+
+ let allowed = router
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/internal/auth/session-introspect")
+ .header("Host", "memory.example")
+ .header("authorization", "Bearer proxy-bearer-token")
+ .header("content-type", "application/json")
+ .body(Body::from(r#"{"session":"","method":"GET"}"#))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(allowed.status(), StatusCode::OK);
+ let json: serde_json::Value = serde_json::from_slice(
+ &axum::body::to_bytes(allowed.into_body(), 4096)
+ .await
+ .unwrap(),
+ )
+ .unwrap();
+ assert_eq!(json["authenticated"], false);
+ let body_text = json.to_string();
+ assert!(
+ !body_text.contains("X-Memory-Actor"),
+ "proxy bearer without actor headers must reach introspect, not MissingIdentity: {body_text}"
+ );
+ }
+
+ #[tokio::test]
+ async fn configured_authority_secrets_cannot_match_api_credentials() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let mut user = NewUser {
+ username: "legacy".into(),
+ name: None,
+ email: None,
+ };
+ user.validate().unwrap();
+ let user_id = store
+ .writer
+ .create_human_user(user, ai_memory_core::UserRole::User, None, false)
+ .await
+ .unwrap();
+ let pepper = TokenPepper::new("pepper");
+ let secret = "configured-authority-collision-32chars";
+ store
+ .writer
+ .create_api_credential(
+ ApiCredentialId::new(),
+ user_id,
+ "legacy".into(),
+ hash_token(secret, &pepper),
+ None,
+ )
+ .await
+ .unwrap();
+
+ let cases = [
+ AuthSettings {
+ token_pepper: Some("pepper".into()),
+ bearer_token: Some(secret.into()),
+ ..AuthSettings::default()
+ },
+ AuthSettings {
+ token_pepper: Some("pepper".into()),
+ actor_proxy_bearer_token: Some(secret.into()),
+ ..AuthSettings::default()
+ },
+ AuthSettings {
+ token_pepper: Some("pepper".into()),
+ recovery_token: Some(SecretString::from(secret)),
+ ..AuthSettings::default()
+ },
+ ];
+ for auth in cases {
+ let err = validate_configured_secret_collisions(&store, &auth, false)
+ .await
+ .unwrap_err();
+ assert!(
+ err.to_string()
+ .contains("collides with an existing API credential")
+ );
+ assert!(!err.to_string().contains(secret));
+ }
+
+ let ignored_initial = AuthSettings {
+ token_pepper: Some("pepper".into()),
+ initial_root_password: Some(SecretString::from(secret)),
+ ..AuthSettings::default()
+ };
+ validate_configured_secret_collisions(&store, &ignored_initial, false)
+ .await
+ .unwrap();
+ assert!(
+ validate_configured_secret_collisions(&store, &ignored_initial, true)
+ .await
+ .is_err()
+ );
+ }
+
// ── Part B: CORS validation tests ──────────────────────────────────────
#[test]
diff --git a/crates/ai-memory-cli/src/commands/user.rs b/crates/ai-memory-cli/src/commands/user.rs
index 9f15195b..34f33f3c 100644
--- a/crates/ai-memory-cli/src/commands/user.rs
+++ b/crates/ai-memory-cli/src/commands/user.rs
@@ -1,18 +1,7 @@
-//! `ai-memory user` — manage registered users for multi-user attribution.
+//! `ai-memory user` — manage compatibility tokens and human password login.
//!
-//! Thin HTTP client over the admin endpoints in
-//! `ai-memory-mcp::admin::handle_{create,list,expire,revive,
-//! rotate_token}_user`. Per invariant #16 (CLI is always a thin HTTP
-//! client) the CLI never opens the store; everything routes through
-//! `/admin/users/*`. The caller's bearer token must authenticate as
-//! root or the server returns 403 (User tier) / 401 (Anonymous).
-//!
-//! Backward compatibility: every install that predates v0.8 lacks the
-//! `[auth].token_pepper` field. The server's user-management routes
-//! 503 in that case with `multi-user not enabled (set
-//! [auth].token_pepper in config or run `ai-memory init`)`. Existing
-//! single-user installs see that error only if they actively try to
-//! use these subcommands — the rest of the CLI keeps working.
+//! Thin HTTP client over `/admin/users*`. The caller's bearer token must
+//! authenticate as root. Single-token commands remain deprecated 1.x shims.
use std::io::{self, BufRead, Write};
@@ -20,16 +9,13 @@ use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use crate::cli::{
- UserAddArgs, UserArgs, UserCommand, UserExpireArgs, UserListArgs, UserReviveArgs,
+ UserAddArgs, UserAddHumanArgs, UserArgs, UserCommand, UserDisableArgs, UserEnableArgs,
+ UserExpireArgs, UserListArgs, UserPatchArgs, UserResetPasswordArgs, UserReviveArgs,
UserRotateTokenArgs,
};
use crate::config::Config;
-use crate::http_client::{ServerEndpoint, get_json, post_json};
+use crate::http_client::{ServerEndpoint, get_json, patch_json, post_json};
-/// Mirrors `ai_memory_core::User` on the server side. Repeated here
-/// rather than imported to keep the CLI <-> server contract explicit
-/// at the deserialisation boundary (the CLI tolerates a future server
-/// that adds fields without a recompile).
#[derive(Debug, Deserialize, Serialize)]
struct UserRow {
id: String,
@@ -43,11 +29,29 @@ struct UserRow {
last_seen_at: Option<i64>,
#[serde(default)]
token_expired_at: Option<i64>,
+ #[serde(default)]
+ role: String,
+ #[serde(default)]
+ must_change_password: bool,
+ #[serde(default)]
+ disabled_at: Option<i64>,
+ #[serde(default)]
+ has_password: bool,
}
impl UserRow {
- fn is_token_active(&self) -> bool {
- self.token_expired_at.is_none()
+ fn status(&self) -> &'static str {
+ if self.disabled_at.is_some() {
+ "disabled"
+ } else if self.has_password && self.must_change_password {
+ "must-change"
+ } else if self.has_password {
+ "active"
+ } else if self.token_expired_at.is_some() {
+ "expired"
+ } else {
+ "active"
+ }
}
}
@@ -57,6 +61,17 @@ struct UserWithToken {
token: String,
}
+#[derive(Debug, Deserialize)]
+struct UserWithPassword {
+ user: UserRow,
+ temporary_password: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct UserResponse {
+ user: UserRow,
+}
+
#[derive(Debug, Deserialize)]
struct UserList {
users: Vec<UserRow>,
@@ -71,10 +86,15 @@ pub async fn run(config: &Config, args: UserArgs) -> Result<()> {
let ep = ServerEndpoint::from_config_resolving_auth(config).await;
match args.command {
UserCommand::Add(args) => add(&ep, args).await,
+ UserCommand::AddHuman(args) => add_human(&ep, args).await,
UserCommand::List(args) => list(&ep, args).await,
UserCommand::Expire(args) => expire(&ep, args).await,
UserCommand::Revive(args) => revive(&ep, args).await,
UserCommand::RotateToken(args) => rotate_token(&ep, args).await,
+ UserCommand::ResetPassword(args) => reset_password(&ep, args).await,
+ UserCommand::Disable(args) => disable(&ep, args).await,
+ UserCommand::Enable(args) => enable(&ep, args).await,
+ UserCommand::Patch(args) => patch(&ep, args).await,
}
}
@@ -85,6 +105,8 @@ struct CreateUserBody<'a> {
name: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
email: Option<&'a str>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ role: Option<&'a str>,
}
async fn add(ep: &ServerEndpoint, args: UserAddArgs) -> Result<()> {
@@ -100,39 +122,38 @@ async fn add(ep: &ServerEndpoint, args: UserAddArgs) -> Result<()> {
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty()),
+ role: None,
};
let resp: UserWithToken = post_json(ep, "/admin/users", &body)
.await
- .context("creating user")?;
- if args.json {
- println!(
- "{}",
- serde_json::to_string_pretty(&serde_json::json!({
- "user": &resp.user,
- "token": &resp.token
- }))?
- );
- } else {
- let mut stderr = io::stderr().lock();
- let _ = writeln!(stderr, "✓ created user '{}'", resp.user.username);
- if let Some(name) = &resp.user.name {
- let _ = writeln!(stderr, " name: {name}");
- }
- if let Some(email) = &resp.user.email {
- let _ = writeln!(stderr, " email: {email}");
- }
- let _ = writeln!(
- stderr,
- " id: {}\n\n\
- Store this token now — it will NOT be shown again. \
- Only its SHA-256 digest is kept in the DB.",
- resp.user.id
- );
- // Token on stdout so it can be piped (`> ~/.config/...`) without
- // the surrounding human chrome.
- println!("{}", resp.token);
- }
- Ok(())
+ .context("creating compatibility user")?;
+ print_token(&resp, args.json, "created")
+}
+
+async fn add_human(ep: &ServerEndpoint, args: UserAddHumanArgs) -> Result<()> {
+ let role = args
+ .role
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty());
+ let body = CreateUserBody {
+ username: args.username.trim(),
+ name: args
+ .name
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty()),
+ email: args
+ .email
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty()),
+ role,
+ };
+ let resp: UserWithPassword = post_json(ep, "/admin/human-users", &body)
+ .await
+ .context("creating human user")?;
+ print_temp_password(&resp, args.json, "created")
}
async fn list(ep: &ServerEndpoint, args: UserListArgs) -> Result<()> {
@@ -147,8 +168,6 @@ async fn list(ep: &ServerEndpoint, args: UserListArgs) -> Result<()> {
println!("(no registered users)");
return Ok(());
}
- // Fixed-width table — usernames are validated ≤ 64 chars in core,
- // but most are short, so right-pad to the longest in this batch.
let user_w = resp
.users
.iter()
@@ -163,39 +182,34 @@ async fn list(ep: &ServerEndpoint, args: UserListArgs) -> Result<()> {
.max()
.unwrap_or(4)
.max(4);
- let email_w = resp
+ let role_w = resp
.users
.iter()
- .filter_map(|u| u.email.as_ref().map(String::len))
+ .map(|u| u.role.len())
.max()
- .unwrap_or(5)
- .max(5);
+ .unwrap_or(4)
+ .max(4);
println!(
- "{:<user_w$} {:<name_w$} {:<email_w$} {:<8}",
+ "{:<user_w$} {:<name_w$} {:<role_w$} {:<12}",
"USERNAME",
"NAME",
- "EMAIL",
+ "ROLE",
"STATUS",
user_w = user_w,
name_w = name_w,
- email_w = email_w,
+ role_w = role_w,
);
for u in &resp.users {
- let status = if u.is_token_active() {
- "active"
- } else {
- "expired"
- };
println!(
- "{:<user_w$} {:<name_w$} {:<email_w$} {:<8}",
+ "{:<user_w$} {:<name_w$} {:<role_w$} {:<12}",
u.username,
u.name.as_deref().unwrap_or("-"),
- u.email.as_deref().unwrap_or("-"),
- status,
+ u.role,
+ u.status(),
user_w = user_w,
name_w = name_w,
- email_w = email_w,
+ role_w = role_w,
);
}
Ok(())
@@ -209,20 +223,18 @@ async fn expire(ep: &ServerEndpoint, args: UserExpireArgs) -> Result<()> {
))?;
}
let path = format!("/admin/users/{}/expire", url_encode(&args.username));
- // The server returns `{ user: UserRow }` but the CLI only needs to
- // confirm a 2xx; ignore the payload.
- let _: serde_json::Value = post_json(ep, &path, &serde_json::json!({}))
+ let _: UserResponse = post_json(ep, &path, &serde_json::json!({}))
.await
- .context("expiring user")?;
+ .context("expiring user token")?;
println!("✓ expired token for user '{}'", args.username);
Ok(())
}
async fn revive(ep: &ServerEndpoint, args: UserReviveArgs) -> Result<()> {
let path = format!("/admin/users/{}/revive", url_encode(&args.username));
- let _: serde_json::Value = post_json(ep, &path, &serde_json::json!({}))
+ let _: UserResponse = post_json(ep, &path, &serde_json::json!({}))
.await
- .context("reviving user")?;
+ .context("reviving user token")?;
println!("✓ revived token for user '{}'", args.username);
Ok(())
}
@@ -230,8 +242,7 @@ async fn revive(ep: &ServerEndpoint, args: UserReviveArgs) -> Result<()> {
async fn rotate_token(ep: &ServerEndpoint, args: UserRotateTokenArgs) -> Result<()> {
if !args.yes {
confirm(&format!(
- "Rotate token for user '{}'? Any existing client using the old token will \
- start getting 401 immediately. (y/N) ",
+ "Rotate token for user '{}'? Existing clients will start getting 401 immediately. (y/N) ",
args.username
))?;
}
@@ -239,7 +250,98 @@ async fn rotate_token(ep: &ServerEndpoint, args: UserRotateTokenArgs) -> Result<
let resp: UserWithToken = post_json(ep, &path, &serde_json::json!({}))
.await
.context("rotating user token")?;
+ print_token(&resp, args.json, "rotated token for")
+}
+
+async fn reset_password(ep: &ServerEndpoint, args: UserResetPasswordArgs) -> Result<()> {
+ if !args.yes {
+ confirm(&format!(
+ "Reset password for user '{}'? Their current password stops working immediately. (y/N) ",
+ args.username
+ ))?;
+ }
+ let path = format!("/admin/users/{}/reset-password", url_encode(&args.username));
+ let resp: UserWithPassword = post_json(ep, &path, &serde_json::json!({}))
+ .await
+ .context("resetting password")?;
+ print_temp_password(&resp, args.json, "reset password for")
+}
+
+async fn disable(ep: &ServerEndpoint, args: UserDisableArgs) -> Result<()> {
+ if !args.yes {
+ confirm(&format!(
+ "Disable human login for user '{}'? (y/N) ",
+ args.username
+ ))?;
+ }
+ let path = format!("/admin/users/{}/disable", url_encode(&args.username));
+ let _: UserResponse = post_json(ep, &path, &serde_json::json!({}))
+ .await
+ .context("disabling user")?;
+ println!("✓ disabled user '{}'", args.username);
+ Ok(())
+}
+
+async fn enable(ep: &ServerEndpoint, args: UserEnableArgs) -> Result<()> {
+ let path = format!("/admin/users/{}/enable", url_encode(&args.username));
+ let _: UserResponse = post_json(ep, &path, &serde_json::json!({}))
+ .await
+ .context("enabling user")?;
+ println!("✓ enabled user '{}'", args.username);
+ Ok(())
+}
+
+#[derive(Debug, Serialize)]
+struct PatchUserBody {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ name: Option<Option<String>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ email: Option<Option<String>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ role: Option<String>,
+}
+
+async fn patch(ep: &ServerEndpoint, args: UserPatchArgs) -> Result<()> {
+ let body = PatchUserBody {
+ name: args.name.map(|s| {
+ let trimmed = s.trim().to_string();
+ if trimmed.is_empty() {
+ None
+ } else {
+ Some(trimmed)
+ }
+ }),
+ email: args.email.map(|s| {
+ let trimmed = s.trim().to_string();
+ if trimmed.is_empty() {
+ None
+ } else {
+ Some(trimmed)
+ }
+ }),
+ role: args
+ .role
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty()),
+ };
+ let path = format!("/admin/users/{}", url_encode(&args.username));
+ let resp: UserResponse = patch_json(ep, &path, &body)
+ .await
+ .context("patching user")?;
if args.json {
+ println!("{}", serde_json::to_string_pretty(&resp.user)?);
+ } else {
+ println!(
+ "✓ updated user '{}' ({})",
+ resp.user.username,
+ resp.user.status()
+ );
+ }
+ Ok(())
+}
+
+fn print_token(resp: &UserWithToken, json: bool, verb: &str) -> Result<()> {
+ if json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
@@ -251,8 +353,7 @@ async fn rotate_token(ep: &ServerEndpoint, args: UserRotateTokenArgs) -> Result<
let mut stderr = io::stderr().lock();
let _ = writeln!(
stderr,
- "✓ rotated token for user '{}'\n\n\
- Store this token now — it will NOT be shown again.",
+ "✓ {verb} user '{}'\n\nStore this token now — it will NOT be shown again.",
resp.user.username
);
println!("{}", resp.token);
@@ -260,8 +361,36 @@ async fn rotate_token(ep: &ServerEndpoint, args: UserRotateTokenArgs) -> Result<
Ok(())
}
-/// Lightweight interactive y/N prompt. Reads from stdin; an empty
-/// reply, EOF, or anything starting with `n`/`N` aborts.
+fn print_temp_password(resp: &UserWithPassword, json: bool, verb: &str) -> Result<()> {
+ if json {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&serde_json::json!({
+ "user": &resp.user,
+ "temporary_password": &resp.temporary_password
+ }))?
+ );
+ } else {
+ let mut stderr = io::stderr().lock();
+ let _ = writeln!(stderr, "✓ {verb} user '{}'", resp.user.username);
+ if let Some(name) = &resp.user.name {
+ let _ = writeln!(stderr, " name: {name}");
+ }
+ if let Some(email) = &resp.user.email {
+ let _ = writeln!(stderr, " email: {email}");
+ }
+ let _ = writeln!(
+ stderr,
+ " role: {}\n\n\
+ Store this temporary password now — it will NOT be shown again. \
+ The user must change it on next login.",
+ resp.user.role
+ );
+ println!("{}", resp.temporary_password);
+ }
+ Ok(())
+}
+
fn confirm(prompt: &str) -> Result<()> {
let mut stderr = io::stderr().lock();
let _ = write!(stderr, "{prompt}");
@@ -280,11 +409,6 @@ fn confirm(prompt: &str) -> Result<()> {
Ok(())
}
-/// Percent-encode a username for URL-path use. The validation in
-/// `core::user::validate_username` already excludes whitespace and the
-/// common path separators (`/ \ : ; ,`), and emails-as-usernames
-/// (`alice@home`) carry `@` which is reserved in paths. Conservative
-/// encode: anything that isn't alphanumeric / `-_.` becomes `%XX`.
fn url_encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for &b in s.as_bytes() {
@@ -311,29 +435,7 @@ mod tests {
#[test]
fn url_encode_percent_encodes_at_and_other_specials() {
assert_eq!(url_encode("alice@home"), "alice%40home");
- // Validation forbids these but the encoder must still be safe
- // if a future relaxation lets them through.
assert_eq!(url_encode("a/b"), "a%2Fb");
assert_eq!(url_encode("a b"), "a%20b");
}
-
- #[test]
- fn user_row_active_status_reflects_token_expired_at() {
- let active = UserRow {
- id: "x".into(),
- username: "alice".into(),
- name: None,
- email: None,
- created_at: 0,
- last_seen_at: None,
- token_expired_at: None,
- };
- assert!(active.is_token_active());
-
- let expired = UserRow {
- token_expired_at: Some(123),
- ..active
- };
- assert!(!expired.is_token_active());
- }
}
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index 47638b01..96bd8704 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -17,7 +17,7 @@ use figment::{
Figment,
providers::{Env, Format, Serialized, Toml},
};
-use secrecy::SecretString;
+use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Serialize};
/// Default HTTP bind address for the local single-user server.
@@ -470,9 +470,9 @@ pub struct AuthSettings {
/// `Authorization: Bearer <token>`. Generate one with
/// `ai-memory generate-auth-token`.
pub bearer_token: Option<String>,
- /// Mark the browser session cookie `Secure`. Enable this only when a
- /// trusted reverse proxy terminates HTTPS for `/web`; direct HTTP browsers
- /// deliberately will not send a Secure cookie.
+ /// Mark the browser session cookie `Secure`. Human authentication on a
+ /// non-loopback listener requires this explicit HTTPS reverse-proxy
+ /// posture. It may be false only for direct loopback smoke/development.
pub secure_cookie: bool,
/// Username attributed to writes authenticated by the bearer
/// token (rung 1: "identified single-user"). When set, the
@@ -499,12 +499,11 @@ pub struct AuthSettings {
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.
+ /// `api_credentials.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. It enables DB-user
- /// token resolution even during first-user bootstrap; operational admin
- /// access becomes root-only once a user row exists.
+ /// hex-encoded). MUST NOT change after the first native API key is
+ /// added — rotating it invalidates every existing native key. Human
+ /// passwords and sessions do not use this pepper.
pub token_pepper: Option<String>,
/// Dedicated bearer token for a trusted authenticating proxy, allowing it
/// to name the real end user in `X-Memory-Actor-*` headers.
@@ -516,6 +515,21 @@ pub struct AuthSettings {
///
/// Only set this when the server is reachable *only* through that proxy.
pub actor_proxy_bearer_token: Option<String>,
+ /// One-shot greenfield root password. Consumed when
+ /// `human_auth_state.bootstrap_completed` is false, then ignored forever.
+ /// Set with `AI_MEMORY_AUTH__INITIAL_ROOT_PASSWORD`.
+ #[serde(skip_serializing)]
+ pub initial_root_password: Option<SecretString>,
+ /// Break-glass recovery secret for `POST /auth/recovery`. Compared
+ /// constant-time; never stored in SQLite. Set with
+ /// `AI_MEMORY_AUTH__RECOVERY_TOKEN`.
+ #[serde(skip_serializing)]
+ pub recovery_token: Option<SecretString>,
+ /// CIDRs allowed to supply `X-Forwarded-For` for login rate limiting.
+ /// Bare addresses are treated as `/32` or `/128`. Set with
+ /// `AI_MEMORY_AUTH__TRUSTED_PROXY_CIDRS`.
+ #[serde(default, deserialize_with = "deserialize_string_or_vec")]
+ pub trusted_proxy_cidrs: Vec<String>,
}
impl std::fmt::Debug for AuthSettings {
@@ -539,6 +553,15 @@ impl std::fmt::Debug for AuthSettings {
"actor_proxy_bearer_token",
&self.actor_proxy_bearer_token.as_ref().map(|_| "<redacted>"),
)
+ .field(
+ "initial_root_password",
+ &self.initial_root_password.as_ref().map(|_| "<redacted>"),
+ )
+ .field(
+ "recovery_token",
+ &self.recovery_token.as_ref().map(|_| "<redacted>"),
+ )
+ .field("trusted_proxy_cidrs", &self.trusted_proxy_cidrs)
.finish()
}
}
@@ -993,6 +1016,8 @@ impl Config {
);
}
+ validate_auth_secrets(&config.auth)?;
+
Ok(config)
}
@@ -1313,6 +1338,48 @@ fn env_secret(name: &str) -> Option<SecretString> {
env_string(name).map(SecretString::from)
}
+fn non_empty_secret(secret: Option<&SecretString>) -> Option<&str> {
+ non_empty(secret.map(ExposeSecret::expose_secret))
+}
+
+/// Reject equal configured secrets without logging their values.
+fn validate_auth_secrets(auth: &AuthSettings) -> Result<()> {
+ let mut named: Vec<(&str, &str)> = Vec::new();
+ if let Some(v) = non_empty(auth.bearer_token.as_deref()) {
+ named.push(("[auth].bearer_token", v));
+ }
+ if let Some(v) = non_empty(auth.actor_proxy_bearer_token.as_deref()) {
+ named.push(("[auth].actor_proxy_bearer_token", v));
+ }
+ if let Some(v) = non_empty_secret(auth.recovery_token.as_ref()) {
+ if v.len() < 32 {
+ anyhow::bail!("[auth].recovery_token must be at least 32 characters");
+ }
+ if v.starts_with(ai_memory_core::SESSION_SECRET_PREFIX)
+ || v.starts_with(ai_memory_core::NATIVE_API_KEY_PREFIX)
+ || v.starts_with(ai_memory_core::EXTERNAL_API_KEY_PREFIX)
+ {
+ anyhow::bail!("[auth].recovery_token must not use a reserved credential prefix");
+ }
+ named.push(("[auth].recovery_token", v));
+ }
+ if let Some(v) = non_empty_secret(auth.initial_root_password.as_ref()) {
+ named.push(("[auth].initial_root_password", v));
+ }
+ for i in 0..named.len() {
+ for j in (i + 1)..named.len() {
+ if named[i].1 == named[j].1 {
+ anyhow::bail!(
+ "{} must differ from {}; reuse would collapse credential classes",
+ named[i].0,
+ named[j].0
+ );
+ }
+ }
+ }
+ Ok(())
+}
+
fn non_empty(s: Option<&str>) -> Option<&str> {
s.map(str::trim).filter(|s| !s.is_empty())
}
@@ -1351,7 +1418,7 @@ fn normalize_home_dir(home: &str) -> Option<String> {
#[cfg(test)]
mod tests {
use super::*;
- use secrecy::ExposeSecret;
+ use secrecy::{ExposeSecret, SecretString};
use tempfile::TempDir;
#[test]
@@ -1361,6 +1428,8 @@ mod tests {
root_username: Some("operator".into()),
token_pepper: Some("pepper-secret-sentinel".into()),
actor_proxy_bearer_token: Some("proxy-secret-sentinel".into()),
+ initial_root_password: Some(SecretString::from("initial-password-sentinel")),
+ recovery_token: Some(SecretString::from("recovery-token-sentinel-32chars")),
..AuthSettings::default()
};
let config = Config {
@@ -1375,12 +1444,58 @@ mod tests {
"bearer-secret-sentinel",
"pepper-secret-sentinel",
"proxy-secret-sentinel",
+ "initial-password-sentinel",
+ "recovery-token-sentinel-32chars",
] {
assert!(!rendered.contains(secret), "Debug output exposed {secret}");
}
}
}
+ #[test]
+ fn validate_auth_secrets_rejects_short_recovery_token() {
+ let auth = AuthSettings {
+ recovery_token: Some(SecretString::from("too-short-recovery-token")),
+ ..AuthSettings::default()
+ };
+ let err = validate_auth_secrets(&auth).unwrap_err();
+ assert!(err.to_string().contains("32"), "{err:#}");
+ assert!(!err.to_string().contains("too-short-recovery-token"));
+ }
+
+ #[test]
+ fn validate_auth_secrets_rejects_equal_recovery_and_bearer() {
+ let secret = "this-recovery-token-is-32-chars!!";
+ let auth = AuthSettings {
+ bearer_token: Some(secret.into()),
+ recovery_token: Some(SecretString::from(secret)),
+ ..AuthSettings::default()
+ };
+ let err = validate_auth_secrets(&auth).unwrap_err();
+ assert!(err.to_string().contains("must differ"), "{err:#}");
+ }
+
+ #[test]
+ fn validate_auth_secrets_rejects_recovery_credential_prefixes() {
+ for prefix in [
+ ai_memory_core::SESSION_SECRET_PREFIX,
+ ai_memory_core::NATIVE_API_KEY_PREFIX,
+ ai_memory_core::EXTERNAL_API_KEY_PREFIX,
+ ] {
+ let auth = AuthSettings {
+ recovery_token: Some(SecretString::from(format!(
+ "{prefix}reserved-recovery-token-padding-32"
+ ))),
+ ..AuthSettings::default()
+ };
+ let err = validate_auth_secrets(&auth).unwrap_err();
+ assert!(
+ err.to_string().contains("reserved credential prefix"),
+ "{err:#}"
+ );
+ }
+ }
+
#[test]
fn defaults_have_canonical_endings() {
let cfg = Config::default();
diff --git a/crates/ai-memory-cli/src/http_client.rs b/crates/ai-memory-cli/src/http_client.rs
index 4aa1d342..c74d8261 100644
--- a/crates/ai-memory-cli/src/http_client.rs
+++ b/crates/ai-memory-cli/src/http_client.rs
@@ -237,6 +237,32 @@ pub async fn get_json<T: DeserializeOwned>(
.with_context(|| format!("parsing JSON body from GET {url}"))
}
+/// PATCH JSON body to `<endpoint>{path}`, deserialise JSON response.
+///
+/// # Errors
+/// Same as [`get_json`].
+pub async fn patch_json<B: Serialize, T: DeserializeOwned>(
+ endpoint: &ServerEndpoint,
+ path: &str,
+ body: &B,
+) -> Result<T> {
+ let client = reqwest::Client::new();
+ let url = endpoint.build_url(path);
+ let req = endpoint.authenticate(client.patch(&url).json(body));
+ let resp = req
+ .send()
+ .await
+ .map_err(|e| augment_connect_error(e, endpoint, &url))?;
+ let status = resp.status();
+ if !status.is_success() {
+ let body = resp.text().await.unwrap_or_default();
+ return Err(server_response_error(status, body));
+ }
+ resp.json::<T>()
+ .await
+ .with_context(|| format!("parsing JSON body from PATCH {url}"))
+}
+
/// POST JSON body to `<endpoint>{path}`, deserialise JSON response.
///
/// # Errors
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 34a0c2b6..837196b4 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -152,6 +152,7 @@ async fn main() -> Result<()> {
Command::Uninstall(args) => commands::uninstall::run(&config, args),
Command::Auth(args) => commands::auth::run(&config, args).await,
Command::User(args) => commands::user::run(&config, args).await,
+ Command::ApiKey(args) => commands::api_key::run(&config, args).await,
// `Completions` is handled in the fast-path above (before config/tracing).
Command::Completions(args) => commands::completions::run(args),
}
diff --git a/crates/ai-memory-cli/templates/config.default.toml b/crates/ai-memory-cli/templates/config.default.toml
index 96196301..d44dce59 100644
--- a/crates/ai-memory-cli/templates/config.default.toml
+++ b/crates/ai-memory-cli/templates/config.default.toml
@@ -225,5 +225,12 @@ mid_session = "follow-cwd"
# behind a trusted HTTPS-terminating reverse proxy, set this to true so browsers
# send the cookie only over HTTPS. Do not enable it for direct HTTP: browsers
# will not send a Secure cookie there.
+#
+# Prefer environment variables for secrets so they are not stored in this file:
+# AI_MEMORY_AUTH__INITIAL_ROOT_PASSWORD one-shot greenfield root password
+# AI_MEMORY_AUTH__RECOVERY_TOKEN break-glass (>=32 chars); never a session
+# AI_MEMORY_AUTH__TRUSTED_PROXY_CIDRS CIDRs allowed to supply X-Forwarded-For
+# Unset INITIAL_ROOT_PASSWORD after the first successful serve. Recovery only
+# resets the configured root_username via POST /auth/recovery.
[auth]
secure_cookie = false
diff --git a/crates/ai-memory-cli/tests/completions.rs b/crates/ai-memory-cli/tests/completions.rs
index 654b51b5..a81eab68 100644
--- a/crates/ai-memory-cli/tests/completions.rs
+++ b/crates/ai-memory-cli/tests/completions.rs
@@ -69,7 +69,10 @@ fn scripts_cover_subcommands_from_across_the_tree() {
"purge-project",
"move-session",
"user",
- "rotate-token",
+ "reset-password",
+ "api-key",
+ "rotate",
+ "revoke",
"auth",
"login",
] {
diff --git a/crates/ai-memory-core/src/actor.rs b/crates/ai-memory-core/src/actor.rs
index 0e8179b1..15c5dfd3 100644
--- a/crates/ai-memory-core/src/actor.rs
+++ b/crates/ai-memory-core/src/actor.rs
@@ -17,7 +17,7 @@
//! `config.auth.bearer_token`. Middleware fills `user` / `email` / `name`
//! from `[auth].root_username` / `root_email` (and optional `root_name`).
//! 3. **Identified multi-user** — bearer token matches an active
-//! `users.token_hash` row. Middleware fills the actor from the row.
+//! `api_credentials.token_hash` row. Middleware fills the actor from the owning user.
//! 4. **External auth proxy** — a trusted sidecar authenticates with the
//! dedicated proxy bearer and asserts a username or complete OIDC
//! issuer/subject pair in `X-Memory-Actor-*` headers. Proxy callers are users
diff --git a/crates/ai-memory-core/src/error.rs b/crates/ai-memory-core/src/error.rs
index 732e0a50..a7f495ed 100644
--- a/crates/ai-memory-core/src/error.rs
+++ b/crates/ai-memory-core/src/error.rs
@@ -35,6 +35,11 @@ pub enum MemoryError {
#[error("invalid email: {0}")]
InvalidEmail(String),
+ /// A human password failed [`crate::user::validate_human_password`].
+ /// The string is a generic policy message and never names the value.
+ #[error("invalid password: {0}")]
+ InvalidPassword(String),
+
/// Wraps any underlying I/O failure.
#[error(transparent)]
Io(#[from] std::io::Error),
diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rs
index b3343ecc..fe5ab6c5 100644
--- a/crates/ai-memory-core/src/ids.rs
+++ b/crates/ai-memory-core/src/ids.rs
@@ -87,6 +87,7 @@ id_newtype!(pub HandoffId, "Identifier for a cross-agent handoff record.");
id_newtype!(pub WorkstreamId, "Identifier for a managed cross-harness workstream.");
id_newtype!(pub ManagedRunId, "Identifier for one `ai-memory run` invocation.");
id_newtype!(pub UserId, "Identifier for a registered user (multi-user attribution; see [`crate::actor`]).");
+id_newtype!(pub ApiCredentialId, "Identifier for one native `aim_` API credential.");
id_newtype!(pub AutoImproveRunId, "Identifier for one auto-improvement review run.");
id_newtype!(pub AutoImproveProposalId, "Identifier for one staged auto-improvement proposal.");
id_newtype!(pub PageFeedbackId, "Identifier for one page-feedback signal (`memory_feedback`).");
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index 9a23b72d..33402ec4 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -54,9 +54,9 @@ pub use handoff::{
HandoffState, NewHandoff,
};
pub use ids::{
- AgentKind, AutoImproveProposalId, AutoImproveRunId, EntityId, HandoffId, ManagedRunId,
- ObservationId, PageFeedbackId, PageId, PagePath, ProjectId, SessionId, UserId, WorkspaceId,
- WorkstreamId,
+ AgentKind, ApiCredentialId, AutoImproveProposalId, AutoImproveRunId, EntityId, HandoffId,
+ ManagedRunId, ObservationId, PageFeedbackId, PageId, PagePath, ProjectId, SessionId, UserId,
+ WorkspaceId, WorkstreamId,
};
pub use observation::{NewObservation, NewSession, Observation, ObservationKind};
pub use page::{
@@ -72,7 +72,12 @@ pub use slots::{
SLOT_PREFIX, SlotPlacement, SlotVisibility, is_slot_named, is_slot_path, slot_owner,
slot_placement,
};
-pub use user::{MAX_EMAIL_LEN, MAX_USERNAME_LEN, NewUser, User, validate_email, validate_username};
+pub use user::{
+ ApiCredential, EXTERNAL_API_KEY_PREFIX, MAX_EMAIL_LEN, MAX_HUMAN_PASSWORD_BYTES,
+ MAX_USERNAME_LEN, MIN_HUMAN_PASSWORD_BYTES, NATIVE_API_KEY_PREFIX, NewUser,
+ SESSION_SECRET_PREFIX, User, UserRole, validate_email, validate_human_password,
+ validate_username,
+};
pub use workstream::{
FinishManagedRunRequest, FinishManagedRunResponse, LinkManagedRunRequest,
ListManagedWorkstreamsRequest, MANAGED_WORKSTREAM_PACKET_MARKER, ManagedRunContextResponse,
diff --git a/crates/ai-memory-core/src/user.rs b/crates/ai-memory-core/src/user.rs
index c8587806..3e0b07d2 100644
--- a/crates/ai-memory-core/src/user.rs
+++ b/crates/ai-memory-core/src/user.rs
@@ -11,20 +11,41 @@
//!
//! See [`crate::actor`] for the broader rationale: ai-memory's data is
//! single-tenant by design. A `User` row records *who* a write came
-//! from; it does not gate *whether* the write was allowed.
+//! from; it does not gate *whether* the write was allowed. Human
+//! `role=root` vs `role=user` only affects web-session capabilities;
+//! a native API credential always authenticates as [`crate::AuthLevel::User`].
//!
-//! ## Token storage (referenced here, implemented in `ai-memory-store`)
+//! ## Credential classes (referenced here, implemented in `ai-memory-store`)
//!
-//! Tokens are 32 bytes of CSPRNG (256 bits of entropy). The store keeps
-//! a single `SHA-256(token || ":" || pepper)` digest per user; the
-//! per-server pepper from `[auth].token_pepper` makes a DB-only theft
-//! useless to an offline attacker. SHA-256 gives an O(1) UNIQUE-index
-//! lookup the per-request auth hot path needs. See
-//! `ai_memory_store::users` for the actual hash + generate helpers.
+//! Human passwords are Argon2id PHC strings on `users.password_hash` and
+//! never authenticate as Bearer. Native machine keys are 256-bit secrets
+//! with prefix [`NATIVE_API_KEY_PREFIX`]; the store keeps
+//! `SHA-256(token || ":" || pepper)` in `api_credentials`. Web sessions
+//! use prefix [`SESSION_SECRET_PREFIX`] and store only SHA-256 of the
+//! secret (no pepper). See `ai_memory_store::users` / `api_credentials`
+//! / `web_sessions`.
use serde::{Deserialize, Serialize};
-use crate::{MemoryError, UserId};
+use crate::{ApiCredentialId, MemoryError, UserId};
+
+/// Web-session secret prefix. A human password that equals this prefix
+/// is rejected so a leaked session cookie cannot be reused as a password.
+pub const SESSION_SECRET_PREFIX: &str = "ams_";
+
+/// Native engine-issued API key prefix (`aim_…`). Distinct from the
+/// external `amk_` keys issued by mcp-auth.
+pub const NATIVE_API_KEY_PREFIX: &str = "aim_";
+
+/// External mcp-auth consumer-key prefix. Human passwords must not
+/// impersonate this class either.
+pub const EXTERNAL_API_KEY_PREFIX: &str = "amk_";
+
+/// Minimum UTF-8 byte length of a human password.
+pub const MIN_HUMAN_PASSWORD_BYTES: usize = 12;
+
+/// Maximum UTF-8 byte length of a human password.
+pub const MAX_HUMAN_PASSWORD_BYTES: usize = 1024;
/// Maximum username length. Anything longer is a misconfiguration; the
/// engine, CLI, and web UI all assume a small username fits in a single
@@ -34,8 +55,48 @@ pub const MAX_USERNAME_LEN: usize = 64;
/// Maximum email length per RFC 5321 §4.5.3.1.3 (path length).
pub const MAX_EMAIL_LEN: usize = 254;
+/// Human role stored on `users.role`. Only two values exist; a native
+/// API credential never inherits Root from this field.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum UserRole {
+ /// Console operator. A web session for this role is
+ /// [`crate::AuthLevel::Root`].
+ Root,
+ /// Default human role. Web sessions and native API keys are
+ /// [`crate::AuthLevel::User`].
+ #[default]
+ User,
+}
+
+impl UserRole {
+ /// Wire / SQL value.
+ #[must_use]
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Root => "root",
+ Self::User => "user",
+ }
+ }
+
+ /// Parse a stored `users.role` value.
+ ///
+ /// # Errors
+ /// Returns [`MemoryError::MalformedRecord`] for any other string.
+ pub fn parse(value: &str) -> Result<Self, MemoryError> {
+ match value {
+ "root" => Ok(Self::Root),
+ "user" => Ok(Self::User),
+ other => Err(MemoryError::MalformedRecord(format!(
+ "unknown user role {other:?}"
+ ))),
+ }
+ }
+}
+
/// A registered user as stored. `id` is the UUIDv7 primary key; the
-/// other fields mirror the `users` table.
+/// other fields mirror the public `users` columns. Password hashes,
+/// session hashes, CSRF hashes, and API-key hashes never appear here.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct User {
/// Stable identity. Used by `audit_log.author_id` and
@@ -52,23 +113,64 @@ pub struct User {
/// Microseconds since epoch; `None` until the first authenticated
/// request from this user. Updated fire-and-forget per request.
pub last_seen_at: Option<i64>,
- /// Microseconds since epoch; `None` means the token is active.
- /// `ai-memory user expire` stamps it, `revive` clears it,
- /// `rotate-token` issues a fresh hash AND implicitly clears this
- /// field (rotating a token only makes sense to make it usable again).
+ /// Microseconds since epoch; `None` means the deprecated single-token
+ /// compatibility credential is active. Native `api_credentials` have
+ /// independent revocation metadata.
+ #[serde(default)]
pub token_expired_at: Option<i64>,
+ /// Human role. Native API credentials ignore this for AuthLevel.
+ pub role: UserRole,
+ /// The next web login must change the password before `/admin` or
+ /// `/api/v1` become available.
+ pub must_change_password: bool,
+ /// Microseconds since epoch; `None` means human login is enabled.
+ pub disabled_at: Option<i64>,
+ /// `true` when `users.password_hash` is populated. Token-only
+ /// brownfield rows are `false` ("API only") until reset-password.
+ pub has_password: bool,
}
impl User {
- /// `true` if the user's current token is usable. Auth middleware
- /// uses this to short-circuit the request before hitting any
- /// further state.
+ /// `true` when human login is currently allowed.
+ #[must_use]
+ pub fn is_human_enabled(&self) -> bool {
+ self.disabled_at.is_none() && self.has_password
+ }
+
+ /// `true` when the deprecated single-token compatibility credential is
+ /// active.
#[must_use]
pub fn is_token_active(&self) -> bool {
self.token_expired_at.is_none()
}
}
+/// Public metadata for one native API credential. The authenticating
+/// hash is never serialised.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ApiCredential {
+ /// Stable credential id. Brownfield copies use the parent `user_id`.
+ pub id: ApiCredentialId,
+ /// Owning human (or brownfield) identity.
+ pub user_id: UserId,
+ /// Operator-supplied label.
+ pub label: String,
+ /// Optional non-authenticating preview (e.g. last four of `aim_…`).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub preview: Option<String>,
+ /// Microseconds since epoch.
+ pub created_at: i64,
+ /// Microseconds since epoch; `None` until first use.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub last_used_at: Option<i64>,
+ /// Optional absolute expiry.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub expires_at: Option<i64>,
+ /// Microseconds since epoch when revoked; `None` means active.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub revoked_at: Option<i64>,
+}
+
/// Pre-insert shape for a new user. Carries the inputs the caller
/// (CLI / admin endpoint) collected; the actual token generation +
/// hashing lives in `ai-memory-store::users` since it owns the
@@ -218,6 +320,48 @@ pub fn validate_email(s: &str) -> Result<(), MemoryError> {
Ok(())
}
+/// Validate a human password before Argon2id hashing.
+///
+/// Policy (AUTH-010): 12–1024 UTF-8 bytes; not a reserved credential
+/// prefix ([`SESSION_SECRET_PREFIX`], [`NATIVE_API_KEY_PREFIX`],
+/// [`EXTERNAL_API_KEY_PREFIX`]); not equal to `username` or any
+/// configured reserved secret (recovery token, machine-root bearer,
+/// actor-proxy bearer). Token-hash collision is checked by the store
+/// against `api_credentials` hashes only.
+///
+/// Failures always use the same generic [`MemoryError::InvalidPassword`]
+/// text so callers cannot distinguish which rule fired.
+///
+/// # Errors
+/// Returns [`MemoryError::InvalidPassword`] on any policy violation.
+pub fn validate_human_password(
+ password: &str,
+ username: Option<&str>,
+ reserved_plaintext: &[&str],
+) -> Result<(), MemoryError> {
+ const GENERIC: &str = "does not meet policy";
+ let bytes = password.len();
+ if !(MIN_HUMAN_PASSWORD_BYTES..=MAX_HUMAN_PASSWORD_BYTES).contains(&bytes) {
+ return Err(MemoryError::InvalidPassword(GENERIC.into()));
+ }
+ if password.starts_with(SESSION_SECRET_PREFIX)
+ || password.starts_with(NATIVE_API_KEY_PREFIX)
+ || password.starts_with(EXTERNAL_API_KEY_PREFIX)
+ {
+ return Err(MemoryError::InvalidPassword(GENERIC.into()));
+ }
+ if username.is_some_and(|name| password == name) {
+ return Err(MemoryError::InvalidPassword(GENERIC.into()));
+ }
+ if reserved_plaintext
+ .iter()
+ .any(|secret| !secret.is_empty() && password == *secret)
+ {
+ return Err(MemoryError::InvalidPassword(GENERIC.into()));
+ }
+ Ok(())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -414,4 +558,30 @@ mod tests {
};
assert!(matches!(nu.validate(), Err(MemoryError::InvalidEmail(_))));
}
+ #[test]
+ fn human_password_accepts_typical() {
+ assert!(validate_human_password("twelve chars!!", Some("alice"), &[]).is_ok());
+ }
+
+ #[test]
+ fn human_password_rejects_short_long_prefix_and_reserved() {
+ let ok = "twelve chars!!";
+ assert!(validate_human_password(&ok[..11], None, &[]).is_err());
+ let too_long = "a".repeat(MAX_HUMAN_PASSWORD_BYTES + 1);
+ assert!(validate_human_password(&too_long, None, &[]).is_err());
+ assert!(validate_human_password(&format!("ams_{ok}"), None, &[]).is_err());
+ assert!(validate_human_password(&format!("aim_{ok}"), None, &[]).is_err());
+ assert!(validate_human_password(&format!("amk_{ok}"), None, &[]).is_err());
+ assert!(validate_human_password(ok, Some(ok), &[]).is_err());
+ assert!(validate_human_password(ok, Some("alice"), &[ok]).is_err());
+ }
+
+ #[test]
+ fn user_role_round_trips() {
+ assert_eq!(UserRole::parse("root").unwrap(), UserRole::Root);
+ assert_eq!(UserRole::parse("user").unwrap(), UserRole::User);
+ assert!(UserRole::parse("admin").is_err());
+ assert_eq!(UserRole::Root.as_str(), "root");
+ assert_eq!(UserRole::default(), UserRole::User);
+ }
}
diff --git a/crates/ai-memory-mcp/Cargo.toml b/crates/ai-memory-mcp/Cargo.toml
index 1717fde2..bcd0f5d3 100644
--- a/crates/ai-memory-mcp/Cargo.toml
+++ b/crates/ai-memory-mcp/Cargo.toml
@@ -28,8 +28,8 @@ rmcp.workspace = true
schemars.workspace = true
axum.workspace = true
http.workspace = true
-# HTTP auth middleware (bearer/basic/cookie): constant-time token
-# compare, Basic-header decoding, random token generation.
+# HTTP auth middleware: constant-time Bearer compare. Basic is not a
+# credential; sessions live in human_auth.
subtle.workspace = true
base64.workspace = true
getrandom.workspace = true
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index b0391e50..3c7b7f4e 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -78,7 +78,7 @@ use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
-use axum::routing::{get, post};
+use axum::routing::{get, patch, post};
use flate2::Compression;
use flate2::write::GzEncoder;
use serde::{Deserialize, Serialize};
@@ -141,12 +141,12 @@ 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`.
+ /// Per-server token pepper, used by `/admin/api-credentials` to hash
+ /// freshly-issued `aim_` secrets before they land in
+ /// `api_credentials.token_hash`. `None` when the operator hasn't set
+ /// `[auth].token_pepper` in config (single-user installs that predate
+ /// v0.8); native API-credential endpoints then return 503
+ /// `multi-user not enabled`.
pub token_pepper: Option<ai_memory_store::TokenPepper>,
/// Shared in-process pointer to the project the agent is currently
/// active in (published by the hook router). Read by `move-project` to
@@ -639,11 +639,31 @@ pub fn admin_router_with_sweep_tuning(
"/admin/users",
get(handle_list_users).post(handle_create_user),
)
+ .route("/admin/human-users", post(handle_create_human_user))
+ .route("/admin/users/{username}", patch(handle_patch_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),
+ )
+ .route(
+ "/admin/users/{username}/reset-password",
+ post(handle_reset_password),
+ )
+ .route("/admin/users/{username}/disable", post(handle_disable_user))
+ .route("/admin/users/{username}/enable", post(handle_enable_user))
+ .route(
+ "/admin/api-credentials",
+ get(handle_list_api_credentials).post(handle_create_api_credential),
+ )
+ .route(
+ "/admin/api-credentials/{id}/rotate",
+ post(handle_rotate_api_credential),
+ )
+ .route(
+ "/admin/api-credentials/{id}/revoke",
+ post(handle_revoke_api_credential),
);
operational
.merge(users)
@@ -6351,51 +6371,74 @@ struct CreateUserRequest {
name: Option<String>,
#[serde(default)]
email: Option<String>,
+ #[serde(default)]
+ role: Option<ai_memory_core::UserRole>,
+}
+
+#[derive(Debug, Deserialize)]
+struct PatchUserRequest {
+ #[serde(default)]
+ name: Option<Option<String>>,
+ #[serde(default)]
+ email: Option<Option<String>>,
+ #[serde(default)]
+ role: Option<ai_memory_core::UserRole>,
+}
+
+#[derive(Debug, Deserialize)]
+struct CreateApiCredentialRequest {
+ username: String,
+ label: 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 UserWithPasswordResponse {
+ user: ai_memory_core::User,
+ temporary_password: String,
+}
+
#[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.
+#[derive(Debug, Serialize)]
+struct ApiCredentialWithTokenResponse {
+ credential: ai_memory_core::ApiCredential,
+ token: String,
+}
+
+#[derive(Debug, Serialize)]
+struct ApiCredentialListResponse {
+ credentials: Vec<ai_memory_core::ApiCredential>,
+}
+
fn require_root(
level: ai_memory_core::AuthLevel,
) -> Result<(), (StatusCode, Json<serde_json::Value>)> {
level
- .authorize(Capability::UserManagement, true)
+ .authorize(ai_memory_core::Capability::UserManagement, true)
.map_err(|e| {
- (
- authz_status(e),
- Json(serde_json::json!({ "error": e.message() })),
- )
+ let status = if e.is_authentication_required() {
+ StatusCode::UNAUTHORIZED
+ } else {
+ StatusCode::FORBIDDEN
+ };
+ (status, Json(serde_json::json!({ "error": e.message() })))
})
}
-/// 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>)> {
@@ -6409,20 +6452,99 @@ fn require_pepper(
})
}
-/// 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.
+fn reserved_password(
+ auth: Option<axum::Extension<std::sync::Arc<crate::auth::AuthState>>>,
+ password: &str,
+) -> bool {
+ auth.is_some_and(|axum::Extension(state)| {
+ crate::human_auth::password_is_reserved(&state, password)
+ })
+}
+
+async fn hash_temp_password() -> Result<String, (StatusCode, Json<serde_json::Value>)> {
+ let raw = ai_memory_store::password::generate_temporary_password()
+ .map_err(|e| internal_err(e.to_string()))?;
+ ai_memory_core::validate_human_password(&raw, None, &[])
+ .map_err(|e| validation_error(e.to_string()))?;
+ Ok(raw)
+}
+
+async fn mint_temporary_password(
+ state: &AdminState,
+ auth: Option<axum::Extension<Arc<crate::auth::AuthState>>>,
+) -> Result<String, (StatusCode, Json<serde_json::Value>)> {
+ for _ in 0..8 {
+ let raw = hash_temp_password().await?;
+ if reserved_password(auth.clone(), &raw) {
+ continue;
+ }
+ if let Some(pepper) = state.token_pepper.as_ref() {
+ let hash = ai_memory_store::hash_token(&raw, pepper);
+ match state.reader.token_hash_exists(hash).await {
+ Ok(true) => continue,
+ Ok(false) => {}
+ Err(e) => return Err(internal_err(e.to_string())),
+ }
+ }
+ return Ok(raw);
+ }
+ Err(internal_err(
+ "could not mint a unique temporary password".to_string(),
+ ))
+}
+
+async fn create_human_user_response(
+ state: &AdminState,
+ auth: Option<axum::Extension<Arc<crate::auth::AuthState>>>,
+ req: CreateUserRequest,
+) -> Result<(StatusCode, Json<serde_json::Value>), (StatusCode, Json<serde_json::Value>)> {
+ 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 role = req.role.unwrap_or(ai_memory_core::UserRole::User);
+ let raw = mint_temporary_password(state, auth).await?;
+ let phc = ai_memory_store::password::hash_password(raw.clone())
+ .await
+ .map_err(|e| internal_err(e.to_string()))?;
+ let user_id = state
+ .writer
+ .create_human_user(new_user, role, Some(phc), true)
+ .await
+ .map_err(map_user_store_err)?;
+ 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(UserWithPasswordResponse {
+ user,
+ temporary_password: raw,
+ })
+ .unwrap_or_default(),
+ ),
+ ))
+}
+
async fn handle_create_user(
State(state): State<Arc<AdminState>>,
axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,
+ auth: Option<axum::Extension<Arc<crate::auth::AuthState>>>,
Json(req): Json<CreateUserRequest>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
require_root(level)?;
+ if req.role.is_some() {
+ return create_human_user_response(&state, auth, req).await;
+ }
let pepper = require_pepper(&state)?;
-
let mut new_user = ai_memory_core::NewUser {
username: req.username,
name: req.name,
@@ -6431,34 +6553,35 @@ async fn handle_create_user(
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)
+ .create_user(new_user, 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_create_human_user(
+ State(state): State<Arc<AdminState>>,
+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,
+ auth: Option<axum::Extension<Arc<crate::auth::AuthState>>>,
+ Json(req): Json<CreateUserRequest>,
+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
+ require_root(level)?;
+ create_human_user_response(&state, auth, req).await
+}
+
async fn handle_list_users(
State(state): State<Arc<AdminState>>,
axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,
@@ -6475,9 +6598,6 @@ async fn handle_list_users(
))
}
-/// 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>,
@@ -6489,22 +6609,19 @@ async fn handle_expire_user(
.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.
+ .map_err(map_user_store_err)?;
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_or_else(|| internal_err("user vanished after token expiry".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>,
@@ -6516,24 +6633,19 @@ async fn handle_revive_user(
.writer
.revive_user_token(user.id)
.await
- .map_err(|e| internal_err(e.to_string()))?;
+ .map_err(map_user_store_err)?;
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_or_else(|| internal_err("user vanished after token revival".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>,
@@ -6542,15 +6654,13 @@ async fn handle_rotate_user_token(
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()))?;
+ .map_err(map_user_store_err)?;
if !updated {
return Err((
StatusCode::NOT_FOUND,
@@ -6562,76 +6672,303 @@ async fn handle_rotate_user_token(
.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_or_else(|| internal_err("user vanished after token rotation".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
+async fn handle_patch_user(
+ State(state): State<Arc<AdminState>>,
+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,
+ axum::extract::Path(username): axum::extract::Path<String>,
+ Json(req): Json<PatchUserRequest>,
+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
+ require_root(level)?;
+ let user = lookup_user_by_username(&state, &username).await?;
+ state
+ .writer
+ .patch_user(user.id, req.name, req.email, req.role)
+ .await
+ .map_err(map_user_store_err)?;
+ let user = state
.reader
- .find_user_by_username(username.to_string())
+ .find_user_by_id(user.id)
+ .await
+ .map_err(|e| internal_err(e.to_string()))?
+ .ok_or_else(|| internal_err("user vanished after patch".to_string()))?;
+ Ok((
+ StatusCode::OK,
+ Json(serde_json::to_value(UserResponse { user }).unwrap_or_default()),
+ ))
+}
+
+async fn handle_reset_password(
+ State(state): State<Arc<AdminState>>,
+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,
+ auth: Option<axum::Extension<Arc<crate::auth::AuthState>>>,
+ 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?;
+ let raw = mint_temporary_password(&state, auth).await?;
+ let phc = ai_memory_store::password::hash_password(raw.clone())
.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}") })),
- )
- })
+ state
+ .writer
+ .reset_human_password(user.id, phc, true)
+ .await
+ .map_err(map_user_store_err)?;
+ 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 reset".to_string()))?;
+ Ok((
+ StatusCode::OK,
+ Json(
+ serde_json::to_value(UserWithPasswordResponse {
+ user,
+ temporary_password: raw,
+ })
+ .unwrap_or_default(),
+ ),
+ ))
}
-/// 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 })),
- )
+async fn handle_disable_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
+ .set_user_disabled(user.id, true)
+ .await
+ .map_err(map_user_store_err)?;
+ 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 disable".to_string()))?;
+ Ok((
+ StatusCode::OK,
+ Json(serde_json::to_value(UserResponse { user }).unwrap_or_default()),
+ ))
}
-/// 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()),
- }
+async fn handle_enable_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
+ .set_user_disabled(user.id, false)
+ .await
+ .map_err(map_user_store_err)?;
+ 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 enable".to_string()))?;
+ Ok((
+ StatusCode::OK,
+ Json(serde_json::to_value(UserResponse { user }).unwrap_or_default()),
+ ))
}
-#[cfg(test)]
-mod tests {
- use super::*;
- use ai_memory_core::{
- ActorContext, AgentKind, IdentityKey, NewObservation, NewSession, ObservationKind,
- };
- use ai_memory_core::{Sanitized, Sanitizer};
- use ai_memory_llm::{ChatRequest, ChatResponse, LlmResult};
- use ai_memory_store::Store;
- use axum::body::to_bytes;
- use axum::http::Request;
- use tempfile::TempDir;
- use tower::ServiceExt;
+async fn handle_create_api_credential(
+ State(state): State<Arc<AdminState>>,
+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,
+ Json(req): Json<CreateApiCredentialRequest>,
+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
+ require_root(level)?;
+ let pepper = require_pepper(&state)?;
+ let user = lookup_user_by_username(&state, &req.username).await?;
+ let token = ai_memory_store::generate_api_key().map_err(|e| internal_err(e.to_string()))?;
+ let token_hash = ai_memory_store::hash_token(&token, pepper);
+ let preview = ai_memory_store::api_key_preview(&token);
+ let id = state
+ .writer
+ .create_api_credential(
+ ai_memory_core::ApiCredentialId::new(),
+ user.id,
+ req.label,
+ token_hash,
+ Some(preview),
+ )
+ .await
+ .map_err(map_user_store_err)?;
+ let credential = state
+ .reader
+ .find_api_credential(id)
+ .await
+ .map_err(|e| internal_err(e.to_string()))?
+ .ok_or_else(|| internal_err("credential vanished after create".to_string()))?;
+ Ok((
+ StatusCode::OK,
+ Json(
+ serde_json::to_value(ApiCredentialWithTokenResponse { credential, token })
+ .unwrap_or_default(),
+ ),
+ ))
+}
- struct FakeAutoImproveLlm;
+async fn handle_list_api_credentials(
+ 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 credentials = state
+ .reader
+ .list_api_credentials()
+ .await
+ .map_err(|e| internal_err(e.to_string()))?;
+ Ok((
+ StatusCode::OK,
+ Json(serde_json::to_value(ApiCredentialListResponse { credentials }).unwrap_or_default()),
+ ))
+}
- #[async_trait::async_trait]
- impl LlmProvider for FakeAutoImproveLlm {
- fn name(&self) -> &'static str {
+async fn handle_rotate_api_credential(
+ State(state): State<Arc<AdminState>>,
+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,
+ axum::extract::Path(id): axum::extract::Path<String>,
+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
+ require_root(level)?;
+ let pepper = require_pepper(&state)?;
+ let id: ai_memory_core::ApiCredentialId = id
+ .parse()
+ .map_err(|e: ai_memory_core::MemoryError| validation_error(e.to_string()))?;
+ let token = ai_memory_store::generate_api_key().map_err(|e| internal_err(e.to_string()))?;
+ let token_hash = ai_memory_store::hash_token(&token, pepper);
+ let preview = ai_memory_store::api_key_preview(&token);
+ let updated = state
+ .writer
+ .rotate_api_credential(id, token_hash, Some(preview))
+ .await
+ .map_err(map_user_store_err)?;
+ if !updated {
+ return Err((
+ StatusCode::NOT_FOUND,
+ Json(serde_json::json!({ "error": "no such credential" })),
+ ));
+ }
+ let credential = state
+ .reader
+ .find_api_credential(id)
+ .await
+ .map_err(|e| internal_err(e.to_string()))?
+ .ok_or_else(|| internal_err("credential vanished after rotate".to_string()))?;
+ Ok((
+ StatusCode::OK,
+ Json(
+ serde_json::to_value(ApiCredentialWithTokenResponse { credential, token })
+ .unwrap_or_default(),
+ ),
+ ))
+}
+
+async fn handle_revoke_api_credential(
+ State(state): State<Arc<AdminState>>,
+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,
+ axum::extract::Path(id): axum::extract::Path<String>,
+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
+ require_root(level)?;
+ let id: ai_memory_core::ApiCredentialId = id
+ .parse()
+ .map_err(|e: ai_memory_core::MemoryError| validation_error(e.to_string()))?;
+ state
+ .writer
+ .revoke_api_credential(id)
+ .await
+ .map_err(|e| internal_err(e.to_string()))?;
+ let credential = state
+ .reader
+ .find_api_credential(id)
+ .await
+ .map_err(|e| internal_err(e.to_string()))?
+ .ok_or_else(|| {
+ (
+ StatusCode::NOT_FOUND,
+ Json(serde_json::json!({ "error": "no such credential" })),
+ )
+ })?;
+ Ok((
+ StatusCode::OK,
+ Json(serde_json::json!({ "credential": credential })),
+ ))
+}
+
+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}") })),
+ )
+ })
+}
+
+fn validation_error(msg: String) -> (StatusCode, Json<serde_json::Value>) {
+ (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({ "error": msg })),
+ )
+}
+
+fn map_user_store_err(e: ai_memory_store::StoreError) -> (StatusCode, Json<serde_json::Value>) {
+ match e {
+ ai_memory_store::StoreError::Duplicate(msg)
+ | ai_memory_store::StoreError::InvalidState(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))
+ | ai_memory_store::StoreError::Memory(ai_memory_core::MemoryError::InvalidPassword(msg)) => {
+ validation_error(msg)
+ }
+ other => internal_err(other.to_string()),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ai_memory_core::{
+ ActorContext, AgentKind, IdentityKey, NewObservation, NewSession, ObservationKind,
+ };
+ use ai_memory_core::{Sanitized, Sanitizer};
+ use ai_memory_llm::{ChatRequest, ChatResponse, LlmResult};
+ use ai_memory_store::Store;
+ use axum::body::to_bytes;
+ use axum::http::Request;
+ use tempfile::TempDir;
+ use tower::ServiceExt;
+
+ struct FakeAutoImproveLlm;
+
+ #[async_trait::async_trait]
+ impl LlmProvider for FakeAutoImproveLlm {
+ fn name(&self) -> &'static str {
"fake-auto-improve"
}
@@ -9875,6 +10212,91 @@ mod tests {
(tmp, router)
}
+ /// Same AdminState as [`user_admin_test_router`], but AuthLevel comes from
+ /// the production dual-auth Bearer lookup (`authenticate_bearer` +
+ /// `api_credentials` hash), not a stub that stamps Root/User by string
+ /// compare. Configured `root_token` is AuthLevel::Root; a DB native key
+ /// authenticates as AuthLevel::User even when `users.role` is root.
+ fn user_admin_dual_auth_router(root_token: &'static str) -> (TempDir, Router) {
+ 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 {
+ ingest_metrics: std::sync::Arc::new(ai_memory_core::IngestMetrics::default()),
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ 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(pepper.clone()),
+ active_project: ai_memory_core::ActiveProject::new(),
+ scope_invalidator: None,
+ trusted_proxy_identity: false,
+ });
+ let auth_state = Arc::new(
+ crate::auth::AuthState::new(Some(root_token.to_string())).with_multiuser(
+ pepper,
+ store.reader.clone(),
+ store.writer.clone(),
+ ),
+ );
+ let router = router.layer(axum::middleware::from_fn_with_state(
+ auth_state,
+ crate::human_auth::require_dual_auth,
+ ));
+ (tmp, router)
+ }
+
+ async fn post_disable_user(
+ router: &Router,
+ root_token: &str,
+ username: &str,
+ ) -> axum::http::Response<Body> {
+ router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri(format!("/admin/users/{username}/disable"))
+ .header("authorization", format!("Bearer {root_token}"))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap()
+ }
+
+ async fn patch_user(
+ router: &Router,
+ root_token: &str,
+ username: &str,
+ body: serde_json::Value,
+ ) -> axum::http::Response<Body> {
+ router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("PATCH")
+ .uri(format!("/admin/users/{username}"))
+ .header("content-type", "application/json")
+ .header("authorization", format!("Bearer {root_token}"))
+ .body(Body::from(serde_json::to_vec(&body).unwrap()))
+ .unwrap(),
+ )
+ .await
+ .unwrap()
+ }
+
async fn post_create_user(
router: &Router,
root_token: &str,
@@ -9895,6 +10317,41 @@ mod tests {
.unwrap()
}
+ async fn post_create_human_user(
+ router: &Router,
+ root_token: &str,
+ body: serde_json::Value,
+ ) -> axum::http::Response<Body> {
+ router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/admin/human-users")
+ .header("content-type", "application/json")
+ .header("authorization", format!("Bearer {root_token}"))
+ .body(Body::from(serde_json::to_vec(&body).unwrap()))
+ .unwrap(),
+ )
+ .await
+ .unwrap()
+ }
+
+ async fn user_token_admin_status(router: &Router, token: &str) -> StatusCode {
+ router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/admin/users")
+ .header("authorization", format!("Bearer {token}"))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap()
+ .status()
+ }
+
fn admin_route_samples() -> Vec<(&'static str, &'static str, serde_json::Value)> {
vec![
("POST", "/admin/backup", serde_json::Value::Null),
@@ -10059,6 +10516,11 @@ mod tests {
"/admin/users",
serde_json::json!({"username": "alice"}),
),
+ (
+ "POST",
+ "/admin/human-users",
+ serde_json::json!({"username": "human"}),
+ ),
("POST", "/admin/users/alice/expire", serde_json::Value::Null),
("POST", "/admin/users/alice/revive", serde_json::Value::Null),
(
@@ -10066,6 +10528,13 @@ mod tests {
"/admin/users/alice/rotate-token",
serde_json::Value::Null,
),
+ (
+ "POST",
+ "/admin/users/alice/disable",
+ serde_json::Value::Null,
+ ),
+ ("POST", "/admin/users/alice/enable", serde_json::Value::Null),
+ ("GET", "/admin/api-credentials", serde_json::Value::Null),
]
}
@@ -10286,7 +10755,7 @@ mod tests {
.oneshot(
Request::builder()
.method("POST")
- .uri("/admin/users/alice/expire")
+ .uri("/admin/users/alice/disable")
.header("authorization", "Bearer root-token")
.body(Body::empty())
.unwrap(),
@@ -10419,10 +10888,114 @@ mod tests {
// 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).
+ // Plaintext token is surfaced exactly once.
let token = json["token"].as_str().unwrap();
assert_eq!(token.len(), 43);
+ assert!(json["user"]["token_expired_at"].is_null());
+ assert!(json.get("temporary_password").is_none());
+ }
+
+ #[tokio::test]
+ async fn create_human_user_is_additive_and_returns_temporary_password_once() {
+ let (_tmp, router) = user_admin_test_router("root-token");
+ let resp = post_create_human_user(
+ &router,
+ "root-token",
+ serde_json::json!({
+ "username": "alice",
+ "role": "root"
+ }),
+ )
+ .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!(json["temporary_password"].as_str().unwrap().len() >= 12);
+ assert_eq!(json["user"]["role"], "root");
+ assert!(json["user"]["must_change_password"].as_bool().unwrap());
+ assert!(json.get("token").is_none());
+ }
+
+ #[tokio::test]
+ async fn deprecated_user_token_routes_drive_the_legacy_api_credential() {
+ let (_tmp, router) = user_admin_dual_auth_router("root-token");
+ let create = post_create_user(
+ &router,
+ "root-token",
+ serde_json::json!({"username": "alice"}),
+ )
+ .await;
+ assert_eq!(create.status(), StatusCode::OK);
+ let body = to_bytes(create.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ let original = json["token"].as_str().unwrap().to_string();
+ assert_eq!(
+ user_token_admin_status(&router, &original).await,
+ StatusCode::FORBIDDEN,
+ "active legacy token must authenticate as a non-root DB user"
+ );
+
+ 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);
+ assert_eq!(
+ user_token_admin_status(&router, &original).await,
+ StatusCode::UNAUTHORIZED
+ );
+
+ let revive = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/admin/users/alice/revive")
+ .header("authorization", "Bearer root-token")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(revive.status(), StatusCode::OK);
+ assert_eq!(
+ user_token_admin_status(&router, &original).await,
+ StatusCode::FORBIDDEN
+ );
+
+ let rotate = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/admin/users/alice/rotate-token")
+ .header("authorization", "Bearer root-token")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(rotate.status(), StatusCode::OK);
+ let body = to_bytes(rotate.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ let rotated = json["token"].as_str().unwrap();
+ assert_ne!(rotated, original);
+ assert_eq!(
+ user_token_admin_status(&router, &original).await,
+ StatusCode::UNAUTHORIZED
+ );
+ assert_eq!(
+ user_token_admin_status(&router, rotated).await,
+ StatusCode::FORBIDDEN
+ );
}
#[tokio::test]
@@ -10514,12 +11087,15 @@ mod tests {
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");
+ assert!(
+ u.get("token").is_none() && u.get("temporary_password").is_none(),
+ "list must not leak secrets"
+ );
}
}
#[tokio::test]
- async fn expire_then_revive_round_trips() {
+ async fn disable_then_enable_round_trips() {
let (_tmp, router) = user_admin_test_router("root-token");
let _ = post_create_user(
&router,
@@ -10528,13 +11104,12 @@ mod tests {
)
.await;
- // Expire.
let resp = router
.clone()
.oneshot(
Request::builder()
.method("POST")
- .uri("/admin/users/alice/expire")
+ .uri("/admin/users/alice/disable")
.header("authorization", "Bearer root-token")
.body(Body::empty())
.unwrap(),
@@ -10544,14 +11119,13 @@ mod tests {
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());
+ assert!(json["user"]["disabled_at"].is_i64());
- // Revive.
let resp = router
.oneshot(
Request::builder()
.method("POST")
- .uri("/admin/users/alice/revive")
+ .uri("/admin/users/alice/enable")
.header("authorization", "Bearer root-token")
.body(Body::empty())
.unwrap(),
@@ -10561,17 +11135,17 @@ mod tests {
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());
+ assert!(json["user"]["disabled_at"].is_null());
}
#[tokio::test]
- async fn expire_unknown_user_returns_404() {
+ async fn disable_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")
+ .uri("/admin/users/ghost/disable")
.header("authorization", "Bearer root-token")
.body(Body::empty())
.unwrap(),
@@ -10582,25 +11156,45 @@ mod tests {
}
#[tokio::test]
- async fn rotate_token_issues_a_distinct_token() {
+ async fn rotate_api_credential_issues_a_distinct_secret() {
let (_tmp, router) = user_admin_test_router("root-token");
- let create_resp = post_create_user(
+ let _ = post_create_user(
&router,
"root-token",
serde_json::json!({"username": "alice"}),
)
.await;
+ let create_resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/admin/api-credentials")
+ .header("authorization", "Bearer root-token")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "username": "alice",
+ "label": "laptop"
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(create_resp.status(), StatusCode::OK);
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 created: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ let original_token = created["token"].as_str().unwrap().to_string();
+ let id = created["credential"]["id"].as_str().unwrap();
+ assert!(original_token.starts_with("aim_"));
let resp = router
.oneshot(
Request::builder()
.method("POST")
- .uri("/admin/users/alice/rotate-token")
+ .uri(format!("/admin/api-credentials/{id}/rotate"))
.header("authorization", "Bearer root-token")
.body(Body::empty())
.unwrap(),
@@ -10611,14 +11205,13 @@ mod tests {
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");
+ assert!(new_token.starts_with("aim_"));
+ assert_ne!(new_token, original_token, "rotate must change the secret");
}
#[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.
+ async fn create_human_user_works_without_pepper_but_api_keys_return_503() {
+ // Humans do not need a pepper. Native API keys still do.
use ai_memory_core::ActorContext;
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path()).unwrap();
@@ -10644,8 +11237,8 @@ mod tests {
scope_invalidator: None,
trusted_proxy_identity: false,
});
- // Inject a Root level so we're past the require_root gate;
- // the 503 must come from require_pepper.
+ // Inject Root so the human create reaches its handler; only native
+ // API credentials require the 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);
@@ -10654,11 +11247,12 @@ mod tests {
},
));
- let resp = router
+ let created = router
+ .clone()
.oneshot(
Request::builder()
.method("POST")
- .uri("/admin/users")
+ .uri("/admin/human-users")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&serde_json::json!({"username": "alice"})).unwrap(),
@@ -10667,10 +11261,237 @@ mod tests {
)
.await
.unwrap();
+ assert_eq!(created.status(), StatusCode::OK);
+
+ let resp = router
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/admin/api-credentials")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "username": "alice",
+ "label": "cli"
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
let _ = tmp;
}
+ #[tokio::test]
+ async fn patch_demotion_of_last_recoverable_root_returns_409() {
+ let (_tmp, router) = user_admin_test_router("root-token");
+ let created = post_create_user(
+ &router,
+ "root-token",
+ serde_json::json!({"username": "keeper", "role": "root"}),
+ )
+ .await;
+ assert_eq!(created.status(), StatusCode::OK);
+ let body = to_bytes(created.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["user"]["role"], "root");
+ assert_eq!(json["user"]["has_password"].as_bool(), Some(true));
+
+ let resp = patch_user(
+ &router,
+ "root-token",
+ "keeper",
+ serde_json::json!({"role": "user"}),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::CONFLICT);
+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert!(
+ json["error"]
+ .as_str()
+ .unwrap_or("")
+ .contains("last recoverable root"),
+ "409 body must surface the store InvalidState mapping; got {json:?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn disable_of_last_recoverable_root_returns_409() {
+ let (_tmp, router) = user_admin_test_router("root-token");
+ let created = post_create_user(
+ &router,
+ "root-token",
+ serde_json::json!({"username": "keeper", "role": "root"}),
+ )
+ .await;
+ assert_eq!(created.status(), StatusCode::OK);
+
+ let resp = post_disable_user(&router, "root-token", "keeper").await;
+ assert_eq!(resp.status(), StatusCode::CONFLICT);
+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert!(
+ json["error"]
+ .as_str()
+ .unwrap_or("")
+ .contains("last recoverable root"),
+ "409 body must surface the store InvalidState mapping; got {json:?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn concurrent_root_removals_leave_one_recoverable_root() {
+ let (_tmp, router) = user_admin_test_router("root-token");
+ for name in ["alice", "bob"] {
+ let created = post_create_user(
+ &router,
+ "root-token",
+ serde_json::json!({"username": name, "role": "root"}),
+ )
+ .await;
+ assert_eq!(created.status(), StatusCode::OK, "setup {name}");
+ }
+
+ let (demote, disable) = tokio::join!(
+ patch_user(
+ &router,
+ "root-token",
+ "alice",
+ serde_json::json!({"role": "user"}),
+ ),
+ post_disable_user(&router, "root-token", "bob"),
+ );
+ let statuses = [demote.status(), disable.status()];
+ let ok = statuses.iter().filter(|s| **s == StatusCode::OK).count();
+ assert!(
+ ok <= 1,
+ "at most one concurrent root-removal may succeed; got {statuses:?}"
+ );
+ assert!(
+ statuses
+ .iter()
+ .all(|s| *s == StatusCode::OK || *s == StatusCode::CONFLICT),
+ "root-removal must be 200 or 409; got {statuses:?}"
+ );
+
+ let listed = router
+ .oneshot(
+ Request::builder()
+ .uri("/admin/users")
+ .header("authorization", "Bearer root-token")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(listed.status(), StatusCode::OK);
+ let body = to_bytes(listed.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ let recoverable = json["users"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter(|u| {
+ u["role"] == "root"
+ && u["disabled_at"].is_null()
+ && u["has_password"].as_bool() == Some(true)
+ })
+ .count();
+ assert!(
+ recoverable >= 1,
+ "a recoverable root must remain after concurrent removals; got {json:?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn native_api_token_for_root_role_user_cannot_manage_users() {
+ let (_tmp, router) = user_admin_dual_auth_router("root-token");
+ let created = post_create_user(
+ &router,
+ "root-token",
+ serde_json::json!({"username": "boss", "role": "root"}),
+ )
+ .await;
+ assert_eq!(created.status(), StatusCode::OK);
+ let body = to_bytes(created.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["user"]["role"], "root");
+
+ let issued = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/admin/api-credentials")
+ .header("authorization", "Bearer root-token")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "username": "boss",
+ "label": "legacy-user-token"
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(issued.status(), StatusCode::OK);
+ let body = to_bytes(issued.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ let native_token = json["token"].as_str().unwrap();
+ assert!(native_token.starts_with("aim_"));
+
+ let as_native = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/admin/users")
+ .header("authorization", format!("Bearer {native_token}"))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ as_native.status(),
+ StatusCode::FORBIDDEN,
+ "role=root must not elevate a looked-up native API credential"
+ );
+
+ let unknown = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/admin/users")
+ .header("authorization", "Bearer aim_not-a-stored-credential")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ unknown.status(),
+ StatusCode::UNAUTHORIZED,
+ "unknown bearer must 401 through real lookup, not a User stub"
+ );
+
+ let as_root = router
+ .oneshot(
+ Request::builder()
+ .uri("/admin/users")
+ .header("authorization", "Bearer root-token")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(as_root.status(), StatusCode::OK);
+ }
+
// ---------------------------------------------------------------------
// delete-page
// ---------------------------------------------------------------------
diff --git a/crates/ai-memory-mcp/src/auth.rs b/crates/ai-memory-mcp/src/auth.rs
index f3149304..8fb3075f 100644
--- a/crates/ai-memory-mcp/src/auth.rs
+++ b/crates/ai-memory-mcp/src/auth.rs
@@ -1,74 +1,57 @@
//! Authorization middleware for the HTTP server.
//!
-//! When `[auth].bearer_token` (or the `AI_MEMORY_AUTH_TOKEN` env var)
-//! is set, every request to `/mcp`, `/hook`, `/handoff`, and `/web/*`
-//! must present the token via one of three transports:
+//! Machine-only routes (`/mcp`, `/hook`, `/handoff`,
+//! `/workstream/*`) accept `Authorization: Bearer` only. Browser
+//! routes use Bearer plus one of two mutually exclusive modes:
//!
-//! - **Bearer header** (any method): MCP clients + hooks. Required
-//! on all non-GET methods.
-//! - **Basic auth** (GET only): browsers — username ignored, token
-//! in the password field. Triggers the native credential dialog
-//! via the `WWW-Authenticate: Basic` challenge in 401 responses.
-//! - **Session cookie** (GET only): set automatically after a
-//! successful Basic auth so the browser doesn't re-prompt every
-//! session.
+//! - before human password auth is configured, GET requests retain
+//! the deprecated Basic / `ai_memory_auth` cookie transport;
+//! - after human auth is configured, only short-lived human sessions
+//! authenticate browser requests.
//!
-//! When the token is *unset*, the middleware is a no-op — preserving
-//! the zero-config local-development experience and keeping the
-//! existing e2e + unit tests working.
+//! When no authority is configured the middleware is a no-op,
+//! preserving zero-config loopback.
//!
//! Comparison uses [`subtle::ConstantTimeEq`] so an attacker on the
//! same LAN cannot use response-time leaks to recover the token byte
-//! by byte. The constant-time guarantee depends on both sides being
-//! the same length; `subtle` returns a constant-cost `Choice::from(0)`
-//! when lengths differ, which is the right thing here.
-//!
-//! Wire shape matches the MCP authorization spec
-//! (modelcontextprotocol.io/specification/.../basic/authorization):
-//! 401 responses include `WWW-Authenticate: Bearer …` so MCP clients
-//! detect missing/expired credentials. GET 401s ALSO include `Basic
-//! …` so browsers dialog-prompt automatically.
-//!
-//! ## Why not OAuth
-//!
-//! The MCP spec mandates full OAuth 2.1 for HTTP-authenticated
-//! servers. That's overkill for a single-user homelab and would
-//! force every MCP client config to deal with authorization-server
-//! discovery + PKCE + token refresh. A static bearer token is
-//! wire-compatible with the spec's `Authorization: Bearer …` shape
-//! (clients send the header the same way; they just don't run the
-//! OAuth dance to obtain the token). Every supported client
-//! (Claude Code, Codex, OpenCode, Cursor, Claude Desktop via
-//! `mcp-remote`, Gemini CLI, OpenClaw) accepts a static
-//! `Authorization` header in its config.
+//! by byte.
use std::sync::Arc;
use ai_memory_core::{ActorContext, AuthLevel, IdentityKey};
use ai_memory_store::{ReaderPool, TokenPepper, WriterHandle, hash_token};
use axum::extract::State;
-use axum::http::{HeaderMap, Method, Request, StatusCode, header};
+use axum::http::{HeaderMap, Request, StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use subtle::ConstantTimeEq;
use tracing::debug;
-/// Cookie name used for browser session persistence after a
-/// successful Basic auth handshake.
-const AUTH_COOKIE: &str = "ai_memory_auth";
-/// Realm advertised in `WWW-Authenticate` challenges. Shows up in
-/// the browser's credential prompt as "Server says: <realm>".
+/// Realm advertised in `WWW-Authenticate` Bearer challenges.
const AUTH_REALM: &str = "ai-memory";
+/// Outcome of inspecting `Authorization: Bearer` without running the
+/// rest of the stack.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum BearerAuth {
+ /// Actor and [`AuthLevel`] were injected into the request.
+ Authenticated,
+ /// No Bearer scheme. Basic, empty, unknown, or missing Authorization
+ /// do not count as a presented Bearer.
+ Absent,
+ /// Bearer scheme was present and did not authenticate.
+ Rejected,
+}
+
/// Optional multi-user resolver tier — token-hash lookup against the
-/// `users` table. Populated only when both a per-server pepper and a
+/// `api_credentials` 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.
+ /// `api_credentials.token_hash` lookup.
pub pepper: TokenPepper,
/// Read-only pool used by the auth hot path
/// (`find_active_user_by_token_hash`).
@@ -104,6 +87,13 @@ pub struct AuthState {
/// separate from the root bearer so a missing identity assertion cannot
/// accidentally turn proxy traffic into root traffic.
actor_proxy_bearer: Option<String>,
+ /// Human password/session runtime. `None` for machine-only or
+ /// zero-config anonymous loopback.
+ pub human: Option<crate::human_auth::HumanAuthRuntime>,
+ /// Whether human auth was intended at startup. Runtime presence is
+ /// separate because the browser transition checks persisted password /
+ /// bootstrap state on every request.
+ human_intended: bool,
}
impl AuthState {
@@ -171,8 +161,8 @@ impl AuthState {
}
/// 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.
+ /// token is hashed with `pepper` and checked against
+ /// `api_credentials`; a hit attributes the request to that user.
/// Without this attach, the middleware only knows about rung 0/1
/// and rejects unknown bearers (closing the bypass).
#[must_use]
@@ -190,37 +180,52 @@ impl AuthState {
self
}
- /// True when a token is configured (i.e. the middleware is doing
- /// anything). Useful for the startup log line so the operator
- /// sees whether their server is open or closed.
+ /// Attach an active human password/session runtime.
+ #[must_use]
+ pub fn with_human(self, human: crate::human_auth::HumanAuthRuntime) -> Self {
+ self.with_human_runtime(human, true)
+ }
+
+ /// Attach the runtime while preserving the startup decision about whether
+ /// human auth contributes authority. HTTP serving attaches the runtime
+ /// even before bootstrap so the transition can happen without restart.
+ #[must_use]
+ pub fn with_human_runtime(
+ mut self,
+ human: crate::human_auth::HumanAuthRuntime,
+ human_intended: bool,
+ ) -> Self {
+ self.human = Some(human);
+ self.human_intended = human_intended;
+ self
+ }
+
+ /// Per-server token pepper when multi-user lookup is enabled.
+ #[must_use]
+ pub fn pepper(&self) -> Option<&TokenPepper> {
+ self.multiuser.as_ref().map(|mu| &mu.pepper)
+ }
+
+ /// Whether browser cookies must be marked `Secure`.
+ #[must_use]
+ pub fn secure_cookie(&self) -> bool {
+ self.secure_cookie
+ }
+
+ /// Dedicated actor-proxy bearer, if configured.
+ #[must_use]
+ pub fn actor_proxy_bearer(&self) -> Option<&str> {
+ self.actor_proxy_bearer.as_deref()
+ }
+
+ /// True when machine authority or startup-intended human auth is
+ /// configured.
#[must_use]
pub fn enabled(&self) -> bool {
- self.expected.is_some()
+ self.expected.is_some() || self.human_intended
}
}
-/// axum middleware closure. Wire with
-/// `axum::middleware::from_fn_with_state(state, require_bearer)`.
-///
-/// Token sources, in priority order:
-/// 1. `Authorization: Bearer <token>` header. Works for any method.
-/// This is what MCP + hook clients send.
-/// 2. **GET only:** `Authorization: Basic <base64(user:token)>`.
-/// Username is ignored; the password portion is the token.
-/// Browsers send this automatically after the native credential
-/// prompt fires on a 401 + `WWW-Authenticate: Basic`. On success
-/// we also set the `ai_memory_auth` cookie so subsequent visits
-/// (including from a fresh browser session) skip the prompt.
-/// 3. **GET only:** `ai_memory_auth` cookie set by the Basic handshake.
-///
-/// POST / PUT / DELETE / etc. require the Bearer header. Cookie and
-/// Basic auth are GET-only, which confines cookie-CSRF to read-only
-/// pages — `/mcp` + `/hook` are POST-only and stay header-gated.
-///
-/// On 401 for GET requests the response includes both `Basic` and
-/// `Bearer` challenges in `WWW-Authenticate`. Browsers honour the
-/// `Basic` challenge (native dialog); MCP clients honour the `Bearer`
-/// challenge.
/// Every header the trusted-proxy assertion reads.
/// A repeated occurrence of any of them makes the assertion ambiguous — see
/// [`trusted_proxy_actor`].
@@ -275,82 +280,48 @@ fn trusted_proxy_actor(headers: &HeaderMap) -> Result<ActorContext, ProxyAsserti
Ok(asserted)
}
-/// axum middleware closure. Wire with
-/// `axum::middleware::from_fn_with_state(state, require_bearer)`.
-///
-/// Token sources, in priority order:
-/// 1. `Authorization: Bearer <token>` header. Works for any method.
-/// This is what MCP + hook clients send.
-/// 2. **GET only:** `Authorization: Basic <base64(user:token)>`.
-/// Username is ignored; the password portion is the token.
-/// Browsers send this automatically after the native credential
-/// prompt fires on a 401 + `WWW-Authenticate: Basic`. On success
-/// we also set the `ai_memory_auth` cookie so subsequent visits
-/// (including from a fresh browser session) skip the prompt.
-/// 3. **GET only:** `ai_memory_auth` cookie set by the Basic handshake.
-///
-/// POST / PUT / DELETE / etc. require the Bearer header. Cookie and
-/// Basic auth are GET-only, which confines cookie-CSRF to read-only
-/// pages — `/mcp` + `/hook` are POST-only and stay header-gated.
+/// Inspect `Authorization: Bearer` and inject actor / [`AuthLevel`] on
+/// success.
///
-/// On 401 for GET requests the response includes both `Basic` and
-/// `Bearer` challenges in `WWW-Authenticate`. Browsers honour the
-/// `Basic` challenge (native dialog); MCP clients honour the `Bearer`
-/// challenge.
-pub async fn require_bearer(
- State(state): State<Arc<AuthState>>,
- mut req: Request<axum::body::Body>,
- next: Next,
-) -> Response {
- // 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;
- };
-
- let is_get = req.method() == Method::GET;
- let from_bearer = extract_bearer_header(&req);
- let from_basic = if is_get {
- extract_basic_header(&req)
- } else {
- None
+/// * [`BearerAuth::Authenticated`] — extensions populated; caller runs `next`.
+/// * [`BearerAuth::Absent`] — no Bearer scheme (missing, Basic, empty, unknown).
+/// * [`BearerAuth::Rejected`] — Bearer scheme was present and did not authenticate.
+/// * `Err(Response)` — trusted-proxy assertion is malformed (400).
+pub async fn authenticate_bearer(
+ state: &AuthState,
+ req: &mut Request<axum::body::Body>,
+) -> Result<BearerAuth, Response> {
+ let Some(provided) = extract_bearer_from_headers(req.headers()) else {
+ return Ok(BearerAuth::Absent);
};
- let from_cookie = if is_get { extract_cookie(&req) } else { None };
-
- let provided = from_bearer
- .as_deref()
- .or(from_basic.as_deref())
- .or(from_cookie.as_deref())
- .unwrap_or("");
+ authenticate_token(state, req, &provided, true).await
+}
- // Rung 1: root credential. Actor assertion headers are intentionally
- // ignored here; only the distinct proxy credential may assert them.
- if bool::from(provided.as_bytes().ct_eq(expected.as_bytes())) {
+/// Authenticate one already-extracted token.
+///
+/// Browser Basic/cookie compatibility calls this with `allow_proxy=false`:
+/// proxy credentials may assert identities only through an explicit Bearer.
+pub(crate) async fn authenticate_token(
+ state: &AuthState,
+ req: &mut Request<axum::body::Body>,
+ provided: &str,
+ allow_proxy: bool,
+) -> Result<BearerAuth, Response> {
+ if provided.is_empty() {
+ return Ok(BearerAuth::Rejected);
+ }
+
+ if let Some(expected) = state.expected.as_deref()
+ && bool::from(provided.as_bytes().ct_eq(expected.as_bytes()))
+ {
req.extensions_mut().insert(state.root_actor.clone());
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
- // 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, state.secure_cookie).parse() {
- resp.headers_mut().insert(header::SET_COOKIE, cookie);
- }
- return resp;
- }
- return next.run(req).await;
+ return Ok(BearerAuth::Authenticated);
}
- // Rung 1b: only an explicit Bearer token can enter the trusted-proxy
- // branch. Basic auth and cookies are browser conveniences for the root
- // credential, not a way to impersonate the proxy.
- if let (Some(proxy_expected), Some(proxy_provided)) =
- (state.actor_proxy_bearer.as_deref(), from_bearer.as_deref())
- && bool::from(proxy_provided.as_bytes().ct_eq(proxy_expected.as_bytes()))
+ if allow_proxy
+ && let Some(proxy_expected) = state.actor_proxy_bearer.as_deref()
+ && bool::from(provided.as_bytes().ct_eq(proxy_expected.as_bytes()))
{
let actor = match trusted_proxy_actor(req.headers()) {
Ok(actor) => actor,
@@ -359,7 +330,7 @@ pub async fn require_bearer(
?error,
"auth rejected: invalid trusted-proxy identity assertion"
);
- return invalid_proxy_identity(error);
+ return Err(invalid_proxy_identity(error));
}
};
let level = if state.asserts_root_identity(&actor) {
@@ -367,120 +338,139 @@ pub async fn require_bearer(
} else {
AuthLevel::User
};
- debug!(actor.user = ?actor.user, actor.issuer = ?actor.issuer, actor.sub = ?actor.sub, ?level, "identity asserted by trusted proxy");
+ debug!(
+ actor.user = ?actor.user,
+ actor.issuer = ?actor.issuer,
+ actor.sub = ?actor.sub,
+ ?level,
+ "identity asserted by trusted proxy"
+ );
req.extensions_mut().insert(actor);
req.extensions_mut().insert(level);
- return next.run(req).await;
+ return Ok(BearerAuth::Authenticated);
}
- // Rung 2: bearer matches neither root nor proxy. 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()
- {
+ if let Some(mu) = state.multiuser.as_ref() {
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");
+ Ok(Some(hit)) => {
+ debug!(actor.user = %hit.user.username, "authenticated as DB user");
let actor = ActorContext {
- user: Some(user.username.clone()),
- name: user.name.clone(),
- email: user.email.clone(),
+ user: Some(hit.user.username.clone()),
+ name: hit.user.name.clone(),
+ email: hit.user.email.clone(),
..ActorContext::default()
};
req.extensions_mut().insert(actor);
- req.extensions_mut().insert(user.id);
+ req.extensions_mut().insert(hit.user.id);
req.extensions_mut().insert(AuthLevel::User);
-
- // 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;
+ let user_id = hit.user.id;
+ let credential_id = hit.credential_id;
tokio::spawn(async move {
+ if let Err(e) = writer.touch_api_credential(credential_id).await {
+ tracing::warn!(
+ error = %e,
+ credential_id = %credential_id,
+ "touch_api_credential failed"
+ );
+ }
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, state.secure_cookie).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.
+ return Ok(BearerAuth::Authenticated);
}
+ Ok(None) => return Ok(BearerAuth::Rejected),
Err(e) => {
- tracing::error!(error = %e, "auth: users table lookup failed");
- return unauthorized(is_get);
+ tracing::error!(error = %e, "auth: api_credentials lookup failed");
+ return Ok(BearerAuth::Rejected);
}
}
}
- debug!("auth rejected: invalid or missing token");
- unauthorized(is_get)
+ Ok(BearerAuth::Rejected)
+}
+
+/// Machine-only middleware. Wire with
+/// `axum::middleware::from_fn_with_state(state, require_bearer)`.
+///
+/// Anonymous passthrough happens only when [`AuthState::enabled`] is
+/// false (zero-config loopback). Human mode without a presented Bearer
+/// is 401 — sessions never authenticate `/mcp`.
+pub async fn require_bearer(
+ State(state): State<Arc<AuthState>>,
+ mut req: Request<axum::body::Body>,
+ next: Next,
+) -> Response {
+ match authenticate_bearer(&state, &mut req).await {
+ Ok(BearerAuth::Authenticated) => next.run(req).await,
+ Err(resp) => resp,
+ Ok(BearerAuth::Absent) if !state.enabled() => {
+ req.extensions_mut().insert(ActorContext::anonymous());
+ req.extensions_mut().insert(AuthLevel::Anonymous);
+ next.run(req).await
+ }
+ Ok(BearerAuth::Absent | BearerAuth::Rejected) => {
+ debug!("auth rejected: invalid or missing token");
+ unauthorized_bearer()
+ }
+ }
}
-fn extract_bearer_header(req: &Request<axum::body::Body>) -> Option<String> {
- let h = req.headers().get(header::AUTHORIZATION)?.to_str().ok()?;
- // Accept both "Bearer xxx" and "bearer xxx" (case-insensitive
- // scheme per RFC 7235 §2.1).
- let (scheme, value) = h.split_once(' ')?;
- if scheme.eq_ignore_ascii_case("Bearer") {
- Some(value.trim_start().to_string())
- } else {
- None
+/// Bearer token value from all `Authorization` occurrences.
+///
+/// Basic, unknown, and empty headers are discarded. Exactly one Bearer
+/// attempt is accepted; repeated Bearer attempts collapse to an empty
+/// value so authentication fails closed rather than choosing one.
+#[must_use]
+pub fn extract_bearer_from_headers(headers: &HeaderMap) -> Option<String> {
+ let mut bearer = None;
+ for value in headers.get_all(header::AUTHORIZATION) {
+ let Ok(raw) = value.to_str() else {
+ continue;
+ };
+ let trimmed = raw.trim();
+ let split_at = trimmed.find([' ', '\t']);
+ let (scheme, token) = split_at.map_or((trimmed, ""), |idx| {
+ (&trimmed[..idx], trimmed[idx..].trim())
+ });
+ if !scheme.eq_ignore_ascii_case("Bearer") {
+ continue;
+ }
+ if bearer.is_some() {
+ return Some(String::new());
+ }
+ bearer = Some(token.to_string());
}
+ bearer
}
-fn extract_basic_header(req: &Request<axum::body::Body>) -> Option<String> {
- use base64::Engine;
- let h = req.headers().get(header::AUTHORIZATION)?.to_str().ok()?;
- let (scheme, value) = h.split_once(' ')?;
- if !scheme.eq_ignore_ascii_case("Basic") {
- return None;
- }
- let decoded = base64::engine::general_purpose::STANDARD
- .decode(value.trim_start())
- .ok()?;
- let s = std::str::from_utf8(&decoded).ok()?;
- // Standard form: `user:password`. We ignore the username (the
- // browser dialog always asks for one but we don't have multi-user
- // accounts — only the password = bearer token matters).
- let (_user, pass) = s.split_once(':')?;
- Some(pass.to_string())
+/// True when `Authorization` uses the Bearer scheme, even with no token.
+#[must_use]
+pub fn has_bearer_scheme(headers: &HeaderMap) -> bool {
+ extract_bearer_from_headers(headers).is_some()
}
-fn extract_cookie(req: &Request<axum::body::Body>) -> Option<String> {
- let h = req.headers().get(header::COOKIE)?.to_str().ok()?;
- for pair in h.split(';') {
- let pair = pair.trim();
- if let Some(val) = pair.strip_prefix(&format!("{AUTH_COOKIE}=")) {
- return Some(val.to_string());
- }
- }
- None
+/// True when any trusted-proxy identity header is present.
+#[must_use]
+pub fn any_actor_header(headers: &HeaderMap) -> bool {
+ PROXY_ASSERTION_HEADERS
+ .iter()
+ .any(|name| headers.contains_key(*name))
}
-fn build_session_cookie(token: &str, secure_cookie: bool) -> String {
- // 30-day Max-Age — long enough that re-entering the credential
- // every month is rare. HttpOnly hides it from inline JS and Strict keeps
- // cross-site requests from riding it. `Secure` remains opt-in so direct
- // loopback/plain-HTTP browser use works; never infer it from proxy headers.
- let secure = if secure_cookie { "; Secure" } else { "" };
- format!("{AUTH_COOKIE}={token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=2592000{secure}")
+/// 401 with `WWW-Authenticate: Bearer` only. Never advertise Basic.
+#[must_use]
+pub fn unauthorized_bearer() -> Response {
+ let mut resp = (StatusCode::UNAUTHORIZED, "auth required\n").into_response();
+ resp.headers_mut().insert(
+ header::WWW_AUTHENTICATE,
+ format!("Bearer realm=\"{AUTH_REALM}\", error=\"invalid_token\"")
+ .parse()
+ .expect("static header value is valid"),
+ );
+ resp
}
/// The proxy's identity headers contradict themselves. Not a 401 — the
@@ -502,32 +492,6 @@ fn invalid_proxy_identity(error: ProxyAssertionError) -> Response {
(StatusCode::BAD_REQUEST, message).into_response()
}
-fn unauthorized(include_basic_challenge: bool) -> Response {
- let mut resp = (StatusCode::UNAUTHORIZED, "auth required\n").into_response();
- // Order of challenges matters: browsers parse the first challenge
- // they understand and show the dialog for it. Putting `Basic`
- // first ensures GET-from-browser triggers the native prompt; MCP
- // clients (which speak only Bearer) ignore the Basic and read
- // their challenge from the second value.
- //
- // Non-GET 401s skip the Basic challenge — sending it on a POST
- // would invite the browser to dialog-prompt for an endpoint
- // it can't authenticate this way anyway.
- let value = if include_basic_challenge {
- format!(
- "Basic realm=\"{AUTH_REALM}\", \
- Bearer realm=\"{AUTH_REALM}\", error=\"invalid_token\""
- )
- } else {
- format!("Bearer realm=\"{AUTH_REALM}\", error=\"invalid_token\"")
- };
- resp.headers_mut().insert(
- header::WWW_AUTHENTICATE,
- value.parse().expect("static header value is valid"),
- );
- resp
-}
-
/// Generate a fresh random bearer token, hex-encoded.
///
/// `bytes` is the entropy budget; 32 bytes (256 bits) is plenty for
@@ -602,10 +566,8 @@ mod tests {
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
let www = resp.headers().get(header::WWW_AUTHENTICATE).unwrap();
let www = www.to_str().unwrap();
- // GET 401 advertises BOTH challenges so browsers (Basic) and
- // MCP clients (Bearer) each see what they understand.
assert!(www.contains("Bearer"));
- assert!(www.contains("Basic"));
+ assert!(!www.contains("Basic"));
}
#[tokio::test]
@@ -674,7 +636,7 @@ mod tests {
}
#[tokio::test]
- async fn cookie_with_right_token_passes_get() {
+ async fn cookie_is_never_a_machine_credential() {
let r = router_with_auth(Some("right-token"));
let resp = r
.oneshot(
@@ -686,7 +648,8 @@ mod tests {
)
.await
.unwrap();
- assert_eq!(resp.status(), StatusCode::OK);
+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+ assert!(resp.headers().get(header::SET_COOKIE).is_none());
}
#[tokio::test]
@@ -706,44 +669,6 @@ mod tests {
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
- #[tokio::test]
- async fn cookie_with_wrong_token_fails() {
- let r = router_with_auth(Some("right-token"));
- let resp = r
- .oneshot(
- Request::builder()
- .uri("/probe")
- .header("Cookie", "ai_memory_auth=wrong-token")
- .body(Body::empty())
- .unwrap(),
- )
- .await
- .unwrap();
- assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
- }
-
- #[tokio::test]
- async fn cookie_ignored_on_post() {
- // POST routes must use Bearer header; cookie auth is GET-only
- // to keep the CSRF surface confined to read paths.
- let state = Arc::new(AuthState::new(Some("right-token".to_string())));
- let r = Router::new()
- .route("/probe", axum::routing::post(|| async { "ok" }))
- .layer(axum::middleware::from_fn_with_state(state, require_bearer));
- let resp = r
- .oneshot(
- Request::builder()
- .method("POST")
- .uri("/probe")
- .header("Cookie", "ai_memory_auth=right-token")
- .body(Body::empty())
- .unwrap(),
- )
- .await
- .unwrap();
- assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
- }
-
/// Helper: build a Basic-auth header value (any username, token as password).
fn basic_auth(token: &str) -> String {
use base64::Engine;
@@ -755,7 +680,7 @@ mod tests {
}
#[tokio::test]
- async fn basic_auth_with_right_token_passes_get_and_sets_non_secure_cookie() {
+ async fn basic_auth_is_never_a_machine_credential() {
let r = router_with_auth(Some("right-token"));
let resp = r
.oneshot(
@@ -767,64 +692,16 @@ mod tests {
)
.await
.unwrap();
- assert_eq!(resp.status(), StatusCode::OK);
- // First successful Basic hit also stamps the cookie so the
- // browser doesn't dialog-prompt every session.
- let cookie = resp
- .headers()
- .get(header::SET_COOKIE)
- .expect("set-cookie on first Basic-auth success")
- .to_str()
- .unwrap();
- assert_eq!(
- cookie,
- "ai_memory_auth=right-token; HttpOnly; SameSite=Strict; Path=/; Max-Age=2592000"
- );
- }
-
- #[tokio::test]
- async fn basic_auth_sets_secure_cookie_only_when_explicitly_enabled() {
- let r = router_with_auth_secure_cookie(Some("right-token"), true);
- let resp = r
- .oneshot(
- Request::builder()
- .uri("/probe")
- .header("Authorization", basic_auth("right-token"))
- .body(Body::empty())
- .unwrap(),
- )
- .await
- .unwrap();
- assert_eq!(resp.status(), StatusCode::OK);
- assert_eq!(
- resp.headers()
- .get(header::SET_COOKIE)
- .expect("set-cookie on first Basic-auth success")
- .to_str()
- .unwrap(),
- "ai_memory_auth=right-token; HttpOnly; SameSite=Strict; Path=/; Max-Age=2592000; Secure"
- );
- }
-
- #[tokio::test]
- async fn basic_auth_with_wrong_password_returns_401() {
- let r = router_with_auth(Some("right-token"));
- let resp = r
- .oneshot(
- Request::builder()
- .uri("/probe")
- .header("Authorization", basic_auth("wrong-token"))
- .body(Body::empty())
- .unwrap(),
- )
- .await
- .unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+ assert!(resp.headers().get(header::SET_COOKIE).is_none());
+ let www = resp.headers().get(header::WWW_AUTHENTICATE).unwrap();
+ let www = www.to_str().unwrap();
+ assert!(www.contains("Bearer"));
+ assert!(!www.contains("Basic"));
}
#[tokio::test]
async fn basic_auth_ignored_on_post() {
- // POST routes must use Bearer header; Basic auth is GET-only.
let state = Arc::new(AuthState::new(Some("right-token".to_string())));
let r = Router::new()
.route("/probe", axum::routing::post(|| async { "ok" }))
@@ -841,31 +718,41 @@ mod tests {
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
- // POST 401 must NOT advertise Basic — browsers would dialog
- // for a route they can't authenticate this way.
let www = resp.headers().get(header::WWW_AUTHENTICATE).unwrap();
let www = www.to_str().unwrap();
assert!(www.contains("Bearer"));
assert!(!www.contains("Basic"));
}
- #[tokio::test]
- async fn cookie_request_does_not_re_set_cookie() {
- // Already-authed-by-cookie requests don't need a Set-Cookie
- // refresh; that's a waste of bandwidth on every navigation.
- let r = router_with_auth(Some("right-token"));
- let resp = r
- .oneshot(
- Request::builder()
- .uri("/probe")
- .header("Cookie", "ai_memory_auth=right-token")
- .body(Body::empty())
- .unwrap(),
- )
- .await
- .unwrap();
- assert_eq!(resp.status(), StatusCode::OK);
- assert!(resp.headers().get(header::SET_COOKIE).is_none());
+ #[test]
+ fn bearer_parser_discards_other_schemes_and_accepts_tabs() {
+ let mut headers = HeaderMap::new();
+ headers.append(
+ header::AUTHORIZATION,
+ axum::http::HeaderValue::from_static("Basic saved-browser-value"),
+ );
+ headers.append(
+ header::AUTHORIZATION,
+ axum::http::HeaderValue::from_static("bEaReR\tmachine-token"),
+ );
+ assert_eq!(
+ extract_bearer_from_headers(&headers).as_deref(),
+ Some("machine-token")
+ );
+ }
+
+ #[test]
+ fn bearer_parser_rejects_multiple_bearer_attempts() {
+ let mut headers = HeaderMap::new();
+ headers.append(
+ header::AUTHORIZATION,
+ axum::http::HeaderValue::from_static("Bearer first"),
+ );
+ headers.append(
+ header::AUTHORIZATION,
+ axum::http::HeaderValue::from_static("Bearer second"),
+ );
+ assert_eq!(extract_bearer_from_headers(&headers).as_deref(), Some(""));
}
#[test]
@@ -1447,17 +1334,28 @@ mod tests {
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();
+ let user_id = store
+ .writer
+ .create_human_user(new_user, ai_memory_core::UserRole::User, None, false)
+ .await
+ .unwrap();
+ let token = ai_memory_store::generate_api_key().unwrap();
+ let token_hash = ai_memory_store::hash_token(&token, &pepper);
store
.writer
- .create_user(new_user, token_hash)
+ .create_api_credential(
+ ai_memory_core::ApiCredentialId::new(),
+ user_id,
+ "test".into(),
+ token_hash,
+ Some(ai_memory_store::api_key_preview(&token)),
+ )
.await
.unwrap();
@@ -1517,14 +1415,12 @@ mod tests {
}
#[tokio::test]
- async fn rung2_expired_user_token_is_rejected() {
- // Expiring a user's token must immediately stop authenticating
+ async fn rung2_revoked_api_credential_is_rejected() {
+ // Revoking a native API key must immediately stop authenticating
// (no 30s cache window or similar). Critical for `ai-memory
- // user expire` to be useful as an offboarding tool.
+ // api-key revoke` 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()
@@ -1534,8 +1430,16 @@ mod tests {
.await
.unwrap()
.unwrap();
+ let creds = state
+ .multiuser
+ .as_ref()
+ .unwrap()
+ .reader
+ .list_api_credentials_for_user(user.id)
+ .await
+ .unwrap();
let writer = state.multiuser.as_ref().unwrap().writer.clone();
- writer.expire_user_token(user.id).await.unwrap();
+ writer.revoke_api_credential(creds[0].id).await.unwrap();
let r = router_with_state(state);
let resp = r
@@ -1556,8 +1460,8 @@ mod tests {
}
#[tokio::test]
- async fn rung2_revived_user_token_authenticates_again() {
- let (_tmp, state, token) = setup_multiuser("alice").await;
+ async fn rung2_rotated_api_credential_replaces_the_secret() {
+ let (_tmp, state, old_token) = setup_multiuser("alice").await;
let user = state
.multiuser
.as_ref()
@@ -1567,22 +1471,50 @@ mod tests {
.await
.unwrap()
.unwrap();
+ let creds = state
+ .multiuser
+ .as_ref()
+ .unwrap()
+ .reader
+ .list_api_credentials_for_user(user.id)
+ .await
+ .unwrap();
+ let pepper = state.pepper().expect("pepper");
+ let new_token = ai_memory_store::generate_api_key().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();
+ writer
+ .rotate_api_credential(
+ creds[0].id,
+ ai_memory_store::hash_token(&new_token, pepper),
+ Some(ai_memory_store::api_key_preview(&new_token)),
+ )
+ .await
+ .unwrap();
let r = router_with_state(state);
- let resp = r
+ let old = r
+ .clone()
.oneshot(
Request::builder()
.uri("/probe")
- .header("Authorization", format!("Bearer {token}"))
+ .header("Authorization", format!("Bearer {old_token}"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
- assert_eq!(resp.status(), StatusCode::OK);
+ assert_eq!(old.status(), StatusCode::UNAUTHORIZED);
+ let new = r
+ .oneshot(
+ Request::builder()
+ .uri("/probe")
+ .header("Authorization", format!("Bearer {new_token}"))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(new.status(), StatusCode::OK);
}
#[tokio::test]
@@ -1624,16 +1556,27 @@ mod tests {
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();
+ let user_id = store
+ .writer
+ .create_human_user(user, ai_memory_core::UserRole::User, None, false)
+ .await
+ .unwrap();
+ let token = ai_memory_store::generate_api_key().unwrap();
store
.writer
- .create_user(user, ai_memory_store::hash_token(&token, &pepper))
+ .create_api_credential(
+ ai_memory_core::ApiCredentialId::new(),
+ user_id,
+ "test".into(),
+ ai_memory_store::hash_token(&token, &pepper),
+ Some(ai_memory_store::api_key_preview(&token)),
+ )
.await
.unwrap();
@@ -1668,6 +1611,28 @@ mod tests {
assert!(!AuthState::new(Some(" ".into())).enabled());
}
+ #[tokio::test]
+ async fn require_bearer_401_advertises_bearer_not_basic() {
+ let resp = router_with_auth(Some("secret"))
+ .oneshot(
+ Request::builder()
+ .uri("/probe")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+ let www = resp
+ .headers()
+ .get(header::WWW_AUTHENTICATE)
+ .expect("WWW-Authenticate")
+ .to_str()
+ .unwrap();
+ assert!(www.contains("Bearer"), "{www}");
+ assert!(!www.to_ascii_lowercase().contains("basic"), "{www}");
+ }
+
#[tokio::test]
async fn rung1_setup_with_unknown_bearer_returns_401() {
// Existing single-user setup (rung 1 only, no multi-user). An
diff --git a/crates/ai-memory-mcp/src/human_auth.rs b/crates/ai-memory-mcp/src/human_auth.rs
new file mode 100644
index 00000000..8c3830a4
--- /dev/null
+++ b/crates/ai-memory-mcp/src/human_auth.rs
@@ -0,0 +1,2151 @@
+//! Human authentication: passwords, web sessions, CSRF, recovery.
+//!
+//! Four credential classes stay isolated here. Human passwords only
+//! issue sessions. Sessions never authenticate `/mcp`, hooks, or
+//! workstreams. Recovery never issues a session. Native API keys are
+//! handled by [`crate::auth::require_bearer`] / dual-auth Bearer.
+
+use std::collections::{HashMap, VecDeque};
+use std::net::{IpAddr, SocketAddr};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use ai_memory_core::{
+ ActorContext, AuthLevel, Capability, User, UserId, UserRole, validate_human_password,
+};
+use ai_memory_store::{LiveWebSession, ReaderPool, WriterHandle, hash_session_secret, hash_token};
+use axum::Json;
+use axum::Router;
+use axum::extract::State;
+use axum::http::{HeaderMap, Method, Request, StatusCode, header};
+use axum::middleware::Next;
+use axum::response::{IntoResponse, Response};
+use axum::routing::{get, post};
+use serde::{Deserialize, Serialize};
+use subtle::ConstantTimeEq;
+
+use crate::auth::AuthState;
+
+/// HttpOnly session cookie.
+pub const SESSION_COOKIE: &str = "ai_memory_session";
+/// Readable CSRF cookie.
+pub const CSRF_COOKIE: &str = "ai_memory_csrf";
+/// Deprecated Basic-auth compatibility cookie. Issued only before human auth
+/// activates, then expired on the next browser response.
+pub const LEGACY_AUTH_COOKIE: &str = "ai_memory_auth";
+/// CSRF header required on cookie-authenticated mutations.
+pub const CSRF_HEADER: &str = "x-csrf-token";
+
+const LOGIN_WINDOW: Duration = Duration::from_secs(60);
+const LOGIN_IP_LIMIT: usize = 10;
+const LOGIN_LIMITER_MAX_KEYS: usize = 4_096;
+
+/// Runtime extras for human auth. Attached to [`AuthState`].
+#[derive(Clone)]
+pub struct HumanAuthRuntime {
+ /// Store reader.
+ pub reader: ReaderPool,
+ /// Store writer.
+ pub writer: WriterHandle,
+ /// SHA-256 of the break-glass recovery secret.
+ pub recovery_token_hash: Option<[u8; 32]>,
+ /// Recovery / bootstrap target username.
+ pub root_username: String,
+ /// Optional display fields for bootstrap/recovery create.
+ pub root_name: Option<String>,
+ /// Optional email for bootstrap/recovery create.
+ pub root_email: Option<String>,
+ /// Plaintext secrets that must not be chosen as a human password.
+ pub reserved_passwords: Vec<String>,
+ /// CIDRs allowed to supply `X-Forwarded-For`.
+ pub trusted_proxy_cidrs: Vec<Cidr>,
+ /// Login rate limiter.
+ pub limiter: Arc<LoginLimiter>,
+}
+
+/// IPv4/IPv6 CIDR.
+#[derive(Debug, Clone, Copy)]
+pub struct Cidr {
+ addr: IpAddr,
+ prefix: u8,
+}
+
+impl Cidr {
+ /// Parse `a.b.c.d/n` or a bare address (`/32` or `/128`).
+ ///
+ /// # Errors
+ /// Malformed address or prefix.
+ pub fn parse(spec: &str) -> Result<Self, String> {
+ let spec = spec.trim();
+ if spec.is_empty() {
+ return Err("empty CIDR".into());
+ }
+ let (addr_s, prefix) = if let Some((a, p)) = spec.split_once('/') {
+ let prefix: u8 = p
+ .parse()
+ .map_err(|_| format!("invalid CIDR prefix in {spec:?}"))?;
+ (a, prefix)
+ } else if spec.contains(':') {
+ (spec, 128)
+ } else {
+ (spec, 32)
+ };
+ let addr: IpAddr = addr_s
+ .parse()
+ .map_err(|_| format!("invalid CIDR address in {spec:?}"))?;
+ let max = if addr.is_ipv4() { 32 } else { 128 };
+ if prefix > max {
+ return Err(format!("CIDR prefix {prefix} exceeds {max}"));
+ }
+ Ok(Self { addr, prefix })
+ }
+
+ /// Membership test.
+ #[must_use]
+ pub fn contains(self, ip: IpAddr) -> bool {
+ match (self.addr, ip) {
+ (IpAddr::V4(net), IpAddr::V4(got)) => {
+ let shift = 32u32.saturating_sub(u32::from(self.prefix));
+ let mask = if shift >= 32 { 0 } else { u32::MAX << shift };
+ (u32::from(net) & mask) == (u32::from(got) & mask)
+ }
+ (IpAddr::V6(net), IpAddr::V6(got)) => {
+ let shift = 128u32.saturating_sub(u32::from(self.prefix));
+ let mask = if shift >= 128 { 0 } else { u128::MAX << shift };
+ (u128::from(net) & mask) == (u128::from(got) & mask)
+ }
+ _ => false,
+ }
+ }
+}
+
+/// Bounded per-IP and per-username login attempt windows.
+#[derive(Debug, Default)]
+pub struct LoginLimiter {
+ ip: Mutex<HashMap<IpAddr, VecDeque<Instant>>>,
+ user: Mutex<HashMap<[u8; 32], VecDeque<Instant>>>,
+}
+
+impl LoginLimiter {
+ fn prune(q: &mut VecDeque<Instant>, now: Instant) {
+ while q
+ .front()
+ .is_some_and(|t| now.saturating_duration_since(*t) > LOGIN_WINDOW)
+ {
+ q.pop_front();
+ }
+ }
+
+ fn record_failure<K>(map: &mut HashMap<K, VecDeque<Instant>>, key: K, now: Instant)
+ where
+ K: Copy + Eq + std::hash::Hash,
+ {
+ if !map.contains_key(&key) && map.len() >= LOGIN_LIMITER_MAX_KEYS {
+ map.retain(|_, q| {
+ Self::prune(q, now);
+ !q.is_empty()
+ });
+ if map.len() >= LOGIN_LIMITER_MAX_KEYS
+ && let Some(oldest) = map
+ .iter()
+ .filter_map(|(key, q)| q.front().map(|instant| (*key, *instant)))
+ .min_by_key(|(_, instant)| *instant)
+ .map(|(key, _)| key)
+ {
+ map.remove(&oldest);
+ }
+ }
+ let q = map.entry(key).or_default();
+ Self::prune(q, now);
+ q.push_back(now);
+ }
+
+ /// True when this IP has already spent its window. Call before Argon2.
+ #[must_use]
+ pub fn ip_blocked(&self, ip: IpAddr) -> bool {
+ let now = Instant::now();
+ let mut map = self.ip.lock().unwrap_or_else(|e| e.into_inner());
+ let Some(q) = map.get_mut(&ip) else {
+ return false;
+ };
+ Self::prune(q, now);
+ let blocked = q.len() >= LOGIN_IP_LIMIT;
+ if q.is_empty() {
+ map.remove(&ip);
+ }
+ blocked
+ }
+
+ /// Record an IP failure.
+ pub fn record_ip_failure(&self, ip: IpAddr) {
+ let now = Instant::now();
+ let mut map = self.ip.lock().unwrap_or_else(|e| e.into_inner());
+ Self::record_failure(&mut map, ip, now);
+ }
+
+ /// Record a username failure in a fixed-size, bounded key space.
+ pub fn record_username_failure(&self, username: &str) {
+ let now = Instant::now();
+ let key = hash_session_secret(username);
+ let mut map = self.user.lock().unwrap_or_else(|e| e.into_inner());
+ Self::record_failure(&mut map, key, now);
+ }
+}
+
+/// Public login + recovery (no session, no Bearer).
+pub fn public_auth_router(state: Arc<AuthState>) -> Router {
+ Router::new()
+ .route("/auth/login", post(handle_login))
+ .route("/auth/recovery", post(handle_recovery))
+ .with_state(state)
+}
+
+/// Session-class `/auth/me`, password change, logout.
+pub fn session_auth_router(state: Arc<AuthState>) -> Router {
+ Router::new()
+ .route("/auth/me", get(handle_me))
+ .route_layer(axum::middleware::from_fn_with_state(
+ state.clone(),
+ require_session_or_anonymous,
+ ))
+ .merge(
+ Router::new()
+ .route("/auth/password", post(handle_change_password))
+ .route("/auth/logout", post(handle_logout))
+ .route_layer(axum::middleware::from_fn_with_state(
+ state.clone(),
+ require_session,
+ )),
+ )
+ .with_state(state)
+}
+
+/// Private sidecar introspection. Handler checks the actor-proxy bearer.
+pub fn internal_auth_router(state: Arc<AuthState>) -> Router {
+ Router::new()
+ .route(
+ "/internal/auth/session-introspect",
+ post(handle_session_introspect),
+ )
+ .with_state(state)
+}
+
+#[derive(Debug, Deserialize)]
+struct LoginBody {
+ username: String,
+ password: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct RecoveryBody {
+ recovery_token: String,
+ new_password: String,
+ new_password_confirmation: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct ChangePasswordBody {
+ current_password: String,
+ new_password: String,
+ new_password_confirmation: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct IntrospectBody {
+ session: String,
+ method: String,
+ #[serde(default)]
+ csrf: Option<String>,
+}
+
+#[derive(Debug, Serialize)]
+struct MeBody {
+ username: Option<String>,
+ name: Option<String>,
+ role: Option<UserRole>,
+ must_change_password: bool,
+ via: &'static str,
+ capabilities: CapabilitiesBody,
+}
+
+#[derive(Debug, Serialize)]
+struct CapabilitiesBody {
+ normal_read: bool,
+ normal_write: bool,
+ admin: bool,
+ user_management: bool,
+}
+
+fn capabilities_for(level: AuthLevel, must_change: bool) -> CapabilitiesBody {
+ let distinguishes = matches!(level, AuthLevel::Root | AuthLevel::User);
+ let admin_ok = !must_change && level.authorize(Capability::Admin, distinguishes).is_ok();
+ let users_ok = !must_change
+ && level
+ .authorize(Capability::UserManagement, distinguishes)
+ .is_ok();
+ CapabilitiesBody {
+ normal_read: !must_change
+ && level
+ .authorize(Capability::NormalRead, distinguishes)
+ .is_ok(),
+ normal_write: !must_change
+ && level
+ .authorize(Capability::NormalWrite, distinguishes)
+ .is_ok(),
+ admin: admin_ok,
+ user_management: users_ok,
+ }
+}
+
+fn reserved_refs(runtime: &HumanAuthRuntime) -> Vec<&str> {
+ runtime
+ .reserved_passwords
+ .iter()
+ .map(String::as_str)
+ .collect()
+}
+
+fn me_snapshot(user: &User) -> MeBody {
+ let level = if user.role == UserRole::Root {
+ AuthLevel::Root
+ } else {
+ AuthLevel::User
+ };
+ MeBody {
+ username: Some(user.username.clone()),
+ name: user.name.clone(),
+ role: Some(user.role),
+ must_change_password: user.must_change_password,
+ via: "session",
+ capabilities: capabilities_for(level, user.must_change_password),
+ }
+}
+
+fn json_err(status: StatusCode, msg: &str) -> Response {
+ (status, Json(serde_json::json!({ "error": msg }))).into_response()
+}
+
+fn peer_ip(headers: &HeaderMap, extensions: &axum::http::Extensions, cidrs: &[Cidr]) -> IpAddr {
+ let peer = extensions
+ .get::<axum::extract::ConnectInfo<SocketAddr>>()
+ .map(|c| c.0.ip());
+ let Some(peer) = peer else {
+ return IpAddr::from([0, 0, 0, 0]);
+ };
+ if !cidrs.iter().any(|c| c.contains(peer)) {
+ return peer;
+ }
+
+ let forwarded = headers.get_all("x-forwarded-for");
+ let mut hops = Vec::new();
+ let mut found = false;
+ for value in forwarded.iter() {
+ found = true;
+ let Ok(value) = value.to_str() else {
+ return peer;
+ };
+ for hop in value.split(',') {
+ let Ok(ip) = hop.trim().parse() else {
+ return peer;
+ };
+ hops.push(ip);
+ }
+ }
+ if !found {
+ return peer;
+ }
+ hops.iter()
+ .rev()
+ .find(|ip| !cidrs.iter().any(|c| c.contains(**ip)))
+ .copied()
+ .or_else(|| hops.first().copied())
+ .unwrap_or(peer)
+}
+
+fn cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
+ let h = headers.get(header::COOKIE)?.to_str().ok()?;
+ for pair in h.split(';') {
+ let pair = pair.trim();
+ if let Some(val) = pair.strip_prefix(&format!("{name}=")) {
+ return Some(val.to_string());
+ }
+ }
+ None
+}
+
+fn legacy_basic_password(headers: &HeaderMap) -> Option<String> {
+ use base64::Engine;
+ let value = headers.get(header::AUTHORIZATION)?.to_str().ok()?;
+ let (scheme, encoded) = value.split_once([' ', '\t'])?;
+ if !scheme.eq_ignore_ascii_case("Basic") {
+ return None;
+ }
+ let decoded = base64::engine::general_purpose::STANDARD
+ .decode(encoded.trim())
+ .ok()?;
+ let credentials = std::str::from_utf8(&decoded).ok()?;
+ let (_, password) = credentials.split_once(':')?;
+ Some(password.to_string())
+}
+
+fn legacy_browser_credential(headers: &HeaderMap) -> Option<(String, bool)> {
+ legacy_basic_password(headers)
+ .map(|token| (token, true))
+ .or_else(|| cookie_value(headers, LEGACY_AUTH_COOKIE).map(|token| (token, false)))
+}
+
+fn legacy_cookie(token: &str, secure: bool) -> String {
+ set_cookie(LEGACY_AUTH_COOKIE, token, true, 2_592_000, secure)
+}
+
+fn unauthorized_legacy_browser() -> Response {
+ let mut response = crate::auth::unauthorized_bearer();
+ response.headers_mut().insert(
+ header::WWW_AUTHENTICATE,
+ "Basic realm=\"ai-memory\", Bearer realm=\"ai-memory\", error=\"invalid_token\""
+ .parse()
+ .expect("static challenge is a valid header value"),
+ );
+ response
+}
+
+async fn human_auth_configured(state: &AuthState) -> Result<bool, Response> {
+ let Some(runtime) = state.human.as_ref() else {
+ return Ok(false);
+ };
+ if runtime
+ .reader
+ .bootstrap_completed()
+ .await
+ .map_err(|error| json_err(StatusCode::INTERNAL_SERVER_ERROR, &error.to_string()))?
+ {
+ return Ok(true);
+ }
+ runtime
+ .reader
+ .any_password_hash()
+ .await
+ .map_err(|error| json_err(StatusCode::INTERNAL_SERVER_ERROR, &error.to_string()))
+}
+
+fn set_cookie(name: &str, value: &str, http_only: bool, max_age: i64, secure: bool) -> String {
+ let http = if http_only { "; HttpOnly" } else { "" };
+ let sec = if secure { "; Secure" } else { "" };
+ format!("{name}={value}{http}; SameSite=Strict; Path=/; Max-Age={max_age}{sec}")
+}
+
+fn expire_legacy(secure: bool) -> String {
+ set_cookie(LEGACY_AUTH_COOKIE, "", true, 0, secure)
+}
+
+fn seconds_until_expiry(expires_at: i64) -> i64 {
+ expires_at
+ .saturating_sub(jiff::Timestamp::now().as_microsecond())
+ .div_euclid(1_000_000)
+ .max(0)
+}
+
+fn append_session_cookies(
+ resp: &mut Response,
+ session: &str,
+ csrf: &str,
+ expires_at: i64,
+ secure: bool,
+) {
+ let headers = resp.headers_mut();
+ let max_age = seconds_until_expiry(expires_at);
+ if let Ok(v) = set_cookie(SESSION_COOKIE, session, true, max_age, secure).parse() {
+ headers.append(header::SET_COOKIE, v);
+ }
+ if let Ok(v) = set_cookie(CSRF_COOKIE, csrf, false, max_age, secure).parse() {
+ headers.append(header::SET_COOKIE, v);
+ }
+ if let Ok(v) = expire_legacy(secure).parse() {
+ headers.append(header::SET_COOKIE, v);
+ }
+}
+
+fn attach_legacy_expire(resp: &mut Response, secure: bool) {
+ if let Ok(v) = expire_legacy(secure).parse() {
+ resp.headers_mut().append(header::SET_COOKIE, v);
+ }
+}
+
+/// Expire the deprecated Basic-auth cookie once human auth is active.
+pub async fn expire_legacy_cookie_mw(
+ State(state): State<Arc<AuthState>>,
+ req: Request<axum::body::Body>,
+ next: Next,
+) -> Response {
+ let expire = human_auth_configured(&state).await.unwrap_or(true);
+ let mut resp = next.run(req).await;
+ if expire {
+ attach_legacy_expire(&mut resp, state.secure_cookie());
+ }
+ resp
+}
+
+fn clear_session_cookies(resp: &mut Response, secure: bool) {
+ let headers = resp.headers_mut();
+ if let Ok(v) = set_cookie(SESSION_COOKIE, "", true, 0, secure).parse() {
+ headers.append(header::SET_COOKIE, v);
+ }
+ if let Ok(v) = set_cookie(CSRF_COOKIE, "", false, 0, secure).parse() {
+ headers.append(header::SET_COOKIE, v);
+ }
+ if let Ok(v) = expire_legacy(secure).parse() {
+ headers.append(header::SET_COOKIE, v);
+ }
+}
+
+fn is_reserved_password(runtime: &HumanAuthRuntime, password: &str) -> bool {
+ runtime
+ .reserved_passwords
+ .iter()
+ .any(|s| !s.is_empty() && bool::from(s.as_bytes().ct_eq(password.as_bytes())))
+ || runtime.recovery_token_hash.is_some_and(|expected| {
+ bool::from(
+ hash_session_secret(password)
+ .as_slice()
+ .ct_eq(expected.as_slice()),
+ )
+ })
+}
+
+async fn password_collides_with_api_key(
+ runtime: &HumanAuthRuntime,
+ pepper: Option<&ai_memory_store::TokenPepper>,
+ password: &str,
+) -> Result<bool, Response> {
+ let Some(pepper) = pepper else {
+ return Ok(false);
+ };
+ let hash = hash_token(password, pepper);
+ runtime
+ .reader
+ .token_hash_exists(hash)
+ .await
+ .map_err(|e| json_err(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()))
+}
+
+async fn issue_cookies(
+ runtime: &HumanAuthRuntime,
+ user_id: UserId,
+ expected_phc: &str,
+ expected_role: UserRole,
+ expected_must_change: bool,
+) -> Result<(String, String, i64), Response> {
+ let secret = ai_memory_store::web_sessions::generate_session_secret()
+ .map_err(|e| json_err(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()))?;
+ let csrf = ai_memory_store::web_sessions::generate_csrf_secret()
+ .map_err(|e| json_err(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()))?;
+ let session_hash = hash_session_secret(&secret);
+ let csrf_hash = hash_session_secret(&csrf);
+ let issued = runtime
+ .writer
+ .issue_web_session(
+ user_id,
+ expected_phc.to_string(),
+ expected_role,
+ expected_must_change,
+ session_hash,
+ csrf_hash,
+ )
+ .await
+ .map_err(|e| {
+ tracing::warn!(error = %e, user_id = %user_id, "session issuance rejected after password verification");
+ json_err(StatusCode::UNAUTHORIZED, "invalid credentials")
+ })?;
+ Ok((secret, csrf, issued.expires_at))
+}
+
+async fn dummy_login_failure(
+ runtime: &HumanAuthRuntime,
+ ip: IpAddr,
+ username: &str,
+ password: String,
+) -> Response {
+ match ai_memory_store::password::dummy_verify(password).await {
+ Err(ai_memory_store::StoreError::InvalidState(msg)) if msg.contains("saturated") => {
+ json_err(StatusCode::TOO_MANY_REQUESTS, "kdf saturated")
+ }
+ Err(error) => {
+ tracing::error!(%error, "dummy password verification failed");
+ json_err(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "authentication unavailable",
+ )
+ }
+ Ok(()) => {
+ runtime.limiter.record_ip_failure(ip);
+ runtime.limiter.record_username_failure(username);
+ json_err(StatusCode::UNAUTHORIZED, "invalid credentials")
+ }
+ }
+}
+
+async fn handle_login(
+ State(state): State<Arc<AuthState>>,
+ req: Request<axum::body::Body>,
+) -> Response {
+ let Some(runtime) = state.human.as_ref() else {
+ return json_err(StatusCode::UNAUTHORIZED, "auth required");
+ };
+ let headers = req.headers().clone();
+ let ip = peer_ip(&headers, req.extensions(), &runtime.trusted_proxy_cidrs);
+ if runtime.limiter.ip_blocked(ip) {
+ return json_err(StatusCode::TOO_MANY_REQUESTS, "too many login attempts");
+ }
+ let body = match axum::body::to_bytes(req.into_body(), 64 * 1024).await {
+ Ok(b) => b,
+ Err(_) => return json_err(StatusCode::BAD_REQUEST, "invalid body"),
+ };
+ let LoginBody { username, password } = match serde_json::from_slice(&body) {
+ Ok(v) => v,
+ Err(_) => return json_err(StatusCode::BAD_REQUEST, "invalid body"),
+ };
+ let username = username.trim().to_string();
+
+ let login = match runtime
+ .reader
+ .find_login_user_by_username(username.clone())
+ .await
+ {
+ Ok(v) => v,
+ Err(e) => return json_err(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
+ };
+
+ let fail = || {
+ runtime.limiter.record_ip_failure(ip);
+ runtime.limiter.record_username_failure(&username);
+ json_err(StatusCode::UNAUTHORIZED, "invalid credentials")
+ };
+
+ let Some(login) = login else {
+ return dummy_login_failure(runtime, ip, &username, password).await;
+ };
+ if login.user.disabled_at.is_some() {
+ return dummy_login_failure(runtime, ip, &username, password).await;
+ }
+ let Some(phc) = login.password_hash.clone() else {
+ return dummy_login_failure(runtime, ip, &username, password).await;
+ };
+ let ok = match ai_memory_store::password::verify_password(password, phc.clone()).await {
+ Ok(v) => v,
+ Err(ai_memory_store::StoreError::InvalidState(msg)) if msg.contains("saturated") => {
+ return json_err(StatusCode::TOO_MANY_REQUESTS, "kdf saturated");
+ }
+ Err(e) => return json_err(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
+ };
+ if !ok {
+ return fail();
+ }
+
+ let (secret, csrf, expires_at) = match issue_cookies(
+ runtime,
+ login.user.id,
+ &phc,
+ login.user.role,
+ login.user.must_change_password,
+ )
+ .await
+ {
+ Ok(v) => v,
+ Err(resp) => return resp,
+ };
+ let snapshot = me_snapshot(&login.user);
+ let mut resp = Json(snapshot).into_response();
+ append_session_cookies(&mut resp, &secret, &csrf, expires_at, state.secure_cookie());
+ resp
+}
+
+async fn recovery_public_fail(
+ runtime: &HumanAuthRuntime,
+ ip: IpAddr,
+ password: String,
+) -> Response {
+ runtime.limiter.record_ip_failure(ip);
+ match ai_memory_store::password::dummy_verify(password).await {
+ Err(ai_memory_store::StoreError::InvalidState(msg)) if msg.contains("saturated") => {
+ json_err(StatusCode::TOO_MANY_REQUESTS, "kdf saturated")
+ }
+ _ => json_err(StatusCode::UNAUTHORIZED, "invalid credentials"),
+ }
+}
+
+fn recovery_token_matches(expected: Option<&[u8; 32]>, provided: &str) -> bool {
+ let provided_hash = hash_session_secret(provided);
+ expected.is_some_and(|expected| bool::from(provided_hash.as_slice().ct_eq(expected.as_slice())))
+}
+
+async fn handle_recovery(
+ State(state): State<Arc<AuthState>>,
+ req: Request<axum::body::Body>,
+) -> Response {
+ let generic = || json_err(StatusCode::UNAUTHORIZED, "invalid credentials");
+ let Some(runtime) = state.human.as_ref() else {
+ return generic();
+ };
+ let headers = req.headers().clone();
+ let ip = peer_ip(&headers, req.extensions(), &runtime.trusted_proxy_cidrs);
+ if runtime.limiter.ip_blocked(ip) {
+ return json_err(StatusCode::TOO_MANY_REQUESTS, "too many login attempts");
+ }
+ let body = match axum::body::to_bytes(req.into_body(), 64 * 1024).await {
+ Ok(b) => b,
+ Err(_) => return json_err(StatusCode::BAD_REQUEST, "invalid body"),
+ };
+ let RecoveryBody {
+ recovery_token,
+ new_password,
+ new_password_confirmation,
+ } = match serde_json::from_slice(&body) {
+ Ok(v) => v,
+ Err(_) => return json_err(StatusCode::BAD_REQUEST, "invalid body"),
+ };
+ if !recovery_token_matches(runtime.recovery_token_hash.as_ref(), &recovery_token) {
+ return recovery_public_fail(runtime, ip, new_password).await;
+ }
+ if new_password != new_password_confirmation
+ || is_reserved_password(runtime, &new_password)
+ || validate_human_password(
+ &new_password,
+ Some(runtime.root_username.as_str()),
+ &reserved_refs(runtime),
+ )
+ .is_err()
+ {
+ return recovery_public_fail(runtime, ip, new_password).await;
+ }
+ match password_collides_with_api_key(runtime, state.pepper(), &new_password).await {
+ Ok(true) => return recovery_public_fail(runtime, ip, new_password).await,
+ Ok(false) => {}
+ Err(resp) => return resp,
+ }
+ let phc = match ai_memory_store::password::hash_password(new_password).await {
+ Ok(h) => h,
+ Err(ai_memory_store::StoreError::InvalidState(msg)) if msg.contains("saturated") => {
+ return json_err(StatusCode::TOO_MANY_REQUESTS, "kdf saturated");
+ }
+ Err(e) => return json_err(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
+ };
+ if let Err(e) = runtime
+ .writer
+ .recover_root(
+ runtime.root_username.clone(),
+ runtime.root_name.clone(),
+ runtime.root_email.clone(),
+ phc,
+ )
+ .await
+ {
+ return json_err(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
+ }
+ tracing::info!(username = %runtime.root_username, "root recovered via break-glass");
+ let mut resp = StatusCode::NO_CONTENT.into_response();
+ if let Ok(v) = expire_legacy(state.secure_cookie()).parse() {
+ resp.headers_mut().append(header::SET_COOKIE, v);
+ }
+ resp
+}
+
+async fn handle_me(
+ State(state): State<Arc<AuthState>>,
+ axum::Extension(level): axum::Extension<AuthLevel>,
+ axum::Extension(actor): axum::Extension<ActorContext>,
+ session: Option<axum::Extension<LiveWebSession>>,
+) -> Response {
+ let mut resp = if level == AuthLevel::Anonymous {
+ Json(MeBody {
+ username: None,
+ name: None,
+ role: None,
+ must_change_password: false,
+ via: "anonymous",
+ capabilities: capabilities_for(AuthLevel::Anonymous, false),
+ })
+ .into_response()
+ } else {
+ let user = session.map(|s| s.0.user.clone());
+ Json(MeBody {
+ username: actor
+ .user
+ .clone()
+ .or_else(|| user.as_ref().map(|u| u.username.clone())),
+ name: actor
+ .name
+ .clone()
+ .or_else(|| user.as_ref().and_then(|u| u.name.clone())),
+ role: user.as_ref().map(|u| u.role),
+ must_change_password: user.as_ref().is_some_and(|u| u.must_change_password),
+ via: "session",
+ capabilities: capabilities_for(
+ level,
+ user.as_ref().is_some_and(|u| u.must_change_password),
+ ),
+ })
+ .into_response()
+ };
+ attach_legacy_expire(&mut resp, state.secure_cookie());
+ resp
+}
+
+async fn handle_change_password(
+ State(state): State<Arc<AuthState>>,
+ axum::Extension(session): axum::Extension<LiveWebSession>,
+ Json(body): Json<ChangePasswordBody>,
+) -> Response {
+ let Some(runtime) = state.human.as_ref() else {
+ return json_err(StatusCode::UNAUTHORIZED, "auth required");
+ };
+ if body.new_password != body.new_password_confirmation {
+ return json_err(
+ StatusCode::BAD_REQUEST,
+ "password confirmation does not match",
+ );
+ }
+ if let Err(e) = validate_human_password(
+ &body.new_password,
+ Some(session.user.username.as_str()),
+ &reserved_refs(runtime),
+ ) {
+ return json_err(StatusCode::BAD_REQUEST, &e.to_string());
+ }
+ if is_reserved_password(runtime, &body.new_password) {
+ return json_err(StatusCode::BAD_REQUEST, "password is reserved");
+ }
+ let login = match runtime
+ .reader
+ .find_login_user_by_username(session.user.username.clone())
+ .await
+ {
+ Ok(Some(u)) => u,
+ Ok(None) => return json_err(StatusCode::UNAUTHORIZED, "auth required"),
+ Err(e) => return json_err(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
+ };
+ let Some(phc) = login.password_hash.clone() else {
+ return json_err(StatusCode::UNAUTHORIZED, "auth required");
+ };
+ let ok = match ai_memory_store::password::verify_password(body.current_password, phc.clone())
+ .await
+ {
+ Ok(v) => v,
+ Err(e) => return json_err(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
+ };
+ if !ok {
+ return json_err(StatusCode::UNAUTHORIZED, "invalid credentials");
+ }
+ match password_collides_with_api_key(runtime, state.pepper(), &body.new_password).await {
+ Ok(true) => return json_err(StatusCode::BAD_REQUEST, "password is reserved"),
+ Ok(false) => {}
+ Err(response) => return response,
+ }
+ let new_phc = match ai_memory_store::password::hash_password(body.new_password).await {
+ Ok(h) => h,
+ Err(e) => return json_err(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
+ };
+ let secret = match ai_memory_store::web_sessions::generate_session_secret() {
+ Ok(s) => s,
+ Err(e) => return json_err(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
+ };
+ let csrf = match ai_memory_store::web_sessions::generate_csrf_secret() {
+ Ok(s) => s,
+ Err(e) => return json_err(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
+ };
+ if let Err(e) = runtime
+ .writer
+ .change_password(
+ session.user.id,
+ phc,
+ new_phc,
+ session.id,
+ hash_session_secret(&secret),
+ hash_session_secret(&csrf),
+ )
+ .await
+ {
+ return json_err(StatusCode::CONFLICT, &e.to_string());
+ }
+ let mut resp = StatusCode::NO_CONTENT.into_response();
+ append_session_cookies(
+ &mut resp,
+ &secret,
+ &csrf,
+ session.expires_at,
+ state.secure_cookie(),
+ );
+ resp
+}
+
+async fn handle_logout(State(state): State<Arc<AuthState>>, headers: HeaderMap) -> Response {
+ if let (Some(runtime), Some(secret)) =
+ (state.human.as_ref(), cookie_value(&headers, SESSION_COOKIE))
+ {
+ let hash = hash_session_secret(&secret);
+ let _ = runtime.writer.revoke_web_session(hash).await;
+ }
+ let mut resp = StatusCode::NO_CONTENT.into_response();
+ clear_session_cookies(&mut resp, state.secure_cookie());
+ resp
+}
+
+#[derive(Debug, Serialize)]
+struct IntrospectResponse {
+ authenticated: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ username: Option<String>,
+ can_manage_api_keys: bool,
+}
+
+async fn handle_session_introspect(
+ State(state): State<Arc<AuthState>>,
+ headers: HeaderMap,
+ Json(body): Json<IntrospectBody>,
+) -> Response {
+ if crate::auth::any_actor_header(&headers) {
+ return json_err(
+ StatusCode::BAD_REQUEST,
+ "X-Memory-Actor-* headers are not allowed on /internal",
+ );
+ }
+ let Some(expected) = state.actor_proxy_bearer() else {
+ return json_err(StatusCode::UNAUTHORIZED, "auth required");
+ };
+ let provided = crate::auth::extract_bearer_from_headers(&headers).unwrap_or_default();
+ if provided.len() != expected.len()
+ || !bool::from(provided.as_bytes().ct_eq(expected.as_bytes()))
+ {
+ return json_err(StatusCode::UNAUTHORIZED, "auth required");
+ }
+ let Some(runtime) = state.human.as_ref() else {
+ return Json(IntrospectResponse {
+ authenticated: false,
+ username: None,
+ can_manage_api_keys: false,
+ })
+ .into_response();
+ };
+ let hash = hash_session_secret(&body.session);
+ let live = match runtime.reader.find_live_session_by_hash(hash).await {
+ Ok(v) => v,
+ Err(e) => return json_err(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
+ };
+ let Some(live) = live else {
+ return Json(IntrospectResponse {
+ authenticated: false,
+ username: None,
+ can_manage_api_keys: false,
+ })
+ .into_response();
+ };
+ let method = body.method.to_ascii_uppercase();
+ let mutating = matches!(method.as_str(), "POST" | "PUT" | "PATCH" | "DELETE");
+ if mutating {
+ let Some(csrf) = body.csrf.as_deref() else {
+ return Json(IntrospectResponse {
+ authenticated: false,
+ username: None,
+ can_manage_api_keys: false,
+ })
+ .into_response();
+ };
+ let csrf_hash = hash_session_secret(csrf);
+ if !ai_memory_store::users::constant_time_eq(&csrf_hash, &live.csrf_hash) {
+ return Json(IntrospectResponse {
+ authenticated: false,
+ username: None,
+ can_manage_api_keys: false,
+ })
+ .into_response();
+ }
+ }
+ let can_manage = live.user.role == UserRole::Root
+ && !live.user.must_change_password
+ && live.user.disabled_at.is_none();
+ Json(IntrospectResponse {
+ authenticated: true,
+ username: Some(live.user.username),
+ can_manage_api_keys: can_manage,
+ })
+ .into_response()
+}
+
+/// Session-only: reject Bearer; require a live cookie session.
+pub async fn require_session(
+ State(state): State<Arc<AuthState>>,
+ mut req: Request<axum::body::Body>,
+ next: Next,
+) -> Response {
+ if crate::auth::extract_bearer_from_headers(req.headers()).is_some() {
+ return json_err(StatusCode::UNAUTHORIZED, "auth required");
+ }
+ match load_session(&state, req.headers(), req.method()).await {
+ Ok(live) => inject_session(&mut req, live),
+ Err(resp) => return resp,
+ }
+ next.run(req).await
+}
+
+/// `/auth/me`: anonymous when nothing is configured; otherwise a session.
+pub async fn require_session_or_anonymous(
+ State(state): State<Arc<AuthState>>,
+ mut req: Request<axum::body::Body>,
+ next: Next,
+) -> Response {
+ if crate::auth::extract_bearer_from_headers(req.headers()).is_some() {
+ return json_err(StatusCode::UNAUTHORIZED, "auth required");
+ }
+ if !state.enabled() {
+ req.extensions_mut().insert(ActorContext::anonymous());
+ req.extensions_mut().insert(AuthLevel::Anonymous);
+ return next.run(req).await;
+ }
+ match load_session(&state, req.headers(), req.method()).await {
+ Ok(live) => inject_session(&mut req, live),
+ Err(resp) => return resp,
+ }
+ next.run(req).await
+}
+
+/// Dual-auth for `/admin`, `/api/v1`, and the builtin wiki.
+///
+/// Bearer always wins and never falls back. Before a human password or
+/// bootstrap marker exists, deprecated Basic / `ai_memory_auth` credentials
+/// remain valid for GET only. The persisted human-auth transition is read on
+/// every browser request, so completing bootstrap closes both legacy
+/// transports without a restart.
+pub async fn require_dual_auth(
+ State(state): State<Arc<AuthState>>,
+ mut req: Request<axum::body::Body>,
+ next: Next,
+) -> Response {
+ match crate::auth::authenticate_bearer(&state, &mut req).await {
+ Ok(crate::auth::BearerAuth::Authenticated) => {
+ req.extensions_mut().insert(state.clone());
+ return next.run(req).await;
+ }
+ Err(resp) => return resp,
+ Ok(crate::auth::BearerAuth::Rejected) => {
+ return crate::auth::unauthorized_bearer();
+ }
+ Ok(crate::auth::BearerAuth::Absent) => {}
+ }
+
+ let human_configured = match human_auth_configured(&state).await {
+ Ok(configured) => configured,
+ Err(response) => return response,
+ };
+ if !human_configured {
+ if !state.enabled() {
+ req.extensions_mut().insert(ActorContext::anonymous());
+ req.extensions_mut().insert(AuthLevel::Anonymous);
+ return next.run(req).await;
+ }
+ if req.method() != Method::GET {
+ return crate::auth::unauthorized_bearer();
+ }
+ let had_legacy_cookie = cookie_value(req.headers(), LEGACY_AUTH_COOKIE).is_some();
+ let Some((provided, from_basic)) = legacy_browser_credential(req.headers()) else {
+ return unauthorized_legacy_browser();
+ };
+ match crate::auth::authenticate_token(&state, &mut req, &provided, false).await {
+ Ok(crate::auth::BearerAuth::Authenticated) => {
+ req.extensions_mut().insert(state.clone());
+ let mut response = next.run(req).await;
+ if from_basic
+ && !had_legacy_cookie
+ && let Ok(cookie) = legacy_cookie(&provided, state.secure_cookie()).parse()
+ {
+ response.headers_mut().append(header::SET_COOKIE, cookie);
+ }
+ return response;
+ }
+ Err(response) => return response,
+ Ok(crate::auth::BearerAuth::Absent | crate::auth::BearerAuth::Rejected) => {
+ return unauthorized_legacy_browser();
+ }
+ }
+ }
+
+ match load_session(&state, req.headers(), req.method()).await {
+ Ok(live) => {
+ if live.user.must_change_password {
+ return json_err(StatusCode::FORBIDDEN, "password change required");
+ }
+ inject_session(&mut req, live);
+ req.extensions_mut().insert(state.clone());
+ next.run(req).await
+ }
+ Err(resp) => resp,
+ }
+}
+
+fn inject_session(req: &mut Request<axum::body::Body>, live: LiveWebSession) {
+ let level = if live.user.role == UserRole::Root {
+ AuthLevel::Root
+ } else {
+ AuthLevel::User
+ };
+ let actor = ActorContext {
+ user: Some(live.user.username.clone()),
+ name: live.user.name.clone(),
+ email: live.user.email.clone(),
+ ..ActorContext::default()
+ };
+ req.extensions_mut().insert(live.user.id);
+ req.extensions_mut().insert(actor);
+ req.extensions_mut().insert(level);
+ req.extensions_mut().insert(live);
+}
+
+async fn load_session(
+ state: &AuthState,
+ headers: &HeaderMap,
+ method: &Method,
+) -> Result<LiveWebSession, Response> {
+ let Some(runtime) = state.human.as_ref() else {
+ return Err(json_err(StatusCode::UNAUTHORIZED, "auth required"));
+ };
+ let Some(secret) = cookie_value(headers, SESSION_COOKIE) else {
+ return Err(json_err(StatusCode::UNAUTHORIZED, "auth required"));
+ };
+ let hash = hash_session_secret(&secret);
+ let live = runtime
+ .reader
+ .find_live_session_by_hash(hash)
+ .await
+ .map_err(|e| json_err(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()))?
+ .ok_or_else(|| json_err(StatusCode::UNAUTHORIZED, "auth required"))?;
+ if live.user.disabled_at.is_some() {
+ return Err(json_err(StatusCode::UNAUTHORIZED, "auth required"));
+ }
+ if !matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS) {
+ let header_csrf = headers
+ .get(CSRF_HEADER)
+ .and_then(|v| v.to_str().ok())
+ .map(str::to_string);
+ let cookie_csrf = cookie_value(headers, CSRF_COOKIE);
+ let (Some(h), Some(c)) = (header_csrf, cookie_csrf) else {
+ return Err(json_err(StatusCode::FORBIDDEN, "csrf required"));
+ };
+ if h.len() != c.len() || !bool::from(h.as_bytes().ct_eq(c.as_bytes())) {
+ return Err(json_err(StatusCode::FORBIDDEN, "csrf required"));
+ }
+ let csrf_hash = hash_session_secret(&h);
+ if !ai_memory_store::users::constant_time_eq(&csrf_hash, &live.csrf_hash) {
+ return Err(json_err(StatusCode::FORBIDDEN, "csrf required"));
+ }
+ }
+ let writer = runtime.writer.clone();
+ let session_id = live.id;
+ let last_used_at = jiff::Timestamp::now().as_microsecond();
+ let user_id = live.user.id;
+ tokio::spawn(async move {
+ let _ = writer.touch_web_session(session_id, last_used_at).await;
+ let _ = writer.touch_user_last_seen(user_id).await;
+ });
+ Ok(live)
+}
+
+/// Helper used by admin password hashing to reject reserved values.
+pub fn password_is_reserved(state: &AuthState, password: &str) -> bool {
+ state
+ .human
+ .as_ref()
+ .is_some_and(|r| is_reserved_password(r, password))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::auth::AuthState;
+ use ai_memory_core::{ActorContext, AuthLevel};
+ use axum::http::{StatusCode, header};
+ use tower::ServiceExt;
+
+ #[test]
+ fn cidr_v4_contains() {
+ let c = Cidr::parse("10.0.0.0/8").unwrap();
+ assert!(c.contains("10.1.2.3".parse().unwrap()));
+ assert!(!c.contains("11.0.0.1".parse().unwrap()));
+ }
+
+ #[test]
+ fn distinct_connection_peers_have_independent_login_budgets() {
+ let headers = HeaderMap::new();
+ let mut first_extensions = axum::http::Extensions::new();
+ first_extensions.insert(axum::extract::ConnectInfo(
+ "192.0.2.10:41000".parse::<SocketAddr>().unwrap(),
+ ));
+ let mut second_extensions = axum::http::Extensions::new();
+ second_extensions.insert(axum::extract::ConnectInfo(
+ "192.0.2.11:41000".parse::<SocketAddr>().unwrap(),
+ ));
+ let first = peer_ip(&headers, &first_extensions, &[]);
+ let second = peer_ip(&headers, &second_extensions, &[]);
+ assert_ne!(first, second);
+
+ let limiter = LoginLimiter::default();
+ for _ in 0..LOGIN_IP_LIMIT {
+ limiter.record_ip_failure(first);
+ }
+ assert!(limiter.ip_blocked(first));
+ assert!(!limiter.ip_blocked(second));
+ }
+
+ #[test]
+ fn forwarded_ip_requires_a_trusted_connection_peer() {
+ let mut headers = HeaderMap::new();
+ headers.insert("x-forwarded-for", "198.51.100.20".parse().unwrap());
+ let mut extensions = axum::http::Extensions::new();
+ extensions.insert(axum::extract::ConnectInfo(
+ "10.0.0.4:41000".parse::<SocketAddr>().unwrap(),
+ ));
+ let trusted = [Cidr::parse("10.0.0.0/8").unwrap()];
+ assert_eq!(
+ peer_ip(&headers, &extensions, &trusted),
+ "198.51.100.20".parse::<IpAddr>().unwrap()
+ );
+ assert_eq!(
+ peer_ip(&headers, &extensions, &[]),
+ "10.0.0.4".parse::<IpAddr>().unwrap()
+ );
+ }
+
+ #[test]
+ fn forwarded_ip_combines_duplicate_field_lines_in_wire_order() {
+ let mut headers = HeaderMap::new();
+ headers.append("x-forwarded-for", "198.51.100.99".parse().unwrap());
+ headers.append("x-forwarded-for", "203.0.113.25".parse().unwrap());
+ let mut extensions = axum::http::Extensions::new();
+ extensions.insert(axum::extract::ConnectInfo(
+ "10.0.0.4:41000".parse::<SocketAddr>().unwrap(),
+ ));
+ let trusted = [Cidr::parse("10.0.0.0/8").unwrap()];
+ assert_eq!(
+ peer_ip(&headers, &extensions, &trusted),
+ "203.0.113.25".parse::<IpAddr>().unwrap()
+ );
+
+ headers.append("x-forwarded-for", "not-an-address".parse().unwrap());
+ assert_eq!(
+ peer_ip(&headers, &extensions, &trusted),
+ "10.0.0.4".parse::<IpAddr>().unwrap()
+ );
+ }
+
+ #[test]
+ fn login_limiter_state_has_a_hard_global_cap() {
+ let limiter = LoginLimiter::default();
+ for n in 0..(LOGIN_LIMITER_MAX_KEYS + 50) {
+ limiter.record_ip_failure(IpAddr::V6(std::net::Ipv6Addr::from(n as u128)));
+ limiter.record_username_failure(&format!("attacker-controlled-{n}"));
+ }
+ assert!(
+ limiter.ip.lock().unwrap_or_else(|e| e.into_inner()).len() <= LOGIN_LIMITER_MAX_KEYS
+ );
+ assert!(
+ limiter.user.lock().unwrap_or_else(|e| e.into_inner()).len() <= LOGIN_LIMITER_MAX_KEYS
+ );
+ }
+
+ #[test]
+ fn rotated_cookie_age_never_exceeds_absolute_session_expiry() {
+ let expires_at = jiff::Timestamp::now()
+ .as_microsecond()
+ .saturating_add(2_000_000);
+ assert!((0..=2).contains(&seconds_until_expiry(expires_at)));
+ assert_eq!(
+ seconds_until_expiry(jiff::Timestamp::now().as_microsecond() - 1),
+ 0
+ );
+ }
+
+ #[test]
+ fn session_introspection_requires_csrf_on_post() {
+ assert_eq!(CSRF_HEADER, "x-csrf-token");
+ assert_eq!(SESSION_COOKIE, "ai_memory_session");
+ }
+
+ #[test]
+ fn recovery_token_compare_hashes_before_constant_time_comparison() {
+ let expected = hash_session_secret("abcd");
+ assert!(recovery_token_matches(Some(&expected), "abcd"));
+ assert!(!recovery_token_matches(Some(&expected), "ab"));
+ assert!(!recovery_token_matches(Some(&expected), "abce"));
+ assert!(!recovery_token_matches(None, "anything-at-all"));
+ }
+
+ async fn human_fixture(recovery: Option<&str>) -> (tempfile::TempDir, Arc<AuthState>, String) {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = ai_memory_store::Store::open(tmp.path()).unwrap();
+ let password = "twelve-chars!!".to_string();
+ let phc = ai_memory_store::password::hash_password(password.clone())
+ .await
+ .unwrap();
+ let mut nu = ai_memory_core::NewUser {
+ username: "root".into(),
+ name: None,
+ email: None,
+ };
+ nu.validate().unwrap();
+ store
+ .writer
+ .create_human_user(nu, ai_memory_core::UserRole::Root, Some(phc), false)
+ .await
+ .unwrap();
+ let runtime = HumanAuthRuntime {
+ reader: store.reader.clone(),
+ writer: store.writer.clone(),
+ recovery_token_hash: recovery.map(hash_session_secret),
+ root_username: "root".into(),
+ root_name: None,
+ root_email: None,
+ reserved_passwords: vec!["root-bearer".into()],
+ trusted_proxy_cidrs: Vec::new(),
+ limiter: Arc::new(LoginLimiter::default()),
+ };
+ let state = Arc::new(
+ AuthState::new(Some("root-bearer".into()))
+ .with_root_actor(ActorContext {
+ user: Some("root".into()),
+ ..ActorContext::default()
+ })
+ .with_human(runtime),
+ );
+ (tmp, state, password)
+ }
+
+ fn set_cookie_value(headers: &axum::http::HeaderMap, name: &str) -> Option<String> {
+ for value in headers.get_all(header::SET_COOKIE) {
+ let Ok(s) = value.to_str() else {
+ continue;
+ };
+ let Some(rest) = s.strip_prefix(&format!("{name}=")) else {
+ continue;
+ };
+ return Some(rest.split(';').next().unwrap_or("").to_string());
+ }
+ None
+ }
+
+ async fn login_cookies(state: Arc<AuthState>, password: &str) -> (String, String) {
+ let resp = public_auth_router(state)
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/auth/login")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "username": "root",
+ "password": password
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let headers = resp.headers().clone();
+ (
+ set_cookie_value(&headers, SESSION_COOKIE).expect("session cookie"),
+ set_cookie_value(&headers, CSRF_COOKIE).expect("csrf cookie"),
+ )
+ }
+
+ async fn echo_level(axum::Extension(level): axum::Extension<AuthLevel>) -> &'static str {
+ match level {
+ AuthLevel::Root => "root",
+ AuthLevel::User => "user",
+ AuthLevel::Anonymous => "anonymous",
+ }
+ }
+
+ fn dual_router(state: Arc<AuthState>) -> axum::Router {
+ axum::Router::new()
+ .route("/probe", axum::routing::get(echo_level).post(echo_level))
+ .route_layer(axum::middleware::from_fn_with_state(
+ state.clone(),
+ require_dual_auth,
+ ))
+ }
+
+ async fn json_error(resp: axum::http::Response<axum::body::Body>) -> serde_json::Value {
+ let bytes = axum::body::to_bytes(resp.into_body(), 4096).await.unwrap();
+ serde_json::from_slice(&bytes).unwrap()
+ }
+
+ fn cookie_pair(session: &str, csrf: &str) -> String {
+ format!("{SESSION_COOKIE}={session}; {CSRF_COOKIE}={csrf}")
+ }
+
+ #[tokio::test]
+ async fn dual_auth_basic_and_empty_authorization_use_session() {
+ let (_tmp, state, password) = human_fixture(None).await;
+ let (session, _csrf) = login_cookies(state.clone(), &password).await;
+ let router = dual_router(state);
+ for auth in [
+ None,
+ Some("Basic YWxpY2U6c2VjcmV0"),
+ Some("Token not-a-bearer"),
+ ] {
+ let mut builder = axum::http::Request::builder()
+ .uri("/probe")
+ .header("cookie", format!("{SESSION_COOKIE}={session}"));
+ if let Some(value) = auth {
+ builder = builder.header("authorization", value);
+ }
+ let resp = router
+ .clone()
+ .oneshot(builder.body(axum::body::Body::empty()).unwrap())
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK, "auth={auth:?}");
+ let body = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
+ assert_eq!(&body[..], b"root");
+ }
+ }
+
+ fn legacy_basic(token: &str) -> String {
+ use base64::Engine;
+ format!(
+ "Basic {}",
+ base64::engine::general_purpose::STANDARD.encode(format!("ignored:{token}"))
+ )
+ }
+
+ async fn legacy_transition_fixture() -> (
+ tempfile::TempDir,
+ Arc<AuthState>,
+ ai_memory_store::WriterHandle,
+ ) {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = ai_memory_store::Store::open(tmp.path()).unwrap();
+ let writer = store.writer.clone();
+ let runtime = HumanAuthRuntime {
+ reader: store.reader.clone(),
+ writer: store.writer.clone(),
+ recovery_token_hash: Some(hash_session_secret("break-glass-recovery-token")),
+ root_username: "root".into(),
+ root_name: None,
+ root_email: None,
+ reserved_passwords: vec!["legacy-root-token".into()],
+ trusted_proxy_cidrs: Vec::new(),
+ limiter: Arc::new(LoginLimiter::default()),
+ };
+ let state = Arc::new(AuthState::new(Some("legacy-root-token".into())).with_human(runtime));
+ (tmp, state, writer)
+ }
+
+ #[tokio::test]
+ async fn legacy_browser_credentials_stop_when_human_bootstrap_completes() {
+ let (_tmp, state, writer) = legacy_transition_fixture().await;
+ let router = dual_router(state);
+
+ let basic = router
+ .clone()
+ .oneshot(
+ axum::http::Request::builder()
+ .uri("/probe")
+ .header("authorization", legacy_basic("legacy-root-token"))
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(basic.status(), StatusCode::OK);
+ let legacy_cookie = set_cookie_value(basic.headers(), LEGACY_AUTH_COOKIE)
+ .expect("successful Basic auth must persist the legacy browser cookie");
+
+ let cookie = router
+ .clone()
+ .oneshot(
+ axum::http::Request::builder()
+ .uri("/probe")
+ .header("cookie", format!("{LEGACY_AUTH_COOKIE}={legacy_cookie}"))
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(cookie.status(), StatusCode::OK);
+
+ writer
+ .bootstrap_root(
+ "root".into(),
+ None,
+ None,
+ "$argon2id$v=19$m=19456,t=2,p=1$ZmFrZQ$ZmFrZQ".into(),
+ )
+ .await
+ .unwrap();
+
+ for (name, authorization, cookie) in [
+ ("basic", Some(legacy_basic("legacy-root-token")), None),
+ (
+ "cookie",
+ None,
+ Some(format!("{LEGACY_AUTH_COOKIE}={legacy_cookie}")),
+ ),
+ ] {
+ let mut request = axum::http::Request::builder().uri("/probe");
+ if let Some(value) = authorization {
+ request = request.header("authorization", value);
+ }
+ if let Some(value) = cookie {
+ request = request.header("cookie", value);
+ }
+ let response = router
+ .clone()
+ .oneshot(request.body(axum::body::Body::empty()).unwrap())
+ .await
+ .unwrap();
+ assert_eq!(
+ response.status(),
+ StatusCode::UNAUTHORIZED,
+ "{name} must fail immediately after human bootstrap"
+ );
+ assert!(
+ response
+ .headers()
+ .get(header::WWW_AUTHENTICATE)
+ .and_then(|value| value.to_str().ok())
+ .is_none_or(|value| !value.contains("Basic")),
+ "human mode must not advertise the legacy Basic challenge"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn dual_auth_invalid_bearer_does_not_fall_back_to_session() {
+ let (_tmp, state, password) = human_fixture(None).await;
+ let (session, _csrf) = login_cookies(state.clone(), &password).await;
+ let resp = dual_router(state)
+ .oneshot(
+ axum::http::Request::builder()
+ .uri("/probe")
+ .header("authorization", "Bearer not-a-known-token")
+ .header("cookie", format!("{SESSION_COOKIE}={session}"))
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+ }
+
+ #[tokio::test]
+ async fn auth_me_anonymous_when_no_authority_configured() {
+ let state = Arc::new(AuthState::new(None));
+ let resp = session_auth_router(state)
+ .oneshot(
+ axum::http::Request::builder()
+ .uri("/auth/me")
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(resp.into_body(), 4096).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["via"], "anonymous");
+ assert!(json["username"].is_null());
+ }
+
+ #[tokio::test]
+ async fn auth_me_401_when_authority_configured_without_session() {
+ let (_tmp, state, _password) = human_fixture(None).await;
+ let resp = session_auth_router(state)
+ .oneshot(
+ axum::http::Request::builder()
+ .uri("/auth/me")
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+ }
+
+ #[tokio::test]
+ async fn recovery_public_failures_share_generic_shape() {
+ let recovery = "break-glass-recovery-token-32chr";
+ let (_tmp, state, _password) = human_fixture(Some(recovery)).await;
+ let cases = [
+ serde_json::json!({
+ "recovery_token": "wrong-recovery-token-value-xxxx",
+ "new_password": "brand-new-pass!!",
+ "new_password_confirmation": "brand-new-pass!!"
+ }),
+ serde_json::json!({
+ "recovery_token": recovery,
+ "new_password": "short",
+ "new_password_confirmation": "short"
+ }),
+ serde_json::json!({
+ "recovery_token": recovery,
+ "new_password": "brand-new-pass!!",
+ "new_password_confirmation": "does-not-match!!"
+ }),
+ ];
+ for body in cases {
+ let resp = public_auth_router(state.clone())
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/auth/recovery")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED, "{body}");
+ let bytes = axum::body::to_bytes(resp.into_body(), 4096).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(json, serde_json::json!({"error": "invalid credentials"}));
+ }
+
+ let (_tmp2, unset, _pw) = human_fixture(None).await;
+ let resp = public_auth_router(unset)
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/auth/recovery")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "recovery_token": recovery,
+ "new_password": "brand-new-pass!!",
+ "new_password_confirmation": "brand-new-pass!!"
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+ let bytes = axum::body::to_bytes(resp.into_body(), 4096).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(json, serde_json::json!({"error": "invalid credentials"}));
+ }
+
+ #[tokio::test]
+ async fn machine_require_bearer_ignores_session_cookie() {
+ let (_tmp, state, password) = human_fixture(None).await;
+ let (session, _csrf) = login_cookies(state.clone(), &password).await;
+ let machine_only = [
+ "/mcp",
+ "/hook",
+ "/hook/batch",
+ "/handoff",
+ "/workstream/runs",
+ ];
+ let mut router = axum::Router::new();
+ for path in machine_only {
+ router = router.route(path, axum::routing::get(|| async { "ok" }));
+ }
+ let router = router.layer(axum::middleware::from_fn_with_state(
+ state,
+ crate::auth::require_bearer,
+ ));
+ for path in machine_only {
+ let resp = router
+ .clone()
+ .oneshot(
+ axum::http::Request::builder()
+ .uri(path)
+ .header("cookie", format!("{SESSION_COOKIE}={session}"))
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED, "{path}");
+ }
+ }
+
+ #[tokio::test]
+ async fn login_unknown_disabled_and_wrong_password_share_generic_shape() {
+ let (_tmp, state, password) = human_fixture(None).await;
+ let runtime = state.human.as_ref().unwrap();
+ let phc = runtime
+ .reader
+ .find_login_user_by_username("root".into())
+ .await
+ .unwrap()
+ .unwrap()
+ .password_hash
+ .unwrap();
+ let mut alice = ai_memory_core::NewUser {
+ username: "alice".into(),
+ name: None,
+ email: None,
+ };
+ alice.validate().unwrap();
+ let alice_id = runtime
+ .writer
+ .create_human_user(alice, ai_memory_core::UserRole::User, Some(phc), false)
+ .await
+ .unwrap();
+ runtime
+ .writer
+ .set_user_disabled(alice_id, true)
+ .await
+ .unwrap();
+
+ let cases = [
+ serde_json::json!({"username": "nobody", "password": &password}),
+ serde_json::json!({"username": "alice", "password": &password}),
+ serde_json::json!({"username": "root", "password": "definitely-wrong!!"}),
+ ];
+ for body in cases {
+ let resp = public_auth_router(state.clone())
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/auth/login")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED, "{body}");
+ assert_eq!(
+ json_error(resp).await,
+ serde_json::json!({"error": "invalid credentials"})
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn login_expires_legacy_auth_cookie_and_marks_session_http_only() {
+ let (_tmp, state, password) = human_fixture(None).await;
+ let resp = public_auth_router(state)
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/auth/login")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "username": "root",
+ "password": password
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let cookies: Vec<String> = resp
+ .headers()
+ .get_all(header::SET_COOKIE)
+ .iter()
+ .filter_map(|v| v.to_str().ok().map(str::to_string))
+ .collect();
+ assert!(
+ cookies.iter().any(|c| c.starts_with("ai_memory_session=")
+ && c.contains("HttpOnly")
+ && c.contains("SameSite=Strict")
+ && c.contains("Path=/")),
+ "{cookies:?}"
+ );
+ assert!(
+ cookies
+ .iter()
+ .any(|c| c.starts_with("ai_memory_csrf=") && !c.contains("HttpOnly")),
+ "{cookies:?}"
+ );
+ assert!(
+ cookies
+ .iter()
+ .any(|c| c.starts_with("ai_memory_auth=") && c.contains("Max-Age=0")),
+ "{cookies:?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn dual_auth_post_requires_matching_csrf_header_and_cookie() {
+ let (_tmp, state, password) = human_fixture(None).await;
+ let (session, csrf) = login_cookies(state.clone(), &password).await;
+ let router = dual_router(state.clone());
+
+ let missing = router
+ .clone()
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/probe")
+ .header("cookie", cookie_pair(&session, &csrf))
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(missing.status(), StatusCode::FORBIDDEN);
+ assert_eq!(
+ json_error(missing).await,
+ serde_json::json!({"error": "csrf required"})
+ );
+
+ let mismatched = router
+ .clone()
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/probe")
+ .header("cookie", cookie_pair(&session, &csrf))
+ .header(CSRF_HEADER, "not-the-csrf-cookie-value")
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(mismatched.status(), StatusCode::FORBIDDEN);
+
+ let ok = router
+ .clone()
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/probe")
+ .header("cookie", cookie_pair(&session, &csrf))
+ .header(CSRF_HEADER, &csrf)
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(ok.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(ok.into_body(), 1024).await.unwrap();
+ assert_eq!(&body[..], b"root");
+
+ let bearer = dual_router(state)
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/probe")
+ .header("authorization", "Bearer root-bearer")
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(bearer.status(), StatusCode::OK);
+ }
+
+ #[tokio::test]
+ async fn must_change_password_forbids_dual_auth_console_routes() {
+ let (_tmp, state, _password) = human_fixture(None).await;
+ let runtime = state.human.as_ref().unwrap();
+ let phc = runtime
+ .reader
+ .find_login_user_by_username("root".into())
+ .await
+ .unwrap()
+ .unwrap()
+ .password_hash
+ .unwrap();
+ let mut pending = ai_memory_core::NewUser {
+ username: "pending".into(),
+ name: None,
+ email: None,
+ };
+ pending.validate().unwrap();
+ runtime
+ .writer
+ .create_human_user(pending, ai_memory_core::UserRole::User, Some(phc), true)
+ .await
+ .unwrap();
+ let resp = public_auth_router(state.clone())
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/auth/login")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "username": "pending",
+ "password": "twelve-chars!!"
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let headers = resp.headers().clone();
+ let session = set_cookie_value(&headers, SESSION_COOKIE).unwrap();
+ let csrf = set_cookie_value(&headers, CSRF_COOKIE).unwrap();
+
+ let blocked = dual_router(state.clone())
+ .oneshot(
+ axum::http::Request::builder()
+ .uri("/probe")
+ .header("cookie", cookie_pair(&session, &csrf))
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(blocked.status(), StatusCode::FORBIDDEN);
+ assert_eq!(
+ json_error(blocked).await,
+ serde_json::json!({"error": "password change required"})
+ );
+
+ let me = session_auth_router(state)
+ .oneshot(
+ axum::http::Request::builder()
+ .uri("/auth/me")
+ .header("cookie", cookie_pair(&session, &csrf))
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(me.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(me.into_body(), 4096).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["must_change_password"], true);
+ assert_eq!(json["username"], "pending");
+ }
+
+ #[tokio::test]
+ async fn recovery_success_issues_no_session_and_revokes_the_old_one() {
+ let recovery = "break-glass-recovery-token-32chr";
+ let (_tmp, state, password) = human_fixture(Some(recovery)).await;
+ let (session, csrf) = login_cookies(state.clone(), &password).await;
+ let new_password = "brand-new-pass!!";
+ let resp = public_auth_router(state.clone())
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/auth/recovery")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "recovery_token": recovery,
+ "new_password": new_password,
+ "new_password_confirmation": new_password
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::NO_CONTENT);
+ assert!(set_cookie_value(resp.headers(), SESSION_COOKIE).is_none());
+ assert!(
+ resp.headers()
+ .get_all(header::SET_COOKIE)
+ .iter()
+ .filter_map(|v| v.to_str().ok())
+ .any(|c| c.starts_with("ai_memory_auth=") && c.contains("Max-Age=0")),
+ "recovery must expire the legacy cookie"
+ );
+
+ let stale = session_auth_router(state.clone())
+ .oneshot(
+ axum::http::Request::builder()
+ .uri("/auth/me")
+ .header("cookie", cookie_pair(&session, &csrf))
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(stale.status(), StatusCode::UNAUTHORIZED);
+
+ let old = public_auth_router(state.clone())
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/auth/login")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "username": "root",
+ "password": password
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(old.status(), StatusCode::UNAUTHORIZED);
+
+ let fresh = public_auth_router(state)
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/auth/login")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "username": "root",
+ "password": new_password
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(fresh.status(), StatusCode::OK);
+ assert!(set_cookie_value(fresh.headers(), SESSION_COOKIE).is_some());
+ }
+
+ fn introspect_state(state: Arc<AuthState>) -> Arc<AuthState> {
+ let human = state.human.clone().expect("human runtime");
+ Arc::new(
+ AuthState::new(Some("root-bearer".into()))
+ .with_trusted_proxy_bearer("proxy-bearer-token")
+ .with_human(human),
+ )
+ }
+
+ #[tokio::test]
+ async fn session_introspect_accepts_proxy_bearer_without_actor_headers() {
+ let (_tmp, state, password) = human_fixture(None).await;
+ let (session, csrf) = login_cookies(state.clone(), &password).await;
+ let state = introspect_state(state);
+ let router = internal_auth_router(state);
+
+ let anonymous = router
+ .clone()
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/internal/auth/session-introspect")
+ .header("authorization", "Bearer proxy-bearer-token")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "session": "",
+ "method": "GET"
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(anonymous.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(anonymous.into_body(), 4096)
+ .await
+ .unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["authenticated"], false);
+ assert_eq!(json["can_manage_api_keys"], false);
+
+ let actor_rejected = router
+ .clone()
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/internal/auth/session-introspect")
+ .header("authorization", "Bearer proxy-bearer-token")
+ .header("x-memory-actor-user", "root")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "session": session,
+ "method": "GET"
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(actor_rejected.status(), StatusCode::BAD_REQUEST);
+
+ let live = router
+ .clone()
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/internal/auth/session-introspect")
+ .header("authorization", "Bearer proxy-bearer-token")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "session": session,
+ "method": "GET"
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(live.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(live.into_body(), 4096).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["authenticated"], true);
+ assert_eq!(json["username"], "root");
+ assert_eq!(json["can_manage_api_keys"], true);
+
+ let mutating_without_csrf = router
+ .clone()
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/internal/auth/session-introspect")
+ .header("authorization", "Bearer proxy-bearer-token")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "session": session,
+ "method": "POST"
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ let body = axum::body::to_bytes(mutating_without_csrf.into_body(), 4096)
+ .await
+ .unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["authenticated"], false);
+
+ let mutating_with_csrf = router
+ .oneshot(
+ axum::http::Request::builder()
+ .method("POST")
+ .uri("/internal/auth/session-introspect")
+ .header("authorization", "Bearer proxy-bearer-token")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&serde_json::json!({
+ "session": session,
+ "method": "POST",
+ "csrf": csrf
+ }))
+ .unwrap(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ let body = axum::body::to_bytes(mutating_with_csrf.into_body(), 4096)
+ .await
+ .unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(json["authenticated"], true);
+ assert_eq!(json["can_manage_api_keys"], true);
+ }
+}
diff --git a/crates/ai-memory-mcp/src/lib.rs b/crates/ai-memory-mcp/src/lib.rs
index 24044bcd..8c149cf7 100644
--- a/crates/ai-memory-mcp/src/lib.rs
+++ b/crates/ai-memory-mcp/src/lib.rs
@@ -11,6 +11,7 @@
pub mod actor;
pub mod admin;
pub mod auth;
+pub mod human_auth;
mod server;
pub use actor::actor_from_headers;
@@ -18,4 +19,8 @@ pub use admin::{
AdminState, ScopeInvalidation, ScopeInvalidator, admin_router, admin_router_with_decay_breadth,
admin_router_with_sweep_tuning,
};
+pub use human_auth::{
+ HumanAuthRuntime, expire_legacy_cookie_mw, internal_auth_router, public_auth_router,
+ require_dual_auth, session_auth_router,
+};
pub use server::{AiMemoryServer, MEMORY_INSTRUCTIONS};
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 7ddf0a89..6a378025 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -8880,18 +8880,17 @@ mod tests {
.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(
+ .create_human_user(
NewUser {
username: "alice".into(),
name: Some("Alice Smith".into()),
email: Some("[email protected]".into()),
},
- token_hash,
+ ai_memory_core::UserRole::User,
+ None,
+ false,
)
.await
.unwrap();
@@ -8982,10 +8981,7 @@ mod tests {
user.validate().unwrap();
store
.writer
- .create_user(
- user,
- ai_memory_store::hash_token("t", &ai_memory_store::TokenPepper::new("pepper")),
- )
+ .create_human_user(user, ai_memory_core::UserRole::User, None, false)
.await
.unwrap();
@@ -9082,10 +9078,7 @@ mod tests {
user.validate().unwrap();
store
.writer
- .create_user(
- user,
- ai_memory_store::hash_token("t", &ai_memory_store::TokenPepper::new("pepper")),
- )
+ .create_human_user(user, ai_memory_core::UserRole::User, None, false)
.await
.unwrap();
diff --git a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs b/crates/ai-memory-mcp/tests/autoscope_multiuser.rs
index eef0fa4e..c673faa5 100644
--- a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs
+++ b/crates/ai-memory-mcp/tests/autoscope_multiuser.rs
@@ -7,7 +7,7 @@
//! crate (no `lib.rs`), so its `auth` module isn't reachable from an
//! integration test in another crate. The slice that matters for
//! `auto_scope` is the (Bearer header → ActorContext.user) wiring, which
-//! is short enough to replicate verbatim. Cookie / Basic-auth paths are
+//! is short enough to replicate verbatim. Cookie paths are
//! covered elsewhere and have no bearing on actor-key derivation.
//!
//! If `require_bearer` adds a new ActorContext field that affects the
@@ -17,10 +17,13 @@
//! `user.username` into the actor key would split the per-actor map
//! across rungs, which is exactly what this test pins.
-use ai_memory_core::{ActiveProject, ActiveProjectMode, ActorContext, NewUser, SessionId, Tier};
+use ai_memory_core::{
+ ActiveProject, ActiveProjectMode, ActorContext, ApiCredentialId, NewUser, SessionId, Tier,
+ UserRole,
+};
use ai_memory_hooks::{HookState, ProjectCacheStore, SubagentSessionSet, hook_router};
use ai_memory_mcp::AiMemoryServer;
-use ai_memory_store::{Store, TokenPepper, generate_token, hash_token};
+use ai_memory_store::{Store, TokenPepper, generate_api_key, hash_token};
use ai_memory_wiki::Wiki;
use axum::Router;
use axum::body::Body;
@@ -77,20 +80,27 @@ impl MultiUserHarness {
let mut users = Vec::with_capacity(num_users);
for i in 1..=num_users {
let username = format!("user{i}");
- let raw_token = generate_token().expect("gen token");
+ let raw_token = generate_api_key().expect("gen token");
let hash = hash_token(&raw_token, &pepper);
- store
+ let user_id = store
.writer
- .create_user(
+ .create_human_user(
NewUser {
username: username.clone(),
name: Some(format!("User {i}")),
email: Some(format!("user{i}@example.com")),
},
- hash,
+ UserRole::User,
+ None,
+ false,
)
.await
.expect("create user");
+ store
+ .writer
+ .create_api_credential(ApiCredentialId::new(), user_id, "test".into(), hash, None)
+ .await
+ .expect("create api credential");
// Each user "owns" a uniquely-named project + marker page; the
// FTS5 tokenizer treats `_` as a TOKEN character, so the body
@@ -227,18 +237,18 @@ async fn bearer_lookup(
if let Some(token) = bearer {
let hash = hash_token(token, &state.pepper);
match state.reader.find_active_user_by_token_hash(hash).await {
- Ok(Some(user)) => {
+ Ok(Some(hit)) => {
// Mirror require_bearer:
- // ActorContext.user = user.username
- // ActorContext.name = user.name
- // ActorContext.email = user.email
+ // ActorContext.user = hit.user.username
+ // ActorContext.name = hit.user.name
+ // ActorContext.email = hit.user.email
req.extensions_mut().insert(ActorContext {
- user: Some(user.username.clone()),
- name: user.name.clone(),
- email: user.email.clone(),
+ user: Some(hit.user.username.clone()),
+ name: hit.user.name.clone(),
+ email: hit.user.email.clone(),
..ActorContext::default()
});
- req.extensions_mut().insert(user.id);
+ req.extensions_mut().insert(hit.user.id);
}
_ => {
req.extensions_mut().insert(ActorContext::anonymous());
diff --git a/crates/ai-memory-store/Cargo.toml b/crates/ai-memory-store/Cargo.toml
index 0ba1efdb..95b74138 100644
--- a/crates/ai-memory-store/Cargo.toml
+++ b/crates/ai-memory-store/Cargo.toml
@@ -27,6 +27,7 @@ sha2.workspace = true
getrandom.workspace = true
base64.workspace = true
subtle.workspace = true
+argon2.workspace = true
rusqlite.workspace = true
refinery.workspace = true
parking_lot.workspace = true
diff --git a/crates/ai-memory-store/migrations/V54__human_auth.sql b/crates/ai-memory-store/migrations/V54__human_auth.sql
new file mode 100644
index 00000000..b36d44cb
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V54__human_auth.sql
@@ -0,0 +1,72 @@
+-- Human authentication: nullable legacy token_hash, role/password
+-- columns, bootstrap marker, and web sessions.
+--
+-- `Store::open` disables foreign keys around refinery's migration runner;
+-- migration-local PRAGMA toggles are ineffective inside refinery's
+-- transaction. Rebuild `users` while preserving pages.author_id /
+-- audit_log.author_id blob values.
+--
+-- token_hash stays nullable and UNIQUE (SQLite UNIQUE allows many
+-- NULLs) without a length CHECK so a pre-V14 malformed blob can still
+-- be copied; V53 aborts on length != 32. Backfill every existing row
+-- as role='user'. Defaults let a restored pre-V52 binary INSERT.
+
+
+CREATE TABLE users_new (
+ id BLOB NOT NULL PRIMARY KEY,
+ username TEXT NOT NULL UNIQUE,
+ name TEXT,
+ email TEXT UNIQUE COLLATE NOCASE,
+ token_hash BLOB UNIQUE,
+ created_at INTEGER NOT NULL,
+ last_seen_at INTEGER,
+ token_expired_at INTEGER,
+ role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('root', 'user')),
+ password_hash TEXT,
+ must_change_password INTEGER NOT NULL DEFAULT 0 CHECK (must_change_password IN (0, 1)),
+ disabled_at INTEGER
+);
+
+INSERT INTO users_new (
+ id, username, name, email, token_hash, created_at, last_seen_at,
+ token_expired_at, role, password_hash, must_change_password, disabled_at
+)
+SELECT
+ id, username, name, email, token_hash, created_at, last_seen_at,
+ token_expired_at, 'user', NULL, 0, NULL
+FROM users;
+
+DROP TABLE users;
+ALTER TABLE users_new RENAME TO users;
+
+CREATE TABLE human_auth_state (
+ id INTEGER PRIMARY KEY NOT NULL CHECK (id = 1),
+ bootstrap_completed INTEGER NOT NULL DEFAULT 0 CHECK (bootstrap_completed IN (0, 1))
+);
+INSERT INTO human_auth_state (id, bootstrap_completed) VALUES (1, 0);
+
+CREATE TABLE web_sessions (
+ id BLOB NOT NULL PRIMARY KEY,
+ session_hash BLOB NOT NULL UNIQUE CHECK (length(session_hash) = 32),
+ user_id BLOB NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ csrf_hash BLOB NOT NULL CHECK (length(csrf_hash) = 32),
+ created_at INTEGER NOT NULL,
+ last_used_at INTEGER NOT NULL,
+ expires_at INTEGER NOT NULL,
+ revoked_at INTEGER
+);
+
+CREATE INDEX idx_web_sessions_user ON web_sessions(user_id);
+CREATE INDEX idx_web_sessions_expires ON web_sessions(expires_at);
+
+-- `PRAGMA foreign_key_check` alone only returns rows under execute_batch and
+-- cannot abort. Fail the migration if this rebuild damaged either V52-owned
+-- author reference, without scanning unrelated pre-existing violations.
+CREATE TABLE v52_fk_guard (
+ ok INTEGER NOT NULL CHECK (ok = 0)
+);
+INSERT INTO v52_fk_guard (ok)
+SELECT
+ (SELECT COUNT(*) FROM pragma_foreign_key_check('pages')) +
+ (SELECT COUNT(*) FROM pragma_foreign_key_check('audit_log'));
+DROP TABLE v52_fk_guard;
diff --git a/crates/ai-memory-store/migrations/V55__api_credentials.sql b/crates/ai-memory-store/migrations/V55__api_credentials.sql
new file mode 100644
index 00000000..9de85f45
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V55__api_credentials.sql
@@ -0,0 +1,91 @@
+-- Native API credentials. Copy existing 32-byte users.token_hash
+-- values losslessly (id = user_id, label = legacy-user-token).
+-- Abort — no partial commit — if any non-NULL hash is the wrong length.
+-- Keep users.token_hash / token_expired_at as the deprecated 1.x
+-- compatibility write path. These mirror triggers are load-bearing until
+-- the user token shims are removed in 2.0; auth lookup uses api_credentials.
+
+CREATE TABLE v53_token_hash_guard (
+ ok INTEGER NOT NULL CHECK (ok = 0)
+);
+INSERT INTO v53_token_hash_guard (ok)
+SELECT COUNT(*) FROM users WHERE token_hash IS NOT NULL AND length(token_hash) != 32;
+DROP TABLE v53_token_hash_guard;
+
+CREATE TABLE api_credentials (
+ id BLOB NOT NULL PRIMARY KEY,
+ user_id BLOB NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ label TEXT NOT NULL,
+ token_hash BLOB NOT NULL UNIQUE CHECK (length(token_hash) = 32),
+ preview TEXT,
+ created_at INTEGER NOT NULL,
+ last_used_at INTEGER,
+ expires_at INTEGER,
+ revoked_at INTEGER
+);
+
+CREATE INDEX idx_api_credentials_user ON api_credentials(user_id);
+
+INSERT INTO api_credentials (
+ id, user_id, label, token_hash, preview, created_at, last_used_at, expires_at, revoked_at
+)
+SELECT
+ id,
+ id,
+ 'legacy-user-token',
+ token_hash,
+ NULL,
+ created_at,
+ last_seen_at,
+ NULL,
+ token_expired_at
+FROM users
+WHERE token_hash IS NOT NULL AND length(token_hash) = 32;
+
+CREATE TRIGGER users_token_hash_length_ai
+BEFORE INSERT ON users
+FOR EACH ROW
+WHEN NEW.token_hash IS NOT NULL AND length(NEW.token_hash) != 32
+BEGIN
+ SELECT RAISE(ABORT, 'users.token_hash must be 32 bytes');
+END;
+
+CREATE TRIGGER users_token_hash_length_au
+BEFORE UPDATE OF token_hash ON users
+FOR EACH ROW
+WHEN NEW.token_hash IS NOT NULL AND length(NEW.token_hash) != 32
+BEGIN
+ SELECT RAISE(ABORT, 'users.token_hash must be 32 bytes');
+END;
+
+CREATE TRIGGER users_token_hash_mirror_ai
+AFTER INSERT ON users
+FOR EACH ROW
+WHEN NEW.token_hash IS NOT NULL AND length(NEW.token_hash) = 32
+BEGIN
+ INSERT INTO api_credentials (
+ id, user_id, label, token_hash, preview, created_at, last_used_at, expires_at, revoked_at
+ ) VALUES (
+ NEW.id, NEW.id, 'legacy-user-token', NEW.token_hash, NULL,
+ NEW.created_at, NULL, NULL, NEW.token_expired_at
+ )
+ ON CONFLICT(id) DO UPDATE SET
+ token_hash = excluded.token_hash,
+ revoked_at = excluded.revoked_at;
+END;
+
+CREATE TRIGGER users_token_hash_mirror_au
+AFTER UPDATE OF token_hash, token_expired_at ON users
+FOR EACH ROW
+WHEN NEW.token_hash IS NOT NULL AND length(NEW.token_hash) = 32
+BEGIN
+ INSERT INTO api_credentials (
+ id, user_id, label, token_hash, preview, created_at, last_used_at, expires_at, revoked_at
+ ) VALUES (
+ NEW.id, NEW.id, 'legacy-user-token', NEW.token_hash, NULL,
+ NEW.created_at, NULL, NULL, NEW.token_expired_at
+ )
+ ON CONFLICT(id) DO UPDATE SET
+ token_hash = excluded.token_hash,
+ revoked_at = excluded.revoked_at;
+END;
diff --git a/crates/ai-memory-store/src/api_credentials.rs b/crates/ai-memory-store/src/api_credentials.rs
new file mode 100644
index 00000000..5ad79b3f
--- /dev/null
+++ b/crates/ai-memory-store/src/api_credentials.rs
@@ -0,0 +1,623 @@
+//! Native `aim_` API credentials. Auth lookup never reads `users.token_hash`.
+
+use ai_memory_core::{ApiCredential, ApiCredentialId, NATIVE_API_KEY_PREFIX, User, UserId};
+use base64::Engine;
+use base64::engine::general_purpose::URL_SAFE_NO_PAD;
+use jiff::Timestamp;
+use rusqlite::{Connection, OptionalExtension, params};
+
+use crate::error::{StoreError, StoreResult};
+use crate::users::{TOKEN_HASH_LEN, TOKEN_RAW_LEN, map_unique_violation, row_to_user};
+
+/// `aim_` + 43 URL-safe characters.
+///
+/// # Errors
+/// [`StoreError::Os`] when the CSPRNG fails.
+pub fn generate_api_key() -> StoreResult<String> {
+ let mut bytes = [0u8; TOKEN_RAW_LEN];
+ getrandom::fill(&mut bytes)
+ .map_err(|e| StoreError::Os(format!("os csprng failed during api key: {e}")))?;
+ Ok(format!(
+ "{NATIVE_API_KEY_PREFIX}{}",
+ URL_SAFE_NO_PAD.encode(bytes)
+ ))
+}
+
+/// Non-authenticating preview (last four of the secret).
+#[must_use]
+pub fn preview_for(secret: &str) -> String {
+ let tail = secret
+ .chars()
+ .rev()
+ .take(4)
+ .collect::<String>()
+ .chars()
+ .rev()
+ .collect::<String>();
+ format!("…{tail}")
+}
+
+/// User authenticated by an active API credential. Always `AuthLevel::User`.
+#[derive(Debug, Clone)]
+pub struct AuthenticatedApiUser {
+ /// Owning identity.
+ pub user: User,
+ /// Credential that matched.
+ pub credential_id: ApiCredentialId,
+}
+
+/// Insert a credential. `id` is caller-chosen so brownfield copies can
+/// reuse `user_id`.
+///
+/// # Errors
+/// Duplicate hash / SQL.
+pub fn insert_api_credential(
+ conn: &Connection,
+ id: ApiCredentialId,
+ user_id: UserId,
+ label: &str,
+ token_hash: &[u8; TOKEN_HASH_LEN],
+ preview: Option<&str>,
+) -> StoreResult<ApiCredentialId> {
+ let now = Timestamp::now().as_microsecond();
+ conn.execute(
+ "INSERT INTO api_credentials \
+ (id, user_id, label, token_hash, preview, created_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
+ params![
+ id.as_bytes(),
+ user_id.as_bytes(),
+ label,
+ token_hash.as_slice(),
+ preview,
+ now,
+ ],
+ )
+ .map_err(map_unique_violation)?;
+ Ok(id)
+}
+
+/// Rotate: write a new hash on the same id, clear revoked_at.
+///
+/// # Errors
+/// Duplicate hash / SQL / not found.
+pub fn rotate_api_credential(
+ conn: &Connection,
+ id: ApiCredentialId,
+ new_token_hash: &[u8; TOKEN_HASH_LEN],
+ preview: Option<&str>,
+) -> StoreResult<bool> {
+ let rows = conn
+ .execute(
+ "UPDATE api_credentials \
+ SET token_hash = ?1, preview = ?2, revoked_at = NULL \
+ WHERE id = ?3",
+ params![new_token_hash.as_slice(), preview, id.as_bytes()],
+ )
+ .map_err(map_unique_violation)?;
+ Ok(rows > 0)
+}
+
+/// Revoke. Idempotent.
+///
+/// # Errors
+/// SQL failures.
+pub fn revoke_api_credential(conn: &Connection, id: ApiCredentialId) -> StoreResult<bool> {
+ let now = Timestamp::now().as_microsecond();
+ let rows = conn.execute(
+ "UPDATE api_credentials SET revoked_at = COALESCE(revoked_at, ?1) WHERE id = ?2",
+ params![now, id.as_bytes()],
+ )?;
+ Ok(rows > 0)
+}
+
+/// Touch last_used_at.
+///
+/// # Errors
+/// SQL failures.
+pub fn touch_api_credential(conn: &Connection, id: ApiCredentialId) -> StoreResult<bool> {
+ let now = Timestamp::now().as_microsecond();
+ let rows = conn.execute(
+ "UPDATE api_credentials SET last_used_at = ?1 WHERE id = ?2",
+ params![now, id.as_bytes()],
+ )?;
+ Ok(rows > 0)
+}
+
+/// Hot-path auth lookup. Does **not** filter `users.disabled_at`.
+///
+/// # Errors
+/// SQL failures.
+pub fn find_active_user_by_token_hash(
+ conn: &Connection,
+ token_hash: &[u8; TOKEN_HASH_LEN],
+ now: i64,
+) -> StoreResult<Option<AuthenticatedApiUser>> {
+ conn.query_row(
+ "SELECT u.id, u.username, u.name, u.email, u.created_at, u.last_seen_at, \
+ u.role, u.must_change_password, u.disabled_at, u.password_hash, \
+ u.token_expired_at, c.id \
+ FROM api_credentials c \
+ JOIN users u ON u.id = c.user_id \
+ WHERE c.token_hash = ?1 AND c.revoked_at IS NULL \
+ AND (c.expires_at IS NULL OR c.expires_at > ?2)",
+ params![token_hash.as_slice(), now],
+ |row| {
+ let cred_bytes: Vec<u8> = row.get(11)?;
+ let credential_id = ApiCredentialId::from_slice(&cred_bytes).map_err(|e| {
+ rusqlite::Error::FromSqlConversionFailure(
+ 11,
+ rusqlite::types::Type::Blob,
+ Box::new(std::io::Error::other(e.to_string())),
+ )
+ })?;
+ Ok(AuthenticatedApiUser {
+ user: row_to_user(row, 0)?,
+ credential_id,
+ })
+ },
+ )
+ .optional()
+ .map_err(StoreError::from)
+}
+
+/// True when any credential (active or revoked) stores this hash.
+/// Used by password-reuse detection.
+///
+/// # Errors
+/// SQL failures.
+pub fn token_hash_exists(
+ conn: &Connection,
+ token_hash: &[u8; TOKEN_HASH_LEN],
+) -> StoreResult<bool> {
+ conn.query_row(
+ "SELECT EXISTS(SELECT 1 FROM api_credentials WHERE token_hash = ?1)",
+ params![token_hash.as_slice()],
+ |row| row.get(0),
+ )
+ .map_err(StoreError::from)
+}
+
+/// List credentials for one user, newest first.
+///
+/// # Errors
+/// SQL failures.
+pub fn list_api_credentials_for_user(
+ conn: &Connection,
+ user_id: UserId,
+) -> StoreResult<Vec<ApiCredential>> {
+ let mut stmt = conn.prepare(
+ "SELECT id, user_id, label, preview, created_at, last_used_at, expires_at, revoked_at \
+ FROM api_credentials WHERE user_id = ?1 ORDER BY created_at DESC",
+ )?;
+ let rows = stmt
+ .query_map(params![user_id.as_bytes()], row_to_credential)?
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(rows)
+}
+
+/// List every credential.
+///
+/// # Errors
+/// SQL failures.
+pub fn list_api_credentials(conn: &Connection) -> StoreResult<Vec<ApiCredential>> {
+ let mut stmt = conn.prepare(
+ "SELECT id, user_id, label, preview, created_at, last_used_at, expires_at, revoked_at \
+ FROM api_credentials ORDER BY created_at DESC",
+ )?;
+ let rows = stmt
+ .query_map([], row_to_credential)?
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(rows)
+}
+
+/// Look up one credential by id.
+///
+/// # Errors
+/// SQL failures.
+pub fn find_api_credential(
+ conn: &Connection,
+ id: ApiCredentialId,
+) -> StoreResult<Option<ApiCredential>> {
+ conn.query_row(
+ "SELECT id, user_id, label, preview, created_at, last_used_at, expires_at, revoked_at \
+ FROM api_credentials WHERE id = ?1",
+ params![id.as_bytes()],
+ row_to_credential,
+ )
+ .optional()
+ .map_err(StoreError::from)
+}
+
+/// True when any native credential row exists (pepper required at startup).
+///
+/// # Errors
+/// SQL failures.
+pub fn api_credentials_exist(conn: &Connection) -> StoreResult<bool> {
+ conn.query_row("SELECT EXISTS(SELECT 1 FROM api_credentials)", [], |row| {
+ row.get(0)
+ })
+ .map_err(StoreError::from)
+}
+
+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| {
+ rusqlite::Error::FromSqlConversionFailure(
+ 0,
+ rusqlite::types::Type::Blob,
+ Box::new(std::io::Error::other(e.to_string())),
+ )
+ })?;
+ let user_bytes: Vec<u8> = row.get(1)?;
+ let user_id = UserId::from_slice(&user_bytes).map_err(|e| {
+ rusqlite::Error::FromSqlConversionFailure(
+ 1,
+ rusqlite::types::Type::Blob,
+ Box::new(std::io::Error::other(e.to_string())),
+ )
+ })?;
+ Ok(ApiCredential {
+ id,
+ user_id,
+ label: row.get(2)?,
+ preview: row.get(3)?,
+ created_at: row.get(4)?,
+ last_used_at: row.get(5)?,
+ expires_at: row.get(6)?,
+ revoked_at: row.get(7)?,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::users::{self, TokenPepper, hash_token};
+ use ai_memory_core::{NewUser, UserId, UserRole};
+ use rusqlite::{Connection, params};
+
+ fn open_to(version: u32) -> Connection {
+ let mut conn = Connection::open_in_memory().unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ crate::migrations::run_to(&mut conn, version).unwrap();
+ conn
+ }
+
+ fn insert_pre_human_user(
+ conn: &Connection,
+ username: &str,
+ hash: &[u8],
+ expired: bool,
+ ) -> UserId {
+ let id = UserId::new();
+ conn.execute(
+ "INSERT INTO users (id, username, name, email, token_hash, created_at, token_expired_at) \
+ VALUES (?1, ?2, NULL, NULL, ?3, 1, ?4)",
+ params![
+ id.as_bytes(),
+ username,
+ hash,
+ if expired { Some(99i64) } else { None }
+ ],
+ )
+ .unwrap();
+ id
+ }
+
+ #[test]
+ fn api_credentials_v55_copies_active_and_expired_hashes() {
+ let mut conn = open_to(50);
+ let active = [0xAAu8; 32];
+ let expired = [0xBBu8; 32];
+ let alice = insert_pre_human_user(&conn, "alice", &active, false);
+ let bob = insert_pre_human_user(&conn, "bob", &expired, true);
+ crate::migrations::run_to(&mut conn, 55).unwrap();
+
+ let (label, hash, revoked): (String, Vec<u8>, Option<i64>) = conn
+ .query_row(
+ "SELECT label, token_hash, revoked_at FROM api_credentials WHERE id = ?1",
+ params![alice.as_bytes()],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
+ )
+ .unwrap();
+ assert_eq!(label, "legacy-user-token");
+ assert_eq!(hash, active);
+ assert!(revoked.is_none());
+
+ let (hash, revoked): (Vec<u8>, Option<i64>) = conn
+ .query_row(
+ "SELECT token_hash, revoked_at FROM api_credentials WHERE id = ?1",
+ params![bob.as_bytes()],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .unwrap();
+ assert_eq!(hash, expired);
+ assert_eq!(revoked, Some(99));
+ }
+
+ #[test]
+ fn api_credentials_v55_aborts_on_malformed_hash_length() {
+ let mut conn = open_to(54);
+ let id = UserId::new();
+ conn.execute(
+ "INSERT INTO users (id, username, name, email, token_hash, created_at, role) \
+ VALUES (?1, 'bad', NULL, NULL, ?2, 1, 'user')",
+ params![id.as_bytes(), [1u8; 16].as_slice()],
+ )
+ .unwrap();
+ let err = crate::migrations::run_to(&mut conn, 55).unwrap_err();
+ let msg = err.to_string();
+ assert!(
+ msg.contains("CHECK") || msg.contains("constraint") || msg.contains("ok"),
+ "{msg}"
+ );
+ }
+
+ #[test]
+ fn api_credentials_v55_skips_password_only_users() {
+ let mut conn = open_to(54);
+ let id = UserId::new();
+ conn.execute(
+ "INSERT INTO users (id, username, name, email, token_hash, created_at, role, password_hash) \
+ VALUES (?1, 'human', NULL, NULL, NULL, 1, 'user', 'phc')",
+ params![id.as_bytes()],
+ )
+ .unwrap();
+ crate::migrations::run_to(&mut conn, 55).unwrap();
+ let count: i64 = conn
+ .query_row("SELECT COUNT(*) FROM api_credentials", [], |row| row.get(0))
+ .unwrap();
+ assert_eq!(count, 0);
+ }
+
+ #[test]
+ fn api_credentials_v55_mirror_trigger_copies_pre_v54_write() {
+ let mut conn = open_to(55);
+ let id = UserId::new();
+ let hash = [0xCCu8; 32];
+ conn.execute(
+ "INSERT INTO users (id, username, name, email, token_hash, created_at, role) \
+ VALUES (?1, 'legacy', NULL, NULL, ?2, 1, 'user')",
+ params![id.as_bytes(), hash.as_slice()],
+ )
+ .unwrap();
+ let copied: Vec<u8> = conn
+ .query_row(
+ "SELECT token_hash FROM api_credentials WHERE id = ?1",
+ params![id.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(copied, hash);
+ crate::migrations::run(&mut conn).unwrap();
+ assert!(
+ find_active_user_by_token_hash(&conn, &hash, 0)
+ .unwrap()
+ .is_some()
+ );
+ }
+
+ #[test]
+ fn schema_stops_at_v55_rollback_bridge() {
+ let mut conn = Connection::open_in_memory().unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ crate::migrations::run(&mut conn).unwrap();
+ let version: i64 = conn
+ .query_row(
+ "SELECT MAX(version) FROM refinery_schema_history",
+ [],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(version, 55);
+ let cols: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM pragma_table_info('users') WHERE name = 'token_hash'",
+ [],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(cols, 1);
+ }
+
+ #[test]
+ fn api_credentials_v55_human_create_has_no_key() {
+ let mut conn = Connection::open_in_memory().unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ crate::migrations::run(&mut conn).unwrap();
+ let mut nu = NewUser {
+ username: "carol".into(),
+ name: None,
+ email: None,
+ };
+ nu.validate().unwrap();
+ let id = users::insert_human_user(&conn, &nu, UserRole::User, Some("phc"), true).unwrap();
+ assert!(list_api_credentials_for_user(&conn, id).unwrap().is_empty());
+ assert!(!api_credentials_exist(&conn).unwrap());
+ }
+
+ #[test]
+ fn api_credentials_auth_lookup_ignores_revoked_and_disabled() {
+ let mut conn = Connection::open_in_memory().unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ crate::migrations::run(&mut conn).unwrap();
+ let mut nu = NewUser {
+ username: "dave".into(),
+ name: None,
+ email: None,
+ };
+ nu.validate().unwrap();
+ let user_id =
+ users::insert_human_user(&conn, &nu, UserRole::User, Some("phc"), false).unwrap();
+ let pepper = TokenPepper::new("test-pepper-1234567890abcdef");
+ let secret = generate_api_key().unwrap();
+ let hash = hash_token(&secret, &pepper);
+ let cred_id = ApiCredentialId::new();
+ insert_api_credential(&conn, cred_id, user_id, "cli", &hash, Some("…key")).unwrap();
+ let found = find_active_user_by_token_hash(&conn, &hash, 0)
+ .unwrap()
+ .unwrap();
+ assert_eq!(found.user.id, user_id);
+ revoke_api_credential(&conn, cred_id).unwrap();
+ assert!(
+ find_active_user_by_token_hash(&conn, &hash, 0)
+ .unwrap()
+ .is_none()
+ );
+ assert!(token_hash_exists(&conn, &hash).unwrap());
+ }
+
+ #[test]
+ fn api_credentials_v55_expire_then_revive_mirrors_legacy_token() {
+ let mut conn = open_to(50);
+ let hash = [0xDDu8; 32];
+ let id = insert_pre_human_user(&conn, "eve", &hash, false);
+ crate::migrations::run_to(&mut conn, 55).unwrap();
+
+ conn.execute(
+ "UPDATE users SET token_expired_at = ?1 WHERE id = ?2",
+ params![123i64, id.as_bytes()],
+ )
+ .unwrap();
+ let (copied, revoked): (Vec<u8>, Option<i64>) = conn
+ .query_row(
+ "SELECT token_hash, revoked_at FROM api_credentials WHERE id = ?1",
+ params![id.as_bytes()],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .unwrap();
+ assert_eq!(copied, hash);
+ assert_eq!(revoked, Some(123));
+ assert!(
+ find_active_user_by_token_hash(&conn, &hash, 0)
+ .unwrap()
+ .is_none()
+ );
+
+ conn.execute(
+ "UPDATE users SET token_expired_at = NULL WHERE id = ?1",
+ params![id.as_bytes()],
+ )
+ .unwrap();
+ let (copied, revoked): (Vec<u8>, Option<i64>) = conn
+ .query_row(
+ "SELECT token_hash, revoked_at FROM api_credentials WHERE id = ?1",
+ params![id.as_bytes()],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .unwrap();
+ assert_eq!(copied, hash);
+ assert!(revoked.is_none());
+ let found = find_active_user_by_token_hash(&conn, &hash, 0)
+ .unwrap()
+ .unwrap();
+ assert_eq!(found.user.id, id);
+ assert_eq!(found.credential_id.as_bytes(), id.as_bytes());
+ }
+
+ #[test]
+ fn api_credentials_v55_post_v55_malformed_hash_write_aborts() {
+ let conn = open_to(55);
+ let bad_id = UserId::new();
+ let err = conn
+ .execute(
+ "INSERT INTO users (id, username, name, email, token_hash, created_at, role) \
+ VALUES (?1, 'bad-post', NULL, NULL, ?2, 1, 'user')",
+ params![bad_id.as_bytes(), [1u8; 16].as_slice()],
+ )
+ .unwrap_err();
+ let msg = err.to_string();
+ assert!(msg.contains("users.token_hash must be 32 bytes"), "{msg}");
+ let users: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM users WHERE username = 'bad-post'",
+ [],
+ |row| row.get(0),
+ )
+ .unwrap();
+ let creds: i64 = conn
+ .query_row("SELECT COUNT(*) FROM api_credentials", [], |row| row.get(0))
+ .unwrap();
+ assert_eq!(users, 0);
+ assert_eq!(creds, 0);
+
+ let id = UserId::new();
+ let good = [0xEEu8; 32];
+ conn.execute(
+ "INSERT INTO users (id, username, name, email, token_hash, created_at, role) \
+ VALUES (?1, 'ok-then-bad', NULL, NULL, ?2, 1, 'user')",
+ params![id.as_bytes(), good.as_slice()],
+ )
+ .unwrap();
+ let err = conn
+ .execute(
+ "UPDATE users SET token_hash = ?1 WHERE id = ?2",
+ params![[2u8; 8].as_slice(), id.as_bytes()],
+ )
+ .unwrap_err();
+ let msg = err.to_string();
+ assert!(msg.contains("users.token_hash must be 32 bytes"), "{msg}");
+ let (user_hash, cred_hash): (Vec<u8>, Vec<u8>) = conn
+ .query_row(
+ "SELECT u.token_hash, c.token_hash \
+ FROM users u JOIN api_credentials c ON c.id = u.id \
+ WHERE u.id = ?1",
+ params![id.as_bytes()],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .unwrap();
+ assert_eq!(user_hash, good);
+ assert_eq!(cred_hash, good);
+ assert!(
+ find_active_user_by_token_hash(&conn, &good, 0)
+ .unwrap()
+ .is_some()
+ );
+ }
+
+ #[test]
+ fn api_credentials_v55_v50_peppered_secret_still_authenticates() {
+ let mut conn = open_to(50);
+ let pepper = TokenPepper::new("test-pepper-1234567890abcdef");
+ let active_secret = "v50-plaintext-active-secret";
+ let expired_secret = "v50-plaintext-expired-secret";
+ let active_hash = hash_token(active_secret, &pepper);
+ let expired_hash = hash_token(expired_secret, &pepper);
+ let alice = insert_pre_human_user(&conn, "alice-v50", &active_hash, false);
+ let bob = insert_pre_human_user(&conn, "bob-v50", &expired_hash, true);
+ crate::migrations::run_to(&mut conn, 55).unwrap();
+
+ let copied_active: Vec<u8> = conn
+ .query_row(
+ "SELECT token_hash FROM api_credentials WHERE id = ?1",
+ params![alice.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ let copied_expired: Vec<u8> = conn
+ .query_row(
+ "SELECT token_hash FROM api_credentials WHERE id = ?1",
+ params![bob.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(copied_active, active_hash);
+ assert_eq!(copied_expired, expired_hash);
+
+ let lookup_hash = hash_token(active_secret, &pepper);
+ assert_eq!(lookup_hash, active_hash);
+ let found = find_active_user_by_token_hash(&conn, &lookup_hash, 0)
+ .unwrap()
+ .unwrap();
+ assert_eq!(found.user.id, alice);
+ assert_eq!(found.credential_id.as_bytes(), alice.as_bytes());
+
+ let expired_lookup = hash_token(expired_secret, &pepper);
+ assert_eq!(expired_lookup, expired_hash);
+ assert!(
+ find_active_user_by_token_hash(&conn, &expired_lookup, 0)
+ .unwrap()
+ .is_none()
+ );
+ }
+}
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index b2f8eca7..4b8bca8c 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -14,6 +14,7 @@ use std::path::{Path, PathBuf};
use rusqlite::Connection;
+mod api_credentials;
mod auto_improve;
pub mod decay;
mod error;
@@ -21,15 +22,18 @@ mod fts_query;
mod maintenance;
mod migrations;
mod ops;
+pub mod password;
mod reader;
mod scope;
mod session_consolidation;
pub mod users;
+pub mod web_sessions;
mod workstream;
mod writer;
pub use fts_query::prepare_fts5_query;
+pub use api_credentials::{AuthenticatedApiUser, generate_api_key, preview_for as api_key_preview};
pub use auto_improve::{
ApproveAutoImproveProposal, ApproveAutoImproveProposalResult, AutoImproveProposalDetail,
AutoImproveProposalEvent, AutoImproveProposalOperation, AutoImproveProposalStatus,
@@ -67,7 +71,10 @@ pub use scope::{
lookup_global_scope, resolve_many_existing_scopes,
};
pub use session_consolidation::{SESSION_CONSOLIDATION_MAX_ATTEMPTS, SessionConsolidationJob};
-pub use users::{TOKEN_HASH_LEN, TOKEN_RAW_LEN, TokenPepper, generate_token, hash_token};
+pub use users::{
+ LoginUser, TOKEN_HASH_LEN, TOKEN_RAW_LEN, TokenPepper, generate_token, hash_token,
+};
+pub use web_sessions::{LiveWebSession, WebSession, hash_session_secret};
pub use workstream::{
FinishWorkstreamRun, FinishedWorkstreamRun, ManagedRunContext, PrepareWorkstreamRun,
PreparedWorkstreamRun, RenameWorkstream, RenamedWorkstream, StoredManagedRunStatus,
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 9d947496..c7b81345 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -5549,8 +5549,8 @@ pub(crate) mod tests {
let author = UserId::new();
let now = Timestamp::now().as_microsecond();
conn.execute(
- "INSERT INTO users (id, username, token_hash, created_at) \
- VALUES (?1, 'feedback-author', X'01', ?2)",
+ "INSERT INTO users (id, username, created_at) \
+ VALUES (?1, 'feedback-author', ?2)",
params![author.as_bytes(), now],
)
.unwrap();
@@ -5756,9 +5756,8 @@ pub(crate) mod tests {
let user_id = UserId::new();
let now = jiff::Timestamp::now().as_microsecond();
conn.execute(
- "INSERT INTO users \
- (id, username, name, email, token_hash, created_at) \
- VALUES (?1, 'alice', NULL, NULL, X'00', ?2)",
+ "INSERT INTO users (id, username, name, email, created_at) \
+ VALUES (?1, 'alice', NULL, NULL, ?2)",
params![user_id.as_bytes(), now],
)
.unwrap();
@@ -5820,9 +5819,9 @@ pub(crate) mod tests {
let alice = UserId::new();
let bob = UserId::new();
conn.execute(
- "INSERT INTO users (id, username, name, email, token_hash, created_at) \
- VALUES (?1, 'alice', NULL, NULL, X'01', ?2), \
- (?3, 'bob', NULL, NULL, X'02', ?2)",
+ "INSERT INTO users (id, username, name, email, created_at) \
+ VALUES (?1, 'alice', NULL, NULL, ?2), \
+ (?3, 'bob', NULL, NULL, ?2)",
params![alice.as_bytes(), now, bob.as_bytes()],
)
.unwrap();
@@ -8679,14 +8678,16 @@ pub(crate) mod tests {
}
fn seed_user(conn: &Connection, username: &str) -> ai_memory_core::UserId {
- crate::users::insert_user(
+ crate::users::insert_human_user(
conn,
&ai_memory_core::NewUser {
username: username.to_string(),
name: None,
email: None,
},
- &[7u8; crate::users::TOKEN_HASH_LEN],
+ ai_memory_core::UserRole::User,
+ None,
+ false,
)
.expect("seed user")
}
diff --git a/crates/ai-memory-store/src/password.rs b/crates/ai-memory-store/src/password.rs
new file mode 100644
index 00000000..e6cdd302
--- /dev/null
+++ b/crates/ai-memory-store/src/password.rs
@@ -0,0 +1,138 @@
+//! Argon2id password hashing, always off the writer thread.
+//!
+//! Human passwords use the crate-default Argon2id PHC string. The KDF
+//! runs in `spawn_blocking` behind a two-permit semaphore so a login
+//! flood cannot stall the SQLite writer. Unknown and disabled users
+//! still pay a dummy verify so the timing of "no such user" matches a
+//! real miss.
+
+use std::sync::LazyLock;
+
+use argon2::Argon2;
+use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
+use base64::Engine;
+use tokio::sync::Semaphore;
+
+use crate::error::{StoreError, StoreResult};
+
+/// Concurrent Argon2id slots. Login IP rate-limit fires first; this
+/// bound prevents password work from saturating the blocking pool.
+const KDF_PERMITS: usize = 2;
+/// Active plus queued KDF jobs. Exceeding this bound returns HTTP 429.
+const KDF_PENDING_LIMIT: usize = 32;
+
+static KDF_SLOTS: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(KDF_PERMITS));
+static KDF_PENDING: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(KDF_PENDING_LIMIT));
+
+fn dummy_phc() -> &'static str {
+ "$argon2id$v=19$m=19456,t=2,p=1$YWktbWVtb3J5LWR1bW15$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+}
+
+fn hash_password_sync(password: &str) -> StoreResult<String> {
+ let mut salt_bytes = [0u8; 16];
+ getrandom::fill(&mut salt_bytes)
+ .map_err(|e| StoreError::Os(format!("os csprng failed during password salt: {e}")))?;
+ let salt = SaltString::encode_b64(&salt_bytes)
+ .map_err(|e| StoreError::InvalidState(format!("password salt: {e}")))?;
+ Argon2::default()
+ .hash_password(password.as_bytes(), &salt)
+ .map(|hash| hash.to_string())
+ .map_err(|e| StoreError::InvalidState(format!("password hash: {e}")))
+}
+
+fn verify_password_sync(password: &str, phc: &str) -> StoreResult<bool> {
+ let parsed = PasswordHash::new(phc)
+ .map_err(|e| StoreError::MalformedRecord(format!("password hash: {e}")))?;
+ Ok(Argon2::default()
+ .verify_password(password.as_bytes(), &parsed)
+ .is_ok())
+}
+
+async fn with_kdf_slot<T, F>(work: F) -> StoreResult<T>
+where
+ F: FnOnce() -> StoreResult<T> + Send + 'static,
+ T: Send + 'static,
+{
+ let pending_permit = KDF_PENDING
+ .try_acquire()
+ .map_err(|_| StoreError::InvalidState("kdf saturated".into()))?;
+ let slot_permit = KDF_SLOTS
+ .acquire()
+ .await
+ .map_err(|_| StoreError::InvalidState("kdf unavailable".into()))?;
+ let result = tokio::task::spawn_blocking(work)
+ .await
+ .map_err(|e| StoreError::PoolPanic(format!("password kdf task: {e}")))?;
+ drop(slot_permit);
+ drop(pending_permit);
+ result
+}
+
+/// Hash `password` to a PHC string. Runs off the writer thread.
+///
+/// # Errors
+/// [`StoreError::InvalidState`] when the KDF queue is saturated (HTTP 429)
+/// or hashing fails. [`StoreError::Os`] when the CSPRNG fails.
+pub async fn hash_password(password: String) -> StoreResult<String> {
+ with_kdf_slot(move || hash_password_sync(&password)).await
+}
+
+/// Verify `password` against a stored PHC string. Runs off the writer thread.
+///
+/// # Errors
+/// [`StoreError::InvalidState`] when saturated; [`StoreError::MalformedRecord`]
+/// when the stored PHC cannot be parsed.
+pub async fn verify_password(password: String, phc: String) -> StoreResult<bool> {
+ with_kdf_slot(move || verify_password_sync(&password, &phc)).await
+}
+
+/// Always run a KDF against the process-wide dummy PHC so unknown and
+/// disabled logins spend the same time as a real miss.
+///
+/// # Errors
+/// Same as [`verify_password`].
+pub async fn dummy_verify(password: String) -> StoreResult<()> {
+ let phc = dummy_phc().to_string();
+ let _ = verify_password(password, phc).await?;
+ Ok(())
+}
+
+/// 24 CSPRNG bytes encoded as 32 URL-safe characters. Callers still run
+/// [`ai_memory_core::validate_human_password`] and retry on collision.
+///
+/// # Errors
+/// [`StoreError::Os`] when the CSPRNG fails.
+pub fn generate_temporary_password() -> StoreResult<String> {
+ let mut bytes = [0u8; 24];
+ getrandom::fill(&mut bytes)
+ .map_err(|e| StoreError::Os(format!("os csprng failed during temporary password: {e}")))?;
+ Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn hash_password_sync_round_trips() {
+ let phc = hash_password_sync("twelve chars!!").unwrap();
+ assert!(phc.starts_with("$argon2id$"));
+ assert!(verify_password_sync("twelve chars!!", &phc).unwrap());
+ assert!(!verify_password_sync("twelve chars??", &phc).unwrap());
+ }
+
+ #[test]
+ fn dummy_phc_is_valid_and_never_matches_login_input() {
+ assert!(!verify_password_sync("anything", dummy_phc()).unwrap());
+ }
+
+ #[test]
+ fn generate_temporary_password_is_url_safe_32() {
+ let pw = generate_temporary_password().unwrap();
+ assert_eq!(pw.len(), 32);
+ assert!(
+ pw.chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
+ );
+ }
+}
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 469fd2ff..44df4433 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1184,7 +1184,7 @@ pub struct PageSummary {
///
/// Repeated here rather than reused from `ai_memory_core::User` because
/// the response shape intentionally omits internal fields (id,
-/// created_at, last_seen_at, token_expired_at) — only the human-facing
+/// created_at, last_seen_at, role) — only the human-facing
/// identity is part of the API contract.
#[derive(Debug, Clone, Serialize)]
pub struct PageAuthor {
@@ -7063,24 +7063,26 @@ impl ReaderPool {
// ── user lookups ────────────────────────────────────────────────
- /// Hot path for the auth middleware: hash the incoming bearer token,
- /// look up the matching row, and return the user iff their token is
- /// active (`token_expired_at IS NULL`).
+ /// Hot path for Bearer auth: native `api_credentials` where
+ /// `revoked_at IS NULL`. Does not filter `users.disabled_at`.
+ /// Always authenticates as [`ai_memory_core::AuthLevel::User`].
///
/// # Errors
- /// Propagates any SQL or pool error. Returns `Ok(None)` when no row
- /// matches the hash (either no such user, or the token was expired).
+ /// Propagates any SQL or pool error. Returns `Ok(None)` when no
+ /// active credential matches.
pub async fn find_active_user_by_token_hash(
&self,
token_hash: [u8; TOKEN_HASH_LEN],
- ) -> StoreResult<Option<User>> {
- self.with_conn(move |conn| crate::users::find_active_user_by_token_hash(conn, &token_hash))
- .await
+ ) -> StoreResult<Option<crate::AuthenticatedApiUser>> {
+ let now = now_us();
+ self.with_conn(move |conn| {
+ crate::api_credentials::find_active_user_by_token_hash(conn, &token_hash, now)
+ })
+ .await
}
/// Look up a user by exact-match username. Used by admin endpoints
- /// that accept username on the wire (`expire`, `revive`,
- /// `rotate-token`).
+ /// that accept username on the wire.
///
/// # Errors
/// Propagates any SQL or pool error.
@@ -7089,9 +7091,34 @@ impl ReaderPool {
.await
}
- /// Look up a user by id. **Returns even users whose token is expired**
- /// — this is the attribution-display path (a page authored by alice
- /// must still render "alice" after her token has been expired).
+ /// Login lookup including the stored Argon2id PHC.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn find_login_user_by_username(
+ &self,
+ username: String,
+ ) -> StoreResult<Option<crate::LoginUser>> {
+ self.with_conn(move |conn| crate::users::find_login_user_by_username(conn, &username))
+ .await
+ }
+
+ /// Live (unrevoked, unexpired) web session by secret hash.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn find_live_session_by_hash(
+ &self,
+ session_hash: [u8; TOKEN_HASH_LEN],
+ ) -> StoreResult<Option<crate::LiveWebSession>> {
+ let now = now_us();
+ self.with_conn(move |conn| {
+ crate::web_sessions::find_live_session_by_hash(conn, &session_hash, now)
+ })
+ .await
+ }
+
+ /// Look up a user by id, including disabled and password-less rows.
///
/// # Errors
/// Propagates any SQL or pool error.
@@ -7100,9 +7127,7 @@ impl ReaderPool {
.await
}
- /// All registered users, ordered by `created_at` ascending. Includes
- /// users whose token is expired (the CLI surfaces the active/expired
- /// flag from `token_expired_at`).
+ /// All registered users, ordered by `created_at` ascending.
///
/// # Errors
/// Propagates any SQL or pool error.
@@ -7110,6 +7135,83 @@ impl ReaderPool {
self.with_conn(crate::users::list_users).await
}
+ /// Whether bootstrap has been marked complete.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn bootstrap_completed(&self) -> StoreResult<bool> {
+ self.with_conn(crate::users::bootstrap_completed).await
+ }
+
+ /// Whether any user has a password hash.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn any_password_hash(&self) -> StoreResult<bool> {
+ self.with_conn(crate::users::any_password_hash).await
+ }
+
+ /// Recoverable-root count for startup validation.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn count_recoverable_roots(&self) -> StoreResult<i64> {
+ self.with_conn(crate::users::count_recoverable_roots).await
+ }
+
+ /// Whether any native API credential exists (pepper required).
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn api_credentials_exist(&self) -> StoreResult<bool> {
+ self.with_conn(crate::api_credentials::api_credentials_exist)
+ .await
+ }
+
+ /// True when any credential (active or revoked) stores this hash.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn token_hash_exists(&self, token_hash: [u8; TOKEN_HASH_LEN]) -> StoreResult<bool> {
+ self.with_conn(move |conn| crate::api_credentials::token_hash_exists(conn, &token_hash))
+ .await
+ }
+
+ /// List native API credentials, newest first.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn list_api_credentials(&self) -> StoreResult<Vec<ai_memory_core::ApiCredential>> {
+ self.with_conn(crate::api_credentials::list_api_credentials)
+ .await
+ }
+
+ /// List credentials for one user.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn list_api_credentials_for_user(
+ &self,
+ user_id: UserId,
+ ) -> StoreResult<Vec<ai_memory_core::ApiCredential>> {
+ self.with_conn(move |conn| {
+ crate::api_credentials::list_api_credentials_for_user(conn, user_id)
+ })
+ .await
+ }
+
+ /// Look up one credential by id.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn find_api_credential(
+ &self,
+ id: ai_memory_core::ApiCredentialId,
+ ) -> StoreResult<Option<ai_memory_core::ApiCredential>> {
+ self.with_conn(move |conn| crate::api_credentials::find_api_credential(conn, id))
+ .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.
diff --git a/crates/ai-memory-store/src/users.rs b/crates/ai-memory-store/src/users.rs
index 3418f3a8..a1352f50 100644
--- a/crates/ai-memory-store/src/users.rs
+++ b/crates/ai-memory-store/src/users.rs
@@ -1,39 +1,10 @@
-//! User management — SQL ops + token generation/hashing.
+//! User identity SQL plus human-auth lifecycle.
//!
-//! ## Token storage rationale
-//!
-//! Tokens are 32 bytes of OS CSPRNG (256 bits of entropy), URL-safe
-//! base64-encoded for transport. The stored digest is
-//! `SHA-256(token || ":" || pepper)` where `pepper` is a per-server
-//! secret kept in `[auth].token_pepper` (auto-generated by
-//! `ai-memory init`).
-//!
-//! Why SHA-256, not argon2id:
-//!
-//! - **Brute force is infeasible regardless of hash strength.** 2^256
-//! search space dwarfs any plausible offline campaign. Argon2id's slow
-//! hashing buys nothing against tokens of this entropy.
-//! - **Per-request lookup is the hot path.** SHA-256 is deterministic →
-//! indexed `UNIQUE` lookup is O(1). Argon2id's per-hash salt would
-//! force an O(N) scan + hash-compare per request, or a separate
-//! deterministic index column that argon2id was meant to replace.
-//! - **The realistic threat is DB-only theft.** An attacker without the
-//! config can't reconstruct any token because the pepper isn't in the
-//! stolen rows. (An attacker with both the DB *and* the config has
-//! tokens directly anyway — argon2id wouldn't help.)
-//!
-//! Token comparison in the auth path uses [`subtle::ConstantTimeEq`]
-//! to side-step timing attacks against the hash compare.
-//!
-//! ## Function layout
-//!
-//! Each function takes a `&Connection` (or `&Transaction`) and returns
-//! a `StoreResult`. The writer actor owns the connection; these
-//! functions don't open or close it. The lookup functions take
-//! `&Connection` for read-pool use. See module-level tests for the
-//! intended call shapes.
+//! Native API-key hashing stays SHA-256(token || ":" || pepper) for the
+//! hot-path UNIQUE lookup. Human passwords never live in this module's
+//! KDF — see [`crate::password`].
-use ai_memory_core::{NewUser, User, UserId};
+use ai_memory_core::{NewUser, User, UserId, UserRole};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use jiff::Timestamp;
@@ -42,47 +13,33 @@ use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
use crate::error::{StoreError, StoreResult};
+use crate::web_sessions;
-/// Length of a SHA-256 digest in bytes. The `users.token_hash` column
-/// stores exactly this many bytes per row.
+/// Length of a SHA-256 digest in bytes.
pub const TOKEN_HASH_LEN: usize = 32;
-/// Length of a raw token in bytes (256 bits of entropy). The
-/// URL-safe-base64-encoded form returned by [`generate_token`] is 43
-/// characters (32 bytes → ⌈32*4/3⌉ = 43 unpadded chars).
+/// Length of a raw token in bytes (256 bits of entropy).
pub const TOKEN_RAW_LEN: usize = 32;
-/// Per-server token pepper, newtyped to keep it from being mixed up with
-/// other secrets at call sites. Carries the secret read from
-/// `[auth].token_pepper` in config; clone is cheap (small `String`).
+/// Per-server token pepper, newtyped so it is not mixed with other secrets.
#[derive(Debug, Clone)]
pub struct TokenPepper {
inner: String,
}
impl TokenPepper {
- /// Wrap a config-loaded pepper. The caller's responsibility to
- /// ensure it carries enough entropy — `ai-memory init` generates
- /// a 32-byte CSPRNG hex-encoded pepper by default.
+ /// Wrap a config-loaded pepper.
#[must_use]
pub fn new(s: impl Into<String>) -> Self {
Self { inner: s.into() }
}
- /// Bytes used as the second argument to the hash. The `:` separator
- /// in [`hash_token`] lives outside this method so callers can't
- /// accidentally omit it.
fn as_bytes(&self) -> &[u8] {
self.inner.as_bytes()
}
}
-/// Hash a plaintext token to its storage digest.
-///
-/// Layout: `SHA-256(token || ":" || pepper)`. The literal `:` byte
-/// between the two inputs prevents the (cosmetic but real)
-/// `token || pepper` ambiguity where some `(t1, p1)` and `(t2, p2)`
-/// pairs would otherwise collide if `t1 || p1 == t2 || p2`.
+/// `SHA-256(token || ":" || pepper)`.
#[must_use]
pub fn hash_token(token: &str, pepper: &TokenPepper) -> [u8; TOKEN_HASH_LEN] {
let mut hasher = Sha256::new();
@@ -92,21 +49,18 @@ pub fn hash_token(token: &str, pepper: &TokenPepper) -> [u8; TOKEN_HASH_LEN] {
hasher.finalize().into()
}
-/// Constant-time comparison of a fresh hash against a stored row hash.
-/// Equivalent to `==` for correctness; differs in timing characteristics.
+/// Constant-time comparison of two hashes.
#[must_use]
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
a.ct_eq(b).into()
}
-/// Generate a fresh URL-safe-base64 token. 32 bytes of OS CSPRNG, 43
-/// characters of output (unpadded). The caller is expected to display
-/// this exactly once (returning it from `POST /admin/users` or
-/// `POST /admin/users/:username/rotate-token`) and never store it.
+/// Generate a fresh URL-safe-base64 secret (43 characters). Prefer
+/// [`crate::api_credentials::generate_api_key`] for native keys so the
+/// `aim_` prefix is applied.
///
/// # Errors
-/// Returns [`StoreError::Os`] if the OS CSPRNG read fails. In practice
-/// this only happens on misconfigured embedded platforms.
+/// [`StoreError::Os`] if the OS CSPRNG fails.
pub fn generate_token() -> StoreResult<String> {
let mut bytes = [0u8; TOKEN_RAW_LEN];
getrandom::fill(&mut bytes)
@@ -114,16 +68,21 @@ pub fn generate_token() -> StoreResult<String> {
Ok(URL_SAFE_NO_PAD.encode(bytes))
}
-// ── SQL ops ────────────────────────────────────────────────────────
+/// Login lookup: public user plus the stored PHC (never serialised).
+#[derive(Debug, Clone)]
+pub struct LoginUser {
+ /// Public identity.
+ pub user: User,
+ /// Argon2id PHC, if the human has a password.
+ pub password_hash: Option<String>,
+}
-/// Insert a fresh user row. `new_user` MUST have been validated by
-/// [`NewUser::validate`](ai_memory_core::NewUser::validate) before this
-/// call; the writer actor owns that pre-flight.
+/// Insert a token-only compatibility identity. V53 mirrors
+/// `users.token_hash` into the reserved `legacy-user-token`
+/// `api_credentials` row in the same transaction.
///
/// # Errors
-/// - [`StoreError::Duplicate`] when `username` or `email` clashes with
-/// an existing row (UNIQUE violation).
-/// - [`StoreError::Sql`] for any other SQL failure.
+/// Duplicate username/email/token or SQL.
pub fn insert_user(
conn: &Connection,
new_user: &NewUser,
@@ -148,14 +107,10 @@ pub fn insert_user(
Ok(id)
}
-/// Replace the user's `token_hash` with a freshly-generated digest, and
-/// clear `token_expired_at` (rotating a token only makes sense to make
-/// it usable again). Returns whether a row was actually updated; `false`
-/// means the user id didn't exist.
+/// Replace and reactivate the deprecated single-token credential.
///
/// # Errors
-/// Returns [`StoreError::Sql`] for any SQL failure other than the
-/// "no row matched" case (which is reported as `Ok(false)`).
+/// SQL failures.
pub fn rotate_user_token(
conn: &Connection,
id: UserId,
@@ -168,13 +123,10 @@ pub fn rotate_user_token(
Ok(rows > 0)
}
-/// Stamp `token_expired_at = now()` — the user's current token stops
-/// authenticating but the row stays put so historical attribution
-/// references remain valid. Idempotent: expiring an already-expired
-/// token returns `Ok(true)` and leaves `token_expired_at` unchanged.
+/// Idempotently revoke the deprecated single-token credential.
///
/// # Errors
-/// Returns [`StoreError::Sql`] for any SQL failure.
+/// SQL failures.
pub fn expire_user_token(conn: &Connection, id: UserId) -> StoreResult<bool> {
let now = Timestamp::now().as_microsecond();
let rows = conn.execute(
@@ -184,11 +136,10 @@ pub fn expire_user_token(conn: &Connection, id: UserId) -> StoreResult<bool> {
Ok(rows > 0)
}
-/// Clear `token_expired_at`, re-activating the user's existing token.
-/// Idempotent: reviving an already-active token is a no-op.
+/// Idempotently reactivate the deprecated single-token credential.
///
/// # Errors
-/// Returns [`StoreError::Sql`] for any SQL failure.
+/// SQL failures.
pub fn revive_user_token(conn: &Connection, id: UserId) -> StoreResult<bool> {
let rows = conn.execute(
"UPDATE users SET token_expired_at = NULL WHERE id = ?1",
@@ -197,14 +148,341 @@ pub fn revive_user_token(conn: &Connection, id: UserId) -> StoreResult<bool> {
Ok(rows > 0)
}
-/// Update `last_seen_at = now()` for the user. Called fire-and-forget
-/// by the auth middleware on every authenticated request; never blocks
-/// the response. Returns `Ok(false)` when the row doesn't exist (the
-/// caller authenticated against a token whose user was deleted
-/// mid-request — already a logic error elsewhere).
+/// Insert a human identity. `password_hash` is already Argon2id PHC (or
+/// `None` for API-only brownfield-style rows). No API credential is created.
+///
+/// # Errors
+/// Duplicate username/email, SQL.
+pub fn insert_human_user(
+ conn: &Connection,
+ new_user: &NewUser,
+ role: UserRole,
+ password_hash: Option<&str>,
+ must_change_password: bool,
+) -> StoreResult<UserId> {
+ let id = UserId::new();
+ let now = Timestamp::now().as_microsecond();
+ conn.execute(
+ "INSERT INTO users \
+ (id, username, name, email, created_at, role, password_hash, must_change_password) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
+ params![
+ id.as_bytes(),
+ &new_user.username,
+ &new_user.name,
+ &new_user.email,
+ now,
+ role.as_str(),
+ password_hash,
+ i64::from(must_change_password),
+ ],
+ )
+ .map_err(map_unique_violation)?;
+ Ok(id)
+}
+
+/// One-shot root bootstrap. No-op error when already completed — the
+/// caller must not invoke this after the marker is set.
+///
+/// # Errors
+/// Duplicate / SQL / already completed.
+pub fn bootstrap_root(
+ conn: &mut Connection,
+ username: &str,
+ name: Option<&str>,
+ email: Option<&str>,
+ password_hash: &str,
+) -> StoreResult<UserId> {
+ let tx = conn.transaction()?;
+ if bootstrap_completed(&tx)? {
+ return Err(StoreError::InvalidState(
+ "bootstrap already completed".into(),
+ ));
+ }
+ let now = Timestamp::now().as_microsecond();
+ let id = if let Some(existing) = find_user_by_username(&tx, username)? {
+ tx.execute(
+ "UPDATE users SET role = 'root', password_hash = ?1, must_change_password = 1, \
+ disabled_at = NULL, name = COALESCE(?2, name), email = COALESCE(?3, email) \
+ WHERE id = ?4",
+ params![password_hash, name, email, existing.id.as_bytes()],
+ )?;
+ existing.id
+ } else {
+ let id = UserId::new();
+ tx.execute(
+ "INSERT INTO users \
+ (id, username, name, email, created_at, role, password_hash, must_change_password) \
+ VALUES (?1, ?2, ?3, ?4, ?5, 'root', ?6, 1)",
+ params![id.as_bytes(), username, name, email, now, password_hash],
+ )
+ .map_err(map_unique_violation)?;
+ id
+ };
+ set_bootstrap_completed(&tx, true)?;
+ tx.commit()?;
+ Ok(id)
+}
+
+/// Break-glass root reset: create/promote `username`, write PHC with
+/// `must_change_password=false`, revoke that identity's web sessions,
+/// mark bootstrap complete. Does not touch API credentials.
+///
+/// # Errors
+/// Duplicate / SQL.
+pub fn recover_root(
+ conn: &mut Connection,
+ username: &str,
+ name: Option<&str>,
+ email: Option<&str>,
+ password_hash: &str,
+) -> StoreResult<UserId> {
+ let tx = conn.transaction()?;
+ let now = Timestamp::now().as_microsecond();
+ let id = if let Some(existing) = find_user_by_username(&tx, username)? {
+ tx.execute(
+ "UPDATE users SET role = 'root', password_hash = ?1, must_change_password = 0, \
+ disabled_at = NULL, name = COALESCE(?2, name), email = COALESCE(?3, email) \
+ WHERE id = ?4",
+ params![password_hash, name, email, existing.id.as_bytes()],
+ )?;
+ existing.id
+ } else {
+ let id = UserId::new();
+ tx.execute(
+ "INSERT INTO users \
+ (id, username, name, email, created_at, role, password_hash, must_change_password) \
+ VALUES (?1, ?2, ?3, ?4, ?5, 'root', ?6, 0)",
+ params![id.as_bytes(), username, name, email, now, password_hash],
+ )
+ .map_err(map_unique_violation)?;
+ id
+ };
+ web_sessions::revoke_user_sessions(&tx, id, None)?;
+ set_bootstrap_completed(&tx, true)?;
+ tx.commit()?;
+ Ok(id)
+}
+
+/// Replace the stored PHC, optionally force a password change, and revoke
+/// sessions. Used by admin reset-password.
+///
+/// # Errors
+/// Not found / SQL.
+pub fn reset_human_password(
+ conn: &mut Connection,
+ user_id: UserId,
+ password_hash: &str,
+ must_change_password: bool,
+) -> StoreResult<bool> {
+ let tx = conn.transaction()?;
+ let rows = tx.execute(
+ "UPDATE users SET password_hash = ?1, must_change_password = ?2, disabled_at = disabled_at \
+ WHERE id = ?3",
+ params![
+ password_hash,
+ i64::from(must_change_password),
+ user_id.as_bytes()
+ ],
+ )?;
+ if rows == 0 {
+ return Ok(false);
+ }
+ web_sessions::revoke_user_sessions(&tx, user_id, None)?;
+ tx.commit()?;
+ Ok(true)
+}
+
+/// Change password for the current live session: write PHC, clear
+/// must_change, revoke other sessions, and rotate this session's hashes.
+///
+/// # Errors
+/// Invalid state when the PHC changed, the user was disabled, or the
+/// current session was revoked/expired concurrently.
+pub fn change_password(
+ conn: &mut Connection,
+ user_id: UserId,
+ expected_password_hash: &str,
+ new_password_hash: &str,
+ session_id: uuid::Uuid,
+ new_session_hash: &[u8; TOKEN_HASH_LEN],
+ new_csrf_hash: &[u8; TOKEN_HASH_LEN],
+) -> StoreResult<bool> {
+ let tx = conn.transaction()?;
+ let current: Option<(Option<String>, Option<i64>)> = tx
+ .query_row(
+ "SELECT password_hash, disabled_at FROM users WHERE id = ?1",
+ params![user_id.as_bytes()],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .optional()?;
+ match current {
+ Some((Some(phc), None)) if phc == expected_password_hash => {}
+ _ => {
+ return Err(StoreError::InvalidState(
+ "credentials changed concurrently".into(),
+ ));
+ }
+ }
+ let now = Timestamp::now().as_microsecond();
+ let session_live: bool = tx.query_row(
+ "SELECT EXISTS(SELECT 1 FROM web_sessions \
+ WHERE id = ?1 AND user_id = ?2 AND revoked_at IS NULL AND expires_at > ?3)",
+ params![session_id.as_bytes(), user_id.as_bytes(), now],
+ |row| row.get(0),
+ )?;
+ if !session_live {
+ return Err(StoreError::InvalidState(
+ "session changed concurrently".into(),
+ ));
+ }
+ tx.execute(
+ "UPDATE users SET password_hash = ?1, must_change_password = 0 WHERE id = ?2",
+ params![new_password_hash, user_id.as_bytes()],
+ )?;
+ web_sessions::revoke_user_sessions(&tx, user_id, Some(session_id))?;
+ if !web_sessions::rotate_web_session_secrets(&tx, session_id, new_session_hash, new_csrf_hash)?
+ {
+ return Err(StoreError::InvalidState(
+ "session changed concurrently".into(),
+ ));
+ }
+ tx.commit()?;
+ Ok(true)
+}
+
+/// Recheck stored PHC/role/disabled then insert a session.
+///
+/// # Errors
+/// Invalid state when the row no longer matches the verified PHC.
+pub fn issue_web_session(
+ conn: &mut Connection,
+ user_id: UserId,
+ expected_password_hash: &str,
+ expected_role: UserRole,
+ expected_must_change: bool,
+ session_hash: &[u8; TOKEN_HASH_LEN],
+ csrf_hash: &[u8; TOKEN_HASH_LEN],
+) -> StoreResult<web_sessions::WebSession> {
+ let tx = conn.transaction()?;
+ let row = tx.query_row(
+ "SELECT password_hash, role, must_change_password, disabled_at FROM users WHERE id = ?1",
+ params![user_id.as_bytes()],
+ |r| {
+ Ok((
+ r.get::<_, Option<String>>(0)?,
+ r.get::<_, String>(1)?,
+ r.get::<_, bool>(2)?,
+ r.get::<_, Option<i64>>(3)?,
+ ))
+ },
+ );
+ let (phc, role, must_change, disabled_at) = match row {
+ Ok(v) => v,
+ Err(rusqlite::Error::QueryReturnedNoRows) => {
+ return Err(StoreError::NotFound("user".into()));
+ }
+ Err(e) => return Err(e.into()),
+ };
+ if disabled_at.is_some()
+ || phc.as_deref() != Some(expected_password_hash)
+ || UserRole::parse(&role)? != expected_role
+ || must_change != expected_must_change
+ {
+ return Err(StoreError::InvalidState(
+ "credentials no longer valid".into(),
+ ));
+ }
+ let session = web_sessions::insert_web_session(&tx, user_id, session_hash, csrf_hash)?;
+ tx.commit()?;
+ Ok(session)
+}
+
+/// Enable or disable human login. Disable revokes sessions. Never touches
+/// API credentials. Refuses to disable the last recoverable root.
+///
+/// # Errors
+/// Last-root invariant / not found / SQL.
+pub fn set_user_disabled(
+ conn: &mut Connection,
+ user_id: UserId,
+ disabled: bool,
+) -> StoreResult<bool> {
+ let tx = conn.transaction()?;
+ let Some(user) = find_user_by_id(&tx, user_id)? else {
+ return Ok(false);
+ };
+ if disabled && user.role == UserRole::Root && user.has_password && user.disabled_at.is_none() {
+ ensure_not_last_recoverable_root(&tx, user_id)?;
+ }
+ let now = Timestamp::now().as_microsecond();
+ let rows = if disabled {
+ tx.execute(
+ "UPDATE users SET disabled_at = COALESCE(disabled_at, ?1) WHERE id = ?2",
+ params![now, user_id.as_bytes()],
+ )?
+ } else {
+ tx.execute(
+ "UPDATE users SET disabled_at = NULL WHERE id = ?1",
+ params![user_id.as_bytes()],
+ )?
+ };
+ if disabled {
+ web_sessions::revoke_user_sessions(&tx, user_id, None)?;
+ }
+ tx.commit()?;
+ Ok(rows > 0)
+}
+
+/// Patch name/email/role with a last-root recheck.
///
/// # Errors
-/// Returns [`StoreError::Sql`] for any SQL failure.
+/// Last-root invariant / not found / duplicate email / SQL.
+pub fn patch_user(
+ conn: &mut Connection,
+ user_id: UserId,
+ name: Option<Option<String>>,
+ email: Option<Option<String>>,
+ role: Option<UserRole>,
+) -> StoreResult<bool> {
+ let tx = conn.transaction()?;
+ let Some(user) = find_user_by_id(&tx, user_id)? else {
+ return Ok(false);
+ };
+ if let Some(UserRole::User) = role
+ && user.role == UserRole::Root
+ && user.has_password
+ && user.disabled_at.is_none()
+ {
+ ensure_not_last_recoverable_root(&tx, user_id)?;
+ }
+ if let Some(name) = name {
+ tx.execute(
+ "UPDATE users SET name = ?1 WHERE id = ?2",
+ params![name, user_id.as_bytes()],
+ )?;
+ }
+ if let Some(email) = email {
+ tx.execute(
+ "UPDATE users SET email = ?1 WHERE id = ?2",
+ params![email, user_id.as_bytes()],
+ )
+ .map_err(map_unique_violation)?;
+ }
+ if let Some(role) = role {
+ tx.execute(
+ "UPDATE users SET role = ?1 WHERE id = ?2",
+ params![role.as_str(), user_id.as_bytes()],
+ )?;
+ }
+ tx.commit()?;
+ Ok(true)
+}
+
+/// Update `last_seen_at = now()`.
+///
+/// # Errors
+/// SQL failures.
pub fn touch_user_last_seen(conn: &Connection, id: UserId) -> StoreResult<bool> {
let now = Timestamp::now().as_microsecond();
let rows = conn.execute(
@@ -214,127 +492,174 @@ pub fn touch_user_last_seen(conn: &Connection, id: UserId) -> StoreResult<bool>
Ok(rows > 0)
}
-/// Look up the user that owns `token_hash` IF the token is currently
-/// active (`token_expired_at IS NULL`). Hot path for the auth
-/// middleware.
+/// Look up by username.
///
/// # Errors
-/// Returns [`StoreError::Sql`] for any SQL failure other than "no row
-/// matched" (which is reported as `Ok(None)`).
-pub fn find_active_user_by_token_hash(
- conn: &Connection,
- token_hash: &[u8; TOKEN_HASH_LEN],
-) -> StoreResult<Option<User>> {
+/// SQL failures.
+pub fn find_user_by_username(conn: &Connection, username: &str) -> StoreResult<Option<User>> {
conn.query_row(
- "SELECT id, username, name, email, created_at, last_seen_at, token_expired_at \
- FROM users WHERE token_hash = ?1 AND token_expired_at IS NULL",
- params![token_hash.as_slice()],
- row_to_user,
+ "SELECT id, username, name, email, created_at, last_seen_at, \
+ role, must_change_password, disabled_at, password_hash, token_expired_at \
+ FROM users WHERE username = ?1",
+ params![username],
+ |row| row_to_user(row, 0),
)
.optional()
.map_err(StoreError::from)
}
-/// Look up a user by exact-match username. Used by the admin endpoints
-/// (`expire`, `revive`, `rotate-token` all accept username on the wire).
+/// Look up by id, including disabled / password-less rows.
///
/// # Errors
-/// Returns [`StoreError::Sql`] for any SQL failure other than "no row
-/// matched" (`Ok(None)`).
-pub fn find_user_by_username(conn: &Connection, username: &str) -> StoreResult<Option<User>> {
+/// SQL failures.
+pub fn find_user_by_id(conn: &Connection, id: UserId) -> StoreResult<Option<User>> {
conn.query_row(
- "SELECT id, username, name, email, created_at, last_seen_at, token_expired_at \
- FROM users WHERE username = ?1",
- params![username],
- row_to_user,
+ "SELECT id, username, name, email, created_at, last_seen_at, \
+ role, must_change_password, disabled_at, password_hash, token_expired_at \
+ FROM users WHERE id = ?1",
+ params![id.as_bytes()],
+ |row| row_to_user(row, 0),
)
.optional()
.map_err(StoreError::from)
}
-/// Look up a user by id. **Returns even users whose token is expired**
-/// — needed by the attribution display path (we still want to render
-/// "alice wrote this last month" after alice's token has been expired).
+/// Login lookup including the PHC.
///
/// # Errors
-/// Returns [`StoreError::Sql`] for any SQL failure other than "no row
-/// matched" (`Ok(None)`).
-pub fn find_user_by_id(conn: &Connection, id: UserId) -> StoreResult<Option<User>> {
+/// SQL failures.
+pub fn find_login_user_by_username(
+ conn: &Connection,
+ username: &str,
+) -> StoreResult<Option<LoginUser>> {
conn.query_row(
- "SELECT id, username, name, email, created_at, last_seen_at, token_expired_at \
- FROM users WHERE id = ?1",
- params![id.as_bytes()],
- row_to_user,
+ "SELECT id, username, name, email, created_at, last_seen_at, \
+ role, must_change_password, disabled_at, password_hash, token_expired_at \
+ FROM users WHERE username = ?1",
+ params![username],
+ |row| {
+ let password_hash: Option<String> = row.get(9)?;
+ Ok(LoginUser {
+ user: row_to_user(row, 0)?,
+ password_hash,
+ })
+ },
)
.optional()
.map_err(StoreError::from)
}
-/// All users, ordered by `created_at` ascending. Used by
-/// `GET /admin/users` / `ai-memory user list`. Includes users whose
-/// token is expired (the CLI surfaces the active/expired flag from
-/// `token_expired_at`).
+/// All users, created_at ascending.
///
/// # Errors
-/// Returns [`StoreError::Sql`] for any SQL failure.
+/// SQL failures.
pub fn list_users(conn: &Connection) -> StoreResult<Vec<User>> {
let mut stmt = conn.prepare(
- "SELECT id, username, name, email, created_at, last_seen_at, token_expired_at \
+ "SELECT id, username, name, email, created_at, last_seen_at, \
+ role, must_change_password, disabled_at, password_hash, token_expired_at \
FROM users ORDER BY created_at ASC",
)?;
let rows = stmt
- .query_map([], row_to_user)?
+ .query_map([], |row| row_to_user(row, 0))?
.collect::<Result<Vec<_>, _>>()?;
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.
+/// Whether any user row exists.
+///
+/// # Errors
+/// SQL failures.
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 ────────────────────────────────────────────────────────
+/// Whether bootstrap has been marked complete.
+///
+/// # Errors
+/// SQL failures.
+pub fn bootstrap_completed(conn: &Connection) -> StoreResult<bool> {
+ conn.query_row(
+ "SELECT bootstrap_completed FROM human_auth_state WHERE id = 1",
+ [],
+ |row| {
+ let v: i64 = row.get(0)?;
+ Ok(v != 0)
+ },
+ )
+ .map_err(StoreError::from)
+}
+
+/// Persist the bootstrap marker.
+///
+/// # Errors
+/// SQL failures.
+pub fn set_bootstrap_completed(conn: &Connection, completed: bool) -> StoreResult<()> {
+ conn.execute(
+ "UPDATE human_auth_state SET bootstrap_completed = ?1 WHERE id = 1",
+ params![i64::from(completed)],
+ )?;
+ Ok(())
+}
-fn row_to_user(row: &rusqlite::Row<'_>) -> rusqlite::Result<User> {
- let id_bytes: Vec<u8> = row.get(0)?;
- let id = UserId::from_slice(&id_bytes).map_err(|e| {
- rusqlite::Error::FromSqlConversionFailure(
- 0,
- rusqlite::types::Type::Blob,
- Box::new(std::io::Error::other(e.to_string())),
- )
- })?;
- Ok(User {
- id,
- username: row.get(1)?,
- name: row.get(2)?,
- email: row.get(3)?,
- created_at: row.get(4)?,
- last_seen_at: row.get(5)?,
- token_expired_at: row.get(6)?,
- })
+/// True when any user has a password hash.
+///
+/// # Errors
+/// SQL failures.
+pub fn any_password_hash(conn: &Connection) -> StoreResult<bool> {
+ conn.query_row(
+ "SELECT EXISTS(SELECT 1 FROM users WHERE password_hash IS NOT NULL)",
+ [],
+ |row| row.get(0),
+ )
+ .map_err(StoreError::from)
+}
+
+/// Recoverable roots: `role=root AND password_hash IS NOT NULL AND disabled_at IS NULL`.
+///
+/// # Errors
+/// SQL failures.
+pub fn count_recoverable_roots(conn: &Connection) -> StoreResult<i64> {
+ conn.query_row(
+ "SELECT COUNT(*) FROM users \
+ WHERE role = 'root' AND password_hash IS NOT NULL AND disabled_at IS NULL",
+ [],
+ |row| row.get(0),
+ )
+ .map_err(StoreError::from)
}
-/// Map SQLite UNIQUE-violation errors to a typed `Duplicate`. Anything
-/// else passes through verbatim. The CLI / admin endpoint relies on
-/// this to render a readable "username already taken" message.
-fn map_unique_violation(e: rusqlite::Error) -> StoreError {
+fn ensure_not_last_recoverable_root(conn: &Connection, user_id: UserId) -> StoreResult<()> {
+ let count = count_recoverable_roots(conn)?;
+ if count <= 1 {
+ let is_recoverable: bool = conn.query_row(
+ "SELECT EXISTS(SELECT 1 FROM users WHERE id = ?1 \
+ AND role = 'root' AND password_hash IS NOT NULL AND disabled_at IS NULL)",
+ params![user_id.as_bytes()],
+ |row| row.get(0),
+ )?;
+ if is_recoverable {
+ return Err(StoreError::InvalidState(
+ "cannot demote or disable the last recoverable root".into(),
+ ));
+ }
+ }
+ Ok(())
+}
+
+/// Map SQLite UNIQUE-violation errors to a typed `Duplicate`.
+pub(crate) fn map_unique_violation(e: rusqlite::Error) -> StoreError {
if let rusqlite::Error::SqliteFailure(sqlite_err, msg) = &e
&& sqlite_err.code == rusqlite::ErrorCode::ConstraintViolation
{
let text = msg.clone().unwrap_or_else(|| sqlite_err.to_string());
- // SQLite reports `UNIQUE constraint failed: users.username`
- // (or `users.email`); the substring is stable across versions.
if text.contains("users.username") {
return StoreError::Duplicate("username already taken".into());
}
if text.contains("users.email") {
return StoreError::Duplicate("email already in use".into());
}
- if text.contains("users.token_hash") {
+ if text.contains("token_hash") {
return StoreError::Duplicate("token hash collision".into());
}
return StoreError::Duplicate(text);
@@ -342,9 +667,46 @@ fn map_unique_violation(e: rusqlite::Error) -> StoreError {
StoreError::from(e)
}
+/// Decode a user row starting at `offset`. Relative columns 9 and 10 are
+/// `password_hash` and the deprecated `token_expired_at`.
+pub(crate) fn row_to_user(row: &rusqlite::Row<'_>, offset: usize) -> rusqlite::Result<User> {
+ let id_bytes: Vec<u8> = row.get(offset)?;
+ let id = UserId::from_slice(&id_bytes).map_err(|e| {
+ rusqlite::Error::FromSqlConversionFailure(
+ offset,
+ rusqlite::types::Type::Blob,
+ Box::new(std::io::Error::other(e.to_string())),
+ )
+ })?;
+ let role_s: String = row.get(offset + 6)?;
+ let role = UserRole::parse(&role_s).map_err(|e| {
+ rusqlite::Error::FromSqlConversionFailure(
+ offset + 6,
+ rusqlite::types::Type::Text,
+ Box::new(std::io::Error::other(e.to_string())),
+ )
+ })?;
+ let must: i64 = row.get(offset + 7)?;
+ let password_hash: Option<String> = row.get(offset + 9)?;
+ Ok(User {
+ id,
+ username: row.get(offset + 1)?,
+ name: row.get(offset + 2)?,
+ email: row.get(offset + 3)?,
+ created_at: row.get(offset + 4)?,
+ last_seen_at: row.get(offset + 5)?,
+ token_expired_at: row.get(offset + 10)?,
+ role,
+ must_change_password: must != 0,
+ disabled_at: row.get(offset + 8)?,
+ has_password: password_hash.is_some(),
+ })
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ use crate::api_credentials;
use ai_memory_core::NewUser;
use rusqlite::Connection;
@@ -355,11 +717,7 @@ mod tests {
conn
}
- fn pepper() -> TokenPepper {
- TokenPepper::new("test-pepper-1234567890abcdef")
- }
-
- fn sample_new_user(name: &str) -> NewUser {
+ fn sample(name: &str) -> NewUser {
NewUser {
username: name.to_string(),
name: None,
@@ -367,297 +725,439 @@ mod tests {
}
}
- #[test]
- fn hash_token_is_deterministic_and_isolates_pepper() {
- let p = pepper();
- let h1 = hash_token("hunter2", &p);
- let h2 = hash_token("hunter2", &p);
- assert_eq!(h1, h2, "same input → same hash");
-
- let p2 = TokenPepper::new("different-pepper");
- let h3 = hash_token("hunter2", &p2);
- assert_ne!(h1, h3, "different pepper → different hash");
-
- let h4 = hash_token("hunter3", &p);
- assert_ne!(h1, h4, "different token → different hash");
- }
-
- #[test]
- fn hash_token_separator_blocks_ambiguous_concatenation() {
- // Without the `:` separator, ("ab", "cd") and ("abc", "d") would
- // hash the same input. The separator prevents that.
- let p1 = TokenPepper::new("cd");
- let p2 = TokenPepper::new("d");
- let h1 = hash_token("ab", &p1);
- let h2 = hash_token("abc", &p2);
- assert_ne!(h1, h2);
+ fn schema_version(conn: &Connection) -> i64 {
+ conn.query_row(
+ "SELECT MAX(version) FROM refinery_schema_history",
+ [],
+ |row| row.get(0),
+ )
+ .unwrap()
}
- #[test]
- fn generate_token_emits_url_safe_base64_of_expected_length() {
- let tok = generate_token().unwrap();
- // URL-safe-no-pad of 32 bytes is 43 chars (`(32*8+5)/6 = 43`).
- assert_eq!(tok.len(), 43);
+ fn assert_foreign_keys_clean(conn: &Connection) {
+ let mut stmt = conn.prepare("PRAGMA foreign_key_check").unwrap();
+ let violations: Vec<(String, i64, String, i64)> = stmt
+ .query_map([], |row| {
+ Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
+ })
+ .unwrap()
+ .collect::<Result<Vec<_>, _>>()
+ .unwrap();
assert!(
- tok.chars()
- .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
+ violations.is_empty(),
+ "PRAGMA foreign_key_check: {violations:?}"
);
}
#[test]
- fn generate_token_is_unique_per_call() {
- let a = generate_token().unwrap();
- let b = generate_token().unwrap();
- assert_ne!(a, b);
+ fn hash_token_is_deterministic_and_isolates_pepper() {
+ let p = TokenPepper::new("test-pepper-1234567890abcdef");
+ let h1 = hash_token("hunter2", &p);
+ let h2 = hash_token("hunter2", &p);
+ assert_eq!(h1, h2);
+ let p2 = TokenPepper::new("different-pepper");
+ assert_ne!(h1, hash_token("hunter2", &p2));
+ assert_ne!(h1, hash_token("hunter3", &p));
}
#[test]
- fn insert_then_find_by_username_round_trip() {
+ fn insert_human_user_has_no_api_credential() {
let conn = fresh_conn();
- let p = pepper();
- let hash = hash_token("the-token", &p);
-
- let mut nu = sample_new_user("alice");
+ let mut nu = sample("alice");
nu.validate().unwrap();
- let id = insert_user(&conn, &nu, &hash).unwrap();
-
+ let id = insert_human_user(&conn, &nu, UserRole::User, Some("phc"), true).unwrap();
let found = find_user_by_username(&conn, "alice").unwrap().unwrap();
assert_eq!(found.id, id);
- assert_eq!(found.username, "alice");
- assert!(found.is_token_active());
+ assert!(found.has_password);
+ assert!(found.must_change_password);
+ assert_eq!(found.role, UserRole::User);
+ assert!(
+ api_credentials::list_api_credentials_for_user(&conn, id)
+ .unwrap()
+ .is_empty()
+ );
}
#[test]
- fn insert_rejects_duplicate_username() {
- let conn = fresh_conn();
- let p = pepper();
- let mut nu = sample_new_user("alice");
+ fn last_recoverable_root_cannot_be_disabled_or_demoted() {
+ let mut conn = fresh_conn();
+ let mut nu = sample("root");
nu.validate().unwrap();
-
- let h1 = hash_token("token-a", &p);
- let h2 = hash_token("token-b", &p);
- insert_user(&conn, &nu, &h1).unwrap();
- let err = insert_user(&conn, &nu, &h2).unwrap_err();
+ let id = insert_human_user(&conn, &nu, UserRole::Root, Some("phc"), false).unwrap();
+ let err = set_user_disabled(&mut conn, id, true).unwrap_err();
assert!(
- matches!(&err, StoreError::Duplicate(m) if m.contains("username")),
- "expected Duplicate(username), got {err:?}"
+ matches!(&err, StoreError::InvalidState(m) if m.contains("last recoverable root")),
+ "{err:?}"
);
+ let err = patch_user(&mut conn, id, None, None, Some(UserRole::User)).unwrap_err();
+ assert!(matches!(err, StoreError::InvalidState(_)));
}
#[test]
- fn insert_rejects_duplicate_email_case_insensitive() {
- let conn = fresh_conn();
- let p = pepper();
- let mut a = NewUser {
- username: "alice".into(),
- name: None,
- email: Some("[email protected]".into()),
- };
+ fn second_root_allows_demoting_the_first() {
+ let mut conn = fresh_conn();
+ let mut a = sample("root");
a.validate().unwrap();
- insert_user(&conn, &a, &hash_token("ta", &p)).unwrap();
-
- let mut b = NewUser {
- username: "bob".into(),
- name: None,
- email: Some("[email protected]".into()),
- };
+ let first = insert_human_user(&conn, &a, UserRole::Root, Some("phc"), false).unwrap();
+ let mut b = sample("boss");
b.validate().unwrap();
- // Both lowercased to `[email protected]` — UNIQUE COLLATE NOCASE
- // catches it even without the validation lowercase.
- let err = insert_user(&conn, &b, &hash_token("tb", &p)).unwrap_err();
- assert!(matches!(&err, StoreError::Duplicate(m) if m.contains("email")));
+ insert_human_user(&conn, &b, UserRole::Root, Some("phc2"), false).unwrap();
+ assert!(patch_user(&mut conn, first, None, None, Some(UserRole::User)).unwrap());
+ assert_eq!(
+ find_user_by_id(&conn, first).unwrap().unwrap().role,
+ UserRole::User
+ );
}
#[test]
- fn find_active_user_by_token_hash_returns_only_active() {
- let conn = fresh_conn();
- let p = pepper();
- let token = "live-token";
- let hash = hash_token(token, &p);
- let mut nu = sample_new_user("alice");
- nu.validate().unwrap();
- let id = insert_user(&conn, &nu, &hash).unwrap();
-
- // Active → returns Some.
- let found = find_active_user_by_token_hash(&conn, &hash).unwrap();
- assert_eq!(found.unwrap().id, id);
+ fn recovery_creates_root_and_marks_bootstrap() {
+ let mut conn = fresh_conn();
+ assert!(!bootstrap_completed(&conn).unwrap());
+ let id = recover_root(&mut conn, "root", None, None, "phc").unwrap();
+ let user = find_user_by_id(&conn, id).unwrap().unwrap();
+ assert_eq!(user.role, UserRole::Root);
+ assert!(user.has_password);
+ assert!(!user.must_change_password);
+ assert!(bootstrap_completed(&conn).unwrap());
+ }
- // After expire → returns None.
- let updated = expire_user_token(&conn, id).unwrap();
- assert!(updated);
- let found = find_active_user_by_token_hash(&conn, &hash).unwrap();
+ #[test]
+ fn bootstrap_root_is_one_shot() {
+ let mut conn = fresh_conn();
+ bootstrap_root(&mut conn, "root", None, None, "phc-one").unwrap();
+ let err = bootstrap_root(&mut conn, "root", None, None, "phc-two").unwrap_err();
assert!(
- found.is_none(),
- "expired user must NOT come back from active-token lookup"
+ matches!(&err, StoreError::InvalidState(m) if m.contains("already completed")),
+ "{err:?}"
);
+ let login = find_login_user_by_username(&conn, "root").unwrap().unwrap();
+ assert_eq!(login.password_hash.as_deref(), Some("phc-one"));
+ assert!(login.user.must_change_password);
}
#[test]
- fn find_user_by_id_returns_even_expired_users() {
- // Critical for attribution: a page authored by alice last
- // month must still display "alice" today even after alice's
- // token has been expired.
- let conn = fresh_conn();
- let p = pepper();
- let mut nu = sample_new_user("alice");
+ fn token_only_row_is_not_a_recoverable_root() {
+ let mut conn = fresh_conn();
+ let mut nu = sample("legacy");
nu.validate().unwrap();
- let id = insert_user(&conn, &nu, &hash_token("t", &p)).unwrap();
- expire_user_token(&conn, id).unwrap();
-
+ let id = insert_human_user(&conn, &nu, UserRole::Root, None, false).unwrap();
let found = find_user_by_id(&conn, id).unwrap().unwrap();
- assert_eq!(found.id, id);
- assert!(found.token_expired_at.is_some());
- assert!(!found.is_token_active());
+ assert!(!found.has_password);
+ assert_eq!(count_recoverable_roots(&conn).unwrap(), 0);
+ assert!(set_user_disabled(&mut conn, id, true).unwrap());
}
#[test]
- fn expire_is_idempotent_preserving_original_timestamp() {
- let conn = fresh_conn();
- let p = pepper();
- let mut nu = sample_new_user("alice");
+ fn password_change_rejects_a_revoked_current_session_without_updating_phc() {
+ let mut conn = fresh_conn();
+ let mut nu = sample("alice");
nu.validate().unwrap();
- let id = insert_user(&conn, &nu, &hash_token("t", &p)).unwrap();
+ let id = insert_human_user(&conn, &nu, UserRole::User, Some("old-phc"), true).unwrap();
+ let session =
+ web_sessions::insert_web_session(&conn, id, &[1; TOKEN_HASH_LEN], &[2; TOKEN_HASH_LEN])
+ .unwrap();
+ web_sessions::revoke_session_by_hash(&conn, &[1; TOKEN_HASH_LEN]).unwrap();
- expire_user_token(&conn, id).unwrap();
- let first = find_user_by_id(&conn, id)
- .unwrap()
- .unwrap()
- .token_expired_at;
- assert!(first.is_some());
-
- // Second expire call must not move the timestamp forward —
- // COALESCE in the UPDATE keeps the original.
- expire_user_token(&conn, id).unwrap();
- let second = find_user_by_id(&conn, id)
- .unwrap()
+ assert!(
+ change_password(
+ &mut conn,
+ id,
+ "old-phc",
+ "new-phc",
+ session.id,
+ &[3; TOKEN_HASH_LEN],
+ &[4; TOKEN_HASH_LEN],
+ )
+ .is_err()
+ );
+ let login = find_login_user_by_username(&conn, "alice")
.unwrap()
- .token_expired_at;
- assert_eq!(first, second, "expire must be idempotent");
+ .unwrap();
+ assert_eq!(login.password_hash.as_deref(), Some("old-phc"));
+ assert!(login.user.must_change_password);
}
#[test]
- fn revive_clears_expiration() {
- let conn = fresh_conn();
- let p = pepper();
- let mut nu = sample_new_user("alice");
+ fn session_issuance_rechecks_role_and_must_change_state() {
+ let mut conn = fresh_conn();
+ let mut nu = sample("alice");
nu.validate().unwrap();
- let id = insert_user(&conn, &nu, &hash_token("t", &p)).unwrap();
+ let id = insert_human_user(&conn, &nu, UserRole::User, Some("phc"), true).unwrap();
- expire_user_token(&conn, id).unwrap();
+ conn.execute(
+ "UPDATE users SET role = 'root' WHERE id = ?1",
+ params![id.as_bytes()],
+ )
+ .unwrap();
assert!(
- !find_user_by_id(&conn, id)
- .unwrap()
- .unwrap()
- .is_token_active()
+ issue_web_session(
+ &mut conn,
+ id,
+ "phc",
+ UserRole::User,
+ true,
+ &[1; TOKEN_HASH_LEN],
+ &[2; TOKEN_HASH_LEN],
+ )
+ .is_err()
);
- revive_user_token(&conn, id).unwrap();
+ conn.execute(
+ "UPDATE users SET role = 'user', must_change_password = 0 WHERE id = ?1",
+ params![id.as_bytes()],
+ )
+ .unwrap();
assert!(
- find_user_by_id(&conn, id)
- .unwrap()
- .unwrap()
- .is_token_active()
+ issue_web_session(
+ &mut conn,
+ id,
+ "phc",
+ UserRole::User,
+ true,
+ &[3; TOKEN_HASH_LEN],
+ &[4; TOKEN_HASH_LEN],
+ )
+ .is_err()
);
- }
-
- #[test]
- fn rotate_token_issues_new_hash_and_revives() {
- let conn = fresh_conn();
- let p = pepper();
- let mut nu = sample_new_user("alice");
- nu.validate().unwrap();
- let h_old = hash_token("old-token", &p);
- let id = insert_user(&conn, &nu, &h_old).unwrap();
- expire_user_token(&conn, id).unwrap();
-
- let h_new = hash_token("new-token", &p);
- let updated = rotate_user_token(&conn, id, &h_new).unwrap();
- assert!(updated);
-
- // Old hash no longer authenticates.
assert!(
- find_active_user_by_token_hash(&conn, &h_old)
- .unwrap()
- .is_none()
+ issue_web_session(
+ &mut conn,
+ id,
+ "phc",
+ UserRole::User,
+ false,
+ &[5; TOKEN_HASH_LEN],
+ &[6; TOKEN_HASH_LEN],
+ )
+ .is_ok()
);
- // New hash does — and the user is implicitly revived.
- let found = find_active_user_by_token_hash(&conn, &h_new).unwrap();
- assert_eq!(found.unwrap().id, id);
}
#[test]
- fn touch_last_seen_records_timestamp() {
- let conn = fresh_conn();
- let p = pepper();
- let mut nu = sample_new_user("alice");
- nu.validate().unwrap();
- let id = insert_user(&conn, &nu, &hash_token("t", &p)).unwrap();
- assert!(
- find_user_by_id(&conn, id)
- .unwrap()
- .unwrap()
- .last_seen_at
- .is_none(),
- "fresh users have no last_seen_at"
- );
-
- touch_user_last_seen(&conn, id).unwrap();
- assert!(
- find_user_by_id(&conn, id)
- .unwrap()
- .unwrap()
- .last_seen_at
- .is_some(),
- "touch must populate last_seen_at"
- );
+ fn human_auth_v54_migrates_token_only_user() {
+ let mut conn = Connection::open_in_memory().unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ crate::migrations::run_to(&mut conn, 53).unwrap();
+ let id = UserId::new();
+ let hash = [7u8; 32];
+ conn.execute(
+ "INSERT INTO users (id, username, name, email, token_hash, created_at) \
+ VALUES (?1, 'alice', NULL, NULL, ?2, 1)",
+ params![id.as_bytes(), hash.as_slice()],
+ )
+ .unwrap();
+ crate::migrations::run_to(&mut conn, 54).unwrap();
+ let (username, role, token, bootstrap): (String, String, Vec<u8>, i64) = conn
+ .query_row(
+ "SELECT u.username, u.role, u.token_hash, s.bootstrap_completed \
+ FROM users u, human_auth_state s WHERE u.username = 'alice'",
+ [],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
+ )
+ .unwrap();
+ assert_eq!(username, "alice");
+ assert_eq!(role, "user");
+ assert_eq!(token, hash);
+ assert_eq!(bootstrap, 0);
+ crate::migrations::run(&mut conn).unwrap();
+ let user = find_user_by_id(&conn, id).unwrap().unwrap();
+ assert!(!user.has_password);
+ assert_eq!(user.username, "alice");
}
#[test]
- fn list_users_orders_by_created_at_ascending() {
- let conn = fresh_conn();
- let p = pepper();
- for name in ["alice", "bob", "carol"] {
- let mut nu = sample_new_user(name);
- nu.validate().unwrap();
- insert_user(&conn, &nu, &hash_token(name, &p)).unwrap();
- }
- let users = list_users(&conn).unwrap();
- assert_eq!(users.len(), 3);
- let usernames: Vec<_> = users.iter().map(|u| u.username.as_str()).collect();
- assert_eq!(usernames, vec!["alice", "bob", "carol"]);
+ fn human_auth_v54_empty_store_leaves_bootstrap_incomplete() {
+ let mut conn = Connection::open_in_memory().unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ crate::migrations::run_to(&mut conn, 53).unwrap();
+ // SQLite ignores PRAGMA foreign_keys inside refinery's transaction;
+ // Store::open disables FKs around migrations for the same reason.
+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();
+ crate::migrations::run_to(&mut conn, 54).unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ assert_eq!(schema_version(&conn), 54);
+ assert!(!users_exist(&conn).unwrap());
+ assert!(!bootstrap_completed(&conn).unwrap());
+ assert_foreign_keys_clean(&conn);
+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();
+ crate::migrations::run(&mut conn).unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ assert!(!bootstrap_completed(&conn).unwrap());
+ assert!(!users_exist(&conn).unwrap());
+ assert_foreign_keys_clean(&conn);
}
#[test]
- fn users_exist_counts_expired_rows() {
- let conn = fresh_conn();
- assert!(!users_exist(&conn).unwrap());
+ fn human_auth_v54_rejects_orphaned_page_author_ids() {
+ let mut conn = Connection::open_in_memory().unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ crate::migrations::run_to(&mut conn, 53).unwrap();
+ conn.pragma_update(None, "foreign_keys", "OFF").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());
+ let workspace = [1u8; 16];
+ let project = [2u8; 16];
+ let page = [3u8; 16];
+ let missing_author = UserId::new();
+ conn.execute(
+ "INSERT INTO workspaces (id, name, created_at) VALUES (?1, 'ws', 1)",
+ params![workspace.as_slice()],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO projects (id, workspace_id, name, created_at) \
+ VALUES (?1, ?2, 'p', 1)",
+ params![project.as_slice(), workspace.as_slice()],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO pages \
+ (id, workspace_id, project_id, path, title, tier, body, body_sha256, \
+ frontmatter_json, is_latest, pinned, created_at, updated_at, author_id) \
+ VALUES (?1, ?2, ?3, 'notes/orphan.md', 'title', 'semantic', 'body', ?4, '{}', 1, 0, 1, 1, ?5)",
+ params![
+ page.as_slice(),
+ workspace.as_slice(),
+ project.as_slice(),
+ [0u8; 32].as_slice(),
+ missing_author.as_bytes(),
+ ],
+ )
+ .unwrap();
- expire_user_token(&conn, id).unwrap();
- assert!(users_exist(&conn).unwrap());
+ let error = crate::migrations::run_to(&mut conn, 54)
+ .expect_err("V52 must abort rather than preserve an orphaned page author");
+ assert!(
+ error.to_string().contains("CHECK constraint failed"),
+ "unexpected V52 guard error: {error}"
+ );
+ assert_eq!(schema_version(&conn), 53, "failed V54 must roll back");
}
#[test]
- fn rotate_returns_false_for_unknown_user() {
- let conn = fresh_conn();
- let p = pepper();
- let ghost = UserId::new();
- let updated = rotate_user_token(&conn, ghost, &hash_token("x", &p)).unwrap();
- assert!(!updated);
+ fn human_auth_v54_ignores_unrelated_preexisting_foreign_key_violations() {
+ let mut conn = Connection::open_in_memory().unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ crate::migrations::run_to(&mut conn, 53).unwrap();
+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();
+ conn.execute(
+ "INSERT INTO projects (id, workspace_id, name, created_at) \
+ VALUES (?1, ?2, 'preexisting-orphan', 1)",
+ params![[1u8; 16].as_slice(), [2u8; 16].as_slice()],
+ )
+ .unwrap();
+
+ crate::migrations::run_to(&mut conn, 54)
+ .expect("V52 must guard only references affected by its users-table rebuild");
+ assert_eq!(schema_version(&conn), 54);
}
#[test]
- fn constant_time_eq_matches_plain_eq() {
- let a = [1u8, 2, 3, 4];
- let b = [1u8, 2, 3, 4];
- let c = [1u8, 2, 3, 5];
- assert!(constant_time_eq(&a, &b));
- assert!(!constant_time_eq(&a, &c));
- assert!(!constant_time_eq(&a, &[1u8, 2, 3]));
+ fn human_auth_v54_preserves_page_and_audit_author_ids() {
+ let mut conn = Connection::open_in_memory().unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ crate::migrations::run_to(&mut conn, 53).unwrap();
+ let author = UserId::new();
+ let hash = [9u8; 32];
+ conn.execute(
+ "INSERT INTO users (id, username, name, email, token_hash, created_at) \
+ VALUES (?1, 'alice', NULL, NULL, ?2, 1)",
+ params![author.as_bytes(), hash.as_slice()],
+ )
+ .unwrap();
+ let workspace = [1u8; 16];
+ let project = [2u8; 16];
+ let page = [3u8; 16];
+ let body_hash = [0u8; 32];
+ conn.execute(
+ "INSERT INTO workspaces (id, name, created_at) VALUES (?1, 'ws', 1)",
+ params![workspace.as_slice()],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO projects (id, workspace_id, name, created_at) \
+ VALUES (?1, ?2, 'p', 1)",
+ params![project.as_slice(), workspace.as_slice()],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO pages \
+ (id, workspace_id, project_id, path, title, tier, body, body_sha256, \
+ frontmatter_json, is_latest, pinned, created_at, updated_at, author_id) \
+ VALUES (?1, ?2, ?3, 'notes/a.md', 'title', 'semantic', 'body', ?4, '{}', 1, 0, 1, 1, ?5)",
+ params![
+ page.as_slice(),
+ workspace.as_slice(),
+ project.as_slice(),
+ body_hash.as_slice(),
+ author.as_bytes(),
+ ],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO audit_log (at, op, workspace_id, project_id, page_id, detail, author_id) \
+ VALUES (1, 'upsert', ?1, ?2, ?3, '{}', ?4)",
+ params![
+ workspace.as_slice(),
+ project.as_slice(),
+ page.as_slice(),
+ author.as_bytes(),
+ ],
+ )
+ .unwrap();
+
+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();
+ crate::migrations::run_to(&mut conn, 54).unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ assert_eq!(schema_version(&conn), 54);
+ let (user_id, role): (Vec<u8>, String) = conn
+ .query_row(
+ "SELECT id, role FROM users WHERE username = 'alice'",
+ [],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .unwrap();
+ assert_eq!(user_id, author.as_bytes());
+ assert_eq!(role, "user");
+ let page_author: Vec<u8> = conn
+ .query_row(
+ "SELECT author_id FROM pages WHERE id = ?1",
+ params![page.as_slice()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ let audit_author: Vec<u8> = conn
+ .query_row(
+ "SELECT author_id FROM audit_log WHERE page_id = ?1",
+ params![page.as_slice()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(page_author, author.as_bytes());
+ assert_eq!(audit_author, author.as_bytes());
+ assert_foreign_keys_clean(&conn);
+
+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();
+ crate::migrations::run(&mut conn).unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ let page_author: Vec<u8> = conn
+ .query_row(
+ "SELECT author_id FROM pages WHERE id = ?1",
+ params![page.as_slice()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ let audit_author: Vec<u8> = conn
+ .query_row(
+ "SELECT author_id FROM audit_log WHERE page_id = ?1",
+ params![page.as_slice()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(page_author, author.as_bytes());
+ assert_eq!(audit_author, author.as_bytes());
+ let user = find_user_by_id(&conn, author).unwrap().unwrap();
+ assert_eq!(user.id, author);
+ assert_eq!(user.username, "alice");
+ assert_foreign_keys_clean(&conn);
}
}
diff --git a/crates/ai-memory-store/src/web_sessions.rs b/crates/ai-memory-store/src/web_sessions.rs
new file mode 100644
index 00000000..f00098d7
--- /dev/null
+++ b/crates/ai-memory-store/src/web_sessions.rs
@@ -0,0 +1,264 @@
+//! Web sessions: SHA-256 of `ams_…` secrets (no pepper) plus CSRF hashes.
+
+use ai_memory_core::{SESSION_SECRET_PREFIX, User, UserId};
+use base64::Engine;
+use base64::engine::general_purpose::URL_SAFE_NO_PAD;
+use jiff::Timestamp;
+use rusqlite::{Connection, OptionalExtension, params};
+use sha2::{Digest, Sha256};
+use uuid::Uuid;
+
+use crate::error::{StoreError, StoreResult};
+use crate::users::{TOKEN_HASH_LEN, TOKEN_RAW_LEN, row_to_user};
+
+/// Absolute session lifetime (seven days).
+pub const SESSION_TTL_MICROS: i64 = 7 * 24 * 60 * 60 * 1_000_000;
+/// Skip `last_used_at` writes more often than once per minute.
+pub const SESSION_TOUCH_MIN_MICROS: i64 = 60 * 1_000_000;
+
+/// SHA-256 of a session secret or CSRF value. No pepper — the secret is
+/// already 256 bits of CSPRNG with a reserved prefix.
+#[must_use]
+pub fn hash_session_secret(secret: &str) -> [u8; TOKEN_HASH_LEN] {
+ Sha256::digest(secret.as_bytes()).into()
+}
+
+/// `ams_` + 43 URL-safe characters.
+///
+/// # Errors
+/// [`StoreError::Os`] when the CSPRNG fails.
+pub fn generate_session_secret() -> StoreResult<String> {
+ let mut bytes = [0u8; TOKEN_RAW_LEN];
+ getrandom::fill(&mut bytes)
+ .map_err(|e| StoreError::Os(format!("os csprng failed during session secret: {e}")))?;
+ Ok(format!(
+ "{SESSION_SECRET_PREFIX}{}",
+ URL_SAFE_NO_PAD.encode(bytes)
+ ))
+}
+
+/// 32 URL-safe characters for the readable CSRF cookie.
+///
+/// # Errors
+/// [`StoreError::Os`] when the CSPRNG fails.
+pub fn generate_csrf_secret() -> StoreResult<String> {
+ let mut bytes = [0u8; 24];
+ getrandom::fill(&mut bytes)
+ .map_err(|e| StoreError::Os(format!("os csprng failed during csrf secret: {e}")))?;
+ Ok(URL_SAFE_NO_PAD.encode(bytes))
+}
+
+/// Issued session row after a successful login/password rotation.
+#[derive(Debug, Clone)]
+pub struct WebSession {
+ /// Session row id.
+ pub id: Uuid,
+ /// Owning user.
+ pub user_id: UserId,
+ /// Absolute expiry (microseconds since epoch).
+ pub expires_at: i64,
+}
+
+/// Live session plus the owning user, used by `/auth/me` and dual-auth.
+#[derive(Debug, Clone)]
+pub struct LiveWebSession {
+ /// Session row id.
+ pub id: Uuid,
+ /// CSRF hash stored on the row.
+ pub csrf_hash: [u8; TOKEN_HASH_LEN],
+ /// Absolute expiry.
+ pub expires_at: i64,
+ /// Last persisted touch.
+ pub last_used_at: i64,
+ /// Owning user.
+ pub user: User,
+}
+
+/// Insert a new session. Caller hashed the secret and CSRF off-thread.
+///
+/// # Errors
+/// SQL / unique-hash collisions.
+pub fn insert_web_session(
+ conn: &Connection,
+ user_id: UserId,
+ session_hash: &[u8; TOKEN_HASH_LEN],
+ csrf_hash: &[u8; TOKEN_HASH_LEN],
+) -> StoreResult<WebSession> {
+ let id = Uuid::now_v7();
+ let created_at = Timestamp::now().as_microsecond();
+ let expires_at = created_at.saturating_add(SESSION_TTL_MICROS);
+ conn.execute(
+ "INSERT INTO web_sessions \
+ (id, session_hash, user_id, csrf_hash, created_at, last_used_at, expires_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?5, ?6)",
+ params![
+ id.as_bytes().as_slice(),
+ session_hash.as_slice(),
+ user_id.as_bytes(),
+ csrf_hash.as_slice(),
+ created_at,
+ expires_at,
+ ],
+ )?;
+ Ok(WebSession {
+ id,
+ user_id,
+ expires_at,
+ })
+}
+
+/// Replace the current session's secret and CSRF hashes (password change).
+///
+/// # Errors
+/// SQL failures.
+pub fn rotate_web_session_secrets(
+ conn: &Connection,
+ session_id: Uuid,
+ session_hash: &[u8; TOKEN_HASH_LEN],
+ csrf_hash: &[u8; TOKEN_HASH_LEN],
+) -> StoreResult<bool> {
+ let rows = conn.execute(
+ "UPDATE web_sessions SET session_hash = ?1, csrf_hash = ?2 \
+ WHERE id = ?3 AND revoked_at IS NULL",
+ params![
+ session_hash.as_slice(),
+ csrf_hash.as_slice(),
+ session_id.as_bytes().as_slice(),
+ ],
+ )?;
+ Ok(rows > 0)
+}
+
+/// Revoke every session for `user_id`, optionally keeping `except`.
+///
+/// # Errors
+/// SQL failures.
+pub fn revoke_user_sessions(
+ conn: &Connection,
+ user_id: UserId,
+ except: Option<Uuid>,
+) -> StoreResult<u64> {
+ let now = Timestamp::now().as_microsecond();
+ let rows = if let Some(keep) = except {
+ conn.execute(
+ "UPDATE web_sessions SET revoked_at = COALESCE(revoked_at, ?1) \
+ WHERE user_id = ?2 AND id != ?3",
+ params![now, user_id.as_bytes(), keep.as_bytes().as_slice()],
+ )?
+ } else {
+ conn.execute(
+ "UPDATE web_sessions SET revoked_at = COALESCE(revoked_at, ?1) \
+ WHERE user_id = ?2",
+ params![now, user_id.as_bytes()],
+ )?
+ };
+ Ok(rows as u64)
+}
+
+/// Revoke one session by hash (logout).
+///
+/// # Errors
+/// SQL failures.
+pub fn revoke_session_by_hash(
+ conn: &Connection,
+ session_hash: &[u8; TOKEN_HASH_LEN],
+) -> StoreResult<bool> {
+ let now = Timestamp::now().as_microsecond();
+ let rows = conn.execute(
+ "UPDATE web_sessions SET revoked_at = COALESCE(revoked_at, ?1) \
+ WHERE session_hash = ?2",
+ params![now, session_hash.as_slice()],
+ )?;
+ Ok(rows > 0)
+}
+
+/// Look up a live (unrevoked, unexpired) session by secret hash.
+///
+/// # Errors
+/// SQL failures.
+pub fn find_live_session_by_hash(
+ conn: &Connection,
+ session_hash: &[u8; TOKEN_HASH_LEN],
+ now: i64,
+) -> StoreResult<Option<LiveWebSession>> {
+ conn.query_row(
+ "SELECT s.id, s.csrf_hash, s.expires_at, s.last_used_at, \
+ u.id, u.username, u.name, u.email, u.created_at, u.last_seen_at, \
+ u.role, u.must_change_password, u.disabled_at, u.password_hash, \
+ u.token_expired_at \
+ FROM web_sessions s \
+ JOIN users u ON u.id = s.user_id \
+ WHERE s.session_hash = ?1 AND s.revoked_at IS NULL AND s.expires_at > ?2",
+ params![session_hash.as_slice(), now],
+ |row| {
+ let id_bytes: Vec<u8> = row.get(0)?;
+ let id = Uuid::from_slice(&id_bytes).map_err(|e| {
+ rusqlite::Error::FromSqlConversionFailure(
+ 0,
+ rusqlite::types::Type::Blob,
+ Box::new(std::io::Error::other(e.to_string())),
+ )
+ })?;
+ let csrf: Vec<u8> = row.get(1)?;
+ let csrf_hash: [u8; TOKEN_HASH_LEN] = csrf.as_slice().try_into().map_err(|_| {
+ rusqlite::Error::FromSqlConversionFailure(
+ 1,
+ rusqlite::types::Type::Blob,
+ Box::new(std::io::Error::other("csrf_hash must be 32 bytes")),
+ )
+ })?;
+ Ok(LiveWebSession {
+ id,
+ csrf_hash,
+ expires_at: row.get(2)?,
+ last_used_at: row.get(3)?,
+ user: row_to_user(row, 4)?,
+ })
+ },
+ )
+ .optional()
+ .map_err(StoreError::from)
+}
+
+/// Touch `last_used_at` at most once per minute.
+///
+/// # Errors
+/// SQL failures.
+pub fn touch_web_session(
+ conn: &Connection,
+ session_id: Uuid,
+ last_used_at: i64,
+) -> StoreResult<bool> {
+ let rows = conn.execute(
+ "UPDATE web_sessions SET last_used_at = ?1 \
+ WHERE id = ?2 AND (?1 - last_used_at) >= ?3",
+ params![
+ last_used_at,
+ session_id.as_bytes().as_slice(),
+ SESSION_TOUCH_MIN_MICROS
+ ],
+ )?;
+ Ok(rows > 0)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ai_memory_core::SESSION_SECRET_PREFIX;
+ use sha2::{Digest, Sha256};
+
+ #[test]
+ fn generate_session_secret_uses_ams_prefix() {
+ let secret = generate_session_secret().unwrap();
+ assert!(secret.starts_with(SESSION_SECRET_PREFIX), "{secret}");
+ assert_eq!(secret.len(), SESSION_SECRET_PREFIX.len() + 43);
+ }
+
+ #[test]
+ fn hash_session_secret_is_unpeppered_sha256() {
+ let secret = "ams_not-a-real-session-secret";
+ let got = hash_session_secret(secret);
+ let expected: [u8; TOKEN_HASH_LEN] = Sha256::digest(secret.as_bytes()).into();
+ assert_eq!(got, expected);
+ }
+}
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 46feb189..1fdcab0e 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -11,13 +11,15 @@ use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use ai_memory_core::{
- AgentKind, HandoffAcceptance, HandoffId, IdentityKey, ManagedRunId, NewHandoff, NewObservation,
- NewPage, NewSession, NewUser, ObservationId, OwnerFilter, PageId, PagePath, ProjectId,
- Sanitized, SessionId, UserId, WorkspaceId,
+ AgentKind, ApiCredentialId, HandoffAcceptance, HandoffId, IdentityKey, ManagedRunId,
+ NewHandoff, NewObservation, NewPage, NewSession, NewUser, ObservationId, OwnerFilter, PageId,
+ PagePath, ProjectId, Sanitized, SessionId, UserId, UserRole, WorkspaceId,
};
use rusqlite::Connection;
use tokio::sync::{mpsc, oneshot};
+use uuid::Uuid;
+use crate::api_credentials;
use crate::auto_improve::{
ApproveAutoImproveProposal, ApproveAutoImproveProposalResult, FailAutoImproveProposal,
RejectAutoImproveProposal, StageAutoImproveRun, StagedAutoImproveRun,
@@ -31,6 +33,7 @@ use crate::ops::{
};
use crate::session_consolidation::SessionConsolidationJob;
use crate::users::{self, TOKEN_HASH_LEN};
+use crate::web_sessions::{self, WebSession};
use crate::workstream::{
FinishWorkstreamRun, FinishedWorkstreamRun, PrepareWorkstreamRun, PreparedWorkstreamRun,
RenameWorkstream, RenamedWorkstream,
@@ -390,6 +393,20 @@ pub(crate) enum WriteCmd {
applied_at: i64,
reply: oneshot::Sender<StoreResult<()>>,
},
+ BootstrapRoot {
+ username: String,
+ name: Option<String>,
+ email: Option<String>,
+ password_hash: String,
+ reply: oneshot::Sender<StoreResult<UserId>>,
+ },
+ RecoverRoot {
+ username: String,
+ name: Option<String>,
+ email: Option<String>,
+ password_hash: String,
+ reply: oneshot::Sender<StoreResult<UserId>>,
+ },
CreateUser {
new_user: NewUser,
token_hash: [u8; TOKEN_HASH_LEN],
@@ -397,7 +414,7 @@ pub(crate) enum WriteCmd {
},
RotateUserToken {
user_id: UserId,
- new_token_hash: [u8; TOKEN_HASH_LEN],
+ token_hash: [u8; TOKEN_HASH_LEN],
reply: oneshot::Sender<StoreResult<bool>>,
},
ExpireUserToken {
@@ -408,6 +425,80 @@ pub(crate) enum WriteCmd {
user_id: UserId,
reply: oneshot::Sender<StoreResult<bool>>,
},
+ CreateHumanUser {
+ new_user: NewUser,
+ role: UserRole,
+ password_hash: Option<String>,
+ must_change_password: bool,
+ reply: oneshot::Sender<StoreResult<UserId>>,
+ },
+ ResetHumanPassword {
+ user_id: UserId,
+ password_hash: String,
+ must_change_password: bool,
+ reply: oneshot::Sender<StoreResult<bool>>,
+ },
+ SetUserDisabled {
+ user_id: UserId,
+ disabled: bool,
+ reply: oneshot::Sender<StoreResult<bool>>,
+ },
+ PatchUser {
+ user_id: UserId,
+ name: Option<Option<String>>,
+ email: Option<Option<String>>,
+ role: Option<UserRole>,
+ reply: oneshot::Sender<StoreResult<bool>>,
+ },
+ ChangePassword {
+ user_id: UserId,
+ expected_password_hash: String,
+ new_password_hash: String,
+ session_id: Uuid,
+ new_session_hash: [u8; TOKEN_HASH_LEN],
+ new_csrf_hash: [u8; TOKEN_HASH_LEN],
+ reply: oneshot::Sender<StoreResult<bool>>,
+ },
+ IssueWebSession {
+ user_id: UserId,
+ expected_password_hash: String,
+ expected_role: UserRole,
+ expected_must_change: bool,
+ session_hash: [u8; TOKEN_HASH_LEN],
+ csrf_hash: [u8; TOKEN_HASH_LEN],
+ reply: oneshot::Sender<StoreResult<WebSession>>,
+ },
+ RevokeWebSession {
+ session_hash: [u8; TOKEN_HASH_LEN],
+ reply: oneshot::Sender<StoreResult<bool>>,
+ },
+ TouchWebSession {
+ session_id: Uuid,
+ last_used_at: i64,
+ reply: oneshot::Sender<StoreResult<bool>>,
+ },
+ CreateApiCredential {
+ id: ApiCredentialId,
+ user_id: UserId,
+ label: String,
+ token_hash: [u8; TOKEN_HASH_LEN],
+ preview: Option<String>,
+ reply: oneshot::Sender<StoreResult<ApiCredentialId>>,
+ },
+ RotateApiCredential {
+ id: ApiCredentialId,
+ new_token_hash: [u8; TOKEN_HASH_LEN],
+ preview: Option<String>,
+ reply: oneshot::Sender<StoreResult<bool>>,
+ },
+ RevokeApiCredential {
+ id: ApiCredentialId,
+ reply: oneshot::Sender<StoreResult<bool>>,
+ },
+ TouchApiCredential {
+ id: ApiCredentialId,
+ reply: oneshot::Sender<StoreResult<bool>>,
+ },
TouchUserLastSeen {
user_id: UserId,
reply: oneshot::Sender<StoreResult<bool>>,
@@ -1631,16 +1722,56 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
- /// Insert a new user. `new_user` MUST already have been validated by
- /// [`NewUser::validate`](ai_memory_core::NewUser::validate); the
- /// caller (CLI or admin handler) generates the plaintext token,
- /// hashes it with the per-server pepper via
- /// [`crate::users::hash_token`], and passes only the digest in.
+ /// One-shot root bootstrap. `password_hash` is already Argon2id PHC.
+ ///
+ /// # Errors
+ /// Writer closed, duplicate identity, already completed, SQL.
+ pub async fn bootstrap_root(
+ &self,
+ username: String,
+ name: Option<String>,
+ email: Option<String>,
+ password_hash: String,
+ ) -> StoreResult<UserId> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::BootstrapRoot {
+ username,
+ name,
+ email,
+ password_hash,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Break-glass root reset. Does not touch API credentials.
///
/// # Errors
- /// - [`StoreError::WriterClosed`] if the writer has shut down.
- /// - [`StoreError::Duplicate`] when the username or email collides.
- /// - [`StoreError::Sqlite`] for any other SQL failure.
+ /// Writer closed, duplicate, SQL.
+ pub async fn recover_root(
+ &self,
+ username: String,
+ name: Option<String>,
+ email: Option<String>,
+ password_hash: String,
+ ) -> StoreResult<UserId> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::RecoverRoot {
+ username,
+ name,
+ email,
+ password_hash,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Insert a token-only compatibility identity.
+ ///
+ /// # Errors
+ /// Writer closed, duplicate username/email/token, SQL.
pub async fn create_user(
&self,
new_user: NewUser,
@@ -1656,35 +1787,29 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
- /// Replace a user's token hash with a freshly-generated digest.
- /// Implicitly clears `token_expired_at` — rotating an expired
- /// token only makes sense to make it usable again. Returns `false`
- /// when the user id doesn't exist; `true` on successful update.
+ /// Rotate and reactivate a user's deprecated single-token credential.
///
/// # Errors
- /// Returns [`StoreError::WriterClosed`] / [`StoreError::Sqlite`]
- /// per the usual writer-actor flow.
+ /// Writer closed or SQL.
pub async fn rotate_user_token(
&self,
user_id: UserId,
- new_token_hash: [u8; TOKEN_HASH_LEN],
+ token_hash: [u8; TOKEN_HASH_LEN],
) -> StoreResult<bool> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::RotateUserToken {
user_id,
- new_token_hash,
+ token_hash,
reply: tx,
})
.await?;
rx.await.map_err(|_| StoreError::WriterClosed)?
}
- /// Stamp `token_expired_at = now()` so the user's current token stops
- /// authenticating. Idempotent — repeating the call leaves the original
- /// expiry timestamp untouched. Returns `false` when the user doesn't exist.
+ /// Revoke a user's deprecated single-token credential.
///
/// # Errors
- /// Returns [`StoreError::WriterClosed`] / [`StoreError::Sqlite`].
+ /// Writer closed or SQL.
pub async fn expire_user_token(&self, user_id: UserId) -> StoreResult<bool> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::ExpireUserToken { user_id, reply: tx })
@@ -1692,11 +1817,10 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
- /// Clear `token_expired_at`, re-activating the user's existing token.
- /// Idempotent. Returns `false` when the user doesn't exist.
+ /// Reactivate a user's deprecated single-token credential.
///
/// # Errors
- /// Returns [`StoreError::WriterClosed`] / [`StoreError::Sqlite`].
+ /// Writer closed or SQL.
pub async fn revive_user_token(&self, user_id: UserId) -> StoreResult<bool> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::ReviveUserToken { user_id, reply: tx })
@@ -1704,6 +1828,248 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ /// Insert a human identity. `new_user` MUST already have been validated.
+ /// No API credential is created.
+ ///
+ /// # Errors
+ /// Writer closed, duplicate username/email, SQL.
+ pub async fn create_human_user(
+ &self,
+ new_user: NewUser,
+ role: UserRole,
+ password_hash: Option<String>,
+ must_change_password: bool,
+ ) -> StoreResult<UserId> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::CreateHumanUser {
+ new_user,
+ role,
+ password_hash,
+ must_change_password,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Admin password reset. Revokes web sessions.
+ ///
+ /// # Errors
+ /// Writer closed / SQL.
+ pub async fn reset_human_password(
+ &self,
+ user_id: UserId,
+ password_hash: String,
+ must_change_password: bool,
+ ) -> StoreResult<bool> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::ResetHumanPassword {
+ user_id,
+ password_hash,
+ must_change_password,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Enable or disable human login. Disable revokes sessions.
+ ///
+ /// # Errors
+ /// Last recoverable root, writer closed, SQL.
+ pub async fn set_user_disabled(&self, user_id: UserId, disabled: bool) -> StoreResult<bool> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::SetUserDisabled {
+ user_id,
+ disabled,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Patch name/email/role. `Some(None)` clears an optional field.
+ ///
+ /// # Errors
+ /// Last recoverable root, duplicate email, writer closed, SQL.
+ pub async fn patch_user(
+ &self,
+ user_id: UserId,
+ name: Option<Option<String>>,
+ email: Option<Option<String>>,
+ role: Option<UserRole>,
+ ) -> StoreResult<bool> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::PatchUser {
+ user_id,
+ name,
+ email,
+ role,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Change password for the current session and rotate its cookies.
+ ///
+ /// # Errors
+ /// Concurrent password change, writer closed, SQL.
+ pub async fn change_password(
+ &self,
+ user_id: UserId,
+ expected_password_hash: String,
+ new_password_hash: String,
+ session_id: Uuid,
+ new_session_hash: [u8; TOKEN_HASH_LEN],
+ new_csrf_hash: [u8; TOKEN_HASH_LEN],
+ ) -> StoreResult<bool> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::ChangePassword {
+ user_id,
+ expected_password_hash,
+ new_password_hash,
+ session_id,
+ new_session_hash,
+ new_csrf_hash,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Recheck PHC, role, disabled state, and must-change state, then insert
+ /// a web session.
+ ///
+ /// # Errors
+ /// Credentials no longer valid, writer closed, SQL.
+ pub async fn issue_web_session(
+ &self,
+ user_id: UserId,
+ expected_password_hash: String,
+ expected_role: UserRole,
+ expected_must_change: bool,
+ session_hash: [u8; TOKEN_HASH_LEN],
+ csrf_hash: [u8; TOKEN_HASH_LEN],
+ ) -> StoreResult<WebSession> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::IssueWebSession {
+ user_id,
+ expected_password_hash,
+ expected_role,
+ expected_must_change,
+ session_hash,
+ csrf_hash,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Logout: revoke one session by secret hash.
+ ///
+ /// # Errors
+ /// Writer closed / SQL.
+ pub async fn revoke_web_session(
+ &self,
+ session_hash: [u8; TOKEN_HASH_LEN],
+ ) -> StoreResult<bool> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::RevokeWebSession {
+ session_hash,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Touch `web_sessions.last_used_at` at most once per minute.
+ ///
+ /// # Errors
+ /// Writer closed / SQL.
+ pub async fn touch_web_session(
+ &self,
+ session_id: Uuid,
+ last_used_at: i64,
+ ) -> StoreResult<bool> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::TouchWebSession {
+ session_id,
+ last_used_at,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Insert a native API credential. `id` is caller-chosen.
+ ///
+ /// # Errors
+ /// Duplicate hash, writer closed, SQL.
+ pub async fn create_api_credential(
+ &self,
+ id: ApiCredentialId,
+ user_id: UserId,
+ label: String,
+ token_hash: [u8; TOKEN_HASH_LEN],
+ preview: Option<String>,
+ ) -> StoreResult<ApiCredentialId> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::CreateApiCredential {
+ id,
+ user_id,
+ label,
+ token_hash,
+ preview,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Rotate a native API credential hash and un-revoke it.
+ ///
+ /// # Errors
+ /// Duplicate hash, writer closed, SQL.
+ pub async fn rotate_api_credential(
+ &self,
+ id: ApiCredentialId,
+ new_token_hash: [u8; TOKEN_HASH_LEN],
+ preview: Option<String>,
+ ) -> StoreResult<bool> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::RotateApiCredential {
+ id,
+ new_token_hash,
+ preview,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Revoke a native API credential. Idempotent.
+ ///
+ /// # Errors
+ /// Writer closed / SQL.
+ pub async fn revoke_api_credential(&self, id: ApiCredentialId) -> StoreResult<bool> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::RevokeApiCredential { id, reply: tx })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Touch `api_credentials.last_used_at`.
+ ///
+ /// # Errors
+ /// Writer closed / SQL.
+ pub async fn touch_api_credential(&self, id: ApiCredentialId) -> StoreResult<bool> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::TouchApiCredential { id, 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
@@ -2505,6 +2871,38 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
let result = ops::insert_wiki_migration(&mut conn, &name, applied_at);
send_or_warn(reply, result, "insert_wiki_migration");
}
+ WriteCmd::BootstrapRoot {
+ username,
+ name,
+ email,
+ password_hash,
+ reply,
+ } => {
+ let result = users::bootstrap_root(
+ &mut conn,
+ &username,
+ name.as_deref(),
+ email.as_deref(),
+ &password_hash,
+ );
+ send_or_warn(reply, result, "bootstrap_root");
+ }
+ WriteCmd::RecoverRoot {
+ username,
+ name,
+ email,
+ password_hash,
+ reply,
+ } => {
+ let result = users::recover_root(
+ &mut conn,
+ &username,
+ name.as_deref(),
+ email.as_deref(),
+ &password_hash,
+ );
+ send_or_warn(reply, result, "recover_root");
+ }
WriteCmd::CreateUser {
new_user,
token_hash,
@@ -2515,10 +2913,10 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
}
WriteCmd::RotateUserToken {
user_id,
- new_token_hash,
+ token_hash,
reply,
} => {
- let result = users::rotate_user_token(&conn, user_id, &new_token_hash);
+ let result = users::rotate_user_token(&conn, user_id, &token_hash);
send_or_warn(reply, result, "rotate_user_token");
}
WriteCmd::ExpireUserToken { user_id, reply } => {
@@ -2529,6 +2927,149 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
let result = users::revive_user_token(&conn, user_id);
send_or_warn(reply, result, "revive_user_token");
}
+ WriteCmd::CreateHumanUser {
+ new_user,
+ role,
+ password_hash,
+ must_change_password,
+ reply,
+ } => {
+ let result = users::insert_human_user(
+ &conn,
+ &new_user,
+ role,
+ password_hash.as_deref(),
+ must_change_password,
+ );
+ send_or_warn(reply, result, "create_human_user");
+ }
+ WriteCmd::ResetHumanPassword {
+ user_id,
+ password_hash,
+ must_change_password,
+ reply,
+ } => {
+ let result = users::reset_human_password(
+ &mut conn,
+ user_id,
+ &password_hash,
+ must_change_password,
+ );
+ send_or_warn(reply, result, "reset_human_password");
+ }
+ WriteCmd::SetUserDisabled {
+ user_id,
+ disabled,
+ reply,
+ } => {
+ let result = users::set_user_disabled(&mut conn, user_id, disabled);
+ send_or_warn(reply, result, "set_user_disabled");
+ }
+ WriteCmd::PatchUser {
+ user_id,
+ name,
+ email,
+ role,
+ reply,
+ } => {
+ let result = users::patch_user(&mut conn, user_id, name, email, role);
+ send_or_warn(reply, result, "patch_user");
+ }
+ WriteCmd::ChangePassword {
+ user_id,
+ expected_password_hash,
+ new_password_hash,
+ session_id,
+ new_session_hash,
+ new_csrf_hash,
+ reply,
+ } => {
+ let result = users::change_password(
+ &mut conn,
+ user_id,
+ &expected_password_hash,
+ &new_password_hash,
+ session_id,
+ &new_session_hash,
+ &new_csrf_hash,
+ );
+ send_or_warn(reply, result, "change_password");
+ }
+ WriteCmd::IssueWebSession {
+ user_id,
+ expected_password_hash,
+ expected_role,
+ expected_must_change,
+ session_hash,
+ csrf_hash,
+ reply,
+ } => {
+ let result = users::issue_web_session(
+ &mut conn,
+ user_id,
+ &expected_password_hash,
+ expected_role,
+ expected_must_change,
+ &session_hash,
+ &csrf_hash,
+ );
+ send_or_warn(reply, result, "issue_web_session");
+ }
+ WriteCmd::RevokeWebSession {
+ session_hash,
+ reply,
+ } => {
+ let result = web_sessions::revoke_session_by_hash(&conn, &session_hash);
+ send_or_warn(reply, result, "revoke_web_session");
+ }
+ WriteCmd::TouchWebSession {
+ session_id,
+ last_used_at,
+ reply,
+ } => {
+ let result = web_sessions::touch_web_session(&conn, session_id, last_used_at);
+ send_or_warn(reply, result, "touch_web_session");
+ }
+ WriteCmd::CreateApiCredential {
+ id,
+ user_id,
+ label,
+ token_hash,
+ preview,
+ reply,
+ } => {
+ let result = api_credentials::insert_api_credential(
+ &conn,
+ id,
+ user_id,
+ &label,
+ &token_hash,
+ preview.as_deref(),
+ );
+ send_or_warn(reply, result, "create_api_credential");
+ }
+ WriteCmd::RotateApiCredential {
+ id,
+ new_token_hash,
+ preview,
+ reply,
+ } => {
+ let result = api_credentials::rotate_api_credential(
+ &conn,
+ id,
+ &new_token_hash,
+ preview.as_deref(),
+ );
+ send_or_warn(reply, result, "rotate_api_credential");
+ }
+ WriteCmd::RevokeApiCredential { id, reply } => {
+ let result = api_credentials::revoke_api_credential(&conn, id);
+ send_or_warn(reply, result, "revoke_api_credential");
+ }
+ WriteCmd::TouchApiCredential { id, reply } => {
+ let result = api_credentials::touch_api_credential(&conn, id);
+ send_or_warn(reply, result, "touch_api_credential");
+ }
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/crates/ai-memory-store/tests/audit_log.rs b/crates/ai-memory-store/tests/audit_log.rs
index 009cbb9b..30f438fa 100644
--- a/crates/ai-memory-store/tests/audit_log.rs
+++ b/crates/ai-memory-store/tests/audit_log.rs
@@ -1,7 +1,7 @@
//! Reader for the append-only `audit_log` table.
-use ai_memory_core::{NewPage, NewUser, PagePath, ProjectId, Tier, UserId, WorkspaceId};
-use ai_memory_store::{AuditLogFilter, Store, TOKEN_HASH_LEN};
+use ai_memory_core::{NewPage, NewUser, PagePath, ProjectId, Tier, UserId, UserRole, WorkspaceId};
+use ai_memory_store::{AuditLogFilter, Store};
async fn seed_page(
store: &Store,
@@ -38,13 +38,15 @@ async fn list_audit_events_resolves_names_pages_and_clamps_limit() {
let alice = store
.writer
- .create_user(
+ .create_human_user(
NewUser {
username: "alice".to_string(),
name: None,
email: None,
},
- [7u8; TOKEN_HASH_LEN],
+ UserRole::User,
+ None,
+ false,
)
.await
.unwrap();
diff --git a/crates/ai-memory-web/src/lib.rs b/crates/ai-memory-web/src/lib.rs
index efb01acf..a1b25e17 100644
--- a/crates/ai-memory-web/src/lib.rs
+++ b/crates/ai-memory-web/src/lib.rs
@@ -34,8 +34,8 @@ mod state;
mod templates;
pub use mount::{
- WebMountSpec, inject_base_href, inject_base_path_meta, mount_web_router, normalize_prefix,
- web_base_href,
+ SplitWebRouters, WebMountSpec, inject_base_href, inject_base_path_meta, normalize_prefix,
+ split_web_routers, web_base_href,
};
pub use state::WebState;
diff --git a/crates/ai-memory-web/src/mount.rs b/crates/ai-memory-web/src/mount.rs
index cd2b4655..8c6689e7 100644
--- a/crates/ai-memory-web/src/mount.rs
+++ b/crates/ai-memory-web/src/mount.rs
@@ -1,11 +1,10 @@
//! Mounting orchestration for the `/api/v1` + web-UI HTTP surfaces.
//!
-//! The host binary (`ai-memory serve`) builds its MCP/hook/admin router,
-//! then hands it to [`mount_web_router`] to nest the JSON API and mount
-//! either the operator's custom SPA (`--web-ui-dir`) or the built-in
-//! server-rendered wiki browser. Base-path / web-slug normalisation and
-//! `<base href>` injection live here too so the served HTML always
-//! resolves relative URLs under the configured prefix.
+//! The host binary (`ai-memory serve`) splits the JSON API and either the
+//! operator's custom SPA (`--web-ui-dir`) or built-in server-rendered wiki,
+//! attaches the appropriate public/dual-auth middleware, then merges them.
+//! Base-path normalisation and `<base href>` injection live here too so
+//! served HTML resolves relative URLs under the configured prefix.
use std::convert::Infallible;
use std::path::Path;
@@ -17,7 +16,7 @@ use ai_memory_wiki::Wiki;
use anyhow::{Context, Result};
use axum::body::Body;
use axum::extract::State;
-use axum::http::{Method, Request, StatusCode, header};
+use axum::http::{HeaderName, Method, Request, StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use tower::service_fn;
@@ -275,10 +274,9 @@ mod web_base_tests {
}
}
-/// Path / URL config the web mount needs. Bundling these together
-/// keeps `mount_web_router` and its helpers under clippy's
-/// `too_many_arguments` threshold without `#[allow]` papering over
-/// the call shape.
+/// Path / URL config the web mount needs. Bundling these together keeps
+/// [`split_web_routers`] below clippy's `too_many_arguments` threshold
+/// without hiding the call shape.
pub struct WebMountSpec<'a> {
/// Operator-supplied custom SPA directory (`--web-ui-dir`). `None`
/// mounts the built-in server-rendered wiki browser instead.
@@ -295,49 +293,70 @@ pub struct WebMountSpec<'a> {
pub base_path: &'a str,
}
-/// Orchestrator: assemble the `/api/v1` + web-UI surfaces on top of
-/// `router`. Skips everything when web is disabled. Each concern lives
-/// in a dedicated helper below so this function reads as a four-step
-/// recipe (CORS-scoped API, slug normalisation, SPA-vs-builtin choice,
-/// final mount).
-pub fn mount_web_router(
- router: axum::Router,
+/// Public SPA vs dual-auth wiki/API split.
+///
+/// Custom `--web-ui-dir` shells are public (session login lives in the SPA).
+/// Builtin wiki pages and `/api/v1` are dual-auth.
+pub struct SplitWebRouters {
+ /// Unauthenticated custom SPA (empty when builtin wiki is mounted).
+ pub public: axum::Router,
+ /// `/api/v1` plus the builtin wiki when that is the chosen UI.
+ pub protected: axum::Router,
+}
+
+/// Split the web surfaces so the host can attach different auth layers.
+///
+/// # Errors
+/// Custom SPA `index.html` cannot be read.
+pub fn split_web_routers(
enable_web: bool,
reader: ReaderPool,
wiki: Wiki,
spec: WebMountSpec<'_>,
-) -> Result<axum::Router> {
+) -> Result<SplitWebRouters> {
if !enable_web {
- return Ok(router);
+ return Ok(SplitWebRouters {
+ public: axum::Router::new(),
+ protected: axum::Router::new(),
+ });
}
- // Register the web surfaces BEFORE applying the bearer middleware. In
- // axum 0.8, `.layer()` only attaches to routes registered before the
- // call; nesting after the layer would silently bypass auth for /web/*.
- let router = router.nest(
- "/api/v1",
- build_api_router(&reader, &wiki, spec.cors_origins),
- );
-
- // Where the UI is mounted WITHIN the (already-applied) base path.
- // Empty slug => the UI is the root of the base path itself.
+ let api = build_api_router(&reader, &wiki, spec.cors_origins);
+ let protected_api = axum::Router::new().nest("/api/v1", api);
let slug = normalize_prefix(spec.web_slug);
let mount = if slug.is_empty() { "/" } else { slug.as_str() };
-
- // Custom SPA via --web-ui-dir (SPA fallback to index.html), otherwise
- // the built-in server-side wiki browser. In both cases the served
- // index carries an injected `<base href>` so relative asset/router
- // URLs resolve under `{base_path}{web_slug}`.
if let Some(dir) = spec.web_ui_dir {
- return mount_custom_spa(router, dir, &slug, spec.base_href, spec.base_path, mount);
+ let public = mount_custom_spa(
+ axum::Router::new(),
+ dir,
+ &slug,
+ spec.base_href,
+ spec.base_path,
+ mount,
+ )?;
+ return Ok(SplitWebRouters {
+ public,
+ protected: protected_api,
+ });
}
- Ok(mount_builtin_browser(
- router,
- reader,
- wiki,
- &slug,
- spec.base_href,
- mount,
- ))
+ Ok(SplitWebRouters {
+ public: axum::Router::new(),
+ protected: mount_builtin_browser(protected_api, reader, wiki, &slug, spec.base_href, mount),
+ })
+}
+
+/// Test-only composition helper. Production must attach distinct auth
+/// middleware to [`SplitWebRouters::public`] and
+/// [`SplitWebRouters::protected`] before merging them.
+#[cfg(test)]
+fn mount_web_router(
+ router: axum::Router,
+ enable_web: bool,
+ reader: ReaderPool,
+ wiki: Wiki,
+ spec: WebMountSpec<'_>,
+) -> Result<axum::Router> {
+ let split = split_web_routers(enable_web, reader, wiki, spec)?;
+ Ok(router.merge(split.protected).merge(split.public))
}
/// Build the `/api/v1` router and apply the per-origin CORS layer if
@@ -358,7 +377,11 @@ fn build_api_router(reader: &ReaderPool, wiki: &Wiki, cors_origins: &[String]) -
let cors = CorsLayer::new()
.allow_origin(parsed)
.allow_methods([Method::GET, Method::POST, Method::OPTIONS])
- .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE])
+ .allow_headers([
+ header::AUTHORIZATION,
+ header::CONTENT_TYPE,
+ HeaderName::from_static("x-csrf-token"),
+ ])
.allow_credentials(true)
.max_age(Duration::from_secs(600));
info!(origins = ?cors_origins, "CORS layer attached to /api/v1");
diff --git a/crates/ai-memory-web/tests/routes.rs b/crates/ai-memory-web/tests/routes.rs
index 9d561dc0..18a9ae76 100644
--- a/crates/ai-memory-web/tests/routes.rs
+++ b/crates/ai-memory-web/tests/routes.rs
@@ -236,8 +236,6 @@ async fn web_page_view_renders_author_chip_for_attributed_pages() {
.get_or_create_project(ws, "scratch", None)
.await
.unwrap();
- let pepper = ai_memory_store::TokenPepper::new("test-pepper");
- let token_hash = ai_memory_store::hash_token("t", &pepper);
let mut new_user = ai_memory_core::NewUser {
username: "alice".into(),
name: Some("Alice Smith".into()),
@@ -246,7 +244,7 @@ async fn web_page_view_renders_author_chip_for_attributed_pages() {
new_user.validate().unwrap();
let user_id = store
.writer
- .create_user(new_user, token_hash)
+ .create_human_user(new_user, ai_memory_core::UserRole::User, None, false)
.await
.unwrap();
@@ -2834,8 +2832,6 @@ async fn api_v1_page_surfaces_author_for_db_user_writes() {
.unwrap();
// Seed a `users` row and write a page attributed to that id.
- let pepper = ai_memory_store::TokenPepper::new("test-pepper");
- let token_hash = ai_memory_store::hash_token("any-token", &pepper);
let mut new_user = ai_memory_core::NewUser {
username: "alice".into(),
name: Some("Alice Smith".into()),
@@ -2844,7 +2840,7 @@ async fn api_v1_page_surfaces_author_for_db_user_writes() {
new_user.validate().unwrap();
let user_id = store
.writer
- .create_user(new_user, token_hash)
+ .create_human_user(new_user, ai_memory_core::UserRole::User, None, false)
.await
.unwrap();
@@ -2899,8 +2895,6 @@ async fn api_v1_etag_differs_between_anonymous_and_attributed_writes() {
.get_or_create_project(ws, "scratch", None)
.await
.unwrap();
- let pepper = ai_memory_store::TokenPepper::new("test-pepper");
- let token_hash = ai_memory_store::hash_token("t", &pepper);
let mut new_user = ai_memory_core::NewUser {
username: "alice".into(),
name: None,
@@ -2909,7 +2903,7 @@ async fn api_v1_etag_differs_between_anonymous_and_attributed_writes() {
new_user.validate().unwrap();
let user_id = store
.writer
- .create_user(new_user, token_hash)
+ .create_human_user(new_user, ai_memory_core::UserRole::User, None, false)
.await
.unwrap();
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index 65834040..52256886 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -3926,8 +3926,6 @@ mod tests {
.unwrap();
// Pre-load an actual users row so author_id can FK-resolve.
- let pepper = ai_memory_store::TokenPepper::new("test-pepper-attribution");
- let token_hash = ai_memory_store::hash_token("test-token", &pepper);
let mut new_user = NewUser {
username: "alice".into(),
name: Some("Alice Smith".into()),
@@ -3936,7 +3934,7 @@ mod tests {
new_user.validate().unwrap();
let user_id: UserId = store
.writer
- .create_user(new_user, token_hash)
+ .create_human_user(new_user, ai_memory_core::UserRole::User, None, false)
.await
.unwrap();
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 318648fe..a3ee3c55 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -438,6 +438,23 @@ keeps the same auth, scope resolver, and tool handlers as direct HTTP clients.
The adapter fails closed without a Claude session id and is installed only by
the explicit `install-mcp --client claude-code --session-aware` option.
+## HTTP authentication classes
+
+The process separates four active credential classes from one transitional
+browser compatibility path:
+
+| Class | Wire | Authorizes |
+|---|---|---|
+| Human password | `POST /auth/login` body | Session issuance only |
+| Web session | `ai_memory_session` cookie + CSRF | `/auth/me`, `/admin/*`, `/api/v1/*` by `AuthLevel`; never `/mcp` or hooks |
+| Recovery | `POST /auth/recovery` body | Root password reset; no session |
+| API key | `Authorization: Bearer` (`aim_`, root `AI_MEMORY_AUTH_TOKEN`, or external `amk_`) | Machine APIs; never a web session |
+| Deprecated browser compatibility | HTTP Basic root bearer, then HttpOnly `ai_memory_auth` cookie | GET-only browser routes until any human password or completed bootstrap exists; never machine routes |
+
+The deprecated Basic/cookie path stops immediately when human auth becomes
+active; restart is not required. `/web` SPA HTML is public static; the builtin
+wiki browser and JSON APIs stay behind the route class above.
+
## CLI subcommand surface
```
@@ -458,6 +475,7 @@ reorg purge-project rename-project
move-project move-session uninstall
auth user completions
handoffs purge-session compact
+api-key
```
Run `ai-memory --help` for the full tree.
diff --git a/docs/auto-scope.md b/docs/auto-scope.md
index 0c335c00..af743621 100644
--- a/docs/auto-scope.md
+++ b/docs/auto-scope.md
@@ -175,9 +175,9 @@ For built-in installs that use static MCP config, prefer:
## Pairing with multi-user mode
`per_actor` is most useful when the engine is in multi-user mode (see
-[`docs/users.md`](users.md)) — each authenticated user has their own
-`users.token_hash` row, so the auth middleware tags every request with
-the right `user`. With `[auto_scope] mode = "per_actor"`, two
+[`docs/users.md`](users.md)) — each native API credential resolves through
+`api_credentials` to its owning `users` row, so the auth middleware tags
+every request with the right `user`. With `[auto_scope] mode = "per_actor"`, two
authenticated users running concurrent agent sessions through the same
engine no longer overwrite each other's "current project" pointer for
MCP calls; if their clients also forward session ids, concurrent
diff --git a/docs/deploy.md b/docs/deploy.md
index e90b7272..104b5336 100644
--- a/docs/deploy.md
+++ b/docs/deploy.md
@@ -105,7 +105,7 @@ CLI sends an `Authorization: Bearer <token>` header on every call; ai-memory's
middleware validates with a constant-time comparison.
**Encrypted transport.** Plain HTTP on the LAN means anyone with a
-packet capture can read the bearer token (and per-user tokens once
+packet capture can read the bearer token (and native `aim_` keys once
multi-user mode is on) in transit. Add a TLS-terminating reverse
proxy in front of ai-memory — Caddy with Let's Encrypt, Caddy with
its internal CA, Cloudflare Tunnel, nginx, or external cert files —
diff --git a/docs/frontend-api.md b/docs/frontend-api.md
index 10e8d8c6..37b3d4ca 100644
--- a/docs/frontend-api.md
+++ b/docs/frontend-api.md
@@ -16,44 +16,49 @@
## 2. Auth model
-Every `/api/v1/*` request goes through the same bearer + host-allowlist
-middleware as `/mcp`, `/hook`, and `/admin/*` — they're all nested
-*before* the auth layers are applied
-(`crates/ai-memory-cli/src/commands/serve.rs`, see `mount_web_router` →
-`apply_http_layers`). So:
-
-- **Anonymous request → `401 Unauthorized`** (when the server is running
- with a bearer token configured).
-- **Disallowed `Host` header → `403 Forbidden`** (DNS-rebinding guard).
-- The static bearer is the root credential. DB-user tokens and a configured
- trusted-proxy bearer resolve per-user identities; actor-scoped responses then
- expose only that operator's plus shared handoffs. See
- [`docs/users.md`](users.md) for the full auth ladder.
-
-Pass the bearer in the standard header:
+`/api/v1/*` and `/admin/*` are dual-auth surfaces:
+
+- Human operators authenticate with `POST /auth/login`. The engine returns an
+ `HttpOnly`, `SameSite=Strict` `ai_memory_session` cookie plus a readable
+ `ai_memory_csrf` cookie. Browser requests use `credentials: "include"`;
+ mutations also copy the CSRF cookie to `X-CSRF-Token`.
+- Machine clients send `Authorization: Bearer <token>`. The static
+ `AI_MEMORY_AUTH_TOKEN` is machine-root authority; native `aim_` API keys are
+ always User-level. Bearers never authenticate `/auth/*`.
+- A recognized Bearer has precedence over every browser credential. An invalid
+ Bearer fails closed rather than falling back. Before human auth activates,
+ deprecated Basic/cookie compatibility is evaluated for GET requests; after
+ activation, Basic and unknown schemes do not suppress a valid web session.
+- `/mcp`, hooks, handoffs, and workstream routes are machine-only. A web-session
+ cookie cannot authenticate them.
+- A disallowed `Host` header receives `403 Forbidden` before auth evaluation
+ (DNS-rebinding guard).
+
+The custom SPA shell and its static assets are public so the login screen can
+load. Its data routes remain protected. Start with:
```http
-Authorization: Bearer <token>
+GET /auth/me
```
-Get a token:
+An authenticated response includes the operator identity, password-change
+state, and server-calculated capabilities. On an intentionally zero-config
+loopback server it instead returns an explicit anonymous snapshot. When human
+authority is configured, login is:
-```bash
-ai-memory generate-auth-token # writes a root token to stdout
-# then export AI_MEMORY_AUTH_TOKEN=<token> in the server's environment,
-# or put it under [auth].bearer_token in config.toml
-```
-
-In a same-origin SPA, the token can come from:
+```http
+POST /auth/login
+Content-Type: application/json
-- A user-pasted value in the UI (the simplest model — same as the
- built-in `/web` browser's HTTP Basic prompt).
-- A platform-specific secret store, then injected into `fetch()` calls.
+{"username":"alice","password":"…"}
+```
-> **XSS note:** if your SPA stores the bearer in `localStorage` and ships
-> with an XSS bug, the token is exfiltrable. That's the SPA's risk, not
-> the API's. Consider read-only environment-injected tokens or HTTP-only
-> cookie tunneling via a reverse proxy if you're hardening for that.
+Do not put `AI_MEMORY_AUTH_TOKEN`, `aim_` keys, session values, or CSRF values
+in `localStorage`. Before any human password or completed bootstrap exists,
+deprecated GET-only browser compatibility may accept the root bearer through
+HTTP Basic and an HttpOnly `ai_memory_auth` cookie. Human activation disables
+that path immediately. See [`docs/users.md`](users.md) for bootstrap, password
+rotation, recovery, roles, session expiry, and API-key lifecycle.
## 3. Error model
@@ -67,11 +72,12 @@ with one of these statuses:
| Status | When |
|---|---|
-| `400 Bad Request` | invalid query params, malformed `Authorization`, partial scope (workspace without project or vice versa), too many scopes in `POST /search` (>25), empty `q`, malformed session id, unknown observation `kinds` or `order`. |
-| `401 Unauthorized` | bearer missing or wrong. |
-| `403 Forbidden` | Host header not in allowlist; or a non-root caller requests `all_owners=true`. |
+| `400 Bad Request` | invalid query params, malformed input, partial scope (workspace without project or vice versa), too many scopes in `POST /search` (>25), empty `q`, malformed session id, unknown observation `kinds` or `order`. |
+| `401 Unauthorized` | human session or machine Bearer is missing, expired, revoked, or invalid. |
+| `403 Forbidden` | Host header not in allowlist; cookie mutation lacks valid CSRF; password change is pending; or the authenticated authority lacks the requested capability. |
| `404 Not Found` | workspace, project, or page doesn't exist; page file missing on disk; or a session id that is not visible in that project for the caller. |
-| `500 Internal Server Error` | reader pool / SQLite failure. Body is always the fixed `{"error":"internal server error"}`; the underlying cause is logged server-side rather than returned, so it cannot leak paths or configuration to a browser. |
+| `429 Too Many Requests` | login/recovery rate limit or bounded password-KDF queue is saturated. |
+| `500 Internal Server Error` | reader pool / SQLite failure. Body is always a fixed generic error; the underlying cause is logged server-side rather than returned, so it cannot leak paths or configuration to a browser. |
## 4. Endpoint reference
@@ -438,10 +444,9 @@ mounted at the absolute host root — outside `--base-path` and outside
the `/web` nest — so the browser's automatic fetch reaches it even
under a subpath deployment. The response is `image/png` despite the
`.ico` URL (modern browsers accept PNG icons), and the route is
-**exempt from bearer auth and host allowlist**: a browser opening a
-fresh tab gets the icon without an HTTP Basic prompt, and the
-embedded PNG is the same one any visitor to `/web` already sees, so
-the info-leak surface is nil.
+**exempt from authentication and host allowlist**: a fresh tab can fetch the
+icon before login, and the embedded PNG is the same one any visitor to `/web`
+already sees, so the info-leak surface is nil.
### 4.11 Sessions
@@ -566,10 +571,11 @@ ai-memory serve \
The static directory is served at `/web` via `tower-http::ServeDir`:
-- **Same auth as `/api/v1`.** Mounted before the bearer middleware
- layer, so `/web/*` requests must carry the same `Authorization`
- header (browsers typically prompt via HTTP Basic when auth is on —
- the user pastes the token as the password).
+- **Public shell, protected data.** `index.html`, client-router fallbacks, and
+ static assets load without credentials so the login form can render.
+ `/auth/me`, `/api/v1/*`, and `/admin/*` enforce the session/Bearer contract
+ above. The built-in wiki router used when `--web-ui-dir` is absent remains
+ protected because it renders data server-side.
- **SPA fallback.** Missing paths fall back to `index.html`, so a
client-side router (React Router, SvelteKit, etc.) can own
`/web/whatever` without 404s.
@@ -621,23 +627,41 @@ project tree). No regression.
## 7. Worked example: minimal SPA fetch
```js
-// Resolve the API base from the SPA shell injected by ai-memory. The meta tag
-// is empty at host root and e.g. "/wiki" behind a subpath reverse proxy.
+// Resolve bases from the SPA shell injected by ai-memory. The meta tag is
+// empty at host root and e.g. "/wiki" behind a subpath reverse proxy.
const basePath = document
.querySelector('meta[name="ai-memory-base-path"]')
?.getAttribute("content") ?? "";
-const API = `${location.origin}${basePath}/api/v1`;
-const TOKEN = localStorage.getItem("ai-memory-token"); // your storage choice
+const origin = `${location.origin}${basePath}`;
+const API = `${origin}/api/v1`;
+
+async function login(username, password) {
+ const resp = await fetch(`${origin}/auth/login`, {
+ method: "POST",
+ credentials: "include",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ username, password }),
+ });
+ if (!resp.ok) throw new Error(`login failed: ${resp.status}`);
+ return resp.json();
+}
+
+function cookie(name) {
+ const prefix = `${encodeURIComponent(name)}=`;
+ return document.cookie
+ .split(";")
+ .map(value => value.trim())
+ .find(value => value.startsWith(prefix))
+ ?.slice(prefix.length);
+}
async function apiGet(path, params) {
const url = new URL(`${API}${path}`, location.origin);
- if (params) Object.entries(params).forEach(([k, v]) =>
- v != null && url.searchParams.set(k, v));
+ if (params) Object.entries(params).forEach(([key, value]) =>
+ value != null && url.searchParams.set(key, value));
const resp = await fetch(url, {
- headers: {
- Accept: "application/json",
- ...(TOKEN ? { Authorization: `Bearer ${TOKEN}` } : {}),
- },
+ credentials: "include",
+ headers: { Accept: "application/json" },
});
if (!resp.ok) {
const { error } = await resp.json().catch(() => ({ error: resp.statusText }));
@@ -646,16 +670,19 @@ async function apiGet(path, params) {
return resp.json();
}
-// Top-level "home" view in one request.
-const overview = await apiGet("/workspaces/default/projects/ai-memory/overview", { limit: 10 });
+// Call login() from the UI first. The HttpOnly session is never visible here.
+const overview = await apiGet("/workspaces/default/projects/ai-memory/overview", {
+ limit: 10,
+});
console.log(overview.briefing.counts.pages_latest, "pages");
-// Multi-scope search.
+// POST is CSRF-protected even when the operation is read-only.
const search = await fetch(`${API}/search`, {
method: "POST",
+ credentials: "include",
headers: {
"Content-Type": "application/json",
- Authorization: `Bearer ${TOKEN}`,
+ "X-CSRF-Token": decodeURIComponent(cookie("ai_memory_csrf") ?? ""),
},
body: JSON.stringify({
q: "karpathy",
@@ -665,7 +692,7 @@ const search = await fetch(`${API}/search`, {
],
limit: 20,
}),
-}).then(r => r.json());
+}).then(response => response.json());
```
`curl` smoke test:
diff --git a/docs/https-via-proxy.md b/docs/https-via-proxy.md
index 39d1bd85..5b39431e 100644
--- a/docs/https-via-proxy.md
+++ b/docs/https-via-proxy.md
@@ -25,19 +25,20 @@ Add a TLS-terminating proxy in front of ai-memory when any of these
apply:
- **Multi-user mode is on** (at least one user row exists; `[auth].token_pepper`
- is the credential prerequisite). Per-user tokens travel between clients and
+ is the credential prerequisite). Native `aim_` keys travel between clients and
the server — sniffable over plain HTTP on the LAN. See
[`docs/users.md`](users.md).
- **The server is bound beyond loopback** (`AI_MEMORY_BIND=0.0.0.0:49374` or a LAN-routable IP). Anyone on the network segment sees plaintext token traffic and `/web` cookies.
-- **You access `/web` from a different machine** than the one running ai-memory. The browser session cookie set after Basic auth lives in the clear over HTTP.
+- **You access `/web` from a different machine** than the one running ai-memory. The browser session cookie set after password login lives in the clear over HTTP.
- **You're exposing ai-memory beyond the LAN.** Cloudflare Tunnel or a public-domain Caddy with Let's Encrypt are the two patterns most homelab operators land on.
-ai-memory refuses to start unauthenticated non-loopback HTTP by default.
-Configure `AI_MEMORY_AUTH_TOKEN` or bind loopback; the dangerous
-`--allow-insecure-no-auth` escape hatch exists only for intentional plain-HTTP
-LAN use. Authenticated non-loopback plain HTTP remains available and logs a
-loud warning: bearer tokens and `/web` cookies are still sniffable without
-TLS. The decision to add TLS is yours; this page is the recipes.
+ai-memory refuses unauthenticated non-loopback HTTP by default. Machine-only
+Bearer deployments may still bind authenticated plain HTTP and receive a loud
+warning because those credentials remain sniffable. Human authentication is
+stricter: a non-loopback listener refuses startup unless
+`AI_MEMORY_AUTH__SECURE_COOKIE=true`, which is the operator's explicit signal
+that a trusted HTTPS proxy owns the browser-facing edge. Non-Secure human
+cookies are supported only on an actual loopback listener.
## Pick a path
@@ -160,9 +161,11 @@ ai-memory install-hooks --agent claude-code --apply \
--server-url "https://memory.example.com/wiki" --auth-token "$AI_MEMORY_AUTH_TOKEN"
```
-The built-in browser is then at `https://memory.example.com/wiki/web`; add
-`AI_MEMORY_WEB_SLUG=/` if you want the browser or custom `--web-ui-dir` SPA at
-`https://memory.example.com/wiki` itself.
+The web surface is then at `https://memory.example.com/wiki/web`; add
+`AI_MEMORY_WEB_SLUG=/` if you want the built-in browser or custom
+`--web-ui-dir` SPA at `https://memory.example.com/wiki` itself. Human console
+login requires the custom SPA; the built-in server-rendered wiki remains
+protected data rather than an authentication page.
**Safety rules on both flags.** `AI_MEMORY_BASE_PATH` and
`AI_MEMORY_WEB_SLUG` go through the same normaliser. Segments must be
@@ -421,13 +424,12 @@ directly off the request, which proxies forward verbatim. The
For browser access to `/web` through HTTPS, set
`AI_MEMORY_AUTH__SECURE_COOKIE=true` (or `[auth] secure_cookie = true`). This
-marks the Basic-auth session cookie `Secure`; it is always `HttpOnly`,
+marks the `ai_memory_session` cookie `Secure`; it is always `HttpOnly`,
`SameSite=Strict`, and `Path=/`. ai-memory intentionally does **not** infer
HTTPS from `X-Forwarded-Proto` or any other proxy header. Close direct HTTP
-access to the public hostname, or redirect it to HTTPS. Enabling
-`secure_cookie` on a direct HTTP deployment makes browsers withhold the cookie,
-which is expected safety behavior. It remains false by default so loopback and
-plain-HTTP local `/web` continue to work.
+access to the public hostname, or redirect it to HTTPS. Human auth on a
+non-loopback listener will not start without this setting. It remains false by
+default only so direct loopback smoke/development can use plain HTTP.
The only thing to mind: **`AI_MEMORY_ALLOWED_HOSTS` must include the
public hostname**, not just `localhost`. The host-allowlist middleware
diff --git a/docs/install.md b/docs/install.md
index b4e65df6..90aa1488 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -19,6 +19,7 @@ path (docker + Claude Code). This page covers everything else:
- [LLM provider tiers + self-hosted Ollama](#llm-provider-tiers)
- [Common subcommands](#common-subcommands)
- [Managed routing snippets and Agent Skills](#managed-routing-snippets-and-agent-skills)
+- [Human password bootstrap and recovery](#human-password-bootstrap-and-recovery)
- [Operating without auth](#operating-without-auth) (local-only)
- [Keeping ai-memory up to date](#keeping-ai-memory-up-to-date)
@@ -1809,6 +1810,9 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree
| `commit -m "…"` | `docker exec` | Stage + commit the wiki tree |
| `reset --confirm` | `docker exec` | Wipe data (refuses while siblings alive) |
| `generate-auth-token` | `docker run --rm` | Print a random hex bearer token |
+| `user add-human` / `list` / `reset-password` / `disable` / `enable` / `patch` | `docker exec` or native binary | Human identities and temporary passwords; never issues an API key |
+| `user add` / `expire` / `revive` / `rotate-token` | `docker exec` or native binary | Deprecated 1.x compatibility-token lifecycle backed by `legacy-user-token` |
+| `api-key add` / `list` / `rotate` / `revoke` | `docker exec` or native binary | Native `aim_` machine credentials |
| `auth login openai-oauth` | same data volume as the server | Store a ChatGPT/Codex OAuth refresh token for the optional `openai-oauth` LLM provider |
| `auth login copilot` | same data volume as the server | Store a GitHub token for the optional `copilot` LLM provider |
| `auth login oidc-device` | same developer data dir as native hooks and thin-client CLI commands | Store a per-developer OIDC device token for native hook authentication and HTTP CLI fallback auth |
@@ -2015,6 +2019,67 @@ either way. To keep durable file logs (and durable hook spooling) inside a
sandbox, map the data dir read-write, e.g. `ai-jail --rw-map
~/.local/share/ai-memory …`.
+## Human password bootstrap and recovery
+
+Human console login is username/password, not a Bearer pasted into the
+browser. Machine APIs keep using `Authorization: Bearer` (`AI_MEMORY_AUTH_TOKEN`
+or a native `aim_` key). Before human auth activates, deprecated GET-only
+browser compatibility may exchange the root bearer through HTTP Basic for an
+HttpOnly `ai_memory_auth` cookie; activation disables that path immediately.
+The active classes stay isolated: a password only issues a session; a session
+never authenticates `/mcp`/hooks/workstreams; recovery never issues a session;
+an API key never logs into `/auth/login`.
+
+### First-time root (greenfield)
+
+Set a one-shot password, then start `serve`. The engine creates the configured
+`root_username` (default `root`) with `must_change_password=true` and marks
+bootstrap complete. Later restarts ignore the value even if it stays in the
+environment — unset it so the plaintext is not kept in process env.
+
+```bash
+# At least 12 characters. Must not equal the root bearer, actor-proxy bearer,
+# or recovery token, and must not use an `ams_`/`aim_`/`amk_` prefix.
+export AI_MEMORY_AUTH__INITIAL_ROOT_PASSWORD='choose-a-long-password'
+docker compose up -d # or: ai-memory serve
+unset AI_MEMORY_AUTH__INITIAL_ROOT_PASSWORD
+```
+
+The first login must change that password (`POST /auth/password` with CSRF).
+If the password collides with an existing native API-credential hash, startup
+fails closed and bootstrap is not marked complete.
+
+### Break-glass recovery
+
+If the last human root is lost, set a high-entropy recovery secret (at least
+32 characters) and `POST /auth/recovery` with a new password. Success returns
+204, expires the legacy `ai_memory_auth` cookie, revokes that user's sessions,
+and does **not** set `ai_memory_session`. Sign in again with the new password.
+
+```bash
+export AI_MEMORY_AUTH__RECOVERY_TOKEN='at-least-32-characters-of-entropy-here'
+# restart serve so the process picks up the new value
+curl -sS -D - -o /dev/null -X POST http://127.0.0.1:49374/auth/recovery \
+ -H 'content-type: application/json' \
+ -d '{"recovery_token":"'"$AI_MEMORY_AUTH__RECOVERY_TOKEN"'","new_password":"brand-new-pass!!","new_password_confirmation":"brand-new-pass!!"}'
+```
+
+Rotate by changing the env var and restarting; the previous token stops
+working immediately. Public failures (wrong token, recovery unset, password
+policy) share one 401 body. The recovery token is not a Bearer, cookie, or
+login password.
+
+When human mode is on (bootstrap completed, any password hash, or
+initial/recovery secrets configured), `serve` refuses to start unless a
+recoverable root exists (`role=root` with a password and not disabled) or
+recovery is configured. Explicit machine-only remote deploys with
+`AI_MEMORY_AUTH_TOKEN` and no human secrets remain valid. Loopback with
+neither Bearer nor human auth stays anonymous.
+
+CIDRs in `AI_MEMORY_AUTH__TRUSTED_PROXY_CIDRS` may supply `X-Forwarded-For`
+for login rate limits; untrusted peers' XFF is ignored. Behind HTTPS, set
+`AI_MEMORY_AUTH__SECURE_COOKIE=true` as noted above.
+
## Operating without auth
For local-only / single-machine deploys you can skip the bearer
diff --git a/docs/shell-completions.md b/docs/shell-completions.md
index 22558e8f..dedca81f 100644
--- a/docs/shell-completions.md
+++ b/docs/shell-completions.md
@@ -3,8 +3,8 @@
`ai-memory completions <shell>` prints a completion script to stdout for
`bash`, `zsh`, `fish`, `powershell`, or `elvish`. The script is generated from
the binary's own command tree, so it covers every subcommand and flag of the
-version that produced it — including nested commands like `user rotate-token`
-and `auth login`.
+version that produced it — including nested commands like `user reset-password`,
+`api-key rotate`, and `auth login`.
The Docker wrapper's `upgrade` command is wrapper-owned rather than part of the
native clap command tree, so it is the one subcommand not present in generated
diff --git a/docs/usage.md b/docs/usage.md
index 0e9ce427..3cb1ee64 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -336,8 +336,8 @@ ai-memory auth status
```
The login command stores only provider credentials in `<data_dir>/auth.json`.
-It is separate from `AI_MEMORY_AUTH_TOKEN`, which protects MCP, hooks, and the
-web UI.
+It is separate from `AI_MEMORY_AUTH_TOKEN`, the machine-root Bearer used by
+MCP, hooks, handoffs, workstreams, and machine calls to dual-auth APIs.
For GitHub Copilot, use the matching provider login before starting the server
with `AI_MEMORY_LLM_PROVIDER=copilot`:
@@ -375,10 +375,17 @@ current page's project unless the target carries its own scope).
only by their own glyph), inline `` `…` `` code, and 4-space-indented
code; external schemes inside the brackets (`http://`, `https://`,
`mailto:`, `data:`, `javascript:`, `vbscript:`, `tel:`, `file:`)
-stay literal too. If the server has `AI_MEMORY_AUTH_TOKEN` set, the
-browser uses HTTP Basic auth: leave the username blank and paste the
-token as the password. MCP and hook clients continue to use
-`Authorization: Bearer <token>`.
+stay literal too.
+
+With no authority configured on loopback, the built-in wiki remains
+anonymous. For human-authenticated administration, serve the compiled admin SPA
+with `--web-ui-dir`: it signs in through `/auth/login` and uses an HttpOnly web
+session plus CSRF protection. Before human auth is active, deprecated GET-only
+browser compatibility accepts the root bearer through HTTP Basic and an
+HttpOnly `ai_memory_auth` cookie; it stops immediately after a human password or
+completed bootstrap exists. Browser-stored Bearers remain unsupported.
+`AI_MEMORY_AUTH_TOKEN` and `aim_` API keys remain machine-only credentials sent
+as `Authorization: Bearer <token>` by MCP, hook, handoff, and workstream clients.
To host the web UI under a URL subpath behind a reverse proxy, the
`--base-path` / `--web-slug` flags do the work — see
diff --git a/docs/users.md b/docs/users.md
index 00174709..795a77b8 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -1,7 +1,7 @@
# Multi-user attribution
-> **Status:** Introduced in v0.8; this page documents the current shipped
-> contract.
+> **Status:** Introduced in v0.8; human password login, web sessions, and
+> native `aim_` API credentials are the current shipped contract.
ai-memory is **single-tenant wiki data** with **optional multi-user
attribution**. Every authenticated request sees the same wiki pages —
@@ -59,7 +59,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. |
| **1b — Proxy-asserted user** | Bearer matches the distinct `[auth].actor_proxy_bearer_token`. | Identity is taken from trusted `X-Memory-Actor-*` headers. The request is a **user** unless its OIDC issuer/subject pair exactly matches the configured root pair. Missing or malformed identity is rejected. |
-| **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. |
+| **2 — DB user** | Bearer doesn't match root, matches an active `api_credentials.token_hash` (SHA-256 of the secret + `[auth].token_pepper`). Native keys use the `aim_` prefix. | Allowed as **that user** for normal read/write APIs. Native keys always resolve as `AuthLevel::User`, even when the owning identity is `role=root`. 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 first credential that
@@ -67,6 +67,43 @@ applies, never escalates. Startup rejects equal root and proxy credentials;
root and proxy credentials take precedence over any accidental DB-token
collision.
+Human password login is **not** a bearer rung. A browser session cookie never
+authenticates `/mcp`, `/hook`, `/handoff`, or `/workstream/*`, and a password
+never authenticates as `Authorization: Bearer`.
+
+## Human login (password + web session)
+
+The console signs in with username and password. The engine issues an
+`HttpOnly` `ai_memory_session` cookie (`ams_` secret, hash only in SQLite)
+plus a separate CSRF cookie that the SPA must send on cookie-authenticated
+`POST`/`PUT`/`PATCH`/`DELETE`. Machine Bearers skip CSRF.
+
+| Endpoint | Class | Notes |
+|---|---|---|
+| `POST /auth/login` | public | Rate-limited. Returns the `/auth/me` snapshot plus `Set-Cookie`. |
+| `GET /auth/me` | session | Identity, `role`, `must_change_password`, capabilities. Anonymous only in zero-config loopback. |
+| `POST /auth/password` | session + CSRF | Changes password, revokes other sessions, rotates this one. |
+| `POST /auth/logout` | session + CSRF | Revokes the session and expires cookies. |
+| `POST /auth/recovery` | public | Break-glass for the configured `root_username`. Never issues a session. |
+
+Passwords are Argon2id PHC strings, 12–1024 UTF-8 bytes, hashed off the writer
+actor. The last enabled root with a password cannot be disabled or demoted.
+
+Greenfield bootstrap consumes `AI_MEMORY_AUTH__INITIAL_ROOT_PASSWORD` once
+(`human_auth_state.bootstrap_completed`). Later restarts ignore it — unset the
+env var. Lost root uses `AI_MEMORY_AUTH__RECOVERY_TOKEN` (at least 32
+characters), compared constant-time and never stored in SQLite. Public
+recovery failures — wrong token, recovery unset, or password policy —
+share one 401 `{"error":"invalid credentials"}` body. `Config::load()`
+rejects equality among the initial password, recovery token, root bearer,
+and actor-proxy bearer without logging the values. Operator runbook:
+[Human password bootstrap and recovery](install.md#human-password-bootstrap-and-recovery).
+
+`/admin/*` and `/api/v1/*` accept a machine Bearer **or** a web session.
+Custom SPA HTML at `/web` is public static; the builtin wiki browser stays
+behind auth. Once human auth becomes active, the engine expires the deprecated
+`ai_memory_auth` compatibility cookie.
+
## Trusted proxy identity
A deployment that terminates SSO validates the end user's credential, then
@@ -81,7 +118,7 @@ Configure a distinct proxy credential:
[auth]
bearer_token = "<root-token>" # direct administration
actor_proxy_bearer_token = "<different-token>" # SSO proxy only
-secure_cookie = true # when `/web` is HTTPS-only
+secure_cookie = true # required beyond loopback
# Optional stable identity for the root human behind an OIDC proxy.
root_issuer = "https://idp.example"
@@ -92,9 +129,11 @@ root_subject = "<root-subject>"
differ from `bearer_token`, and `serve` refuses startup otherwise or when the
root bearer is absent.
- Only set it when the server is reachable *only* through that proxy.
-- `secure_cookie` is independent of proxy identity. Enable it when a trusted
- reverse proxy terminates HTTPS for `/web`; ai-memory never trusts forwarded
- protocol headers to infer it. Direct HTTP browsers will not send that cookie.
+- `secure_cookie` is independent of proxy identity. Human auth requires it on
+ every non-loopback listener; ai-memory treats it as the explicit signal that
+ a trusted reverse proxy terminates HTTPS for `/web` and never trusts
+ forwarded protocol headers to infer that fact. Direct HTTP browsers will not
+ send a Secure cookie.
- **The proxy MUST strip client-supplied `X-Memory-Actor-*` headers before
setting its own.** Use a directive that *replaces* the header rather than
appending to it (nginx `proxy_set_header`, Traefik `customRequestHeaders`) —
@@ -346,89 +385,99 @@ root_name = "Boss" # optional, surfaced in UIs
```
`token_pepper` was auto-generated by `ai-memory init`; **do not
-change it after adding users** — rotating the pepper invalidates
-every existing token. The pepper is what makes a stolen `users`
-table useless to an offline attacker; an attacker with both the
-DB and the config has tokens at their disposal anyway, so the
-pepper's job is closed by the file-permission boundary.
-
-`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
-
-Each `ai-memory user add` issues one token, printed **exactly
-once**. Only its SHA-256 digest is kept in the DB.
+change it after issuing native API keys** — rotating the pepper invalidates
+every `aim_` credential. The pepper makes copied
+`api_credentials.token_hash` rows useless to an offline attacker; human
+passwords and sessions do not use it.
+
+`init` creates the pepper before any keys exist. Human users and web
+sessions can operate without a machine-root bearer; native API-key lookup
+still requires the original pepper. If `api_credentials` contains rows and
+the 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.
+
+### 2. Add another human
+
+Each `ai-memory user add-human` creates a person with a temporary password,
+printed **exactly once**. The new user must change it on next login.
+This does **not** issue an API key.
```console
$ AI_MEMORY_AUTH_TOKEN=<root-token> \
- ai-memory user add --username alice --email alice@home --name "Alice Smith"
+ ai-memory user add-human --username alice --email alice@home --name "Alice Smith"
✓ created user 'alice'
name: Alice Smith
email: alice@home
- id: 01935a82-6f7a-7d22-b8c0-...
+ role: user
-Store this token now — it will NOT be shown again. Only its
-SHA-256 digest is kept in the DB.
+Store this temporary password now — it will NOT be shown again.
+The user must change it on next login.
-mYi3pq...<43-chars>...wKp2Ze
+xK7mPq...<temp password>
```
-stderr carries the human chrome, stdout carries the bare token
-so you can pipe it (`> ~/.config/ai-memory/alice.token`).
+stderr carries the human chrome; stdout is the bare password so you can
+pipe it. Use `--role root` to create a second recoverable root.
### 3. List users
```console
$ AI_MEMORY_AUTH_TOKEN=<root-token> ai-memory user list
-USERNAME NAME EMAIL STATUS
-alice Alice Smith alice@home active
-bob - bob@home active
-carol - - expired
+USERNAME NAME ROLE STATUS
+alice Alice Smith user must-change
+bob - user active
+carol - user disabled
+dave - user active
+erin - user expired
```
-The list never surfaces tokens — only their hashes are in the DB.
+An `active` row without a password can be a deprecated 1.x compatibility-token
+identity. Grant human login with `user reset-password`; that does not reveal or
+rotate the machine secret. The list never surfaces passwords, hashes, or API
+secrets.
-### 4. Disable a token (without losing attribution history)
+### 4. Disable human login (without losing attribution history)
-`ai-memory user expire <username>` stamps `token_expired_at = now()`
-on the row. The user's bearer stops authenticating immediately, but
-the row stays put so historical `author_id` references in
-`audit_log` and `pages` keep resolving to their
-real names.
+`ai-memory user disable <username>` stamps `disabled_at` and revokes web
+sessions. Historical `author_id` references keep resolving. Native API
+credentials stay valid — revoke those separately with `api-key revoke`.
```console
-$ ai-memory user expire alice
-Expire token for user 'alice'? Their token stops authenticating immediately. (y/N) y
-✓ expired token for user 'alice'
+$ ai-memory user disable alice
+Disable human login for user 'alice'? (y/N) y
+✓ disabled user 'alice'
```
-Pass `--yes` to skip the prompt (CI / scripts).
+Pass `--yes` to skip the prompt (CI / scripts). Re-enable with
+`ai-memory user enable alice`. The last enabled root with a password
+cannot be disabled or demoted.
-To re-enable later: `ai-memory user revive alice`.
+### 5. Issue, rotate, or revoke a native API key
-### 5. Rotate a leaked / lost token
+Machine clients use `aim_` credentials, not passwords:
```console
-$ ai-memory user rotate-token alice
-Rotate token for user 'alice'? Any existing client using the old token will start getting 401 immediately. (y/N) y
-✓ rotated token for user 'alice'
+$ ai-memory api-key add --username alice --label codex-laptop
+✓ created API key '…' (codex-laptop)
Store this token now — it will NOT be shown again.
-XGqsBp...<43-chars>...zRm0Vt
+aim_mYi3pq...<secret>
+```
+
+```console
+$ ai-memory api-key rotate <id>
+$ ai-memory api-key revoke <id>
```
-Rotation implicitly revives an expired token — you can recover an
-offboarded user without first running `revive`.
+Rotation 401s the previous plaintext immediately. A revoked secret does
+not come back; issue a new key instead. Native keys authenticate as
+`AuthLevel::User` even when attached to a `role=root` identity —
+root automation still uses `[auth].bearer_token`. External `amk_` keys
+stay in `mcp-auth`; they are not listed here.
#### What rotation does to already-spooled hook events
@@ -451,25 +500,31 @@ normal retry budget rather than blocking the rest of the spool (#493).
## Backward compatibility
-If you're upgrading from a pre-v0.8 ai-memory:
-
-- **No action is required.** Your existing
- `[auth].bearer_token`-only setup continues to authenticate
- exactly as before. The auth middleware just stamps an anonymous
- `ActorContext` and your audit log records the same shape it did
- before.
-- The `users` table is added by migration V14 and stays empty
- until you actively run `ai-memory user add`. SQL queries against
- it return no rows; the rest of the schema is unchanged.
-- Multi-user mode requires `[auth].token_pepper`. Without it, the
- user-management endpoints return **503** with a clear
- `multi-user not enabled` message. Existing installs never trip
- this because they never call `user add`.
-- `/admin/*` endpoints are open to the configured bearer token in
- single-user mode, matching historical behavior. Creating the first user row
- immediately makes every admin endpoint root-only; DB-user tokens receive
- **403** and anonymous requests receive **401**. Merely configuring
- `[auth].token_pepper` does not activate that boundary.
+If you're upgrading a machine-bearer-only install:
+
+- **No immediate action is required.** Existing
+ `[auth].bearer_token` authentication continues to work as before.
+ Configure human bootstrap/recovery only when enabling password login.
+- Migration V52 extends the existing `users` table with human role/password
+ state and creates `web_sessions`; V53 copies every valid legacy
+ `users.token_hash` into `api_credentials` without changing its digest or
+ owner id.
+- Deprecated 1.x `user add`, `user expire`, `user revive`, and
+ `user rotate-token` commands remain available for compatibility. They manage
+ the migrated `legacy-user-token` credential; new automation should use
+ `api-key` commands, and new people should use `user add-human`.
+ The V53 mirror triggers are load-bearing for those shims and remain until the
+ shims are removed in 2.0.
+- Before any human password or completed bootstrap exists, GET-only browser
+ routes continue to accept the root bearer through HTTP Basic and the
+ HttpOnly `ai_memory_auth` cookie. Human activation disables that path
+ immediately, without a restart. Machine routes remain Bearer-only.
+- Native API credentials require `[auth].token_pepper`. Human user creation,
+ password reset, disable/enable, and session login do not create or depend
+ on API keys.
+- In human mode, `/admin/*` is available to a root web session or the
+ machine-root bearer. Native `aim_` credentials always remain
+ `AuthLevel::User` and receive **403** on root-only operations.
### Migrating an existing single-user install
@@ -498,24 +553,29 @@ config:
You can defer steps 3-4 indefinitely — `bearer_token` alone keeps
working as it always has.
-## How tokens are stored
-
-- 32 bytes of OS CSPRNG, URL-safe-base64-encoded → 43-character
- string.
-- DB column `users.token_hash` stores `SHA-256(token || ":" ||
- token_pepper)`, never the plaintext.
-- The per-server `token_pepper` makes a DB-only theft (e.g. a
- copied SQLite file) useless to an offline attacker: the search
- space for the unpeppered hash is `(token, pepper)` jointly.
-- Constant-time comparison (`subtle::ConstantTimeEq`) on the hash
- side-steps timing attacks against the lookup path.
-
-We deliberately **don't** use argon2id here even though it would be
-the textbook choice. Tokens are 256-bit CSPRNG, so brute force is
-infeasible regardless of hash strength; argon2id's per-hash salt
-would force O(N) scans on every auth request, where SHA-256 +
-`UNIQUE` index gives us the O(1) lookup the hot path needs.
-See `crates/ai-memory-store/src/users.rs` for the full rationale.
+## How credentials are stored
+
+**Passwords** are Argon2id PHC strings on `users.password_hash` with a
+random per-password salt. They never land in `api_credentials` and are
+never compared as Bearer.
+
+**Native API keys** (`aim_` + 43 URL-safe characters from 32 CSPRNG
+bytes) store `SHA-256(token || ":" || token_pepper)` in
+`api_credentials.token_hash`. The per-server `token_pepper` makes a
+DB-only theft (a copied SQLite file) useless offline. Constant-time
+comparison on the hash avoids timing leaks on the lookup path.
+Argon2id is the wrong KDF here: 256-bit CSPRNG secrets are not
+brute-forceable, and a per-hash salt would force O(N) scans on every
+auth request. See `crates/ai-memory-store/src/api_credentials.rs`.
+
+**Web sessions** hash a 256-bit `ams_` secret with SHA-256 (no pepper)
+into `web_sessions`. The cookie is `HttpOnly`, `SameSite=Strict`,
+`Path=/`. CSRF is a separate cookie compared to the session's CSRF
+hash.
+
+Brownfield `users.token_hash` values were copied losslessly into
+`api_credentials` (same 32-byte digest, label `legacy-user-token`).
+Runtime lookup no longer reads the old columns.
## Where attribution shows up
@@ -523,7 +583,7 @@ See `crates/ai-memory-store/src/users.rs` for the full rationale.
|---|---|
| Auth middleware injects `Extension<ActorContext>` on every request | ✓ P1.3 |
| 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 |
+| `ai-memory user add-human/list/reset-password/disable/enable/patch`, deprecated `user add/expire/revive/rotate-token`, and `ai-memory api-key add/list/rotate/revoke` | ✓ |
| `pages.author_id` populated, frontmatter `last_modified_by` block | ✓ P1.6 |
| `/api/v1` page responses include `author: { username, name?, email? }` | ✓ P1.7 |
| ETag invalidation on author change (so caches refresh attribution) | ✓ P1.7 |
@@ -535,20 +595,17 @@ Commit ids for each milestone are recorded in `CHANGELOG.md`.
## Wiring agent hooks to a specific user
-After `ai-memory user add` prints a user's token, point that user's
+After `ai-memory api-key add` prints a native secret, point that user's
agent install at it via `install-hooks`:
```console
-$ ai-memory user add --username alice --email alice@home --name "Alice Smith"
-✓ created user 'alice'
- name: Alice Smith
- email: alice@home
- ...
+$ ai-memory api-key add --username alice --label claude-hooks
+✓ created API key '…' (claude-hooks)
-XGq...<43-chars>...zRm # the token, stdout only
+aim_XGq...<secret> # stdout only
$ ai-memory install-hooks --apply --agent claude-code \
- --as-user alice --auth-token XGq...<43-chars>...zRm
+ --as-user alice --auth-token aim_XGq...<secret>
[ai-memory] hooks installing for user: alice
✓ staged 5 hook script(s) → ...
```
@@ -573,16 +630,21 @@ the bearer authenticates, attribution flows from the token's owner
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 every `/admin/*` endpoint. DB users created with `user add` are
- normal users, not additional admins.
+- **Native keys are not passwords.** `user add-human` never issues an `aim_`
+ secret; `api-key add` never issues a login session. The deprecated `user add`
+ command is the exception: it issues one compatibility token backed by the
+ reserved `legacy-user-token` credential. Disable/reset of a human leaves API
+ credentials untouched, and revoke/rotate of a native key leaves the
+ password/session untouched. One identity may hold several native keys with
+ distinct labels.
+- **Root token is single.** `[auth].bearer_token` is the programmatic
+ admin credential for `/admin/*`. A native key attached to a
+ `role=root` identity still authenticates as `AuthLevel::User`. Human
+ roots operate the console with a web session after password login.
- **OIDC is request authentication, not page authorization.** Native hooks and
thin-client CLI commands can send a per-developer OIDC bearer for an external
OIDC-aware gateway/bridge. Native ai-memory server auth still uses static root
- bearer / DB-user tokens, and `/admin/*` stays root-only unless a gateway
+ bearer / native `aim_` keys / web sessions, and `/admin/*` stays root-only unless a gateway
translates accepted OIDC auth into upstream auth that ai-memory accepts.
ai-memory still has one shared wiki per server and no
per-page RBAC. The Keycloak/OIDC `sid` claim is also not an ai-memory agent