Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(audit-P1): harden cwd prefix-match against boundary leaks + 5 tests
AkitaOnRails3c9e90e032e8
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 82798561..6829abca 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -1174,6 +1174,236 @@ mod tests {);}+ /// Boundary: prefix-match is workspace-scoped. A project in+ /// workspace A whose `repo_path` would otherwise match a cwd+ /// must NEVER be picked when the hook event resolves to workspace+ /// B (a `workspace_override` carried in the event's query string).+ #[tokio::test]+ async fn resolve_does_not_leak_across_workspaces_on_prefix_match() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let other_ws = state+ .writer+ .get_or_create_workspace(String::from("other"))+ .await+ .unwrap();+ // Parent project lives in `other`, not in the default workspace.+ let other_parent_id = state+ .writer+ .get_or_create_project(+ other_ws,+ String::from("manga-plus"),+ Some(String::from("/repo/manga-plus")),+ )+ .await+ .unwrap();++ // Hook fires WITHOUT `workspace` override, so it resolves to+ // the default workspace. The `other` project must not be picked.+ let (resolved_ws, resolved_proj) = resolve_project_ids(+ &state,+ Some("/repo/manga-plus/reader"),+ None,+ None,+ ProjectStrategy::Basename,+ &ai_memory_core::ActorKey::default(),+ )+ .await+ .unwrap();+ assert_ne!(resolved_ws, other_ws);+ assert_ne!(+ resolved_proj, other_parent_id,+ "must not pick a project from a foreign workspace"+ );+ }++ /// Boundary: a stored `repo_path` whose value is degenerate+ /// (empty, single slash, trailing slash) MUST NOT match every+ /// cwd. The WHERE filters reject each shape; this asserts the+ /// integrated behaviour end-to-end.+ #[tokio::test]+ async fn resolve_ignores_degenerate_repo_paths() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let ws = state+ .writer+ .get_or_create_workspace(String::from(DEFAULT_WORKSPACE_NAME))+ .await+ .unwrap();+ // Three poison rows that would each match too broadly without+ // the safety filters.+ for (name, repo) in [+ ("empty-repo", String::new()),+ ("root-repo", String::from("/")),+ ("trailing-repo", String::from("/repo/foo/")),+ ] {+ state+ .writer+ .get_or_create_project(ws, String::from(name), Some(repo))+ .await+ .unwrap();+ }++ // Resolve a cwd that the three poison rows would each match+ // pre-fix. Expect: a NEW project created by basename.+ let (resolved_ws, resolved) = resolve_project_ids(+ &state,+ Some("/repo/foo/bar"),+ None,+ None,+ ProjectStrategy::Basename,+ &ai_memory_core::ActorKey::default(),+ )+ .await+ .unwrap();+ let by_name = state+ .reader+ .find_project(resolved_ws, String::from("bar"))+ .await+ .unwrap();+ assert_eq!(+ by_name,+ Some(resolved),+ "degenerate repo_paths must NOT match — fall through to create"+ );+ }++ /// Boundary: `/foo/bar` MUST NOT match a stored `/foo/ba` sibling+ /// (the `/` boundary on the descendant arm).+ #[tokio::test]+ async fn resolve_does_not_match_sibling_substring() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let ws = state+ .writer+ .get_or_create_workspace(String::from(DEFAULT_WORKSPACE_NAME))+ .await+ .unwrap();+ state+ .writer+ .get_or_create_project(+ ws,+ String::from("foo-ba"),+ Some(String::from("/repo/foo-ba")),+ )+ .await+ .unwrap();+ let (resolved_ws, resolved) = resolve_project_ids(+ &state,+ Some("/repo/foo-bar"),+ None,+ None,+ ProjectStrategy::Basename,+ &ai_memory_core::ActorKey::default(),+ )+ .await+ .unwrap();+ let by_name = state+ .reader+ .find_project(resolved_ws, String::from("foo-bar"))+ .await+ .unwrap();+ assert_eq!(+ by_name,+ Some(resolved),+ "sibling substring (`foo-ba` vs `foo-bar`) must not match"+ );+ }++ /// Boundary: a cwd containing dot-segments (`/foo/../bar`,+ /// `/./x`) is rejected by the canonicaliser so it can't be+ /// LIKE-matched against an unrelated parent.+ #[tokio::test]+ async fn resolve_ignores_cwds_with_dot_segments() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let ws = state+ .writer+ .get_or_create_workspace(String::from(DEFAULT_WORKSPACE_NAME))+ .await+ .unwrap();+ let parent_id = state+ .writer+ .get_or_create_project(+ ws,+ String::from("manga-plus"),+ Some(String::from("/repo/manga-plus")),+ )+ .await+ .unwrap();+ for cwd in [+ "/repo/manga-plus/../other",+ "/repo/./manga-plus/x",+ "/repo/manga-plus/./y",+ ] {+ let (_ws, resolved) = resolve_project_ids(+ &state,+ Some(cwd),+ None,+ None,+ ProjectStrategy::Basename,+ &ai_memory_core::ActorKey::default(),+ )+ .await+ .unwrap();+ assert_ne!(+ resolved, parent_id,+ "cwd `{cwd}` contains a dot-segment — must NOT match the parent"+ );+ }+ }++ /// Boundary: a stored `repo_path` containing LIKE wildcards+ /// (`%`, `_`) MUST NOT widen the match set.+ #[tokio::test]+ async fn resolve_ignores_repo_paths_with_like_wildcards() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let ws = state+ .writer+ .get_or_create_workspace(String::from(DEFAULT_WORKSPACE_NAME))+ .await+ .unwrap();+ state+ .writer+ .get_or_create_project(+ ws,+ String::from("poison-percent"),+ Some(String::from("/repo/anything%/poison")),+ )+ .await+ .unwrap();+ state+ .writer+ .get_or_create_project(+ ws,+ String::from("poison-underscore"),+ Some(String::from("/repo/anyth_ng")),+ )+ .await+ .unwrap();+ let (resolved_ws, resolved) = resolve_project_ids(+ &state,+ Some("/repo/anything-foo/poison/sub"),+ None,+ None,+ ProjectStrategy::Basename,+ &ai_memory_core::ActorKey::default(),+ )+ .await+ .unwrap();+ let by_name = state+ .reader+ .find_project(resolved_ws, String::from("sub"))+ .await+ .unwrap();+ assert_eq!(+ by_name,+ Some(resolved),+ "stored repo_path with LIKE wildcards must NOT match"+ );+ }+/// Cold-start preservation: when NO existing project's `repo_path`/// prefix-matches the cwd, the resolver must fall through to the/// previous create-by-basename behaviour. This is the "first timediff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 28378b08..1447624d 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -2710,18 +2710,38 @@ impl ReaderPool {/// Find the existing project whose `repo_path` is the longest/// prefix of `cwd`, if any. Used by the hook router before- /// auto-creating a new project from `basename(cwd)` — so an- /// event whose cwd is inside an existing project's tree resolves- /// to that parent instead of materialising a fragment project- /// for the subdirectory name.+ /// auto-creating a new project from `basename(cwd)` so an event+ /// whose cwd is inside an existing project's tree resolves to+ /// that parent instead of materialising a fragment project for+ /// the subdirectory name.////// `ORDER BY length(repo_path) DESC` picks the most-specific/// match: if the operator declared a sub-project via/// `.ai-memory.toml` (which writes its own row with a longer/// `repo_path`), the sub-project wins over its outer parent.- /// Projects without a `repo_path` (older rows, or those created- /// without a usable cwd) cannot match and are filtered out by the- /// `IS NOT NULL` predicate.+ ///+ /// **Boundary safety.** Every layer of this query has explicit+ /// guards so a path-shaped value can't accidentally widen the+ /// match set:+ ///+ /// - `workspace_id = ?1` — never matches a project in another+ /// workspace.+ /// - `repo_path IS NOT NULL AND length(repo_path) > 1 AND repo_path+ /// NOT LIKE '%/'` — rejects stored values that would match too+ /// broadly (`NULL`, `''`, `/`) or fail the `<repo_path>/%`+ /// boundary (trailing slash).+ /// - `repo_path NOT LIKE '%\%%' ESCAPE '\\' AND repo_path NOT+ /// LIKE '%\_%' ESCAPE '\\'` — refuses stored values containing+ /// LIKE wildcards (`%`, `_`) so a stored `repo_path` can never+ /// match unintended siblings.+ /// - Input canonicalisation — trailing slashes stripped; cwds+ /// containing dot-segments (`/foo/../bar`, `/./x`) are rejected+ /// outright so a traversal-style path can't match a parent it+ /// doesn't logically belong to.+ ///+ /// Returns `None` (caller falls through to create-by-basename)+ /// for every defensive case so a bad input degrades the same way+ /// as "no match" rather than picking the wrong project.////// # Errors/// Propagates any SQL or pool error.@@ -2730,23 +2750,25 @@ impl ReaderPool {workspace_id: WorkspaceId,cwd: String,) -> StoreResult<Option<(ProjectId, String)>> {- // Trim any trailing slash so the LIKE prefix match treats- // `<repo_path>` and `<repo_path>/` identically (the column is- // canonically stored without a trailing slash on insert).let cwd_norm = cwd.trim_end_matches('/').to_string();- if cwd_norm.is_empty() {+ if !is_safe_cwd_for_prefix_match(&cwd_norm) {return Ok(None);}self.with_conn(move |conn| {- // Two-condition LIKE: exact match OR descendant (prefix- // plus `/`). The `/%` half stops `/foo/bar` from- // accidentally matching a stored `/foo/ba` — boundary- // checking is what makes this safe.+ // Two-condition LIKE: exact match OR descendant (prefix ++ // `/`). The boundary `/` on the descendant arm stops+ // `/foo/bar` from matching `/foo/ba`. The WHERE filters+ // reject any stored repo_path that would slip past the+ // boundary (empty, `/`, trailing-slash, LIKE wildcards).let row_opt = conn.query_row("SELECT id, name FROM projects \WHERE workspace_id = ?1 \AND repo_path IS NOT NULL \+ AND length(repo_path) > 1 \+ AND repo_path NOT LIKE '%/' \+ AND repo_path NOT LIKE '%\\%%' ESCAPE '\\' \+ AND repo_path NOT LIKE '%\\_%' ESCAPE '\\' \AND (?2 = repo_path OR ?2 LIKE repo_path || '/%') \ORDER BY length(repo_path) DESC \LIMIT 1",@@ -3524,6 +3546,34 @@ fn briefing_page_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoreResu}))}+/// Reject cwds that can't safely participate in a `repo_path` prefix+/// match. Trailing slash is already trimmed by the caller; this catches:+/// empty / single-slash / dot-segments (a `/foo/../bar` resolved-by-LIKE+/// could match a stored `/foo` parent the cwd doesn't logically belong+/// to, since LIKE doesn't normalise paths) / LIKE wildcards (`%`, `_`)+/// in the input itself. Treats any failure as "no match" so the caller+/// falls through to the safe create-by-basename path.+fn is_safe_cwd_for_prefix_match(cwd: &str) -> bool {+ if cwd.is_empty() || cwd == "/" {+ return false;+ }+ if cwd.contains('%') || cwd.contains('_') {+ // LIKE wildcards in the BOUND value are taken literally (?2+ // is parameter-bound, not interpolated), so this isn't a+ // safety issue per se — but a `_` in a cwd is so unusual it's+ // more likely to be a sign of an unexpected payload than a+ // legit match, and rejecting it costs nothing. `%` is even+ // less likely in a real path.+ return false;+ }+ for segment in cwd.split('/') {+ if segment == "." || segment == ".." {+ return false;+ }+ }+ true+}+fn checkout(inner: &Inner) -> StoreResult<Connection> {if let Some(conn) = inner.pool.lock().pop() {return Ok(conn);