Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(profile): refuse squatting another operator's private profile name
AkitaOnRails84467abb91a8
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex d59525f4..91c23ab9 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -8719,6 +8719,14 @@ async fn handle_project_access("{project} is the shared preferences scope, read by every user; it cannot be restricted")));}+ // A profile project's mode is fixed by its kind: a private profile stays+ // restricted to its owner, a workspace profile stays readable by the+ // workspace. Changing either would expose or hide a profile wholesale.+ if ai_memory_core::profile::is_profile_project(project) {+ return Err(validation_error(format!(+ "{project} is a cross-project profile; its access mode is fixed"+ )));+ }let (_, project_id) = lookup_ws_proj_no_create(&state, workspace, project).await?;let previous = state.writer@@ -14491,7 +14499,8 @@ mod tests {}/// `POST /admin/projects/access` (#708): a mode is required and never- /// guessed, the shared preferences scope cannot be restricted, an unknown+ /// guessed, the shared preferences scope cannot be restricted, a profile+ /// project's mode is fixed (a private one is never opened), an unknown/// project creates nothing, repeating a mode reports no change, and only/// root may call it.#[tokio::test]@@ -14507,6 +14516,8 @@ mod tests {serde_json::json!({"workspace": "default", "project": "client-work"}),serde_json::json!({"workspace": "default", "project": "client-work", "mode": "members"}),serde_json::json!({"workspace": "default", "project": "_global", "mode": "restricted"}),+ serde_json::json!({"workspace": "default", "project": "_profile", "mode": "restricted"}),+ serde_json::json!({"workspace": "default", "project": "_profile.00000000000000000000000000000001", "mode": "open"}),] {let (status, json) = call("root-token", body.clone()).await;assert_eq!(status, StatusCode::BAD_REQUEST, "{body} -> {json}");diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex d02581dd..528e6ed3 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -13704,6 +13704,67 @@ mod tests {.unwrap_or_default()}+ /// Squatting: before joao has a profile, maria names his private profile+ /// project in an explicit write. Creating it would make her its creator+ /// and lock joao out for good, so it is refused before anything exists.+ /// Controls: joao's own profile then works, and joao may also name his+ /// own private project explicitly.+ #[tokio::test]+ async fn a_user_cannot_squat_another_operators_private_profile() {+ let tmp = TempDir::new().unwrap();+ let (store, server, joao, maria) = global_gate_fixture(&tmp).await;+ let server = server.with_profile(profile_on(ai_memory_core::profile::ProfileShare::Auto));+ let joaos = ai_memory_core::profile::user_profile_project(joao);++ let mut squat = profile_entry("profile/tools/npm.md", None);+ squat.workspace = Some("default".into());+ squat.project = Some(joaos.clone());+ server+ .memory_write_page(Parameters(squat), OptionalParts(parts_as_user(maria)))+ .await+ .expect_err("maria cannot create joao's private profile");+ let ws = store+ .reader+ .find_workspace("default".into())+ .await+ .unwrap()+ .unwrap();+ assert!(+ store+ .reader+ .find_project(ws, joaos.clone())+ .await+ .unwrap()+ .is_none(),+ "the refused write created nothing"+ );+ let mut workspace_profile = profile_entry("profile/tools/npm.md", None);+ workspace_profile.workspace = Some("default".into());+ workspace_profile.project = Some(ai_memory_core::profile::WORKSPACE_PROFILE_PROJECT.into());+ server+ .memory_write_page(+ Parameters(workspace_profile),+ OptionalParts(parts_as_user(maria)),+ )+ .await+ .expect_err("a workspace profile is only created through the profile path");++ server+ .memory_write_page(+ Parameters(profile_entry("tools/pnpm.md", Some("profile"))),+ OptionalParts(parts_as_user(joao)),+ )+ .await+ .expect("joao's own profile still works");+ let mut explicit_own = profile_entry("profile/tools/yarn.md", None);+ explicit_own.workspace = Some("default".into());+ explicit_own.project = Some(joaos);+ server+ .memory_write_page(Parameters(explicit_own), OptionalParts(parts_as_user(joao)))+ .await+ .expect("joao may name his own private profile");+ }+/// Multi-user, profile enabled (`share` auto → one private profile per/// operator). Adversarial: maria can neither see joao's profile through/// her query union nor read, write or delete it by naming its project.diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 394e567c..3dfdea91 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -4888,6 +4888,29 @@ pub fn rename_project("project name must not contain '/' (it appears in URL paths)".into(),));}+ // A profile project is found by its name (and a private one's owner is+ // its name), so renaming one away orphans it and renaming a project onto+ // a profile name hands someone else's pages to that profile.+ if ai_memory_core::profile::is_profile_project(trimmed) {+ return Err(StoreError::InvalidProjectName(format!(+ "{trimmed} is reserved for the cross-project profile"+ )));+ }+ let current: Option<String> = conn+ .query_row(+ "SELECT name FROM projects WHERE id = ?1 AND workspace_id = ?2",+ params![project_id.as_bytes(), workspace_id.as_bytes()],+ |row| row.get(0),+ )+ .optional()?;+ if current+ .as_deref()+ .is_some_and(ai_memory_core::profile::is_profile_project)+ {+ return Err(StoreError::InvalidProjectName(+ "a cross-project profile project cannot be renamed".into(),+ ));+ }// Wrap the UPDATE + audit row in one transaction so the trail can never// diverge from the rename it records (on any error the tx drops without@@ -14612,6 +14635,37 @@ pub(crate) mod tests {.expect("rename of live project must succeed");}+ /// A profile project is found by name and a private one's owner is in its+ /// name: renaming a project onto a profile name, or a profile away, is+ /// refused, and the refused rename changes nothing.+ #[test]+ fn rename_project_refuses_profile_names_both_ways() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ for name in ["_profile", "_profile.00000000000000000000000000000001"] {+ let err = rename_project(&mut conn, &ws, &proj, name, None)+ .expect_err("renaming onto a profile name must be refused");+ assert!(matches!(err, StoreError::InvalidProjectName(_)), "{err:?}");+ }+ let private = get_or_create_project(+ &mut conn,+ &ws,+ "_profile.00000000000000000000000000000002",+ None,+ )+ .unwrap();+ let err = rename_project(&mut conn, &ws, &private, "plain", None)+ .expect_err("renaming a profile away must be refused");+ assert!(matches!(err, StoreError::InvalidProjectName(_)), "{err:?}");+ let name: String = conn+ .query_row(+ "SELECT name FROM projects WHERE id = ?1",+ params![private.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(name, "_profile.00000000000000000000000000000002");+ }+fn seed_user(conn: &Connection, username: &str) -> ai_memory_core::UserId {crate::users::insert_human_user(conn,diff --git a/crates/ai-memory-store/src/scope.rs b/crates/ai-memory-store/src/scope.rsindex 52a87523..147622d9 100644--- a/crates/ai-memory-store/src/scope.rs+++ b/crates/ai-memory-store/src/scope.rs@@ -486,10 +486,46 @@ pub async fn create_explicit_scope_guarded(project: &str,viewer: Option<UserId>,) -> Result<ResolvedScope, ScopeResolutionError> {+ refuse_foreign_profile_name(Some(workspace), project, viewer)?;let workspace_id = writer.get_or_create_workspace(workspace.to_owned()).await?;create_project_in_workspace_guarded(reader, writer, workspace_id, project, viewer).await}+/// Refusal for an explicit write that names a profile project it does not own.+pub const PROFILE_NAME_RESERVED: &str = "profile projects are reserved: write profile entries \+ with scope \"profile\", which resolves your own profile";++/// A database user may name exactly one profile project explicitly: their own+/// private profile, `default/_profile.<their id>`. Any other `_profile` or+/// `_profile.*` name is refused before anything is created, so a user cannot+/// create (squat) another operator's private profile and lock its owner out,+/// nor create a workspace profile outside the profile path. A caller with no+/// database user (root, or a single-user server) may, for repair.+///+/// `workspace` is the name the caller gave; `None` (the workspace inferred+/// from the active project or the server default) never matches, so a user+/// names `default` explicitly to reach their own private profile this way.+fn refuse_foreign_profile_name(+ workspace: Option<&str>,+ project: &str,+ viewer: Option<UserId>,+) -> Result<(), ScopeResolutionError> {+ if !ai_memory_core::profile::is_profile_project(project) {+ return Ok(());+ }+ let Some(viewer) = viewer else {+ return Ok(());+ };+ if workspace == Some(ai_memory_core::DEFAULT_WORKSPACE_NAME)+ && project == ai_memory_core::profile::user_profile_project(viewer)+ {+ return Ok(());+ }+ Err(ScopeResolutionError::Forbidden(+ PROFILE_NAME_RESERVED.to_owned(),+ ))+}+/// [`create_explicit_scope_guarded`] for a workspace already resolved by id.async fn create_project_in_workspace_guarded(reader: &ReaderPool,@@ -1028,6 +1064,7 @@ impl<'a> ScopeResolver<'a> {// the choke point below then admits; one that already existed is// decided like any other write, so "create" is never a way in.let creator = self.authz.as_ref().and_then(|principal| principal.user_id);+ refuse_foreign_profile_name(trimmed_opt(explicit_workspace), project, creator)?;let (project_id, _) = writer.get_or_create_project_as(workspace_id, project.to_owned(), None, creator).await?;