Skip to content

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

Rust

fix(mcp): ship session management and self-service keys as runtime opt-ins

AkitaOnRails0ea84c8010ba
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 5f25d6f8..b8055aa5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -45,32 +45,6 @@ jobs:
- uses: Swatinem/rust-cache@f0d9c3887740aee45f6153b24b3a6b815192ec16 # v2
- run: cargo clippy --workspace --all-targets -- -D warnings
- session-management:
- name: optional session-management
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- - uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable
- with:
- components: clippy
- - uses: Swatinem/rust-cache@f0d9c3887740aee45f6153b24b3a6b815192ec16 # v2
- - run: cargo clippy --workspace --all-targets --features ai-memory-cli/session-management -- -D warnings
- - run: cargo test -p ai-memory-mcp --features session-management session_management
- - run: cargo test -p ai-memory-cli --features session-management --lib session_management
-
- self-service-keys:
- name: optional self-service-keys
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- - uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable
- with:
- components: clippy
- - uses: Swatinem/rust-cache@f0d9c3887740aee45f6153b24b3a6b815192ec16 # v2
- - run: cargo clippy --workspace --all-targets --features ai-memory-cli/self-service-keys -- -D warnings
- - run: cargo test -p ai-memory-mcp --features self-service-keys self_service_keys
- - run: cargo test -p ai-memory-cli --features self-service-keys --lib self_service_keys
-
test:
name: test (${{ matrix.os }})
strategy:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1207d617..bc3a2a9f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,12 +12,17 @@ version in [`docs/changelog/`](docs/changelog/):
## [Unreleased]
### Added
-- Added optional human-session session inspection and owned purging, gated by the
- `session-management` build feature and runtime switch. Reused existing human
- authentication, authorization, and SQLite storage. (#1231)
-- Added optional human-session self-service native API keys, gated by the
- `self-service-keys` build feature and runtime switch. Reused existing
- authentication, credential hashing, and SQLite storage. (#1231)
+- Added opt-in session inspection and owned-session purging for signed-in
+ browser users, enabled at runtime with `serve --enable-session-management`
+ (`AI_MEMORY_ENABLE_SESSION_MANAGEMENT`). A user can purge only a session they
+ own in a project they may write; an Admin can purge any. Requested in #1231.
+ (#1267)
+- Added opt-in self-service `aim_` API keys for signed-in browser users,
+ enabled at runtime with `serve --enable-self-service-keys`
+ (`AI_MEMORY_ENABLE_SELF_SERVICE_KEYS`). Labels must be 1 to 128 characters
+ and a user may hold at most 20 active keys. A self-issued key survives a
+ password reset or account disable and must be revoked separately. Requested
+ in #1231. (#1268)
- Added `ai-memory search --global`, which searches the wiki pages of every
project from the terminal instead of only the current one. Each hit shows
its `workspace/project` in the text output and carries `workspace` and
diff --git a/README.md b/README.md
index c317fa40..6446a2c2 100644
--- a/README.md
+++ b/README.md
@@ -573,6 +573,13 @@ and [`docs/deploy.md`](docs/deploy.md) for the server itself. It includes
measured capacity numbers and the one rule you must follow: one server per
data directory, never two.
+Two opt-in HTTP surfaces build on the same browser sign-in, and both are off
+by default. `serve --enable-session-management` lets signed-in users inspect
+sessions and purge the ones they own
+([`docs/session-management.md`](docs/session-management.md)).
+`serve --enable-self-service-keys` lets them issue and revoke their own `aim_`
+API keys ([`docs/self-service-keys.md`](docs/self-service-keys.md)).
+
## Security
The server binds to loopback only by default. A fresh `ai-memory init` also
@@ -691,9 +698,3 @@ MIT. See [LICENSE](LICENSE).
This codebase is being built collaboratively with Claude Code
(Anthropic Claude Opus 4.7) following the plan documented in
`docs/design-decisions.md`.
-
-The optional [human-session session inspection and owned purging](docs/session-management.md)
-uses existing browser authentication and is disabled by default.
-
-Optional [self-service MCP API keys](docs/self-service-keys.md) reuse existing
-browser authentication and are disabled by default.
diff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.toml
index 0613f267..bd874a05 100644
--- a/crates/ai-memory-cli/Cargo.toml
+++ b/crates/ai-memory-cli/Cargo.toml
@@ -23,11 +23,6 @@ path = "src/main.rs"
# a second ~120 MB harness binary for it that contains no tests.
test = false
-[features]
-default = []
-session-management = ["ai-memory-mcp/session-management"]
-self-service-keys = ["ai-memory-mcp/self-service-keys"]
-
[dependencies]
ai-memory-consolidate.workspace = true
ai-memory-core.workspace = true
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 8e533755..046bcd01 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -3374,13 +3374,14 @@ pub enum TransportKind {
/// Arguments for `serve`.
#[derive(Debug, Args)]
pub struct ServeArgs {
- /// Enable optional browser-session management API (requires an opt-in build).
- #[cfg(feature = "session-management")]
+ /// Serve the `/management/v1` session inspection and owned-purge routes to
+ /// signed-in browser users. Off by default; requires `--transport http`.
#[arg(long, env = "AI_MEMORY_ENABLE_SESSION_MANAGEMENT")]
pub enable_session_management: bool,
- /// Enable optional browser-session management API (requires an opt-in build).
- #[cfg(feature = "self-service-keys")]
+ /// Let signed-in browser users issue and revoke their own `aim_` API keys
+ /// under `/management/v1/credentials`. Off by default; requires
+ /// `--transport http`.
#[arg(long, env = "AI_MEMORY_ENABLE_SELF_SERVICE_KEYS")]
pub enable_self_service_keys: bool,
@@ -3516,7 +3517,6 @@ pub struct WritePageArgs {
#[cfg(test)]
mod tests {
- #[cfg(feature = "session-management")]
#[test]
fn session_management_is_runtime_opt_in() {
let parsed = Cli::try_parse_from(["ai-memory", "serve"]).unwrap();
@@ -3537,15 +3537,6 @@ mod tests {
};
assert!(args.enable_session_management);
}
- #[cfg(not(feature = "session-management"))]
- #[test]
- fn session_management_flag_is_absent_by_default() {
- assert!(
- Cli::try_parse_from(["ai-memory", "serve", "--enable-session-management"]).is_err()
- );
- }
-
- #[cfg(feature = "self-service-keys")]
#[test]
fn self_service_keys_is_runtime_opt_in() {
let parsed = Cli::try_parse_from(["ai-memory", "serve"]).unwrap();
@@ -3566,12 +3557,6 @@ mod tests {
};
assert!(args.enable_self_service_keys);
}
- #[cfg(not(feature = "self-service-keys"))]
- #[test]
- fn self_service_keys_flag_is_absent_by_default() {
- assert!(Cli::try_parse_from(["ai-memory", "serve", "--enable-self-service-keys"]).is_err());
- }
-
use super::*;
use clap::{CommandFactory, Parser};
use std::collections::BTreeSet;
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 8b28f320..8bcbb068 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -1151,11 +1151,9 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
validate_web_ui_args(args.enable_web, args.web_ui_dir.as_deref())?;
refuse_a_missing_token_file(&config.auth)?;
- #[cfg(feature = "session-management")]
if args.enable_session_management && !matches!(args.transport, TransportKind::Http) {
anyhow::bail!("--enable-session-management requires --transport http");
}
- #[cfg(feature = "self-service-keys")]
if args.enable_self_service_keys && !matches!(args.transport, TransportKind::Http) {
anyhow::bail!("--enable-self-service-keys requires --transport http");
}
@@ -1842,7 +1840,6 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
auth_state.clone(),
expire_legacy_cookie_mw,
)));
- #[cfg(feature = "session-management")]
let router = if args.enable_session_management {
router.merge(ai_memory_mcp::session_management::router(
ai_memory_mcp::session_management::SessionManagementState {
@@ -1855,7 +1852,6 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
} else {
router
};
- #[cfg(feature = "self-service-keys")]
let router = if args.enable_self_service_keys {
router.merge(ai_memory_mcp::self_service_keys::router(
ai_memory_mcp::self_service_keys::SelfServiceKeysState {
diff --git a/crates/ai-memory-mcp/Cargo.toml b/crates/ai-memory-mcp/Cargo.toml
index 12e84f74..5ad36d8f 100644
--- a/crates/ai-memory-mcp/Cargo.toml
+++ b/crates/ai-memory-mcp/Cargo.toml
@@ -12,11 +12,6 @@ description = "MCP server transport and tool router for ai-memory."
# statically links the whole dep graph and gets scanned by macOS on
# first run.
-[features]
-default = []
-session-management = []
-self-service-keys = []
-
[dependencies]
ai-memory-core.workspace = true
ai-memory-consolidate.workspace = true
diff --git a/crates/ai-memory-mcp/src/lib.rs b/crates/ai-memory-mcp/src/lib.rs
index 5e7f1f6e..919f91f1 100644
--- a/crates/ai-memory-mcp/src/lib.rs
+++ b/crates/ai-memory-mcp/src/lib.rs
@@ -15,7 +15,9 @@ pub mod auth;
pub mod human_auth;
pub mod identity;
pub mod metrics;
+pub mod self_service_keys;
mod server;
+pub mod session_management;
pub use actor::actor_from_headers;
pub use admin::{
@@ -38,9 +40,3 @@ extern crate self as ai_memory_mcp;
#[cfg(test)]
#[path = "../tests/suite/mod.rs"]
mod integration;
-
-#[cfg(feature = "session-management")]
-pub mod session_management;
-
-#[cfg(feature = "self-service-keys")]
-pub mod self_service_keys;
diff --git a/crates/ai-memory-mcp/src/self_service_keys.rs b/crates/ai-memory-mcp/src/self_service_keys.rs
index baf16483..e05fd70c 100644
--- a/crates/ai-memory-mcp/src/self_service_keys.rs
+++ b/crates/ai-memory-mcp/src/self_service_keys.rs
@@ -13,6 +13,12 @@ use axum::{
use serde::Deserialize;
use serde_json::{Value, json};
use std::sync::Arc;
+
+/// Longest label a user may give a self-issued key, in characters.
+pub const MAX_LABEL_CHARS: usize = 128;
+/// Active (unrevoked, unexpired) self-issued keys one user may hold at once.
+pub const MAX_ACTIVE_KEYS_PER_USER: usize = 20;
+
/// Dependencies resolved once at startup; credentials never read server config.
#[derive(Clone)]
pub struct SelfServiceKeysState {
@@ -97,6 +103,13 @@ async fn create_credential(
Extension(user): Extension<UserId>,
Json(body): Json<KeyBody>,
) -> Result<Json<Value>, Response> {
+ let label = body.label.trim();
+ if label.is_empty() || label.chars().count() > MAX_LABEL_CHARS {
+ return Err(error(
+ StatusCode::BAD_REQUEST,
+ &format!("label must be 1 to {MAX_LABEL_CHARS} characters after trimming"),
+ ));
+ }
let pepper = state
.pepper
.as_ref()
@@ -104,12 +117,13 @@ async fn create_credential(
let token = ai_memory_store::generate_api_key().map_err(store_error)?;
let id = state
.writer
- .create_api_credential(
+ .create_api_credential_within_limit(
ApiCredentialId::new(),
user,
- body.label,
+ label.to_owned(),
ai_memory_store::hash_token(&token, pepper),
Some(ai_memory_store::api_key_preview(&token)),
+ MAX_ACTIVE_KEYS_PER_USER,
)
.await
.map_err(store_error)?;
@@ -126,7 +140,9 @@ async fn revoke_credential(
.find_api_credential(id)
.await
.map_err(store_error)?
- .filter(|key| key.user_id == user)
+ // A foreign id and an already-revoked one both read as absent, so
+ // the response never confirms another user's credential exists.
+ .filter(|key| key.user_id == user && key.revoked_at.is_none())
.ok_or_else(|| error(StatusCode::NOT_FOUND, "credential not found"))?;
state
.writer
diff --git a/crates/ai-memory-mcp/tests/suite/mod.rs b/crates/ai-memory-mcp/tests/suite/mod.rs
index 490c997b..814cb24c 100644
--- a/crates/ai-memory-mcp/tests/suite/mod.rs
+++ b/crates/ai-memory-mcp/tests/suite/mod.rs
@@ -38,12 +38,8 @@ mod query_superseded;
mod read_page_related;
mod recap_identity;
mod retrieval_via_tools;
+mod self_service_keys;
+mod session_management;
mod slot_identity;
mod stress_autoscope;
mod web_search_parity;
-
-#[cfg(feature = "session-management")]
-mod session_management;
-
-#[cfg(feature = "self-service-keys")]
-mod self_service_keys;
diff --git a/crates/ai-memory-mcp/tests/suite/self_service_keys.rs b/crates/ai-memory-mcp/tests/suite/self_service_keys.rs
index 5b8a73b9..d2d4afa7 100644
--- a/crates/ai-memory-mcp/tests/suite/self_service_keys.rs
+++ b/crates/ai-memory-mcp/tests/suite/self_service_keys.rs
@@ -280,3 +280,167 @@ async fn self_service_keys_refuse_foreign_ids_csrf_machine_and_pending_password_
1
);
}
+
+const KEYS: &str = "/management/v1/credentials";
+
+async fn active_keys(h: &Harness, user: UserId) -> Vec<ai_memory_core::ApiCredential> {
+ h.store
+ .reader
+ .list_api_credentials_for_user(user)
+ .await
+ .unwrap()
+ .into_iter()
+ .filter(|key| key.revoked_at.is_none())
+ .collect()
+}
+
+async fn issue(h: &Harness, who: &Browser, label: &str) -> (StatusCode, Value) {
+ call(h, Some(who), "POST", KEYS, json!({ "label": label }), true).await
+}
+
+#[tokio::test]
+async fn self_service_keys_refuse_blank_and_overlong_labels() {
+ let h = harness().await;
+ for label in [String::new(), " \t ".into(), "x".repeat(129)] {
+ let (status, body) = issue(&h, &h.alice, &label).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "label {label:?}");
+ assert!(body.get("token").is_none());
+ }
+ // Multi-byte characters count as characters, not bytes.
+ let (status, body) = issue(&h, &h.alice, &"é".repeat(129)).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert!(body.get("token").is_none());
+ assert!(active_keys(&h, h.alice.user).await.is_empty());
+
+ // Controls: the limit itself is accepted, and labels are stored trimmed.
+ assert_eq!(
+ issue(&h, &h.alice, &"é".repeat(128)).await.0,
+ StatusCode::OK
+ );
+ assert_eq!(issue(&h, &h.alice, " laptop ").await.0, StatusCode::OK);
+ let labels: Vec<String> = active_keys(&h, h.alice.user)
+ .await
+ .into_iter()
+ .map(|key| key.label)
+ .collect();
+ assert_eq!(labels.len(), 2);
+ assert!(labels.contains(&"laptop".to_string()));
+}
+
+#[tokio::test]
+async fn self_service_keys_cap_active_keys_per_user() {
+ let h = harness().await;
+ let max = ai_memory_mcp::self_service_keys::MAX_ACTIVE_KEYS_PER_USER;
+ let mut first = None;
+ for n in 0..max {
+ let (status, body) = issue(&h, &h.alice, &format!("key {n}")).await;
+ assert_eq!(status, StatusCode::OK, "key {n}");
+ first.get_or_insert_with(|| body["id"].as_str().unwrap().to_string());
+ }
+ let (status, body) = issue(&h, &h.alice, "one too many").await;
+ assert_eq!(status, StatusCode::CONFLICT);
+ assert!(body.get("token").is_none());
+ assert!(
+ body["error"].as_str().unwrap().contains("limit"),
+ "unclear refusal: {body}"
+ );
+ assert_eq!(active_keys(&h, h.alice.user).await.len(), max);
+
+ // The cap is per user: another user still issues keys.
+ assert_eq!(issue(&h, &h.bob, "bob's key").await.0, StatusCode::OK);
+ // Revoked keys do not count: revoking one frees a slot.
+ let revoke = format!("{KEYS}/{}/revoke", first.unwrap());
+ assert_eq!(
+ call(&h, Some(&h.alice), "POST", &revoke, json!({}), true)
+ .await
+ .0,
+ StatusCode::OK
+ );
+ assert_eq!(issue(&h, &h.alice, "replacement").await.0, StatusCode::OK);
+ assert_eq!(active_keys(&h, h.alice.user).await.len(), max);
+}
+
+#[tokio::test]
+async fn self_service_keys_refuse_a_disabled_user() {
+ let h = harness().await;
+ assert_eq!(issue(&h, &h.alice, "before").await.0, StatusCode::OK);
+ let id = active_keys(&h, h.alice.user).await[0].id;
+ h.store
+ .writer
+ .set_user_disabled(h.alice.user, true)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ call(&h, Some(&h.alice), "GET", KEYS, Value::Null, false)
+ .await
+ .0,
+ StatusCode::UNAUTHORIZED
+ );
+ assert_eq!(
+ issue(&h, &h.alice, "after").await.0,
+ StatusCode::UNAUTHORIZED
+ );
+ let revoke = format!("{KEYS}/{id}/revoke");
+ assert_eq!(
+ call(&h, Some(&h.alice), "POST", &revoke, json!({}), true)
+ .await
+ .0,
+ StatusCode::UNAUTHORIZED
+ );
+ assert_eq!(active_keys(&h, h.alice.user).await.len(), 1);
+ // Control: an enabled user is unaffected.
+ assert_eq!(issue(&h, &h.bob, "bob").await.0, StatusCode::OK);
+}
+
+#[tokio::test]
+async fn self_service_keys_revoking_an_unknown_or_revoked_id_is_not_found() {
+ let h = harness().await;
+ let alice_key = issue(&h, &h.alice, "alice").await.1["id"]
+ .as_str()
+ .unwrap()
+ .to_string();
+ assert_eq!(issue(&h, &h.bob, "bob").await.0, StatusCode::OK);
+
+ let unknown = format!("{KEYS}/{}/revoke", ai_memory_core::ApiCredentialId::new());
+ assert_eq!(
+ call(&h, Some(&h.alice), "POST", &unknown, json!({}), true)
+ .await
+ .0,
+ StatusCode::NOT_FOUND
+ );
+
+ let revoke = format!("{KEYS}/{alice_key}/revoke");
+ assert_eq!(
+ call(&h, Some(&h.alice), "POST", &revoke, json!({}), true)
+ .await
+ .0,
+ StatusCode::OK
+ );
+ let revoked_at = h
+ .store
+ .reader
+ .list_api_credentials_for_user(h.alice.user)
+ .await
+ .unwrap()[0]
+ .revoked_at;
+ assert!(revoked_at.is_some());
+ assert_eq!(
+ call(&h, Some(&h.alice), "POST", &revoke, json!({}), true)
+ .await
+ .0,
+ StatusCode::NOT_FOUND
+ );
+ // The repeat neither moved the original revocation time nor touched
+ // another user's key.
+ assert_eq!(
+ h.store
+ .reader
+ .list_api_credentials_for_user(h.alice.user)
+ .await
+ .unwrap()[0]
+ .revoked_at,
+ revoked_at
+ );
+ assert_eq!(active_keys(&h, h.bob.user).await.len(), 1);
+}
diff --git a/crates/ai-memory-store/src/api_credentials.rs b/crates/ai-memory-store/src/api_credentials.rs
index 711890c3..8942ce9e 100644
--- a/crates/ai-memory-store/src/api_credentials.rs
+++ b/crates/ai-memory-store/src/api_credentials.rs
@@ -78,6 +78,26 @@ pub fn insert_api_credential(
Ok(id)
}
+/// Count a user's credentials that still authenticate: not revoked and not
+/// expired at `now`.
+///
+/// # Errors
+/// SQL failures.
+pub fn count_active_api_credentials_for_user(
+ conn: &Connection,
+ user_id: UserId,
+ now: i64,
+) -> StoreResult<usize> {
+ let count: i64 = conn.query_row(
+ "SELECT COUNT(*) FROM api_credentials \
+ WHERE user_id = ?1 AND revoked_at IS NULL \
+ AND (expires_at IS NULL OR expires_at > ?2)",
+ params![user_id.as_bytes(), now],
+ |row| row.get(0),
+ )?;
+ Ok(usize::try_from(count).unwrap_or(usize::MAX))
+}
+
/// Rotate: write a new hash on the same id, clear revoked_at.
///
/// # Errors
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index e8aee7b6..4a27c258 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -684,6 +684,10 @@ pub(crate) enum WriteCmd {
label: String,
token_hash: [u8; TOKEN_HASH_LEN],
preview: Option<String>,
+ /// Refuse with [`StoreError::InvalidState`] when the user already
+ /// holds this many active credentials. Checked on the writer thread,
+ /// so concurrent creates cannot both slip under the limit.
+ max_active: Option<usize>,
reply: oneshot::Sender<StoreResult<ApiCredentialId>>,
},
RotateApiCredential {
@@ -3089,6 +3093,38 @@ impl WriterHandle {
label: String,
token_hash: [u8; TOKEN_HASH_LEN],
preview: Option<String>,
+ ) -> StoreResult<ApiCredentialId> {
+ self.send_create_api_credential(id, user_id, label, token_hash, preview, None)
+ .await
+ }
+
+ /// Insert a native API credential unless `user_id` already holds
+ /// `max_active` active ones.
+ ///
+ /// # Errors
+ /// [`StoreError::InvalidState`] at the limit; duplicate hash, writer
+ /// closed, SQL.
+ pub async fn create_api_credential_within_limit(
+ &self,
+ id: ApiCredentialId,
+ user_id: UserId,
+ label: String,
+ token_hash: [u8; TOKEN_HASH_LEN],
+ preview: Option<String>,
+ max_active: usize,
+ ) -> StoreResult<ApiCredentialId> {
+ self.send_create_api_credential(id, user_id, label, token_hash, preview, Some(max_active))
+ .await
+ }
+
+ async fn send_create_api_credential(
+ &self,
+ id: ApiCredentialId,
+ user_id: UserId,
+ label: String,
+ token_hash: [u8; TOKEN_HASH_LEN],
+ preview: Option<String>,
+ max_active: Option<usize>,
) -> StoreResult<ApiCredentialId> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::CreateApiCredential {
@@ -3097,6 +3133,7 @@ impl WriterHandle {
label,
token_hash,
preview,
+ max_active,
reply: tx,
})
.await?;
@@ -4601,16 +4638,32 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
label,
token_hash,
preview,
+ max_active,
reply,
} => {
- let result = api_credentials::insert_api_credential(
- &conn,
- id,
- user_id,
- &label,
- &token_hash,
- preview.as_deref(),
- );
+ let at_limit = match max_active {
+ Some(max) => api_credentials::count_active_api_credentials_for_user(
+ &conn,
+ user_id,
+ jiff::Timestamp::now().as_microsecond(),
+ )
+ .map(|active| (active >= max).then_some(max)),
+ None => Ok(None),
+ };
+ let result = match at_limit {
+ Ok(Some(max)) => Err(StoreError::InvalidState(format!(
+ "active API key limit reached ({max}); revoke a key before creating another"
+ ))),
+ Ok(None) => api_credentials::insert_api_credential(
+ &conn,
+ id,
+ user_id,
+ &label,
+ &token_hash,
+ preview.as_deref(),
+ ),
+ Err(e) => Err(e),
+ };
send_or_warn(reply, result, "create_api_credential");
}
WriteCmd::RotateApiCredential {
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 03feba69..956d984b 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -112,10 +112,8 @@ means the boundary is not built yet.
| 16 | Relay queue identity, migration, and private filesystem state | `companions/ai-memory-relay/src/queue.rs` `Queue::open_inner` performs read-only identity preflight, rechecks under `IMMEDIATE`, commits schema and metadata together; `configure` checks the presence of user objects and rechecks `identity`/`schema_version` metadata on the same connection before every bounded BUSY/LOCKED retry; `fsguard.rs` checks existing paths and creates owner-only files before SQLite opens them | `tests/relay.rs` `a_foreign_database_is_refused_byte_for_byte`, `unknown_schemas_refuse_without_mutation`, `a_foreign_database_with_a_writer_is_refused_before_write_coordination`, `a_foreign_identity_after_preflight_is_refused_without_mutation`, `a_foreign_identity_during_journal_retry_is_refused_without_mutation`, `journal_retry_refuses_a_changed_version_or_empty_database_without_mutation`; controls: `journal_transition_retries_sqlite_lock_without_losing_v1_values`, `fresh_queue_init_and_v1_reopens_work_across_processes`; recovery: `interrupted_and_failed_migrations_roll_back_and_recover`, `journal_reclassification_busy_preserves_committed_migration_and_retries_same_queue`; diagnostics: `classification_read_failures_display_the_sqlite_cause_once_and_preserve_foreign_bytes`; Unix privacy: `the_queue_database_and_its_sidecars_are_owner_only` and the contended migration control | Guard-removal proof covers preflight, locked recheck, and journal retry identity/version checks; full table structure is outside this classification. Windows path rejection is preserved; Windows ACL hardening remains operator-owned |
| 17 | `ai-memory setup --web` local wizard: only the page this process printed can read the plan or apply a setup | `ai-memory-cli/src/commands/setup_web.rs` `guard` (binds `127.0.0.1` on an OS-picked port; every request needs a `Host` of exactly `127.0.0.1:<port>` or `localhost:<port>` and the one-time 256-bit path secret, compared with `subtle`; a POST also needs this page's `Origin` and the CSRF token the page reads from its own JSON; no CORS grant; `no-store`, `no-referrer`, `DENY` framing, and a CSP with a per-run nonce and no outside sources on the page) and `apply` (agent names must be `--agent` values, de-duplicated, at least one; the child is always `ai-memory setup --yes --agent ...` with the wizard's own flags, never a caller-chosen argument) | `setup_web.rs` `the_page_is_served_only_to_our_host_and_secret` (a rebinding `Host`, a bare `127.0.0.1`, another port, a wrong secret and a missing one refused; controls: `127.0.0.1` and `localhost` with the secret), `apply_refuses_cross_site_and_unknown_input_and_starts_nothing` (no `Origin`, a foreign `Origin`, no CSRF token and a wrong one each refused; `--force`, a shell-like name and an empty choice refused; no child starts), `apply_runs_setup_with_the_picked_agents_and_streams_its_output` (legitimate control: exact argument list); `tests/suite/setup_e2e.rs` `setup_web_serves_the_plan_and_applies_the_picked_agent` (the same through the binary); bite-checked by removing the `Host` check, the `Origin` check, the CSRF check and the agent allowlist one at a time | STRONG |
| 18 | `uninstall` removes only a service `setup` wrote, including the Windows logon entry | `ai-memory-cli/src/commands/user_service.rs` `planned_removal` / `is_rendered_by_setup` (a unit file whose identity digest still matches) and `planned_removal_for` / `is_setup_run_entry_for` (a `REG_SZ` `HKCU\...\Run\ai-memory` value that is a quoted `ai-memory.exe` ending in `service-host`, with no `&` or `|` chaining, whose `--data-dir`, the first argument after the quoted executable and a whole quoted argument ending at its closing quote, is the data dir being uninstalled, both absolute (`X:\…`, UNC or `\\?\Volume{GUID}\…`; a drive-relative `C:` matches nothing), compared without the verbatim `\\?\` / `\\?\UNC\` prefix, case or trailing separators) before `remove` stops anything or deletes it | `user_service.rs` `uninstall_removes_only_setups_logon_entry` (another install's entry, naming a different `--data-dir`, is left with only the query run; another program's value under the same name is left; absent value is nothing to do; control: this data dir's entry is deleted), `only_the_entry_for_this_data_dir_is_ours` (a temporary data dir does not claim the operator's entry, #1280), `a_volume_guid_data_dir_owns_its_entry` (a volume GUID data dir owns its rendered entry and not another volume's; `uninstall_removes_only_setups_logon_entry` drives both through `remove`), `a_drive_relative_data_dir_is_not_the_drive_root` (`--data-dir "C:"` does not claim `C:\`'s entry; control: the rendered drive-root entry does; `uninstall_removes_only_setups_logon_entry` drives it through `remove` and asserts nothing is stopped or deleted), `a_data_dir_that_runs_past_its_quote_is_not_ours` (`"C:\d"\other` and an escaped closing quote, which Windows reads as other directories, do not claim `C:\d`'s entry; control: the rendered entry does; `uninstall_removes_only_setups_logon_entry` drives the same case through `remove`), `the_data_dir_is_read_after_the_executable` and, on Windows, `a_rendered_entry_belongs_to_its_own_data_dir` (a ` --data-dir ` inside the executable's path neither hides nor fakes the option), `data_dirs_compare_without_prefix_case_or_trailing_separator` (verbatim UNC matches its plain spelling; another share does not), Windows-only `only_a_plain_string_value_is_read` (a `REG_EXPAND_SZ` value under the name is not read as setup's; control: the same data as `REG_SZ` is), `only_setups_entry_shape_counts_as_ours` (unquoted, other program, `serve`, `&`/`|` chaining all refused), and the unit-file identity tests in the same module | STRONG |
-
-| 17 | Human-session session inspection and owned purging | `mcp/src/session_management.rs`: human session/CSRF, completed password change, guarded scope lookup, exact ownership; `ops::purge_session_with_owner`: transaction ownership/write-grant checks and collateral refusal; `Wiki::purge_owned_session`: mutation lock, admission/checkpoints, partial cleanup/tombstones. | MCP `session_management` suite (foreign/shared/raw ids, wrong/partial scopes, anonymous/machine/CSRF, admission refusal, owner/Admin controls); store `multi_session::owned_session_purge_*`; wiki `owned_session_purge_authorization_failure_preserves_page_and_index`, `owned_session_purge_cleanup_failure_is_reported_and_tombstoned`. | Adversarial controls and guard-removal proofs. |
-
-| 18 | Human-session self-service native API keys | `mcp/src/self_service_keys.rs`: human session/CSRF and completed password change; creation takes authenticated `UserId`, never a supplied username; revocation verifies immutable owner; existing native keys remain User-level. | `self_service_keys_refuse_foreign_ids_csrf_machine_and_pending_password_with_owner_controls` (anonymous/machine/CSRF/pending-password/foreign-id refusal, supplied username ignored, legitimate User/Root controls). | Adversarial controls and guard-removal proofs. |
+| 19 | Human-session session inspection and owned purging (`serve --enable-session-management`, #1267) | `ai-memory-mcp/src/session_management.rs`: human session and CSRF, completed password change, guarded no-create scope lookup, and an exact-owner preflight before any admission or checkpoint side effect; `ai-memory-store/src/ops.rs` `purge_session_with_owner`: ownership and project write grant rechecked inside the deletion transaction (previews included), cross-project collateral refused unless an Admin purges; `Wiki::purge_owned_session`: wiki mutation lock, admission, pre/post checkpoints, partial-cleanup reporting and replay tombstones | MCP `session_management` suite: `management_refuses_foreign_ids_shared_deletion_and_missing_csrf_with_admin_control` (foreign and shared sessions, anonymous, machine bearer, missing CSRF refused; owner and Admin controls), `management_raw_session_ids_fail_closed_on_wrong_and_partial_scope`, `management_purge_admission_rejection_preserves_rows_and_files`, `management_pagination_reports_its_limit_and_keeps_pages_disjoint`; store `multi_session::owned_session_purge_refuses_foreign_shared_and_wrong_scope_sessions`, `owned_session_purge_refuses_cross_project_cascades_with_admin_control`; wiki `owned_session_purge_authorization_failure_preserves_page_and_index`, `owned_session_purge_cleanup_failure_is_reported_and_tombstoned`. Bite-checked: removing the transaction owner check fails `owned_session_purge_refuses_foreign_shared_and_wrong_scope_sessions`; removing it together with the handler preflight fails `management_refuses_foreign_ids_shared_deletion_and_missing_csrf_with_admin_control` (the two are defence in depth) | STRONG |
+| 20 | Human-session self-service native API keys (`serve --enable-self-service-keys`, #1268) | `ai-memory-mcp/src/self_service_keys.rs`: human session and CSRF (a disabled account's session is refused by `load_session`), completed password change; creation takes the authenticated `UserId`, never a supplied username, trims and bounds `label` (1 to 128 characters) and asks the writer for `create_api_credential_within_limit` (at most 20 active keys per user, counted on the writer thread); revocation answers 404 unless the credential is the caller's own and still active; the token appears only in the one-time create response; issued keys stay `AuthLevel::User` | `self_service_keys_refuse_foreign_ids_csrf_machine_and_pending_password_with_owner_controls` (anonymous, machine bearer, missing CSRF, pending password and foreign-id revoke refused; supplied username ignored; User and Root owner controls), `self_service_keys_refuse_blank_and_overlong_labels` (empty, whitespace, 129 ASCII and 129 multi-byte characters refused with nothing stored; control: 128 characters and a trimmed label accepted), `self_service_keys_cap_active_keys_per_user` (the 21st key refused with 409; controls: another user unaffected, a revoked key frees a slot), `self_service_keys_refuse_a_disabled_user` (list, create and revoke refused; key untouched; control: an enabled user), `self_service_keys_revoking_an_unknown_or_revoked_id_is_not_found` (unknown and already-revoked ids answer 404 without moving the revocation time or touching another user's key). Bite-checked: removing the owner filter fails the foreign-id test; removing the active filter or the key limit fails the revoked-id and cap tests | STRONG |
## Keeping this current (the standing protocol)
diff --git a/docs/self-service-keys.md b/docs/self-service-keys.md
index de82e202..a7243182 100644
--- a/docs/self-service-keys.md
+++ b/docs/self-service-keys.md
@@ -1,22 +1,28 @@
# Self-service MCP API keys
-Build with `--features self-service-keys` and start the HTTP server with
-`--enable-self-service-keys` (`AI_MEMORY_ENABLE_SELF_SERVICE_KEYS=true`). Both
-switches default to off. Existing human browser sessions may GET or POST
+Start the HTTP server with `--enable-self-service-keys`
+(`AI_MEMORY_ENABLE_SELF_SERVICE_KEYS=true`). It is off by default and requires
+`--transport http`. Existing human browser sessions may GET or POST
`/management/v1/credentials` and POST `/management/v1/credentials/{id}/revoke`.
Machine bearers and password-change-required sessions cannot use these routes;
mutations require the existing CSRF cookie/header pair.
POST a `label` to create a key for the authenticated immutable user id. The
-server returns the `aim_` key once and stores only its peppered hash. Configure
-`[auth] token_pepper` as for the existing native-key administration commands.
-Revocation refuses another user's credential id. Listing returns metadata and
-previews, never token material. Responses use `Cache-Control: private, no-store`.
+server returns the `aim_` key once and stores only its peppered hash. The
+label is trimmed and must be 1 to 128 characters (400 otherwise). A user may
+hold at most 20 active keys; the 21st is refused with 409 until one is
+revoked. Configure `[auth] token_pepper` as for the existing native-key
+administration commands. Revocation answers 404 for another user's credential
+id, an unknown id, or a key that is already revoked, so it never confirms that
+someone else's key exists. Listing returns metadata and previews, never token
+material. Responses use `Cache-Control: private, no-store`.
Use the key as an Authorization: Bearer credential for `/mcp` and lifecycle
-hooks. It remains User-level even when its owner is an Admin. Disabling browser
-access does not revoke machine keys; revoke them separately. No identity
-provider, password implementation, database, or schema is added.
+hooks. It remains User-level even when its owner is an Admin. A password reset
+or an account disable ends browser sessions but does not revoke self-issued
+keys; revoke them separately. No identity provider, password implementation,
+database, or schema is added.
-Run `cargo t -p ai-memory-mcp --features self-service-keys` for the adversarial
-anonymous, machine, CSRF, pending-password, foreign-id, and legitimate owner tests.
+Run `cargo t -p ai-memory-mcp -E 'test(/self_service_keys/)'` for the adversarial
+anonymous, machine, CSRF, pending-password, disabled-user, foreign, unknown and
+revoked id, label, key-limit, and legitimate owner tests.
diff --git a/docs/session-management.md b/docs/session-management.md
index c8568992..68e354dc 100644
--- a/docs/session-management.md
+++ b/docs/session-management.md
@@ -1,8 +1,8 @@
# Self-service session management
-Build with `--features session-management` and start the HTTP server with
-`--enable-session-management` (`AI_MEMORY_ENABLE_SESSION_MANAGEMENT=true`).
-Both switches default to off. This enables `/management/v1/projects`,
+Start the HTTP server with `--enable-session-management`
+(`AI_MEMORY_ENABLE_SESSION_MANAGEMENT=true`). It is off by default and
+requires `--transport http`. This enables `/management/v1/projects`,
`/management/v1/sessions`, `/management/v1/sessions/{id}/observations`, and
`/management/v1/sessions/{id}/purge` for existing human browser sessions.
Machine bearers and password-change-required sessions are refused; mutations
@@ -23,6 +23,6 @@ cannot be rolled back after file cleanup fails: `files_failed` reports the
remaining paths, and recovery honors the tombstone. Git history, backups, and
native transcripts can retain earlier content.
-Run `cargo t -p ai-memory-mcp --features session-management`,
+Run `cargo t -p ai-memory-mcp -E 'test(/session_management/)'`,
`cargo t -p ai-memory-store -E 'test(/owned_session_purge/)'`, and
`cargo t -p ai-memory-wiki -E 'test(/owned_session_purge/)'` for the boundary tests.
diff --git a/docs/users.md b/docs/users.md
index addf5c21..7b0b18ae 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -803,7 +803,21 @@ ones who should keep access; nothing is granted automatically.
authenticates as, like any other. The Keycloak/OIDC `sid` claim is also not an ai-memory agent
session id; session auto-scope needs the lifecycle-hook session id or explicit
`workspace` + `project` / `scopes`.
+- **Self-issued keys outlive a password reset or a disable.** A key a user
+ issued through the self-service routes is an ordinary native key. Resetting
+ that user's password or disabling the account ends their browser sessions
+ but leaves every key they issued active; revoke those keys separately
+ (`ai-memory api-key revoke`, or the self-service revoke route while the user
+ can still sign in).
-See [Human-session session inspection and owned purging](session-management.md) for the opt-in HTTP surface.
+### Opt-in browser surfaces
-See [Self-service MCP API keys](self-service-keys.md) for the opt-in HTTP surface.
+Two HTTP surfaces reuse the browser sign-in and are off unless `serve` is
+started with their runtime flag. Both need `--transport http`; machine bearers
+and sessions that still owe a password change are refused, and every mutation
+needs the CSRF cookie/header pair.
+
+| Flag | Environment variable | What it serves |
+|---|---|---|
+| `--enable-session-management` | `AI_MEMORY_ENABLE_SESSION_MANAGEMENT=true` | Session inspection and purging of sessions the user owns. See [session-management.md](session-management.md). |
+| `--enable-self-service-keys` | `AI_MEMORY_ENABLE_SELF_SERVICE_KEYS=true` | Each user issues, lists and revokes their own `aim_` keys, up to 20 active keys, labels of 1 to 128 characters. See [self-service-keys.md](self-service-keys.md). |