Skip to content

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

Rust

fix(auth): accept only JSON bodies on the public sign-in routes

AkitaOnRailsf193c5eb9678
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8d8788af..9e44e577 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
server must be re-staged with `ai-memory install-hooks` (or
`ai-memory upgrade`); loopback installs need nothing.
(GHSA-6mc4-46pr-w82w)
+- Fixed `POST /auth/login` and `POST /auth/recovery` accepting request bodies
+ that are not declared as JSON, which a page on another site could use to
+ sign the operator's browser in or to try passwords when human sign-in is
+ enabled. Both routes now answer 415 unless the body is `application/json`;
+ the built-in login page and the documented `curl` recovery already send
+ that.
- Fixed approving or rejecting an unknown pending write
(`POST /admin/pending-writes/{id}/approve` or `/reject`) answering 500 instead
of 404. An id outside the given workspace and project now answers 404 too.
diff --git a/crates/ai-memory-mcp/src/human_auth.rs b/crates/ai-memory-mcp/src/human_auth.rs
index 2547e177..23adcbf2 100644
--- a/crates/ai-memory-mcp/src/human_auth.rs
+++ b/crates/ai-memory-mcp/src/human_auth.rs
@@ -581,6 +581,43 @@ async fn dummy_login_failure(runtime: &HumanAuthRuntime, ip: IpAddr, password: S
}
}
+/// Whether the request declares a JSON body, by the rule axum's `Json`
+/// extractor applies: `application/json` or `application/*+json`, parameters
+/// and case ignored.
+///
+/// `/auth/login` and `/auth/recovery` read their bodies by hand so they can
+/// rate-limit first, which skipped that check. A page on another site can
+/// `POST` `text/plain` (or a form) cross-origin without a preflight, which let
+/// it sign the operator's browser into an account of its choosing or spend the
+/// login budget guessing passwords. A JSON content type needs a preflight
+/// these routes never answer. The built-in login page, the frontend API
+/// examples and the recovery `curl` all send `application/json`.
+fn declares_json_body(headers: &HeaderMap) -> bool {
+ let Some(value) = headers
+ .get(header::CONTENT_TYPE)
+ .and_then(|v| v.to_str().ok())
+ else {
+ return false;
+ };
+ let essence = value
+ .split(';')
+ .next()
+ .unwrap_or_default()
+ .trim()
+ .to_ascii_lowercase();
+ essence == "application/json"
+ || essence
+ .strip_prefix("application/")
+ .is_some_and(|subtype| subtype.len() > "+json".len() && subtype.ends_with("+json"))
+}
+
+fn unsupported_media_type() -> Response {
+ json_err(
+ StatusCode::UNSUPPORTED_MEDIA_TYPE,
+ "expected Content-Type: application/json",
+ )
+}
+
async fn handle_login(
State(state): State<Arc<AuthState>>,
req: Request<axum::body::Body>,
@@ -588,6 +625,9 @@ async fn handle_login(
let Some(runtime) = state.human.as_ref() else {
return json_err(StatusCode::UNAUTHORIZED, "auth required");
};
+ if !declares_json_body(req.headers()) {
+ return unsupported_media_type();
+ }
let headers = req.headers().clone();
let ip = peer_ip(&headers, req.extensions(), &runtime.trusted_proxy_cidrs);
if runtime.limiter.ip_blocked(ip) {
@@ -682,6 +722,9 @@ async fn handle_recovery(
let Some(runtime) = state.human.as_ref() else {
return generic();
};
+ if !declares_json_body(req.headers()) {
+ return unsupported_media_type();
+ }
let headers = req.headers().clone();
let ip = peer_ip(&headers, req.extensions(), &runtime.trusted_proxy_cidrs);
if runtime.limiter.ip_blocked(ip) {
@@ -2088,6 +2131,118 @@ mod tests {
assert!(set_cookie_value(fresh.headers(), SESSION_COOKIE).is_some());
}
+ #[test]
+ fn json_body_declaration() {
+ for (value, json) in [
+ (Some("application/json"), true),
+ (Some("application/json; charset=utf-8"), true),
+ (Some("Application/JSON"), true),
+ (Some("application/vnd.api+json"), true),
+ (None, false),
+ (Some(""), false),
+ (Some("text/plain"), false),
+ (Some("text/plain;charset=UTF-8"), false),
+ (Some("application/x-www-form-urlencoded"), false),
+ (Some("multipart/form-data; boundary=x"), false),
+ (Some("application/+json"), false),
+ (Some("text/json"), false),
+ (Some("application/jsonp"), false),
+ ] {
+ let mut headers = HeaderMap::new();
+ if let Some(value) = value {
+ headers.insert(header::CONTENT_TYPE, value.parse().unwrap());
+ }
+ assert_eq!(declares_json_body(&headers), json, "{value:?}");
+ }
+ }
+
+ /// A foreign page can `POST` the three CORS-safelisted content types
+ /// without a preflight. Neither public auth route may act on one: no
+ /// session for the attacker's account (login CSRF), no password check
+ /// (guessing), no root reset.
+ #[tokio::test]
+ async fn public_auth_routes_refuse_preflight_free_browser_bodies() {
+ let recovery = "break-glass-recovery-token-32chr";
+ let (_tmp, state, password) = human_fixture(Some(recovery)).await;
+ let new_password = "brand-new-pass!!";
+ let send = |path: &'static str, content_type: Option<&'static str>, body: Vec<u8>| {
+ let state = state.clone();
+ async move {
+ let mut req = axum::http::Request::builder().method("POST").uri(path);
+ // A JSON body is what only a same-origin page or a non-browser
+ // client can send; everything else comes from the foreign page.
+ req = if content_type.is_some_and(|c| c.starts_with("application/json")) {
+ req.header("origin", "http://127.0.0.1:49374")
+ .header("sec-fetch-site", "same-origin")
+ } else {
+ req.header("origin", "https://evil.example")
+ .header("sec-fetch-site", "cross-site")
+ };
+ if let Some(content_type) = content_type {
+ req = req.header("content-type", content_type);
+ }
+ public_auth_router(state)
+ .oneshot(req.body(axum::body::Body::from(body)).unwrap())
+ .await
+ .unwrap()
+ }
+ };
+ let login_body = serde_json::to_vec(&serde_json::json!({
+ "username": "root",
+ "password": password,
+ }))
+ .unwrap();
+ let recovery_body = serde_json::to_vec(&serde_json::json!({
+ "recovery_token": recovery,
+ "new_password": new_password,
+ "new_password_confirmation": new_password,
+ }))
+ .unwrap();
+ // More attempts than the per-IP failure budget, so a refusal that
+ // still charged it would lock out the control login below.
+ for _ in 0..=LOGIN_IP_LIMIT {
+ for content_type in [
+ Some("text/plain;charset=UTF-8"),
+ Some("application/x-www-form-urlencoded"),
+ Some("multipart/form-data; boundary=----a0"),
+ None,
+ ] {
+ let login = send("/auth/login", content_type, login_body.clone()).await;
+ assert_eq!(
+ login.status(),
+ StatusCode::UNSUPPORTED_MEDIA_TYPE,
+ "login as {content_type:?}"
+ );
+ assert!(
+ login.headers().get(header::SET_COOKIE).is_none(),
+ "a refused login must not issue a session ({content_type:?})"
+ );
+ let reset = send("/auth/recovery", content_type, recovery_body.clone()).await;
+ assert_eq!(
+ reset.status(),
+ StatusCode::UNSUPPORTED_MEDIA_TYPE,
+ "recovery as {content_type:?}"
+ );
+ }
+ }
+ // Controls: the root password is unchanged and the login budget
+ // untouched, so a JSON login (what the built-in page sends) works.
+ let control = send(
+ "/auth/login",
+ Some("application/json; charset=utf-8"),
+ login_body,
+ )
+ .await;
+ assert_eq!(control.status(), StatusCode::OK);
+ assert!(set_cookie_value(control.headers(), SESSION_COOKIE).is_some());
+ let reset = send("/auth/recovery", Some("application/json"), recovery_body).await;
+ assert_eq!(
+ reset.status(),
+ StatusCode::NO_CONTENT,
+ "JSON recovery works"
+ );
+ }
+
fn introspect_state(state: Arc<AuthState>) -> Arc<AuthState> {
let human = state.human.clone().expect("human runtime");
Arc::new(
diff --git a/docs/frontend-api.md b/docs/frontend-api.md
index 40341b42..9dc47334 100644
--- a/docs/frontend-api.md
+++ b/docs/frontend-api.md
@@ -62,6 +62,9 @@ Content-Type: application/json
{"username":"alice","password":"…"}
```
+`/auth/login` and `/auth/recovery` answer 415 to any other content type, so a
+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 values
in `localStorage`. Before any human password or completed bootstrap exists,
deprecated GET-only browser compatibility may accept the root bearer through
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 55fb0690..c613c800 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -34,6 +34,7 @@ means the boundary is not built yet.
| 2b | Managed-workstream discovery stays checkout-local, including pagination | `ai-memory-workstream/src/repository.rs` `inspect_repository_fingerprints` shares the launch identity derivation without checkpoint scans; `ai-memory-cli/src/commands/resume.rs` `candidates_for_checkout` queries only the cwd, never registry links; the explicit `--all` walk (`candidates_across_checkouts`) lists each linked checkout through its own fingerprint-scoped request and applies `--workspace` before any request; `ai-memory-hooks/src/workstream.rs` `list_recent_workstreams` resolves an authorized explicit scope on every page; `ai-memory-store/src/workstream.rs` `list_recent` applies workspace/project/repository/worktree predicates before `LIMIT`/`OFFSET` | `resume.rs` `resume_lists_all_current_checkout_rows_not_registered_foreign_checkouts` (same scope/remote foreign checkout refused, 125 local rows visible), `empty_current_checkout_does_not_fall_back_to_the_registry`, `resume_all_walks_every_linked_checkout_and_honours_the_workspace_filter` (a foreign workspace filter sends no request; the default picker still ignores the registry); `workstream.rs` `recent_workstream_pages_reach_older_rows_without_crossing_checkout_or_scope` (foreign repo, worktree, project and workspace excluded on every page; 105 legitimate rows reach the client, huge offsets return nothing); store `recent_workstreams_are_checkout_local_and_include_linked_harnesses` (page two keeps native harness links); `repository.rs` `reports_origin_push_url_and_linked_worktree` verifies lightweight/full fingerprint parity and distinct worktree keys; CLI `resume_yolo_displays_picker_without_scanning_git_status` verifies listing skips status scans | STRONG |
| 3 | Multi-user auth ladder | `ai-memory-core/src/actor.rs` `AuthLevel::authorize`; `ai-memory-mcp/src/auth.rs` middleware; `admin.rs` `require_root_for_multiuser_admin` / `require_root`; `identity.rs` authorizes `NormalRead` behind the same machine bearer middleware as MCP; `serve.rs` mounts API-only and web+API protected routers behind `require_dual_auth` | `admin.rs` `multiuser_admin_routes_reject_db_user_tier` / `…reject_anonymous` / `create_user_as_user_tier_returns_403`; `auth.rs` unknown-bearer 401; `actor.rs` `skip_admission_chain_rejects_db_users`; `identity.rs` `identity_real_auth_isolates_users_root_and_revoked_keys`, `identity_anonymous_ignores_forged_headers_and_proxy_qualifies_oidc` (distinct users and root, invalid/revoked keys, forged headers, anonymous control); `serve.rs` `api_only_mode_keeps_data_authenticated_and_web_absent` (anonymous API read refused, authenticated control admitted, browser route absent; #986) | STRONG |
| 3b | Browser triage of pending writes (#855) | `ai-memory-web/src/routes/pending.rs` `require_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`, trusted-proxy flag from `WebMountSpec`) gates `GET {web_slug}/pending`; `html_auth.rs` `AdminRequired` keeps a non-root 403 off the change-password redirect; decisions post to the existing `/admin/pending-writes/{id}/approve\|reject` behind `require_dual_auth` (session + CSRF) and `require_root_for_multiuser_admin`. `ai-memory-web` has no write route | `ai-memory-web` `tests/suite/pending.rs` — anonymous refused (401, login redirect), DB user refused (403, no proposal text, no redirect), trusted-proxy flag reaches the gate, single-operator control admits, POSTs to `/pending*` refused, project filter keys do not collide on `/` in names, projects past the 500-row read cap stay counted and reachable; `ai-memory-mcp` `tests/suite/admin_pending_writes_session.rs` — anonymous and DB-user sessions refused, root session without a matching CSRF header refused (each leaves the proposal pending and no file), root approval keeps `auto_improve_proposal_id`/`auto_improve_run_id` and records the approver, root reject writes no file (each proven to fail with its guard removed) | STRONG |
+| 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` |
| 4 | Handoff single-claim / no-steal | `ai-memory-store/src/ops.rs` `accept_handoff_in_transaction` (metadata `state='open'` guard + atomic CAS) | `multi_session.rs` `a_second_accept_cannot_steal_an_accepted_handoff`; `handoff_ownership.rs` `another_operator_cannot_claim_the_handoff` | 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/security.md b/docs/security.md
index 7f75aaf1..e7792f9b 100644
--- a/docs/security.md
+++ b/docs/security.md
@@ -80,7 +80,10 @@ keep working unchanged. A browser that sends no fetch metadata even to loopback
(Safari before 16.4) only gets the `Origin` check there, which an image or link
does not trigger; set a bearer token if you use one. The `Host`
allowlist refuses DNS-rebinding hostnames, and the JSON-only routes refuse the
-content types a browser can send without a CORS preflight. Images in wiki pages
+content types a browser can send without a CORS preflight. The public sign-in
+routes (`POST /auth/login`, `POST /auth/recovery`) accept only
+`application/json` bodies too, so a page on another site cannot sign your
+browser in or try passwords. Images in wiki pages
rendered by the web UI may only use relative paths that stay inside the UI, so
viewing a stored page cannot make your browser call those routes either.
diff --git a/docs/users.md b/docs/users.md
index 4fc71668..4ae6844a 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -80,11 +80,11 @@ plus a separate CSRF cookie that the SPA must send on cookie-authenticated
| Endpoint | Class | Notes |
|---|---|---|
-| `POST /auth/login` | public | Rate-limited. Returns the `/auth/me` snapshot plus `Set-Cookie`. |
+| `POST /auth/login` | public | Rate-limited; `application/json` body only (415 otherwise). Returns the `/auth/me` snapshot plus `Set-Cookie`. |
| `GET /auth/me` | session | Identity, `role`, `must_change_password`, capabilities. Anonymous only in zero-config loopback. |
| `POST /auth/password` | session + CSRF | Changes password, revokes other sessions, rotates this one. |
| `POST /auth/logout` | session + CSRF | Revokes the session and expires cookies. |
-| `POST /auth/recovery` | public | Break-glass for the configured `root_username`. Never issues a session. |
+| `POST /auth/recovery` | public | Break-glass for the configured `root_username`; `application/json` body only (415 otherwise). Never issues a session. |
Passwords are Argon2id PHC strings, 12–1024 UTF-8 bytes, hashed off the writer
actor. The last enabled root with a password cannot be disabled or demoted.