Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(authz): gate writes to the reserved global scope (GHSA-7qj3-7wqw-m5w6)
AkitaOnRails4002cbcb5acd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ca172515..2451b975 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Documented FutureInfra as an endpoint for the existing `openai-compat`provider. (#1026)+### Security+- Fixed GHSA-7qj3-7wqw-m5w6: in multi-user mode a database user without a+ write grant on the reserved global preferences scope (`default/_global`)+ could write it, and its pages are unioned into every user's queries,+ including restricted projects. Writing it now needs root or an explicit+ `write` grant on `_global`, whichever way the scope is named; creating it+ grants nothing, reads stay open, and installs without database users are+ unchanged. Reported by @Josehbr.+### Fixed- Fixed watcher reindexing racing with writes and batches to the same page bysharing their per-page mutex from disk read through SQLite upsert. Bothdiff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 92150de5..82d2aefb 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -3840,10 +3840,15 @@ impl AiMemoryServer {None,));}- ai_memory_store::create_global_scope(&self.writer)- .await- .map_err(Self::scope_error)?- .as_tuple()+ // The same resolver and choke point as an explicit+ // `default/_global` write, so both spellings are gated alike.+ self.write_target_ids_with_actor(+ Some(ai_memory_core::DEFAULT_WORKSPACE_NAME),+ Some(ai_memory_core::GLOBAL_SCOPE_PROJECT),+ &aps_actor,+ Self::viewer_from_parts(Some(&parts)),+ )+ .await?}Some(other) => {return Err(McpError::internal_error(@@ -12050,6 +12055,234 @@ mod tests {.expect("a writer may delete");}+ /// Two users and a restricted project, for the global-scope write gate:+ /// `joao` writes `acme-app`, `maria` holds nothing anywhere.+ async fn global_gate_fixture(+ tmp: &TempDir,+ ) -> (+ Store,+ AiMemoryServer,+ ai_memory_core::UserId,+ ai_memory_core::UserId,+ ) {+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let acme = store+ .writer+ .get_or_create_project(ws, "acme-app", None)+ .await+ .unwrap();+ store+ .writer+ .set_access_mode(acme, ai_memory_store::AccessMode::Restricted)+ .await+ .unwrap();+ let mut users = Vec::new();+ for name in ["joao", "maria"] {+ users.push(+ store+ .writer+ .create_human_user(+ NewUser {+ username: name.into(),+ name: None,+ email: None,+ },+ ai_memory_core::UserRole::User,+ None,+ false,+ )+ .await+ .unwrap(),+ );+ }+ grant_writer(store.db_path(), users[0], acme);+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, acme)+ .with_wiki(wiki);+ (store, server, users[0], users[1])+ }++ fn parts_as_user(user: ai_memory_core::UserId) -> axum::http::request::Parts {+ let mut parts = test_parts_default();+ parts.extensions.insert(AuthLevel::User);+ parts.extensions.insert(user);+ parts+ .extensions+ .insert(ai_memory_core::AuthorizedViewer(user));+ parts+ }++ fn global_page(+ path: &str,+ scope: Option<&str>,+ workspace: Option<&str>,+ project: Option<&str>,+ ) -> WritePageArgs {+ WritePageArgs {+ path: path.into(),+ body: "# Preferences\n\nglobalverify marker.".into(),+ title: None,+ tier: Some("semantic".into()),+ tags: vec![],+ pinned: false,+ project: project.map(str::to_owned),+ workspace: workspace.map(str::to_owned),+ scope: scope.map(str::to_owned),+ expires_at: None,+ }+ }++ /// GHSA-7qj3-7wqw-m5w6: the reserved global scope is unioned into every+ /// user's reads, so a database user without a write grant on it must not+ /// write it — through `scope: "global"` or by naming `default/_global` —+ /// nor delete from it. Having created `_global` first grants nothing.+ #[tokio::test]+ async fn a_user_without_a_global_grant_cannot_change_the_global_scope() {+ let tmp = TempDir::new().unwrap();+ let (store, server, _joao, maria) = global_gate_fixture(&tmp).await;++ for (label, args) in [+ (+ "scope: global",+ global_page("preferences.md", Some("global"), None, None),+ ),+ (+ "explicit default/_global",+ global_page("preferences.md", None, Some("default"), Some("_global")),+ ),+ ] {+ let err = server+ .memory_write_page(Parameters(args), OptionalParts(parts_as_user(maria)))+ .await+ .expect_err(label);+ assert!(+ err.message.contains("not authorized for _global"),+ "{label}: {}",+ err.message+ );+ }+ // Maria's refused write created `_global` and recorded her as its+ // creator; that must not have made her a writer.+ let conn = rusqlite::Connection::open(store.db_path()).unwrap();+ let creator: Option<Vec<u8>> = conn+ .query_row(+ "SELECT created_by FROM projects WHERE name = '_global'",+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(creator.as_deref(), Some(maria.as_bytes().as_slice()));+ server+ .memory_write_page(+ Parameters(global_page("preferences.md", Some("global"), None, None)),+ OptionalParts(parts_as_user(maria)),+ )+ .await+ .expect_err("the creator of _global is not its writer");++ // Root (no viewer) writes a real global page; maria cannot delete it.+ server+ .memory_write_page(+ Parameters(global_page("preferences.md", Some("global"), None, None)),+ OptionalParts(test_parts_default()),+ )+ .await+ .expect("root writes the global scope");+ server+ .memory_delete_page(+ Parameters(DeletePageArgs {+ path: "preferences.md".into(),+ project: Some("_global".into()),+ workspace: Some("default".into()),+ }),+ OptionalParts(parts_as_user(maria)),+ )+ .await+ .expect_err("maria holds no write grant on _global");+ server+ .memory_read_page(+ Parameters(ReadPageArgs {+ include_related: false,+ related_depth: None,+ path: Some("preferences.md".into()),+ query: None,+ project: Some("_global".into()),+ workspace: Some("default".into()),+ }),+ OptionalParts(parts_as_user(maria)),+ )+ .await+ .expect("the refused delete left the page, and reads stay open");+ }++ /// The legitimate half of GHSA-7qj3: a write grant on `_global` admits+ /// both spellings, and every user still reads the global page through the+ /// union on their own restricted project.+ #[tokio::test]+ async fn a_global_write_grant_admits_writes_and_the_union_stays_readable() {+ let tmp = TempDir::new().unwrap();+ let (store, server, joao, maria) = global_gate_fixture(&tmp).await;+ let global = ai_memory_store::create_global_scope(&store.writer)+ .await+ .unwrap();+ grant_writer(store.db_path(), maria, global.project_id);++ server+ .memory_write_page(+ Parameters(global_page("preferences.md", Some("global"), None, None)),+ OptionalParts(parts_as_user(maria)),+ )+ .await+ .expect("a write grant on _global admits scope: global");+ server+ .memory_write_page(+ Parameters(global_page(+ "style.md",+ None,+ Some("default"),+ Some("_global"),+ )),+ OptionalParts(parts_as_user(maria)),+ )+ .await+ .expect("a write grant on _global admits default/_global");++ let result = server+ .memory_query(+ Parameters(QueryArgs {+ query: "globalverify".into(),+ limit: Some(5),+ project: Some("acme-app".into()),+ scopes: Vec::new(),+ workspace: Some("default".into()),+ global: None,+ include_expired: None,+ include_superseded: None,+ pin_first: None,+ explain: None,+ as_of: None,+ answer: None,+ reasoning: None,+ }),+ OptionalParts(parts_as_user(joao)),+ )+ .await+ .expect("joao reads his restricted project");+ let value = tool_json(&result);+ let paths: Vec<&str> = value["global_scope_hits"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|hit| hit["path"].as_str())+ .collect();+ assert!(paths.contains(&"preferences.md"), "{value}");+ }+/// The finding that started #708, as a test.////// Two `role=user` accounts on upstream 2.1.1: alice writes a page into herdiff --git a/crates/ai-memory-store/src/grants.rs b/crates/ai-memory-store/src/grants.rsindex 0956d179..448bff17 100644--- a/crates/ai-memory-store/src/grants.rs+++ b/crates/ai-memory-store/src/grants.rs@@ -651,6 +651,7 @@ mod tests {is_root: false,is_creator: false,grant: Some(level),+ reserved_global: false,};assert!(crate::authorize_project(&ctx, crate::ProjectAccess::Read).is_ok(),diff --git a/crates/ai-memory-store/src/project_authz.rs b/crates/ai-memory-store/src/project_authz.rsindex 3255621f..242e08aa 100644--- a/crates/ai-memory-store/src/project_authz.rs+++ b/crates/ai-memory-store/src/project_authz.rs@@ -17,6 +17,14 @@//! where there is no notion of "another user" to gate against, and//! - any `open` project.//!+//! ## The reserved global scope is read-open, write-gated+//!+//! `default/_global` stays `open` because its pages are unioned into every+//! project's reads. Writing it therefore reaches every other user's results,+//! so on a deployment that distinguishes operators a write needs root or an+//! explicit `write` grant on it, whatever its access mode. Creating it first+//! grants nothing: the first writer must not become a permanent one.+//!//! ## Never fail closed on a resolution gap (#678)//!//! A `restricted` project with **zero** grants still admits root and the@@ -40,6 +48,9 @@ use crate::error::StoreResult;pub const RESTRICTED_PROJECT_FORBIDDEN: &str ="project access is restricted; root, the project creator, or a matching grant is required";+/// Denial message surfaced when a write to the reserved global scope is refused.+pub const GLOBAL_SCOPE_WRITE_FORBIDDEN: &str = "the global scope is shared with every project; writing it requires root or a write grant on it";+/// A project's enforcement mode, stored in `projects.access_mode` (V68).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum AccessMode {@@ -176,12 +187,16 @@ pub struct ProjectAuthz {pub is_creator: bool,/// The caller's grant on the project, if any.pub grant: Option<GrantLevel>,+ /// The project is the reserved global scope (`default/_global`).+ pub reserved_global: bool,}impl ProjectAuthz {/// Decide whether the caller may perform `need` in this project.////// - A deployment that does not distinguish operators skips the gate.+ /// - A write to the reserved global scope needs root or a `write` grant,+ /// in either mode; its creator gets nothing extra./// - An `open` project admits everyone (today's behaviour)./// - A `restricted` project admits root and the creator unconditionally;/// otherwise a read needs any grant and a write needs a `write` grant.@@ -193,6 +208,13 @@ impl ProjectAuthz {if !self.distinguishes_operators {return Ok(());}+ if self.reserved_global && need == ProjectAccess::Write {+ return if self.is_root || self.grant == Some(GrantLevel::Write) {+ Ok(())+ } else {+ Err(AuthzError::Forbidden(GLOBAL_SCOPE_WRITE_FORBIDDEN))+ };+ }match self.access_mode {AccessMode::Open => Ok(()),AccessMode::Restricted => {@@ -223,35 +245,59 @@ pub fn authorize_project(ctx: &ProjectAuthz, need: ProjectAccess) -> Result<(),ctx.authorize(need)}-/// Read `projects.access_mode` and `projects.created_by`, degrading to-/// [`AccessMode::Open`] with no creator on any read failure and for an unknown-/// project. Never fails closed.-fn read_project_row(conn: &Connection, project_id: ProjectId) -> (AccessMode, Option<UserId>) {+/// The facts [`resolve_project_authz`] reads from a project's row.+struct ProjectRow {+ access_mode: AccessMode,+ creator: Option<UserId>,+ reserved_global: bool,+}++/// Read `projects.access_mode`, `projects.created_by` and whether the project+/// is the reserved global scope, degrading to [`AccessMode::Open`] with no+/// creator on any read failure and for an unknown project. Never fails closed.+fn read_project_row(conn: &Connection, project_id: ProjectId) -> ProjectRow {match conn.query_row(- "SELECT access_mode, created_by FROM projects WHERE id = ?1",+ "SELECT p.access_mode, p.created_by, p.name, w.name \+ FROM projects p JOIN workspaces w ON w.id = p.workspace_id WHERE p.id = ?1",params![project_id.as_bytes()],|row| {Ok((row.get::<_, Option<String>>(0)?,row.get::<_, Option<Vec<u8>>>(1)?,+ row.get::<_, String>(2)?,+ row.get::<_, String>(3)?,))},) {- Ok((mode, creator)) => (- AccessMode::from_db(mode.as_deref()),- creator.and_then(|raw| UserId::from_slice(&raw).ok()),- ),- Err(rusqlite::Error::QueryReturnedNoRows) => (AccessMode::Open, None),+ Ok((mode, creator, project, workspace)) => ProjectRow {+ access_mode: AccessMode::from_db(mode.as_deref()),+ creator: creator.and_then(|raw| UserId::from_slice(&raw).ok()),+ reserved_global: is_reserved_global(&workspace, &project),+ },+ Err(rusqlite::Error::QueryReturnedNoRows) => ProjectRow {+ access_mode: AccessMode::Open,+ creator: None,+ reserved_global: false,+ },Err(err) => {tracing::warn!(error = %err,"could not read projects.access_mode; degrading project authz to open",);- (AccessMode::Open, None)+ ProjectRow {+ access_mode: AccessMode::Open,+ creator: None,+ reserved_global: false,+ }}}}+fn is_reserved_global(workspace: &str, project: &str) -> bool {+ workspace == ai_memory_core::DEFAULT_WORKSPACE_NAME+ && project == ai_memory_core::GLOBAL_SCOPE_PROJECT+}+/// Look up a caller's grant on a project. Returns the failure so the caller can/// decide how to degrade (a restricted project degrades to open when its grants/// cannot be read).@@ -294,9 +340,27 @@ pub fn resolve_project_authz(principal: &ProjectPrincipal,distinguishes_operators: bool,) -> StoreResult<ProjectAuthz> {- let (mut access_mode, creator) = read_project_row(conn, project_id);+ let ProjectRow {+ mut access_mode,+ creator,+ reserved_global,+ } = read_project_row(conn, project_id);let is_creator = principal.is_creator || (creator.is_some() && creator == principal.user_id);- let grant = if access_mode == AccessMode::Restricted {+ let grant = if reserved_global {+ // The global scope's write gate needs the grant in either mode. An+ // unreadable grant admits no write; reads stay open regardless.+ principal.user_id.and_then(|user_id| {+ read_grant(conn, workspace_id, project_id, user_id)+ .inspect_err(|err| {+ tracing::warn!(+ error = %err,+ "could not read project_grants for the global scope; refusing writes",+ );+ })+ .ok()+ .flatten()+ })+ } else if access_mode == AccessMode::Restricted {match principal.user_id {Some(user_id) => match read_grant(conn, workspace_id, project_id, user_id) {Ok(grant) => grant,@@ -322,6 +386,7 @@ pub fn resolve_project_authz(is_root: principal.is_root,is_creator,grant,+ reserved_global,})}@@ -342,7 +407,53 @@ mod tests {is_root,is_creator,grant,+ reserved_global: false,+ }+ }++ /// GHSA-7qj3-7wqw-m5w6: writing the reserved global scope needs root or a+ /// write grant in either mode; its creator and an open mode admit nothing+ /// extra, reads stay open, and an install without operators is unchanged.+ #[test]+ fn the_global_scope_admits_writes_only_from_root_or_a_write_grant() {+ let global = |mode, is_root, is_creator, grant| ProjectAuthz {+ reserved_global: true,+ ..ctx(true, mode, is_root, is_creator, grant)+ };+ for mode in [AccessMode::Open, AccessMode::Restricted] {+ let refused = [+ global(mode, false, false, None),+ global(mode, false, true, None),+ global(mode, false, false, Some(GrantLevel::Read)),+ ];+ for ctx in refused {+ assert_eq!(+ ctx.authorize(ProjectAccess::Write),+ Err(AuthzError::Forbidden(GLOBAL_SCOPE_WRITE_FORBIDDEN)),+ "{ctx:?}"+ );+ }+ assert!(+ global(mode, true, false, None)+ .authorize(ProjectAccess::Write)+ .is_ok()+ );+ assert!(+ global(mode, false, false, Some(GrantLevel::Write))+ .authorize(ProjectAccess::Write)+ .is_ok()+ );}+ assert!(+ global(AccessMode::Open, false, false, None)+ .authorize(ProjectAccess::Read)+ .is_ok()+ );+ let single_user = ProjectAuthz {+ distinguishes_operators: false,+ ..global(AccessMode::Open, false, false, None)+ };+ assert!(single_user.authorize(ProjectAccess::Write).is_ok());}#[test]diff --git a/crates/ai-memory-store/src/scope.rs b/crates/ai-memory-store/src/scope.rsindex 3448f1d7..4377fc15 100644--- a/crates/ai-memory-store/src/scope.rs+++ b/crates/ai-memory-store/src/scope.rs@@ -526,10 +526,11 @@ pub async fn resolve_many_existing_scopes_guarded(/// scope participates in default reads by existence, so an absent scope/// means "nothing to union in", never an error (issue #154).///-/// Unauthorized by design, together with [`create_global_scope`]: the global-/// scope is unioned into everybody's default reads, and the unscoped-read-/// filters admit it for every viewer (#708). Per-project authorization is-/// about project scopes; the global preferences scope is common ground.+/// Unauthorized by design: the global scope is unioned into everybody's+/// default reads, and the unscoped-read filters admit it for every viewer+/// (#708). Writing it is gated: the choke point admits only root or a `write`+/// grant on it, so user-facing writes resolve it through a [`ScopeResolver`]+/// rather than [`create_global_scope`].////// # Errors/// Propagates store failures only; a missing workspace or project is `None`.@@ -557,8 +558,9 @@ pub async fn lookup_global_scope(}))}-/// Create or fetch the reserved global preferences scope. Write-path only —-/// the counterpart of [`lookup_global_scope`] for `scope: "global"` writes.+/// Create or fetch the reserved global preferences scope, unauthorized.+/// For server-internal callers and tests: a caller acting for a user resolves+/// it through a [`ScopeResolver`], whose choke point gates the write.////// # Errors/// Propagates store failures.diff --git a/crates/ai-memory-store/tests/suite/access_mode.rs b/crates/ai-memory-store/tests/suite/access_mode.rsindex 79eadeb6..493b8ccb 100644--- a/crates/ai-memory-store/tests/suite/access_mode.rs+++ b/crates/ai-memory-store/tests/suite/access_mode.rs@@ -289,9 +289,16 @@ async fn new_projects_follow_the_server_default_and_admit_their_creator() {.await.unwrap();assert!(- admits(&f.store, f.ws, id, f.reader, ProjectAccess::Write).await,+ admits(&f.store, f.ws, id, f.reader, ProjectAccess::Read).await,"{reserved} must stay open");+ // The global scope reaches every user's reads, so its writes are+ // gated even though it stays open (GHSA-7qj3-7wqw-m5w6).+ assert_eq!(+ admits(&f.store, f.ws, id, f.reader, ProjectAccess::Write).await,+ reserved == ai_memory_core::DEFAULT_PROJECT_NAME,+ "{reserved} write"+ );}// An existing project is not touched by the flag.assert!(admits(&f.store, f.ws, open_one, f.reader, ProjectAccess::Write).await);diff --git a/crates/ai-memory-store/tests/suite/project_authz.rs b/crates/ai-memory-store/tests/suite/project_authz.rsindex f0380e8f..4daac17f 100644--- a/crates/ai-memory-store/tests/suite/project_authz.rs+++ b/crates/ai-memory-store/tests/suite/project_authz.rs@@ -490,6 +490,7 @@ async fn pure_authorize_project_reference() {is_root: false,is_creator: false,grant: None,+ reserved_global: false,};assert!(authorize_project(&deny, ProjectAccess::Read).is_err());diff --git a/docs/cookbook.md b/docs/cookbook.mdindex 69e3b7cc..05dad40f 100644--- a/docs/cookbook.md+++ b/docs/cookbook.md@@ -42,7 +42,8 @@ Your agent calls `memory_write_page` and it lands as a durable wiki page (routedunder `_rules/` when it's a rule). Next session, `memory_query` surfaces it, andif the project's `.ai-memory.toml` opts into the on-start brief, rules areprepended to the agent's context automatically. To make it apply to **all** your-projects, ask for it as a global rule (`scope: "global"`).+projects, ask for it as a global rule (`scope: "global"`). On a multi-user+server, writing a global rule needs root or a `write` grant on `_global`.## Recipe: have a project read a specific document before implementingdiff --git a/docs/design-per-project-authz.md b/docs/design-per-project-authz.mdindex 72ac4973..a7c86700 100644--- a/docs/design-per-project-authz.md+++ b/docs/design-per-project-authz.md@@ -161,7 +161,9 @@ explicitly, then grants users. Single-user/loopback is unaffected (no DB usersconfig `[auth] new_projects_restricted = true` to flip it — so secure-by-default isavailable without breaking the common case.2. **Global scope (`_global`)**: read-open to all authenticated users (it is shared- preference context), never restricted. Writes stay as today.+ preference context), never restricted. Writing it needs root or an explicit+ `write` grant on it (GHSA-7qj3-7wqw-m5w6): an open write there reaches every+ user's reads, restricted projects included.3. **Interaction with cross-project messaging (V64)**: a `restricted` recipient inboxshould require the sender to hold a `write` grant on the recipient project, or themessage is refused — otherwise grants are bypassable via the mailbox. This ties #708diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 4e918447..14010347 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -24,6 +24,7 @@ boundary not yet built.|---|----------|----------------|---------------------|----------|| 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)` | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs` | 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 || 2 | Workspace isolation | same as #1; same-named project → distinct ids per workspace | `scope.rs` cross-workspace resolution rows; `multi_scope` dedup/validate | 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` | `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` | 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 |diff --git a/docs/users.md b/docs/users.mdindex 4e712e66..97eef6d1 100644--- a/docs/users.md+++ b/docs/users.md@@ -741,6 +741,12 @@ ones who should keep access; nothing is granted automatically.reserved `scratch` project and the global preferences scope always startopen, and the global scope can never be restricted: it is shared byconstruction.+- **Writing the global preferences scope** (`scope: "global"`, or+ `default/_global` by name) needs root or an explicit `write` grant on it,+ because its pages reach every user's queries. Reading it stays open, and+ having created it first grants nothing. To let a user maintain team-wide+ preferences: `ai-memory user grant --user alice --project _global --level+ write` (the scope must already exist; root creates it with its first write).- **Gates entry, never rows.** Access decides which projects a user reaches;inside a project pages stay shared exactly as before (see below).- **Refusals are explicit.** A user outside a restricted project gets a 403