Skip to content

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

Rust

test(store): reject foreign or missing receiver session on handoff accept

Vajean10d2b33cbef3c
diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rs
index 19c4a4ed..290b657e 100644
--- a/crates/ai-memory-store/tests/suite/multi_session.rs
+++ b/crates/ai-memory-store/tests/suite/multi_session.rs
@@ -590,6 +590,179 @@ async fn a_second_accept_cannot_steal_an_accepted_handoff() {
);
}
+/// The receiver named in a claim must be a real session of the claim's own
+/// workspace, project and agent kind. A session from a sibling project, from
+/// another workspace (even one using the same project name), of a different
+/// agent kind, or one that does not exist must be refused with `InvalidState`
+/// and must leave the baton open and untouched; a matching receiver still
+/// claims it, and nobody can claim it a second time.
+#[tokio::test]
+async fn handoff_accept_rejects_foreign_or_missing_receiver_session() {
+ /// The columns a claim writes, read straight from the row.
+ #[derive(Debug, PartialEq)]
+ struct ClaimColumns {
+ state: HandoffState,
+ accepted_by: Option<String>,
+ accepted_at: Option<i64>,
+ accepted_by_session: Option<Vec<u8>>,
+ accepted_by_user: Option<String>,
+ }
+
+ async fn claim_columns(store: &Store, id: ai_memory_core::HandoffId) -> ClaimColumns {
+ let handoff_bytes = id.as_bytes().to_vec();
+ store
+ .reader
+ .with_conn(move |conn| {
+ Ok(conn.query_row(
+ "SELECT state, accepted_by, accepted_at, accepted_by_session, \
+ accepted_by_user \
+ FROM handoffs WHERE id = ?1",
+ rusqlite::params![handoff_bytes],
+ |r| {
+ Ok(ClaimColumns {
+ state: r.get::<_, String>(0)?.parse().unwrap(),
+ accepted_by: r.get(1)?,
+ accepted_at: r.get(2)?,
+ accepted_by_session: r.get(3)?,
+ accepted_by_user: r.get(4)?,
+ })
+ },
+ )?)
+ })
+ .await
+ .unwrap()
+ }
+
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+ let sibling_proj = store
+ .writer
+ .get_or_create_project(ws, "sibling-app".to_string(), None)
+ .await
+ .unwrap();
+ let rival_ws = store
+ .writer
+ .get_or_create_workspace("rival".to_string())
+ .await
+ .unwrap();
+ // Same project name as the real one, in another workspace: a lookup by
+ // name alone would conflate the two.
+ let rival_proj = store
+ .writer
+ .get_or_create_project(rival_ws, "shared-app".to_string(), None)
+ .await
+ .unwrap();
+
+ let id = store
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: ws,
+ project_id: proj,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ from_session_id: None,
+ summary: "pick this up".into(),
+ next_steps: Vec::new(),
+ open_questions: Vec::new(),
+ files_touched: Vec::new(),
+ cwd: None,
+ owner_user: None,
+ })
+ .await
+ .unwrap();
+
+ // Every claim names the handoff's own scope and `ClaudeCode`; only the
+ // receiver session varies.
+ let claim = |session: SessionId| HandoffAcceptance {
+ handoff_id: id,
+ workspace_id: ws,
+ project_id: proj,
+ accepting_agent: AgentKind::ClaudeCode,
+ accepting_session: Some(session),
+ accepting_user: None,
+ owner_filter: OwnerFilter::Any,
+ receiving_cwd: None,
+ };
+
+ let valid = open_session(&store, ws, proj, AgentKind::ClaudeCode).await;
+ let other_project = open_session(&store, ws, sibling_proj, AgentKind::ClaudeCode).await;
+ let other_workspace = open_session(&store, rival_ws, rival_proj, AgentKind::ClaudeCode).await;
+ let wrong_agent = open_session(&store, ws, proj, AgentKind::Codex).await;
+ let missing = SessionId::new();
+
+ let open = ClaimColumns {
+ state: HandoffState::Open,
+ accepted_by: None,
+ accepted_at: None,
+ accepted_by_session: None,
+ accepted_by_user: None,
+ };
+ assert_eq!(claim_columns(&store, id).await, open, "fixture starts open");
+
+ for (label, receiver) in [
+ ("a session of a sibling project", other_project),
+ ("a session of another workspace", other_workspace),
+ ("a session of a different agent kind", wrong_agent),
+ ("a session that does not exist", missing),
+ ] {
+ let err = store
+ .writer
+ .accept_handoff(claim(receiver))
+ .await
+ .expect_err(label);
+ assert!(
+ matches!(&err, StoreError::InvalidState(_)),
+ "{label} must be refused as InvalidState, got {err:?}"
+ );
+ assert_eq!(
+ claim_columns(&store, id).await,
+ open,
+ "{label} must leave the handoff open and unclaimed"
+ );
+ }
+
+ // Control: the matching receiver takes the baton.
+ assert!(
+ store.writer.accept_handoff(claim(valid)).await.unwrap(),
+ "a receiver in the handoff's own workspace, project and agent kind claims it"
+ );
+ let accepted = claim_columns(&store, id).await;
+ assert_eq!(accepted.state, HandoffState::Accepted);
+ assert_eq!(
+ accepted.accepted_by.as_deref(),
+ Some(AgentKind::ClaudeCode.as_str())
+ );
+ assert_eq!(
+ accepted.accepted_by_session.as_deref(),
+ Some(&valid.as_bytes()[..])
+ );
+ assert!(accepted.accepted_at.is_some(), "the claim is timestamped");
+ assert_eq!(
+ accepted.accepted_by_user, None,
+ "the claim named no operator"
+ );
+
+ // Nobody claims it twice: neither the same receiver retrying nor another
+ // matching session (the latter reaches the `state = 'open'` guards rather
+ // than the per-receiver early return).
+ let second_match = open_session(&store, ws, proj, AgentKind::ClaudeCode).await;
+ for (label, receiver) in [
+ ("the same receiver retrying", valid),
+ ("a second matching session", second_match),
+ ] {
+ assert!(
+ !store.writer.accept_handoff(claim(receiver)).await.unwrap(),
+ "{label} must not claim an accepted handoff"
+ );
+ assert_eq!(
+ claim_columns(&store, id).await,
+ accepted,
+ "{label} must leave the first claim intact"
+ );
+ }
+}
+
/// Ownership still applies to batons even though pages are shared: the two
/// halves of the model must not collapse into each other.
#[tokio::test]
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 4cf48719..da2fce47 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -22,7 +22,7 @@ means the boundary is not built yet.
| # | Boundary | Enforcing code | Adversarial test(s) | Coverage |
|---|----------|----------------|---------------------|----------|
-| 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)`; `reader.rs` `sessions_for_scope_filtered` joins only consolidation jobs in the requested workspace and project; `reader.rs` `incremental_pages` filters workspace and project before its keyset and limit; `reader.rs` `session_counts_by_agent` filters mixed-source observations by the requested workspace and project | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs`; `session_observations.rs` `consolidation_summary_latest_generation_is_scope_and_owner_bound` (a foreign-scope job is absent; the own latest generation and owner controls pass), `incremental_pages_equal_timestamps_cutoff_expiry_and_foreign_scope` (foreign scope absent with a same-scope control), `mixed_capture_count_scopes_observations_and_preserves_owner_and_window` (foreign-scope observations cannot turn an own session into a mixed one; same-scope control can) | STRONG |
+| 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)`; `reader.rs` `sessions_for_scope_filtered` joins only consolidation jobs in the requested workspace and project; `reader.rs` `incremental_pages` filters workspace and project before its keyset and limit; `reader.rs` `session_counts_by_agent` filters mixed-source observations by the requested workspace and project | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs`; `session_observations.rs` `consolidation_summary_latest_generation_is_scope_and_owner_bound` (a foreign-scope job is absent; the own latest generation and owner controls pass), `incremental_pages_equal_timestamps_cutoff_expiry_and_foreign_scope` (foreign scope absent with a same-scope control), `mixed_capture_count_scopes_observations_and_preserves_owner_and_window` (foreign-scope observations cannot turn an own session into a mixed one; same-scope control can); handoff receiver-session scope: see row 4, `multi_session.rs` `handoff_accept_rejects_foreign_or_missing_receiver_session` (cross-project and cross-workspace receivers refused) | STRONG |
| 1b | Reserved `_global` scope union never leaks a foreign project (#930) | `ai-memory-mcp/src/server.rs` `memory_query` — the union runs for single-project queries (`scopes` empty) and searches **only** `lookup_global_scope`'s reserved `(workspace_id, project_id)`, never an arbitrary project; the double-search guard resolves the *queried* project (named or active) so it can't be tricked into skipping | `server.rs` `global_union_never_leaks_a_foreign_projects_pages` (a third real project's page must not surface via the union; reserved page must), `single_project_query_unions_global_scope_and_multi_scope_skips_it` | STRONG |
| 1c | Reserved `_global` scope is read-open, write-gated (GHSA-7qj3-7wqw-m5w6) | `ai-memory-store/src/project_authz.rs` `ProjectAuthz::authorize` (a write to `default/_global` needs root or a `write` grant in either access mode; creator ignored) fed by `resolve_project_authz`/`read_project_row` (`reserved_global`, grant read for the global scope regardless of mode); `ai-memory-mcp/src/server.rs` `memory_write_page` resolves `scope: "global"` through `write_target_ids_with_actor` like an explicit `default/_global` | `project_authz.rs` `the_global_scope_admits_writes_only_from_root_or_a_write_grant`; `server.rs` `a_user_without_a_global_grant_cannot_change_the_global_scope` (both spellings and delete refused for an ungranted user and for `_global`'s creator; page survives; reads stay open), `a_global_write_grant_admits_writes_and_the_union_stays_readable` (legitimate control: write grant admits both spellings, another user's restricted-project query still unions the page); bite-checked with the authz rule removed and with the raw `create_global_scope` path restored | STRONG |
| 1d | A private cross-project profile is readable and writable by its operator alone (`[profile] share = "user"`) | `ai-memory-store/src/ops.rs` `initial_access_mode` (a `_profile.<user id>` project is always created `restricted`, creator recorded in the same transaction); `ai-memory-store/src/scope.rs` `lookup_profile_scope` / `create_profile_scope` (the project name derives from the authenticated viewer's id; no database user, no private profile); `ai-memory-mcp/src/server.rs` `profile_target_ids` and the `memory_query` profile union (resolved per viewer through the per-project choke point); `scope.rs` `refuse_foreign_profile_name` (called by `ScopeResolver` explicit writes and `create_explicit_scope_guarded`: a database user may name only their own `default/_profile.<id>`, so nobody can create another operator's private profile first and lock its owner out); `ops.rs` `rename_project` (no rename onto or away from a profile name); `admin.rs` `handle_project_access` (a profile project's mode is fixed) and `move_project_core` (a private profile cannot leave `default`) | store `integration::profile` `a_private_profile_refuses_every_other_operator` (another operator's read and write by name refused; owner control admitted), `reserved_profile_projects_get_their_fixed_access_modes`; `server.rs` `a_private_profile_is_private_to_its_operator` (no union leak; read, write and delete by name refused; owner and own-profile controls); `multi_session.rs` `two_harnesses_of_one_operator_share_one_private_profile`; both fail with the restricted-mode guard removed; `server.rs` `a_user_cannot_squat_another_operators_private_profile` (another user's explicit write naming the owner's private profile refused and creates nothing; owner's profile and explicit own-name controls; fails with the name guard removed); `ops.rs` `rename_project_refuses_profile_names_both_ways`; `admin.rs` `project_access_sets_the_mode_and_refuses_what_it_must`; `admin_move.rs` `move_project_refuses_a_private_profile` | STRONG |
@@ -34,7 +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 |
-| 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 |
+| 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) | `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`) | 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 |
| 4d | Native session rebind / drifted-end is owner+agent+cwd CAS | `ai-memory-store/src/ops.rs` — `session.moved` rebind gated on `agent==OpenCode` + `ended_at IS NULL` + lexical `normalize_cwd(stored)==normalize_cwd(from)`; `expire_same_cwd_auto_handoffs` AND-gated on `owner_user IS ?4 AND id IS NOT ?5` and on the source not being another still-open session (row 4e, #883); drifted `SessionEnd` ends only same owner+agent+cwd | `ops.rs` `native_move_rebinds_live_session_only_from_its_current_cwd`, `native_move_rejects_foreign_owner_and_ignores_completed_replay`, `drifted_session_end_ends_only_the_same_actor_agent_and_cwd` (#865) | STRONG |