Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(serve): refuse non-fetch browser requests on an unauthenticated server
AkitaOnRails2138bf74bed5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9dd9491d..62c53034 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,10 +11,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Fixed a web page open in the operator's browser being able to act on anunauthenticated server (the loopback default, no token), such as claiming aproject's pending handoff or starting admin jobs. With auth off, the machine- and admin routes now refuse requests a browser marks as coming from another- site; hooks, the CLI, MCP clients and the built-in web UI are unaffected, and- servers with a bearer token are unchanged. Images in wiki pages rendered by- the web UI are also limited to relative paths that stay inside the UI.+ and admin routes now refuse browser requests that come from another site or+ that are not script calls from a page, such as links and images; hooks, the+ CLI, MCP clients and the built-in web UI are unaffected, and servers with a+ bearer token are unchanged. Images in wiki pages rendered by the web UI are+ also limited to relative paths that stay inside the UI.(GHSA-6mc4-46pr-w82w)- Fixed approving or rejecting an unknown pending write(`POST /admin/pending-writes/{id}/approve` or `/reject`) answering 500 insteaddiff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 7a1f1b10..4fa5e93c 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -2942,6 +2942,14 @@ async fn require_allowed_host(/// `Sec-Fetch-Site`; the built-in web UI's same-origin calls into `/admin`/// pass. With auth on, the bearer token (which a foreign page cannot attach)/// and the session CSRF token are the gate instead.+///+/// The same layer also refuses any browser request whose `Sec-Fetch-Dest` is+/// not `empty`. Script `fetch()`/XHR, which is how the web UI calls `/admin`,+/// sends `empty`; images, navigations, link clicks, iframes and form posts+/// send another destination. That keeps a link or image stored in a page, or+/// a link opened from another application, off these routes even when the+/// browser labels it `same-origin` or `none`. Non-browser clients send no+/// fetch metadata and are unaffected.fn refuse_cross_origin_browser_requests(router: axum::Router, auth_enabled: bool) -> axum::Router {if auth_enabled {return router;@@ -2950,7 +2958,8 @@ fn refuse_cross_origin_browser_requests(router: axum::Router, auth_enabled: bool}async fn require_same_origin_browser(req: Request<Body>, next: Next) -> Response {- if !is_cross_origin_browser_request(req.headers()) {+ let headers = req.headers();+ if !is_cross_origin_browser_request(headers) && !is_non_script_browser_request(headers) {return next.run(req).await;}// Any page the operator opens can trigger this at will, so it stays out@@ -2958,13 +2967,10 @@ async fn require_same_origin_browser(req: Request<Body>, next: Next) -> Responsetracing::debug!(path = req.uri().path(),origin = ?req.headers().get(header::ORIGIN),- "rejected cross-origin browser request to an unauthenticated server"+ dest = ?req.headers().get("sec-fetch-dest"),+ "rejected browser request to an unauthenticated server");- (- StatusCode::FORBIDDEN,- "cross-origin browser request refused\n",- )- .into_response()+ (StatusCode::FORBIDDEN, "browser request refused\n").into_response()}/// Whether a browser marks this request as issued by a page of another origin.@@ -2992,6 +2998,15 @@ fn is_cross_origin_browser_request(headers: &axum::http::HeaderMap) -> bool {}}+/// Whether a browser says this request was not issued by script `fetch()` or+/// XHR (`Sec-Fetch-Dest` other than `empty`). A value that is not valid UTF-8+/// is refused; an absent header leaves the decision to the origin check.+fn is_non_script_browser_request(headers: &axum::http::HeaderMap) -> bool {+ headers+ .get("sec-fetch-dest")+ .is_some_and(|dest| !dest.to_str().is_ok_and(|d| d.eq_ignore_ascii_case("empty")))+}+fn host_allowed(host: &str, allowed_hosts: &[String]) -> bool {allowed_hosts.iter().any(|allowed| {host.eq_ignore_ascii_case(allowed) || host_without_port(host).eq_ignore_ascii_case(allowed)@@ -4980,6 +4995,53 @@ mod tests {}}+ #[test]+ fn non_script_browser_request_detection() {+ for (pairs, refused) in [+ // No fetch metadata (hooks, CLI, MCP clients): the origin check decides.+ (&[][..], false),+ (&[("sec-fetch-site", "same-origin")][..], false),+ // Script fetch()/XHR, as the web UI sends.+ (&[("sec-fetch-dest", "empty")][..], false),+ (&[("sec-fetch-dest", "EMPTY")][..], false),+ (+ &[+ ("sec-fetch-site", "same-origin"),+ ("sec-fetch-dest", "empty"),+ ][..],+ false,+ ),+ // Images, navigations, frames: refused even same-origin or `none`.+ (&[("sec-fetch-dest", "image")][..], true),+ (&[("sec-fetch-dest", "document")][..], true),+ (&[("sec-fetch-dest", "iframe")][..], true),+ (+ &[+ ("sec-fetch-site", "same-origin"),+ ("sec-fetch-dest", "image"),+ ][..],+ true,+ ),+ (+ &[("sec-fetch-site", "none"), ("sec-fetch-dest", "document")][..],+ true,+ ),+ (&[("sec-fetch-dest", "")][..], true),+ ] {+ assert_eq!(+ is_non_script_browser_request(&browser_headers(pairs)),+ refused,+ "{pairs:?}"+ );+ }+ let mut headers = browser_headers(&[]);+ headers.insert(+ "sec-fetch-dest",+ axum::http::HeaderValue::from_bytes(b"emp\xffty").unwrap(),+ );+ assert!(is_non_script_browser_request(&headers), "non-UTF-8 dest");+ }+#[tokio::test]async fn cross_origin_browser_guard_applies_only_without_auth() {use tower::ServiceExt as _;@@ -5009,17 +5071,59 @@ mod tests {send(false, &[("origin", "https://evil.example")]).await,StatusCode::FORBIDDEN);+ // Attack: a same-origin image or a navigation from outside the browser.+ assert_eq!(+ send(+ false,+ &[+ ("sec-fetch-site", "same-origin"),+ ("sec-fetch-dest", "image")+ ]+ )+ .await,+ StatusCode::FORBIDDEN+ );+ assert_eq!(+ send(+ false,+ &[("sec-fetch-site", "none"), ("sec-fetch-dest", "document")]+ )+ .await,+ StatusCode::FORBIDDEN+ );// Controls: a hook-style request, and the web UI's same-origin call.assert_eq!(send(false, &[]).await, StatusCode::OK);assert_eq!(send(false, &[("sec-fetch-site", "same-origin")]).await,StatusCode::OK);+ assert_eq!(+ send(+ false,+ &[+ ("sec-fetch-site", "same-origin"),+ ("sec-fetch-dest", "empty")+ ]+ )+ .await,+ StatusCode::OK+ );// With auth on, the bearer gate decides; this layer stays out of it.assert_eq!(send(true, &[("sec-fetch-site", "cross-site")]).await,StatusCode::OK);+ assert_eq!(+ send(+ true,+ &[+ ("sec-fetch-site", "same-origin"),+ ("sec-fetch-dest", "document")+ ]+ )+ .await,+ StatusCode::OK+ );}#[test]diff --git a/crates/ai-memory-cli/tests/suite/cross_origin_e2e.rs b/crates/ai-memory-cli/tests/suite/cross_origin_e2e.rsindex ba0a3412..72bfe300 100644--- a/crates/ai-memory-cli/tests/suite/cross_origin_e2e.rs+++ b/crates/ai-memory-cli/tests/suite/cross_origin_e2e.rs@@ -17,8 +17,10 @@//! 1. The browser-origin guard on the machine and admin routes//! (`serve::refuse_cross_origin_browser_requests`) refuses a request a//! browser marks as cross-site (`Sec-Fetch-Site`) or, from a browser too old-//! to send fetch metadata, one whose `Origin` names another host. Hooks,-//! the CLI and MCP clients never send either header.+//! to send fetch metadata, one whose `Origin` names another host. It also+//! refuses any request whose `Sec-Fetch-Dest` is not `empty` (a link,+//! image or navigation rather than script `fetch()`). Hooks, the CLI and+//! MCP clients send none of these headers.//! 2. JSON-only extractors (axum `Json`, rmcp's `Content-Type` check) refuse//! the three simple content types with 415, so a preflight-free `POST`//! cannot deliver a body even past guard 1.@@ -568,6 +570,38 @@ mod slow {}}+ // A browser request that is not script fetch(): a link stored in a+ // page (same-origin navigation or image) or a link opened from another+ // application (`Sec-Fetch-Site: none`). The origin check alone lets+ // these through; the destination check refuses them.+ let handoff_url =+ format!("{base}/handoff?agent=claude-code&workspace={WORKSPACE}&project={PROJECT}");+ for (site, dest) in [+ ("same-origin", "document"),+ ("same-origin", "image"),+ ("none", "document"),+ ] {+ let status = client+ .get(&handoff_url)+ .header("sec-fetch-site", site)+ .header("sec-fetch-mode", "navigate")+ .header("sec-fetch-dest", dest)+ .send()+ .await+ .expect("non-fetch browser request")+ .status();+ assert_eq!(+ status,+ StatusCode::FORBIDDEN,+ "/handoff with Sec-Fetch-Site {site} and Sec-Fetch-Dest {dest} must be refused"+ );+ }+ assert_eq!(+ open_handoffs(&client, &base).await,+ 1,+ "a non-fetch browser request must not claim the baton"+ );+// Checked before the legitimate session-start hook below, which// publishes the project itself.assert_eq!(diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 10148c85..41249460 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -75,7 +75,7 @@ means the boundary is not built yet.| 11i | OpenCode executable probing and generated-config cleanup (#1097) | `ai-memory-cli/src/config.rs` captures the full process environment once in typed `RuntimeEnv`; `run.rs` overlays explicit `run --env` values with platform key semantics and uses that same effective environment for executable resolution, probing, and launch without rereading process environment; `opencode_dialect.rs` invokes only direct argv `--version`, caps output and time, and rejects malformed/future majors. Automatic launch skips only OpenCode on probe failure; explicit OpenCode fails. `install_hooks.rs` quarantines the incompatible sibling before reading its exact ownership markers, restores unowned content with an atomic no-replace link, and never deletes or overwrites a concurrent replacement; `install_mcp.rs` owns the shared dual-schema endpoint/token inference used by both installers, rejects conflicting generated V1/V2 entries before mutation, and migrates an alternate-major entry only when endpoint, generated shape, and absent-or-Authorization-only headers match, preserving custom headers and ambiguous entries; auto-wire migrates MCP before hooks infer from that exact config path and skips hook mutation when transition preflight fails | `run.rs` `automatic_opencode_probe_failure_keeps_another_harness_available`, `opencode_executable_probe_selects_v2_for_launch_and_autowire`, effective-child-environment PATH casing controls, fake V1/V2/env-derived-major/malformed/future/timeout executable tests, `setup-agent` V1/V2 no-probe integration controls; `install_hooks.rs` `opencode_plugin_cleanup_removes_only_exact_owned_incompatible_sibling`, `opencode_plugin_cleanup_preserves_a_concurrent_user_replacement`, `opencode_plugin_restore_moves_quarantine_when_destination_is_free`, `opencode_plugin_restore_preserves_an_existing_replacement`, `opencode_plugin_restore_does_not_replace_a_file_created_at_restore_window`, `opencode_plugin_cleanup_does_not_escape_custom_target_directory`; `install_mcp.rs` `opencode_install_reuses_owned_endpoint_and_token_across_major_transitions`, `opencode_install_refuses_conflicting_owned_transition_entries`, `opencode_install_does_not_infer_from_a_user_owned_transition_entry`, `opencode_mcp_migration_moves_only_owned_alternate_shape`, `opencode_mcp_migration_preserves_ambiguous_user_entry`, `opencode_mcp_migration_preserves_custom_headers`, `opencode_mcp_migration_accepts_only_historical_generated_headers` | STRONG for Unix process probes and platform-neutral ownership gates; exact Windows executable resolution remains covered by `run.rs` resolver tests and requires the PR `windows` label || 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls | STRONG || 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments, with `sanitize_events` and `append_boundary_events` scrubbing event/checkpoint/losses content *before* the 64 KiB cap so a cap-straddling secret is never cut into an unmatchable prefix (#1113); `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, scrubbing content with the explicitly supplied configured sanitizer before its 16 KiB store-boundary bound; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`, `workstream_content_is_scrubbed_before_the_store_cap` (a credential straddling the 16 KiB store cap is redacted, not persisted as an unmatchable prefix; benign control verbatim; #1113); `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls), `finish_run_scrubs_event_content_before_the_byte_cap` and `finish_run_scrubs_boundary_events_before_the_byte_cap` (a credential straddling the 64 KiB event cap is redacted in the raw segment and never reaches the index; checkpoint/losses and benign controls; #1113); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten |-| 12c | Browser cross-origin writes refused on an unauthenticated loopback server (a foreign page in the operator's browser, and DNS rebinding) | `serve.rs` `refuse_cross_origin_browser_requests` / `is_cross_origin_browser_request`, layered on the machine (`/mcp`, `/hook*`, `/handoff`, `/workstream/*`, `/identity`) and admin (`/admin/*`) routes when auth is off: `Sec-Fetch-Site` other than `same-origin`/`none` → 403, or, without fetch metadata, an `Origin` whose authority is not the `Host` → 403. Hooks, the CLI and MCP clients send neither header; the web UI's same-origin `/admin/pending-writes` calls pass. Behind it, axum `Json` and rmcp's `Content-Type: application/json` check refuse the preflight-free content types (`text/plain`, form-urlencoded, multipart) with 415; `require_allowed_host` (and rmcp `allowed_hosts` on `/mcp`) refuses a rebinding `Host`; machine/admin routes carry no CORS layer, so a preflight never comes back permissive. A stored wiki page viewed in the built-in web UI could otherwise turn the guard's same-origin allowance into a claim: `ai-memory-web/src/markdown.rs` `safe_image_url` / `is_safe_image_target` render as `#` any image target that is root-relative, a network path, carries a `..` segment (also percent-encoded), or, for a UI mounted at the base-path root, starts with a server route segment | `cli/tests/suite/cross_origin_e2e.rs` `browser_cross_origin_requests_cannot_write_to_an_unauthenticated_loopback_server`, against the shipped `serve`: every write route (`/hook`, `/hook/batch`, MCP `memory_write_page`/`memory_delete_page`/`memory_message_send`/`memory_handoff_accept`, `/admin/write-page`/`delete-page`/`purge-project`/`messages/send`, `/workstream/runs`) × each simple content type × modern, Origin-only and fetch-metadata-only browser shapes → 4xx; body-less `GET /handoff` (which claims the single-use baton), `POST /admin/profile/rebuild` and `POST /admin/backup` → 403; a rebinding `Host` → 403; preflights answer no `Access-Control-Allow-*`. Then a canary scan of the whole data dir, page/project/handoff survival, and legitimate controls (JSON MCP calls, a JSON hook → 202, the web UI's same-origin `/admin/pending-writes` list and approve reach their handlers, the anonymous active-project pointer is unmoved after the refused `/handoff` fetches while the closing hook-style fetch claims the baton and moves it). `serve.rs` `cross_origin_browser_request_detection` (header table) and `cross_origin_browser_guard_applies_only_without_auth`; `ai-memory-web` `markdown.rs` `neutralises_images_that_reach_server_routes` (`/handoff?…`, `/admin/backup`, `//host/…`, `../` and `%2e%2e/` traversal, root-mounted route names refused) with `preserves_relative_images` as the legitimate control | STRONG with listed residuals. Bite checks: with the guard removed, the cross-origin `GET /handoff` returns 200, consumes the baton and moves the active-project pointer (the pre-fix behaviour); with the guard treating `same-origin` as foreign, the web UI control gets 403; with the host layer removed, a rebound `/hook` returns 202; a permissive `CorsLayer` fails the preflight assertion; reverting `is_safe_image_target` to the pre-fix rule fails the markdown test on `/handoff?…`, dropping the percent-decoding fails it on `%2e%2e/`, and emptying the route list fails it on a root-mounted `handoff`. To reproduce the bite on the 415 layer, remove the guard and make `/hook` read a raw body instead of `Json`: a `text/plain` hook then returns 202 and the test fails. Residuals, all closed by setting a bearer token: a browser without fetch metadata (Safari before 16.4) sends neither header on an `<img>` `GET`, so it still reaches `/handoff`; a link opened from another app arrives as `Sec-Fetch-Site: none` and passes, but needs the operator's click; a link (not an image) to a machine route in a stored page viewed in the web UI is a same-origin navigation and passes on click. With auth on, the bearer token and the session CSRF token are the gate and this layer is a no-op |+| 12c | Browser cross-origin writes refused on an unauthenticated loopback server (a foreign page in the operator's browser, and DNS rebinding) | `serve.rs` `refuse_cross_origin_browser_requests` / `is_cross_origin_browser_request`, layered on the machine (`/mcp`, `/hook*`, `/handoff`, `/workstream/*`, `/identity`) and admin (`/admin/*`) routes when auth is off: `Sec-Fetch-Site` other than `same-origin`/`none` → 403, or, without fetch metadata, an `Origin` whose authority is not the `Host` → 403; and `is_non_script_browser_request`: any `Sec-Fetch-Dest` other than `empty` (case-insensitive; non-UTF-8 refused) → 403 whatever `Sec-Fetch-Site` says, so links, images, navigations, iframes and form posts are refused even as `same-origin` or `none`. Hooks, the CLI and MCP clients send none of these headers; the web UI's same-origin `/admin/pending-writes` calls are `fetch()` (`Sec-Fetch-Dest: empty`) and pass. Behind it, axum `Json` and rmcp's `Content-Type: application/json` check refuse the preflight-free content types (`text/plain`, form-urlencoded, multipart) with 415; `require_allowed_host` (and rmcp `allowed_hosts` on `/mcp`) refuses a rebinding `Host`; machine/admin routes carry no CORS layer, so a preflight never comes back permissive. A stored wiki page viewed in the built-in web UI could otherwise turn the guard's same-origin allowance into a claim: `ai-memory-web/src/markdown.rs` `safe_image_url` / `is_safe_image_target` render as `#` any image target that is root-relative, a network path, carries a `..` segment (also percent-encoded), or, for a UI mounted at the base-path root, starts with a server route segment | `cli/tests/suite/cross_origin_e2e.rs` `browser_cross_origin_requests_cannot_write_to_an_unauthenticated_loopback_server`, against the shipped `serve`: every write route (`/hook`, `/hook/batch`, MCP `memory_write_page`/`memory_delete_page`/`memory_message_send`/`memory_handoff_accept`, `/admin/write-page`/`delete-page`/`purge-project`/`messages/send`, `/workstream/runs`) × each simple content type × modern, Origin-only and fetch-metadata-only browser shapes → 4xx; body-less `GET /handoff` (which claims the single-use baton), `POST /admin/profile/rebuild` and `POST /admin/backup` → 403; a rebinding `Host` → 403; preflights answer no `Access-Control-Allow-*`; `GET /handoff` as a same-origin `document` or `image` and as a `Sec-Fetch-Site: none` `document` → 403 with the baton still open. Then a canary scan of the whole data dir, page/project/handoff survival, and legitimate controls (JSON MCP calls, a JSON hook → 202, the web UI's same-origin `/admin/pending-writes` list and approve reach their handlers, the anonymous active-project pointer is unmoved after the refused `/handoff` fetches while the closing hook-style fetch claims the baton and moves it). `serve.rs` `cross_origin_browser_request_detection` and `non_script_browser_request_detection` (header tables) and `cross_origin_browser_guard_applies_only_without_auth` (same-origin `image` and `none` `document` refused, same-origin `empty` passes, both pass with auth on); `ai-memory-web` `markdown.rs` `neutralises_images_that_reach_server_routes` (`/handoff?…`, `/admin/backup`, `//host/…`, `../` and `%2e%2e/` traversal, root-mounted route names refused) with `preserves_relative_images` as the legitimate control | STRONG with listed residuals. Bite checks: with the guard removed, the cross-origin `GET /handoff` returns 200, consumes the baton and moves the active-project pointer (the pre-fix behaviour); with the guard treating `same-origin` as foreign, the web UI control gets 403; with the `Sec-Fetch-Dest` check removed, the same-origin `document` `GET /handoff` returns 200 and the unit guard test lets a same-origin image through; with the host layer removed, a rebound `/hook` returns 202; a permissive `CorsLayer` fails the preflight assertion; reverting `is_safe_image_target` to the pre-fix rule fails the markdown test on `/handoff?…`, dropping the percent-decoding fails it on `%2e%2e/`, and emptying the route list fails it on a root-mounted `handoff`. To reproduce the bite on the 415 layer, remove the guard and make `/hook` read a raw body instead of `Json`: a `text/plain` hook then returns 202 and the test fails. Residual, closed by setting a bearer token: a browser without fetch metadata (Safari before 16.4) sends no `Sec-Fetch-*` header and no `Origin` on an image `GET` or a link click, so such a request still reaches `/handoff` and the other `GET` routes. Browsers that send fetch metadata no longer have the earlier link residuals: a link opened from another app (`Sec-Fetch-Site: none`) and a link clicked in a stored page (`same-origin` navigation) both carry a non-`empty` destination and are refused. With auth on, the bearer token and the session CSRF token are the gate and this layer is a no-op || 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_continued_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050), and to a `/clear`ed session only when that session's own transcript records the `/clear` command and names the run's session as its launch `session_id` from this checkout or below it; `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `claude_continued_session_follows_only_this_checkouts_bg_records` (a concurrent launch's background session, another checkout's, and a non-background record refused; own attachment control); `transcript.rs` `claude_continued_session_follows_only_this_launchs_clear` (an uncleared transcript, a quoted `/clear`, another checkout's clear, a concurrent launch's clear, a subagent file, and a pre-run clear refused; own clear and the newest of two as controls); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`, `a_claude_run_that_was_cleared_follows_the_new_session`; `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous || 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet || 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `interactive_launch_waits_out_a_lapsing_lease_then_proceeds`, and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users |diff --git a/docs/security.md b/docs/security.mdindex 61241f93..72528036 100644--- a/docs/security.md+++ b/docs/security.md@@ -59,7 +59,13 @@ With no token (the loopback default), a web page open in your browser canstill address `127.0.0.1:49374`. The server refuses those requests on themachine and admin routes: a request the browser marks as cross-site(`Sec-Fetch-Site`), or one whose `Origin` is not the server's own host, gets a-403. Hooks, the CLI and MCP clients never send those headers. The `Host`+403. So does any browser request that is not a script `fetch()` call+(`Sec-Fetch-Dest` other than `empty`): a link, image or navigation is refused+even when it comes from the server's own pages or from another application.+Hooks, the CLI and MCP clients never send those headers, and the web UI's own+admin calls use `fetch()`. A browser without fetch metadata (Safari before+16.4) only gets the `Origin` check, 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 thecontent types a browser can send without a CORS preflight. Images in wiki pagesrendered by the web UI may only use relative paths that stay inside the UI, so