Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(auth): stop minting a 30-day root-bearer cookie on Basic sign-in
AkitaOnRails0d916282048d
diff --git a/crates/ai-memory-mcp/src/human_auth.rs b/crates/ai-memory-mcp/src/human_auth.rsindex 23adcbf2..27ddb5f0 100644--- a/crates/ai-memory-mcp/src/human_auth.rs+++ b/crates/ai-memory-mcp/src/human_auth.rs@@ -391,14 +391,8 @@ fn legacy_basic_password(headers: &HeaderMap) -> Option<String> {Some(password.to_string())}-fn legacy_browser_credential(headers: &HeaderMap) -> Option<(String, bool)> {- legacy_basic_password(headers)- .map(|token| (token, true))- .or_else(|| cookie_value(headers, LEGACY_AUTH_COOKIE).map(|token| (token, false)))-}--fn legacy_cookie(token: &str, secure: bool) -> String {- set_cookie(LEGACY_AUTH_COOKIE, token, true, 2_592_000, secure)+fn legacy_browser_credential(headers: &HeaderMap) -> Option<String> {+ legacy_basic_password(headers).or_else(|| cookie_value(headers, LEGACY_AUTH_COOKIE))}fn unauthorized_legacy_browser() -> Response {@@ -1083,21 +1077,18 @@ pub async fn require_dual_auth(if req.method() != Method::GET {return crate::auth::unauthorized_bearer();}- let had_legacy_cookie = cookie_value(req.headers(), LEGACY_AUTH_COOKIE).is_some();- let Some((provided, from_basic)) = legacy_browser_credential(req.headers()) else {+ // A Basic sign-in mints no cookie: the browser resends the cached+ // Basic credentials on every same-origin request by itself, and a+ // persistent cookie would park the raw root bearer on disk for 30+ // days, sent over plain HTTP off loopback. A cookie an older build+ // set is still accepted until human auth retires it.+ let Some(provided) = legacy_browser_credential(req.headers()) else {return unauthorized_legacy_browser();};match crate::auth::authenticate_token(&state, &mut req, &provided, false).await {Ok(crate::auth::BearerAuth::Authenticated) => {req.extensions_mut().insert(state.clone());- let mut response = next.run(req).await;- if from_basic- && !had_legacy_cookie- && let Ok(cookie) = legacy_cookie(&provided, state.secure_cookie()).parse()- {- response.headers_mut().append(header::SET_COOKIE, cookie);- }- return response;+ return next.run(req).await;}Err(response) => return response,Ok(crate::auth::BearerAuth::Absent | crate::auth::BearerAuth::Rejected) => {@@ -1564,6 +1555,54 @@ mod tests {(tmp, state, writer)}+ /// A fresh bearer-only server signs a browser in through Basic. That+ /// sign-in must not park the root bearer in a cookie: none was needed+ /// (the browser resends Basic itself), and the old 30-day cookie held the+ /// raw token, `Secure` only when `secure_cookie` was on. Control: the+ /// Basic GET is still served, and the bearer still authenticates.+ #[tokio::test]+ async fn a_basic_sign_in_mints_no_cookie_holding_the_root_bearer() {+ let (_tmp, state, _writer) = legacy_transition_fixture().await;+ let router = dual_router(state);++ let basic = router+ .clone()+ .oneshot(+ axum::http::Request::builder()+ .uri("/probe")+ .header("authorization", legacy_basic("legacy-root-token"))+ .body(axum::body::Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(basic.status(), StatusCode::OK, "Basic sign-in is served");+ for value in basic.headers().get_all(header::SET_COOKIE) {+ let value = value.to_str().unwrap();+ assert!(+ !value.contains("legacy-root-token"),+ "no cookie may carry the root bearer: {value}"+ );+ }+ assert!(set_cookie_value(basic.headers(), LEGACY_AUTH_COOKIE).is_none());++ let bearer = router+ .oneshot(+ axum::http::Request::builder()+ .uri("/probe")+ .header("authorization", "Bearer legacy-root-token")+ .body(axum::body::Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(+ bearer.status(),+ StatusCode::OK,+ "the bearer API still works"+ );+ }+#[tokio::test]async fn legacy_browser_credentials_stop_when_human_bootstrap_completes() {let (_tmp, state, writer) = legacy_transition_fixture().await;@@ -1581,8 +1620,8 @@ mod tests {.await.unwrap();assert_eq!(basic.status(), StatusCode::OK);- let legacy_cookie = set_cookie_value(basic.headers(), LEGACY_AUTH_COOKIE)- .expect("successful Basic auth must persist the legacy browser cookie");+ // A cookie an older build minted still works until bootstrap.+ let legacy_cookie = "legacy-root-token";let cookie = router.clone()diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex d92ebad5..e30e8924 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -695,7 +695,7 @@ browser compatibility path:| Web session | `ai_memory_session` cookie + CSRF | `/auth/me`, `/admin/*`, `/api/v1/*` by `AuthLevel`; never `/mcp` or hooks || Recovery | `POST /auth/recovery` body | Root password reset; no session || API key | `Authorization: Bearer` (`aim_`, the root bearer from `AI_MEMORY_AUTH_TOKEN`, `[auth].bearer_token` or `[auth].bearer_token_file`, or external `amk_`) | Machine APIs; never a web session |-| Browser token sign-in (no human accounts yet) | HTTP Basic with the root bearer as the password, then HttpOnly `ai_memory_auth` cookie | GET-only browser routes until any human password or completed bootstrap exists; never machine routes. A fresh install has no human accounts, so this is how a browser reaches `/web` there: the 401 carries a Basic challenge, which the HTML login redirect lets through |+| Browser token sign-in (no human accounts yet) | HTTP Basic with the root bearer as the password, resent by the browser on each request (no cookie is set; an `ai_memory_auth` cookie an older build set is still accepted) | GET-only browser routes until any human password or completed bootstrap exists; never machine routes. A fresh install has no human accounts, so this is how a browser reaches `/web` there: the 401 carries a Basic challenge, which the HTML login redirect lets through |The deprecated Basic/cookie path stops immediately when human auth becomesactive; restart is not required. `/web` SPA HTML is public static; the builtindiff --git a/docs/frontend-api.md b/docs/frontend-api.mdindex 4cddf3b5..3b7a1473 100644--- a/docs/frontend-api.md+++ b/docs/frontend-api.md@@ -88,7 +88,8 @@ form post or a `text/plain` request from another site cannot reach them.Do not put `AI_MEMORY_AUTH_TOKEN`, `aim_` keys, session values, or CSRF valuesin `localStorage`. Before any human password or completed bootstrap exists,deprecated GET-only browser compatibility may accept the root bearer through-HTTP Basic and an HttpOnly `ai_memory_auth` cookie. Human activation disables+HTTP Basic, or an HttpOnly `ai_memory_auth` cookie an older build set; a Basic+sign-in no longer sets that cookie. Human activation disablesthat path immediately. See [`docs/users.md`](users.md) for bootstrap, passwordrotation, recovery, roles, session expiry, and API-key lifecycle.diff --git a/docs/install.md b/docs/install.mdindex 534feb15..7e40ae84 100644--- a/docs/install.md+++ b/docs/install.md@@ -3157,8 +3157,9 @@ sandbox, map the data dir read-write, e.g. `ai-jail --rw-mapHuman console login is username/password, not a Bearer pasted into thebrowser. Machine APIs keep using `Authorization: Bearer` (`AI_MEMORY_AUTH_TOKEN`or a native `aim_` key). Before human auth activates, deprecated GET-only-browser compatibility may exchange the root bearer through HTTP Basic for an-HttpOnly `ai_memory_auth` cookie; activation disables that path immediately.+browser compatibility may accept the root bearer through HTTP Basic (no cookie+is set; an `ai_memory_auth` cookie an older build set is still accepted);+activation disables that path immediately.The active classes stay isolated: a password only issues a session; a sessionnever authenticates `/mcp`/hooks/workstreams; recovery never issues a session;an API key never logs into `/auth/login`.diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 7867e2e8..9e6be216 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -38,6 +38,7 @@ means the boundary is not built yet.| 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 |+| 3g | A Basic browser sign-in on a server without human accounts never persists the root bearer in a cookie | `ai-memory-mcp/src/human_auth.rs` `require_dual_auth` accepts Basic (or an `ai_memory_auth` cookie an older build set) for GET only before human auth exists and sets no cookie on success; the browser resends Basic itself; `expire_legacy_cookie_mw` retires a leftover cookie once human auth is active | `human_auth.rs` `a_basic_sign_in_mints_no_cookie_holding_the_root_bearer` (no `Set-Cookie` carries the token, no `ai_memory_auth` is set; control: the Basic GET is served and the bearer still authenticates; bite-checked against the old cookie minting), `legacy_browser_credentials_stop_when_human_bootstrap_completes` (Basic and a leftover cookie both stop at bootstrap) | STRONG || 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/usage.md b/docs/usage.mdindex df02a26c..0d29f006 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -575,8 +575,9 @@ With no bearer token configured on loopback (an install from before 3.0 thatnever ran `ai-memory auth enable`), the built-in wiki remains anonymous. Afresh install has a bearer token and no human accounts, so a browser gets aBasic sign-in prompt: any username, and the contents of-`<data_dir>/auth-tokens/default` as the password. That GET-only browser path-then keeps an HttpOnly `ai_memory_auth` cookie, and it stops immediately after+`<data_dir>/auth-tokens/default` as the password. The browser resends those+credentials itself, so no cookie holds the token. That GET-only browser path+stops immediately aftera human password or completed bootstrap exists. For human-authenticatedadministration, create the first root account ([first-timeroot](install.md#first-time-root-greenfield)) and serve the compiled admin SPAdiff --git a/docs/users.md b/docs/users.mdindex e3061e86..a5b582c8 100644--- a/docs/users.md+++ b/docs/users.md@@ -600,8 +600,9 @@ If you're upgrading a machine-bearer-only install: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 browser- routes continue to accept the root bearer through HTTP Basic and the- HttpOnly `ai_memory_auth` cookie. Human activation disables that path+ routes continue to accept the root bearer through HTTP Basic, and an+ HttpOnly `ai_memory_auth` cookie an older build set (a Basic sign-in no+ longer sets one). Human activation disables that pathimmediately, without a restart. Machine routes remain Bearer-only.- Native API credentials require `[auth].token_pepper`. Human user creation,password reset, disable/enable, and session login do not create or depend