Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge release/2.5 into feat/708-authz-slice2b
AkitaOnRails73772bf42c7c
diff --cc crates/ai-memory-store/migrations/V68__project_grants.sqlindex efb421e3,00000000..efb421e3mode 100644,000000..100644--- a/crates/ai-memory-store/migrations/V68__project_grants.sql+++ b/crates/ai-memory-store/migrations/V68__project_grants.sqldiff --cc crates/ai-memory-store/src/api_credentials.rsindex 37f6e010,37f6e010..1cc4780b--- a/crates/ai-memory-store/src/api_credentials.rs+++ b/crates/ai-memory-store/src/api_credentials.rs@@@ -411,7 -411,7 +411,7 @@@ mod tests|row| row.get(0),).unwrap();-- assert_eq!(version, 67, "update the pin when adding a migration");++ assert_eq!(version, 68, "update the pin when adding a migration");let cols: i64 = conn.query_row("SELECT COUNT(*) FROM pragma_table_info('users') WHERE name = 'token_hash'",diff --cc crates/ai-memory-store/src/project_authz.rsindex 2a09a2bf,00000000..16c6eee8mode 100644,000000..100644--- a/crates/ai-memory-store/src/project_authz.rs+++ b/crates/ai-memory-store/src/project_authz.rs@@@ -1,395 -1,0 +1,395 @@@+//! Per-project authorization choke point (#708).+//!+//! On a multi-user server, attribution ([`ai_memory_core::ActorContext`]) records+//! *who* made a write but does not gate *whether* they were allowed to touch a+//! given project. This module is the single typed decision point that closes+//! that gap. It is consulted by [`crate::ScopeResolver`] read/write resolution+//! (the one place every scoped MCP/API/web path funnels through) and by the+//! writer actor as defense in depth for writes.+//!+//! ## Ship inert (slice 2)+//!- //! The V67 schema is additive and every project defaults to `open`, so this is a++//! The V68 schema is additive and every project defaults to `open`, so this is a+//! pure pass-through until an operator opts a project into `restricted` (a+//! follow-up slice adds the management surface). The gate short-circuits to+//! ALLOW for:+//! - a deployment that does not distinguish operators (single-user / loopback),+//! where there is no notion of "another user" to gate against, and+//! - any `open` project.+//!+//! ## Never fail closed on a resolution gap (#678)+//!+//! A `restricted` project with **zero** grants still admits root and the+//! project creator — an operator is never locked out of their own data. If the+//! grants table cannot be read (an older schema mid-migration), the decision+//! degrades to `open` with a loud warning rather than denying every read.+//!+//! ## Invariant #16+//!+//! This is an *authorization* check that returns allow/deny for **entry** to a+//! project. It is never an [`ai_memory_core::OwnerFilter`] on page rows and it+//! never scopes page reads by user: a team with grants sees the same shared+//! pages. `pages.author_id` must never become a read filter.++use ai_memory_core::{AuthzError, ProjectId, UserId, WorkspaceId};+use rusqlite::{Connection, OptionalExtension, params};++use crate::error::StoreResult;++/// Denial message surfaced when a `restricted` project refuses a caller.+pub const RESTRICTED_PROJECT_FORBIDDEN: &str =+ "project access is restricted; root, the project creator, or a matching grant is required";+- /// A project's enforcement mode, stored in `projects.access_mode` (V67).++/// A project's enforcement mode, stored in `projects.access_mode` (V68).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum AccessMode {+ /// Today's behaviour: any authenticated user is admitted.+ Open,+ /// Only root, the project creator, and matching grants are admitted.+ Restricted,+}++impl AccessMode {+ /// Stable snake_case token stored in SQL.+ #[must_use]+ pub fn as_str(self) -> &'static str {+ match self {+ AccessMode::Open => "open",+ AccessMode::Restricted => "restricted",+ }+ }++ /// Parse the stored value, degrading anything unexpected to [`Self::Open`].+ ///+ /// A `NULL`/absent column, an unknown token, or a value written by a newer+ /// build all read as `open`. Never fail closed on a value we cannot make+ /// sense of (the #678 degrade-don't-lock-out rule).+ #[must_use]+ pub fn from_db(value: Option<&str>) -> Self {+ match value {+ Some("restricted") => AccessMode::Restricted,+ _ => AccessMode::Open,+ }+ }+}+- /// A user's grant level on a project (`project_grants.level`, V67).++/// A user's grant level on a project (`project_grants.level`, V68).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum GrantLevel {+ /// Read the project's pages/observations/status.+ Read,+ /// Read plus write/consolidate/handoff/message/delete.+ Write,+}++impl GrantLevel {+ /// Stable snake_case token stored in SQL.+ #[must_use]+ pub fn as_str(self) -> &'static str {+ match self {+ GrantLevel::Read => "read",+ GrantLevel::Write => "write",+ }+ }++ /// Parse the stored value; an unknown token is no grant.+ #[must_use]+ pub fn from_db(value: &str) -> Option<Self> {+ match value {+ "read" => Some(GrantLevel::Read),+ "write" => Some(GrantLevel::Write),+ _ => None,+ }+ }+}++/// What a caller is attempting to do in a project.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ProjectAccess {+ /// A read (query, read page/observations, status, briefing).+ Read,+ /// A write (write page, consolidate, handoff, message, delete).+ Write,+}++/// The caller, reduced to the facts the gate needs.+///+/// Root and creator are supplied by the auth layer; the grant is looked up from+/// `project_grants` by [`Self::user_id`]. No `projects.created_by` column exists+/// yet, so `is_creator` is threaded through the type for complete, testable+/// semantics and populated by the management surface in a follow-up slice.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ProjectPrincipal {+ /// Authenticated as the configured root operator.+ pub is_root: bool,+ /// The creator of this project.+ pub is_creator: bool,+ /// The caller's `users.id`, used to look up a grant. `None` for anonymous+ /// callers and for identities not mapped to a DB user.+ pub user_id: Option<UserId>,+}++impl ProjectPrincipal {+ /// An anonymous, ungranted, non-privileged caller.+ #[must_use]+ pub fn anonymous() -> Self {+ Self {+ is_root: false,+ is_creator: false,+ user_id: None,+ }+ }++ /// A root caller.+ #[must_use]+ pub fn root() -> Self {+ Self {+ is_root: true,+ is_creator: false,+ user_id: None,+ }+ }+}++/// A project's authorization state, fully resolved from SQL, ready to decide.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ProjectAuthz {+ /// Whether the deployment distinguishes operators (DB users / trusted proxy).+ pub distinguishes_operators: bool,+ /// The project's enforcement mode.+ pub access_mode: AccessMode,+ /// Whether the caller is root.+ pub is_root: bool,+ /// Whether the caller created the project.+ pub is_creator: bool,+ /// The caller's grant on the project, if any.+ pub grant: Option<GrantLevel>,+}++impl ProjectAuthz {+ /// Decide whether the caller may perform `need` in this project.+ ///+ /// - A deployment that does not distinguish operators skips the gate.+ /// - An `open` project admits everyone (today's behaviour).+ /// - A `restricted` project admits root and the creator unconditionally;+ /// otherwise a read needs any grant and a write needs a `write` grant.+ /// Anyone else — including an anonymous caller — is [`AuthzError::Forbidden`].+ ///+ /// # Errors+ /// [`AuthzError::Forbidden`] when a restricted project refuses the caller.+ pub fn authorize(&self, need: ProjectAccess) -> Result<(), AuthzError> {+ if !self.distinguishes_operators {+ return Ok(());+ }+ match self.access_mode {+ AccessMode::Open => Ok(()),+ AccessMode::Restricted => {+ if self.is_root || self.is_creator {+ return Ok(());+ }+ let admitted = match need {+ // A read or write grant both admit a read.+ ProjectAccess::Read => self.grant.is_some(),+ ProjectAccess::Write => self.grant == Some(GrantLevel::Write),+ };+ if admitted {+ Ok(())+ } else {+ Err(AuthzError::Forbidden(RESTRICTED_PROJECT_FORBIDDEN))+ }+ }+ }+ }+}++/// The choke point: decide `need` for `ctx`. Free-function form of+/// [`ProjectAuthz::authorize`] so call sites read as `authorize_project(...)`.+///+/// # Errors+/// [`AuthzError::Forbidden`] when a restricted project refuses the caller.+pub fn authorize_project(ctx: &ProjectAuthz, need: ProjectAccess) -> Result<(), AuthzError> {+ ctx.authorize(need)+}++/// Read `projects.access_mode`, degrading to [`AccessMode::Open`] on any read+/// failure and for an unknown project. Never fails closed.+fn read_access_mode(conn: &Connection, project_id: ProjectId) -> AccessMode {+ match conn.query_row(+ "SELECT access_mode FROM projects WHERE id = ?1",+ params![project_id.as_bytes()],+ |row| row.get::<_, Option<String>>(0),+ ) {+ Ok(value) => AccessMode::from_db(value.as_deref()),+ Err(rusqlite::Error::QueryReturnedNoRows) => AccessMode::Open,+ Err(err) => {+ tracing::warn!(+ error = %err,+ "could not read projects.access_mode; degrading project authz to open",+ );+ AccessMode::Open+ }+ }+}++/// Look up a caller's grant on a project. Returns the failure so the caller can+/// decide how to degrade (a restricted project degrades to open when its grants+/// cannot be read).+fn read_grant(+ conn: &Connection,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ user_id: UserId,+) -> rusqlite::Result<Option<GrantLevel>> {+ let level: Option<String> = conn+ .query_row(+ "SELECT level FROM project_grants \+ WHERE workspace_id = ?1 AND project_id = ?2 AND user_id = ?3",+ params![+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ user_id.as_bytes()+ ],+ |row| row.get(0),+ )+ .optional()?;+ Ok(level.as_deref().and_then(GrantLevel::from_db))+}++/// Resolve the full [`ProjectAuthz`] for a project from a live connection.+///+/// `open` short-circuits without touching `project_grants`. A `restricted`+/// project whose grants cannot be read degrades to `open` with a warning rather+/// than denying every caller (#678).+///+/// # Errors+/// Propagates only failures that are not the grant-read degrade path; the+/// access-mode read itself never errors (it degrades to open).+pub fn resolve_project_authz(+ conn: &Connection,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ principal: &ProjectPrincipal,+ distinguishes_operators: bool,+) -> StoreResult<ProjectAuthz> {+ let mut access_mode = read_access_mode(conn, project_id);+ let grant = if access_mode == AccessMode::Restricted {+ match principal.user_id {+ Some(user_id) => match read_grant(conn, workspace_id, project_id, user_id) {+ Ok(grant) => grant,+ Err(err) => {+ // The grants table cannot be read: degrade to open rather+ // than lock everyone out of a restricted project (#678).+ tracing::warn!(+ error = %err,+ "could not read project_grants; degrading project authz to open",+ );+ access_mode = AccessMode::Open;+ None+ }+ },+ None => None,+ }+ } else {+ None+ };+ Ok(ProjectAuthz {+ distinguishes_operators,+ access_mode,+ is_root: principal.is_root,+ is_creator: principal.is_creator,+ grant,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn ctx(+ distinguishes_operators: bool,+ access_mode: AccessMode,+ is_root: bool,+ is_creator: bool,+ grant: Option<GrantLevel>,+ ) -> ProjectAuthz {+ ProjectAuthz {+ distinguishes_operators,+ access_mode,+ is_root,+ is_creator,+ grant,+ }+ }++ #[test]+ fn access_mode_round_trips_and_degrades_open() {+ assert_eq!(AccessMode::from_db(Some("open")), AccessMode::Open);+ assert_eq!(+ AccessMode::from_db(Some("restricted")),+ AccessMode::Restricted+ );+ // Anything unexpected degrades to open, never fail closed.+ for weird in [None, Some(""), Some("RESTRICTED"), Some("locked")] {+ assert_eq!(AccessMode::from_db(weird), AccessMode::Open, "{weird:?}");+ }+ assert_eq!(AccessMode::Open.as_str(), "open");+ assert_eq!(AccessMode::Restricted.as_str(), "restricted");+ }++ #[test]+ fn grant_level_parse() {+ assert_eq!(GrantLevel::from_db("read"), Some(GrantLevel::Read));+ assert_eq!(GrantLevel::from_db("write"), Some(GrantLevel::Write));+ assert_eq!(GrantLevel::from_db("admin"), None);+ }++ /// The pure decision table. Every row must flip if the gate were removed or+ /// inverted, so this is the adversarial core the SQL wrapper reuses.+ #[test]+ fn authorize_decision_matrix() {+ use AccessMode::{Open, Restricted};+ use GrantLevel::{Read, Write};+ use ProjectAccess as A;++ // (distinguishes, mode, is_root, is_creator, grant, need, expect_ok)+ let rows = [+ // Single-user / loopback: the gate does not exist.+ (false, Restricted, false, false, None, A::Read, true),+ (false, Restricted, false, false, None, A::Write, true),+ // Open: everyone is admitted, even anonymous.+ (true, Open, false, false, None, A::Read, true),+ (true, Open, false, false, None, A::Write, true),+ // Restricted + root: always admitted.+ (true, Restricted, true, false, None, A::Read, true),+ (true, Restricted, true, false, None, A::Write, true),+ // Restricted + creator, zero grants: still admitted.+ (true, Restricted, false, true, None, A::Read, true),+ (true, Restricted, false, true, None, A::Write, true),+ // Restricted + no grant, non-root, non-creator: denied both ways.+ (true, Restricted, false, false, None, A::Read, false),+ (true, Restricted, false, false, None, A::Write, false),+ // Restricted + read grant: read OK, write denied.+ (true, Restricted, false, false, Some(Read), A::Read, true),+ (true, Restricted, false, false, Some(Read), A::Write, false),+ // Restricted + write grant: both OK.+ (true, Restricted, false, false, Some(Write), A::Read, true),+ (true, Restricted, false, false, Some(Write), A::Write, true),+ ];++ for (distinguishes, mode, root, creator, grant, need, expect_ok) in rows {+ let decision = authorize_project(&ctx(distinguishes, mode, root, creator, grant), need);+ assert_eq!(+ decision.is_ok(),+ expect_ok,+ "row d={distinguishes} mode={mode:?} root={root} creator={creator} \+ grant={grant:?} need={need:?}",+ );+ if !expect_ok {+ assert_eq!(+ decision.unwrap_err(),+ AuthzError::Forbidden(RESTRICTED_PROJECT_FORBIDDEN),+ );+ }+ }+ }+}diff --cc crates/ai-memory-store/tests/suite/project_authz.rsindex b0bc1ec6,00000000..f0380e8fmode 100644,000000..100644--- a/crates/ai-memory-store/tests/suite/project_authz.rs+++ b/crates/ai-memory-store/tests/suite/project_authz.rs@@@ -1,509 -1,0 +1,509 @@@+//! Adversarial integration tests for the per-project authorization choke+//! point (#708, slice 2).+//!+//! These prove the gate BITES: with the guard removed or inverted every+//! restricted-project row here would flip. They deliberately live at+//! integration level (invariant #16) — a single-tenant happy path cannot see+//! an authorization defect. The gate is an allow/deny check for ENTRY to a+//! project; it is never an `OwnerFilter` on page rows, so nothing here filters+//! page reads by user.+//!+//! Slice 2 ships inert: every project defaults to `open`, so the gate is a+//! pass-through until an operator opts a project into `restricted`. The tests+//! set `access_mode='restricted'` and insert `project_grants` rows directly via+//! SQL to exercise the enforcing branch the management surface (slice 3) will+//! drive.++use ai_memory_core::{ActorKey, AuthzError, NewUser, ProjectId, UserId, UserRole, WorkspaceId};+use ai_memory_store::{+ AccessMode, GrantLevel, ProjectAccess, ProjectAuthz, ProjectPrincipal, ScopeResolver, Store,+ authorize_project,+};+use rusqlite::{Connection, params};++const GRANTED_AT: i64 = 1_700_000_000_000_000;++async fn make_user(store: &Store, username: &str) -> UserId {+ store+ .writer+ .create_human_user(+ NewUser {+ username: username.to_string(),+ name: None,+ email: None,+ },+ UserRole::User,+ None,+ false,+ )+ .await+ .unwrap()+}++/// Flip a project's access mode via raw SQL — stands in for the slice-3+/// management surface.+fn set_access_mode(store: &Store, project_id: ProjectId, mode: &str) {+ let conn = Connection::open(store.db_path()).unwrap();+ let updated = conn+ .execute(+ "UPDATE projects SET access_mode = ?1 WHERE id = ?2",+ params![mode, project_id.as_bytes()],+ )+ .unwrap();+ assert_eq!(updated, 1, "expected to update exactly one project row");+}++/// Insert a grant row via raw SQL.+fn insert_grant(+ store: &Store,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ user_id: UserId,+ level: &str,+) {+ let conn = Connection::open(store.db_path()).unwrap();+ conn.execute(+ "INSERT INTO project_grants \+ (workspace_id, project_id, user_id, level, granted_by, granted_at) \+ VALUES (?1, ?2, ?3, ?4, NULL, ?5)",+ params![+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ user_id.as_bytes(),+ level,+ GRANTED_AT+ ],+ )+ .unwrap();+}++async fn scope(store: &Store, ws_name: &str, proj_name: &str) -> (WorkspaceId, ProjectId) {+ let ws = store+ .writer+ .get_or_create_workspace(ws_name.to_string())+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, proj_name.to_string(), None)+ .await+ .unwrap();+ (ws, proj)+}++/// (a) AUTHZ MATRIX — root / granted-read / granted-write / no-grant /+/// anonymous × {open, restricted}, resolved from real SQL through both the+/// reader-pool and writer-actor entry points. Every restricted row flips if the+/// gate is removed; the legitimate controls (root, creator, matching grant) are+/// admitted.+#[tokio::test]+async fn authz_matrix_reader_and_writer_paths() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();++ let (ws, restricted) = scope(&store, "acme", "restricted").await;+ let (_, open) = scope(&store, "acme", "open").await;++ let reader = make_user(&store, "reader-user").await;+ let writer = make_user(&store, "writer-user").await;+ let nogrant = make_user(&store, "no-grant-user").await;++ set_access_mode(&store, restricted, "restricted");+ insert_grant(&store, ws, restricted, reader, "read");+ insert_grant(&store, ws, restricted, writer, "write");++ let root = ProjectPrincipal::root();+ let creator = ProjectPrincipal {+ is_root: false,+ is_creator: true,+ user_id: None,+ };+ let read_grantee = ProjectPrincipal {+ is_root: false,+ is_creator: false,+ user_id: Some(reader),+ };+ let write_grantee = ProjectPrincipal {+ is_root: false,+ is_creator: false,+ user_id: Some(writer),+ };+ let no_grant = ProjectPrincipal {+ is_root: false,+ is_creator: false,+ user_id: Some(nogrant),+ };+ let anon = ProjectPrincipal::anonymous();++ // (principal, need, target_project, expect_ok)+ use ProjectAccess::{Read, Write};+ let cases: Vec<(&str, ProjectPrincipal, ProjectAccess, ProjectId, bool)> = vec![+ // Restricted project.+ (+ "root reads restricted",+ root.clone(),+ Read,+ restricted,+ true,+ ),+ (+ "root writes restricted",+ root.clone(),+ Write,+ restricted,+ true,+ ),+ (+ "creator reads restricted",+ creator.clone(),+ Read,+ restricted,+ true,+ ),+ (+ "creator writes restricted",+ creator.clone(),+ Write,+ restricted,+ true,+ ),+ (+ "read-grant reads restricted",+ read_grantee.clone(),+ Read,+ restricted,+ true,+ ),+ (+ "read-grant CANNOT write restricted",+ read_grantee.clone(),+ Write,+ restricted,+ false,+ ),+ (+ "write-grant reads restricted",+ write_grantee.clone(),+ Read,+ restricted,+ true,+ ),+ (+ "write-grant writes restricted",+ write_grantee.clone(),+ Write,+ restricted,+ true,+ ),+ (+ "no-grant CANNOT read restricted",+ no_grant.clone(),+ Read,+ restricted,+ false,+ ),+ (+ "no-grant CANNOT write restricted",+ no_grant.clone(),+ Write,+ restricted,+ false,+ ),+ (+ "anonymous CANNOT read restricted",+ anon.clone(),+ Read,+ restricted,+ false,+ ),+ (+ "anonymous CANNOT write restricted",+ anon.clone(),+ Write,+ restricted,+ false,+ ),+ // Open project — everyone, including anonymous, is admitted.+ ("anonymous reads open", anon.clone(), Read, open, true),+ ("anonymous writes open", anon.clone(), Write, open, true),+ ("no-grant reads open", no_grant.clone(), Read, open, true),+ ("no-grant writes open", no_grant.clone(), Write, open, true),+ ];++ for (name, principal, need, project, expect_ok) in cases {+ // Reader-pool entry point.+ let via_reader = store+ .reader+ .authorize_project(ws, project, principal.clone(), true, need)+ .await+ .unwrap();+ assert_eq!(via_reader.is_ok(), expect_ok, "reader: {name}");++ // Writer-actor entry point (defense in depth) — same decision.+ let via_writer = store+ .writer+ .authorize_project(ws, project, principal.clone(), true, need)+ .await+ .unwrap();+ assert_eq!(via_writer.is_ok(), expect_ok, "writer: {name}");++ if !expect_ok {+ assert!(+ matches!(via_reader, Err(AuthzError::Forbidden(_))),+ "{name} must be Forbidden, not some other outcome",+ );+ }+ }+}++/// (b) SHIP-INERT — an empty grants table with the default `open` mode admits+/// everyone; a `restricted` project with ZERO grants still admits root and the+/// creator (never locked out of your own data).+#[tokio::test]+async fn ship_inert_open_admits_all_and_restricted_admits_root_and_creator() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();++ let (ws, open) = scope(&store, "team", "open").await;+ let (_, restricted) = scope(&store, "team", "locked").await;+ set_access_mode(&store, restricted, "restricted");++ // Empty grants + default open: anonymous is admitted for read and write.+ for need in [ProjectAccess::Read, ProjectAccess::Write] {+ let decision = store+ .reader+ .authorize_project(ws, open, ProjectPrincipal::anonymous(), true, need)+ .await+ .unwrap();+ assert!(decision.is_ok(), "open project admits everyone: {need:?}");+ }++ // Restricted + zero grants: root and creator still admitted.+ let creator = ProjectPrincipal {+ is_root: false,+ is_creator: true,+ user_id: None,+ };+ for principal in [ProjectPrincipal::root(), creator] {+ for need in [ProjectAccess::Read, ProjectAccess::Write] {+ let decision = store+ .reader+ .authorize_project(ws, restricted, principal.clone(), true, need)+ .await+ .unwrap();+ assert!(+ decision.is_ok(),+ "restricted-with-zero-grants must admit root/creator: {principal:?} {need:?}",+ );+ }+ }++ // The control that proves the restriction is real: a bare authenticated+ // user with no grant is refused the same restricted project.+ let stranger = make_user(&store, "stranger").await;+ let decision = store+ .reader+ .authorize_project(+ ws,+ restricted,+ ProjectPrincipal {+ is_root: false,+ is_creator: false,+ user_id: Some(stranger),+ },+ true,+ ProjectAccess::Read,+ )+ .await+ .unwrap();+ assert!(+ decision.is_err(),+ "a restricted project with zero grants must still refuse an ungranted stranger",+ );+}++/// (d) distinguishes_operators() == false skips the gate entirely: even a+/// restricted project with no grant admits an anonymous caller, because a+/// single-user / loopback deployment has no notion of "another operator".+#[tokio::test]+async fn gate_is_skipped_when_operators_are_not_distinguished() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();++ let (ws, restricted) = scope(&store, "solo", "locked").await;+ set_access_mode(&store, restricted, "restricted");++ for need in [ProjectAccess::Read, ProjectAccess::Write] {+ // distinguishes_operators = false -> allow.+ let skipped = store+ .reader+ .authorize_project(ws, restricted, ProjectPrincipal::anonymous(), false, need)+ .await+ .unwrap();+ assert!(skipped.is_ok(), "single-user mode skips the gate: {need:?}");++ // The control: with distinguishing ON, the same call is refused, so the+ // pass above is the skip, not an always-allow bug.+ let enforced = store+ .reader+ .authorize_project(ws, restricted, ProjectPrincipal::anonymous(), true, need)+ .await+ .unwrap();+ assert!(+ enforced.is_err(),+ "multi-user mode enforces the gate: {need:?}"+ );+ }+}+- /// (c) MIGRATION IDEMPOTENCY — V67 applies cleanly (the table exists, the column++/// (c) MIGRATION IDEMPOTENCY — V68 applies cleanly (the table exists, the column+/// defaults to 'open'), the CHECK constraints bite, and re-opening the store+/// (which re-runs the migration set) is a no-op that preserves the data.+#[tokio::test]+async fn migration_applies_defaults_open_and_reopen_is_a_noop() {+ let tmp = tempfile::tempdir().unwrap();+ let project_id;+ {+ let store = Store::open(tmp.path()).unwrap();+ let (_, proj) = scope(&store, "acme", "app").await;+ project_id = proj;++ let conn = Connection::open(store.db_path()).unwrap();++ // Additive: an existing project defaults to 'open'.+ let mode: String = conn+ .query_row(+ "SELECT access_mode FROM projects WHERE id = ?1",+ params![proj.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(mode, "open");++ // The grants table exists and starts empty.+ let grant_count: i64 = conn+ .query_row("SELECT COUNT(*) FROM project_grants", [], |row| row.get(0))+ .unwrap();+ assert_eq!(grant_count, 0);++ // CHECK constraints bite.+ assert!(+ conn.execute(+ "UPDATE projects SET access_mode = 'bogus' WHERE id = ?1",+ params![proj.as_bytes()],+ )+ .is_err(),+ "access_mode CHECK must reject an unknown mode",+ );+ assert!(+ conn.execute(+ "INSERT INTO project_grants \+ (workspace_id, project_id, user_id, level, granted_by, granted_at) \+ VALUES (randomblob(16), ?1, randomblob(16), 'admin', NULL, ?2)",+ params![proj.as_bytes(), GRANTED_AT],+ )+ .is_err(),+ "level CHECK must reject a level other than read/write",+ );+ }++ // Re-open the same data dir: migrations re-run and must be a no-op.+ let store = Store::open(tmp.path()).unwrap();+ let conn = Connection::open(store.db_path()).unwrap();+ let mode: String = conn+ .query_row(+ "SELECT access_mode FROM projects WHERE id = ?1",+ params![project_id.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(+ mode, "open",+ "re-open must preserve the applied schema + data"+ );+}++/// The choke point is genuinely wired into `ScopeResolver` read + write+/// resolution: a restricted project is refused there, an ungated resolver still+/// admits it (proving the gate — not something else — is what bites), and root+/// is admitted through the same wiring.+#[tokio::test]+async fn scope_resolver_gates_restricted_projects() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();++ let (ws, restricted) = scope(&store, "acme", "restricted").await;+ let (default_ws, default_proj) = scope(&store, "acme", "fallback").await;+ set_access_mode(&store, restricted, "restricted");++ let actor = ActorKey::default();++ // With the authz principal attached, an anonymous caller is Forbidden the+ // restricted project on both the read and write paths.+ let gated_read = ScopeResolver::new(&store.reader, default_ws, default_proj)+ .with_project_authz(ProjectPrincipal::anonymous(), true)+ .resolve_read_args(Some("acme"), Some("restricted"), &actor)+ .await+ .unwrap_err();+ assert!(gated_read.is_forbidden(), "read: {gated_read:?}");++ let gated_write = ScopeResolver::new(&store.reader, default_ws, default_proj)+ .with_writer(&store.writer)+ .with_project_authz(ProjectPrincipal::anonymous(), true)+ .resolve_write_args(Some("acme"), Some("restricted"), &actor)+ .await+ .unwrap_err();+ assert!(gated_write.is_forbidden(), "write: {gated_write:?}");++ // Proof it bites: the SAME resolution WITHOUT the authz principal admits the+ // restricted project (today's behaviour — the gate is opt-in and inert).+ let ungated = ScopeResolver::new(&store.reader, default_ws, default_proj)+ .resolve_read_args(Some("acme"), Some("restricted"), &actor)+ .await+ .unwrap();+ assert_eq!(ungated.as_tuple(), (ws, restricted));++ // The legitimate control: root is admitted through the same wiring.+ let root_ok = ScopeResolver::new(&store.reader, default_ws, default_proj)+ .with_project_authz(ProjectPrincipal::root(), true)+ .resolve_read_args(Some("acme"), Some("restricted"), &actor)+ .await+ .unwrap();+ assert_eq!(root_ok.as_tuple(), (ws, restricted));++ // And an open project is unaffected: the gate admits everyone.+ let open_ok = ScopeResolver::new(&store.reader, default_ws, default_proj)+ .with_project_authz(ProjectPrincipal::anonymous(), true)+ .resolve_read_args(Some("acme"), Some("fallback"), &actor)+ .await+ .unwrap();+ assert_eq!(open_ok.as_tuple(), (default_ws, default_proj));+}++/// The pure decision function reused as documentation of intent: a resolved+/// restricted context with no grant denies, a write grant admits both.+#[tokio::test]+async fn pure_authorize_project_reference() {+ let deny = ProjectAuthz {+ distinguishes_operators: true,+ access_mode: AccessMode::Restricted,+ is_root: false,+ is_creator: false,+ grant: None,+ };+ assert!(authorize_project(&deny, ProjectAccess::Read).is_err());++ let write_grant = ProjectAuthz {+ grant: Some(GrantLevel::Write),+ ..deny+ };+ assert!(authorize_project(&write_grant, ProjectAccess::Read).is_ok());+ assert!(authorize_project(&write_grant, ProjectAccess::Write).is_ok());++ let read_grant = ProjectAuthz {+ grant: Some(GrantLevel::Read),+ ..deny+ };+ assert!(authorize_project(&read_grant, ProjectAccess::Read).is_ok());+ assert!(authorize_project(&read_grant, ProjectAccess::Write).is_err());+}diff --cc docs/design-per-project-authz.mdindex cabd371f,d5acc6b9..d22b14ca--- a/docs/design-per-project-authz.md+++ b/docs/design-per-project-authz.md@@@ -1,20 -1,8 +1,20 @@@# Design proposal: per-project authorization for multi-user servers (#708)- **Implementation status.** Slice 2 has landed: the inert V67 schema-**Status: proposal for review — not implemented.** This is the design pass promised-on #708 before any code lands. It changes a security boundary, so it is deliberately-separated from implementation.++**Implementation status.** Slice 2 has landed: the inert V68 schema+(`project_grants` + `projects.access_mode`, default `open`) and the+`authorize_project` choke point (`ai-memory-store/src/project_authz.rs`),+wired into `ScopeResolver` read/write resolution and the writer actor. It is+always-allow (no project is `restricted` yet), so there is no behaviour change.+**Slice 3 is pending** and is what makes `restricted` safe end-to-end: closing+the two bypass classes below (unscoped/global reads filtered before `LIMIT`;+raw-id entry points resolving through `authorize_project`), the root-only+management surface (setting `restricted`, issuing grants), and a+`projects.created_by` source for the creator check. Sections below are the+original design pass, retained as the spec.++**Original status: proposal for review — not implemented.** This was the design+pass promised on #708 before any code lands. It changes a security boundary, so+it is deliberately separated from implementation.## Problemdiff --cc docs/security-boundaries.mdindex 3fbca745,c571ac6c..b1af7bfc--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@@ -45,7 -46,8 +46,8 @@@ boundary not yet built| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn) | `capture_policy.rs` per-agent `…honors_exclusions` tests | STRONG || 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH || 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401 | STRONG |- | 13 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (inert V67 schema: `project_grants` + `projects.access_mode`, default `open`); consulted by `scope.rs` `ScopeResolver` read+write resolution (opt-in `with_project_authz`, reader-pool for reads, writer-actor for writes) and by `WriterHandle::authorize_project` as defense in depth | `tests/suite/project_authz.rs` — `authz_matrix_reader_and_writer_paths`, `ship_inert_open_admits_all_and_restricted_admits_root_and_creator`, `gate_is_skipped_when_operators_are_not_distinguished`, `scope_resolver_gates_restricted_projects`, `migration_applies_defaults_open_and_reopen_is_a_noop`, `authorize_decision_matrix` (each proven to fail with the gate neutralized) | PARTIAL — slice 2: choke point + inert schema exist and are always-allow (no project is `restricted` yet). `restricted` is **not safe end-to-end** until slice 3 closes the two bypass classes (unscoped/global reads must filter by readable projects **before** `LIMIT`; raw-id entry points — session/run/page id, `page_evidence_counts` — must resolve→`authorize_project`) and adds the root-only management surface that sets `restricted` and issues grants (creator resolution + a `projects.created_by` source land there too) |+ | 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), and never falls back to a link it set aside | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout |-| — | Per-project authorization (#708) | proposal only — `docs/design-per-project-authz.md` (`authorize_project` choke point + unscoped-read/raw-id bypass classes) | none yet — the design's "Verification plan" tests (authz matrix, unscoped-read-leak, raw-id-authz, ship-inert) land WITH the code | FUTURE |++| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (inert V68 schema: `project_grants` + `projects.access_mode`, default `open`); consulted by `scope.rs` `ScopeResolver` read+write resolution (opt-in `with_project_authz`, reader-pool for reads, writer-actor for writes) and by `WriterHandle::authorize_project` as defense in depth | `tests/suite/project_authz.rs` — `authz_matrix_reader_and_writer_paths`, `ship_inert_open_admits_all_and_restricted_admits_root_and_creator`, `gate_is_skipped_when_operators_are_not_distinguished`, `scope_resolver_gates_restricted_projects`, `migration_applies_defaults_open_and_reopen_is_a_noop`, `authorize_decision_matrix` (each proven to fail with the gate neutralized) | PARTIAL — slice 2: choke point + inert schema exist and are always-allow (no project is `restricted` yet). `restricted` is **not safe end-to-end** until slice 3 closes the two bypass classes (unscoped/global reads must filter by readable projects **before** `LIMIT`; raw-id entry points — session/run/page id, `page_evidence_counts` — must resolve→`authorize_project`) and adds the root-only management surface that sets `restricted` and issues grants |## Keeping this current (the standing protocol)