Skip to content

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

Rust

fix(workstream): apply the run owner check to every run mutation route

AkitaOnRails7a13d44bf96e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e8780141..3a9674ac 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -182,9 +182,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
queued SessionEnd consolidation job completed. (#1038)
### Changed
-- Required managed-run finish imports and finished retries to pass an
- authenticated owner check and current project access checks, repeated in the
- writer transaction. Database users required current Write access; trusted
+- Required managed-run finish imports and finished retries, and the cancel,
+ heartbeat, native-session link and context-acceptance routes, to pass an
+ authenticated owner check and current project access checks (repeated in
+ finish's writer transaction), so another operator cannot release or rebind a
+ run. Database users required current Write access; trusted
proxy operators retained their existing project policy. Active API keys
remained valid after human login was disabled. Shared, unattributed runs and
late finishes of still-active runs retained their existing behavior. (#1075)
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index eefff6ec..572b57b1 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -13653,7 +13653,7 @@ mod tests {
state
.writer
.finish_workstream_run(
- ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_store::ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -14071,7 +14071,7 @@ mod tests {
state
.writer
.finish_workstream_run(
- ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_store::ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rs
index 2f40a3ff..db3c3201 100644
--- a/crates/ai-memory-hooks/src/workstream.rs
+++ b/crates/ai-memory-hooks/src/workstream.rs
@@ -156,6 +156,36 @@ async fn authorize_run(
.map_err(scope_refusal)
}
+/// Admit a mutation of `run_id` only for its owner with current Write access
+/// on the run's project — the rule finish applies, shared by every route that
+/// releases, renews or rebinds a run so none of them is a side door around it.
+/// The authority comes from authenticated middleware extensions only.
+async fn authorize_run_owner(
+ state: &WorkstreamState,
+ run_id: ManagedRunId,
+ level: Option<Extension<AuthLevel>>,
+ viewer: Option<Extension<ai_memory_core::AuthorizedViewer>>,
+ user_id: Option<Extension<ai_memory_core::UserId>>,
+ actor: Option<Extension<ai_memory_core::ActorContext>>,
+) -> Result<ai_memory_store::ManagedRunAuthority, Response> {
+ let authority = ai_memory_store::ManagedRunAuthority::from_auth(
+ level.map_or(AuthLevel::Anonymous, |Extension(level)| level),
+ viewer.map(|Extension(viewer)| viewer),
+ user_id.map(|Extension(user_id)| user_id),
+ &actor.map_or_else(
+ ai_memory_core::ActorContext::anonymous,
+ |Extension(actor)| actor,
+ ),
+ state.trusted_proxy_identity,
+ );
+ state
+ .reader
+ .authorize_managed_run(run_id, authority.clone())
+ .await
+ .map_err(store_error_response)?;
+ Ok(authority)
+}
+
/// A refusal as a response: 403 for an access problem, 500 otherwise.
fn scope_refusal(failure: ScopeResolutionError) -> Response {
if failure.is_forbidden() {
@@ -368,7 +398,9 @@ async fn run_status(
async fn heartbeat_run(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
- actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
+ viewer: Option<Extension<ai_memory_core::AuthorizedViewer>>,
+ actor: Option<Extension<ai_memory_core::ActorContext>>,
+ user_id: Option<Extension<ai_memory_core::UserId>>,
AxumPath(raw_run_id): AxumPath<String>,
) -> Response {
if let Err(response) = authorize(level, Capability::NormalWrite) {
@@ -378,13 +410,7 @@ 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
+ if let Err(response) = authorize_run_owner(&state, run_id, level, viewer, user_id, actor).await
{
return response;
}
@@ -398,7 +424,9 @@ async fn heartbeat_run(
async fn cancel_run(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
- actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
+ viewer: Option<Extension<ai_memory_core::AuthorizedViewer>>,
+ actor: Option<Extension<ai_memory_core::ActorContext>>,
+ user_id: Option<Extension<ai_memory_core::UserId>>,
AxumPath(raw_run_id): AxumPath<String>,
) -> Response {
if let Err(response) = authorize(level, Capability::NormalWrite) {
@@ -408,13 +436,7 @@ 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
+ if let Err(response) = authorize_run_owner(&state, run_id, level, viewer, user_id, actor).await
{
return response;
}
@@ -473,7 +495,9 @@ async fn run_context(
async fn accept_run_context(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
- actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
+ viewer: Option<Extension<ai_memory_core::AuthorizedViewer>>,
+ actor: Option<Extension<ai_memory_core::ActorContext>>,
+ user_id: Option<Extension<ai_memory_core::UserId>>,
AxumPath(raw_run_id): AxumPath<String>,
) -> Response {
if let Err(response) = authorize(level, Capability::NormalWrite) {
@@ -483,13 +507,7 @@ 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
+ if let Err(response) = authorize_run_owner(&state, run_id, level, viewer, user_id, actor).await
{
return response;
}
@@ -762,7 +780,9 @@ async fn search_events(
async fn link_run(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
- actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
+ viewer: Option<Extension<ai_memory_core::AuthorizedViewer>>,
+ actor: Option<Extension<ai_memory_core::ActorContext>>,
+ user_id: Option<Extension<ai_memory_core::UserId>>,
AxumPath(raw_run_id): AxumPath<String>,
Json(request): Json<LinkManagedRunRequest>,
) -> Response {
@@ -773,13 +793,7 @@ 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
+ if let Err(response) = authorize_run_owner(&state, run_id, level, viewer, user_id, actor).await
{
return response;
}
@@ -823,23 +837,10 @@ async fn finish_run(
Ok(id) => id,
Err(response) => return response.into_response(),
};
- let authority = ai_memory_store::WorkstreamFinishAuthority::from_auth(
- level.map_or(AuthLevel::Anonymous, |Extension(level)| level),
- viewer.map(|Extension(viewer)| viewer),
- user_id.map(|Extension(user_id)| user_id),
- &actor.map_or_else(
- ai_memory_core::ActorContext::anonymous,
- |Extension(actor)| actor,
- ),
- state.trusted_proxy_identity,
- );
- if let Err(failure) = state
- .reader
- .authorize_workstream_finish(run_id, authority.clone())
- .await
- {
- return store_error_response(failure);
- }
+ let authority = match authorize_run_owner(&state, run_id, level, viewer, user_id, actor).await {
+ Ok(authority) => authority,
+ Err(response) => return response,
+ };
#[cfg(test)]
if let Some(barrier) = &state.finish_barrier {
barrier.0.notify_one();
@@ -1618,7 +1619,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_store::ManagedRunAuthority::from_auth(
AuthLevel::Anonymous,
None,
None,
@@ -1721,7 +1722,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_store::ManagedRunAuthority::from_auth(
AuthLevel::Anonymous,
None,
None,
@@ -1809,7 +1810,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_store::ManagedRunAuthority::from_auth(
AuthLevel::Anonymous,
None,
None,
@@ -1946,6 +1947,154 @@ mod tests {
);
}
+ /// #1075: every route that renews, rebinds, accepts for or releases a run
+ /// applies finish's owner rule, so none is a side door around it. Another
+ /// operator — even one who may write the project, and root acting under a
+ /// different identity — is refused on all four, and the run stays intact;
+ /// the owner is admitted (legitimate control).
+ #[tokio::test]
+ async fn run_mutation_routes_refuse_another_operator() {
+ let temp = TempDir::new().unwrap();
+ let store = Store::open(temp.path()).unwrap();
+ let state = test_state(&store, temp.path());
+ for name in ["alice", "bob"] {
+ store
+ .writer
+ .create_human_user(
+ ai_memory_core::NewUser {
+ username: name.into(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ }
+ let actor = |name: &str| {
+ Some(Extension(ai_memory_core::ActorContext {
+ user: Some(name.into()),
+ ..ai_memory_core::ActorContext::default()
+ }))
+ };
+ let user = || Some(Extension(AuthLevel::User));
+ let prepared = prepare_run(
+ State(state.clone()),
+ None,
+ actor("alice"),
+ None,
+ Json(PrepareManagedRunRequest {
+ workspace: "default".into(),
+ project: "managed-owner-routes".into(),
+ cwd: "/repo".into(),
+ repo_fingerprint: "repo".into(),
+ worktree_fingerprint: "worktree".into(),
+ agent: AgentKind::Grok,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ workstream: None,
+ new_workstream: None,
+ force_unlock: false,
+ lease_owner: "alice:1".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 run = || AxumPath(prepared.run_id.to_string());
+ let link = || {
+ Json(LinkManagedRunRequest {
+ native_session_id: "native-link".into(),
+ })
+ };
+
+ for (who, level) in [("bob", user()), ("admin", Some(Extension(AuthLevel::Root)))] {
+ let statuses = [
+ heartbeat_run(State(state.clone()), level, None, actor(who), None, run())
+ .await
+ .status(),
+ link_run(
+ State(state.clone()),
+ level,
+ None,
+ actor(who),
+ None,
+ run(),
+ link(),
+ )
+ .await
+ .status(),
+ accept_run_context(State(state.clone()), level, None, actor(who), None, run())
+ .await
+ .status(),
+ cancel_run(State(state.clone()), level, None, actor(who), None, run())
+ .await
+ .status(),
+ ];
+ assert_eq!(statuses, [StatusCode::FORBIDDEN; 4], "{who}");
+ }
+ let status = store
+ .reader
+ .managed_run_status(prepared.run_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ status.state, "active",
+ "refused callers must not end the run"
+ );
+ assert!(!status.context_delivered);
+ assert_eq!(status.native_session_id, None);
+
+ let statuses = [
+ heartbeat_run(
+ State(state.clone()),
+ user(),
+ None,
+ actor("alice"),
+ None,
+ run(),
+ )
+ .await
+ .status(),
+ link_run(
+ State(state.clone()),
+ user(),
+ None,
+ actor("alice"),
+ None,
+ run(),
+ link(),
+ )
+ .await
+ .status(),
+ accept_run_context(
+ State(state.clone()),
+ user(),
+ None,
+ actor("alice"),
+ None,
+ run(),
+ )
+ .await
+ .status(),
+ cancel_run(
+ State(state.clone()),
+ user(),
+ None,
+ actor("alice"),
+ None,
+ run(),
+ )
+ .await
+ .status(),
+ ];
+ assert_eq!(statuses, [StatusCode::NO_CONTENT; 4]);
+ }
+
#[tokio::test]
async fn force_unlock_cannot_evict_another_operator() {
let temp = TempDir::new().unwrap();
@@ -2080,7 +2229,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_store::ManagedRunAuthority::from_auth(
AuthLevel::Anonymous,
None,
None,
@@ -2159,7 +2308,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_store::ManagedRunAuthority::from_auth(
AuthLevel::Anonymous,
None,
None,
@@ -2238,7 +2387,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_store::ManagedRunAuthority::from_auth(
AuthLevel::Anonymous,
None,
None,
@@ -2320,7 +2469,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_store::ManagedRunAuthority::from_auth(
AuthLevel::Anonymous,
None,
None,
@@ -2387,6 +2536,8 @@ mod tests {
State(state.clone()),
None,
None,
+ None,
+ None,
AxumPath(prepared.run_id.to_string()),
)
.await;
@@ -2425,6 +2576,8 @@ mod tests {
State(state.clone()),
None,
None,
+ None,
+ None,
AxumPath(prepared.run_id.to_string()),
)
.await;
@@ -2452,7 +2605,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_store::ManagedRunAuthority::from_auth(
AuthLevel::Anonymous,
None,
None,
@@ -2527,6 +2680,8 @@ mod tests {
State(state.clone()),
None,
None,
+ None,
+ None,
AxumPath(crush.run_id.to_string()),
)
.await;
@@ -2652,7 +2807,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_store::ManagedRunAuthority::from_auth(
AuthLevel::Anonymous,
None,
None,
@@ -2716,6 +2871,7 @@ mod tests {
.await
.unwrap();
let as_viewer = |user| Some(Extension(AuthorizedViewer(user)));
+ let as_user = || Some(Extension(AuthLevel::User));
let run = || AxumPath(prepared.run_id.to_string());
// Status is a read: bob (nothing) is refused, carol (reader) is not.
@@ -2737,24 +2893,45 @@ mod tests {
// 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(),
+ heartbeat_run(
+ State(state.clone()),
+ as_user(),
+ as_viewer(viewer),
+ None,
+ None,
+ run()
+ )
+ .await
+ .status(),
StatusCode::FORBIDDEN,
"heartbeat"
);
assert_eq!(
- cancel_run(State(state.clone()), None, as_viewer(viewer), run())
- .await
- .status(),
+ cancel_run(
+ State(state.clone()),
+ as_user(),
+ as_viewer(viewer),
+ None,
+ None,
+ run()
+ )
+ .await
+ .status(),
StatusCode::FORBIDDEN,
"cancel"
);
}
assert_eq!(
- heartbeat_run(State(state.clone()), None, as_viewer(alice), run())
- .await
- .status(),
+ heartbeat_run(
+ State(state.clone()),
+ as_user(),
+ as_viewer(alice),
+ None,
+ None,
+ run()
+ )
+ .await
+ .status(),
StatusCode::NO_CONTENT,
"alice's own run keeps working"
);
@@ -2883,7 +3060,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_store::ManagedRunAuthority::from_auth(
AuthLevel::User,
Some(ai_memory_core::AuthorizedViewer(alice)),
Some(alice),
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 4c5e2167..20543412 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -98,9 +98,9 @@ pub use users::{
};
pub use web_sessions::{LiveWebSession, WebSession, hash_session_secret};
pub use workstream::{
- FinishWorkstreamRun, FinishedWorkstreamRun, LinkOrAdoptManagedRunSession, ManagedRunContext,
- ManagedRunSessionLink, PrepareWorkstreamRun, PreparedWorkstreamRun, RenameWorkstream,
- RenamedWorkstream, StoredManagedRunStatus, StoredWorkstreamSummary, WorkstreamFinishAuthority,
+ FinishWorkstreamRun, FinishedWorkstreamRun, LinkOrAdoptManagedRunSession, ManagedRunAuthority,
+ ManagedRunContext, ManagedRunSessionLink, PrepareWorkstreamRun, PreparedWorkstreamRun,
+ RenameWorkstream, RenamedWorkstream, StoredManagedRunStatus, StoredWorkstreamSummary,
WorkstreamSelection, WorkstreamSelector,
};
pub use writer::{StartupContextAcceptance, WriterHandle};
@@ -5016,7 +5016,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5082,7 +5082,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5097,7 +5097,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5123,7 +5123,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5211,7 +5211,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5229,7 +5229,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5257,7 +5257,7 @@ mod tests {
let finished = store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5333,7 +5333,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5374,7 +5374,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5495,7 +5495,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5535,7 +5535,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5602,7 +5602,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5676,7 +5676,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5873,7 +5873,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5976,7 +5976,7 @@ mod tests {
let first = store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -5994,7 +5994,7 @@ mod tests {
let second = store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -6049,7 +6049,7 @@ mod tests {
let cancelled = store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -6068,7 +6068,7 @@ mod tests {
let unknown = store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -6104,7 +6104,7 @@ mod tests {
let wrong_agent = store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -6160,7 +6160,7 @@ mod tests {
let wrong_session = store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -6194,7 +6194,7 @@ mod tests {
let finished = store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -6264,7 +6264,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -6478,7 +6478,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -6589,7 +6589,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -6842,7 +6842,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -6874,7 +6874,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
@@ -6899,7 +6899,7 @@ mod tests {
store
.writer
.finish_workstream_run(
- WorkstreamFinishAuthority::from_auth(
+ ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
diff --git a/crates/ai-memory-store/src/project_authz.rs b/crates/ai-memory-store/src/project_authz.rs
index dacf3ab0..48097c43 100644
--- a/crates/ai-memory-store/src/project_authz.rs
+++ b/crates/ai-memory-store/src/project_authz.rs
@@ -516,6 +516,58 @@ mod tests {
}
}
+ /// The strict resolution managed-run mutations use is the canonical
+ /// decision, not a parallel one: the reserved global scope's write gate
+ /// holds there too, and only a resolution gap is treated differently (an
+ /// unknown project fails instead of degrading to open).
+ #[tokio::test]
+ async fn strict_resolution_shares_the_global_gate_and_fails_closed_on_a_gap() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = crate::Store::open(tmp.path()).unwrap();
+ let global = crate::create_global_scope(&store.writer).await.unwrap();
+ let user = store
+ .writer
+ .create_human_user(
+ ai_memory_core::NewUser {
+ username: "alice".into(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ let conn = Connection::open(store.db_path()).unwrap();
+ let principal = ProjectPrincipal::user(user);
+
+ let strict = resolve_project_authz_strict(
+ &conn,
+ global.workspace_id,
+ global.project_id,
+ &principal,
+ false,
+ )
+ .unwrap();
+ assert!(strict.reserved_global);
+ assert!(
+ strict.distinguishes_operators,
+ "a server with database users distinguishes operators"
+ );
+ assert!(strict.authorize(ProjectAccess::Write).is_err());
+ assert!(strict.authorize(ProjectAccess::Read).is_ok());
+
+ let unknown = ProjectId::new();
+ assert!(
+ resolve_project_authz_strict(&conn, global.workspace_id, unknown, &principal, true)
+ .is_err()
+ );
+ let lenient =
+ resolve_project_authz(&conn, global.workspace_id, unknown, &principal, true).unwrap();
+ assert_eq!(lenient.access_mode, AccessMode::Open);
+ }
+
/// GHSA-7qj3-7wqw-m5w6: writing the reserved global scope needs root or a
/// write grant in either mode; its creator and an open mode admit nothing
/// extra, reads stay open, and an install without operators is unchanged.
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index f193d29c..6b86c834 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1896,19 +1896,20 @@ impl ReaderPool {
.await
}
- /// Check finish ownership and current Write access in one read snapshot.
+ /// Check a managed run's owner and current Write access in one read
+ /// snapshot, before any mutation of the run.
///
/// # Errors
/// Refuses a foreign owner, insufficient access, absent run or invalid scope;
/// SQL failures propagate without degrading authorization to open.
- pub async fn authorize_workstream_finish(
+ pub async fn authorize_managed_run(
&self,
run_id: ManagedRunId,
- authority: crate::WorkstreamFinishAuthority,
+ authority: crate::ManagedRunAuthority,
) -> StoreResult<()> {
self.with_conn(move |conn| {
let tx = conn.unchecked_transaction()?;
- crate::workstream::authorize_finish(&tx, run_id, &authority)
+ crate::workstream::authorize_run_mutation(&tx, run_id, &authority)
})
.await
}
diff --git a/crates/ai-memory-store/src/workstream.rs b/crates/ai-memory-store/src/workstream.rs
index a2a920f0..61ef3c5f 100644
--- a/crates/ai-memory-store/src/workstream.rs
+++ b/crates/ai-memory-store/src/workstream.rs
@@ -30,25 +30,27 @@ pub enum WorkstreamSelection {
New(String),
}
-/// Authenticated authority shared by finish preflight and the writer transaction.
+/// Authenticated authority for a managed-run mutation: finish (its preflight
+/// and its import transaction), cancel, heartbeat, native-session link and
+/// context acceptance.
///
/// Construct only from middleware extensions, never transcript metadata. Owner
/// filters are derived here so this boundary cannot request `OwnerFilter::Any`.
#[derive(Debug, Clone)]
-pub struct WorkstreamFinishAuthority {
+pub struct ManagedRunAuthority {
principal: crate::ProjectPrincipal,
owner: ai_memory_core::OwnerFilter,
distinguishes_operators: bool,
- project_policy: FinishProjectPolicy,
+ project_policy: RunProjectPolicy,
}
#[derive(Debug, Clone, Copy)]
-enum FinishProjectPolicy {
+enum RunProjectPolicy {
Grants,
TrustedProxyLegacy,
}
-impl WorkstreamFinishAuthority {
+impl ManagedRunAuthority {
/// Reduce the actual HTTP auth extensions to one immutable finish authority.
/// A DB user's attribution id remains authoritative without a viewer marker.
#[must_use]
@@ -80,8 +82,8 @@ impl WorkstreamFinishAuthority {
// no DB principal. Preserve its viewer-less project policy only when
// this server actually enables trusted proxy authentication.
let project_policy = match (level, user, actor.identity_key(), trusted_proxy_identity) {
- (AuthLevel::User, None, Some(_), true) => FinishProjectPolicy::TrustedProxyLegacy,
- _ => FinishProjectPolicy::Grants,
+ (AuthLevel::User, None, Some(_), true) => RunProjectPolicy::TrustedProxyLegacy,
+ _ => RunProjectPolicy::Grants,
};
Self {
principal,
@@ -94,10 +96,10 @@ impl WorkstreamFinishAuthority {
/// Resolve only the real run scope and owner, without creating a scope or
/// changing the active-project pointer. Both callers supply a SQL snapshot.
-pub(crate) fn authorize_finish(
+pub(crate) fn authorize_run_mutation(
conn: &Connection,
run_id: ManagedRunId,
- authority: &WorkstreamFinishAuthority,
+ authority: &ManagedRunAuthority,
) -> StoreResult<()> {
let (owner, workspace, project) = conn
.query_row(
@@ -129,8 +131,8 @@ pub(crate) fn authorize_finish(
authority.distinguishes_operators,
)?;
match authority.project_policy {
- FinishProjectPolicy::TrustedProxyLegacy => Ok(()),
- FinishProjectPolicy::Grants => project_authz
+ RunProjectPolicy::TrustedProxyLegacy => Ok(()),
+ RunProjectPolicy::Grants => project_authz
.authorize(crate::ProjectAccess::Write)
.map_err(|failure| StoreError::Forbidden(failure.message())),
}
@@ -934,12 +936,12 @@ fn accept_context_in_transaction(
/// Index one immutable source segment and close the run atomically.
pub(crate) fn finish_run(
conn: &mut Connection,
- authority: &WorkstreamFinishAuthority,
+ authority: &ManagedRunAuthority,
input: &FinishWorkstreamRun,
) -> StoreResult<FinishedWorkstreamRun> {
let now = Timestamp::now().as_microsecond();
let tx = conn.transaction()?;
- authorize_finish(&tx, input.run_id, authority)?;
+ authorize_run_mutation(&tx, input.run_id, authority)?;
let run: Option<FinishRunRow> = tx
.query_row(
"SELECT workstream_id, agent_kind, native_session_id, state, \
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 0df03ad7..a3d3a29d 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -748,7 +748,7 @@ pub(crate) enum WriteCmd {
reply: oneshot::Sender<StoreResult<StartupContextAcceptance>>,
},
FinishWorkstreamRun {
- authority: crate::WorkstreamFinishAuthority,
+ authority: crate::ManagedRunAuthority,
input: FinishWorkstreamRun,
reply: oneshot::Sender<StoreResult<FinishedWorkstreamRun>>,
},
@@ -3123,7 +3123,7 @@ impl WriterHandle {
/// Index an immutable transcript segment and release the run lease.
pub async fn finish_workstream_run(
&self,
- authority: crate::WorkstreamFinishAuthority,
+ authority: crate::ManagedRunAuthority,
input: FinishWorkstreamRun,
) -> StoreResult<FinishedWorkstreamRun> {
let (tx, rx) = oneshot::channel();
diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rs
index cf67eece..cbe86659 100644
--- a/crates/ai-memory-store/tests/suite/multi_session.rs
+++ b/crates/ai-memory-store/tests/suite/multi_session.rs
@@ -1119,8 +1119,8 @@ fn finish_authority(
level: ai_memory_core::AuthLevel,
user: Option<ai_memory_core::UserId>,
name: Option<&str>,
-) -> ai_memory_store::WorkstreamFinishAuthority {
- ai_memory_store::WorkstreamFinishAuthority::from_auth(
+) -> ai_memory_store::ManagedRunAuthority {
+ ai_memory_store::ManagedRunAuthority::from_auth(
level,
user.map(ai_memory_core::AuthorizedViewer),
user,
@@ -1241,7 +1241,7 @@ impl FinishFixture {
}
}
- fn alice(&self) -> ai_memory_store::WorkstreamFinishAuthority {
+ fn alice(&self) -> ai_memory_store::ManagedRunAuthority {
finish_authority(
ai_memory_core::AuthLevel::User,
Some(self.alice),
@@ -1278,13 +1278,13 @@ impl FinishFixture {
async fn refused_unchanged(
&self,
run_id: ai_memory_core::ManagedRunId,
- authority: ai_memory_store::WorkstreamFinishAuthority,
+ authority: ai_memory_store::ManagedRunAuthority,
) {
let before = finish_snapshot(&self.store).await;
assert!(
self.store
.reader
- .authorize_workstream_finish(run_id, authority.clone())
+ .authorize_managed_run(run_id, authority.clone())
.await
.is_err(),
"preflight must refuse"
@@ -1315,7 +1315,7 @@ async fn owner_finish_store_refuses_another_writer_including_finished_retry() {
assert!(matches!(
f.store
.reader
- .authorize_workstream_finish(run.run_id, bob.clone())
+ .authorize_managed_run(run.run_id, bob.clone())
.await,
Err(StoreError::Forbidden(_))
));
@@ -1341,7 +1341,7 @@ async fn owner_finish_store_refuses_another_writer_including_finished_retry() {
.await;
f.store
.reader
- .authorize_workstream_finish(run.run_id, f.alice())
+ .authorize_managed_run(run.run_id, f.alice())
.await
.unwrap();
let result = f
@@ -1381,7 +1381,7 @@ async fn owner_finish_store_refuses_another_writer_including_finished_retry() {
let shared = f.run(name, None).await;
f.store
.reader
- .authorize_workstream_finish(shared.run_id, auth.clone())
+ .authorize_managed_run(shared.run_id, auth.clone())
.await
.unwrap();
assert_eq!(
@@ -1403,7 +1403,7 @@ async fn owner_finish_store_rechecks_write_after_preflight() {
let auth = f.alice();
f.store
.reader
- .authorize_workstream_finish(run.run_id, auth.clone())
+ .authorize_managed_run(run.run_id, auth.clone())
.await
.unwrap();
f.store
@@ -1436,7 +1436,7 @@ async fn owner_finish_store_rechecks_write_after_preflight() {
.unwrap();
f.store
.reader
- .authorize_workstream_finish(run.run_id, auth.clone())
+ .authorize_managed_run(run.run_id, auth.clone())
.await
.unwrap();
f.store
@@ -1446,11 +1446,11 @@ async fn owner_finish_store_rechecks_write_after_preflight() {
.unwrap();
f.store
.reader
- .authorize_workstream_finish(run.run_id, auth.clone())
+ .authorize_managed_run(run.run_id, auth.clone())
.await
.unwrap();
// Attribution UserId is real middleware data even if a viewer marker is absent.
- let fallback = ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ let fallback = ai_memory_store::ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::User,
None,
Some(f.alice),
@@ -1463,7 +1463,7 @@ async fn owner_finish_store_rechecks_write_after_preflight() {
assert!(
f.store
.reader
- .authorize_workstream_finish(run.run_id, fallback.clone())
+ .authorize_managed_run(run.run_id, fallback.clone())
.await
.is_ok(),
"the real DB-user attribution id must retain its Write grant without a viewer marker"
@@ -1491,7 +1491,7 @@ async fn owner_finish_store_refuses_a_deleted_user_after_preflight() {
.unwrap();
f.store
.reader
- .authorize_workstream_finish(run.run_id, auth.clone())
+ .authorize_managed_run(run.run_id, auth.clone())
.await
.unwrap();
let conn = rusqlite::Connection::open(f.store.db_path()).unwrap();
@@ -1509,7 +1509,7 @@ async fn owner_finish_store_refuses_a_deleted_user_after_preflight() {
matches!(
f.store
.reader
- .authorize_workstream_finish(run.run_id, auth.clone())
+ .authorize_managed_run(run.run_id, auth.clone())
.await,
Err(StoreError::Forbidden(_))
),
@@ -1568,7 +1568,7 @@ async fn owner_finish_store_proxy_policy_requires_server_and_authenticated_ident
"proxy compatibility requires trusted server configuration",
),
] {
- let auth = ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ let auth = ai_memory_store::ManagedRunAuthority::from_auth(
level, None, None, &identity, configured,
);
let before = finish_snapshot(&f.store).await;
@@ -1576,7 +1576,7 @@ async fn owner_finish_store_proxy_policy_requires_server_and_authenticated_ident
matches!(
f.store
.reader
- .authorize_workstream_finish(run.run_id, auth.clone())
+ .authorize_managed_run(run.run_id, auth.clone())
.await,
Err(StoreError::Forbidden(_))
),
@@ -1594,7 +1594,7 @@ async fn owner_finish_store_proxy_policy_requires_server_and_authenticated_ident
);
assert_eq!(finish_snapshot(&f.store).await, before);
}
- let proxy = ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ let proxy = ai_memory_store::ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::User,
None,
None,
@@ -1733,7 +1733,7 @@ async fn owner_finish_store_topology_reload_and_phase_controls() {
let anonymous = finish_authority(ai_memory_core::AuthLevel::Anonymous, None, None);
store
.reader
- .authorize_workstream_finish(run.run_id, anonymous.clone())
+ .authorize_managed_run(run.run_id, anonymous.clone())
.await
.unwrap();
store
@@ -1755,7 +1755,7 @@ async fn owner_finish_store_topology_reload_and_phase_controls() {
matches!(
store
.reader
- .authorize_workstream_finish(run.run_id, anonymous.clone())
+ .authorize_managed_run(run.run_id, anonymous.clone())
.await,
Err(StoreError::Forbidden(_))
),
@@ -1780,7 +1780,7 @@ async fn owner_finish_store_topology_reload_and_phase_controls() {
assert!(
store
.reader
- .authorize_workstream_finish(run.run_id, anonymous.clone())
+ .authorize_managed_run(run.run_id, anonymous.clone())
.await
.is_err(),
"unreadable topology must fail closed in preflight"
@@ -1803,7 +1803,7 @@ async fn owner_finish_store_topology_reload_and_phase_controls() {
.unwrap();
store
.reader
- .authorize_workstream_finish(run.run_id, root.clone())
+ .authorize_managed_run(run.run_id, root.clone())
.await
.unwrap();
assert_eq!(
@@ -1884,7 +1884,7 @@ async fn owner_finish_store_topology_reload_and_phase_controls() {
assert!(matches!(
store
.reader
- .authorize_workstream_finish(ai_memory_core::ManagedRunId::new(), root.clone())
+ .authorize_managed_run(ai_memory_core::ManagedRunId::new(), root.clone())
.await,
Err(StoreError::NotFound(_))
));
@@ -2000,7 +2000,7 @@ async fn owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_fa
.unwrap();
f.store
.reader
- .authorize_workstream_finish(run.run_id, f.alice())
+ .authorize_managed_run(run.run_id, f.alice())
.await
.unwrap();
assert_eq!(
@@ -2024,7 +2024,7 @@ async fn owner_finish_store_keeps_qualified_identity_namespaces() {
let run = f.run("subject-owned", Some(identity.storage_key())).await;
// A display username matching another identity's subject is a different owner.
f.refused_unchanged(run.run_id, f.alice()).await;
- let subject = ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ let subject = ai_memory_store::ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::User,
Some(ai_memory_core::AuthorizedViewer(f.alice)),
Some(f.alice),
@@ -2035,7 +2035,7 @@ async fn owner_finish_store_keeps_qualified_identity_namespaces() {
issuer: "https://other-idp.example".into(),
subject: "alice".into(),
};
- let foreign = ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ let foreign = ai_memory_store::ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::User,
Some(ai_memory_core::AuthorizedViewer(f.alice)),
Some(f.alice),
@@ -2045,7 +2045,7 @@ async fn owner_finish_store_keeps_qualified_identity_namespaces() {
f.refused_unchanged(run.run_id, foreign).await;
f.store
.reader
- .authorize_workstream_finish(run.run_id, subject.clone())
+ .authorize_managed_run(run.run_id, subject.clone())
.await
.unwrap();
assert_eq!(
diff --git a/crates/ai-memory-store/tests/suite/workstream_provenance.rs b/crates/ai-memory-store/tests/suite/workstream_provenance.rs
index 709dc19b..126553fb 100644
--- a/crates/ai-memory-store/tests/suite/workstream_provenance.rs
+++ b/crates/ai-memory-store/tests/suite/workstream_provenance.rs
@@ -548,8 +548,8 @@ async fn workstream_provenance_retry_with_marker_matching_pattern_is_idempotent(
/// A single-user (no database users) caller: the finish gate admits it, so
/// these provenance tests exercise only the storage boundary.
-fn local_authority() -> ai_memory_store::WorkstreamFinishAuthority {
- ai_memory_store::WorkstreamFinishAuthority::from_auth(
+fn local_authority() -> ai_memory_store::ManagedRunAuthority {
+ ai_memory_store::ManagedRunAuthority::from_auth(
ai_memory_core::AuthLevel::Anonymous,
None,
None,
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 94b320e3..d3787c69 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -71,7 +71,7 @@ boundary not yet built.
| 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `interactive_launch_waits_out_a_lapsing_lease_then_proceeds`, and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users |
| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor; batch outcomes do not bypass the capture grant or session owner check | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository` (foreign raw workstream id refuses populated provenance; granted reader receives the source record and tool correlation); `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |
| 14aa | Companion capture privacy before persistence and delivery | `companions/ai-memory-client/src/lib.rs` `reject_sensitive`, `sanitize_external_value`, `check_body`; `src/scrub.rs` `sanitize_external_text`; relay `identity::validate`, `check_scope`, `relay::init` and `flush_locked`; importer `plan_external_conversation`, `planned_hook_event`, `truncate_utf8`, `ImportClient::post_hook_batch` | SDK secret-position, nested key, numeric metric (11 names plus numeric `*_tokens` counts; string values still redact), bounded schema and literal-marker tests; relay `sensitive_envelope_is_rejected_before_enqueue_with_clean_control`, `new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry`, `unsafe_legacy_pending_is_dropped_locally_and_never_blocks_its_session`, `unsafe_legacy_native_identity_is_dropped_and_its_session_continues`, `legacy_binding_scope_spaces_are_preserved_on_delivery`; importer `sensitive_native_identity_is_refused_before_manifest_and_http_with_unicode_control`, `shared_key_sanitation_precedes_plan_manifest_transport_and_exact_retry`, `preview_and_manifest_use_scrubbed_bodies_and_digest`, `forged_body_authority_is_refused_before_transport`, `sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles`. Controls preserve opaque native Unicode IDs, metric representation and untrusted provenance. An unsafe item queued before these checks never reaches the wire (body or request line); it leaves the queue as a local `dropped_policy` receipt so the rest of its session ships. Guard-removal runtime probes target the final formatted sources and restore identical hashes. | Client-side privacy only; server scope, auth, admission and capture-policy guards remain authoritative |
-| 14ap | Managed-run finish owner and current project access | `hooks/src/workstream.rs` derives `WorkstreamFinishAuthority` only from authenticated middleware extensions and checks the real run before status/payload/segment handling; `ReaderPool::authorize_workstream_finish` and `store/src/workstream.rs` `authorize_finish` use a read snapshot and the existing writer transaction, respectively. Strict finish resolution requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within the writer transaction; a revocation after preflight can leave an unindexed raw segment. Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional |
+| 14ap | Managed-run mutation owner and current project access (finish, cancel, heartbeat, native-session link, context acceptance) | `hooks/src/workstream.rs` `authorize_run_owner` derives `ManagedRunAuthority` only from authenticated middleware extensions and checks the real run before any mutation — for finish before status/payload/segment handling; cancel, heartbeat, link and context acceptance go through the same helper, so none is a side door around finish's rule; `ReaderPool::authorize_managed_run` and `store/src/workstream.rs` `authorize_run_mutation` use a read snapshot and the existing writer transaction, respectively. Strict resolution (`project_authz.rs` `resolve_project_authz_strict`, the canonical decision with a fail-closed resolution mode, so the reserved global-scope write gate applies here too) requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`; hooks `workstream.rs` `run_mutation_routes_refuse_another_operator` (another operator and root under another identity refused on heartbeat/link/accept/cancel, run left active; owner admitted); store `project_authz.rs` `strict_resolution_shares_the_global_gate_and_fails_closed_on_a_gap`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within finish's writer transaction; a revocation after preflight can leave an unindexed raw segment. Cancel, heartbeat, link and acceptance check one read snapshot immediately before a single-row update (a run's owner never changes). The hook-ingress SessionStart link by `AI_MEMORY_RUN_ID` is a separate server-internal path not covered here. Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional |
| 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`; `router.rs` `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others |
| 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) |
| 14d | `include_related` shows and walks only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` applies, so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed; `ai-memory-mcp` `server.rs` `bob_does_not_see_restricted_pages_through_the_related_walk` (an ungranted user's `memory_read_page{include_related}` omits the restricted page; control: no viewer still reaches it) — fails with `memory_read_page` passing `None` instead of `viewer_from_parts` | STRONG |