Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat!: remove the 1.x compatibility-token commands
AkitaOnRails3c67df282639
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0bd7e3ef..eda2abc3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -446,6 +446,22 @@ and [0.x](docs/changelog/0.x.md).so metadata survives a round trip. The first run after upgrading rewritesunedited files of an earlier export in place. (#1164)+### Removed+- Removed the 1.x compatibility-token commands `ai-memory user add`,+ `user expire`, `user revive` and `user rotate-token`, and their admin+ endpoints `POST /admin/users` and `POST+ /admin/users/{name}/expire`, `/revive` and `/rotate-token`. They were+ deprecated in 2.0. Tokens they issued keep authenticating after the upgrade+ as ordinary API keys with the label `legacy-user-token`: list them with+ `ai-memory api-key list`, replace one with `api-key rotate <id>` and retire+ one with `api-key revoke <id>`. A token expired before the upgrade stays+ refused. Add people with `user add-human` and machine credentials with+ `api-key add`. Migration V79 drops the unused `users.token_hash` and+ `users.token_expired_at` columns and the triggers that mirrored them into+ `api_credentials`, so user records from `/admin/users` and `ai-memory user+ list --json` no longer carry `token_expired_at`, and `user list` no longer+ shows an `expired` status.+### Fixed- Fixed the companion relay refusing to open its queue on Windows when anotherrelay process was committing to the same queue. SQLite deletes its rollbackdiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 966f56d7..bc883146 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -347,8 +347,8 @@ pub enum Command {Upgrade(UpgradeArgs),/// Manage optional upstream LLM provider authentication.Auth(AuthArgs),- /// Manage human users and deprecated 1.x compatibility tokens. All- /// subcommands require the root bearer token.+ /// Manage human users and their project grants. All subcommands+ /// require the root bearer token. API keys live under `api-key`.User(UserArgs),/// Manage native `aim_` API credentials. All subcommands require/// the root bearer token and `[auth].token_pepper`.@@ -1066,8 +1066,6 @@ pub struct CompletionsArgs {/// Subcommands for `user`.#[derive(Debug, Subcommand)]pub enum UserCommand {- /// Create a token-only compatibility user and print their token once.- Add(UserAddArgs),/// 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")]@@ -1075,13 +1073,6 @@ pub enum UserCommand {/// List every registered identity. Passwords and hashes are never/// surfaced.List(UserListArgs),- /// Deprecated: expire the user's compatibility token.- Expire(UserExpireArgs),- /// Deprecated: reactivate the user's compatibility token.- Revive(UserReviveArgs),- /// 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.@@ -1104,23 +1095,6 @@ pub enum UserCommand {Grants(UserGrantsArgs),}-/// Arguments for `user add`.-#[derive(Debug, Args)]-pub struct UserAddArgs {- /// Stable username.- #[arg(long)]- pub username: String,- /// Optional display name.- #[arg(long)]- pub name: Option<String>,- /// Optional email.- #[arg(long)]- pub email: Option<String>,- /// 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 {@@ -1149,36 +1123,6 @@ pub struct UserListArgs {pub json: bool,}-/// Arguments for deprecated `user expire`.-#[derive(Debug, Args)]-pub struct UserExpireArgs {- /// Username whose compatibility token to expire.- pub username: String,- /// Skip the interactive confirmation prompt.- #[arg(long)]- pub yes: bool,-}--/// Arguments for deprecated `user revive`.-#[derive(Debug, Args)]-pub struct UserReviveArgs {- /// Username whose compatibility token to revive.- pub username: String,-}--/// Arguments for deprecated `user rotate-token`.-#[derive(Debug, Args)]-pub struct UserRotateTokenArgs {- /// 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 {@@ -4819,47 +4763,57 @@ mod tests {}#[test]- fn deprecated_user_token_commands_and_additive_human_create_parse() {+ fn removed_user_token_commands_no_longer_parse() {for argv in [+ vec!["ai-memory", "user", "add", "--username", "alice"],vec!["ai-memory", "user", "expire", "alice", "--yes"],vec!["ai-memory", "user", "revive", "alice"],+ vec!["ai-memory", "user", "rotate-token", "alice", "--yes"],+ ] {+ let error =+ Cli::try_parse_from(&argv).expect_err("the 1.x token commands were removed in 3.0");+ assert_eq!(+ error.kind(),+ clap::error::ErrorKind::InvalidSubcommand,+ "{argv:?}"+ );+ }+ let parsed = Cli::try_parse_from([+ "ai-memory",+ "user",+ "add-human",+ "--username",+ "alice",+ "--role",+ "root",+ ])+ .expect("user add-human still parses");+ let Command::User(args) = parsed.command else {+ panic!("expected user command");+ };+ assert!(matches!(args.command, UserCommand::AddHuman(_)));+ for argv in [+ vec!["ai-memory", "api-key", "list"],vec!["ai-memory",- "user",- "rotate-token",- "alice",+ "api-key",+ "rotate",+ "0190f0b8-0000-7000-8000-000000000000","--yes",- "--json",],vec!["ai-memory",- "user",- "add-human",- "--username",- "alice",- "--role",- "root",+ "api-key",+ "revoke",+ "0190f0b8-0000-7000-8000-000000000000",+ "--yes",],] {Cli::try_parse_from(&argv)- .unwrap_or_else(|error| panic!("{argv:?} must remain parseable: {error}"));+ .unwrap_or_else(|error| panic!("{argv:?} is the replacement path: {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/user.rs b/crates/ai-memory-cli/src/commands/user.rsindex 88a788be..872482fc 100644--- a/crates/ai-memory-cli/src/commands/user.rs+++ b/crates/ai-memory-cli/src/commands/user.rs@@ -1,7 +1,9 @@-//! `ai-memory user` — manage compatibility tokens and human password login.+//! `ai-memory user` — manage human users, password login and project grants.//!-//! Thin HTTP client over `/admin/users*`. The caller's bearer token must-//! authenticate as root. Single-token commands remain deprecated 1.x shims.+//! Thin HTTP client over `/admin/users*` and `/admin/human-users`. The+//! caller's bearer token must authenticate as root. API keys, including the+//! `legacy-user-token` rows left by the removed 1.x token commands, are+//! managed by `ai-memory api-key`.use std::io::{self, BufRead, Write};@@ -9,9 +11,8 @@ use anyhow::{Context, Result, bail};use serde::{Deserialize, Serialize};use crate::cli::{- UserAddArgs, UserAddHumanArgs, UserArgs, UserCommand, UserDisableArgs, UserEnableArgs,- UserExpireArgs, UserListArgs, UserPatchArgs, UserResetPasswordArgs, UserReviveArgs,- UserRotateTokenArgs,+ UserAddHumanArgs, UserArgs, UserCommand, UserDisableArgs, UserEnableArgs, UserListArgs,+ UserPatchArgs, UserResetPasswordArgs,};use crate::config::Config;use crate::http_client::{ServerEndpoint, get_json, patch_json, post_json};@@ -28,8 +29,6 @@ struct UserRow {#[serde(default)]last_seen_at: Option<i64>,#[serde(default)]- token_expired_at: Option<i64>,- #[serde(default)]role: String,#[serde(default)]must_change_password: bool,@@ -45,22 +44,12 @@ impl UserRow {"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"}}}-#[derive(Debug, Deserialize)]-struct UserWithToken {- user: UserRow,- token: String,-}-#[derive(Debug, Deserialize)]struct UserWithPassword {user: UserRow,@@ -85,12 +74,8 @@ struct UserList {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,@@ -112,27 +97,6 @@ struct CreateUserBody<'a> {role: Option<&'a str>,}-async fn add(ep: &ServerEndpoint, args: UserAddArgs) -> Result<()> {- let body = CreateUserBody {- username: args.username.trim(),- name: args- .name- .as_deref()- .map(str::trim)- .filter(|s| !s.is_empty()),- email: args- .as_deref()- .map(str::trim)- .filter(|s| !s.is_empty()),- role: None,- };- let resp: UserWithToken = post_json(ep, "/admin/users", &body)- .await- .context("creating compatibility user")?;- print_token(&resp, args.json, "created")-}-async fn add_human(ep: &ServerEndpoint, args: UserAddHumanArgs) -> Result<()> {let role = args.role@@ -218,44 +182,6 @@ async fn list(ep: &ServerEndpoint, args: UserListArgs) -> Result<()> {Ok(())}-async fn expire(ep: &ServerEndpoint, args: UserExpireArgs) -> Result<()> {- if !args.yes {- confirm(&format!(- "Expire token for user '{}'? Their token stops authenticating immediately. (y/N) ",- args.username- ))?;- }- let path = format!("/admin/users/{}/expire", url_encode(&args.username));- let _: UserResponse = post_json(ep, &path, &serde_json::json!({}))- .await- .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 _: UserResponse = post_json(ep, &path, &serde_json::json!({}))- .await- .context("reviving user token")?;- println!("✓ revived token for user '{}'", args.username);- Ok(())-}--async fn rotate_token(ep: &ServerEndpoint, args: UserRotateTokenArgs) -> Result<()> {- if !args.yes {- confirm(&format!(- "Rotate token for user '{}'? Existing clients will start getting 401 immediately. (y/N) ",- args.username- ))?;- }- let path = format!("/admin/users/{}/rotate-token", url_encode(&args.username));- 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!(@@ -343,27 +269,6 @@ async fn patch(ep: &ServerEndpoint, args: UserPatchArgs) -> Result<()> {Ok(())}-fn print_token(resp: &UserWithToken, json: bool, verb: &str) -> Result<()> {- if 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,- "✓ {verb} user '{}'\n\nStore this token now — it will NOT be shown again.",- resp.user.username- );- println!("{}", resp.token);- }- Ok(())-}-fn print_temp_password(resp: &UserWithPassword, json: bool, verb: &str) -> Result<()> {if json {println!(diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 06403332..4bfae0f0 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -3284,7 +3284,7 @@ mod tests {}}- /// Re-running `install-hooks --apply` after `user rotate-token` must leave+ /// Re-running `install-hooks --apply` after `api-key rotate` must leave/// the new bearer, not both.#[test]fn storing_a_second_token_replaces_the_first() {diff --git a/crates/ai-memory-core/src/user.rs b/crates/ai-memory-core/src/user.rsindex 3e0b07d2..df2bdd58 100644--- a/crates/ai-memory-core/src/user.rs+++ b/crates/ai-memory-core/src/user.rs@@ -113,11 +113,6 @@ 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 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@@ -136,13 +131,6 @@ impl User {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 authenticatingdiff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rsindex 8a0f2c11..a0d17468 100644--- a/crates/ai-memory-hooks/src/workstream.rs+++ b/crates/ai-memory-hooks/src/workstream.rs@@ -1453,13 +1453,15 @@ mod tests {state.wiki.commit_all("fixture baseline").unwrap();let reader = store.writer- .create_user(+ .create_human_user(ai_memory_core::NewUser {username: "promotion-reader".into(),name: None,email: None,},- [7; ai_memory_store::TOKEN_HASH_LEN],+ ai_memory_core::UserRole::User,+ None,+ false,).await.unwrap();@@ -4916,18 +4918,20 @@ mod tests {.set_access_mode(holder, ai_memory_store::AccessMode::Restricted).await.unwrap();- let user = |name: &str, seed: u8| {- store.writer.create_user(+ let user = |name: &str| {+ store.writer.create_human_user(ai_memory_core::NewUser {username: name.into(),name: None,email: None,},- [seed; ai_memory_store::TOKEN_HASH_LEN],+ ai_memory_core::UserRole::User,+ None,+ false,)};- let outsider = user("outsider", 3).await.unwrap();- let member = user("member", 4).await.unwrap();+ let outsider = user("outsider").await.unwrap();+ let member = user("member").await.unwrap();store.writer.grant_memory(member, holder, ai_memory_store::GrantLevel::Write, None)@@ -4991,18 +4995,20 @@ mod tests {.set_access_mode(legacy, ai_memory_store::AccessMode::Restricted).await.unwrap();- let user = |name: &str, seed: u8| {- store.writer.create_user(+ let user = |name: &str| {+ store.writer.create_human_user(ai_memory_core::NewUser {username: name.into(),name: None,email: None,},- [seed; ai_memory_store::TOKEN_HASH_LEN],+ ai_memory_core::UserRole::User,+ None,+ false,)};- let outsider = user("outsider", 3).await.unwrap();- let member = user("member", 4).await.unwrap();+ let outsider = user("outsider").await.unwrap();+ let member = user("member").await.unwrap();store.writer.grant_memory(member, legacy, ai_memory_store::GrantLevel::Write, None)diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex af2d5376..389a7d9a 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -711,18 +711,9 @@ pub fn admin_router_with_sweep_tuning(.route("/admin/write-page", post(handle_write_page)).route("/admin/delete-page", post(handle_delete_page));let users = Router::new()- .route(- "/admin/users",- get(handle_list_users).post(handle_create_user),- )+ .route("/admin/users", get(handle_list_users)).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),@@ -8454,12 +8445,6 @@ struct CreateApiCredentialRequest {label: String,}-#[derive(Debug, Serialize)]-struct UserWithTokenResponse {- user: ai_memory_core::User,- token: String,-}-#[derive(Debug, Serialize)]struct UserWithPasswordResponse {user: ai_memory_core::User,@@ -8597,44 +8582,6 @@ async fn create_human_user_response())}-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,- email: req.email,- };- new_user- .validate()- .map_err(|e| validation_error(e.to_string()))?;- let token = ai_memory_store::generate_token().map_err(|e| internal_err(e.to_string()))?;- let token_hash = ai_memory_store::hash_token(&token, pepper);- let user_id = state- .writer- .create_user(new_user, token_hash)- .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(UserWithTokenResponse { user, token }).unwrap_or_default()),- ))-}-async fn handle_create_human_user(State(state): State<Arc<AdminState>>,axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,@@ -8661,87 +8608,6 @@ async fn handle_list_users())}-async fn handle_expire_user(- State(state): State<Arc<AdminState>>,- axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,- axum::extract::Path(username): axum::extract::Path<String>,-) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {- require_root(level)?;- let user = lookup_user_by_username(&state, &username).await?;- state- .writer- .expire_user_token(user.id)- .await- .map_err(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 token expiry".to_string()))?;- Ok((- StatusCode::OK,- Json(serde_json::to_value(UserResponse { user }).unwrap_or_default()),- ))-}--async fn handle_revive_user(- State(state): State<Arc<AdminState>>,- axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,- axum::extract::Path(username): axum::extract::Path<String>,-) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {- require_root(level)?;- let user = lookup_user_by_username(&state, &username).await?;- state- .writer- .revive_user_token(user.id)- .await- .map_err(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 token revival".to_string()))?;- Ok((- StatusCode::OK,- Json(serde_json::to_value(UserResponse { user }).unwrap_or_default()),- ))-}--async fn handle_rotate_user_token(- State(state): State<Arc<AdminState>>,- axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,- axum::extract::Path(username): axum::extract::Path<String>,-) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {- require_root(level)?;- let pepper = require_pepper(&state)?;- let user = lookup_user_by_username(&state, &username).await?;- let token = ai_memory_store::generate_token().map_err(|e| internal_err(e.to_string()))?;- let token_hash = ai_memory_store::hash_token(&token, pepper);- let updated = state- .writer- .rotate_user_token(user.id, token_hash)- .await- .map_err(map_user_store_err)?;- if !updated {- return Err((- StatusCode::NOT_FOUND,- Json(serde_json::json!({ "error": "user vanished mid-rotation" })),- ));- }- let user = state- .reader- .find_user_by_id(user.id)- .await- .map_err(|e| internal_err(e.to_string()))?- .ok_or_else(|| internal_err("user vanished after token rotation".to_string()))?;- Ok((- StatusCode::OK,- Json(serde_json::to_value(UserWithTokenResponse { user, token }).unwrap_or_default()),- ))-}-async fn handle_patch_user(State(state): State<Arc<AdminState>>,axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,@@ -13705,6 +13571,15 @@ mod tests {/// 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, _store, router) = user_admin_dual_auth_router_with_store(root_token);+ (tmp, router)+ }++ /// [`user_admin_dual_auth_router`] plus the store behind it, for tests+ /// that seed rows the HTTP surface can no longer create.+ fn user_admin_dual_auth_router_with_store(+ root_token: &'static str,+ ) -> (TempDir, Store, Router) {let tmp = TempDir::new().unwrap();let store = Store::open(tmp.path()).unwrap();let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();@@ -13744,7 +13619,7 @@ mod tests {auth_state,crate::human_auth::require_dual_auth,));- (tmp, router)+ (tmp, store, router)}async fn post_disable_user(@@ -13787,26 +13662,6 @@ mod tests {.unwrap()}- async fn post_create_user(- router: &Router,- root_token: &str,- body: serde_json::Value,- ) -> axum::http::Response<Body> {- router- .clone()- .oneshot(- Request::builder()- .method("POST")- .uri("/admin/users")- .header("content-type", "application/json")- .header("authorization", format!("Bearer {root_token}"))- .body(Body::from(serde_json::to_vec(&body).unwrap()))- .unwrap(),- )- .await- .unwrap()- }-async fn post_create_human_user(router: &Router,root_token: &str,@@ -14022,23 +13877,11 @@ mod tests {}),),("GET", "/admin/users", serde_json::Value::Null),- (- "POST",- "/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),- (- "POST",- "/admin/users/alice/rotate-token",- serde_json::Value::Null,- ),("POST","/admin/users/alice/disable",@@ -14052,7 +13895,7 @@ mod tests {#[tokio::test]async fn multiuser_admin_routes_reject_db_user_tier() {let (_tmp, router) = user_admin_test_router("root-token");- post_create_user(+ post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice"}),@@ -14086,7 +13929,7 @@ mod tests {#[tokio::test]async fn multiuser_admin_routes_reject_anonymous() {let (_tmp, router) = user_admin_test_router("root-token");- post_create_user(+ post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice"}),@@ -14128,7 +13971,7 @@ mod tests {#[tokio::test]async fn multiuser_purge_project_dry_run_rejects_db_user_and_anonymous() {let (_tmp, router) = user_admin_test_router("root-token");- post_create_user(+ post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice"}),@@ -14213,7 +14056,7 @@ mod tests {#[tokio::test]async fn multiuser_purge_session_dry_run_rejects_db_user_and_anonymous() {let (_tmp, router) = user_admin_test_router("root-token");- post_create_user(+ post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice"}),@@ -14296,7 +14139,7 @@ mod tests {#[tokio::test]async fn multiuser_delete_workspace_dry_run_rejects_db_user_and_anonymous() {let (_tmp, router) = user_admin_test_router("root-token");- post_create_user(+ post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice"}),@@ -14508,7 +14351,7 @@ mod tests {.unwrap();assert_eq!(anonymous_before.status(), StatusCode::OK);- let create = post_create_user(+ let create = post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice"}),@@ -14654,33 +14497,6 @@ mod tests {}}- #[tokio::test]- async fn create_user_happy_path_returns_token_once() {- let (_tmp, router) = user_admin_test_router("root-token");- let resp = post_create_user(- &router,- "root-token",- serde_json::json!({- "username": "alice",- "name": "Alice Smith",- "email": "[email protected]"- }),- )- .await;- assert_eq!(resp.status(), StatusCode::OK);- let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();- let json: serde_json::Value = serde_json::from_slice(&body).unwrap();- assert_eq!(json["user"]["username"], "alice");- // Email was normalised to lowercase by NewUser::validate.- assert_eq!(json["user"]["email"], "[email protected]");- assert_eq!(json["user"]["name"], "Alice Smith");- // Plaintext token is surfaced exactly once.- 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");@@ -14702,98 +14518,247 @@ mod tests {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,+ const LEGACY_TEST_PEPPER: &str = "test-pepper-admin";++ /// What a 2.x `user add` left behind once V55 copied it: a user without a+ /// password and a `legacy-user-token` credential whose id is the user id+ /// and whose secret has no `aim_` prefix.+ async fn seed_legacy_token_user(+ store: &Store,+ username: &str,+ secret: &str,+ ) -> ai_memory_core::UserId {+ let user_id = store+ .writer+ .create_human_user(+ ai_memory_core::NewUser {+ username: username.to_string(),+ name: None,+ email: None,+ },+ ai_memory_core::UserRole::User,+ None,+ false,+ )+ .await+ .unwrap();+ let pepper = ai_memory_store::TokenPepper::new(LEGACY_TEST_PEPPER);+ store+ .writer+ .create_api_credential(+ ai_memory_core::ApiCredentialId::from_slice(user_id.as_bytes()).unwrap(),+ user_id,+ "legacy-user-token".to_string(),+ ai_memory_store::hash_token(secret, &pepper),+ None,+ )+ .await+ .unwrap();+ user_id+ }++ async fn issue_api_key(router: &Router, username: &str) -> String {+ let created = post_create_human_user(+ router,"root-token",- serde_json::json!({"username": "alice"}),+ serde_json::json!({ "username": username }),).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!(created.status(), StatusCode::OK);+ let (status, json) = admin_call(+ router,+ "POST",+ "/admin/api-credentials",+ "root-token",+ Some(serde_json::json!({ "username": username, "label": "cli" })),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ json["token"].as_str().unwrap().to_string()+ }++ /// 3.0 removed the 1.x token-management endpoints. None of them may come+ /// back for any tier: root gets a routing miss, the other tiers never get+ /// past it either, and nothing about the users or their credentials+ /// changes.+ #[tokio::test]+ async fn removed_legacy_token_routes_are_gone_for_every_tier() {+ let (_tmp, store, router) = user_admin_dual_auth_router_with_store("root-token");+ let legacy = "q0N2v1d8kQd3m6Q7e9x4Zb1a2c3d4e5f6g7h8i9j0kL";+ seed_legacy_token_user(&store, "alice", legacy).await;+ let db_user = issue_api_key(&router, "bob").await;++ let removed = [+ (+ "/admin/users",+ Some(serde_json::json!({ "username": "mallory" })),+ ),+ ("/admin/users/alice/expire", None),+ ("/admin/users/alice/revive", None),+ ("/admin/users/alice/rotate-token", None),+ ];+ for (uri, body) in removed {+ for bearer in [+ Some("root-token"),+ Some(db_user.as_str()),+ Some(legacy),+ None,+ ] {+ let mut builder = Request::builder().method("POST").uri(uri);+ if let Some(token) = bearer {+ builder = builder.header("authorization", format!("Bearer {token}"));+ }+ let request_body = match &body {+ Some(json) => {+ builder = builder.header("content-type", "application/json");+ Body::from(serde_json::to_vec(json).unwrap())+ }+ None => Body::empty(),+ };+ let status = router+ .clone()+ .oneshot(builder.body(request_body).unwrap())+ .await+ .unwrap()+ .status();+ let tier = match bearer {+ Some("root-token") => "root",+ Some(token) if token == legacy => "legacy token",+ Some(_) => "DB user",+ None => "anonymous",+ };+ // Root passes every gate and meets the routing miss itself:+ // 405 where GET /admin/users still owns the path, 404 for the+ // rest. Anonymous stops at authentication. On the shared+ // /admin/users path the root gate answers other tiers first.+ let expected = match (tier, uri) {+ ("anonymous", _) => StatusCode::UNAUTHORIZED,+ ("root", "/admin/users") => StatusCode::METHOD_NOT_ALLOWED,+ (_, "/admin/users") => StatusCode::FORBIDDEN,+ _ => StatusCode::NOT_FOUND,+ };+ assert_eq!(+ status, expected,+ "POST {uri} as {tier} must not reach a handler"+ );+ }+ }++ let (status, json) = admin_call(&router, "GET", "/admin/users", "root-token", None).await;+ assert_eq!(status, StatusCode::OK, "GET /admin/users stays mounted");+ let names: Vec<&str> = json["users"]+ .as_array()+ .unwrap()+ .iter()+ .map(|u| u["username"].as_str().unwrap())+ .collect();+ assert_eq!(names, ["alice", "bob"], "no user may be created");+ let (_, json) =+ admin_call(&router, "GET", "/admin/api-credentials", "root-token", None).await;+ for credential in json["credentials"].as_array().unwrap() {+ assert!(+ credential.get("revoked_at").is_none(),+ "no credential may be expired: {credential}"+ );+ }assert_eq!(- user_token_admin_status(&router, &original).await,+ user_token_admin_status(&router, legacy).await,StatusCode::FORBIDDEN,- "active legacy token must authenticate as a non-root DB user"+ "the legacy token must still authenticate");+ }- let expire = router- .clone()- .oneshot(- Request::builder()- .method("POST")- .uri("/admin/users/alice/expire")- .header("authorization", "Bearer root-token")- .body(Body::empty())- .unwrap(),+ /// A token issued by the removed 1.x `user add` is an ordinary API key in+ /// 3.0: it authenticates as its non-root user, an expired one stays+ /// refused, and `api-key list|rotate|revoke` manage it.+ #[tokio::test]+ async fn legacy_user_token_is_managed_as_an_api_key() {+ let (_tmp, store, router) = user_admin_dual_auth_router_with_store("root-token");+ let active = "Lw7u0Qe1r2t3y4u5i6o7p8a9s0d1f2g3h4j5k6l7z8x";+ let expired = "Mx8v1Rf2t3g4y5h6u7j8i9k0o1l2p3a4s5d6f7g8h9j";+ let alice = seed_legacy_token_user(&store, "alice", active).await;+ let carol = seed_legacy_token_user(&store, "carol", expired).await;+ // 2.x `user expire` reached `api_credentials.revoked_at` through the+ // V55 mirror; that is the state an expired token arrives in.+ store+ .writer+ .revoke_api_credential(+ ai_memory_core::ApiCredentialId::from_slice(carol.as_bytes()).unwrap(),).await.unwrap();- assert_eq!(expire.status(), StatusCode::OK);+assert_eq!(- user_token_admin_status(&router, &original).await,- StatusCode::UNAUTHORIZED+ user_token_admin_status(&router, active).await,+ StatusCode::FORBIDDEN,+ "an active legacy token authenticates as a non-root DB user");-- 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+ user_token_admin_status(&router, expired).await,+ StatusCode::UNAUTHORIZED,+ "an expired legacy token stays refused");- 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);+ let (status, json) =+ admin_call(&router, "GET", "/admin/api-credentials", "root-token", None).await;+ assert_eq!(status, StatusCode::OK);+ let listed = json["credentials"]+ .as_array()+ .unwrap()+ .iter()+ .find(|c| c["id"] == alice.to_string())+ .cloned()+ .expect("api-key list shows the legacy credential");+ assert_eq!(listed["label"], "legacy-user-token");+ assert_eq!(listed["user_id"], alice.to_string());+ assert!(listed.get("revoked_at").is_none());++ let (status, json) = admin_call(+ &router,+ "POST",+ &format!("/admin/api-credentials/{alice}/rotate"),+ "root-token",+ None,+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ let rotated = json["token"].as_str().unwrap().to_string();+ assert!(rotated.starts_with("aim_"));assert_eq!(- user_token_admin_status(&router, &original).await,- StatusCode::UNAUTHORIZED+ user_token_admin_status(&router, active).await,+ StatusCode::UNAUTHORIZED,+ "rotation retires the legacy secret");assert_eq!(- user_token_admin_status(&router, rotated).await,+ user_token_admin_status(&router, &rotated).await,StatusCode::FORBIDDEN);- }+ let (status, _) = admin_call(+ &router,+ "POST",+ &format!("/admin/api-credentials/{alice}/revoke"),+ "root-token",+ None,+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(+ user_token_admin_status(&router, &rotated).await,+ StatusCode::UNAUTHORIZED,+ "a revoked credential is refused"+ );+ }#[tokio::test]async fn create_user_rejects_duplicate_username_with_409() {let (_tmp, router) = user_admin_test_router("root-token");- let _ = post_create_user(+ let _ = post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice"}),).await;- let resp = post_create_user(+ let resp = post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice"}),@@ -14805,7 +14770,7 @@ mod tests {#[tokio::test]async fn create_user_rejects_invalid_email_with_400() {let (_tmp, router) = user_admin_test_router("root-token");- let resp = post_create_user(+ let resp = post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice", "email": "not-an-email"}),@@ -14822,7 +14787,7 @@ mod tests {.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(),@@ -14837,7 +14802,7 @@ mod tests {#[tokio::test]async fn create_user_as_user_tier_returns_403() {let (_tmp, router) = user_admin_test_router("root-token");- let resp = post_create_user(+ let resp = post_create_human_user(&router,"not-the-root-token",serde_json::json!({"username": "alice"}),@@ -14851,7 +14816,8 @@ mod tests {let (_tmp, router) = user_admin_test_router("root-token");for n in ["alice", "bob", "carol"] {let _ =- post_create_user(&router, "root-token", serde_json::json!({"username": n})).await;+ post_create_human_user(&router, "root-token", serde_json::json!({"username": n}))+ .await;}let resp = router.oneshot(@@ -14883,7 +14849,7 @@ mod tests {#[tokio::test]async fn disable_then_enable_round_trips() {let (_tmp, router) = user_admin_test_router("root-token");- let _ = post_create_user(+ let _ = post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice"}),@@ -14958,7 +14924,7 @@ mod tests {#[tokio::test]async fn grants_can_be_issued_changed_listed_and_revoked_by_root() {let (_tmp, router) = user_admin_test_router("root-token");- let _ = post_create_user(+ let _ = post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice"}),@@ -15188,7 +15154,7 @@ mod tests {#[tokio::test]async fn purging_a_project_takes_its_grants() {let (_tmp, router) = user_admin_test_router("root-token");- let _ = post_create_user(+ let _ = post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice"}),@@ -15221,7 +15187,7 @@ mod tests {#[tokio::test]async fn a_merging_move_does_not_carry_grants_to_the_destination() {let (_tmp, router) = user_admin_test_router("root-token");- let _ = post_create_user(+ let _ = post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice"}),@@ -15251,7 +15217,7 @@ mod tests {#[tokio::test]async fn deleting_a_workspace_takes_its_grants() {let (_tmp, router) = user_admin_test_router("root-token");- let _ = post_create_user(+ let _ = post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice"}),@@ -15360,7 +15326,7 @@ mod tests {#[tokio::test]async fn rotate_api_credential_issues_a_distinct_secret() {let (_tmp, router) = user_admin_test_router("root-token");- let _ = post_create_user(+ let _ = post_create_human_user(&router,"root-token",serde_json::json!({"username": "alice"}),@@ -15492,7 +15458,7 @@ mod tests {#[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(+ let created = post_create_human_user(&router,"root-token",serde_json::json!({"username": "keeper", "role": "root"}),@@ -15526,7 +15492,7 @@ mod tests {#[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(+ let created = post_create_human_user(&router,"root-token",serde_json::json!({"username": "keeper", "role": "root"}),@@ -15551,7 +15517,7 @@ mod tests {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(+ let created = post_create_human_user(&router,"root-token",serde_json::json!({"username": name, "role": "root"}),@@ -15614,7 +15580,7 @@ mod tests {#[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(+ let created = post_create_human_user(&router,"root-token",serde_json::json!({"username": "boss", "role": "root"}),diff --git a/crates/ai-memory-mcp/tests/suite/admin_metrics.rs b/crates/ai-memory-mcp/tests/suite/admin_metrics.rsindex 85c129b0..fdb96049 100644--- a/crates/ai-memory-mcp/tests/suite/admin_metrics.rs+++ b/crates/ai-memory-mcp/tests/suite/admin_metrics.rs@@ -337,15 +337,26 @@ async fn metrics_are_root_only_on_a_multi_user_server() {let h = harness().await;let create = Request::builder().method("POST")- .uri("/admin/users")+ .uri("/admin/human-users").header("authorization", format!("Bearer {ROOT}")).header("content-type", "application/json").body(Body::from(json!({ "username": "alice" }).to_string())).unwrap();let (status, created) = send(&h.router, create).await;assert_eq!(status, StatusCode::OK, "{created}");- let alice: Value = serde_json::from_str(&created).unwrap();- let alice_token = alice["token"].as_str().expect("DB-user token").to_string();+ let issue = Request::builder()+ .method("POST")+ .uri("/admin/api-credentials")+ .header("authorization", format!("Bearer {ROOT}"))+ .header("content-type", "application/json")+ .body(Body::from(+ json!({ "username": "alice", "label": "metrics" }).to_string(),+ ))+ .unwrap();+ let (status, issued) = send(&h.router, issue).await;+ assert_eq!(status, StatusCode::OK, "{issued}");+ let issued: Value = serde_json::from_str(&issued).unwrap();+ let alice_token = issued["token"].as_str().expect("DB-user token").to_string();let (status, body) = scrape(&h.router, None).await;assert_eq!(status, StatusCode::UNAUTHORIZED, "anonymous: {body}");diff --git a/crates/ai-memory-mcp/tests/suite/admin_status_search.rs b/crates/ai-memory-mcp/tests/suite/admin_status_search.rsindex 12a843a7..575be0e5 100644--- a/crates/ai-memory-mcp/tests/suite/admin_status_search.rs+++ b/crates/ai-memory-mcp/tests/suite/admin_status_search.rs@@ -265,13 +265,15 @@ async fn project_coordinate_reports_all_statuses_and_never_mutates() {};let operator = store.writer- .create_user(+ .create_human_user(NewUser {username: "operator-sentinel".into(),name: Some("private-user-sentinel".into()),email: Some("[email protected]".into()),},- [6; ai_memory_store::TOKEN_HASH_LEN],+ ai_memory_core::UserRole::User,+ None,+ false,).await.unwrap();@@ -453,13 +455,15 @@ async fn project_coordinate_is_root_only_after_multiuser_enablement() {let (state, store) = make_admin_state(&tmp).await;store.writer- .create_user(+ .create_human_user(NewUser {username: "alice".into(),name: None,email: None,},- [7; ai_memory_store::TOKEN_HASH_LEN],+ ai_memory_core::UserRole::User,+ None,+ false,).await.unwrap();diff --git a/crates/ai-memory-mcp/tests/suite/dual_key_scope.rs b/crates/ai-memory-mcp/tests/suite/dual_key_scope.rsindex f5c83f8f..17da5cf5 100644--- a/crates/ai-memory-mcp/tests/suite/dual_key_scope.rs+++ b/crates/ai-memory-mcp/tests/suite/dual_key_scope.rs@@ -25,16 +25,18 @@ struct Harness {_tmp: TempDir,}-async fn user(store: &Store, name: &str, byte: u8) -> UserId {+async fn user(store: &Store, name: &str) -> UserId {store.writer- .create_user(+ .create_human_user(NewUser {username: name.into(),name: None,email: None,},- [byte; ai_memory_store::TOKEN_HASH_LEN],+ ai_memory_core::UserRole::User,+ None,+ false,).await.unwrap()@@ -53,8 +55,8 @@ async fn harness() -> Harness {.get_or_create_project(ws, "scratch", None).await.unwrap();- let writer = user(&store, "writer", 1).await;- let reader = user(&store, "reader", 2).await;+ let writer = user(&store, "writer").await;+ let reader = user(&store, "reader").await;let project = store.writer.resolve_project_by_identity(diff --git a/crates/ai-memory-store/migrations/V79__drop_legacy_user_token_columns.sql b/crates/ai-memory-store/migrations/V79__drop_legacy_user_token_columns.sqlnew file mode 100644index 00000000..17336884--- /dev/null+++ b/crates/ai-memory-store/migrations/V79__drop_legacy_user_token_columns.sql@@ -0,0 +1,90 @@+-- Retire the 1.x compatibility-token columns (3.0).+--+-- `ai-memory user add|expire|revive|rotate-token` and their admin endpoints+-- were the only writers of `users.token_hash` and `users.token_expired_at`.+-- V55's mirror triggers copied each of those writes into the user's+-- `legacy-user-token` row in `api_credentials`, and authentication has read+-- only `api_credentials` since V55. With the commands removed, nothing reads+-- or writes either column, so both columns and the four V55 triggers on them+-- go. `api_credentials` is not touched: a token issued by the old commands+-- keeps authenticating as an ordinary API key, managed with `ai-memory+-- api-key list|rotate|revoke`.+--+-- `ALTER TABLE ... DROP COLUMN` refuses a UNIQUE column, so `users` is+-- rebuilt as V54 rebuilt it, keeping every id byte-for-byte. `Store::open`+-- turns foreign keys off around the migration runner (a PRAGMA inside+-- refinery's transaction is ignored). With them on, `DROP TABLE users` would+-- delete every credential, web session and grant through ON DELETE CASCADE+-- and null every author reference, so the guard below counts each reference+-- to a user that resolves before and after the rebuild and aborts the+-- migration, which rolls it back, if any count changed.++CREATE TABLE v79_user_refs (+ phase TEXT NOT NULL PRIMARY KEY,+ total INTEGER NOT NULL+);++INSERT INTO v79_user_refs (phase, total)+SELECT 'before',+ (SELECT COUNT(*) FROM api_credentials c JOIN users u ON u.id = c.user_id) ++ (SELECT COUNT(*) FROM web_sessions s JOIN users u ON u.id = s.user_id) ++ (SELECT COUNT(*) FROM project_grants g JOIN users u ON u.id = g.user_id) ++ (SELECT COUNT(*) FROM project_grants g JOIN users u ON u.id = g.granted_by) ++ (SELECT COUNT(*) FROM projects p JOIN users u ON u.id = p.created_by) ++ (SELECT COUNT(*) FROM pages p JOIN users u ON u.id = p.author_id) ++ (SELECT COUNT(*) FROM audit_log a JOIN users u ON u.id = a.author_id) ++ (SELECT COUNT(*) FROM page_feedback f JOIN users u ON u.id = f.author_id) ++ (SELECT COUNT(*) FROM auto_improve_proposals p JOIN users u ON u.id = p.decided_by_author_id) ++ (SELECT COUNT(*) FROM auto_improve_proposal_events e JOIN users u ON u.id = e.author_id);++DROP TRIGGER IF EXISTS users_token_hash_length_ai;+DROP TRIGGER IF EXISTS users_token_hash_length_au;+DROP TRIGGER IF EXISTS users_token_hash_mirror_ai;+DROP TRIGGER IF EXISTS users_token_hash_mirror_au;++CREATE TABLE users_new (+ id BLOB NOT NULL PRIMARY KEY,+ username TEXT NOT NULL UNIQUE,+ name TEXT,+ email TEXT UNIQUE COLLATE NOCASE,+ created_at INTEGER NOT NULL,+ last_seen_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, created_at, last_seen_at,+ role, password_hash, must_change_password, disabled_at+)+SELECT+ id, username, name, email, created_at, last_seen_at,+ role, password_hash, must_change_password, disabled_at+FROM users;++DROP TABLE users;+ALTER TABLE users_new RENAME TO users;++INSERT INTO v79_user_refs (phase, total)+SELECT 'after',+ (SELECT COUNT(*) FROM api_credentials c JOIN users u ON u.id = c.user_id) ++ (SELECT COUNT(*) FROM web_sessions s JOIN users u ON u.id = s.user_id) ++ (SELECT COUNT(*) FROM project_grants g JOIN users u ON u.id = g.user_id) ++ (SELECT COUNT(*) FROM project_grants g JOIN users u ON u.id = g.granted_by) ++ (SELECT COUNT(*) FROM projects p JOIN users u ON u.id = p.created_by) ++ (SELECT COUNT(*) FROM pages p JOIN users u ON u.id = p.author_id) ++ (SELECT COUNT(*) FROM audit_log a JOIN users u ON u.id = a.author_id) ++ (SELECT COUNT(*) FROM page_feedback f JOIN users u ON u.id = f.author_id) ++ (SELECT COUNT(*) FROM auto_improve_proposals p JOIN users u ON u.id = p.decided_by_author_id) ++ (SELECT COUNT(*) FROM auto_improve_proposal_events e JOIN users u ON u.id = e.author_id);++CREATE TABLE v79_user_refs_guard (+ ok INTEGER NOT NULL CHECK (ok = 0)+);+INSERT INTO v79_user_refs_guard (ok)+SELECT (SELECT total FROM v79_user_refs WHERE phase = 'after')+ - (SELECT total FROM v79_user_refs WHERE phase = 'before');+DROP TABLE v79_user_refs_guard;+DROP TABLE v79_user_refs;diff --git a/crates/ai-memory-store/src/api_credentials.rs b/crates/ai-memory-store/src/api_credentials.rsindex e7bddba3..c2c6b978 100644--- a/crates/ai-memory-store/src/api_credentials.rs+++ b/crates/ai-memory-store/src/api_credentials.rs@@ -1,4 +1,5 @@-//! Native `aim_` API credentials. Auth lookup never reads `users.token_hash`.+//! Native `aim_` API credentials, plus the `legacy-user-token` rows V55+//! copied from 1.x compatibility tokens. Auth reads only this table.use ai_memory_core::{ApiCredential, ApiCredentialId, NATIVE_API_KEY_PREFIX, User, UserId};use base64::Engine;@@ -135,18 +136,17 @@ pub fn find_active_user_by_token_hash() -> 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 \+ u.role, u.must_change_password, u.disabled_at, u.password_hash, 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 cred_bytes: Vec<u8> = row.get(10)?;let credential_id = ApiCredentialId::from_slice(&cred_bytes).map_err(|e| {rusqlite::Error::FromSqlConversionFailure(- 11,+ 10,rusqlite::types::Type::Blob,Box::new(std::io::Error::other(e.to_string())),)@@ -389,7 +389,9 @@ mod tests {).unwrap();assert_eq!(copied, hash);+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();crate::migrations::run(&mut conn).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();assert!(find_active_user_by_token_hash(&conn, &hash, 0).unwrap()@@ -411,15 +413,193 @@ mod tests {|row| row.get(0),).unwrap();- assert_eq!(version, 78, "update the pin when adding a migration");+ assert_eq!(version, 79, "update the pin when adding a migration");let cols: i64 = conn.query_row(- "SELECT COUNT(*) FROM pragma_table_info('users') WHERE name = 'token_hash'",+ "SELECT COUNT(*) FROM pragma_table_info('users') \+ WHERE name IN ('token_hash', 'token_expired_at')",[],|row| row.get(0),).unwrap();- assert_eq!(cols, 1);+ assert_eq!(cols, 0, "V79 drops the 1.x token columns");+ }++ fn column_count(conn: &Connection, table: &str, column: &str) -> i64 {+ conn.query_row(+ "SELECT COUNT(*) FROM pragma_table_info(?1) WHERE name = ?2",+ params![table, column],+ |row| row.get(0),+ )+ .unwrap()+ }++ fn legacy_trigger_count(conn: &Connection) -> i64 {+ conn.query_row(+ "SELECT COUNT(*) FROM sqlite_master \+ WHERE type = 'trigger' AND name LIKE 'users_token_hash_%'",+ [],+ |row| row.get(0),+ )+ .unwrap()+ }++ /// Seed a user exactly as 2.x `user add` did: the token lands in+ /// `users.token_hash`, and V55's mirror trigger copies it into the+ /// user's `legacy-user-token` credential.+ fn insert_2x_token_user(conn: &Connection, username: &str, hash: &[u8; 32]) -> UserId {+ let id = UserId::new();+ conn.execute(+ "INSERT INTO users (id, username, name, email, token_hash, created_at) \+ VALUES (?1, ?2, NULL, NULL, ?3, 1)",+ params![id.as_bytes(), username, hash.as_slice()],+ )+ .unwrap();+ id+ }++ /// The 3.0 upgrade: a database in the last 2.x shape (V78) holding+ /// tokens issued, expired and rotated by the removed `user` commands.+ /// After V79 every token that authenticated before still does, an+ /// expired one stays refused, `api-key list|rotate|revoke` manage them,+ /// and the rows that point at those users survive the `users` rebuild.+ #[test]+ fn v79_upgrade_keeps_legacy_tokens_as_api_keys() {+ let mut conn = open_to(78);+ let pepper = TokenPepper::new("test-pepper-1234567890abcdef");+ let alice_hash = hash_token("alice-1x-token", &pepper);+ let bob_hash = hash_token("bob-1x-token", &pepper);+ let carol_old = hash_token("carol-1x-token", &pepper);+ let carol_new = hash_token("carol-1x-token-rotated", &pepper);+ let alice = insert_2x_token_user(&conn, "alice", &alice_hash);+ let bob = insert_2x_token_user(&conn, "bob", &bob_hash);+ let carol = insert_2x_token_user(&conn, "carol", &carol_old);+ // 2.x `user expire bob`, then `user rotate-token carol`.+ conn.execute(+ "UPDATE users SET token_expired_at = 77 WHERE id = ?1",+ params![bob.as_bytes()],+ )+ .unwrap();+ conn.execute(+ "UPDATE users SET token_hash = ?1, token_expired_at = NULL WHERE id = ?2",+ params![carol_new.as_slice(), carol.as_bytes()],+ )+ .unwrap();+ let session =+ crate::web_sessions::insert_web_session(&conn, alice, &[3; 32], &[4; 32]).unwrap();+ assert_eq!(legacy_trigger_count(&conn), 4);++ // Store::open's order: foreign keys off around the runner.+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();+ crate::migrations::run(&mut conn).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();++ assert_eq!(column_count(&conn, "users", "token_hash"), 0);+ assert_eq!(column_count(&conn, "users", "token_expired_at"), 0);+ assert_eq!(legacy_trigger_count(&conn), 0);++ let found = find_active_user_by_token_hash(&conn, &alice_hash, 0)+ .unwrap()+ .expect("an active 2.x token still authenticates");+ assert_eq!(found.user.id, alice);+ assert_eq!(found.user.username, "alice");+ assert_eq!(found.credential_id.as_bytes(), alice.as_bytes());+ assert!(+ find_active_user_by_token_hash(&conn, &bob_hash, 0)+ .unwrap()+ .is_none(),+ "an expired 2.x token stays refused"+ );+ assert!(+ find_active_user_by_token_hash(&conn, &carol_old, 0)+ .unwrap()+ .is_none()+ );+ assert_eq!(+ find_active_user_by_token_hash(&conn, &carol_new, 0)+ .unwrap()+ .unwrap()+ .user+ .id,+ carol+ );++ let listed = list_api_credentials(&conn).unwrap();+ assert_eq!(listed.len(), 3, "api-key list shows every legacy token");+ for credential in &listed {+ assert_eq!(credential.label, "legacy-user-token");+ assert_eq!(credential.id.as_bytes(), credential.user_id.as_bytes());+ assert_eq!(+ credential.revoked_at.is_some(),+ credential.user_id == bob,+ "only the expired token is revoked: {credential:?}"+ );+ }++ let alice_cred = ApiCredentialId::from_slice(alice.as_bytes()).unwrap();+ let rotated = hash_token("aim_rotated-after-upgrade", &pepper);+ assert!(rotate_api_credential(&conn, alice_cred, &rotated, Some("…rade")).unwrap());+ assert!(+ find_active_user_by_token_hash(&conn, &alice_hash, 0)+ .unwrap()+ .is_none()+ );+ assert!(+ find_active_user_by_token_hash(&conn, &rotated, 0)+ .unwrap()+ .is_some()+ );+ let carol_cred = ApiCredentialId::from_slice(carol.as_bytes()).unwrap();+ assert!(revoke_api_credential(&conn, carol_cred).unwrap());+ assert!(+ find_active_user_by_token_hash(&conn, &carol_new, 0)+ .unwrap()+ .is_none(),+ "a revoked legacy token is refused"+ );++ let live = crate::web_sessions::find_live_session_by_hash(&conn, &[3; 32], 0)+ .unwrap()+ .expect("the rebuild keeps web sessions");+ assert_eq!(live.id, session.id);+ assert_eq!(live.user.id, alice);+ let violations: i64 = conn+ .query_row("SELECT COUNT(*) FROM pragma_foreign_key_check", [], |row| {+ row.get(0)+ })+ .unwrap();+ assert_eq!(violations, 0);+ }++ /// Recovery: run with foreign keys on, `DROP TABLE users` would cascade+ /// through every credential. The guard must abort V79 instead, and the+ /// rollback must leave the 2.x database, and its tokens, as they were.+ #[test]+ fn v79_rolls_back_rather_than_cascade_delete_credentials() {+ let mut conn = open_to(78);+ let hash = [0x5Au8; 32];+ let alice = insert_2x_token_user(&conn, "alice", &hash);++ let error = crate::migrations::run_to(&mut conn, 79)+ .expect_err("V79 must abort when the rebuild would lose a credential");+ assert!(+ error.to_string().contains("CHECK constraint failed"),+ "unexpected V79 error: {error}"+ );+ let version: i64 = conn+ .query_row(+ "SELECT MAX(version) FROM refinery_schema_history",+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(version, 78, "the failed V79 must roll back");+ assert_eq!(column_count(&conn, "users", "token_hash"), 1);+ assert_eq!(legacy_trigger_count(&conn), 4);+ let found = find_active_user_by_token_hash(&conn, &hash, 0)+ .unwrap()+ .expect("the token survives the aborted upgrade");+ assert_eq!(found.user.id, alice);}#[test]diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 67f40b89..a4b1fd65 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -107,9 +107,7 @@ pub use scope::{resolve_many_existing_scopes, resolve_many_existing_scopes_guarded,};pub use session_consolidation::{SESSION_CONSOLIDATION_MAX_ATTEMPTS, SessionConsolidationJob};-pub use users::{- LoginUser, TOKEN_HASH_LEN, TOKEN_RAW_LEN, TokenPepper, generate_token, hash_token,-};+pub use users::{LoginUser, TOKEN_HASH_LEN, TOKEN_RAW_LEN, TokenPepper, hash_token};pub use web_sessions::{LiveWebSession, WebSession, hash_session_secret};pub use workstream::{FinishWorkstreamRun, FinishedWorkstreamRun, LinkManagedRunSessionInScope,diff --git a/crates/ai-memory-store/src/scope.rs b/crates/ai-memory-store/src/scope.rsindex d39ff86b..3bf741bf 100644--- a/crates/ai-memory-store/src/scope.rs+++ b/crates/ai-memory-store/src/scope.rs@@ -1596,16 +1596,18 @@ mod tests {assert_eq!(written.scope.project_id, secret);}- async fn user_named(store: &Store, username: &str, byte: u8) -> UserId {+ async fn user_named(store: &Store, username: &str) -> UserId {store.writer- .create_user(+ .create_human_user(NewUser {username: username.to_owned(),name: None,email: None,},- [byte; crate::TOKEN_HASH_LEN],+ ai_memory_core::UserRole::User,+ None,+ false,).await.unwrap()@@ -1630,8 +1632,8 @@ mod tests {.get_or_create_project(ws, "client-work", None).await.unwrap();- let alice = user_named(store, "alice", 1).await;- let bob = user_named(store, "bob", 2).await;+ let alice = user_named(store, "alice").await;+ let bob = user_named(store, "bob").await;(ws, project, alice, bob)}diff --git a/crates/ai-memory-store/src/users.rs b/crates/ai-memory-store/src/users.rsindex a1352f50..2f0b772a 100644--- a/crates/ai-memory-store/src/users.rs+++ b/crates/ai-memory-store/src/users.rs@@ -5,8 +5,6 @@//! KDF — see [`crate::password`].use ai_memory_core::{NewUser, User, UserId, UserRole};-use base64::Engine;-use base64::engine::general_purpose::URL_SAFE_NO_PAD;use jiff::Timestamp;use rusqlite::{Connection, OptionalExtension, params};use sha2::{Digest, Sha256};@@ -55,19 +53,6 @@ pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {a.ct_eq(b).into()}-/// 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-/// [`StoreError::Os`] if the OS CSPRNG fails.-pub fn generate_token() -> StoreResult<String> {- let mut bytes = [0u8; TOKEN_RAW_LEN];- getrandom::fill(&mut bytes)- .map_err(|e| StoreError::Os(format!("os csprng failed during token generation: {e}")))?;- Ok(URL_SAFE_NO_PAD.encode(bytes))-}-/// Login lookup: public user plus the stored PHC (never serialised).#[derive(Debug, Clone)]pub struct LoginUser {@@ -77,77 +62,6 @@ pub struct LoginUser {pub password_hash: Option<String>,}-/// 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-/// Duplicate username/email/token or SQL.-pub fn insert_user(- conn: &Connection,- new_user: &NewUser,- token_hash: &[u8; TOKEN_HASH_LEN],-) -> StoreResult<UserId> {- let id = UserId::new();- let now = Timestamp::now().as_microsecond();- conn.execute(- "INSERT INTO users \- (id, username, name, email, token_hash, created_at) \- VALUES (?1, ?2, ?3, ?4, ?5, ?6)",- params![- id.as_bytes(),- &new_user.username,- &new_user.name,- &new_user.email,- token_hash.as_slice(),- now,- ],- )- .map_err(map_unique_violation)?;- Ok(id)-}--/// Replace and reactivate the deprecated single-token credential.-///-/// # Errors-/// SQL failures.-pub fn rotate_user_token(- conn: &Connection,- id: UserId,- new_token_hash: &[u8; TOKEN_HASH_LEN],-) -> StoreResult<bool> {- let rows = conn.execute(- "UPDATE users SET token_hash = ?1, token_expired_at = NULL WHERE id = ?2",- params![new_token_hash.as_slice(), id.as_bytes()],- )?;- Ok(rows > 0)-}--/// Idempotently revoke the deprecated single-token credential.-///-/// # Errors-/// SQL failures.-pub fn expire_user_token(conn: &Connection, id: UserId) -> StoreResult<bool> {- let now = Timestamp::now().as_microsecond();- let rows = conn.execute(- "UPDATE users SET token_expired_at = COALESCE(token_expired_at, ?1) WHERE id = ?2",- params![now, id.as_bytes()],- )?;- Ok(rows > 0)-}--/// Idempotently reactivate the deprecated single-token credential.-///-/// # Errors-/// 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",- params![id.as_bytes()],- )?;- Ok(rows > 0)-}-/// Insert a human identity. `password_hash` is already Argon2id PHC (or/// `None` for API-only brownfield-style rows). No API credential is created.///@@ -499,7 +413,7 @@ pub fn touch_user_last_seen(conn: &Connection, id: UserId) -> StoreResult<bool>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, \- role, must_change_password, disabled_at, password_hash, token_expired_at \+ role, must_change_password, disabled_at, password_hash \FROM users WHERE username = ?1",params![username],|row| row_to_user(row, 0),@@ -515,7 +429,7 @@ pub fn find_user_by_username(conn: &Connection, username: &str) -> StoreResult<Opub 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, \- role, must_change_password, disabled_at, password_hash, token_expired_at \+ role, must_change_password, disabled_at, password_hash \FROM users WHERE id = ?1",params![id.as_bytes()],|row| row_to_user(row, 0),@@ -534,7 +448,7 @@ pub fn find_login_user_by_username() -> StoreResult<Option<LoginUser>> {conn.query_row("SELECT id, username, name, email, created_at, last_seen_at, \- role, must_change_password, disabled_at, password_hash, token_expired_at \+ role, must_change_password, disabled_at, password_hash \FROM users WHERE username = ?1",params![username],|row| {@@ -556,7 +470,7 @@ pub fn find_login_user_by_username(pub fn list_users(conn: &Connection) -> StoreResult<Vec<User>> {let mut stmt = conn.prepare("SELECT id, username, name, email, created_at, last_seen_at, \- role, must_change_password, disabled_at, password_hash, token_expired_at \+ role, must_change_password, disabled_at, password_hash \FROM users ORDER BY created_at ASC",)?;let rows = stmt@@ -667,8 +581,8 @@ pub(crate) 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`.+/// Decode a user row starting at `offset`. Relative column 9 is+/// `password_hash`, read only to derive `has_password`.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| {@@ -695,7 +609,6 @@ pub(crate) fn row_to_user(row: &rusqlite::Row<'_>, offset: usize) -> rusqlite::Remail: 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)?,@@ -959,7 +872,9 @@ mod tests {assert_eq!(role, "user");assert_eq!(token, hash);assert_eq!(bootstrap, 0);+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();crate::migrations::run(&mut conn).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();let user = find_user_by_id(&conn, id).unwrap().unwrap();assert!(!user.has_password);assert_eq!(user.username, "alice");diff --git a/crates/ai-memory-store/src/web_sessions.rs b/crates/ai-memory-store/src/web_sessions.rsindex f00098d7..9166896d 100644--- a/crates/ai-memory-store/src/web_sessions.rs+++ b/crates/ai-memory-store/src/web_sessions.rs@@ -184,8 +184,7 @@ pub fn find_live_session_by_hash(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 \+ u.role, u.must_change_password, u.disabled_at, u.password_hash \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",diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 9e99fbcc..ab72c425 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -612,11 +612,6 @@ pub(crate) enum WriteCmd {password_hash: String,reply: oneshot::Sender<StoreResult<UserId>>,},- CreateUser {- new_user: NewUser,- token_hash: [u8; TOKEN_HASH_LEN],- reply: oneshot::Sender<StoreResult<UserId>>,- },GrantMemory {user_id: UserId,repository_id: ProjectId,@@ -630,19 +625,6 @@ pub(crate) enum WriteCmd {revoked_by: Option<UserId>,reply: oneshot::Sender<StoreResult<bool>>,},- RotateUserToken {- user_id: UserId,- token_hash: [u8; TOKEN_HASH_LEN],- reply: oneshot::Sender<StoreResult<bool>>,- },- ExpireUserToken {- user_id: UserId,- reply: oneshot::Sender<StoreResult<bool>>,- },- ReviveUserToken {- user_id: UserId,- reply: oneshot::Sender<StoreResult<bool>>,- },CreateHumanUser {new_user: NewUser,role: UserRole,@@ -2871,66 +2853,6 @@ impl WriterHandle {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,- token_hash: [u8; TOKEN_HASH_LEN],- ) -> StoreResult<UserId> {- let (tx, rx) = oneshot::channel();- self.send(WriteCmd::CreateUser {- new_user,- token_hash,- reply: tx,- })- .await?;- rx.await.map_err(|_| StoreError::WriterClosed)?- }-- /// Rotate and reactivate a user's deprecated single-token credential.- ///- /// # Errors- /// Writer closed or SQL.- pub async fn rotate_user_token(- &self,- user_id: UserId,- token_hash: [u8; TOKEN_HASH_LEN],- ) -> StoreResult<bool> {- let (tx, rx) = oneshot::channel();- self.send(WriteCmd::RotateUserToken {- user_id,- token_hash,- reply: tx,- })- .await?;- rx.await.map_err(|_| StoreError::WriterClosed)?- }-- /// Revoke a user's deprecated single-token credential.- ///- /// # Errors- /// 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 })- .await?;- rx.await.map_err(|_| StoreError::WriterClosed)?- }-- /// Reactivate a user's deprecated single-token credential.- ///- /// # Errors- /// 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 })- .await?;- rx.await.map_err(|_| StoreError::WriterClosed)?- }-/// Insert a human identity. `new_user` MUST already have been validated./// No API credential is created.///@@ -4485,14 +4407,6 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {);send_or_warn(reply, result, "recover_root");}- WriteCmd::CreateUser {- new_user,- token_hash,- reply,- } => {- let result = users::insert_user(&conn, &new_user, &token_hash);- send_or_warn(reply, result, "create_user");- }WriteCmd::GrantMemory {user_id,repository_id,@@ -4525,22 +4439,6 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {);send_or_warn(reply, result, "revoke_memory");}- WriteCmd::RotateUserToken {- user_id,- token_hash,- reply,- } => {- let result = users::rotate_user_token(&conn, user_id, &token_hash);- send_or_warn(reply, result, "rotate_user_token");- }- WriteCmd::ExpireUserToken { user_id, reply } => {- let result = users::expire_user_token(&conn, user_id);- send_or_warn(reply, result, "expire_user_token");- }- WriteCmd::ReviveUserToken { user_id, reply } => {- let result = users::revive_user_token(&conn, user_id);- send_or_warn(reply, result, "revive_user_token");- }WriteCmd::CreateHumanUser {new_user,role,diff --git a/crates/ai-memory-store/tests/suite/access_mode.rs b/crates/ai-memory-store/tests/suite/access_mode.rsindex 493b8ccb..7fcbc21a 100644--- a/crates/ai-memory-store/tests/suite/access_mode.rs+++ b/crates/ai-memory-store/tests/suite/access_mode.rs@@ -53,16 +53,18 @@ fn page(}}-async fn user(store: &Store, name: &str, byte: u8) -> UserId {+async fn user(store: &Store, name: &str) -> UserId {store.writer- .create_user(+ .create_human_user(NewUser {username: name.to_owned(),name: None,email: None,},- [byte; ai_memory_store::TOKEN_HASH_LEN],+ ai_memory_core::UserRole::User,+ None,+ false,).await.unwrap()@@ -91,9 +93,9 @@ async fn fixture() -> Fixture {.get_or_create_project(ws, "client-work", None).await.unwrap();- let reader = user(&store, "ray", 1).await;- let writer = user(&store, "wren", 2).await;- let outsider = user(&store, "otto", 3).await;+ let reader = user(&store, "ray").await;+ let writer = user(&store, "wren").await;+ let outsider = user(&store, "otto").await;store.writer.grant_memory(reader, project, GrantLevel::Read, None)diff --git a/crates/ai-memory-store/tests/suite/identity_resolution.rs b/crates/ai-memory-store/tests/suite/identity_resolution.rsindex 289ebc05..e2f75ded 100644--- a/crates/ai-memory-store/tests/suite/identity_resolution.rs+++ b/crates/ai-memory-store/tests/suite/identity_resolution.rs@@ -37,16 +37,18 @@ async fn workspace(store: &Store) -> WorkspaceId {.unwrap()}-async fn user(store: &Store, name: &str, byte: u8) -> UserId {+async fn user(store: &Store, name: &str) -> UserId {store.writer- .create_user(+ .create_human_user(NewUser {username: name.to_owned(),name: None,email: None,},- [byte; ai_memory_store::TOKEN_HASH_LEN],+ ai_memory_core::UserRole::User,+ None,+ false,).await.unwrap()@@ -220,8 +222,8 @@ async fn an_outsider_cannot_take_an_unclaimed_projects_identity() {.set_access_mode(team_project, ai_memory_store::AccessMode::Restricted).await.unwrap();- let member = user(&store, "member", 1).await;- let outsider = user(&store, "outsider", 2).await;+ let member = user(&store, "member").await;+ let outsider = user(&store, "outsider").await;store.writer.grant_memory(member, team_project, GrantLevel::Write, None)@@ -277,8 +279,8 @@ async fn a_created_or_split_project_admits_its_creator() {.await.unwrap();let ws = workspace(&store).await;- let alice = user(&store, "alice", 1).await;- let bob = user(&store, "bob", 2).await;+ let alice = user(&store, "alice").await;+ let bob = user(&store, "bob").await;let (a, how) = resolve(&store,@@ -613,7 +615,7 @@ async fn unauthorized_capture_cannot_claim_or_promote_an_identityless_legacy_nam.set_access_mode(project, AccessMode::Restricted).await.unwrap();- let outsider = user(&store, "claim-promotion-outsider", 32).await;+ let outsider = user(&store, "claim-promotion-outsider").await;let (resolved, how) = resolve_capture(&store,@@ -643,7 +645,7 @@ async fn unauthorized_capture_resolves_but_cannot_promote_a_legacy_name() {.set_access_mode(project, AccessMode::Restricted).await.unwrap();- let outsider = user(&store, "promotion-outsider", 33).await;+ let outsider = user(&store, "promotion-outsider").await;let (resolved, how) = resolve_capture(&store,@@ -712,7 +714,7 @@ async fn marker_aliases_require_same_remote_identity_and_preserve_uuid() {.set_access_mode(project, AccessMode::Restricted).await.unwrap();- let writer = user(&store, "alias-writer", 7).await;+ let writer = user(&store, "alias-writer").await;store.writer.grant_memory(writer, project, GrantLevel::Write, None)@@ -737,7 +739,7 @@ async fn marker_aliases_require_same_remote_identity_and_preserve_uuid() {"read does not rename");- let outsider = user(&store, "alias-outsider", 8).await;+ let outsider = user(&store, "alias-outsider").await;let refused = store.writer.resolve_project_aliases_for_write(@@ -1180,7 +1182,7 @@ async fn authorized_write_promotes_in_place_and_preserves_dependents_and_legacy_let tmp = tempfile::TempDir::new().unwrap();let store = Store::open(tmp.path()).unwrap();let ws = workspace(&store).await;- let owner = user(&store, "promotion-owner", 7).await;+ let owner = user(&store, "promotion-owner").await;let project = resolve(&store,ws,@@ -1353,8 +1355,8 @@ async fn read_only_user_cannot_promote_a_legacy_name() {let tmp = tempfile::TempDir::new().unwrap();let store = Store::open(tmp.path()).unwrap();let ws = workspace(&store).await;- let owner = user(&store, "promotion-owner", 8).await;- let reader = user(&store, "promotion-reader", 9).await;+ let owner = user(&store, "promotion-owner").await;+ let reader = user(&store, "promotion-reader").await;let project = resolve(&store,ws,@@ -1459,7 +1461,7 @@ async fn audit_failure_rolls_back_promotion_and_keeps_the_writer_alive() {.upsert_page(preserved_page(ws, project)).await.unwrap();- let owner = user(&store, "rollback-owner", 31).await;+ let owner = user(&store, "rollback-owner").await;store.writer.grant_memory(owner, project, GrantLevel::Write, None)diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rsindex 51e58bfb..ca221c1f 100644--- a/crates/ai-memory-store/tests/suite/multi_session.rs+++ b/crates/ai-memory-store/tests/suite/multi_session.rs@@ -300,25 +300,29 @@ async fn two_operators_promote_two_clone_keys_to_one_uuid_without_moving_active_.0;let alice = store.writer- .create_user(+ .create_human_user(NewUser {username: "alice-promotion".into(),name: None,email: None,},- [41; ai_memory_store::TOKEN_HASH_LEN],+ ai_memory_core::UserRole::User,+ None,+ false,).await.unwrap();let bob = store.writer- .create_user(+ .create_human_user(NewUser {username: "bob-promotion".into(),name: None,email: None,},- [42; ai_memory_store::TOKEN_HASH_LEN],+ ai_memory_core::UserRole::User,+ None,+ false,).await.unwrap();diff --git a/crates/ai-memory-store/tests/suite/related_walk.rs b/crates/ai-memory-store/tests/suite/related_walk.rsindex 953990c6..f1d34190 100644--- a/crates/ai-memory-store/tests/suite/related_walk.rs+++ b/crates/ai-memory-store/tests/suite/related_walk.rs@@ -393,13 +393,15 @@ async fn the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read() {}let viewer = store.writer- .create_user(+ .create_human_user(NewUser {username: "vera".into(),name: None,email: None,},- [7; ai_memory_store::TOKEN_HASH_LEN],+ ai_memory_core::UserRole::User,+ None,+ false,).await.unwrap();diff --git a/crates/ai-memory-web/tests/suite/routes.rs b/crates/ai-memory-web/tests/suite/routes.rsindex cd08bb04..67b84324 100644--- a/crates/ai-memory-web/tests/suite/routes.rs+++ b/crates/ai-memory-web/tests/suite/routes.rs@@ -3242,7 +3242,7 @@ async fn api_v1_etag_differs_between_anonymous_and_attributed_writes() {// Regression guard: the ETag must invalidate when author changes// even if the body stays the same. Otherwise a client cached the// "anonymous" view of a page wouldn't see the attribution flip- // after the operator runs `rotate-token` + re-writes the page.+ // after the operator runs `api-key rotate` + re-writes the page.let (_tmp, store, wiki) = setup().await;let ws = store.writerdiff --git a/docs/install.md b/docs/install.mdindex 00519b74..7fbe8c03 100644--- a/docs/install.md+++ b/docs/install.md@@ -2813,8 +2813,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand 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 |+| `api-key add` / `list` / `rotate` / `revoke` | `docker exec` or native binary | Native `aim_` machine credentials, plus the `legacy-user-token` keys left by the 1.x `user add` (removed in 3.0) || `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 |diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex d12d7f99..2d867b95 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -37,6 +37,7 @@ means the boundary is not built yet.| 3c | Public human-auth routes refuse bodies a foreign page can send without a preflight (login CSRF, password guessing, root recovery) | `ai-memory-mcp/src/human_auth.rs` `handle_login` / `handle_recovery` read their bodies by hand (to rate-limit first), so each checks `declares_json_body` before reading: a `Content-Type` other than `application/json` or `application/*+json` (parameters and case ignored), or none, → 415 before any password or recovery-token check and without charging the per-IP failure budget. `text/plain`, form-urlencoded and multipart are the only bodies a cross-site page can `POST` without a preflight, and `/auth/*` carries no CORS layer. The built-in login page, the `docs/frontend-api.md` examples and the recovery `curl` in `docs/install.md` send `application/json` | `human_auth.rs` `public_auth_routes_refuse_preflight_free_browser_bodies`: valid root credentials and a valid recovery token, sent from a foreign origin as `text/plain`, form-urlencoded, multipart and with no content type, more times than the per-IP failure budget → 415, no session cookie; controls: a same-origin JSON login then succeeds (password unchanged, budget untouched) and a JSON recovery returns 204. `json_body_declaration` (header table) | STRONG. Bite check: with the check removed, the `text/plain` login returns 200 with the session cookie (the pre-fix behaviour) and the test fails. `/auth/password` and `/auth/logout` were already closed: they run behind `require_session`, whose unsafe methods need the `x-csrf-token` header (a custom header, so preflighted), and `/auth/password` also uses axum `Json` || 3d | `GET /admin/metrics` is root-only on a multi-user server and content-free | `ai-memory-mcp/src/admin.rs` mounts `/admin/metrics` inside the operational router under `require_root_for_multiuser_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`); `ai-memory-mcp/src/metrics.rs` `render_prometheus` writes only counts and durations under compile-time metric names and the closed label set `result` / `outcome` / `kind` / `le`; `McpMetrics::record_tool_call` takes only a read/write bit (no client name); `ai-memory-core/src/latency.rs` `LatencyHistogram` holds bucket counts and a sum, nothing keyed on a request; scope is never a label | mcp `integration::admin_metrics` `metrics_count_queries_and_hooks_without_leaking_any_content` (secret-shaped strings planted in a `memory_query` query, a `/hook` prompt and the project name never appear in the scrape, nor do the session id, workspace name or root token; every label key is from the closed set; control: the query and hook histograms, the accepted-hook counter and the read tool-call counter move by exactly what was sent), `metrics_are_root_only_on_a_multi_user_server` (production `require_dual_auth` with a real DB-user key: anonymous 401, DB user 403, unknown bearer 401, root control 200); `admin.rs` `multiuser_admin_routes_reject_db_user_tier` / `…reject_anonymous` include the route, `multiuser_operational_admin_routes_allow_root` admits root | STRONG. Bite checks: with the route mounted outside the gate the three refusal tests fail; with the query, the project name or the hook body rendered as a label value the leak test fails on each || 3e | The web health panel is root-only on a multi-user server, read-only and content-free | `ai-memory-web/src/routes/mod.rs` `require_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`, shared with `/web/pending`; `html_auth.rs` `AdminRequired` keeps a non-root 403 off the change-password redirect) gates `GET {web_slug}/health`, a GET-only route; `routes/health.rs` renders only counters, timestamps and configured provider/model labels, `provider_line` leaves out `last_error_message` (it can quote a response body), and the process side comes through `health::HealthProbe` as counts (`ServeHealthProbe` in `ai-memory-cli/src/commands/serve.rs` drops the journal's error text); the response is `Cache-Control: private, no-store` | `ai-memory-web` `tests/suite/health.rs` — `health_page_refuses_anonymous_once_operators_are_distinguished` (401, login redirect on navigation, no counters or fix lines), `health_page_refuses_a_db_user_and_admits_root` (403 "Root access required", no redirect, no counters; root control 200), `health_page_follows_the_admin_gate_on_a_single_operator_server` (control), `health_page_carries_no_secret_material` (secret-shaped strings planted in a failed LLM call's and a failed embed's provider error body, a page body, a page title and the project name never appear), `health_page_has_no_write_route` (POST/PUT/DELETE 405), plus a fixture per rendered check (`health_page_renders_each_failing_check_with_its_fix_line`, `health_page_renders_pending_spool_and_journal_checks`, `health_page_reports_a_healthy_server_as_passing`, and `src/health.rs` unit tests for every check id) | STRONG. Bite checks: with the `require_admin` call removed from the handler, the anonymous and DB-user tests fail; with `last_error_message` appended to the provider line, the planted-secret test fails |+| 3f | The 1.x token-management surface stays removed, and tokens it issued stay ordinary API keys (3.0) | `ai-memory-mcp/src/admin.rs` mounts only `GET /admin/users` on that path and no `/admin/users/{name}/expire`, `/revive` or `/rotate-token` route; `ai-memory-store` migration `V79__drop_legacy_user_token_columns.sql` drops `users.token_hash` / `token_expired_at` and the V55 mirror triggers, with a guard that aborts the migration if the `users` rebuild would lose any resolving reference to a user (credentials, sessions, grants, authors); authentication reads only `api_credentials` (`api_credentials.rs` `find_active_user_by_token_hash`, `revoked_at` and `expires_at` honored) | `admin.rs` `removed_legacy_token_routes_are_gone_for_every_tier` (production `require_dual_auth`; each removed route as root: 405 on `POST /admin/users`, 404 on the rest; as a DB user and as a legacy-token holder: 403 on `POST /admin/users`, 404 on the rest; anonymous 401; afterwards no user was created, no credential revoked, and the legacy token still authenticates), `legacy_user_token_is_managed_as_an_api_key` (an unprefixed legacy token authenticates as a non-root user, an expired one is 401, `api-key list` shows it as `legacy-user-token`, rotate retires the old secret, revoke refuses the new one); `ai-memory-store` `api_credentials.rs` `v79_upgrade_keeps_legacy_tokens_as_api_keys` (a V78 database seeded the 2.x way with active, expired and rotated tokens plus a web session: after V79 the active and rotated tokens authenticate, the expired and superseded ones do not, all three list as `legacy-user-token`, rotate/revoke work, the session survives, no FK violation) and `v79_rolls_back_rather_than_cascade_delete_credentials` (run with foreign keys on, V79 aborts and leaves the V78 schema and the token intact); `ai-memory-cli` `removed_user_token_commands_no_longer_parse` | STRONG. Bite checks: with a stub `POST /admin/users/{name}/expire` route mounted the route test fails; without V79 the upgrade test and the schema pin fail; without the guard the rollback test fails || 4 | Handoff single-claim / no-steal | `ai-memory-store/src/ops.rs` `accept_handoff_in_transaction` (metadata `state='open'` guard + atomic CAS; the receiver-session check, which requires the receiving session to exist in the claim's own workspace, project and agent kind and refuses with `InvalidState` before the handoff row is touched; an ended receiver is final EXCEPT for the agents where `AgentKind::reuses_session_id_after_end()` holds — Grok and Kimi Code, whose harnesses reuse the native session id across SessionEnd→resume, so accepting reopens `ended_at` only after the claim-once guard) | `multi_session.rs` `a_second_accept_cannot_steal_an_accepted_handoff`; `handoff_ownership.rs` `another_operator_cannot_claim_the_handoff`; `multi_session.rs` `handoff_accept_rejects_foreign_or_missing_receiver_session` (receivers from a sibling project, another workspace, a different agent kind, and a nonexistent session are each refused as `InvalidState` with the handoff left open and every `accepted_*` column NULL; the matching receiver claims it; the same receiver retrying and a second matching session get `false` with the first claim intact; fails with the `project_id` or `agent_kind` predicate, or the missing-session refusal, removed. The `workspace_id` predicate is redundant defence in depth: project ids are globally unique, so the cross-workspace receiver is already caught by `project_id`); `multi_session.rs` `accept_reopens_an_ended_receiver_session_but_keeps_claim_once` (Grok reopen + no-steal) and `accept_reopens_an_ended_kimi_receiver_but_keeps_every_guard` (Kimi Code resume claims and reopens `ended_at`; adversarial controls: an ended claude-code receiver stays refused, a kimi-code receiver in another project stays refused, and the already-claimed guard still refuses the resumed kimi session a second baton) | STRONG || 4b | Handoff owner-scoped recovery (`any_owner` admin gate) | `ai-memory-mcp/src/server.rs` `require_admin_capability` on `memory_handoff_accept`/`_cancel` `any_owner` | `handoff_admission.rs` — cancel gate + **accept gate** (adversarial: non-admin `any_owner` accept refused) | STRONG || 4c | Turn-checkpoint baton is owner+scope-bound | `ai-memory-store/src/ops.rs` `checkpoint_session_handoff` — reads the session's own `(workspace, project, owner_user)` from `sessions WHERE id=?1 AND ended_at IS NULL`, refuses on scope/owner mismatch, refreshes only that session's own `state='open'` baton (id preserved), returns `None` when the session already ended | `ops.rs` `checkpoint_session_handoff_refreshes_only_the_live_sessions_own_baton` (#865) | STRONG |diff --git a/docs/users.md b/docs/users.mdindex 67faaceb..e3061e86 100644--- a/docs/users.md+++ b/docs/users.md@@ -452,13 +452,13 @@ alice Alice Smith user must-changebob - user activecarol - user disableddave - user active-erin - user expired```-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.+An `active` row without a password is an API-only identity, such as a user the+removed 1.x `user add` created. Its token is an API key now: `ai-memory api-key+list` shows it with the label `legacy-user-token`. Grant human login with+`user reset-password`; that does not reveal or rotate the API key. The list+never surfaces passwords, hashes, or API secrets.### 4. Disable human login (without losing attribution history)@@ -584,17 +584,21 @@ 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+- Migration V54 extends the existing `users` table with human role/password+ state and creates `web_sessions`; V55 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 3.0. Credentials they created keep authenticating after- that, as ordinary API keys managed with `api-key`.+ owner id. The copy is labelled `legacy-user-token`, and its credential id is+ the user's id.+- 3.0 removed the 1.x `user add`, `user expire`, `user revive`, and+ `user rotate-token` commands and their `/admin/users` endpoints (`POST+ /admin/users` and `POST /admin/users/{name}/expire|revive|rotate-token`).+ Migration V79 drops the `users.token_hash` and `users.token_expired_at`+ columns and the V55 triggers that mirrored them into `api_credentials`;+ nothing else wrote or read them. Tokens those commands issued keep+ authenticating as ordinary API keys: list them with `api-key list`, replace+ one with `api-key rotate <id>` and retire one with `api-key revoke <id>`. A+ token that was expired before the upgrade stays refused. Add people with+ `user add-human` and machine credentials with `api-key add`.- Before any human password or completed bootstrap exists, GET-only browserroutes continue to accept the root bearer through HTTP Basic and theHttpOnly `ai_memory_auth` cookie. Human activation disables that path@@ -654,8 +658,9 @@ into `web_sessions`. The cookie is `HttpOnly`, `SameSite=Strict`,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.+`api_credentials` (same 32-byte digest, label `legacy-user-token`), and V79+dropped the old columns. A copied token has no `aim_` prefix; the lookup+hashes whatever bearer it gets, so it authenticates like any other key.## Where attribution shows up@@ -663,7 +668,7 @@ Runtime lookup no longer reads the old columns.|---|---|| 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-human/list/reset-password/disable/enable/patch`, deprecated `user add/expire/revive/rotate-token`, and `ai-memory api-key add/list/rotate/revoke` | ✓ |+| `ai-memory user add-human/list/reset-password/disable/enable/patch` 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 |@@ -779,9 +784,7 @@ ones who should keep access; nothing is granted automatically.multi-user collaboration is a core capability. `pages.author_id` isattribution, never a read filter.- **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+ secret; `api-key add` never issues a login session. Disable/reset of a human leaves APIcredentials untouched, and revoke/rotate of a native key leaves thepassword/session untouched. One identity may hold several native keys withdistinct labels.