Skip to content

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

Rust

feat(auth): enforce per-project access on every surface (#708)

luisfnicolau41ca270b9884
diff --git a/Cargo.lock b/Cargo.lock
index 1c4ea073..91d999df 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -221,6 +221,7 @@ dependencies = [
"http",
"jiff",
"rmcp",
+ "rusqlite",
"schemars",
"secrecy",
"serde",
diff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rs
index cd83efa4..79f015c4 100644
--- a/crates/ai-memory-consolidate/src/consolidator.rs
+++ b/crates/ai-memory-consolidate/src/consolidator.rs
@@ -339,18 +339,37 @@ impl Consolidator {
&self,
session_id: SessionId,
) -> ConsolidatorResult<(WorkspaceId, ProjectId)> {
+ Ok(self
+ .session_target(session_id)
+ .await?
+ .unwrap_or((self.workspace_id, self.project_id)))
+ }
+
+ /// The repository a consolidation of `session_id` would write into, or
+ /// `None` when the session has neither observations nor a row.
+ ///
+ /// Exactly [`Self::resolve_target`] without the startup fallback, so a
+ /// caller authorizing the write checks the repository the page will
+ /// actually land in (#708). `None` needs no authorization: with no
+ /// observations there is nothing to consolidate, and the consolidation
+ /// itself fails before writing anything — which also keeps an unknown
+ /// session reported as unknown rather than as a refusal on the server's
+ /// default project.
+ ///
+ /// # Errors
+ /// Propagates store errors.
+ pub async fn session_target(
+ &self,
+ session_id: SessionId,
+ ) -> ConsolidatorResult<Option<(WorkspaceId, ProjectId)>> {
if let Some(scope) = self
.reader
.session_scope_from_observations(session_id)
.await?
{
- return Ok(scope);
+ return Ok(Some(scope));
}
- Ok(self
- .reader
- .session_project_ids(session_id)
- .await?
- .unwrap_or((self.workspace_id, self.project_id)))
+ Ok(self.reader.session_project_ids(session_id).await?)
}
/// Resolve the session's creating harness from the persisted session row.
diff --git a/crates/ai-memory-consolidate/tests/suite/lifecycle.rs b/crates/ai-memory-consolidate/tests/suite/lifecycle.rs
index 590b6276..a46f7fed 100644
--- a/crates/ai-memory-consolidate/tests/suite/lifecycle.rs
+++ b/crates/ai-memory-consolidate/tests/suite/lifecycle.rs
@@ -334,7 +334,7 @@ async fn m8_retention_lifecycle_end_to_end() {
// Keywords unique to evicted pages should disappear from search.
let cognee_hits = store
.reader
- .search_pages("cognee".into(), 5)
+ .search_pages("cognee".into(), 5, None)
.await
.expect("search cognee");
assert!(
@@ -344,7 +344,7 @@ async fn m8_retention_lifecycle_end_to_end() {
let jiff_hits = store
.reader
- .search_pages("jiff".into(), 5)
+ .search_pages("jiff".into(), 5, None)
.await
.expect("search jiff");
assert!(
@@ -358,7 +358,7 @@ async fn m8_retention_lifecycle_end_to_end() {
// distinct standalone keywords to test each page independently.
let backpressure_hits = store
.reader
- .search_pages("backpressure".into(), 5)
+ .search_pages("backpressure".into(), 5, None)
.await
.expect("search backpressure");
let bp_paths: HashSet<&str> = backpressure_hits.iter().map(|h| h.path.as_str()).collect();
@@ -369,7 +369,7 @@ async fn m8_retention_lifecycle_end_to_end() {
let mutations_hits = store
.reader
- .search_pages("mutations".into(), 5)
+ .search_pages("mutations".into(), 5, None)
.await
.expect("search mutations");
let mut_paths: HashSet<&str> = mutations_hits.iter().map(|h| h.path.as_str()).collect();
@@ -380,7 +380,7 @@ async fn m8_retention_lifecycle_end_to_end() {
let karpathy_hits = store
.reader
- .search_pages("karpathy".into(), 5)
+ .search_pages("karpathy".into(), 5, None)
.await
.expect("search karpathy");
let karpathy_paths: HashSet<&str> = karpathy_hits.iter().map(|h| h.path.as_str()).collect();
@@ -394,7 +394,7 @@ async fn m8_retention_lifecycle_end_to_end() {
// for a standalone token from the body instead of `iii-engine`.
let sidecar_hits = store
.reader
- .search_pages("sidecar".into(), 5)
+ .search_pages("sidecar".into(), 5, None)
.await
.expect("search sidecar");
let sidecar_paths: HashSet<&str> = sidecar_hits.iter().map(|h| h.path.as_str()).collect();
@@ -408,7 +408,7 @@ async fn m8_retention_lifecycle_end_to_end() {
// term unique to that page should still return it.
let midterm_hits = store
.reader
- .search_pages("dyn".into(), 5)
+ .search_pages("dyn".into(), 5, None)
.await
.expect("search dyn");
let midterm_paths: HashSet<&str> = midterm_hits.iter().map(|h| h.path.as_str()).collect();
diff --git a/crates/ai-memory-consolidate/tests/suite/recall_eval.rs b/crates/ai-memory-consolidate/tests/suite/recall_eval.rs
index 1a78e3e6..073c9ecd 100644
--- a/crates/ai-memory-consolidate/tests/suite/recall_eval.rs
+++ b/crates/ai-memory-consolidate/tests/suite/recall_eval.rs
@@ -428,7 +428,7 @@ async fn measure_recall(
} else {
store
.reader
- .search_pages((*query).to_string(), 5)
+ .search_pages((*query).to_string(), 5, None)
.await
.expect("search")
};
diff --git a/crates/ai-memory-core/src/actor.rs b/crates/ai-memory-core/src/actor.rs
index 15c5dfd3..23c92f32 100644
--- a/crates/ai-memory-core/src/actor.rs
+++ b/crates/ai-memory-core/src/actor.rs
@@ -88,6 +88,32 @@ pub struct ActorContext {
pub client: Option<String>,
}
+/// The user this request is authorized *as*, for per-repository grants.
+///
+/// Distinct from the bare `UserId` the middleware also stamps, and the
+/// distinction is the whole point. `UserId` answers "who wrote this" and is
+/// always present for a database user, because attribution must not depend on
+/// a policy setting. This answers "whose access applies", and is stamped for
+/// every database user — never for the root token, which authenticates from
+/// configuration and is authorized above per-project granularity, and never on
+/// an install with no database users, where there is nobody to tell apart.
+///
+/// Every guard reads a missing `AuthorizedViewer` as "no per-project check
+/// applies". A present one is checked against the project's access mode: an
+/// `open` project admits every viewer, which is how every project behaves
+/// until an operator restricts it, so stamping every user changes nothing on
+/// upgrade.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct AuthorizedViewer(pub crate::UserId);
+
+impl AuthorizedViewer {
+ /// The user id inside.
+ #[must_use]
+ pub const fn user(self) -> crate::UserId {
+ self.0
+ }
+}
+
/// Authorization tier the auth middleware resolved this request to.
///
/// Identity ([`ActorContext`]) carries *who* the request is from;
diff --git a/crates/ai-memory-core/src/ingest_metrics.rs b/crates/ai-memory-core/src/ingest_metrics.rs
index 48f825e3..557ced30 100644
--- a/crates/ai-memory-core/src/ingest_metrics.rs
+++ b/crates/ai-memory-core/src/ingest_metrics.rs
@@ -32,6 +32,15 @@ pub struct IngestMetrics {
/// Events accepted but deliberately not stored — capture policy or the
/// subagent drop. Still a 202: the client must not retry these.
dropped_by_policy: AtomicU64,
+ /// Events accepted but not stored because the authenticated user holds no
+ /// `write` access to the project the capture resolved to.
+ ///
+ /// Separate from `dropped_by_policy` on purpose. A policy drop is the
+ /// operator's own configuration working as intended; this one means
+ /// somebody's agent has been recording into a repository all day and none
+ /// of it is landing. Those want different answers, so they must not share
+ /// a counter.
+ dropped_unauthorized: AtomicU64,
/// Events shed because the global ingest semaphore had no permit (429).
shed_saturated: AtomicU64,
/// Events shed by the per-source rate limiter (429).
@@ -50,6 +59,10 @@ impl IngestMetrics {
pub fn record_dropped_by_policy(&self) {
self.dropped_by_policy.fetch_add(1, Ordering::Relaxed);
}
+ /// One capture dropped because its author may not write that repository.
+ pub fn record_dropped_unauthorized(&self) {
+ self.dropped_unauthorized.fetch_add(1, Ordering::Relaxed);
+ }
/// One event shed because ingest capacity was exhausted.
pub fn record_shed_saturated(&self) {
self.shed_saturated.fetch_add(1, Ordering::Relaxed);
@@ -69,6 +82,7 @@ impl IngestMetrics {
IngestMetricsSnapshot {
accepted: self.accepted.load(Ordering::Relaxed),
dropped_by_policy: self.dropped_by_policy.load(Ordering::Relaxed),
+ dropped_unauthorized: self.dropped_unauthorized.load(Ordering::Relaxed),
shed_saturated: self.shed_saturated.load(Ordering::Relaxed),
shed_rate_limited: self.shed_rate_limited.load(Ordering::Relaxed),
last_persisted_ms: match self.last_persisted_ms.load(Ordering::Relaxed) {
@@ -86,6 +100,8 @@ pub struct IngestMetricsSnapshot {
pub accepted: u64,
/// Events accepted but intentionally not stored.
pub dropped_by_policy: u64,
+ /// Captures dropped because their author may not write that repository.
+ pub dropped_unauthorized: u64,
/// Events shed because ingest capacity was exhausted.
pub shed_saturated: u64,
/// Events shed by the per-source rate limiter.
@@ -103,6 +119,7 @@ mod tests {
let snap = IngestMetrics::default().snapshot();
assert_eq!(snap.accepted, 0);
assert_eq!(snap.dropped_by_policy, 0);
+ assert_eq!(snap.dropped_unauthorized, 0);
assert_eq!(snap.shed_saturated, 0);
assert_eq!(snap.shed_rate_limited, 0);
assert_eq!(
@@ -144,6 +161,7 @@ mod tests {
vec![
"accepted",
"dropped_by_policy",
+ "dropped_unauthorized",
"last_persisted_ms",
"shed_rate_limited",
"shed_saturated"
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index 6d320bc5..a882afed 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -46,7 +46,7 @@ pub use active_project::{
DEFAULT_PER_KEY_TTL, MidSessionRouting, ReadPointer,
};
pub use actor::{
- ActorContext, AuthLevel, AuthzError, Capability, IdentityKey, OwnerFilter,
+ ActorContext, AuthLevel, AuthorizedViewer, AuthzError, Capability, IdentityKey, OwnerFilter,
SKIP_ADMISSION_CHAIN_HEADER, owner_identity, owner_stamp, parse_skip_admission_chain,
skip_admission_chain_for,
};
diff --git a/crates/ai-memory-hooks/src/grants.rs b/crates/ai-memory-hooks/src/grants.rs
new file mode 100644
index 00000000..1b6efa77
--- /dev/null
+++ b/crates/ai-memory-hooks/src/grants.rs
@@ -0,0 +1,45 @@
+//! Authorizing hook routes that reach a project through an id (#708).
+//!
+//! Most routes name a workspace and project and go through the guarded scope
+//! resolvers. Some take a managed-run or workstream id in the URL instead,
+//! and an id bypasses scope resolution — and the choke point that comes with
+//! it — entirely. These resolve the id to its project first, then ask the same
+//! question the resolvers ask.
+
+use ai_memory_core::{ProjectId, UserId, WorkspaceId};
+use ai_memory_store::{
+ ProjectAccess, ReaderPool, ResolvedScope, ScopeResolutionError, authorize_scope_for,
+};
+
+/// Authorize `viewer` for `need` on the project an id resolved to.
+///
+/// `scope` is `None` when the id matched nothing. That passes: the caller goes
+/// on to report "not found" exactly as it did before, so an unknown id still
+/// reads as unknown rather than as a refusal. A known id in a project the
+/// viewer cannot reach is refused with the same `Forbidden` the resolvers
+/// return — an access problem, never an empty result.
+///
+/// No viewer — an install with no database users, or root — passes without
+/// a lookup.
+pub(crate) async fn authorize_resolved(
+ reader: &ReaderPool,
+ scope: Option<(WorkspaceId, ProjectId)>,
+ viewer: Option<UserId>,
+ need: ProjectAccess,
+) -> Result<(), ScopeResolutionError> {
+ let Some((workspace_id, project_id)) = scope else {
+ return Ok(());
+ };
+ authorize_scope_for(
+ reader,
+ None,
+ ResolvedScope {
+ workspace_id,
+ project_id,
+ },
+ viewer,
+ need,
+ )
+ .await
+ .map(|_| ())
+}
diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rs
index 5eb86445..4b8d00e7 100644
--- a/crates/ai-memory-hooks/src/lib.rs
+++ b/crates/ai-memory-hooks/src/lib.rs
@@ -23,6 +23,7 @@
mod assistant_capture;
pub mod capture_policy;
+mod grants;
pub mod log;
pub mod payload;
pub mod router;
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 45b54687..fc611f6c 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -421,6 +421,24 @@ fn ingest_rate_key(env: &HookEnvelope, actor_user: Option<&str>) -> String {
)
}
+/// A capture whose author may not write the project it
+/// resolved to.
+///
+/// A distinct type rather than a string, because the two call paths have to
+/// tell it apart from a genuine failure and do opposite things with it: this
+/// one is *final*. The event can never succeed, so the client must stop
+/// holding it, exactly as it would for a capture-policy drop.
+#[derive(Debug)]
+pub struct CaptureNotAuthorized;
+
+impl std::fmt::Display for CaptureNotAuthorized {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("capture not authorized for this repository")
+ }
+}
+
+impl std::error::Error for CaptureNotAuthorized {}
+
/// Shared state passed to the hook handler.
#[derive(Clone)]
pub struct HookState {
@@ -604,6 +622,7 @@ async fn handle_hook(
Query(query): Query<HookQuery>,
actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
level_ext: Option<axum::Extension<ai_memory_core::AuthLevel>>,
+ viewer_ext: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
headers: HeaderMap,
Json(mut body): Json<serde_json::Value>,
) -> impl IntoResponse {
@@ -630,11 +649,16 @@ async fn handle_hook(
// extensions — so `process()` can key the `ActiveProject` map by the
// authenticated identity when `[auto_scope] mode = per_actor` is on.
let actor = actor_identity(actor_ext);
+ // Captured here for the same reason as the actor: the request extensions
+ // are gone by the time the spawned task runs. `AuthorizedViewer` is the
+ // gated marker, so this is `None` whenever per-repository authorization is
+ // off, and captures behave exactly as they always have.
+ let viewer = viewer_ext.map(|axum::Extension(v)| v.user());
// Same reason: the skip-list header is read here, while the request
// extensions still exist, and travels with the event into `process()`.
let skip_webhooks = admission_skips(level_ext, &headers);
let actor_storage_key = actor.as_ref().map(IdentityKey::storage_key);
- if should_drop_subagent(&state, &env).await {
+ if should_drop_subagent(&state, &env, viewer).await {
state.ingest_metrics.record_dropped_by_policy();
return (StatusCode::ACCEPTED, "subagent capture dropped");
}
@@ -664,6 +688,7 @@ async fn handle_hook(
actor,
level_ext.map_or(ai_memory_core::AuthLevel::Anonymous, |v| v.0),
skip_webhooks,
+ viewer,
)
.await;
// Stamped only when `process_envelope` actually cleared the writer.
@@ -777,6 +802,7 @@ async fn handle_hook_batch(
State(state): State<Arc<HookState>>,
actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
level_ext: Option<axum::Extension<ai_memory_core::AuthLevel>>,
+ viewer_ext: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
headers: HeaderMap,
Json(items): Json<Vec<HookBatchItem>>,
) -> impl IntoResponse {
@@ -791,6 +817,9 @@ async fn handle_hook_batch(
// All items in a batch share the drain's single identity, so the actor is
// captured once from the batch request (mirrors `handle_hook`).
let actor = actor_identity(actor_ext);
+ // Same marker as the single-event path: `None` for root and on an
+ // install with no database users.
+ let viewer = viewer_ext.map(|axum::Extension(v)| v.user());
let skip_webhooks = admission_skips(level_ext, &headers);
let actor_storage_key = actor.as_ref().map(IdentityKey::storage_key);
let mut accepted_indices = Vec::new();
@@ -816,7 +845,7 @@ async fn handle_hook_batch(
// Accept-but-drop subagent captures (see `handle_hook`): count the item
// as committed so the client clears it from its spool, but do not store
// it. Keeps the contiguous-prefix ack contract intact.
- if should_drop_subagent(&state, &env).await {
+ if should_drop_subagent(&state, &env, viewer).await {
state.ingest_metrics.record_dropped_by_policy();
accepted_indices.push(idx);
continue;
@@ -859,9 +888,20 @@ async fn handle_hook_batch(
actor.clone(),
level_ext.map_or(ai_memory_core::AuthLevel::Anonymous, |v| v.0),
skip_webhooks.clone(),
+ viewer,
)
.await
{
+ if e.downcast_ref::<CaptureNotAuthorized>().is_some() {
+ // Counted as accepted so the client DROPS it. The item can
+ // never be stored, so leaving it spooled would retry it until
+ // its attempt budget ran out and stall every item behind it.
+ // Same treatment a capture-policy drop already gets.
+ state.ingest_metrics.record_dropped_unauthorized();
+ warn!("hook batch capture dropped: author may not write this project");
+ accepted_indices.push(idx);
+ continue;
+ }
if matches!(
e.downcast_ref::<StoreError>(),
Some(StoreError::SessionCollision)
@@ -1134,7 +1174,11 @@ const fn canonical_tool_name(family: ToolFamily) -> &'static str {
/// `stop` / `session_end`) of a session already known to be a subagent. No-op
/// (returns `false`) unless this event's project opted in via the per-event
/// `drop_subagent` flag (sourced from its `.ai-memory.toml`).
-async fn should_drop_subagent(state: &HookState, env: &HookEnvelope) -> bool {
+async fn should_drop_subagent(
+ state: &HookState,
+ env: &HookEnvelope,
+ viewer: Option<ai_memory_core::UserId>,
+) -> bool {
if !env.drop_subagent_requested {
return false;
}
@@ -1147,6 +1191,7 @@ async fn should_drop_subagent(state: &HookState, env: &HookEnvelope) -> bool {
env.workspace_override.as_deref(),
env.project_override.as_deref(),
env.project_strategy,
+ viewer,
)
.await
else {
@@ -1238,17 +1283,25 @@ async fn handle_handoff(
Query(query): Query<HandoffQuery>,
actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
level_ext: Option<axum::Extension<ai_memory_core::AuthLevel>>,
+ viewer_ext: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
headers: HeaderMap,
) -> impl IntoResponse {
let actor = actor_identity(actor_ext);
let skip_webhooks = admission_skips(level_ext, &headers);
- match fetch_and_accept_handoff(&state, query, actor, skip_webhooks).await {
+ let viewer = viewer_ext.map(|axum::Extension(viewer)| viewer.user());
+ match fetch_and_accept_handoff(&state, query, actor, skip_webhooks, viewer).await {
Ok(Some(markdown)) => (StatusCode::OK, markdown),
Ok(None) => (StatusCode::OK, String::new()),
- Err(e) => {
- warn!(error = %e, "handoff fetch failed");
- (StatusCode::OK, String::new())
- }
+ // A refusal is the one failure that must not look like "no handoff":
+ // it is a 403 carrying the reason, which the hook client reports on
+ // stderr and never injects as context (#708).
+ Err(e) => match e.downcast_ref::<ai_memory_store::ScopeResolutionError>() {
+ Some(refusal) if refusal.is_forbidden() => (StatusCode::FORBIDDEN, refusal.to_string()),
+ _ => {
+ warn!(error = %e, "handoff fetch failed");
+ (StatusCode::OK, String::new())
+ }
+ },
}
}
@@ -1257,8 +1310,17 @@ async fn fetch_and_accept_handoff(
query: HandoffQuery,
actor: Option<IdentityKey>,
skip_webhooks: Vec<String>,
+ viewer: Option<ai_memory_core::UserId>,
) -> anyhow::Result<Option<String>> {
- fetch_and_accept_handoff_at(state, query, actor, skip_webhooks, jiff::Timestamp::now()).await
+ fetch_and_accept_handoff_at(
+ state,
+ query,
+ actor,
+ skip_webhooks,
+ viewer,
+ jiff::Timestamp::now(),
+ )
+ .await
}
async fn fetch_and_accept_handoff_at(
@@ -1266,6 +1328,7 @@ async fn fetch_and_accept_handoff_at(
query: HandoffQuery,
actor: Option<IdentityKey>,
skip_webhooks: Vec<String>,
+ viewer: Option<ai_memory_core::UserId>,
now: jiff::Timestamp,
) -> anyhow::Result<Option<String>> {
let agent = query.agent.as_deref().map_or(AgentKind::Other, parse_agent);
@@ -1276,7 +1339,7 @@ async fn fetch_and_accept_handoff_at(
// too. The brief already reaches the managed path (it is recomposed per
// session, so resolving it twice was harmless); the handoff is single-use
// and had no second chance.
- let managed = fetch_managed_context(state, &query, agent).await?;
+ let managed = fetch_managed_context(state, &query, agent, viewer).await?;
// Keep the active-project key compatible with MCP transports: the native
// session id is carried separately below to bind a destructive handoff
// claim to its exact receiver.
@@ -1290,6 +1353,19 @@ async fn fetch_and_accept_handoff_at(
query.workspace.as_deref(),
query.project.as_deref(),
ProjectStrategy::parse(query.project_strategy.as_deref()),
+ viewer,
+ )
+ .await?;
+ // Everything below returns this repository's content — its handoff and
+ // its pinned, rules and slot pages — and claims its handoff, all keyed
+ // only on a project the caller named or a directory they are in (#708).
+ // Checked before the active-project pointer is published, so a refused
+ // repository does not become the caller's default for later calls.
+ crate::grants::authorize_resolved(
+ &state.reader,
+ Some((ws, proj)),
+ viewer,
+ ai_memory_store::ProjectAccess::Read,
)
.await?;
// Session-start handoff delivery is a foreground action. Publish it so
@@ -1491,6 +1567,7 @@ async fn fetch_managed_context(
state: &HookState,
query: &HandoffQuery,
agent: AgentKind,
+ viewer: Option<ai_memory_core::UserId>,
) -> anyhow::Result<Option<PendingManagedContext>> {
let Some(raw_run_id) = query.managed_run.as_deref() else {
return Ok(None);
@@ -1499,6 +1576,18 @@ async fn fetch_managed_context(
warn!(managed_run = %raw_run_id, "invalid managed run id on SessionStart");
return Ok(None);
};
+ // The run id reaches a workstream's event ledger without naming its
+ // repository; the same rule as the `/workstream/runs/*` routes applies.
+ if viewer.is_some() {
+ let scope = state.reader.managed_run_scope(run_id).await?;
+ crate::grants::authorize_resolved(
+ &state.reader,
+ scope,
+ viewer,
+ ai_memory_store::ProjectAccess::Write,
+ )
+ .await?;
+ }
if let Some(native_session_id) = query
.session_id
.as_deref()
@@ -2056,6 +2145,7 @@ async fn resolve_project_ids_inner(
workspace_override: Option<&str>,
project_override: Option<&str>,
project_strategy: ProjectStrategy,
+ creator: Option<ai_memory_core::UserId>,
) -> anyhow::Result<(WorkspaceId, ProjectId)> {
let cwd_raw = cwd.filter(|s| !s.is_empty());
let cwd_norm = cwd_raw.map(normalize_project_path_key);
@@ -2271,11 +2361,16 @@ async fn resolve_project_ids_inner(
);
parent_id
} else {
+ // `creator` is the authorized viewer, set only when per-repository
+ // authorization is on. A repository this capture opens is granted to
+ // them in the same transaction; without that the capture would create
+ // it and then be refused on it, as would every capture after it.
state
.writer
- .get_or_create_project(ws, project_name, repo_path)
+ .get_or_create_project_as(ws, project_name, repo_path, creator)
.await
.map_err(|e| anyhow::anyhow!("get_or_create_project: {e}"))?
+ .0
};
let ids = (ws, proj);
state.project_cache.lock().await.insert(cache_key, ids);
@@ -2301,6 +2396,7 @@ async fn resolve_project_ids(
workspace_override,
project_override,
project_strategy,
+ None,
)
.await?;
if has_publishable_scope_hint(cwd, project_override) {
@@ -2445,10 +2541,17 @@ async fn process_envelope(
actor: Option<IdentityKey>,
level: ai_memory_core::AuthLevel,
skip_webhooks: Vec<String>,
+ viewer: Option<ai_memory_core::UserId>,
) -> bool {
let (session, agent, event) = (resolve_session_id(&env).ok(), env.agent, env.event);
- if let Err(e) = process_authorized(&state, env, actor, level, skip_webhooks).await {
- if matches!(
+ if let Err(e) = process_authorized(&state, env, actor, level, skip_webhooks, viewer).await {
+ if e.downcast_ref::<CaptureNotAuthorized>().is_some() {
+ // Counted separately from a policy drop so an operator can tell
+ // "my configuration is discarding these" from "somebody has been
+ // working all day and none of it is being kept".
+ state.ingest_metrics.record_dropped_unauthorized();
+ warn!("capture dropped: author may not write this project");
+ } else if matches!(
e.downcast_ref::<StoreError>(),
Some(StoreError::SessionCollision)
) {
@@ -2539,6 +2642,7 @@ async fn process(
actor,
ai_memory_core::AuthLevel::Anonymous,
skip_webhooks,
+ None,
)
.await
{
@@ -2564,6 +2668,7 @@ async fn process_authorized(
// Admission webhooks this request opted out of (see `admission_skips`).
// Empty for every caller with no HTTP request behind it.
skip_webhooks: Vec<String>,
+ viewer: Option<ai_memory_core::UserId>,
) -> anyhow::Result<()> {
let session_id = resolve_session_id(&env)?;
// An OpenCode `session.moved` relocation, forwarded by the plugin as a
@@ -2658,11 +2763,44 @@ async fn process_authorized(
env.workspace_override.as_deref(),
env.project_override.as_deref(),
env.project_strategy,
+ viewer,
)
.await?
}
};
+ // A capture is a write, so it needs `write` — the same rule the MCP write
+ // tools follow. The check lands here, rather than in the handler, because
+ // here is the first moment the repository is known: the handler answers
+ // 202 before this resolution runs, and resolving it up there would put a
+ // database round trip in front of every tool call an agent makes.
+ //
+ // The consequence is that the refusal cannot be an HTTP status, and that
+ // is the right outcome anyway. A 403 would reach the client as an ordinary
+ // failure and be retried until it burnt the entry's attempt budget, which
+ // is how this project once spent 10.7M tokens re-sending something that
+ // could never succeed. Dropping it here is final by construction.
+ //
+ // Decided on the read pool, not the writer actor: this runs for every
+ // captured event, and a round trip through the single writer per event is
+ // the contention the hook path is built to avoid.
+ match ai_memory_store::authorize_scope_for(
+ &state.reader,
+ None,
+ ai_memory_store::ResolvedScope {
+ workspace_id: ws,
+ project_id: proj,
+ },
+ viewer,
+ ai_memory_store::ProjectAccess::Write,
+ )
+ .await
+ {
+ Ok(_) => {}
+ Err(err) if err.is_forbidden() => return Err(CaptureNotAuthorized.into()),
+ Err(err) => return Err(err.into()),
+ }
+
// Hooks are fire-and-forget and may arrive out of order. Begin the
// session idempotently before every observation so a resumed agent
// session, or a prompt racing ahead of SessionStart, cannot trip the
@@ -2774,6 +2912,7 @@ async fn process_authorized(
env.workspace_override.as_deref(),
env.project_override.as_deref(),
env.project_strategy,
+ viewer,
)
.await?;
}
@@ -3739,6 +3878,7 @@ mod tests {
Query(session_start_query(&tmp.path().to_string_lossy())),
None,
None,
+ None,
HeaderMap::new(),
)
.await,
@@ -3805,6 +3945,7 @@ mod tests {
Query(session_start_query(&tmp.path().to_string_lossy())),
None,
None,
+ None,
HeaderMap::new(),
)
.await,
@@ -3883,6 +4024,346 @@ mod tests {
}
/// Build a minimal `HookState` backed by a real on-disk store.
+ /// A capture is a write, so it needs `write`.
+ ///
+ /// Captures wrote observations into whichever repository a working
+ /// directory resolved to, with no grant check at all — the one mutating
+ /// path that checked nothing. The refusal has to be silent at the HTTP
+ /// layer (the handler answered 202 long before the repository was known),
+ /// so what this pins is the part that matters: nothing is stored, and the
+ /// drop is counted where an operator can see it.
+ #[tokio::test]
+ async fn a_capture_needs_writer_on_the_repository_it_lands_in() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ // Grants only decide anything in a restricted project.
+ state
+ .writer
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let cwd = tmp.path().to_path_buf();
+
+ // Which repository a capture lands in is resolved from the cwd, not
+ // from the server's baked project, so ask the resolver rather than
+ // assuming: a grant on the wrong repository would make this test pass
+ // for the wrong reason.
+ let probe = SessionId::new().to_string();
+ capture_as(&state, &cwd, &probe, None).await.unwrap();
+ let landed = state
+ .reader
+ .observations_for_session(probe.parse().unwrap())
+ .await
+ .unwrap()[0]
+ .project_id;
+
+ let reader = user_holding(
+ &state,
+ "ray",
+ landed,
+ Some(ai_memory_store::GrantLevel::Read),
+ )
+ .await;
+ let writer = user_holding(
+ &state,
+ "wren",
+ landed,
+ Some(ai_memory_store::GrantLevel::Write),
+ )
+ .await;
+ let stranger = user_holding(&state, "sam", landed, None).await;
+
+ // A read-only grant, and no grant at all, are both refused.
+ for (who, user) in [("reader", reader), ("stranger", stranger)] {
+ let session = SessionId::new().to_string();
+ let err = capture_as(&state, &cwd, &session, Some(user))
+ .await
+ .expect_err("{who} must not be able to capture");
+ assert!(
+ err.downcast_ref::<CaptureNotAuthorized>().is_some(),
+ "{who}: the refusal must be the terminal kind, not a generic failure: {err}"
+ );
+ let stored = state
+ .reader
+ .observations_for_session(session.parse().unwrap())
+ .await
+ .unwrap();
+ assert!(stored.is_empty(), "{who} stored an observation anyway");
+ }
+
+ // Counted where an operator looks, and not confused with a policy drop.
+ let snap = state.ingest_metrics.snapshot();
+ assert_eq!(
+ snap.dropped_unauthorized, 0,
+ "the router records it, not this layer"
+ );
+
+ // A writer's capture lands, exactly as before.
+ let session = SessionId::new().to_string();
+ capture_as(&state, &cwd, &session, Some(writer))
+ .await
+ .expect("a writer may capture");
+ let stored = state
+ .reader
+ .observations_for_session(session.parse().unwrap())
+ .await
+ .unwrap();
+ assert_eq!(stored.len(), 1, "the writer's capture must be stored");
+ }
+
+ /// An unauthorized batch item is CONSUMED, never left to be retried.
+ ///
+ /// This is the half that could have become a retry loop. The batch ack
+ /// tells the client which items to drop from its spool; reporting an
+ /// unauthorized item as not-accepted would leave it there to be re-sent
+ /// until its attempt budget ran out, and every attempt would be refused
+ /// for the same reason. It also stalls every item behind it. So it is
+ /// acked like any other policy drop, and simply not stored.
+ #[tokio::test]
+ async fn an_unauthorized_batch_item_is_consumed_rather_than_retried() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ // Grants only decide anything in a restricted project.
+ state
+ .writer
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let cwd = tmp.path().to_path_buf();
+
+ let probe = SessionId::new().to_string();
+ capture_as(&state, &cwd, &probe, None).await.unwrap();
+ let landed = state
+ .reader
+ .observations_for_session(probe.parse().unwrap())
+ .await
+ .unwrap()[0]
+ .project_id;
+ let reader = user_holding(
+ &state,
+ "ray",
+ landed,
+ Some(ai_memory_store::GrantLevel::Read),
+ )
+ .await;
+
+ let session = SessionId::new().to_string();
+ let items = vec![HookBatchItem {
+ url: "http://h/hook?event=user-prompt-submit&agent=claude-code".into(),
+ body: serde_json::json!({
+ "session_id": session,
+ "cwd": cwd.to_string_lossy(),
+ "prompt": "hello",
+ }),
+ }];
+ let before = state.ingest_metrics.snapshot().dropped_unauthorized;
+ let response = handle_hook_batch(
+ State(Arc::new(state.clone())),
+ None,
+ Some(axum::Extension(ai_memory_core::AuthLevel::User)),
+ Some(axum::Extension(ai_memory_core::AuthorizedViewer(reader))),
+ HeaderMap::new(),
+ Json(items),
+ )
+ .await
+ .into_response();
+ assert_eq!(response.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let ack: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ ack["accepted"], 1,
+ "the client must be told to drop it, or it will re-send it forever: {ack}"
+ );
+
+ let stored = state
+ .reader
+ .observations_for_session(session.parse().unwrap())
+ .await
+ .unwrap();
+ assert!(stored.is_empty(), "an acked item must still not be stored");
+ assert_eq!(
+ state.ingest_metrics.snapshot().dropped_unauthorized,
+ before + 1,
+ "the drop must be visible to an operator"
+ );
+ }
+
+ /// With no viewer, captures behave exactly as they always have.
+ ///
+ /// `None` is what the `AuthorizedViewer` marker yields for root and on an
+ /// install with no database users.
+ #[tokio::test]
+ async fn a_capture_with_no_viewer_is_untouched_by_the_check() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let session = SessionId::new().to_string();
+ capture_as(&state, tmp.path(), &session, None)
+ .await
+ .expect("no viewer must not change capture");
+ let stored = state
+ .reader
+ .observations_for_session(session.parse().unwrap())
+ .await
+ .unwrap();
+ assert_eq!(stored.len(), 1);
+ }
+
+ /// A capture that opens a new project records the user capturing as its
+ /// creator.
+ ///
+ /// The hook path creates a project before it checks access, so without a
+ /// creator the first capture from a new checkout would create a restricted
+ /// row and then be refused on it — and so would every capture after it,
+ /// since nobody would ever hold a grant on it. The choke point admits the
+ /// creator without one; a second user reaching the same row finds it
+ /// existing and is checked like anyone else.
+ #[tokio::test]
+ async fn a_capture_opening_a_new_project_admits_its_creator() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ // Grants only decide anything in a restricted project.
+ state
+ .writer
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let repo = tmp.path().join("fresh-checkout");
+ std::fs::create_dir_all(&repo).unwrap();
+ let cora = user_holding(&state, "cora", state.project_id, None).await;
+ let dan = user_holding(&state, "dan", state.project_id, None).await;
+
+ let first = SessionId::new().to_string();
+ capture_as(&state, &repo, &first, Some(cora))
+ .await
+ .expect("the capture that creates a repository must be kept");
+ let stored = state
+ .reader
+ .observations_for_session(first.parse().unwrap())
+ .await
+ .unwrap();
+ assert_eq!(stored.len(), 1);
+ let created = stored[0].project_id;
+ assert_ne!(created, state.project_id);
+ assert!(
+ state
+ .reader
+ .grants_for(cora, created)
+ .await
+ .unwrap()
+ .is_empty(),
+ "the creator needs no grant"
+ );
+ assert!(
+ state
+ .reader
+ .authorize_project(
+ stored[0].workspace_id,
+ created,
+ ai_memory_store::ProjectPrincipal::user(cora),
+ true,
+ ai_memory_store::ProjectAccess::Write,
+ )
+ .await
+ .unwrap()
+ .is_ok(),
+ "the creator is admitted"
+ );
+
+ let second = SessionId::new().to_string();
+ capture_as(&state, &repo, &second, Some(cora))
+ .await
+ .expect("and so must every capture after it");
+
+ let intruder = SessionId::new().to_string();
+ let refused = capture_as(&state, &repo, &intruder, Some(dan)).await;
+ assert!(
+ refused.is_err_and(|e| e.is::<CaptureNotAuthorized>()),
+ "a second user must not inherit the creator's repository"
+ );
+ assert!(
+ state
+ .reader
+ .observations_for_session(intruder.parse().unwrap())
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ state
+ .reader
+ .grants_for(dan, created)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ }
+
+ /// A capture, with the viewer it is authenticated as.
+ async fn capture_as(
+ state: &HookState,
+ cwd: &std::path::Path,
+ session: &str,
+ viewer: Option<ai_memory_core::UserId>,
+ ) -> anyhow::Result<()> {
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "user-prompt-submit".into(),
+ agent: Some("claude-code".into()),
+ ..Default::default()
+ },
+ serde_json::json!({
+ "session_id": session,
+ "cwd": cwd.to_string_lossy(),
+ "prompt": "hello",
+ }),
+ );
+ process_authorized(
+ state,
+ env,
+ None,
+ ai_memory_core::AuthLevel::User,
+ Vec::new(),
+ viewer,
+ )
+ .await
+ }
+
+ /// A user holding `role` on the capture fixture's repository.
+ ///
+ /// Uses the real grant API rather than raw SQL, so the test exercises the
+ /// same path an operator's `ai-memory user grant` call takes.
+ async fn user_holding(
+ state: &HookState,
+ username: &str,
+ repository: ProjectId,
+ role: Option<ai_memory_store::GrantLevel>,
+ ) -> ai_memory_core::UserId {
+ let id = state
+ .writer
+ .create_human_user(
+ ai_memory_core::NewUser {
+ username: username.to_owned(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ if let Some(role) = role {
+ state
+ .writer
+ .grant_memory(id, repository, role, None)
+ .await
+ .unwrap();
+ }
+ id
+ }
+
async fn make_state(tmp: &TempDir) -> HookState {
let store = Store::open(tmp.path()).unwrap();
let ws = store
@@ -5421,6 +5902,7 @@ mod tests {
}),
None,
None,
+ None,
HeaderMap::new(),
Json(serde_json::json!({ "session_id": sid })),
)
@@ -5457,6 +5939,7 @@ mod tests {
}),
None,
None,
+ None,
HeaderMap::new(),
Json(serde_json::json!({})),
)
@@ -5485,6 +5968,7 @@ mod tests {
Query(query.clone()),
None,
None,
+ None,
HeaderMap::new(),
Json(body.clone()),
)
@@ -5498,6 +5982,7 @@ mod tests {
Query(query),
None,
None,
+ None,
HeaderMap::new(),
Json(body),
)
@@ -5527,6 +6012,7 @@ mod tests {
State(Arc::new(state)),
None,
None,
+ None,
HeaderMap::new(),
Json(items),
)
@@ -5555,6 +6041,7 @@ mod tests {
State(Arc::new(state)),
None,
None,
+ None,
HeaderMap::new(),
Json(vec![
HookBatchItem {
@@ -5590,6 +6077,7 @@ mod tests {
State(Arc::new(state)),
None,
None,
+ None,
HeaderMap::new(),
Json(vec![HookBatchItem {
url: "http://h/hook?event=session-start&agent=claude-code".into(),
@@ -5618,6 +6106,7 @@ mod tests {
State(Arc::new(state)),
None,
None,
+ None,
HeaderMap::new(),
Json(vec![HookBatchItem {
url: "http://h/hook?event=session-start&agent=claude-code".into(),
@@ -5647,6 +6136,7 @@ mod tests {
State(Arc::new(state)),
None,
None,
+ None,
HeaderMap::new(),
Json(vec![
HookBatchItem {
@@ -5702,6 +6192,7 @@ mod tests {
}),
None,
None,
+ None,
HeaderMap::new(),
Json(serde_json::json!({ "prompt": "missing session fails" })),
)
@@ -5735,6 +6226,7 @@ mod tests {
}),
None,
None,
+ None,
HeaderMap::new(),
Json(serde_json::json!({ "session_id": "persist-s1" })),
)
@@ -5770,6 +6262,7 @@ mod tests {
State(Arc::new(state)),
None,
None,
+ None,
HeaderMap::new(),
Json(items),
)
@@ -5833,6 +6326,7 @@ mod tests {
State(state.clone()),
None,
None,
+ None,
HeaderMap::new(),
Json(items),
)
@@ -5922,6 +6416,7 @@ mod tests {
State(state.clone()),
None,
None,
+ None,
HeaderMap::new(),
Json(items),
)
@@ -5957,6 +6452,7 @@ mod tests {
State(state.clone()),
None,
None,
+ None,
HeaderMap::new(),
Json(items),
)
@@ -6018,6 +6514,7 @@ mod tests {
State(state.clone()),
None,
None,
+ None,
HeaderMap::new(),
Json(items),
)
@@ -6085,6 +6582,7 @@ mod tests {
State(state.clone()),
None,
None,
+ None,
HeaderMap::new(),
Json(items),
)
@@ -6141,6 +6639,7 @@ mod tests {
State(state.clone()),
None,
None,
+ None,
HeaderMap::new(),
Json(items),
)
@@ -6203,6 +6702,7 @@ mod tests {
State(state.clone()),
None,
None,
+ None,
HeaderMap::new(),
Json(items),
)
@@ -6247,7 +6747,7 @@ mod tests {
"sessionId": "shared-session", "subagentType": "general-purpose"
}),
);
- assert!(should_drop_subagent(&state, &marked_project_a).await);
+ assert!(should_drop_subagent(&state, &marked_project_a, None).await);
assert!(
state.active_project.get().is_none(),
"drop preflight may resolve scope but must not publish it as active"
@@ -6264,7 +6764,7 @@ mod tests {
serde_json::json!({ "sessionId": "shared-session", "toolName": "kept" }),
);
assert!(
- !should_drop_subagent(&state, &unmarked_project_b).await,
+ !should_drop_subagent(&state, &unmarked_project_b, None).await,
"a subagent session tracked in project-a must not drop same-id events in project-b"
);
@@ -6279,7 +6779,7 @@ mod tests {
serde_json::json!({ "sessionId": "shared-session", "toolName": "dropped" }),
);
assert!(
- should_drop_subagent(&state, &unmarked_project_a).await,
+ should_drop_subagent(&state, &unmarked_project_a, None).await,
"the originally tracked project's unmarked tail still drops"
);
}
@@ -6301,20 +6801,20 @@ mod tests {
query("subagent-start"),
serde_json::json!({ "sessionId": "tail-session" }),
);
- assert!(should_drop_subagent(&state, &start).await);
+ assert!(should_drop_subagent(&state, &start, None).await);
let subagent_stop = HookEnvelope::from_query_and_body(
query("subagent-stop"),
serde_json::json!({ "sessionId": "tail-session" }),
);
- assert!(should_drop_subagent(&state, &subagent_stop).await);
+ assert!(should_drop_subagent(&state, &subagent_stop, None).await);
let unmarked_stop_tail = HookEnvelope::from_query_and_body(
query("stop"),
serde_json::json!({ "sessionId": "tail-session" }),
);
assert!(
- should_drop_subagent(&state, &unmarked_stop_tail).await,
+ should_drop_subagent(&state, &unmarked_stop_tail, None).await,
"SubagentStop must not clear tracking before the unmarked stop tail"
);
@@ -6323,7 +6823,7 @@ mod tests {
serde_json::json!({ "sessionId": "tail-session" }),
);
assert!(
- should_drop_subagent(&state, &session_end_tail).await,
+ should_drop_subagent(&state, &session_end_tail, None).await,
"SessionEnd tail is dropped and then clears tracking"
);
@@ -6332,7 +6832,7 @@ mod tests {
serde_json::json!({ "sessionId": "tail-session", "toolName": "kept" }),
);
assert!(
- !should_drop_subagent(&state, &after_session_end).await,
+ !should_drop_subagent(&state, &after_session_end, None).await,
"SessionEnd clears tracking for that scoped session"
);
}
@@ -6347,6 +6847,7 @@ mod tests {
State(Arc::new(state)),
None,
None,
+ None,
HeaderMap::new(),
Json(vec![HookBatchItem {
url: "http://h/hook?event=session-start&agent=claude-code".into(),
@@ -6370,6 +6871,7 @@ mod tests {
State(Arc::new(state)),
None,
None,
+ None,
HeaderMap::new(),
Json(vec![
HookBatchItem {
@@ -6405,6 +6907,7 @@ mod tests {
State(Arc::new(state)),
None,
None,
+ None,
HeaderMap::new(),
Json(vec![
HookBatchItem {
@@ -6439,6 +6942,7 @@ mod tests {
State(Arc::new(state)),
None,
None,
+ None,
HeaderMap::new(),
Json(vec![HookBatchItem {
url: "http://h/hook?event=pre-tool-use&agent=grok&drop_subagent=1".into(),
@@ -6470,6 +6974,7 @@ mod tests {
State(Arc::new(state)),
None,
None,
+ None,
HeaderMap::new(),
Json(vec![
HookBatchItem {
@@ -6511,6 +7016,7 @@ mod tests {
State(Arc::new(state)),
None,
None,
+ None,
HeaderMap::new(),
Json(items),
)
@@ -6545,6 +7051,7 @@ mod tests {
State(Arc::new(state)),
None,
None,
+ None,
HeaderMap::new(),
Json(items),
)
@@ -7574,6 +8081,7 @@ mod tests {
bob,
ai_memory_core::AuthLevel::Anonymous,
Vec::new(),
+ None,
)
.await
.unwrap_err();
@@ -7659,6 +8167,7 @@ mod tests {
bob,
ai_memory_core::AuthLevel::User,
Vec::new(),
+ None,
)
.await
.unwrap_err();
@@ -7755,6 +8264,7 @@ mod tests {
bob.clone(),
ai_memory_core::AuthLevel::User,
Vec::new(),
+ None,
)
.await
.unwrap_err();
@@ -7834,6 +8344,7 @@ mod tests {
bob,
ai_memory_core::AuthLevel::User,
Vec::new(),
+ None,
)
.await
.unwrap_err();
@@ -7907,6 +8418,7 @@ mod tests {
Some(IdentityKey::User("root".into())),
ai_memory_core::AuthLevel::Root,
Vec::new(),
+ None,
)
.await
.unwrap();
@@ -7930,6 +8442,7 @@ mod tests {
Some(IdentityKey::User("root".into())),
ai_memory_core::AuthLevel::Root,
Vec::new(),
+ None,
)
.await
.unwrap_err();
@@ -7945,6 +8458,7 @@ mod tests {
Some(IdentityKey::User("bob".into())),
ai_memory_core::AuthLevel::User,
Vec::new(),
+ None,
)
.await
.unwrap_err();
@@ -7960,6 +8474,7 @@ mod tests {
Some(IdentityKey::User("root".into())),
ai_memory_core::AuthLevel::Root,
Vec::new(),
+ None,
)
.await
.unwrap_err();
@@ -8011,6 +8526,7 @@ mod tests {
IdentityKey::User("bob".into()).to_actor_context(),
)),
Some(axum::Extension(ai_memory_core::AuthLevel::User)),
+ None,
HeaderMap::new(),
Json(items),
)
@@ -8067,6 +8583,7 @@ mod tests {
None,
ai_memory_core::AuthLevel::Anonymous,
Vec::new(),
+ None,
)
.await
.unwrap();
@@ -8114,6 +8631,7 @@ mod tests {
IdentityKey::User("bob".into()).to_actor_context(),
)),
Some(axum::Extension(ai_memory_core::AuthLevel::User)),
+ None,
HeaderMap::new(),
Json(serde_json::json!({"session_id":"async-owned", "prompt":"foreign"})),
)
@@ -8906,13 +9424,14 @@ mod tests {
session_id: Some(SessionId::new().to_string()),
..Default::default()
};
- let first = fetch_and_accept_handoff_at(&state, query.clone(), None, Vec::new(), quiet)
- .await
- .unwrap()
- .unwrap();
+ let first =
+ fetch_and_accept_handoff_at(&state, query.clone(), None, Vec::new(), None, quiet)
+ .await
+ .unwrap()
+ .unwrap();
assert!(first.contains(&format!("Latest assistant response: {project}-latest")));
assert!(!first.contains(&format!("{other}-")));
- let second = fetch_and_accept_handoff_at(&state, query, None, Vec::new(), quiet)
+ let second = fetch_and_accept_handoff_at(&state, query, None, Vec::new(), None, quiet)
.await
.unwrap();
assert!(
@@ -8983,6 +9502,7 @@ mod tests {
receiver(),
None,
Vec::new(),
+ None,
jiff::Timestamp::now(),
)
.await
@@ -8992,10 +9512,11 @@ mod tests {
// Ten minutes after `between`: beta has been quiet, alpha has not.
let later = between + LIVE_BATON_QUIET_PERIOD;
- let delivered = fetch_and_accept_handoff_at(&state, receiver(), None, Vec::new(), later)
- .await
- .unwrap()
- .expect("a quiet live session's baton is deliverable");
+ let delivered =
+ fetch_and_accept_handoff_at(&state, receiver(), None, Vec::new(), None, later)
+ .await
+ .unwrap()
+ .expect("a quiet live session's baton is deliverable");
assert!(delivered.contains("beta work"), "{delivered}");
assert!(!delivered.contains("alpha"), "{delivered}");
assert_eq!(
@@ -9040,6 +9561,7 @@ mod tests {
None,
ai_memory_core::AuthLevel::Anonymous,
Vec::new(),
+ None,
)
};
for name in ["session-start", "user-prompt"] {
@@ -9511,6 +10033,7 @@ mod tests {
..ai_memory_core::ActorContext::default()
})),
Some(axum::Extension(ai_memory_core::AuthLevel::User)),
+ None,
HeaderMap::new(),
)
.await,
@@ -9737,6 +10260,7 @@ mod tests {
None,
ai_memory_core::AuthLevel::Anonymous,
Vec::new(),
+ None,
)
.await
});
@@ -9754,6 +10278,7 @@ mod tests {
None,
ai_memory_core::AuthLevel::Anonymous,
Vec::new(),
+ None,
)
.await
});
@@ -10010,6 +10535,7 @@ mod tests {
State(Arc::new(state.clone())),
None,
level.map(axum::Extension),
+ None,
headers,
Json(items),
)
@@ -10033,6 +10559,121 @@ mod tests {
);
}
+ /// Session start returns a repository's handoff and pinned pages, and
+ /// claims the handoff, keyed only on a project the caller named or a
+ /// directory they are in (#708). Bob, holding nothing on it, gets a 403
+ /// with the reason — never the handoff, never an empty 200 that the hook
+ /// would read as "nothing was left for you" — and the baton stays open for
+ /// someone who may take it.
+ #[tokio::test]
+ async fn session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read() {
+ use ai_memory_core::{AuthorizedViewer, NewUser, UserRole};
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ // Grants only decide anything in a restricted project. The handoff
+ // lives in `scratch`, which starts open whatever the server default
+ // says, so it is restricted explicitly — which an operator may do.
+ state
+ .writer
+ .set_access_mode(state.project_id, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let cwd = tmp.path().to_string_lossy().into_owned();
+ state
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: state.workspace_id,
+ project_id: state.project_id,
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "HANDOFF-MARKER".to_string(),
+ open_questions: Vec::new(),
+ next_steps: Vec::new(),
+ files_touched: Vec::new(),
+ owner_user: None,
+ })
+ .await
+ .unwrap();
+ let human = |name: &'static str| {
+ let writer = state.writer.clone();
+ async move {
+ writer
+ .create_human_user(
+ NewUser {
+ username: name.into(),
+ name: None,
+ email: None,
+ },
+ UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap()
+ }
+ };
+ let alice = human("alice").await;
+ let bob = human("bob").await;
+ state
+ .writer
+ .grant_memory(
+ alice,
+ state.project_id,
+ ai_memory_store::GrantLevel::Read,
+ None,
+ )
+ .await
+ .unwrap();
+ let query = || HandoffQuery {
+ agent: Some("claude-code".into()),
+ cwd: Some(cwd.clone()),
+ workspace: Some("default".into()),
+ project: Some("scratch".into()),
+ project_strategy: None,
+ briefing: Some("1".into()),
+ briefing_budget: None,
+ managed_run: None,
+ session_id: None,
+ };
+ let state = Arc::new(state);
+ let session_start = |viewer: Option<ai_memory_core::UserId>| {
+ let state = state.clone();
+ let query = query();
+ async move {
+ read_handoff_response(
+ handle_handoff(
+ State(state),
+ Query(query),
+ None,
+ None,
+ viewer.map(|user| axum::Extension(AuthorizedViewer(user))),
+ HeaderMap::new(),
+ )
+ .await,
+ )
+ .await
+ }
+ };
+
+ let (status, body) = session_start(Some(bob)).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
+ assert!(body.contains("not authorized for scratch"), "{body}");
+ assert!(
+ !body.contains("HANDOFF-MARKER"),
+ "leaked the handoff: {body}"
+ );
+ assert!(
+ open_handoff_exists(&state).await,
+ "a refused session must not consume somebody else's baton",
+ );
+
+ let (status, body) = session_start(Some(alice)).await;
+ assert_eq!(status, StatusCode::OK);
+ assert!(body.contains("HANDOFF-MARKER"), "{body}");
+ }
+
/// The session-start claim is destructive (a handoff is single-use), so a
/// refused or unreachable `handoff_accept` webhook must leave the baton
/// open for the next session instead of failing the endpoint — and the
@@ -10085,6 +10726,7 @@ mod tests {
Query(query()),
None,
None,
+ None,
HeaderMap::new(),
)
.await,
@@ -10111,6 +10753,7 @@ mod tests {
Query(query()),
None,
Some(axum::Extension(ai_memory_core::AuthLevel::Root)),
+ None,
headers,
)
.await,
@@ -10251,6 +10894,7 @@ mod tests {
}),
None,
None,
+ None,
HeaderMap::new(),
)
.await,
@@ -11066,6 +11710,7 @@ mod tests {
},
None,
Vec::new(),
+ None,
)
.await
.unwrap();
@@ -11139,6 +11784,7 @@ mod tests {
},
None,
Vec::new(),
+ None,
)
.await
.unwrap()
@@ -11204,7 +11850,7 @@ mod tests {
session_id: Some(session_id.into()),
};
let empty_sid = "empty-native-session";
- let rendered = fetch_and_accept_handoff(&state, query(empty_sid), None, Vec::new())
+ let rendered = fetch_and_accept_handoff(&state, query(empty_sid), None, Vec::new(), None)
.await
.unwrap()
.unwrap();
@@ -11245,11 +11891,16 @@ mod tests {
assert!(reopened.lifecycle.accepted_by.is_none());
assert!(reopened.lifecycle.accepted_at.is_none());
assert!(reopened.lifecycle.accepted_by_session.is_none());
- let next =
- fetch_and_accept_handoff(&state, query("next-substantive-session"), None, Vec::new())
- .await
- .unwrap()
- .unwrap();
+ let next = fetch_and_accept_handoff(
+ &state,
+ query("next-substantive-session"),
+ None,
+ Vec::new(),
+ None,
+ )
+ .await
+ .unwrap()
+ .unwrap();
assert!(next.contains("REAL-WORK-MARKER"));
}
@@ -11335,7 +11986,7 @@ mod tests {
managed_run: Some(run.run_id.to_string()),
session_id: Some("native-2".into()),
};
- let rendered = fetch_and_accept_handoff(&state, query.clone(), None, Vec::new())
+ let rendered = fetch_and_accept_handoff(&state, query.clone(), None, Vec::new(), None)
.await
.unwrap();
@@ -11363,7 +12014,7 @@ mod tests {
"a handoff delivered on a managed SessionStart must be marked accepted"
);
assert!(
- fetch_and_accept_handoff(&state, query, None, Vec::new())
+ fetch_and_accept_handoff(&state, query, None, Vec::new(), None)
.await
.unwrap()
.is_none(),
@@ -11446,11 +12097,16 @@ mod tests {
..ai_memory_core::ActorContext::default()
};
for viewer in [ai_memory_core::ActorContext::anonymous(), named] {
- let rendered =
- fetch_and_accept_handoff(&state, query.clone(), viewer.identity_key(), Vec::new())
- .await
- .unwrap()
- .expect("the brief must be injected");
+ let rendered = fetch_and_accept_handoff(
+ &state,
+ query.clone(),
+ viewer.identity_key(),
+ Vec::new(),
+ None,
+ )
+ .await
+ .unwrap()
+ .expect("the brief must be injected");
assert!(
rendered.contains("the backend runs behind a queue"),
"a pre-existing nested slot must survive the upgrade for {viewer:?}: {rendered}"
@@ -11512,10 +12168,11 @@ mod tests {
session_id: None,
};
- let rendered = fetch_and_accept_handoff(&state, query, carol.identity_key(), Vec::new())
- .await
- .unwrap()
- .expect("the brief must be injected");
+ let rendered =
+ fetch_and_accept_handoff(&state, query, carol.identity_key(), Vec::new(), None)
+ .await
+ .unwrap()
+ .expect("the brief must be injected");
assert!(rendered.contains("SHARED-CONTEXT"), "{rendered}");
assert!(
rendered.contains("CAROL-SECRET"),
@@ -11572,19 +12229,21 @@ mod tests {
};
// Non-truthy opt-in: no handoff pending, nothing to inject.
- let rendered = fetch_and_accept_handoff(&state, query(Some("false")), None, Vec::new())
- .await
- .unwrap();
+ let rendered =
+ fetch_and_accept_handoff(&state, query(Some("false")), None, Vec::new(), None)
+ .await
+ .unwrap();
assert!(
rendered.is_none(),
"non-truthy briefing flag must not inject anything"
);
// Truthy opt-in, no pending handoff: brief alone (the /clear case).
- let rendered = fetch_and_accept_handoff(&state, query(Some("true")), None, Vec::new())
- .await
- .unwrap()
- .expect("brief must be injected without a pending handoff");
+ let rendered =
+ fetch_and_accept_handoff(&state, query(Some("true")), None, Vec::new(), None)
+ .await
+ .unwrap()
+ .expect("brief must be injected without a pending handoff");
assert!(
rendered.contains("project brief") && rendered.contains("single writer actor"),
"brief must carry the rules page body: {rendered}"
@@ -11618,10 +12277,11 @@ mod tests {
})
.await
.unwrap();
- let rendered = fetch_and_accept_handoff(&state, query(Some("true")), None, Vec::new())
- .await
- .unwrap()
- .expect("handoff + brief must both be injected");
+ let rendered =
+ fetch_and_accept_handoff(&state, query(Some("true")), None, Vec::new(), None)
+ .await
+ .unwrap()
+ .expect("handoff + brief must both be injected");
let handoff_pos = rendered.find("resume the auth refactor").unwrap();
let brief_pos = rendered.find("project brief").unwrap();
assert!(
@@ -11714,10 +12374,11 @@ mod tests {
session_id: Some("kimi-session".into()),
};
- let rendered = fetch_and_accept_handoff(&state, query(Some("true")), None, Vec::new())
- .await
- .unwrap()
- .expect("managed delta and brief must be injected");
+ let rendered =
+ fetch_and_accept_handoff(&state, query(Some("true")), None, Vec::new(), None)
+ .await
+ .unwrap()
+ .expect("managed delta and brief must be injected");
let delta_pos = rendered.find("portable managed delta sentinel").unwrap();
let brief_pos = rendered.find("managed briefing sentinel").unwrap();
assert!(
@@ -11725,7 +12386,7 @@ mod tests {
"managed delta must precede the project brief: {rendered}"
);
- let rendered = fetch_and_accept_handoff(&state, query(None), None, Vec::new())
+ let rendered = fetch_and_accept_handoff(&state, query(None), None, Vec::new(), None)
.await
.unwrap();
assert!(
@@ -11733,10 +12394,11 @@ mod tests {
"delivered managed context must not repeat without a new briefing request"
);
- let rendered = fetch_and_accept_handoff(&state, query(Some("true")), None, Vec::new())
- .await
- .unwrap()
- .expect("an explicit later briefing request must still render the project brief");
+ let rendered =
+ fetch_and_accept_handoff(&state, query(Some("true")), None, Vec::new(), None)
+ .await
+ .unwrap()
+ .expect("an explicit later briefing request must still render the project brief");
assert!(rendered.contains("managed briefing sentinel"));
assert!(!rendered.contains("portable managed delta sentinel"));
}
@@ -11925,6 +12587,7 @@ mod tests {
},
None,
Vec::new(),
+ None,
)
.await
.unwrap();
@@ -13589,6 +14252,7 @@ mod tests {
State(state.clone()),
None,
None,
+ None,
HeaderMap::new(),
Json(vec![
HookBatchItem {
@@ -13649,6 +14313,7 @@ mod tests {
State(state.clone()),
None,
None,
+ None,
HeaderMap::new(),
Json(vec![HookBatchItem {
url: "http://h/hook?event=post-tool-use&agent=claude-code".into(),
diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rs
index 35916f0c..85f02917 100644
--- a/crates/ai-memory-hooks/src/workstream.rs
+++ b/crates/ai-memory-hooks/src/workstream.rs
@@ -15,8 +15,8 @@ use ai_memory_core::{
};
use ai_memory_store::{
FinishWorkstreamRun, PrepareWorkstreamRun, ReaderPool, RenameWorkstream, ScopeResolutionError,
- StoreError, WorkstreamSelection, WorkstreamSelector, WriterHandle, create_explicit_scope,
- lookup_existing_scope,
+ StoreError, WorkstreamSelection, WorkstreamSelector, WriterHandle,
+ create_explicit_scope_guarded, lookup_existing_scope_guarded,
};
use axum::extract::{Path as AxumPath, Query, State};
use axum::http::StatusCode;
@@ -105,9 +105,53 @@ fn authorize(
})
}
+/// The user whose grants apply to this request, if any do.
+///
+/// [`ai_memory_core::AuthorizedViewer`] is stamped only when an operator has
+/// switched per-repository authorization on, and never for root. `None`
+/// therefore means no per-repository check applies, which leaves every
+/// existing install behaving exactly as it did before the guard existed.
+fn actor_user(
+ actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
+) -> Option<ai_memory_core::UserId> {
+ actor.map(|Extension(viewer)| viewer.user())
+}
+
+/// Authorize the caller on the repository `run_id` belongs to — see
+/// [`crate::grants::authorize_resolved`]. The run routes take the id in the
+/// URL, so without this they would act on any repository's run.
+async fn authorize_run(
+ state: &WorkstreamState,
+ run_id: ManagedRunId,
+ viewer: Option<ai_memory_core::UserId>,
+ required: ai_memory_store::ProjectAccess,
+) -> Result<(), Response> {
+ if viewer.is_none() {
+ return Ok(());
+ }
+ let scope = state
+ .reader
+ .managed_run_scope(run_id)
+ .await
+ .map_err(|failure| error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()))?;
+ crate::grants::authorize_resolved(&state.reader, scope, viewer, required)
+ .await
+ .map_err(scope_refusal)
+}
+
+/// A refusal as a response: 403 for an access problem, 500 otherwise.
+fn scope_refusal(failure: ScopeResolutionError) -> Response {
+ if failure.is_forbidden() {
+ error(StatusCode::FORBIDDEN, failure.to_string())
+ } else {
+ error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string())
+ }
+}
+
async fn prepare_run(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
+ actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
Json(request): Json<PrepareManagedRunRequest>,
) -> Response {
if let Err(response) = authorize(level, Capability::NormalWrite) {
@@ -190,14 +234,19 @@ async fn prepare_run(
return error(StatusCode::BAD_REQUEST, format!("{label} is too long"));
}
}
- let scope = match create_explicit_scope(
+ let scope = match create_explicit_scope_guarded(
+ &state.reader,
&state.writer,
request.workspace.trim(),
request.project.trim(),
+ actor_user(actor),
)
.await
{
Ok(scope) => scope,
+ Err(failure) if failure.is_forbidden() => {
+ return error(StatusCode::FORBIDDEN, failure.to_string());
+ }
Err(failure) => return error(StatusCode::BAD_REQUEST, failure.to_string()),
};
let selection = match (request.workstream, request.new_workstream) {
@@ -246,6 +295,7 @@ async fn prepare_run(
async fn run_status(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
+ actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
AxumPath(raw_run_id): AxumPath<String>,
) -> Response {
if let Err(response) = authorize(level, Capability::NormalRead) {
@@ -255,6 +305,16 @@ async fn run_status(
Ok(id) => id,
Err(response) => return response.into_response(),
};
+ if let Err(response) = authorize_run(
+ &state,
+ run_id,
+ actor_user(actor),
+ ai_memory_store::ProjectAccess::Read,
+ )
+ .await
+ {
+ return response;
+ }
match state.reader.managed_run_status(run_id).await {
Ok(Some(status)) => Json(ManagedRunStatus {
run_id: status.run_id,
@@ -274,6 +334,7 @@ async fn run_status(
async fn heartbeat_run(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
+ actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
AxumPath(raw_run_id): AxumPath<String>,
) -> Response {
if let Err(response) = authorize(level, Capability::NormalWrite) {
@@ -283,6 +344,16 @@ async fn heartbeat_run(
Ok(id) => id,
Err(response) => return response.into_response(),
};
+ if let Err(response) = authorize_run(
+ &state,
+ run_id,
+ actor_user(actor),
+ ai_memory_store::ProjectAccess::Write,
+ )
+ .await
+ {
+ return response;
+ }
match state.writer.heartbeat_managed_run(run_id).await {
Ok(true) => StatusCode::NO_CONTENT.into_response(),
Ok(false) => error(StatusCode::CONFLICT, "managed run lease is not active"),
@@ -293,6 +364,7 @@ async fn heartbeat_run(
async fn cancel_run(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
+ actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
AxumPath(raw_run_id): AxumPath<String>,
) -> Response {
if let Err(response) = authorize(level, Capability::NormalWrite) {
@@ -302,6 +374,16 @@ async fn cancel_run(
Ok(id) => id,
Err(response) => return response.into_response(),
};
+ if let Err(response) = authorize_run(
+ &state,
+ run_id,
+ actor_user(actor),
+ ai_memory_store::ProjectAccess::Write,
+ )
+ .await
+ {
+ return response;
+ }
match state.writer.cancel_managed_run(run_id).await {
Ok(_) => StatusCode::NO_CONTENT.into_response(),
Err(failure) => store_error_response(failure),
@@ -311,6 +393,7 @@ async fn cancel_run(
async fn run_context(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
+ actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
AxumPath(raw_run_id): AxumPath<String>,
) -> Response {
if let Err(response) = authorize(level, Capability::NormalWrite) {
@@ -320,6 +403,16 @@ async fn run_context(
Ok(id) => id,
Err(response) => return response.into_response(),
};
+ if let Err(response) = authorize_run(
+ &state,
+ run_id,
+ actor_user(actor),
+ ai_memory_store::ProjectAccess::Write,
+ )
+ .await
+ {
+ return response;
+ }
let context = match state.reader.managed_run_context(run_id, 256).await {
Ok(Some(context)) => context,
Ok(None) => return error(StatusCode::NOT_FOUND, "active managed run not found"),
@@ -346,6 +439,7 @@ async fn run_context(
async fn accept_run_context(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
+ actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
AxumPath(raw_run_id): AxumPath<String>,
) -> Response {
if let Err(response) = authorize(level, Capability::NormalWrite) {
@@ -355,6 +449,16 @@ async fn accept_run_context(
Ok(id) => id,
Err(response) => return response.into_response(),
};
+ if let Err(response) = authorize_run(
+ &state,
+ run_id,
+ actor_user(actor),
+ ai_memory_store::ProjectAccess::Write,
+ )
+ .await
+ {
+ return response;
+ }
let status = match state.reader.managed_run_status(run_id).await {
Ok(Some(status)) => status,
Ok(None) => return error(StatusCode::NOT_FOUND, "managed run not found"),
@@ -388,6 +492,7 @@ const fn default_event_limit() -> usize {
async fn list_recent_workstreams(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
+ actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
Json(request): Json<ListManagedWorkstreamsRequest>,
) -> Response {
if let Err(response) = authorize(level, Capability::NormalRead) {
@@ -409,14 +514,19 @@ async fn list_recent_workstreams(
return error(StatusCode::BAD_REQUEST, format!("{label} is too long"));
}
}
- let scope = match lookup_existing_scope(
+ let scope = match lookup_existing_scope_guarded(
&state.reader,
request.workspace.trim(),
request.project.trim(),
+ actor_user(actor),
+ ai_memory_store::ProjectAccess::Read,
)
.await
{
Ok(scope) => scope,
+ Err(failure) if failure.is_forbidden() => {
+ return error(StatusCode::FORBIDDEN, failure.to_string());
+ }
Err(failure) if failure.is_not_found() => {
return error(StatusCode::NOT_FOUND, failure.to_string());
}
@@ -474,6 +584,7 @@ async fn list_recent_workstreams(
async fn rename_workstream(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
+ actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
Json(request): Json<RenameManagedWorkstreamRequest>,
) -> Response {
if let Err(response) = authorize(level, Capability::NormalWrite) {
@@ -521,14 +632,19 @@ async fn rename_workstream(
);
}
};
- let scope = match lookup_existing_scope(
+ let scope = match lookup_existing_scope_guarded(
&state.reader,
request.workspace.trim(),
request.project.trim(),
+ actor_user(actor),
+ ai_memory_store::ProjectAccess::Write,
)
.await
{
Ok(scope) => scope,
+ Err(failure) if failure.is_forbidden() => {
+ return error(StatusCode::FORBIDDEN, failure.to_string());
+ }
Err(failure) if failure.is_not_found() => {
return error(StatusCode::NOT_FOUND, failure.to_string());
}
@@ -566,6 +682,7 @@ async fn rename_workstream(
async fn search_events(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
+ actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
AxumPath(raw_workstream_id): AxumPath<String>,
Query(query): Query<EventQuery>,
) -> Response {
@@ -576,6 +693,23 @@ async fn search_events(
Ok(id) => id,
Err(_) => return error(StatusCode::BAD_REQUEST, "invalid workstream id"),
};
+ // The id reaches a repository's event history without naming it.
+ if let Some(viewer) = actor_user(actor) {
+ let scope = match state.reader.workstream_scope(workstream_id).await {
+ Ok(scope) => scope,
+ Err(failure) => return error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),
+ };
+ if let Err(failure) = crate::grants::authorize_resolved(
+ &state.reader,
+ scope,
+ Some(viewer),
+ ai_memory_store::ProjectAccess::Read,
+ )
+ .await
+ {
+ return scope_refusal(failure);
+ }
+ }
match state
.reader
.search_workstream_events(workstream_id, query.q, query.limit.clamp(1, 100))
@@ -589,6 +723,7 @@ async fn search_events(
async fn link_run(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
+ actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
AxumPath(raw_run_id): AxumPath<String>,
Json(request): Json<LinkManagedRunRequest>,
) -> Response {
@@ -599,6 +734,16 @@ async fn link_run(
Ok(id) => id,
Err(response) => return response.into_response(),
};
+ if let Err(response) = authorize_run(
+ &state,
+ run_id,
+ actor_user(actor),
+ ai_memory_store::ProjectAccess::Write,
+ )
+ .await
+ {
+ return response;
+ }
if request.native_session_id.trim().is_empty()
|| request.native_session_id.len() > MAX_NATIVE_SESSION_ID_BYTES
{
@@ -626,6 +771,7 @@ async fn link_run(
async fn finish_run(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
+ actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
AxumPath(raw_run_id): AxumPath<String>,
Json(mut request): Json<FinishManagedRunRequest>,
) -> Response {
@@ -636,6 +782,16 @@ async fn finish_run(
Ok(id) => id,
Err(response) => return response.into_response(),
};
+ if let Err(response) = authorize_run(
+ &state,
+ run_id,
+ actor_user(actor),
+ ai_memory_store::ProjectAccess::Write,
+ )
+ .await
+ {
+ return response;
+ }
if request.events.len() > MAX_EVENTS_PER_FINISH {
return error(
StatusCode::PAYLOAD_TOO_LARGE,
@@ -996,6 +1152,7 @@ mod tests {
let response = run_status(
State(state.clone()),
None,
+ None,
AxumPath(prepared.run_id.to_string()),
)
.await;
@@ -1046,6 +1203,7 @@ mod tests {
let ok = rename_workstream(
State(state.clone()),
None,
+ None,
Json(request(Some("typo-nmae"), "refactor-db")),
)
.await;
@@ -1063,28 +1221,31 @@ mod tests {
// A name that exists, but in another worktree, must not be reachable.
let mut wrong_worktree = request(Some("refactor-db"), "stolen");
wrong_worktree.worktree_fingerprint = "other-worktree".into();
- let response = rename_workstream(State(state.clone()), None, Json(wrong_worktree)).await;
+ let response =
+ rename_workstream(State(state.clone()), None, None, Json(wrong_worktree)).await;
assert_eq!(response.status(), StatusCode::NOT_FOUND);
// Unknown scopes stay 404 rather than being created by the write.
let mut missing = request(Some("refactor-db"), "stolen");
missing.workspace = "missing".into();
- let response = rename_workstream(State(state.clone()), None, Json(missing)).await;
+ let response = rename_workstream(State(state.clone()), None, None, Json(missing)).await;
assert_eq!(response.status(), StatusCode::NOT_FOUND);
// Neither selector, and both selectors, are caller errors the server
// rejects on its own rather than trusting clap to have done it.
- let neither = rename_workstream(State(state.clone()), None, Json(request(None, "x"))).await;
+ let neither =
+ rename_workstream(State(state.clone()), None, None, Json(request(None, "x"))).await;
assert_eq!(neither.status(), StatusCode::BAD_REQUEST);
let mut both = request(Some("refactor-db"), "x");
both.workstream_id = Some(prepared.workstream_id);
- let both = rename_workstream(State(state.clone()), None, Json(both)).await;
+ let both = rename_workstream(State(state.clone()), None, None, Json(both)).await;
assert_eq!(both.status(), StatusCode::BAD_REQUEST);
// An invalid destination name is a 400, not a 500.
let invalid = rename_workstream(
State(state.clone()),
None,
+ None,
Json(request(Some("refactor-db"), "a/b")),
)
.await;
@@ -1102,6 +1263,7 @@ mod tests {
let conflict = rename_workstream(
State(state),
None,
+ None,
Json(request(Some("refactor-db"), "taken")),
)
.await;
@@ -1139,6 +1301,7 @@ mod tests {
let response = list_recent_workstreams(
State(state.clone()),
None,
+ None,
Json(ListManagedWorkstreamsRequest {
workspace: "default".into(),
project: "managed".into(),
@@ -1164,6 +1327,7 @@ mod tests {
let other_checkout = list_recent_workstreams(
State(state.clone()),
None,
+ None,
Json(ListManagedWorkstreamsRequest {
workspace: "default".into(),
project: "managed".into(),
@@ -1184,6 +1348,7 @@ mod tests {
let missing = list_recent_workstreams(
State(state),
None,
+ None,
Json(ListManagedWorkstreamsRequest {
workspace: "missing".into(),
project: "managed".into(),
@@ -1229,6 +1394,7 @@ mod tests {
let response = prepare_run(
State(state),
None,
+ None,
Json(PrepareManagedRunRequest {
workspace: "default".into(),
project: "managed".into(),
@@ -1264,6 +1430,7 @@ mod tests {
let explicit = prepare_run(
State(state.clone()),
None,
+ None,
Json(PrepareManagedRunRequest {
workspace: "default".into(),
project: "managed".into(),
@@ -1301,6 +1468,7 @@ mod tests {
let automatic = prepare_run(
State(state),
None,
+ None,
Json(PrepareManagedRunRequest {
workspace: "default".into(),
project: "managed".into(),
@@ -1328,6 +1496,7 @@ mod tests {
let explicit = prepare_run(
State(state.clone()),
None,
+ None,
Json(PrepareManagedRunRequest {
workspace: "default".into(),
project: "managed".into(),
@@ -1364,6 +1533,7 @@ mod tests {
let automatic = prepare_run(
State(state),
None,
+ None,
Json(PrepareManagedRunRequest {
workspace: "default".into(),
project: "managed".into(),
@@ -1391,6 +1561,7 @@ mod tests {
let explicit = prepare_run(
State(state.clone()),
None,
+ None,
Json(PrepareManagedRunRequest {
workspace: "default".into(),
project: "managed".into(),
@@ -1427,6 +1598,7 @@ mod tests {
let automatic = prepare_run(
State(state),
None,
+ None,
Json(PrepareManagedRunRequest {
workspace: "default".into(),
project: "managed".into(),
@@ -1454,6 +1626,7 @@ mod tests {
let explicit = prepare_run(
State(state.clone()),
None,
+ None,
Json(PrepareManagedRunRequest {
workspace: "default".into(),
project: "managed".into(),
@@ -1490,6 +1663,7 @@ mod tests {
let automatic = prepare_run(
State(state),
None,
+ None,
Json(PrepareManagedRunRequest {
workspace: "default".into(),
project: "managed".into(),
@@ -1520,6 +1694,7 @@ mod tests {
let explicit = prepare_run(
State(state.clone()),
None,
+ None,
Json(PrepareManagedRunRequest {
workspace: "default".into(),
project: "managed".into(),
@@ -1556,6 +1731,7 @@ mod tests {
let automatic = prepare_run(
State(state),
None,
+ None,
Json(PrepareManagedRunRequest {
workspace: "default".into(),
project: "managed".into(),
@@ -1586,6 +1762,7 @@ mod tests {
let context = run_context(
State(state.clone()),
None,
+ None,
AxumPath(prepared.run_id.to_string()),
)
.await;
@@ -1594,15 +1771,21 @@ mod tests {
let accept = accept_run_context(
State(state.clone()),
None,
+ None,
AxumPath(prepared.run_id.to_string()),
)
.await;
assert_eq!(accept.status(), StatusCode::NO_CONTENT);
// Delivered context is not re-rendered.
- let redelivered = run_context(State(state), None, AxumPath(prepared.run_id.to_string()))
- .await
- .into_body();
+ let redelivered = run_context(
+ State(state),
+ None,
+ None,
+ AxumPath(prepared.run_id.to_string()),
+ )
+ .await
+ .into_body();
let body = to_bytes(redelivered, 64 * 1024).await.unwrap();
let response: ai_memory_core::ManagedRunContextResponse =
serde_json::from_slice(&body).unwrap();
@@ -1626,6 +1809,7 @@ mod tests {
let response = cancel_run(
State(state.clone()),
None,
+ None,
AxumPath(prepared.run_id.to_string()),
)
.await;
@@ -1688,6 +1872,7 @@ mod tests {
run_context(
State(state.clone()),
None,
+ None,
AxumPath(crush.run_id.to_string()),
)
};
@@ -1716,6 +1901,7 @@ mod tests {
let accepted = accept_run_context(
State(state.clone()),
None,
+ None,
AxumPath(crush.run_id.to_string()),
)
.await;
@@ -1788,4 +1974,161 @@ mod tests {
0o600
);
}
+
+ /// The run and workstream routes take an id in the URL, so they never
+ /// passed through scope resolution (#708): anyone holding a run id could
+ /// read its status, heartbeat or cancel it, and anyone holding a
+ /// workstream id could read that repository's event history. With
+ /// authorization on, each now answers only someone who may reach the
+ /// run's repository at the level the operation needs.
+ #[tokio::test]
+ async fn run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository() {
+ use ai_memory_core::{AuthorizedViewer, NewUser, UserRole};
+ let temp = TempDir::new().unwrap();
+ let store = Store::open(temp.path()).unwrap();
+ let state = test_state(&store, temp.path());
+ // Grants only decide anything in a restricted project.
+ store
+ .writer
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+
+ let prepared = prepare_run(
+ State(state.clone()),
+ None,
+ None,
+ Json(PrepareManagedRunRequest {
+ workspace: "default".into(),
+ project: "alice-client-work".into(),
+ cwd: "/repo".into(),
+ repo_fingerprint: "repo".into(),
+ worktree_fingerprint: "worktree".into(),
+ agent: AgentKind::ClaudeCode,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ workstream: None,
+ new_workstream: None,
+ lease_owner: "alice".into(),
+ }),
+ )
+ .await;
+ assert_eq!(prepared.status(), StatusCode::OK);
+ let body = to_bytes(prepared.into_body(), 64 * 1024).await.unwrap();
+ let prepared: PrepareManagedRunResponse = serde_json::from_slice(&body).unwrap();
+ let (_, repository) = store
+ .reader
+ .managed_run_scope(prepared.run_id)
+ .await
+ .unwrap()
+ .expect("the run was just prepared");
+
+ let human = |name: &'static str| {
+ let writer = store.writer.clone();
+ async move {
+ writer
+ .create_human_user(
+ NewUser {
+ username: name.into(),
+ name: None,
+ email: None,
+ },
+ UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap()
+ }
+ };
+ let alice = human("alice").await;
+ let bob = human("bob").await;
+ let carol = human("carol").await;
+ store
+ .writer
+ .grant_memory(alice, repository, ai_memory_store::GrantLevel::Write, None)
+ .await
+ .unwrap();
+ // Carol may read the repository but not act on its runs.
+ store
+ .writer
+ .grant_memory(carol, repository, ai_memory_store::GrantLevel::Read, None)
+ .await
+ .unwrap();
+ let as_viewer = |user| Some(Extension(AuthorizedViewer(user)));
+ let run = || AxumPath(prepared.run_id.to_string());
+
+ // Status is a read: bob (nothing) is refused, carol (reader) is not.
+ let refused = run_status(State(state.clone()), None, as_viewer(bob), run()).await;
+ assert_eq!(refused.status(), StatusCode::FORBIDDEN);
+ let refusal = to_bytes(refused.into_body(), 64 * 1024).await.unwrap();
+ assert!(
+ String::from_utf8_lossy(&refusal).contains("not authorized for alice-client-work"),
+ "{}",
+ String::from_utf8_lossy(&refusal)
+ );
+ assert_eq!(
+ run_status(State(state.clone()), None, as_viewer(carol), run())
+ .await
+ .status(),
+ StatusCode::OK
+ );
+
+ // Acting on the run needs write: carol's read is not enough.
+ for viewer in [bob, carol] {
+ assert_eq!(
+ heartbeat_run(State(state.clone()), None, as_viewer(viewer), run())
+ .await
+ .status(),
+ StatusCode::FORBIDDEN,
+ "heartbeat"
+ );
+ assert_eq!(
+ cancel_run(State(state.clone()), None, as_viewer(viewer), run())
+ .await
+ .status(),
+ StatusCode::FORBIDDEN,
+ "cancel"
+ );
+ }
+ assert_eq!(
+ heartbeat_run(State(state.clone()), None, as_viewer(alice), run())
+ .await
+ .status(),
+ StatusCode::NO_CONTENT,
+ "alice's own run keeps working"
+ );
+
+ // The event history behind a workstream id.
+ let events = |viewer| {
+ search_events(
+ State(state.clone()),
+ None,
+ viewer,
+ AxumPath(prepared.workstream_id.to_string()),
+ Query(EventQuery::default()),
+ )
+ };
+ assert_eq!(events(as_viewer(bob)).await.status(), StatusCode::FORBIDDEN);
+ assert_eq!(events(as_viewer(carol)).await.status(), StatusCode::OK);
+
+ // No viewer — an install with no database users, or root — is unchanged.
+ assert_eq!(
+ run_status(State(state.clone()), None, None, run())
+ .await
+ .status(),
+ StatusCode::OK
+ );
+ assert_eq!(events(None).await.status(), StatusCode::OK);
+
+ // An id that matches nothing is still "not found", not a refusal.
+ let unknown = run_status(
+ State(state.clone()),
+ None,
+ as_viewer(bob),
+ AxumPath(ManagedRunId::new().to_string()),
+ )
+ .await;
+ assert_eq!(unknown.status(), StatusCode::NOT_FOUND);
+ }
}
diff --git a/crates/ai-memory-mcp/Cargo.toml b/crates/ai-memory-mcp/Cargo.toml
index 4b713b5c..365eaa7f 100644
--- a/crates/ai-memory-mcp/Cargo.toml
+++ b/crates/ai-memory-mcp/Cargo.toml
@@ -20,6 +20,9 @@ ai-memory-wiki.workspace = true
anyhow.workspace = true
thiserror.workspace = true
flate2.workspace = true
+# Tests insert grant rows directly, so the decision tests do not depend on
+# the grant management API.
+rusqlite.workspace = true
tar.workspace = true
tempfile.workspace = true
serde.workspace = true
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 54562feb..7604a738 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -717,7 +717,15 @@ pub fn admin_router_with_sweep_tuning(
.route(
"/admin/api-credentials/{id}/revoke",
post(handle_revoke_api_credential),
- );
+ )
+ .route("/admin/users/{username}/grant", post(handle_user_grant))
+ .route("/admin/users/{username}/revoke", post(handle_user_revoke))
+ .route(
+ "/admin/users/{username}/grants",
+ get(handle_list_user_grants),
+ )
+ .route("/admin/projects/grants", get(handle_list_project_grants))
+ .route("/admin/projects/access", post(handle_project_access));
operational
.merge(users)
.route_layer(axum::middleware::from_fn_with_state(
@@ -1182,7 +1190,7 @@ pub struct WikiFormatStatus {
/// chain, such as an offline `--data-dir` purge or a direct DB edit) and can
/// be pruned so the copy reflects the live server.
async fn handle_list_projects(State(state): State<Arc<AdminState>>) -> impl IntoResponse {
- match state.reader.list_projects_with_stats().await {
+ match state.reader.list_projects_with_stats(OPERATOR).await {
Ok(projects) => (
StatusCode::OK,
Json(serde_json::json!({ "projects": projects })),
@@ -1549,7 +1557,7 @@ async fn handle_search(
})),
);
}
- _ => state.reader.search_pages(query.q, limit).await,
+ _ => state.reader.search_pages(query.q, limit, OPERATOR).await,
};
match search_result {
Ok(hits) => (
@@ -1738,6 +1746,21 @@ fn trimmed_opt(value: Option<&str>) -> Option<&str> {
value.map(str::trim).filter(|s| !s.is_empty())
}
+/// Who the admin surface resolves scopes as.
+///
+/// `/admin/*` is the operator's door: the router attaches
+/// [`require_root_for_multiuser_admin`] as a `route_layer`, so on a multi-user
+/// install only `AuthLevel::Root` reaches any handler below (a DB user gets
+/// 403 — covered by the `admin_*_token` tests). Root authenticates from
+/// configuration, not from a `users` row, so the auth middleware stamps no
+/// `UserId` on the request and there is no per-repository grant to check.
+///
+/// This is therefore an assertion, not a forgotten argument: the operator is
+/// authorized by the middleware above, at a coarser granularity than grants.
+/// If a handler here ever needs to run as a named user, it must take the
+/// `UserId` extension and pass it instead of this.
+const OPERATOR: Option<ai_memory_core::UserId> = None;
+
/// Resolve workspace + project IDs, creating them if absent. Returns
/// either the IDs or a ready-to-return error response.
async fn create_ws_proj(
@@ -1779,6 +1802,8 @@ async fn lookup_ws_no_create(
fn scope_err(err: ScopeResolutionError) -> (StatusCode, Json<serde_json::Value>) {
let status = if err.is_bad_request() {
StatusCode::BAD_REQUEST
+ } else if err.is_forbidden() {
+ StatusCode::FORBIDDEN
} else if err.is_not_found() {
StatusCode::NOT_FOUND
} else {
@@ -3669,7 +3694,7 @@ async fn handle_embed(
let summaries = state
.reader
- .list_projects_with_stats()
+ .list_projects_with_stats(OPERATOR)
.await
.map_err(|e| internal_err(e.to_string()))?;
for summary in summaries
@@ -4576,7 +4601,7 @@ async fn delete_workspace_core(
if !force {
match state
.reader
- .list_projects_with_stats_for_workspace(workspace.to_string())
+ .list_projects_with_stats_for_workspace(workspace.to_string(), OPERATOR)
.await
{
Ok(projects) if !projects.is_empty() => {
@@ -6678,7 +6703,7 @@ async fn handle_merge_workspace(
let projects = match state
.reader
- .list_projects_with_stats_for_workspace(req.from.clone())
+ .list_projects_with_stats_for_workspace(req.from.clone(), OPERATOR)
.await
{
Ok(p) => p,
@@ -7596,6 +7621,258 @@ async fn handle_revoke_api_credential(
))
}
+/// Body of `POST /admin/users/{username}/grant` and `…/revoke` (#708).
+///
+/// Names, not ids: this is what an operator types. `level` is required by
+/// grant — never defaulted — and ignored by revoke, which takes away whatever
+/// is held.
+#[derive(Debug, Deserialize)]
+struct UserGrantRequest {
+ workspace: String,
+ project: String,
+ #[serde(default)]
+ level: Option<String>,
+}
+
+/// Resolve a grant's user and project to the ids the table keys on.
+///
+/// The project is looked up, never created: granting access to a project that
+/// does not exist yet would be a typo that silently succeeds and then grants
+/// nothing anyone can reach.
+async fn grant_target(
+ state: &AdminState,
+ username: &str,
+ request: &UserGrantRequest,
+) -> Result<(ai_memory_core::UserId, ProjectId), (StatusCode, Json<serde_json::Value>)> {
+ let user = lookup_user_by_username(state, username.trim()).await?;
+ let (_, project) =
+ lookup_ws_proj_no_create(state, request.workspace.trim(), request.project.trim()).await?;
+ Ok((user.id, project))
+}
+
+fn grants_json(grants: Vec<ai_memory_store::GrantListing>) -> Json<serde_json::Value> {
+ let grants: Vec<_> = grants
+ .into_iter()
+ .map(|g| {
+ serde_json::json!({
+ "username": g.username,
+ "workspace": g.workspace,
+ "project": g.project,
+ "level": g.level.as_str(),
+ })
+ })
+ .collect();
+ Json(serde_json::json!({ "grants": grants }))
+}
+
+/// `GET /admin/users/{username}/grants` — every project one user holds a
+/// grant on.
+async fn handle_list_user_grants(
+ State(state): State<Arc<AdminState>>,
+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,
+ axum::extract::Path(username): axum::extract::Path<String>,
+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
+ require_root(level)?;
+ let user = lookup_user_by_username(&state, username.trim()).await?;
+ let grants = state
+ .reader
+ .list_grants(ai_memory_store::GrantFilter::User(user.id))
+ .await
+ .map_err(|e| internal_err(e.to_string()))?;
+ Ok((StatusCode::OK, grants_json(grants)))
+}
+
+/// Query of `GET /admin/projects/grants`: both names for one project, or
+/// neither for every grant on the server.
+#[derive(Debug, Deserialize)]
+struct ProjectGrantsQuery {
+ workspace: Option<String>,
+ project: Option<String>,
+}
+
+/// `GET /admin/projects/grants[?workspace=&project=]` — who holds a grant on
+/// one project, or every grant on the server.
+async fn handle_list_project_grants(
+ State(state): State<Arc<AdminState>>,
+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,
+ Query(query): Query<ProjectGrantsQuery>,
+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
+ require_root(level)?;
+ let filter = match (query.workspace.as_deref(), query.project.as_deref()) {
+ (None, None) => ai_memory_store::GrantFilter::All,
+ (Some(workspace), Some(project)) => {
+ let (_, project) =
+ lookup_ws_proj_no_create(&state, workspace.trim(), project.trim()).await?;
+ ai_memory_store::GrantFilter::Project(project)
+ }
+ _ => {
+ return Err(validation_error(
+ "pass both workspace and project, or neither for every grant".into(),
+ ));
+ }
+ };
+ let grants = state
+ .reader
+ .list_grants(filter)
+ .await
+ .map_err(|e| internal_err(e.to_string()))?;
+ Ok((StatusCode::OK, grants_json(grants)))
+}
+
+/// `POST /admin/users/{username}/grant` — give a user a level on a project, or
+/// change the level they hold.
+///
+/// Returns what actually happened, so "already had that" is not reported as a
+/// change.
+async fn handle_user_grant(
+ State(state): State<Arc<AdminState>>,
+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,
+ operator: Option<axum::Extension<ai_memory_core::UserId>>,
+ axum::extract::Path(username): axum::extract::Path<String>,
+ Json(request): Json<UserGrantRequest>,
+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
+ require_root(level)?;
+ // Refuse rather than default. A grant whose level was mistyped must not
+ // quietly become `write`: the operator meant *something*, and guessing
+ // which in an authorization table is how access gets wider than intended.
+ let grant_level = request
+ .level
+ .as_deref()
+ .ok_or_else(|| validation_error("level is required: read or write".into()))
+ .and_then(|raw| {
+ ai_memory_store::GrantLevel::from_db(raw.trim())
+ .ok_or_else(|| validation_error(format!("unknown level {raw:?}: read or write")))
+ })?;
+ let (user, project) = grant_target(&state, &username, &request).await?;
+ let outcome = state
+ .writer
+ .grant_memory(
+ user,
+ project,
+ grant_level,
+ operator.map(|axum::Extension(id)| id),
+ )
+ .await
+ .map_err(|e| internal_err(e.to_string()))?;
+ let (changed, previous) = match outcome {
+ ai_memory_store::GrantOutcome::Granted => (true, None),
+ ai_memory_store::GrantOutcome::LevelChanged { from } => (true, Some(from.as_str())),
+ ai_memory_store::GrantOutcome::Unchanged => (false, Some(grant_level.as_str())),
+ };
+ Ok((
+ StatusCode::OK,
+ Json(serde_json::json!({
+ "username": username.trim(),
+ "workspace": request.workspace.trim(),
+ "project": request.project.trim(),
+ "level": grant_level.as_str(),
+ "changed": changed,
+ "previous": previous,
+ })),
+ ))
+}
+
+/// `POST /admin/users/{username}/revoke` — take away whatever a user holds on
+/// a project.
+async fn handle_user_revoke(
+ State(state): State<Arc<AdminState>>,
+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,
+ operator: Option<axum::Extension<ai_memory_core::UserId>>,
+ axum::extract::Path(username): axum::extract::Path<String>,
+ Json(request): Json<UserGrantRequest>,
+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
+ require_root(level)?;
+ let (user, project) = grant_target(&state, &username, &request).await?;
+ let revoked = state
+ .writer
+ .revoke_memory(user, project, operator.map(|axum::Extension(id)| id))
+ .await
+ .map_err(|e| internal_err(e.to_string()))?;
+ Ok((
+ StatusCode::OK,
+ Json(serde_json::json!({
+ "username": username.trim(),
+ "workspace": request.workspace.trim(),
+ "project": request.project.trim(),
+ "revoked": revoked,
+ })),
+ ))
+}
+
+/// Body of `POST /admin/projects/access`.
+#[derive(Debug, serde::Deserialize)]
+struct ProjectAccessRequest {
+ workspace: String,
+ project: String,
+ mode: Option<String>,
+}
+
+/// `POST /admin/projects/access` — set a project `open` or `restricted` (#708).
+///
+/// Restricting admits only root and grant holders from the next request on —
+/// the creator holds `write` from the moment they created it. The response
+/// names the page authors who hold no grant and so lose access, so the
+/// operator can grant the ones who should keep it. Nothing is granted
+/// automatically: restricting is the action meant to narrow access, and it must
+/// not widen it on the way.
+async fn handle_project_access(
+ State(state): State<Arc<AdminState>>,
+ axum::Extension(level): axum::Extension<ai_memory_core::AuthLevel>,
+ Json(request): Json<ProjectAccessRequest>,
+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
+ require_root(level)?;
+ // Required, never defaulted: a mistyped mode must not quietly become one
+ // the operator did not ask for.
+ let mode = request
+ .mode
+ .as_deref()
+ .map(str::trim)
+ .and_then(|raw| match raw {
+ "open" => Some(ai_memory_store::AccessMode::Open),
+ "restricted" => Some(ai_memory_store::AccessMode::Restricted),
+ _ => None,
+ })
+ .ok_or_else(|| validation_error("mode is required: open or restricted".into()))?;
+ let (workspace, project) = (request.workspace.trim(), request.project.trim());
+ if project == ai_memory_core::GLOBAL_SCOPE_PROJECT {
+ return Err(validation_error(format!(
+ "{project} is the shared preferences scope, read by every user; it cannot be restricted"
+ )));
+ }
+ let (_, project_id) = lookup_ws_proj_no_create(&state, workspace, project).await?;
+ let previous = state
+ .writer
+ .set_access_mode(project_id, mode)
+ .await
+ .map_err(|e| internal_err(e.to_string()))?
+ .ok_or_else(|| {
+ (
+ StatusCode::NOT_FOUND,
+ Json(serde_json::json!({ "error": format!("no project {workspace}/{project}") })),
+ )
+ })?;
+ let without_access = if mode == ai_memory_store::AccessMode::Restricted {
+ state
+ .reader
+ .authors_without_grant(project_id)
+ .await
+ .map_err(|e| internal_err(e.to_string()))?
+ } else {
+ Vec::new()
+ };
+ Ok((
+ StatusCode::OK,
+ Json(serde_json::json!({
+ "workspace": workspace,
+ "project": project,
+ "mode": mode.as_str(),
+ "previous": previous.as_str(),
+ "changed": previous != mode,
+ "without_access": without_access,
+ })),
+ ))
+}
+
async fn lookup_user_by_username(
state: &AdminState,
username: &str,
@@ -12273,6 +12550,419 @@ mod tests {
assert!(json["user"]["disabled_at"].is_null());
}
+ async fn admin_call(
+ router: &Router,
+ method: &str,
+ uri: &str,
+ token: &str,
+ body: Option<serde_json::Value>,
+ ) -> (StatusCode, serde_json::Value) {
+ let mut builder = Request::builder()
+ .method(method)
+ .uri(uri)
+ .header("authorization", format!("Bearer {token}"));
+ let body = match body {
+ Some(json) => {
+ builder = builder.header("content-type", "application/json");
+ Body::from(serde_json::to_vec(&json).unwrap())
+ }
+ None => Body::empty(),
+ };
+ let resp = router
+ .clone()
+ .oneshot(builder.body(body).unwrap())
+ .await
+ .unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null);
+ (status, json)
+ }
+
+ /// The operator's whole grant workflow over HTTP, as `ai-memory user grant`
+ /// drives it.
+ #[tokio::test]
+ async fn grants_can_be_issued_changed_listed_and_revoked_by_root() {
+ let (_tmp, router) = user_admin_test_router("root-token");
+ let _ = post_create_user(
+ &router,
+ "root-token",
+ serde_json::json!({"username": "alice"}),
+ )
+ .await;
+ let (status, _) = admin_call(
+ &router,
+ "POST",
+ "/admin/write-page",
+ "root-token",
+ Some(serde_json::json!({
+ "workspace": "default",
+ "project": "client-work",
+ "path": "notes/seed.md",
+ "body": "exists so the repository does",
+ })),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK);
+
+ let target = |level: Option<&str>| {
+ let mut body = serde_json::json!({
+ "workspace": "default",
+ "project": "client-work",
+ });
+ if let Some(level) = level {
+ body["level"] = level.into();
+ }
+ Some(body)
+ };
+
+ // A level left unsaid is refused, not defaulted.
+ let (status, _) = admin_call(
+ &router,
+ "POST",
+ "/admin/users/alice/grant",
+ "root-token",
+ target(None),
+ )
+ .await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ let (status, _) = admin_call(
+ &router,
+ "POST",
+ "/admin/users/alice/grant",
+ "root-token",
+ target(Some("owner")),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "unknown level must not be guessed at"
+ );
+ // There is no per-project administrator: administration is root's.
+ let (status, _) = admin_call(
+ &router,
+ "POST",
+ "/admin/users/alice/grant",
+ "root-token",
+ target(Some("admin")),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "admin is not a grant level"
+ );
+
+ let (status, json) = admin_call(
+ &router,
+ "POST",
+ "/admin/users/alice/grant",
+ "root-token",
+ target(Some("write")),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(json["changed"], true);
+ assert!(json["previous"].is_null());
+
+ let (_, json) = admin_call(
+ &router,
+ "POST",
+ "/admin/users/alice/grant",
+ "root-token",
+ target(Some("write")),
+ )
+ .await;
+ assert_eq!(
+ json["changed"], false,
+ "the same level again is not a change"
+ );
+
+ let (_, json) = admin_call(
+ &router,
+ "POST",
+ "/admin/users/alice/grant",
+ "root-token",
+ target(Some("read")),
+ )
+ .await;
+ assert_eq!(json["changed"], true);
+ assert_eq!(json["previous"], "write");
+
+ // A typo in the repository is a 404, and does not create it: asking
+ // twice still finds nothing.
+ for _ in 0..2 {
+ let (status, _) = admin_call(
+ &router,
+ "POST",
+ "/admin/users/alice/grant",
+ "root-token",
+ Some(serde_json::json!({
+ "workspace": "default",
+ "project": "client-wrok",
+ "level": "read",
+ })),
+ )
+ .await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+ }
+
+ let (status, json) =
+ admin_call(&router, "GET", "/admin/projects/grants", "root-token", None).await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(
+ json["grants"],
+ serde_json::json!([{
+ "username": "alice",
+ "workspace": "default",
+ "project": "client-work",
+ "level": "read",
+ }])
+ );
+ // The same grant seen from the user and from the project.
+ let (_, by_user) = admin_call(
+ &router,
+ "GET",
+ "/admin/users/alice/grants",
+ "root-token",
+ None,
+ )
+ .await;
+ assert_eq!(by_user["grants"], json["grants"]);
+ let (_, by_project) = admin_call(
+ &router,
+ "GET",
+ "/admin/projects/grants?workspace=default&project=client-work",
+ "root-token",
+ None,
+ )
+ .await;
+ assert_eq!(by_project["grants"], json["grants"]);
+ let (status, _) = admin_call(
+ &router,
+ "GET",
+ "/admin/projects/grants?workspace=default",
+ "root-token",
+ None,
+ )
+ .await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "workspace without project");
+
+ let (_, json) = admin_call(
+ &router,
+ "POST",
+ "/admin/users/alice/revoke",
+ "root-token",
+ target(None),
+ )
+ .await;
+ assert_eq!(json["revoked"], true);
+ let (_, json) = admin_call(
+ &router,
+ "POST",
+ "/admin/users/alice/revoke",
+ "root-token",
+ target(None),
+ )
+ .await;
+ assert_eq!(json["revoked"], false, "revoking twice reports honestly");
+ }
+
+ async fn write_fixture_page(router: &Router, workspace: &str, project: &str, path: &str) {
+ let (status, json) = admin_call(
+ router,
+ "POST",
+ "/admin/write-page",
+ "root-token",
+ Some(serde_json::json!({
+ "workspace": workspace,
+ "project": project,
+ "path": path,
+ "body": format!("lives in {workspace}/{project}"),
+ })),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{json}");
+ }
+
+ async fn grant_alice(router: &Router, workspace: &str, project: &str) {
+ let (status, json) = admin_call(
+ router,
+ "POST",
+ "/admin/users/alice/grant",
+ "root-token",
+ Some(serde_json::json!({
+ "workspace": workspace,
+ "project": project,
+ "level": "write",
+ })),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{json}");
+ }
+
+ async fn grants_in_force(router: &Router) -> serde_json::Value {
+ let (_, json) =
+ admin_call(router, "GET", "/admin/projects/grants", "root-token", None).await;
+ json["grants"].clone()
+ }
+
+ /// A grant never outlives its project (#708): the destructive operations
+ /// proceed exactly as they do without grants, and the grants go with what
+ /// they granted — the design's CASCADE.
+ #[tokio::test]
+ async fn purging_a_project_takes_its_grants() {
+ let (_tmp, router) = user_admin_test_router("root-token");
+ let _ = post_create_user(
+ &router,
+ "root-token",
+ serde_json::json!({"username": "alice"}),
+ )
+ .await;
+ write_fixture_page(&router, "default", "client-work", "notes/a.md").await;
+ grant_alice(&router, "default", "client-work").await;
+ assert_eq!(grants_in_force(&router).await.as_array().unwrap().len(), 1);
+
+ let (status, json) = admin_call(
+ &router,
+ "POST",
+ "/admin/purge-project",
+ "root-token",
+ Some(serde_json::json!({
+ "workspace": "default",
+ "project": "client-work",
+ "confirm": true,
+ })),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{json}");
+ assert_eq!(grants_in_force(&router).await, serde_json::json!([]));
+ }
+
+ /// A merging move copies the source into an existing destination and then
+ /// purges the source: the source's grants go with it, and none appear on
+ /// the destination — carrying them across would widen someone's access to
+ /// the destination's other content.
+ #[tokio::test]
+ async fn a_merging_move_does_not_carry_grants_to_the_destination() {
+ let (_tmp, router) = user_admin_test_router("root-token");
+ let _ = post_create_user(
+ &router,
+ "root-token",
+ serde_json::json!({"username": "alice"}),
+ )
+ .await;
+ write_fixture_page(&router, "team-a", "shared", "notes/from-a.md").await;
+ write_fixture_page(&router, "team-b", "shared", "notes/from-b.md").await;
+ grant_alice(&router, "team-a", "shared").await;
+
+ let (status, json) = admin_call(
+ &router,
+ "POST",
+ "/admin/move-project",
+ "root-token",
+ Some(serde_json::json!({
+ "from_workspace": "team-a",
+ "project": "shared",
+ "to_workspace": "team-b",
+ "confirm": true,
+ })),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{json}");
+ assert_eq!(grants_in_force(&router).await, serde_json::json!([]));
+ }
+
+ #[tokio::test]
+ async fn deleting_a_workspace_takes_its_grants() {
+ let (_tmp, router) = user_admin_test_router("root-token");
+ let _ = post_create_user(
+ &router,
+ "root-token",
+ serde_json::json!({"username": "alice"}),
+ )
+ .await;
+ write_fixture_page(&router, "team-c", "api", "notes/x.md").await;
+ grant_alice(&router, "team-c", "api").await;
+
+ let (status, json) = admin_call(
+ &router,
+ "POST",
+ "/admin/delete-workspace",
+ "root-token",
+ Some(serde_json::json!({"workspace": "team-c", "force": true})),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{json}");
+ assert_eq!(grants_in_force(&router).await, serde_json::json!([]));
+ }
+
+ #[tokio::test]
+ async fn only_root_may_touch_grants() {
+ let (_tmp, router) = user_admin_test_router("root-token");
+ // Any bearer that is not root authenticates as an ordinary user in
+ // this harness. None of the grant routes may answer it: a user who
+ // could grant would be a user who could grant themselves.
+ for (method, uri) in [
+ ("GET", "/admin/projects/grants"),
+ ("GET", "/admin/users/alice/grants"),
+ ("POST", "/admin/users/alice/grant"),
+ ("POST", "/admin/users/alice/revoke"),
+ ] {
+ let body = (method == "POST").then(|| {
+ serde_json::json!({
+ "workspace": "default",
+ "project": "client-work",
+ "level": "write",
+ })
+ });
+ let (status, _) = admin_call(&router, method, uri, "not-root", body).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{method} {uri}");
+ }
+ }
+
+ /// `POST /admin/projects/access` (#708): a mode is required and never
+ /// guessed, the shared preferences scope cannot be restricted, an unknown
+ /// project creates nothing, repeating a mode reports no change, and only
+ /// root may call it.
+ #[tokio::test]
+ async fn project_access_sets_the_mode_and_refuses_what_it_must() {
+ let (_tmp, router) = user_admin_test_router("root-token");
+ write_fixture_page(&router, "default", "client-work", "notes/a.md").await;
+ let call = |token: &'static str, body: serde_json::Value| {
+ let router = router.clone();
+ async move { admin_call(&router, "POST", "/admin/projects/access", token, Some(body)).await }
+ };
+
+ for body in [
+ 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"}),
+ ] {
+ let (status, json) = call("root-token", body.clone()).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body} -> {json}");
+ }
+ let (status, _) = call(
+ "root-token",
+ serde_json::json!({"workspace": "default", "project": "nope", "mode": "restricted"}),
+ )
+ .await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+
+ let restrict = serde_json::json!({"workspace": "default", "project": "client-work", "mode": "restricted"});
+ let (status, json) = call("root-token", restrict.clone()).await;
+ assert_eq!(status, StatusCode::OK, "{json}");
+ assert_eq!(json["mode"], "restricted");
+ assert_eq!(json["previous"], "open");
+ assert_eq!(json["changed"], true);
+ let (_, json) = call("root-token", restrict.clone()).await;
+ assert_eq!(json["changed"], false, "repeating a mode is not a change");
+
+ let (status, _) = call("not-root", restrict).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ }
+
#[tokio::test]
async fn disable_unknown_user_returns_404() {
let (_tmp, router) = user_admin_test_router("root-token");
diff --git a/crates/ai-memory-mcp/src/auth.rs b/crates/ai-memory-mcp/src/auth.rs
index 363fa9c4..baa7f333 100644
--- a/crates/ai-memory-mcp/src/auth.rs
+++ b/crates/ai-memory-mcp/src/auth.rs
@@ -363,6 +363,10 @@ pub(crate) async fn authenticate_token(
};
req.extensions_mut().insert(actor);
req.extensions_mut().insert(hit.user.id);
+ // Every database user is subject to per-project access; an
+ // open project admits them, a restricted one asks for a grant.
+ req.extensions_mut()
+ .insert(ai_memory_core::AuthorizedViewer(hit.user.id));
req.extensions_mut().insert(AuthLevel::User);
let writer = mu.writer.clone();
let user_id = hit.user.id;
@@ -1414,6 +1418,47 @@ mod tests {
assert_ne!(actor.user.as_deref(), Some("root"));
}
+ /// Every database user is subject to per-project access, so the
+ /// middleware stamps the viewer for each of them — there is no switch.
+ /// Root is never stamped: it is authorized above per-project granularity.
+ #[tokio::test]
+ async fn a_database_user_is_always_a_viewer_and_root_never_is() {
+ async fn viewer(
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ ) -> String {
+ viewer.map_or_else(String::new, |axum::Extension(v)| v.user().to_string())
+ }
+ let (_tmp, state, token) = setup_multiuser("alice").await;
+ let router = Router::new().route("/viewer", get(viewer)).layer(
+ axum::middleware::from_fn_with_state(Arc::new(state), require_bearer),
+ );
+ let ask = |bearer: String| {
+ let router = router.clone();
+ async move {
+ let resp = router
+ .oneshot(
+ Request::builder()
+ .uri("/viewer")
+ .header("Authorization", format!("Bearer {bearer}"))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let bytes = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
+ String::from_utf8(bytes.to_vec()).unwrap()
+ }
+ };
+ assert!(!ask(token).await.is_empty(), "a database user is a viewer");
+ assert!(
+ ask("root-token-distinct-from-user-token".to_owned())
+ .await
+ .is_empty(),
+ "root is not"
+ );
+ }
+
#[tokio::test]
async fn rung3_unknown_bearer_with_multiuser_returns_401_not_anonymous() {
// The bypass guard: bearer present but matches NEITHER root
diff --git a/crates/ai-memory-mcp/src/human_auth.rs b/crates/ai-memory-mcp/src/human_auth.rs
index d957f192..2547e177 100644
--- a/crates/ai-memory-mcp/src/human_auth.rs
+++ b/crates/ai-memory-mcp/src/human_auth.rs
@@ -1076,12 +1076,23 @@ pub async fn require_dual_auth(
}
}
+/// Stamp a browser session's identity onto the request.
+///
+/// `authorization` decides whether the session also carries an
+/// [`ai_memory_core::AuthorizedViewer`]. A root session never does: root is
+/// the operator, authorized above per-repository granularity, and stamping one
+/// would make the operator's own grants (of which there are none) the limit of
+/// what they can reach.
fn inject_session(req: &mut Request<axum::body::Body>, live: LiveWebSession) {
let level = if live.user.role == UserRole::Root {
AuthLevel::Root
} else {
AuthLevel::User
};
+ if level == AuthLevel::User {
+ req.extensions_mut()
+ .insert(ai_memory_core::AuthorizedViewer(live.user.id));
+ }
let actor = ActorContext {
user: Some(live.user.username.clone()),
name: live.user.name.clone(),
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 95f88133..746fc05c 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -1601,10 +1601,45 @@ struct WritePageArgs {
#[tool_router]
impl AiMemoryServer {
- fn scope_resolver(&self) -> ScopeResolver<'_> {
- ScopeResolver::new(&self.reader, self.workspace_id, self.project_id)
+ /// A resolver bound to the user this request authenticated as (#708).
+ ///
+ /// The viewer is an argument rather than something read from `&self`
+ /// because it is per-request: the server is shared, the caller is not.
+ /// Every tool below reaches its project through here, so this is the one
+ /// place the MCP surface attaches the per-project choke point. A viewer is
+ /// only ever stamped for a database user, so a present one means the
+ /// deployment distinguishes operators; none (root, or an install with no
+ /// database users) attaches no principal and resolves as before.
+ fn scope_resolver_as(&self, viewer: Option<ai_memory_core::UserId>) -> ScopeResolver<'_> {
+ let resolver = ScopeResolver::new(&self.reader, self.workspace_id, self.project_id)
.with_writer(&self.writer)
- .with_active_project(&self.active_project)
+ .with_active_project(&self.active_project);
+ match viewer {
+ Some(viewer) => {
+ resolver.with_project_authz(ai_memory_store::ProjectPrincipal::user(viewer), true)
+ }
+ None => resolver,
+ }
+ }
+
+ /// The user whose grants apply to this request, if any do.
+ ///
+ /// Deliberately reads [`ai_memory_core::AuthorizedViewer`] rather than the
+ /// bare `UserId` alongside it. The bare id is always present for a
+ /// database user because attribution must not depend on a policy setting;
+ /// this one is stamped only when an operator has switched per-repository
+ /// authorization on, and never for root. `None` therefore means "no
+ /// per-repository check applies" — an open install, an install that has
+ /// not enabled authorization, or the operator.
+ fn viewer_from_parts(
+ parts: Option<&axum::http::request::Parts>,
+ ) -> Option<ai_memory_core::UserId> {
+ parts.and_then(|parts| {
+ parts
+ .extensions
+ .get::<ai_memory_core::AuthorizedViewer>()
+ .map(|viewer| viewer.user())
+ })
}
/// Map a scope-resolution failure to the error the caller can act on.
@@ -1836,23 +1871,81 @@ impl AiMemoryServer {
&self,
explicit_project: Option<&str>,
actor: &ai_memory_core::ActorKey,
+ viewer: Option<ai_memory_core::UserId>,
) -> Result<(WorkspaceId, ProjectId), McpError> {
- self.scope_resolver()
+ self.scope_resolver_as(viewer)
.resolve_current_or_project(explicit_project, actor)
.await
.map(ai_memory_store::ResolvedScope::as_tuple)
.map_err(Self::scope_error)
}
+ /// Resolve the scope for a tool that only READS it.
+ ///
+ /// Paired with [`Self::effective_ids_for_mutation_args_with_actor`], which
+ /// takes identical arguments and differs only in the level it demands. Two
+ /// methods named for intent rather than one with a role argument: a role
+ /// argument is a thing a call site can forget, or copy from the wrong
+ /// neighbour, and the neighbours here are tools that delete pages. The
+ /// name at the call site should say which one this is.
async fn effective_ids_for_read_args_with_actor(
&self,
explicit_workspace: Option<&str>,
explicit_project: Option<&str>,
actor: &ai_memory_core::ActorKey,
+ viewer: Option<ai_memory_core::UserId>,
+ ) -> Result<(WorkspaceId, ProjectId), McpError> {
+ self.resolve_existing_args_as(
+ explicit_workspace,
+ explicit_project,
+ actor,
+ viewer,
+ ai_memory_store::ProjectAccess::Read,
+ )
+ .await
+ }
+
+ /// Resolve the scope for a tool that CHANGES it, without creating it.
+ ///
+ /// Same argument shape as a read — an explicit workspace/project pair, or
+ /// the current-project fallback chain — and that is exactly the trap this
+ /// exists to close. `memory_delete_page`, `memory_feedback`,
+ /// `memory_forget_sweep`, `memory_lint`, `memory_auto_improve`, the
+ /// handoff accept/cancel pair, and the message queue's pop, cancel and the
+ /// recipient of a send all take read-shaped arguments and all mutate.
+ ///
+ /// Distinct from [`Self::write_target_ids_with_actor`], which may CREATE
+ /// the target. These tools act on something that must already be there.
+ async fn effective_ids_for_mutation_args_with_actor(
+ &self,
+ explicit_workspace: Option<&str>,
+ explicit_project: Option<&str>,
+ actor: &ai_memory_core::ActorKey,
+ viewer: Option<ai_memory_core::UserId>,
+ ) -> Result<(WorkspaceId, ProjectId), McpError> {
+ self.resolve_existing_args_as(
+ explicit_workspace,
+ explicit_project,
+ actor,
+ viewer,
+ ai_memory_store::ProjectAccess::Write,
+ )
+ .await
+ }
+
+ async fn resolve_existing_args_as(
+ &self,
+ explicit_workspace: Option<&str>,
+ explicit_project: Option<&str>,
+ actor: &ai_memory_core::ActorKey,
+ viewer: Option<ai_memory_core::UserId>,
+ required: ai_memory_store::ProjectAccess,
) -> Result<(WorkspaceId, ProjectId), McpError> {
- self.traced_ids_for_read_args(explicit_workspace, explicit_project, actor)
+ self.scope_resolver_as(viewer)
+ .resolve_existing_args(explicit_workspace, explicit_project, actor, required)
.await
- .map(|(ids, _)| ids)
+ .map(ai_memory_store::ResolvedScope::as_tuple)
+ .map_err(Self::scope_error)
}
/// [`Self::effective_ids_for_read_args_with_actor`], plus where the scope
@@ -1864,10 +1957,49 @@ impl AiMemoryServer {
explicit_workspace: Option<&str>,
explicit_project: Option<&str>,
actor: &ai_memory_core::ActorKey,
+ viewer: Option<ai_memory_core::UserId>,
+ ) -> Result<((WorkspaceId, ProjectId), ai_memory_store::ScopeSource), McpError> {
+ self.traced_ids_for_existing_args(
+ explicit_workspace,
+ explicit_project,
+ actor,
+ viewer,
+ ai_memory_store::ProjectAccess::Read,
+ )
+ .await
+ }
+
+ /// [`Self::effective_ids_for_mutation_args_with_actor`], plus where the
+ /// scope came from — for a mutating tool whose empty answer from an
+ /// inferred scope needs the same hint a read's does.
+ async fn traced_ids_for_mutation_args(
+ &self,
+ explicit_workspace: Option<&str>,
+ explicit_project: Option<&str>,
+ actor: &ai_memory_core::ActorKey,
+ viewer: Option<ai_memory_core::UserId>,
+ ) -> Result<((WorkspaceId, ProjectId), ai_memory_store::ScopeSource), McpError> {
+ self.traced_ids_for_existing_args(
+ explicit_workspace,
+ explicit_project,
+ actor,
+ viewer,
+ ai_memory_store::ProjectAccess::Write,
+ )
+ .await
+ }
+
+ async fn traced_ids_for_existing_args(
+ &self,
+ explicit_workspace: Option<&str>,
+ explicit_project: Option<&str>,
+ actor: &ai_memory_core::ActorKey,
+ viewer: Option<ai_memory_core::UserId>,
+ need: ai_memory_store::ProjectAccess,
) -> Result<((WorkspaceId, ProjectId), ai_memory_store::ScopeSource), McpError> {
let (scope, source) = self
- .scope_resolver()
- .resolve_read_args_traced(explicit_workspace, explicit_project, actor)
+ .scope_resolver_as(viewer)
+ .resolve_existing_args_traced(explicit_workspace, explicit_project, actor, need)
.await
.map_err(Self::scope_error)?;
if source.is_fallback() {
@@ -1912,6 +2044,7 @@ impl AiMemoryServer {
explicit_workspace,
explicit_project,
&ai_memory_core::ActorKey::default(),
+ None,
)
.await
}
@@ -1921,8 +2054,9 @@ impl AiMemoryServer {
explicit_workspace: Option<&str>,
explicit_project: Option<&str>,
actor: &ai_memory_core::ActorKey,
+ viewer: Option<ai_memory_core::UserId>,
) -> Result<(WorkspaceId, ProjectId), McpError> {
- self.scope_resolver()
+ self.scope_resolver_as(viewer)
.resolve_write_args(explicit_workspace, explicit_project, actor)
.await
.map(ai_memory_store::ResolvedScope::as_tuple)
@@ -1932,12 +2066,13 @@ impl AiMemoryServer {
async fn resolve_query_scopes(
&self,
scopes: &[MemoryScopeArg],
+ viewer: Option<ai_memory_core::UserId>,
) -> Result<Vec<(WorkspaceId, ProjectId)>, McpError> {
let names: Vec<_> = scopes
.iter()
.map(|scope| ScopeName::new(&scope.workspace, &scope.project))
.collect();
- self.scope_resolver()
+ self.scope_resolver_as(viewer)
.resolve_many_existing(&names, MAX_QUERY_SCOPES)
.await
.map(|scopes| {
@@ -2409,6 +2544,7 @@ impl AiMemoryServer {
args.query.clone(),
limit,
include_expired.then_some(i64::MIN),
+ Self::viewer_from_parts(Some(&parts)),
)
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
@@ -2461,6 +2597,7 @@ impl AiMemoryServer {
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let fused = self
@@ -2500,7 +2637,10 @@ impl AiMemoryServer {
let resolved_scopes = if args.scopes.is_empty() {
None
} else {
- Some(self.resolve_query_scopes(&args.scopes).await?)
+ Some(
+ self.resolve_query_scopes(&args.scopes, Self::viewer_from_parts(Some(&parts)))
+ .await?,
+ )
};
let hits = if let Some(scopes) = &resolved_scopes {
let mut hits_by_id: HashMap<PageId, (PageHit, Option<ai_memory_store::SearchExplain>)> =
@@ -2549,6 +2689,7 @@ impl AiMemoryServer {
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
self.search_project(
@@ -2602,6 +2743,7 @@ impl AiMemoryServer {
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
self.reader
@@ -2630,7 +2772,12 @@ impl AiMemoryServer {
// global write), `hits` already covers it — don't search
// it twice.
let current = self
- .effective_ids_for_read_args_with_actor(None, None, &aps_actor)
+ .effective_ids_for_read_args_with_actor(
+ None,
+ None,
+ &aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
+ )
.await?;
if current == scope.as_tuple() {
Vec::new()
@@ -2696,6 +2843,7 @@ impl AiMemoryServer {
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let pins = self
@@ -2800,7 +2948,7 @@ impl AiMemoryServer {
if !explicit_scoping && self.active_project.default_global_for(&aps_actor) {
let global_hits = self
.reader
- .recent_pages_global(limit)
+ .recent_pages_global(limit, Self::viewer_from_parts(Some(&parts)))
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
return ok_json(&MemoryRecentResponse {
@@ -2813,6 +2961,7 @@ impl AiMemoryServer {
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let hits = self
@@ -2855,10 +3004,11 @@ impl AiMemoryServer {
.map_err(|e| McpError::invalid_params(format!("invalid path: {e}"), None))?;
let kind = args.signal;
let (ws, proj) = self
- .effective_ids_for_read_args_with_actor(
+ .effective_ids_for_mutation_args_with_actor(
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
// The reason is free-text from the model; scrub it on the way in
@@ -3097,10 +3247,11 @@ impl AiMemoryServer {
self.require_admin_capability(&parts).await?;
let aps_actor = Self::actor_key_from_parts(Some(&parts));
let (ws, proj) = self
- .effective_ids_for_read_args_with_actor(
+ .effective_ids_for_mutation_args_with_actor(
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let report = run_sweep_with_compaction(
@@ -3138,10 +3289,11 @@ impl AiMemoryServer {
));
};
let (ws, proj) = self
- .effective_ids_for_read_args_with_actor(
+ .effective_ids_for_mutation_args_with_actor(
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let report = run_lint(
@@ -3224,7 +3376,12 @@ impl AiMemoryServer {
_ => {
let aps_actor = Self::actor_key_from_parts(Some(&parts));
let (ws, proj) = self
- .effective_ids_for_read_args_with_actor(None, None, &aps_actor)
+ .effective_ids_for_read_args_with_actor(
+ None,
+ None,
+ &aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
+ )
.await?;
let latest = self
.reader
@@ -3246,6 +3403,32 @@ impl AiMemoryServer {
}
};
let dry = args.dry_run.unwrap_or(false);
+ // A session id reaches a repository without naming it, so it never
+ // passes through scope resolution and the grant check that comes with
+ // it (#708). Authorize the repository the page would land in — the
+ // consolidator's own target, not a guess — before anything runs,
+ // dry runs included: a dry run reports the resolved path and the
+ // admission verdict, which is itself information about that
+ // repository. Writing a page needs `write`.
+ if let Some(viewer) = Self::viewer_from_parts(Some(&parts))
+ && let Some((workspace_id, project_id)) = consolidator
+ .session_target(session_id)
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?
+ {
+ ai_memory_store::authorize_scope_for(
+ &self.reader,
+ Some(&self.writer),
+ ai_memory_store::ResolvedScope {
+ workspace_id,
+ project_id,
+ },
+ Some(viewer),
+ ai_memory_store::ProjectAccess::Write,
+ )
+ .await
+ .map_err(Self::scope_error)?;
+ }
// Carry the request's authenticated identity into the write so the
// consolidated page is attributed to the real operator and any
// admission webhook authorizes by that actor (rather than the previous
@@ -3320,10 +3503,11 @@ impl AiMemoryServer {
.unwrap_or_else(ai_memory_core::ActorContext::anonymous);
let author_id = parts.extensions.get::<ai_memory_core::UserId>().copied();
let (ws, proj) = self
- .effective_ids_for_read_args_with_actor(
+ .effective_ids_for_mutation_args_with_actor(
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let Some(llm) = self.llm.as_ref() else {
@@ -3616,6 +3800,7 @@ impl AiMemoryServer {
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?
}
@@ -3777,6 +3962,7 @@ impl AiMemoryServer {
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
// Diagnose cross-project scope-bleed: a read with no explicit scope
@@ -3970,6 +4156,7 @@ impl AiMemoryServer {
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let owner_filter =
@@ -4133,10 +4320,11 @@ impl AiMemoryServer {
let path = PagePath::new(args.path.clone())
.map_err(|e| McpError::internal_error(format!("invalid path: {e}"), None))?;
let (ws, proj) = self
- .effective_ids_for_read_args_with_actor(
+ .effective_ids_for_mutation_args_with_actor(
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
@@ -4215,6 +4403,7 @@ impl AiMemoryServer {
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let open_questions = cap_handoff_list(
@@ -4314,6 +4503,7 @@ impl AiMemoryServer {
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let actor_user = crate::actor::actor_from_parts(&parts)
@@ -4371,10 +4561,11 @@ impl AiMemoryServer {
) -> Result<CallToolResult, McpError> {
let aps_actor = Self::actor_key_from_parts(Some(&parts));
let (ws, proj) = self
- .effective_ids_for_read_args_with_actor(
+ .effective_ids_for_mutation_args_with_actor(
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let actor_user = crate::actor::actor_from_parts(&parts)
@@ -4478,10 +4669,11 @@ impl AiMemoryServer {
let handoff_id = HandoffId::from_str(&args.handoff_id)
.map_err(|e| McpError::internal_error(format!("invalid handoff_id: {e}"), None))?;
let (ws, proj) = self
- .effective_ids_for_read_args_with_actor(
+ .effective_ids_for_mutation_args_with_actor(
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
// Resolve the cross-owner escape hatch before reading the object. A
@@ -4563,16 +4755,21 @@ impl AiMemoryServer {
args.from_workspace.as_deref(),
args.from_project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
- // Recipient MUST already exist: resolve through the no-create read path
- // so a typo fails closed with a scope error naming the target, instead
- // of dropping a message into a phantom inbox nobody reads.
+ // Recipient MUST already exist: resolved without creating it, so a typo
+ // fails closed with a scope error naming the target instead of dropping
+ // a message into a phantom inbox nobody reads. And it needs `write`:
+ // delivering into a project's inbox puts text into its agents' context,
+ // which is a write to that project — otherwise the mailbox would be a
+ // way around a restricted project's grants (#708).
let (to_ws, to_proj) = self
- .effective_ids_for_read_args_with_actor(
+ .effective_ids_for_mutation_args_with_actor(
Some(args.to_workspace.as_str()),
Some(args.to_project.as_str()),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
// Messages bypass `Wiki::write_page`, so scrub the agent-supplied text
@@ -4638,6 +4835,7 @@ impl AiMemoryServer {
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let mailbox = match args.r#box.as_deref().map(str::trim) {
@@ -4697,10 +4895,11 @@ impl AiMemoryServer {
) -> Result<CallToolResult, McpError> {
let aps_actor = Self::actor_key_from_parts(Some(&parts));
let ((ws, proj), scope_source) = self
- .traced_ids_for_read_args(
+ .traced_ids_for_mutation_args(
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let specific_id =
@@ -4772,10 +4971,11 @@ impl AiMemoryServer {
) -> Result<CallToolResult, McpError> {
let aps_actor = Self::actor_key_from_parts(Some(&parts));
let (ws, proj) = self
- .effective_ids_for_read_args_with_actor(
+ .effective_ids_for_mutation_args_with_actor(
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let specific_id =
@@ -4818,6 +5018,7 @@ impl AiMemoryServer {
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let counts = self
@@ -4862,6 +5063,7 @@ impl AiMemoryServer {
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let actor = crate::actor::actor_from_parts(&parts);
@@ -4907,6 +5109,7 @@ impl AiMemoryServer {
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
let actor = crate::actor::actor_from_parts(&parts);
@@ -6724,6 +6927,140 @@ mod tests {
);
}
+ /// The design's open question 3 (#708): delivering into a restricted
+ /// project's inbox needs `write` on it, or the mailbox is a way around its
+ /// grants. Popping an inbox and cancelling an outbox change a queue, so
+ /// they need `write` on it too; a `read` grant is refused all three.
+ #[tokio::test]
+ async fn a_restricted_projects_queues_need_write() {
+ let (_tmp, store, server, ws, _scratch) = setup_server().await;
+ let team = store
+ .writer
+ .get_or_create_project(ws, "team", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .set_access_mode(team, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let human = |name: &'static str| {
+ let writer = store.writer.clone();
+ async move {
+ writer
+ .create_human_user(
+ NewUser {
+ username: name.into(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap()
+ }
+ };
+ let reader = human("ray").await;
+ let member = human("mia").await;
+ grant_role(store.db_path(), reader, team, "read");
+ grant_role(store.db_path(), member, team, "write");
+ let as_user = |user: ai_memory_core::UserId| {
+ let mut parts = test_parts_default();
+ parts.extensions.insert(AuthLevel::User);
+ parts.extensions.insert(user);
+ parts
+ .extensions
+ .insert(ai_memory_core::AuthorizedViewer(user));
+ OptionalParts(parts)
+ };
+ let send = |user, from: &'static str, to: &'static str| {
+ let server = &server;
+ async move {
+ server
+ .memory_message_send(
+ Parameters(MessageSendArgs {
+ to_workspace: "default".into(),
+ to_project: to.into(),
+ body: "please look at this".into(),
+ subject: None,
+ from_project: Some(from.into()),
+ from_workspace: Some("default".into()),
+ }),
+ as_user(user),
+ )
+ .await
+ }
+ };
+ let pop = |user| {
+ let server = &server;
+ async move {
+ server
+ .memory_message_pop(
+ Parameters(MessagePopArgs {
+ message_id: None,
+ project: Some("team".into()),
+ workspace: Some("default".into()),
+ }),
+ as_user(user),
+ )
+ .await
+ }
+ };
+ let cancel = |user| {
+ let server = &server;
+ async move {
+ server
+ .memory_message_cancel(
+ Parameters(MessageCancelArgs {
+ message_id: None,
+ project: Some("team".into()),
+ workspace: Some("default".into()),
+ }),
+ as_user(user),
+ )
+ .await
+ }
+ };
+ let refused_for_write = |result: Result<CallToolResult, McpError>| {
+ let err = result.expect_err("a read grant must be refused");
+ assert!(format!("{err:?}").contains("needs write"), "{err:?}");
+ };
+
+ // Into the restricted inbox: `read` is not enough, `write` is.
+ refused_for_write(send(reader, "scratch", "team").await);
+ send(member, "scratch", "team")
+ .await
+ .expect("write delivers");
+ // Out of it: popping consumes the team's mail.
+ refused_for_write(pop(reader).await);
+ let json = |result: CallToolResult| -> serde_json::Value {
+ let text = result
+ .content
+ .first()
+ .and_then(|c| c.as_text())
+ .map(|t| t.text.clone())
+ .unwrap();
+ serde_json::from_str(&text).unwrap()
+ };
+ let popped = json(pop(member).await.expect("write pops"));
+ assert!(
+ popped["message"]
+ .to_string()
+ .contains("please look at this"),
+ "{popped}"
+ );
+ // The team's outbox: sending FROM it reads the sender side only, but
+ // clearing it is a change to the team's queue.
+ send(member, "team", "scratch")
+ .await
+ .expect("send from team");
+ refused_for_write(cancel(reader).await);
+ let cancelled = json(cancel(member).await.expect("write cancels"));
+ assert_eq!(cancelled["cancelled"], 1, "{cancelled}");
+ }
+
async fn server_project_json(store: &Store, ws: WorkspaceId, name: &str) -> serde_json::Value {
let proj = store
.writer
@@ -7839,7 +8176,7 @@ mod tests {
// Baseline: nothing published, no arg → baked-in default.
assert_eq!(
server
- .effective_ids_with_actor(None, &ai_memory_core::ActorKey::default())
+ .effective_ids_with_actor(None, &ai_memory_core::ActorKey::default(), None)
.await
.unwrap(),
(ws, baked)
@@ -7860,7 +8197,7 @@ mod tests {
server.active_project.set(ws, other);
assert_eq!(
server
- .effective_ids_with_actor(None, &ai_memory_core::ActorKey::default())
+ .effective_ids_with_actor(None, &ai_memory_core::ActorKey::default(), None)
.await
.unwrap(),
(ws, other)
@@ -7869,7 +8206,11 @@ mod tests {
// An explicit (existing) project arg wins over the active pointer.
assert_eq!(
server
- .effective_ids_with_actor(Some("scratch"), &ai_memory_core::ActorKey::default())
+ .effective_ids_with_actor(
+ Some("scratch"),
+ &ai_memory_core::ActorKey::default(),
+ None
+ )
.await
.unwrap(),
(ws, baked),
@@ -7879,7 +8220,11 @@ mod tests {
// An explicit but unknown project name fails closed instead of
// silently falling through to the active pointer.
let err = server
- .effective_ids_with_actor(Some("does-not-exist"), &ai_memory_core::ActorKey::default())
+ .effective_ids_with_actor(
+ Some("does-not-exist"),
+ &ai_memory_core::ActorKey::default(),
+ None,
+ )
.await
.expect_err("unknown explicit project must not fall back");
assert!(
@@ -8046,7 +8391,11 @@ mod tests {
);
assert_eq!(
server
- .effective_ids_with_actor(Some("sibling"), &ai_memory_core::ActorKey::default())
+ .effective_ids_with_actor(
+ Some("sibling"),
+ &ai_memory_core::ActorKey::default(),
+ None
+ )
.await
.unwrap(),
(active_ws, sibling_proj),
@@ -11191,79 +11540,615 @@ mod tests {
assert_eq!(author.email.as_deref(), Some("[email protected]"));
}
- fn parts_with_level(level: ai_memory_core::AuthLevel) -> axum::http::request::Parts {
- let mut parts = test_parts_default();
- parts.extensions.insert(level);
- parts
+ /// Grant `role` on `repository` by writing the row directly, so these
+ /// tests exercise the decision without depending on the grant API.
+ fn grant_role(
+ db: &std::path::Path,
+ user: ai_memory_core::UserId,
+ repository: ProjectId,
+ role: &str,
+ ) {
+ let conn = rusqlite::Connection::open(db).unwrap();
+ conn.execute(
+ "INSERT INTO project_grants \
+ (workspace_id, project_id, user_id, level, granted_by, granted_at) \
+ SELECT workspace_id, ?1, ?2, ?3, ?2, 1 FROM projects WHERE id = ?1",
+ rusqlite::params![
+ repository.as_bytes().to_vec(),
+ user.as_bytes().to_vec(),
+ role
+ ],
+ )
+ .unwrap();
}
- /// Where `memory_write_page` says the page actually landed — not always
- /// the path the caller asked for, since a slot write may be namespaced.
- fn written_path(result: &CallToolResult) -> String {
- let text = result
- .content
- .first()
- .and_then(|c| c.as_text())
- .map(|t| t.text.clone())
- .expect("tool result carries text");
- serde_json::from_str::<serde_json::Value>(&text).expect("tool result is JSON")["path"]
- .as_str()
- .expect("response carries the written path")
- .to_string()
+ fn grant_writer(db: &std::path::Path, user: ai_memory_core::UserId, repository: ProjectId) {
+ grant_role(db, user, repository, "write");
}
- /// A `_slots/<segment>/…` body is injected verbatim into that operator's
- /// next session brief, so an unguarded write into someone else's namespace
- /// is a way to put chosen text into their agent's context. The read
- /// boundary does not cover this direction.
+ /// A reader-only grant must not be able to change anything.
///
- /// Also pins the other half: with `[slots] per_user` off, a nested slot
- /// path is an ordinary page and the write keeps working for anyone.
+ /// This is the bug this branch exists for. Every tool below takes the same
+ /// read-shaped arguments as `memory_read_page`, and every one of them
+ /// mutates; they all resolved through the read path, so `read` was
+ /// enough to delete a page. The table is the audit: if a tool moves
+ /// between the two lists, that is a deliberate policy change and this test
+ /// is where it has to be argued.
#[tokio::test]
- async fn slot_writes_stay_inside_the_callers_namespace() {
- let (tmp, store, server, _ws, _pj) = setup_server().await;
- let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
- let server = server.with_wiki(wiki);
- // A users row is what puts this deployment on the multi-operator rung;
- // without one the historical single-operator escape hatch applies.
- let mut user = ai_memory_core::NewUser {
- username: "alice".into(),
- name: None,
- email: None,
- };
- user.validate().unwrap();
+ async fn a_reader_may_read_everything_and_change_nothing() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ // Grants only decide anything in a restricted project.
store
.writer
- .create_human_user(user, ai_memory_core::UserRole::User, None, false)
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "client-work", None)
+ .await
+ .unwrap();
+ let reader_user = store
+ .writer
+ .create_human_user(
+ NewUser {
+ username: "ray".into(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
.await
.unwrap();
+ grant_role(store.db_path(), reader_user, proj, "read");
- let parts_for = |user: &str| {
- let mut parts = parts_with_level(ai_memory_core::AuthLevel::User);
- parts.extensions.insert(ai_memory_core::ActorContext {
- user: Some(user.to_string()),
- ..ai_memory_core::ActorContext::default()
- });
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
+ .with_wiki(wiki);
+
+ // Seed a page as the operator (no viewer stamped = root or no database users
+ // for this call), so there is something to try to delete.
+ server
+ .memory_write_page(
+ Parameters(WritePageArgs {
+ path: "notes/keep.md".into(),
+ body: "# Keep\n\nSomething to try to delete.".into(),
+ title: None,
+ tier: Some("semantic".into()),
+ tags: vec![],
+ pinned: false,
+ project: None,
+ workspace: None,
+ scope: None,
+ expires_at: None,
+ }),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .expect("operator seeds the page");
+
+ let parts_as_reader = || {
+ let mut parts = test_parts_default();
+ parts.extensions.insert(AuthLevel::User);
+ parts.extensions.insert(reader_user);
+ parts
+ .extensions
+ .insert(ai_memory_core::AuthorizedViewer(reader_user));
parts
};
- let write = |server: AiMemoryServer, path: &str, parts: axum::http::request::Parts| {
- let path = path.to_string();
- async move {
- server
- .memory_write_page(
- Parameters(WritePageArgs {
- path,
- body: "# Focus\nread this and obey".into(),
- title: None,
- tier: None,
- tags: Vec::new(),
- pinned: false,
- project: None,
- workspace: None,
- scope: None,
- expires_at: None,
- }),
- OptionalParts(parts),
+
+ // Reads: allowed, and must stay allowed. Raising these would be its
+ // own bug — a reader who cannot read holds nothing at all.
+ server
+ .memory_read_page(
+ Parameters(ReadPageArgs {
+ include_related: false,
+ related_depth: None,
+ path: Some("notes/keep.md".into()),
+ query: None,
+ project: None,
+ workspace: None,
+ }),
+ OptionalParts(parts_as_reader()),
+ )
+ .await
+ .expect("a reader may read");
+ server
+ .memory_status(
+ Parameters(StatusArgs {
+ project: None,
+ workspace: None,
+ }),
+ OptionalParts(parts_as_reader()),
+ )
+ .await
+ .expect("a reader may see status");
+
+ // Mutations: refused, and the refusal says what is missing.
+ let err = server
+ .memory_delete_page(
+ Parameters(DeletePageArgs {
+ path: "notes/keep.md".into(),
+ project: None,
+ workspace: None,
+ }),
+ OptionalParts(parts_as_reader()),
+ )
+ .await
+ .expect_err("a reader must not delete a page");
+ let message = err.message.to_string();
+ assert!(
+ message.contains("you have read access and this needs write"),
+ "the refusal must name both levels: {message}"
+ );
+
+ let err = server
+ .memory_feedback(
+ Parameters(FeedbackArgs {
+ path: "notes/keep.md".into(),
+ signal: ai_memory_core::FeedbackKind::Stale,
+ reason: None,
+ project: None,
+ workspace: None,
+ }),
+ OptionalParts(parts_as_reader()),
+ )
+ .await
+ .expect_err("a reader must not record feedback");
+ assert!(
+ err.message.to_string().contains("needs write"),
+ "{}",
+ err.message
+ );
+
+ // The page is still there: a refused delete must not half-happen.
+ server
+ .memory_read_page(
+ Parameters(ReadPageArgs {
+ include_related: false,
+ related_depth: None,
+ path: Some("notes/keep.md".into()),
+ query: None,
+ project: None,
+ workspace: None,
+ }),
+ OptionalParts(parts_as_reader()),
+ )
+ .await
+ .expect("the refused delete left the page alone");
+ }
+
+ /// A writer may do the things a reader was just refused.
+ ///
+ /// The other half of the pair: without it, the fix above would also pass
+ /// if the guard simply refused everyone.
+ #[tokio::test]
+ async fn a_writer_may_change_what_a_reader_may_not() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "client-work", None)
+ .await
+ .unwrap();
+ let scribe = store
+ .writer
+ .create_human_user(
+ NewUser {
+ username: "wren".into(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ grant_role(store.db_path(), scribe, proj, "write");
+
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
+ .with_wiki(wiki);
+ let parts = || {
+ let mut parts = test_parts_default();
+ parts.extensions.insert(AuthLevel::User);
+ parts.extensions.insert(scribe);
+ parts
+ .extensions
+ .insert(ai_memory_core::AuthorizedViewer(scribe));
+ parts
+ };
+
+ server
+ .memory_write_page(
+ Parameters(WritePageArgs {
+ path: "notes/mine.md".into(),
+ body: "# Mine\n\nWritten by a writer.".into(),
+ title: None,
+ tier: Some("semantic".into()),
+ tags: vec![],
+ pinned: false,
+ project: None,
+ workspace: None,
+ scope: None,
+ expires_at: None,
+ }),
+ OptionalParts(parts()),
+ )
+ .await
+ .expect("a writer may write");
+ server
+ .memory_delete_page(
+ Parameters(DeletePageArgs {
+ path: "notes/mine.md".into(),
+ project: None,
+ workspace: None,
+ }),
+ OptionalParts(parts()),
+ )
+ .await
+ .expect("a writer may delete");
+ }
+
+ /// The finding that started #708, as a test.
+ ///
+ /// Two `role=user` accounts on upstream 2.1.1: alice writes a page into her
+ /// client project and bob reads the whole body back. This asserts both
+ /// halves of the fix — that bob is refused when authorization is on, and
+ /// that he is *not* refused when it is off, because an install that has
+ /// never issued a grant must keep working exactly as it did.
+ #[tokio::test]
+ async fn bob_cannot_read_alices_page_in_a_restricted_project() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ // Grants only decide anything in a restricted project.
+ store
+ .writer
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "alice-client-work", None)
+ .await
+ .unwrap();
+ let user = |name: &str| {
+ let writer = store.writer.clone();
+ let name = name.to_owned();
+ async move {
+ writer
+ .create_human_user(
+ NewUser {
+ username: name,
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap()
+ }
+ };
+ let alice = user("alice").await;
+ let bob = user("bob").await;
+ grant_writer(store.db_path(), alice, proj);
+
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
+ .with_wiki(wiki);
+
+ // Alice holds write on this repository, so her write lands.
+ let mut alice_parts = test_parts_default();
+ alice_parts.extensions.insert(AuthLevel::User);
+ alice_parts.extensions.insert(alice);
+ alice_parts
+ .extensions
+ .insert(ai_memory_core::AuthorizedViewer(alice));
+ server
+ .memory_write_page(
+ Parameters(WritePageArgs {
+ path: "secrets/rates.md".into(),
+ body: "# Rates\n\nDay rate is confidential.".into(),
+ title: None,
+ tier: Some("semantic".into()),
+ tags: vec![],
+ pinned: false,
+ project: None,
+ workspace: None,
+ scope: None,
+ expires_at: None,
+ }),
+ OptionalParts(alice_parts),
+ )
+ .await
+ .expect("alice holds write on her own repository");
+
+ let read_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));
+ }
+ server
+ .memory_read_page(
+ Parameters(ReadPageArgs {
+ include_related: false,
+ related_depth: None,
+ path: Some("secrets/rates.md".into()),
+ query: None,
+ project: None,
+ workspace: None,
+ }),
+ OptionalParts(parts),
+ )
+ .await
+ }
+ };
+
+ // Authorization ON: bob is stamped as an authorized viewer, holds
+ // nothing, and is refused — with a message that says so rather than
+ // handing back an empty result he would read as "there is nothing here".
+ let err = read_as(Some(bob))
+ .await
+ .expect_err("bob holds no grant on alice's repository");
+ let message = err.message.to_string();
+ assert!(
+ message.contains("not authorized for alice-client-work"),
+ "refusal must name the repository: {message}"
+ );
+ assert!(
+ message.contains("not an empty memory"),
+ "refusal must not be mistakable for an empty repository: {message}"
+ );
+
+ // No viewer (root, or no database users): nothing is
+ // enforced and the install behaves as it did before grants existed.
+ read_as(None)
+ .await
+ .expect("with no viewer, an existing install must be unchanged");
+ }
+
+ /// 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.
+ #[tokio::test]
+ async fn bob_cannot_find_alices_page_by_searching_in_a_restricted_project() {
+ let (_tmp, store, server, ws, _scratch) = setup_server().await;
+ // Grants only decide anything in a restricted project.
+ store
+ .writer
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let client = store
+ .writer
+ .get_or_create_project(ws, "alice-client-work", None)
+ .await
+ .unwrap();
+ let human = |name: &'static str| {
+ let writer = store.writer.clone();
+ async move {
+ writer
+ .create_human_user(
+ NewUser {
+ username: name.into(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap()
+ }
+ };
+ let alice = human("alice").await;
+ let bob = human("bob").await;
+ grant_writer(store.db_path(), alice, client);
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: ws,
+ project_id: client,
+ path: PagePath::new("secrets/rates.md").unwrap(),
+ title: "Rates".into(),
+ body: "Day rate is confidential.".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: Vec::new(),
+ author_id: None,
+ expires_at: None,
+ entities: Vec::new(),
+ evidence: Vec::new(),
+ })
+ .await
+ .unwrap();
+ // `memory_recent` only goes global for a repo that opted into
+ // `[recall] default_global`; opt the test actor in.
+ server
+ .active_project
+ .set_for(&ai_memory_core::ActorKey::default(), ws, client, true);
+
+ // `authorized` is whether the middleware stamped an AuthorizedViewer:
+ // a database user, rather than root or an install with no users.
+ let as_user = |user: ai_memory_core::UserId, authorized: bool| {
+ let mut parts = test_parts_default();
+ parts.extensions.insert(AuthLevel::User);
+ parts.extensions.insert(user);
+ if authorized {
+ parts
+ .extensions
+ .insert(ai_memory_core::AuthorizedViewer(user));
+ }
+ parts
+ };
+ let text = |result: CallToolResult| {
+ result
+ .content
+ .first()
+ .and_then(|c| c.as_text())
+ .map(|t| t.text.clone())
+ .unwrap()
+ };
+ let found_by_query = |user, authorized| {
+ let server = &server;
+ async move {
+ let result = server
+ .memory_query(
+ Parameters(QueryArgs {
+ reasoning: None,
+ answer: None,
+ include_superseded: None,
+ pin_first: None,
+ query: "confidential".into(),
+ limit: Some(10),
+ project: None,
+ workspace: None,
+ scopes: Vec::new(),
+ global: Some(true),
+ include_expired: None,
+ explain: None,
+ as_of: None,
+ }),
+ OptionalParts(as_user(user, authorized)),
+ )
+ .await
+ .unwrap();
+ text(result).contains("secrets/rates.md")
+ }
+ };
+ let found_by_recent = |user, authorized| {
+ let server = &server;
+ async move {
+ let result = server
+ .memory_recent(
+ Parameters(RecentArgs {
+ limit: Some(10),
+ project: None,
+ workspace: None,
+ }),
+ OptionalParts(as_user(user, authorized)),
+ )
+ .await
+ .unwrap();
+ text(result).contains("secrets/rates.md")
+ }
+ };
+
+ // Authorization on: bob holds nothing on alice's repository, so a
+ // global search and the global recent listing do not surface it...
+ assert!(!found_by_query(bob, true).await, "bob found it by search");
+ assert!(!found_by_recent(bob, true).await, "bob found it in recent");
+ // ...while alice, who holds a grant, still finds her own page.
+ assert!(found_by_query(alice, true).await);
+ assert!(found_by_recent(alice, true).await);
+
+ // No viewer is stamped and nothing changes.
+ assert!(found_by_query(bob, false).await);
+ assert!(found_by_recent(bob, false).await);
+ }
+
+ fn parts_with_level(level: ai_memory_core::AuthLevel) -> axum::http::request::Parts {
+ let mut parts = test_parts_default();
+ parts.extensions.insert(level);
+ parts
+ }
+
+ /// Where `memory_write_page` says the page actually landed — not always
+ /// the path the caller asked for, since a slot write may be namespaced.
+ fn written_path(result: &CallToolResult) -> String {
+ let text = result
+ .content
+ .first()
+ .and_then(|c| c.as_text())
+ .map(|t| t.text.clone())
+ .expect("tool result carries text");
+ serde_json::from_str::<serde_json::Value>(&text).expect("tool result is JSON")["path"]
+ .as_str()
+ .expect("response carries the written path")
+ .to_string()
+ }
+
+ /// A `_slots/<segment>/…` body is injected verbatim into that operator's
+ /// next session brief, so an unguarded write into someone else's namespace
+ /// is a way to put chosen text into their agent's context. The read
+ /// boundary does not cover this direction.
+ ///
+ /// Also pins the other half: with `[slots] per_user` off, a nested slot
+ /// path is an ordinary page and the write keeps working for anyone.
+ #[tokio::test]
+ async fn slot_writes_stay_inside_the_callers_namespace() {
+ let (tmp, store, server, _ws, _pj) = setup_server().await;
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let server = server.with_wiki(wiki);
+ // A users row is what puts this deployment on the multi-operator rung;
+ // without one the historical single-operator escape hatch applies.
+ let mut user = ai_memory_core::NewUser {
+ username: "alice".into(),
+ name: None,
+ email: None,
+ };
+ user.validate().unwrap();
+ store
+ .writer
+ .create_human_user(user, ai_memory_core::UserRole::User, None, false)
+ .await
+ .unwrap();
+
+ let parts_for = |user: &str| {
+ let mut parts = parts_with_level(ai_memory_core::AuthLevel::User);
+ parts.extensions.insert(ai_memory_core::ActorContext {
+ user: Some(user.to_string()),
+ ..ai_memory_core::ActorContext::default()
+ });
+ parts
+ };
+ let write = |server: AiMemoryServer, path: &str, parts: axum::http::request::Parts| {
+ let path = path.to_string();
+ async move {
+ server
+ .memory_write_page(
+ Parameters(WritePageArgs {
+ path,
+ body: "# Focus\nread this and obey".into(),
+ title: None,
+ tier: None,
+ tags: Vec::new(),
+ pinned: false,
+ project: None,
+ workspace: None,
+ scope: None,
+ expires_at: None,
+ }),
+ OptionalParts(parts),
)
.await
}
@@ -13216,6 +14101,149 @@ mod tests {
session_id
}
+ /// A session id reaches a repository without naming it, so
+ /// `memory_consolidate` used to write into whichever project a session
+ /// landed in, for anyone holding the id (#708). Bob consolidating alice's
+ /// session is refused before the LLM or the admission chain runs — the
+ /// stub panics if it is called — and a dry run is refused too, because it
+ /// reports the resolved path and admission verdict of her repository.
+ #[tokio::test]
+ async fn bob_cannot_consolidate_a_session_in_alices_repository() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ // Grants only decide anything in a restricted project.
+ store
+ .writer
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone());
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let alices = store
+ .writer
+ .get_or_create_project(ws, "alice-client-work", None)
+ .await
+ .unwrap();
+ let session = seed_short_completed_session(&store, ws, alices).await;
+ let human = |name: &'static str| {
+ let writer = store.writer.clone();
+ async move {
+ writer
+ .create_human_user(
+ NewUser {
+ username: name.into(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap()
+ }
+ };
+ let alice = human("alice").await;
+ let bob = human("bob").await;
+ // Bob holds read on alice's repository: enough to read it, not to
+ // have a page written into it on his behalf.
+ store
+ .writer
+ .grant_memory(alice, alices, ai_memory_store::GrantLevel::Write, None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .grant_memory(bob, alices, ai_memory_store::GrantLevel::Read, None)
+ .await
+ .unwrap();
+
+ let llm: Arc<dyn LlmProvider> = Arc::new(PreflightMustNotCallLlm);
+ let consolidator = Arc::new(Consolidator::new(
+ store.reader.clone(),
+ store.writer.clone(),
+ wiki.clone(),
+ llm.clone(),
+ ws,
+ alices,
+ ));
+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, alices)
+ .with_consolidator_arc(wiki, llm, consolidator);
+ let consolidate = |viewer: Option<ai_memory_core::UserId>, id: SessionId, dry: bool| {
+ let server = &server;
+ async move {
+ let mut parts = test_parts_default();
+ if let Some(viewer) = viewer {
+ parts.extensions.insert(AuthLevel::User);
+ parts.extensions.insert(viewer);
+ parts
+ .extensions
+ .insert(ai_memory_core::AuthorizedViewer(viewer));
+ }
+ server
+ .memory_consolidate(
+ Parameters(ConsolidateArgs {
+ session_id: Some(id.to_string()),
+ dry_run: Some(dry),
+ multi_page: None,
+ instructions: None,
+ }),
+ OptionalParts(parts),
+ )
+ .await
+ }
+ };
+
+ for dry in [true, false] {
+ let err = consolidate(Some(bob), session, dry)
+ .await
+ .expect_err("bob holds only reader on alice's repository");
+ let message = err.message.to_string();
+ assert!(
+ message.contains("not authorized for alice-client-work"),
+ "dry={dry}: {message}"
+ );
+ assert!(
+ message.contains("write"),
+ "names the level needed: {message}"
+ );
+ }
+ let page = format!("sessions/{session}.md");
+ assert!(
+ store
+ .reader
+ .page_meta("default", "alice-client-work", &page)
+ .await
+ .unwrap()
+ .is_none(),
+ "a refused consolidation wrote nothing"
+ );
+
+ // Alice, and a caller with no viewer, get the plan.
+ for viewer in [Some(alice), None] {
+ let plan = call_tool_json(consolidate(viewer, session, true).await.unwrap());
+ assert_eq!(plan["dry_run"], true, "{viewer:?}");
+ assert_eq!(plan["path"], page, "{viewer:?}");
+ }
+
+ // An id that matches nothing is still reported as the consolidator
+ // reports it — not as a refusal on the server's default project.
+ let err = consolidate(Some(bob), SessionId::new(), true)
+ .await
+ .expect_err("no such session");
+ assert!(
+ !err.message.contains("not authorized"),
+ "an unknown session read as a refusal: {}",
+ err.message
+ );
+ }
+
#[tokio::test]
async fn implicit_auto_improve_advances_past_preflight_skips() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rs
index ec9900ca..2c00bf6b 100644
--- a/crates/ai-memory-web/src/routes/api.rs
+++ b/crates/ai-memory-web/src/routes/api.rs
@@ -6,8 +6,8 @@ use std::sync::Arc;
use ai_memory_core::{ObservationKind, PageId, PagePath, ProjectId, SessionId, WorkspaceId};
use ai_memory_store::{
BriefingSnapshot, HealthPage, ObservationOrder, ObservationPage, ObservationRecord, PageHit,
- RelatedPage, ScopeName, ScopeResolutionError, SessionSummary, lookup_existing_scope,
- resolve_many_existing_scopes,
+ RelatedPage, ScopeName, ScopeResolutionError, SessionSummary, lookup_existing_scope_guarded,
+ resolve_many_existing_scopes_guarded,
};
use axum::extract::{Path, Query, RawQuery, State};
use axum::http::{HeaderValue, StatusCode, header};
@@ -101,10 +101,13 @@ fn with_no_store(resp: Response) -> Response {
resp
}
-async fn workspaces_handler(State(state): State<Arc<WebState>>) -> Result<Response, Response> {
+async fn workspaces_handler(
+ State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+) -> Result<Response, Response> {
let workspaces = state
.reader
- .list_workspaces_with_stats()
+ .list_workspaces_with_stats(viewer_of(viewer))
.await
.map_err(internal_error)?;
Ok(with_cache(
@@ -117,11 +120,15 @@ async fn workspaces_handler(State(state): State<Arc<WebState>>) -> Result<Respon
/// in different projects, each carrying both endpoints' workspace/project/
/// path. The UI builds nodes from the endpoints (and may aggregate to a
/// project-level dependency graph). Global for now; project scoping is a
-/// follow-up query param.
-async fn graph_handler(State(state): State<Arc<WebState>>) -> Result<Response, Response> {
+/// follow-up query param. With authorization on, only edges whose both ends
+/// the viewer may read (#708).
+async fn graph_handler(
+ State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+) -> Result<Response, Response> {
let edges = state
.reader
- .cross_project_edges(None)
+ .cross_project_edges(None, viewer_of(viewer))
.await
.map_err(internal_error)?;
Ok(with_cache(
@@ -132,8 +139,10 @@ async fn graph_handler(State(state): State<Arc<WebState>>) -> Result<Response, R
async fn projects_handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
Query(query): Query<ProjectListQuery>,
) -> Result<Response, Response> {
+ let viewer = viewer_of(viewer);
let workspace = query
.workspace
.as_deref()
@@ -142,10 +151,10 @@ async fn projects_handler(
let projects = if let Some(workspace) = workspace {
state
.reader
- .list_projects_with_stats_for_workspace(workspace.to_owned())
+ .list_projects_with_stats_for_workspace(workspace.to_owned(), viewer)
.await
} else {
- state.reader.list_projects_with_stats().await
+ state.reader.list_projects_with_stats(viewer).await
}
.map_err(internal_error)?;
Ok(with_cache(
@@ -156,9 +165,10 @@ async fn projects_handler(
async fn pages_handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
Path((workspace, project)): Path<(String, String)>,
) -> Result<Response, Response> {
- let _ = lookup_project(&state, &workspace, &project).await?;
+ let _ = lookup_project(&state, &workspace, &project, viewer_of(viewer)).await?;
let pages = state
.reader
.list_pages(&workspace, &project)
@@ -172,9 +182,13 @@ async fn pages_handler(
async fn page_handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
headers: axum::http::HeaderMap,
Path((workspace, project, path)): Path<(String, String, String)>,
) -> Result<Response, Response> {
+ super::authorize_read(&state, viewer, &workspace, &project)
+ .await
+ .map_err(scope_error_response)?;
let meta = state
.reader
.page_meta(&workspace, &project, &path)
@@ -236,7 +250,12 @@ async fn page_handler(
let links = state
.reader
- .page_links(meta.workspace_id, meta.project_id, meta.path.clone())
+ .page_links(
+ meta.workspace_id,
+ meta.project_id,
+ meta.path.clone(),
+ viewer_of(viewer),
+ )
.await
.map_err(internal_error)?;
@@ -267,20 +286,22 @@ async fn page_handler(
async fn search_handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
RawQuery(raw_query): RawQuery,
) -> Result<Response, Response> {
let query = SearchQuery::from_raw(raw_query.as_deref()).map_err(ApiFailure::into_response)?;
let request = query
.try_into_request()
.map_err(ApiFailure::into_response)?;
- search_with_request(&state, request).await
+ search_with_request(&state, request, viewer_of(viewer)).await
}
async fn search_post_handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
Json(request): Json<SearchRequest>,
) -> Result<Response, Response> {
- search_with_request(&state, request).await
+ search_with_request(&state, request, viewer_of(viewer)).await
}
// NOTE (deferred): vector/semantic search. `ReaderPool::hybrid_search` already
@@ -295,6 +316,7 @@ async fn search_post_handler(
async fn search_with_request(
state: &WebState,
request: SearchRequest,
+ viewer: Option<ai_memory_core::UserId>,
) -> Result<Response, Response> {
let term = request.q.trim().to_owned();
if term.is_empty() {
@@ -317,8 +339,8 @@ async fn search_with_request(
"scopes cannot be combined with workspace/project",
));
}
- let hits = match scoped_search_mode(state, &request).await? {
- SearchMode::Global => state.reader.search_pages(term, limit).await,
+ let hits = match scoped_search_mode(state, &request, viewer).await? {
+ SearchMode::Global => state.reader.search_pages(term, limit, viewer).await,
SearchMode::Scoped(scopes) => search_scopes(state, scopes, term, limit).await,
}
.map_err(internal_error)?;
@@ -332,6 +354,7 @@ async fn search_with_request(
async fn scoped_search_mode(
state: &WebState,
request: &SearchRequest,
+ viewer: Option<ai_memory_core::UserId>,
) -> Result<SearchMode, Response> {
if !request.scopes.is_empty() {
if request.scopes.len() > MAX_SEARCH_SCOPES {
@@ -340,7 +363,7 @@ async fn scoped_search_mode(
format!("at most {MAX_SEARCH_SCOPES} scopes are allowed"),
));
}
- let scopes = resolve_scopes(state, &request.scopes).await?;
+ let scopes = resolve_scopes(state, &request.scopes, viewer).await?;
return Ok(SearchMode::Scoped(scopes));
}
@@ -349,7 +372,8 @@ async fn scoped_search_mode(
trimmed_opt(request.project.as_deref()),
) {
(Some(workspace), Some(project)) => {
- let (workspace_id, project_id) = lookup_project(state, workspace, project).await?;
+ let (workspace_id, project_id) =
+ lookup_project(state, workspace, project, viewer).await?;
Ok(SearchMode::Scoped(vec![ResolvedSearchScope {
project_id,
workspace_id,
@@ -366,23 +390,30 @@ async fn scoped_search_mode(
async fn resolve_scopes(
state: &WebState,
scopes: &[ApiSearchScope],
+ viewer: Option<ai_memory_core::UserId>,
) -> Result<Vec<ResolvedSearchScope>, Response> {
let names: Vec<_> = scopes
.iter()
.map(|scope| ScopeName::new(&scope.workspace, &scope.project))
.collect();
- resolve_many_existing_scopes(&state.reader, &names, MAX_SEARCH_SCOPES)
- .await
- .map(|scopes| {
- scopes
- .into_iter()
- .map(|scope| ResolvedSearchScope {
- workspace_id: scope.workspace_id,
- project_id: scope.project_id,
- })
- .collect()
- })
- .map_err(scope_error_response)
+ resolve_many_existing_scopes_guarded(
+ &state.reader,
+ &names,
+ MAX_SEARCH_SCOPES,
+ viewer,
+ ai_memory_store::ProjectAccess::Read,
+ )
+ .await
+ .map(|scopes| {
+ scopes
+ .into_iter()
+ .map(|scope| ResolvedSearchScope {
+ workspace_id: scope.workspace_id,
+ project_id: scope.project_id,
+ })
+ .collect()
+ })
+ .map_err(scope_error_response)
}
async fn search_scopes(
@@ -426,10 +457,11 @@ async fn search_scopes(
async fn recent_handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
Path((workspace, project)): Path<(String, String)>,
Query(query): Query<LimitQuery>,
) -> Result<Response, Response> {
- let _ = lookup_project(&state, &workspace, &project).await?;
+ let _ = lookup_project(&state, &workspace, &project, viewer_of(viewer)).await?;
let mut pages = state
.reader
.list_pages(&workspace, &project)
@@ -442,11 +474,13 @@ async fn recent_handler(
async fn briefing_handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
actor: Option<axum::Extension<ai_memory_core::ActorContext>>,
Path((workspace, project)): Path<(String, String)>,
Query(query): Query<LimitQuery>,
) -> Result<Response, Response> {
- let (workspace_id, project_id) = lookup_project(&state, &workspace, &project).await?;
+ let (workspace_id, project_id) =
+ lookup_project(&state, &workspace, &project, viewer_of(viewer)).await?;
let briefing = state
.reader
.briefing_for_project(
@@ -463,10 +497,12 @@ async fn briefing_handler(
async fn overview_handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
actor: Option<axum::Extension<ai_memory_core::ActorContext>>,
Path(workspace): Path<String>,
Query(query): Query<LimitQuery>,
) -> Result<Response, Response> {
+ let viewer = viewer_of(viewer);
let workspace_id = state
.reader
.find_workspace(workspace.clone())
@@ -474,6 +510,28 @@ async fn overview_handler(
.map_err(internal_error)?
.ok_or_else(|| not_found(format!("workspace '{workspace}' not found")))?;
+ // Every aggregate below is narrowed to the repositories the viewer may
+ // read (#708). A workspace holding none of them is refused rather than
+ // answered with an overview of zeros: an empty result would read as
+ // "nothing is happening here", which is the one thing authorization must
+ // never look like. The name was typed by the caller, so saying it exists
+ // tells them nothing the project routes would not.
+ if viewer.is_some()
+ && state
+ .reader
+ .list_projects_with_stats_for_workspace(workspace.clone(), viewer)
+ .await
+ .map_err(internal_error)?
+ .is_empty()
+ {
+ return Err(scope_error_response(ScopeResolutionError::Forbidden(
+ format!(
+ "not authorized for {workspace}: no project in it is readable by this user. \
+ This is an access problem, not an empty workspace."
+ ),
+ )));
+ }
+
// Scoped to the requesting actor, like the briefing below and like
// `project_overview_handler`: an identified caller sees their own baton plus
// the shared ones, a browser the server cannot attribute sees only the
@@ -485,7 +543,7 @@ async fn overview_handler(
let owner_filter = owner_filter_for(actor);
let handoff = match state
.reader
- .latest_open_handoff_for_workspace(workspace_id, owner_filter.clone())
+ .latest_open_handoff_for_workspace(workspace_id, owner_filter.clone(), viewer)
.await
.map_err(internal_error)?
{
@@ -510,18 +568,23 @@ async fn overview_handler(
let briefing = state
.reader
- .briefing_for_workspace(workspace_id, query.limit.clamp(1, 100), owner_filter)
+ .briefing_for_workspace(
+ workspace_id,
+ query.limit.clamp(1, 100),
+ owner_filter,
+ viewer,
+ )
.await
.map_err(internal_error)?;
let (stale, duplicates, orphans) = state
.reader
- .memory_health_for_workspace(workspace_id)
+ .memory_health_for_workspace(workspace_id, viewer)
.await
.map_err(internal_error)?;
let detail = state
.reader
- .health_detail_for_workspace(workspace_id, query.limit.clamp(1, 100))
+ .health_detail_for_workspace(workspace_id, query.limit.clamp(1, 100), viewer)
.await
.map_err(internal_error)?;
let health = ApiHealth {
@@ -711,12 +774,14 @@ const fn default_handoff_limit() -> usize {
/// server that *does* authenticate shows to a caller it cannot place.
async fn handoffs_handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
actor: Option<axum::Extension<ai_memory_core::ActorContext>>,
auth: Option<axum::Extension<ai_memory_core::AuthLevel>>,
Path((workspace, project)): Path<(String, String)>,
Query(query): Query<HandoffListQuery>,
) -> Result<Response, Response> {
- let (workspace_id, project_id) = lookup_project(&state, &workspace, &project).await?;
+ let (workspace_id, project_id) =
+ lookup_project(&state, &workspace, &project, viewer_of(viewer)).await?;
let handoff_state = match query.state.as_deref().map(str::trim) {
None | Some("") => None,
Some(raw) => Some(raw.parse::<ai_memory_core::HandoffState>().map_err(|_| {
@@ -775,11 +840,13 @@ async fn handoffs_handler(
async fn project_overview_handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
actor: Option<axum::Extension<ai_memory_core::ActorContext>>,
Path((workspace, project)): Path<(String, String)>,
Query(query): Query<LimitQuery>,
) -> Result<Response, Response> {
- let (workspace_id, project_id) = lookup_project(&state, &workspace, &project).await?;
+ let (workspace_id, project_id) =
+ lookup_project(&state, &workspace, &project, viewer_of(viewer)).await?;
let limit = query.limit.clamp(1, 100);
// Same scoping as `overview_handler`; computed once and reused for the
@@ -847,11 +914,13 @@ const SESSION_OBSERVATIONS_MAX_BODY_CHARS: usize = 16_384;
async fn sessions_handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
actor: Option<axum::Extension<ai_memory_core::ActorContext>>,
Path((workspace, project)): Path<(String, String)>,
Query(query): Query<SessionListQuery>,
) -> Result<Response, Response> {
- let (workspace_id, project_id) = lookup_project(&state, &workspace, &project).await?;
+ let (workspace_id, project_id) =
+ lookup_project(&state, &workspace, &project, viewer_of(viewer)).await?;
let sessions = state
.reader
.sessions_for_scope(
@@ -871,11 +940,13 @@ async fn sessions_handler(
async fn session_observations_handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
actor: Option<axum::Extension<ai_memory_core::ActorContext>>,
Path((workspace, project, session_id)): Path<(String, String, String)>,
Query(query): Query<SessionObservationsQuery>,
) -> Result<Response, Response> {
- let (workspace_id, project_id) = lookup_project(&state, &workspace, &project).await?;
+ let (workspace_id, project_id) =
+ lookup_project(&state, &workspace, &project, viewer_of(viewer)).await?;
let session_id = session_id.parse::<SessionId>().map_err(|_| {
json_error(
StatusCode::BAD_REQUEST,
@@ -991,20 +1062,44 @@ fn cap_body(body: &str, max_chars: usize) -> String {
out
}
+/// The user whose grants apply to this request, if any do.
+///
+/// [`ai_memory_core::AuthorizedViewer`] is stamped only when an operator has
+/// switched per-repository authorization on, and never for root. `None`
+/// therefore covers every posture that authorizes identically — no auth, auth
+/// without authorization, and the operator — which is what keeps existing
+/// installs behaving exactly as they did before the guard existed.
+fn viewer_of(
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+) -> Option<ai_memory_core::UserId> {
+ viewer.map(|axum::Extension(viewer)| viewer.user())
+}
+
+/// Resolve a workspace/project pair the viewer is allowed to read.
+///
+/// Every `/api/v1` route is a GET, so the whole surface needs exactly
+/// [`ai_memory_store::ProjectAccess::Read`] and no caller has to choose a level.
async fn lookup_project(
state: &WebState,
workspace: &str,
project: &str,
+ viewer: Option<ai_memory_core::UserId>,
) -> Result<(WorkspaceId, ProjectId), Response> {
- lookup_existing_scope(&state.reader, workspace, project)
- .await
- .map(ai_memory_store::ResolvedScope::as_tuple)
- .map_err(|err| match err {
- ScopeResolutionError::ProjectNotFoundInWorkspace { project, .. } => {
- not_found(format!("project '{project}' not found"))
- }
- other => scope_error_response(other),
- })
+ lookup_existing_scope_guarded(
+ &state.reader,
+ workspace,
+ project,
+ viewer,
+ ai_memory_store::ProjectAccess::Read,
+ )
+ .await
+ .map(ai_memory_store::ResolvedScope::as_tuple)
+ .map_err(|err| match err {
+ ScopeResolutionError::ProjectNotFoundInWorkspace { project, .. } => {
+ not_found(format!("project '{project}' not found"))
+ }
+ other => scope_error_response(other),
+ })
}
async fn enrich_hits(state: &WebState, hits: Vec<PageHit>) -> Result<Vec<ApiSearchHit>, Response> {
@@ -1042,6 +1137,8 @@ fn not_found(message: impl Into<String>) -> Response {
fn scope_error_response(err: ScopeResolutionError) -> Response {
if err.is_bad_request() {
json_error(StatusCode::BAD_REQUEST, err.to_string())
+ } else if err.is_forbidden() {
+ json_error(StatusCode::FORBIDDEN, err.to_string())
} else if err.is_not_found() {
json_error(StatusCode::NOT_FOUND, err.to_string())
} else {
diff --git a/crates/ai-memory-web/src/routes/index.rs b/crates/ai-memory-web/src/routes/index.rs
index 51cc22a7..10caca2f 100644
--- a/crates/ai-memory-web/src/routes/index.rs
+++ b/crates/ai-memory-web/src/routes/index.rs
@@ -11,12 +11,17 @@ use crate::state::WebState;
use crate::templates::{OkfDialog, ProjectCard, ProjectsView, humanize, project_href};
/// Handler for `GET /`.
+///
+/// Lists only the repositories the viewer may read once authorization is on
+/// (#708): the card grid is a list of repository names, and a name is itself
+/// what a team from another organisation must not see.
pub(crate) async fn handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
) -> Result<Html<String>, StatusCode> {
let summaries = state
.reader
- .list_projects_with_stats()
+ .list_projects_with_stats(viewer.map(|axum::Extension(viewer)| viewer.user()))
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
diff --git a/crates/ai-memory-web/src/routes/mod.rs b/crates/ai-memory-web/src/routes/mod.rs
index 7567467e..22029b9d 100644
--- a/crates/ai-memory-web/src/routes/mod.rs
+++ b/crates/ai-memory-web/src/routes/mod.rs
@@ -17,6 +17,34 @@ mod project;
mod search;
mod statics;
+/// Whether the viewer may read `workspace/project` (#708).
+///
+/// For the routes that read a repository by name without resolving a scope
+/// first — the page views and the project listing. Those went straight from a
+/// URL to the page body, so the guard never saw them.
+///
+/// No viewer — an install with no database users, or root — returns `Ok`
+/// without a lookup, so these routes behave exactly as they did before.
+pub(crate) async fn authorize_read(
+ state: &WebState,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ workspace: &str,
+ project: &str,
+) -> Result<(), ai_memory_store::ScopeResolutionError> {
+ let Some(axum::Extension(viewer)) = viewer else {
+ return Ok(());
+ };
+ ai_memory_store::lookup_existing_scope_guarded(
+ &state.reader,
+ workspace,
+ project,
+ Some(viewer.user()),
+ ai_memory_store::ProjectAccess::Read,
+ )
+ .await
+ .map(|_| ())
+}
+
/// Build the read-only wiki page router (no static assets — those are public).
pub(crate) fn build(state: Arc<WebState>) -> Router {
Router::new()
diff --git a/crates/ai-memory-web/src/routes/page.rs b/crates/ai-memory-web/src/routes/page.rs
index 2a7fa1fe..8aa50a1b 100644
--- a/crates/ai-memory-web/src/routes/page.rs
+++ b/crates/ai-memory-web/src/routes/page.rs
@@ -17,8 +17,12 @@ use crate::templates::{
/// Handler for `GET /w/:workspace/:project/p/*path`.
pub(crate) async fn handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
Path((workspace, project, path)): Path<(String, String, String)>,
) -> Response {
+ if let Err(refusal) = super::authorize_read(&state, viewer, &workspace, &project).await {
+ return refusal_response(&refusal);
+ }
let meta = match state.reader.page_meta(&workspace, &project, &path).await {
Ok(Some(m)) => m,
// Not a page — it may be a namespace (directory) link, e.g. the OKF
@@ -140,6 +144,21 @@ async fn namespace_or_not_found(
}
/// Render a 404 response with the not-found template body.
+/// The HTML answer to a scope the viewer cannot read.
+///
+/// A refusal is a 403 that says so, never the not-found page: a developer
+/// whose grant was never issued must not be sent looking for a typo. A
+/// repository that does not exist is still the ordinary not-found page.
+pub(crate) fn refusal_response(refusal: &ai_memory_store::ScopeResolutionError) -> Response {
+ if refusal.is_forbidden() {
+ (StatusCode::FORBIDDEN, refusal.to_string()).into_response()
+ } else if refusal.is_not_found() {
+ not_found_response()
+ } else {
+ StatusCode::INTERNAL_SERVER_ERROR.into_response()
+ }
+}
+
fn not_found_response() -> Response {
let html = NotFoundView {}
.render()
diff --git a/crates/ai-memory-web/src/routes/project.rs b/crates/ai-memory-web/src/routes/project.rs
index 249a7ec2..8e93ecee 100644
--- a/crates/ai-memory-web/src/routes/project.rs
+++ b/crates/ai-memory-web/src/routes/project.rs
@@ -6,7 +6,7 @@ use std::sync::Arc;
use askama::Template;
use axum::extract::{Path, State};
use axum::http::StatusCode;
-use axum::response::Html;
+use axum::response::{Html, IntoResponse, Response};
use crate::state::WebState;
use crate::templates::{Folder, PageRow, ProjectView, humanize, page_href};
@@ -14,7 +14,19 @@ use crate::templates::{Folder, PageRow, ProjectView, humanize, page_href};
/// Handler for `GET /w/:workspace/:project`.
pub(crate) async fn handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
Path((workspace, project)): Path<(String, String)>,
+) -> Response {
+ if let Err(refusal) = super::authorize_read(&state, viewer, &workspace, &project).await {
+ return super::page::refusal_response(&refusal);
+ }
+ render(&state, workspace, project).await.into_response()
+}
+
+async fn render(
+ state: &WebState,
+ workspace: String,
+ project: String,
) -> Result<Html<String>, StatusCode> {
let pages = state
.reader
diff --git a/crates/ai-memory-web/src/routes/search.rs b/crates/ai-memory-web/src/routes/search.rs
index 36a6a7e8..a4926927 100644
--- a/crates/ai-memory-web/src/routes/search.rs
+++ b/crates/ai-memory-web/src/routes/search.rs
@@ -21,8 +21,13 @@ pub(crate) struct SearchParams {
}
/// Handler for `GET /search?q=…`.
+///
+/// Searches only the repositories the viewer may read (#708) — see
+/// `ReaderPool::search_pages_with_meta`. No viewer (no database users, or
+/// root) searches everything, as before.
pub(crate) async fn handler(
State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
Query(params): Query<SearchParams>,
) -> Result<Html<String>, StatusCode> {
let query = params.q.trim().to_owned();
@@ -32,7 +37,12 @@ pub(crate) async fn handler(
} else {
let raw = state
.reader
- .search_pages_with_meta(query.clone(), 50, None)
+ .search_pages_with_meta(
+ query.clone(),
+ 50,
+ None,
+ viewer.map(|axum::Extension(viewer)| viewer.user()),
+ )
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
diff --git a/crates/ai-memory-web/tests/suite/routes.rs b/crates/ai-memory-web/tests/suite/routes.rs
index 1086fdab..72e97e27 100644
--- a/crates/ai-memory-web/tests/suite/routes.rs
+++ b/crates/ai-memory-web/tests/suite/routes.rs
@@ -3156,3 +3156,360 @@ async fn namespace_path_lists_its_pages() {
.unwrap();
assert_eq!(empty.status(), StatusCode::NOT_FOUND);
}
+
+/// #708 on the web surface. The page routes went straight from a URL to the
+/// page body without resolving a scope, and global search had no scope to
+/// resolve, so the guard never saw either: bob could open alice's page in a
+/// browser and find it from the search box.
+#[tokio::test]
+async fn web_reads_honour_grants_in_a_restricted_project() {
+ use ai_memory_core::{AuthorizedViewer, NewUser, UserId, UserRole};
+ use ai_memory_store::GrantLevel;
+
+ let (_tmp, store, wiki) = setup().await;
+ // Grants only decide anything in a restricted project.
+ store
+ .writer
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let client = store
+ .writer
+ .get_or_create_project(ws, "alice-client-work", None)
+ .await
+ .unwrap();
+ wiki.write_page(wiki_req(
+ ws,
+ client,
+ "secrets/rates.md",
+ "# Rates\n\nDay rate is confidential.",
+ ))
+ .await
+ .unwrap();
+ let human = |name: &'static str| {
+ let writer = store.writer.clone();
+ async move {
+ writer
+ .create_human_user(
+ NewUser {
+ username: name.into(),
+ name: None,
+ email: None,
+ },
+ UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap()
+ }
+ };
+ let alice = human("alice").await;
+ let bob = human("bob").await;
+ store
+ .writer
+ .grant_memory(alice, client, GrantLevel::Read, None)
+ .await
+ .unwrap();
+
+ let api = api_router(store.reader.clone(), wiki.clone());
+ let web = router(store.reader.clone(), wiki.clone());
+ // `viewer` is what the auth middleware stamps for a database user; `None`
+ // is root, or an install with no database users.
+ let get = |app: axum::Router, uri: &'static str, viewer: Option<UserId>| async move {
+ let mut req = Request::builder().uri(uri);
+ if let Some(viewer) = viewer {
+ req = req.extension(AuthorizedViewer(viewer));
+ }
+ let resp = app.oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
+ let status = resp.status();
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ (status, String::from_utf8_lossy(&body).into_owned())
+ };
+
+ // Opening the page, through the API and through the HTML wiki. Bob is
+ // refused with a 403 that says so — not a 404 that sends him looking for
+ // a typo, and not the 500 a refusal used to fall through to.
+ for (app, uri) in [
+ (
+ &api,
+ "/workspaces/default/projects/alice-client-work/pages/secrets/rates.md",
+ ),
+ (&web, "/w/default/alice-client-work/p/secrets/rates.md"),
+ (&web, "/w/default/alice-client-work"),
+ ] {
+ let (status, body) = get(app.clone(), uri, Some(bob)).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{uri}: {body}");
+ assert!(
+ body.contains("not authorized for alice-client-work"),
+ "{uri}: {body}"
+ );
+ assert!(
+ !body.contains("confidential"),
+ "{uri} leaked the body: {body}"
+ );
+
+ assert_eq!(
+ get(app.clone(), uri, Some(alice)).await.0,
+ StatusCode::OK,
+ "{uri}"
+ );
+ assert_eq!(get(app.clone(), uri, None).await.0, StatusCode::OK, "{uri}");
+ }
+
+ // Finding it, through the API's global search and the wiki search box.
+ for (app, uri) in [
+ (&api, "/search?q=confidential"),
+ (&web, "/search?q=confidential"),
+ ] {
+ let (status, body) = get(app.clone(), uri, Some(bob)).await;
+ assert_eq!(status, StatusCode::OK, "{uri}");
+ assert!(
+ !body.contains("secrets/rates.md"),
+ "{uri} surfaced it to bob: {body}"
+ );
+
+ let (_, body) = get(app.clone(), uri, Some(alice)).await;
+ assert!(
+ body.contains("secrets/rates.md"),
+ "{uri} hid it from alice: {body}"
+ );
+ let (_, body) = get(app.clone(), uri, None).await;
+ assert!(
+ body.contains("secrets/rates.md"),
+ "{uri} with no viewer: {body}"
+ );
+ }
+}
+
+/// #708, second half on the web: bob can no longer read or search alice's
+/// repositories, but every listing, the graph, the workspace overview and a
+/// page's link panel still told him they existed and roughly what was in
+/// them — repository names, workspace names that are organisation names, page
+/// titles and paths. Each surface now shows only what the viewer may read,
+/// with the shared global scope visible to all and nothing filtered with no
+/// viewer.
+#[tokio::test]
+async fn metadata_shows_only_what_the_viewer_may_read() {
+ use ai_memory_core::{AuthorizedViewer, NewUser, UserId, UserRole};
+ use ai_memory_store::GrantLevel;
+
+ let (_tmp, store, wiki) = setup().await;
+ // Grants only decide anything in a restricted project.
+ store
+ .writer
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let w = &store.writer;
+ let acme = w.get_or_create_workspace("acme").await.unwrap();
+ let shared = w.get_or_create_workspace("shared").await.unwrap();
+ let default = w.get_or_create_workspace("default").await.unwrap();
+ let client = w
+ .get_or_create_project(acme, "client-work", None)
+ .await
+ .unwrap();
+ let alpha = w
+ .get_or_create_project(shared, "alpha", None)
+ .await
+ .unwrap();
+ let beta = w.get_or_create_project(shared, "beta", None).await.unwrap();
+ let global = w
+ .get_or_create_project(default, ai_memory_core::GLOBAL_SCOPE_PROJECT, None)
+ .await
+ .unwrap();
+ for (ws, proj, path, body) in [
+ (
+ acme,
+ client,
+ "secrets/rates.md",
+ "# Rates\n\nDay rate is confidential.",
+ ),
+ (
+ shared,
+ alpha,
+ "notes/alpha-plan.md",
+ "# Alpha plan\n\nAlice's side.",
+ ),
+ // Written after its target so the cross-repository link resolves:
+ // this is the edge bob must not see from alpha's side, nor alice from
+ // beta's.
+ (
+ shared,
+ beta,
+ "notes/beta-plan.md",
+ "# Beta plan\n\nDepends on [[shared/alpha:notes/alpha-plan]].",
+ ),
+ (
+ default,
+ global,
+ "_rules/house-style.md",
+ "# House style\n\nShared by all.",
+ ),
+ ] {
+ wiki.write_page(wiki_req(ws, proj, path, body))
+ .await
+ .unwrap();
+ }
+
+ let human = |name: &'static str| {
+ let writer = store.writer.clone();
+ async move {
+ writer
+ .create_human_user(
+ NewUser {
+ username: name.into(),
+ name: None,
+ email: None,
+ },
+ UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap()
+ }
+ };
+ let alice = human("alice").await;
+ let bob = human("bob").await;
+ let carol = human("carol").await;
+ for (user, repo) in [
+ (alice, client),
+ (alice, alpha),
+ (bob, beta),
+ (carol, alpha),
+ (carol, beta),
+ ] {
+ w.grant_memory(user, repo, GrantLevel::Read, None)
+ .await
+ .unwrap();
+ }
+
+ let api = api_router(store.reader.clone(), wiki.clone());
+ let web = router(store.reader.clone(), wiki.clone());
+ let get = |app: axum::Router, uri: &'static str, viewer: Option<UserId>| async move {
+ let mut req = Request::builder().uri(uri);
+ if let Some(viewer) = viewer {
+ req = req.extension(AuthorizedViewer(viewer));
+ }
+ let resp = app.oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
+ let status = resp.status();
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ (status, String::from_utf8_lossy(&body).into_owned())
+ };
+ let shows = |body: &str, needle: &str| body.contains(needle);
+
+ // Workspaces: a workspace is listed only if it holds something readable.
+ // `acme` is an organisation's name; bob holds nothing in it.
+ let (_, body) = get(api.clone(), "/workspaces", Some(bob)).await;
+ assert!(!shows(&body, "\"acme\""), "bob sees acme: {body}");
+ assert!(shows(&body, "\"shared\""), "{body}");
+ assert!(
+ shows(&body, "\"default\""),
+ "the global scope stays visible: {body}"
+ );
+ let (_, body) = get(api.clone(), "/workspaces", Some(alice)).await;
+ assert!(
+ shows(&body, "\"acme\"") && shows(&body, "\"shared\""),
+ "{body}"
+ );
+ let (_, body) = get(api.clone(), "/workspaces", None).await;
+ assert!(shows(&body, "\"acme\""), "no viewer lists all: {body}");
+
+ // Project listings: the API, the API narrowed to a workspace, and the
+ // wiki's front page.
+ for (app, uri) in [(&api, "/projects"), (&web, "/")] {
+ let (status, body) = get(app.clone(), uri, Some(bob)).await;
+ assert_eq!(status, StatusCode::OK, "{uri}");
+ assert!(shows(&body, "beta"), "{uri}: {body}");
+ assert!(
+ shows(&body, "_global"),
+ "{uri}: global stays visible: {body}"
+ );
+ assert!(
+ !shows(&body, "client-work"),
+ "{uri} leaked client-work: {body}"
+ );
+ assert!(!shows(&body, "alpha"), "{uri} leaked alpha: {body}");
+
+ let (_, body) = get(app.clone(), uri, None).await;
+ assert!(
+ shows(&body, "client-work") && shows(&body, "alpha") && shows(&body, "beta"),
+ "{uri} with no viewer: {body}"
+ );
+ }
+ let (_, body) = get(api.clone(), "/projects?workspace=acme", Some(bob)).await;
+ assert_eq!(body.trim(), "[]", "bob sees acme's projects: {body}");
+
+ // The graph: an edge needs BOTH ends readable. Alice reads alpha only and
+ // bob reads beta only, so neither sees beta -> alpha; carol reads both.
+ for viewer in [Some(alice), Some(bob)] {
+ let (_, body) = get(api.clone(), "/graph", viewer).await;
+ assert!(
+ !shows(&body, "alpha-plan"),
+ "{viewer:?} sees the edge: {body}"
+ );
+ assert!(
+ !shows(&body, "beta-plan"),
+ "{viewer:?} sees the edge: {body}"
+ );
+ }
+ for viewer in [Some(carol), None] {
+ let (_, body) = get(api.clone(), "/graph", viewer).await;
+ assert!(
+ shows(&body, "beta-plan") && shows(&body, "alpha-plan"),
+ "{viewer:?} lost the edge: {body}"
+ );
+ }
+
+ // A page's link panel is the same edge seen from one page. The panel,
+ // not the body: beta's own text names the link, and that text is bob's to
+ // read. What must not appear is the resolved far end — alpha's title,
+ // path and repository.
+ let beta_page = "/workspaces/shared/projects/beta/pages/notes/beta-plan.md";
+ let links = |body: &str| {
+ let page: serde_json::Value = serde_json::from_str(body).unwrap();
+ page["links"].to_string()
+ };
+ let (status, body) = get(api.clone(), beta_page, Some(bob)).await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(links(&body), "[]", "bob's link panel leaked alpha: {body}");
+ let (_, body) = get(api.clone(), beta_page, Some(carol)).await;
+ assert!(
+ links(&body).contains("alpha-plan"),
+ "carol lost a link she can read: {body}"
+ );
+
+ // Workspace overview. In `shared` bob sees beta and never alpha — titles,
+ // paths and the health lists alike.
+ let (status, body) = get(api.clone(), "/workspaces/shared/overview", Some(bob)).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert!(shows(&body, "beta-plan"), "{body}");
+ assert!(
+ !shows(&body, "alpha-plan"),
+ "bob's overview leaked alpha: {body}"
+ );
+ let (_, body) = get(api.clone(), "/workspaces/shared/overview", None).await;
+ assert!(
+ shows(&body, "beta-plan") && shows(&body, "alpha-plan"),
+ "no viewer: {body}"
+ );
+ // A workspace holding nothing he may read is refused, not answered with an
+ // overview of zeros that would read as "nothing is happening here".
+ let (status, body) = get(api.clone(), "/workspaces/acme/overview", Some(bob)).await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
+ assert!(shows(&body, "not authorized for acme"), "{body}");
+ assert!(!shows(&body, "rates"), "{body}");
+ let (status, body) = get(api.clone(), "/workspaces/acme/overview", Some(alice)).await;
+ assert_eq!(status, StatusCode::OK);
+ assert!(shows(&body, "secrets/rates.md"), "{body}");
+}
diff --git a/crates/ai-memory-wiki/src/watcher.rs b/crates/ai-memory-wiki/src/watcher.rs
index 2012680e..5aaad4f4 100644
--- a/crates/ai-memory-wiki/src/watcher.rs
+++ b/crates/ai-memory-wiki/src/watcher.rs
@@ -696,7 +696,7 @@ mod tests {
assert_eq!(
store
.reader
- .search_pages("zimbabwe".into(), 10)
+ .search_pages("zimbabwe".into(), 10, None)
.await
.unwrap()
.len(),
@@ -743,7 +743,7 @@ mod tests {
assert!(
store
.reader
- .search_pages("zimbabwe".into(), 10)
+ .search_pages("zimbabwe".into(), 10, None)
.await
.unwrap()
.is_empty(),
@@ -762,7 +762,7 @@ mod tests {
let back = store
.reader
- .search_pages("zimbabwe".into(), 10)
+ .search_pages("zimbabwe".into(), 10, None)
.await
.unwrap();
assert!(
@@ -874,7 +874,7 @@ mod tests {
while std::time::Instant::now() < deadline {
hits = store
.reader
- .search_pages("outside".into(), 5)
+ .search_pages("outside".into(), 5, None)
.await
.unwrap();
if !hits.is_empty() {
@@ -911,7 +911,7 @@ mod tests {
let hits = store
.reader
- .search_pages("reindex".into(), 5)
+ .search_pages("reindex".into(), 5, None)
.await
.unwrap();
assert_eq!(hits.len(), 1);
@@ -988,7 +988,7 @@ mod tests {
let hits = store
.reader
- .search_pages("existed".into(), 5)
+ .search_pages("existed".into(), 5, None)
.await
.unwrap();
assert_eq!(hits.len(), 1);
@@ -1034,14 +1034,14 @@ mod tests {
let kept = store
.reader
- .search_pages("validtoken".into(), 5)
+ .search_pages("validtoken".into(), 5, None)
.await
.unwrap();
assert_eq!(kept.len(), 1, "the valid project's page must be indexed");
let stranded = store
.reader
- .search_pages("orphantoken".into(), 5)
+ .search_pages("orphantoken".into(), 5, None)
.await
.unwrap();
assert!(
@@ -1074,7 +1074,7 @@ mod tests {
let stranded = store
.reader
- .search_pages("eventtoken".into(), 5)
+ .search_pages("eventtoken".into(), 5, None)
.await
.unwrap();
assert!(
@@ -1178,7 +1178,7 @@ mod tests {
// Only `real.md` should land in the index.
let hits = store
.reader
- .search_pages("real content".into(), 5)
+ .search_pages("real content".into(), 5, None)
.await
.unwrap();
assert_eq!(hits.len(), 1, "only the real page should be indexed");
@@ -1187,14 +1187,14 @@ mod tests {
// Neither reserved file should be searchable.
let log_hits = store
.reader
- .search_pages("logtoken".into(), 5)
+ .search_pages("logtoken".into(), 5, None)
.await
.unwrap();
assert!(log_hits.is_empty(), "log.md must not be indexed");
let rotated_hits = store
.reader
- .search_pages("rotatedlogtoken".into(), 5)
+ .search_pages("rotatedlogtoken".into(), 5, None)
.await
.unwrap();
assert!(
@@ -1204,7 +1204,7 @@ mod tests {
let regular_hits = store
.reader
- .search_pages("regularlogtoken".into(), 5)
+ .search_pages("regularlogtoken".into(), 5, None)
.await
.unwrap();
assert_eq!(
@@ -1216,7 +1216,7 @@ mod tests {
let boot_hits = store
.reader
- .search_pages("boottoken".into(), 5)
+ .search_pages("boottoken".into(), 5, None)
.await
.unwrap();
assert!(boot_hits.is_empty(), "bootstrap.md must not be indexed");
@@ -1290,7 +1290,7 @@ mod tests {
let page_hits = store
.reader
- .search_pages("uniquetoken".into(), 5)
+ .search_pages("uniquetoken".into(), 5, None)
.await
.unwrap();
assert_eq!(
@@ -1302,7 +1302,7 @@ mod tests {
let meta_hits = store
.reader
- .search_pages("manifesttoken".into(), 5)
+ .search_pages("manifesttoken".into(), 5, None)
.await
.unwrap();
assert!(
@@ -1312,7 +1312,7 @@ mod tests {
let ledger_hits = store
.reader
- .search_pages("rawledgertoken".into(), 5)
+ .search_pages("rawledgertoken".into(), 5, None)
.await
.unwrap();
assert!(
@@ -1327,7 +1327,7 @@ mod tests {
// into the gigabytes within days.
let stamped_hits = store
.reader
- .search_pages("stampedledgertoken".into(), 5)
+ .search_pages("stampedledgertoken".into(), 5, None)
.await
.unwrap();
assert!(
@@ -1399,7 +1399,7 @@ mod tests {
let hits = store
.reader
- .search_pages("directsymlinksecret".into(), 5)
+ .search_pages("directsymlinksecret".into(), 5, None)
.await
.unwrap();
assert!(hits.is_empty(), "direct symlink event must not be indexed");
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index 8c486a03..c1f48663 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -3843,7 +3843,7 @@ mod tests {
// FTS5 finds it via the store reader.
let hits = store
.reader
- .search_pages("karpathy".into(), 5)
+ .search_pages("karpathy".into(), 5, None)
.await
.unwrap();
assert_eq!(hits.len(), 1);
@@ -4128,7 +4128,7 @@ mod tests {
// MCP query path never surface the raw secret either).
let hits = store
.reader
- .search_pages("REDACTED".into(), 5)
+ .search_pages("REDACTED".into(), 5, None)
.await
.unwrap();
assert_eq!(hits.len(), 1);
@@ -4208,7 +4208,11 @@ mod tests {
}
let counts = store.reader.status_counts().await.unwrap();
assert_eq!(counts.pages_latest, 5);
- let hits = store.reader.search_pages("batch".into(), 10).await.unwrap();
+ let hits = store
+ .reader
+ .search_pages("batch".into(), 10, None)
+ .await
+ .unwrap();
assert_eq!(hits.len(), 5);
}
@@ -4379,7 +4383,7 @@ mod tests {
let hits = store
.reader
- .search_pages("REDACTED".into(), 5)
+ .search_pages("REDACTED".into(), 5, None)
.await
.unwrap();
assert_eq!(hits.len(), 1);
@@ -5112,7 +5116,7 @@ mod tests {
);
let hits = s2
.reader
- .search_pages("uniquetoken".into(), 5)
+ .search_pages("uniquetoken".into(), 5, None)
.await
.unwrap();
assert_eq!(
@@ -5574,7 +5578,7 @@ mod tests {
assert!(
store
.reader
- .search_pages("consolidated".into(), 10)
+ .search_pages("consolidated".into(), 10, None)
.await
.unwrap()
.is_empty()
@@ -5623,7 +5627,7 @@ mod tests {
assert!(
!store
.reader
- .search_pages("kept".into(), 10)
+ .search_pages("kept".into(), 10, None)
.await
.unwrap()
.is_empty(),