Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
test(mcp): pin #999's viewer at the memory_read_page call site
AkitaOnRailsef2e83a2d2c2
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 25375ef5..deffdc48 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -12150,6 +12150,138 @@ mod tests {.expect("with no viewer, an existing install must be unchanged");}+ /// #999 at the MCP surface: an authenticated user without a grant must not+ /// learn about pages in a `restricted` project through+ /// `memory_read_page { include_related: true }`. The store tests pin the+ /// walk's per-hop filter; this pins that the tool passes the caller's+ /// viewer into it — passing `None` there reopened the leak with every store+ /// test still green. Control: with no viewer (root, or authorization off)+ /// the same walk still reaches the cross-project page.+ #[tokio::test]+ async fn bob_does_not_see_restricted_pages_through_the_related_walk() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let app = store+ .writer+ .get_or_create_project(ws, "app", None)+ .await+ .unwrap();+ let secret = store+ .writer+ .get_or_create_project(ws, "secret", None)+ .await+ .unwrap();+ let page = |project, path: &str, links| ai_memory_core::NewPage {+ workspace_id: ws,+ project_id: project,+ path: ai_memory_core::PagePath::new(path).unwrap(),+ title: path.to_string(),+ body: "body".into(),+ tier: ai_memory_core::Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links,+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ };+ let link_to_secret = ai_memory_core::LinkTarget {+ workspace: None,+ project: Some("secret".to_string()),+ path: ai_memory_core::PagePath::new("notes/s.md").unwrap(),+ relation: None,+ };+ store+ .writer+ .upsert_page(page(secret, "notes/s.md", Vec::new()))+ .await+ .unwrap();+ store+ .writer+ .upsert_page(page(app, "notes/a.md", vec![link_to_secret]))+ .await+ .unwrap();+ store+ .writer+ .set_access_mode(secret, ai_memory_store::AccessMode::Restricted)+ .await+ .unwrap();+ let bob = store+ .writer+ .create_human_user(+ NewUser {+ username: "bob".into(),+ name: None,+ email: None,+ },+ ai_memory_core::UserRole::User,+ None,+ false,+ )+ .await+ .unwrap();++ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, app)+ .with_wiki(wiki);+ let related_as = |viewer: Option<ai_memory_core::UserId>| {+ let server = &server;+ async move {+ let mut parts = test_parts_default();+ parts.extensions.insert(AuthLevel::User);+ parts.extensions.insert(bob);+ if let Some(viewer) = viewer {+ parts+ .extensions+ .insert(ai_memory_core::AuthorizedViewer(viewer));+ }+ let result = server+ .memory_read_page(+ Parameters(ReadPageArgs {+ include_related: true,+ related_depth: Some(3),+ path: Some("notes/a.md".into()),+ query: None,+ project: None,+ workspace: None,+ }),+ OptionalParts(parts),+ )+ .await+ .expect("the open project's page is readable");+ call_tool_json(result)["related"]+ .as_array()+ .expect("include_related attaches a related block")+ .iter()+ .map(|node| {+ format!(+ "{}:{}",+ node["project"].as_str().unwrap_or_default(),+ node["path"].as_str().unwrap_or_default()+ )+ })+ .collect::<Vec<_>>()+ }+ };++ let as_bob = related_as(Some(bob)).await;+ assert!(+ as_bob.iter().all(|node| !node.starts_with("secret:")),+ "a restricted page leaked through the related walk: {as_bob:?}"+ );+ let unrestricted = related_as(None).await;+ assert!(+ unrestricted.contains(&"secret:notes/s.md".to_string()),+ "control: with no viewer the walk still reaches it: {unrestricted:?}"+ );+ }+/// The other half of #708: bob could not open alice's page, but he could/// still find it. `global` searches and the `default_global` recent/// listing never resolve a scope, so the resolver guard never saw them.diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 5cf58d4e..986093d3 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -60,7 +60,7 @@ boundary not yet built.| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository`; `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them || 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`; `router.rs` `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others || 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) |-| 14d | `include_related` shows and walks only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` applies, so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed | STRONG |+| 14d | `include_related` shows and walks only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` applies, so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed; `ai-memory-mcp` `server.rs` `bob_does_not_see_restricted_pages_through_the_related_walk` (an ungranted user's `memory_read_page{include_related}` omits the restricted page; control: no viewer still reaches it) — fails with `memory_read_page` passing `None` instead of `viewer_from_parts` | STRONG |## Keeping this current (the standing protocol)