Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(auth): enforce project access policies

Maxvintb7c623162426
diff --git a/core/services/session_fork.py b/core/services/session_fork.py
index f850e21f0..77249f5db 100644
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@ -129,7 +129,7 @@ def reserve_forked_session(
session.
"""
- require_instance_role(authorization_context, "editor")
+ context = require_instance_role(authorization_context, "editor")
from sqlalchemy import select
@@ -146,6 +146,18 @@ def reserve_forked_session(
agent_store = VibeAgentStore(path)
try:
with engine.begin() as conn:
+ if not context.is_instance_owner:
+ from storage import project_access_service
+
+ if not project_access_service.role_allows(
+ project_access_service.get_effective_session_role(
+ conn,
+ context,
+ source_session_id,
+ ),
+ "editor",
+ ):
+ raise SessionForkError("source_not_found")
row = conn.execute(
select(agent_sessions).where(agent_sessions.c.id == str(source_session_id)).limit(1)
).mappings().first()
diff --git a/storage/alembic/versions/20260725_0035_project_access_policies.py b/storage/alembic/versions/20260725_0035_project_access_policies.py
new file mode 100644
index 000000000..1269e611f
--- /dev/null
+++ b/storage/alembic/versions/20260725_0035_project_access_policies.py
@@ -0,0 +1,114 @@
+"""add local Project access policies and bindings
+
+Revision ID: 20260725_0035
+Revises: 20260724_0034
+Create Date: 2026-07-25
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260725_0035"
+down_revision = "20260724_0034"
+branch_labels = None
+depends_on = None
+
+
+def _tables(bind) -> set[str]:
+ return {
+ str(row[0])
+ for row in bind.exec_driver_sql(
+ "select name from sqlite_master where type = 'table'"
+ )
+ }
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ tables = _tables(bind)
+ if "project_access_policies" not in tables:
+ op.create_table(
+ "project_access_policies",
+ sa.Column("project_id", sa.String(), nullable=False),
+ sa.Column("scope_id", sa.String(), nullable=False),
+ sa.Column("organization_id", sa.String(), nullable=True),
+ sa.Column("mode", sa.String(), server_default="inherit", nullable=False),
+ sa.Column("policy_revision", sa.Integer(), server_default="0", nullable=False),
+ sa.Column(
+ "last_applied_control_plane_revision",
+ sa.Integer(),
+ server_default="0",
+ nullable=False,
+ ),
+ sa.Column("created_at", sa.String(), nullable=False),
+ sa.Column("updated_at", sa.String(), nullable=False),
+ sa.CheckConstraint(
+ "last_applied_control_plane_revision >= 0",
+ name="ck_project_access_policies_control_revision",
+ ),
+ sa.CheckConstraint(
+ "mode in ('inherit', 'restricted')",
+ name="ck_project_access_policies_mode",
+ ),
+ sa.CheckConstraint(
+ "policy_revision >= 0",
+ name="ck_project_access_policies_revision",
+ ),
+ sa.ForeignKeyConstraint(["scope_id"], ["scopes.id"], ondelete="CASCADE"),
+ sa.PrimaryKeyConstraint("project_id"),
+ sa.UniqueConstraint("scope_id", name="uq_project_access_policies_scope"),
+ )
+ op.create_index(
+ "ix_project_access_policies_organization",
+ "project_access_policies",
+ ["organization_id"],
+ )
+
+ tables = _tables(bind)
+ if "project_access_bindings" not in tables:
+ op.create_table(
+ "project_access_bindings",
+ sa.Column("project_id", sa.String(), nullable=False),
+ sa.Column("principal_kind", sa.String(), nullable=False),
+ sa.Column("principal_value", sa.String(), nullable=False),
+ sa.Column("access_role", sa.String(), nullable=False),
+ sa.Column("created_at", sa.String(), nullable=False),
+ sa.CheckConstraint(
+ "access_role in ('editor', 'viewer')",
+ name="ck_project_access_bindings_role",
+ ),
+ sa.CheckConstraint(
+ "principal_kind in ('email', 'email_domain', 'organization_group')",
+ name="ck_project_access_bindings_kind",
+ ),
+ sa.ForeignKeyConstraint(
+ ["project_id"],
+ ["project_access_policies.project_id"],
+ ondelete="CASCADE",
+ ),
+ sa.PrimaryKeyConstraint("project_id", "principal_kind", "principal_value"),
+ )
+ op.create_index(
+ "ix_project_access_bindings_principal",
+ "project_access_bindings",
+ ["principal_kind", "principal_value"],
+ )
+
+
+def downgrade() -> None:
+ bind = op.get_bind()
+ tables = _tables(bind)
+ if "project_access_bindings" in tables:
+ op.drop_index(
+ "ix_project_access_bindings_principal",
+ table_name="project_access_bindings",
+ )
+ op.drop_table("project_access_bindings")
+ if "project_access_policies" in tables:
+ op.drop_index(
+ "ix_project_access_policies_organization",
+ table_name="project_access_policies",
+ )
+ op.drop_table("project_access_policies")
diff --git a/storage/messages_service.py b/storage/messages_service.py
index a4cab394b..d1b5369a9 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -224,6 +224,7 @@ def search_messages(
platform: str = "avibe",
types: Optional[Iterable[str]] = None,
limit: int = 50,
+ scope_ids: Optional[Iterable[str]] = None,
) -> dict[str, Any]:
"""Global message-content search, grouped by session.
@@ -251,6 +252,9 @@ def search_messages(
cleaned = (query or "").strip()
if not cleaned:
return {"sessions": [], "total": 0, "session_count": 0}
+ allowed_scope_ids = list(dict.fromkeys(scope_ids)) if scope_ids is not None else None
+ if allowed_scope_ids == []:
+ return {"sessions": [], "total": 0, "session_count": 0}
like = escape_sql_like(cleaned)
type_list = list(types if types is not None else ("user", HARNESS_TYPE, "result"))
@@ -288,6 +292,8 @@ def search_messages(
.order_by(messages.c.created_at.desc(), messages.c.id.desc())
.limit(effective_limit)
)
+ if allowed_scope_ids is not None:
+ stmt = stmt.where(agent_sessions.c.scope_id.in_(allowed_scope_ids))
rows = conn.execute(stmt).mappings().all()
@@ -941,6 +947,7 @@ def unread_counts_by_session(
conn: Connection,
*,
platform: Optional[str] = None,
+ scope_ids: Optional[Iterable[str]] = None,
) -> dict[str, int]:
"""Return ``{session_id: count}`` for unread agent ``result`` messages.
@@ -952,6 +959,10 @@ def unread_counts_by_session(
count (the realtime ``inbox.session.updated`` row is result-only too).
"""
+ allowed_scope_ids = list(dict.fromkeys(scope_ids)) if scope_ids is not None else None
+ if allowed_scope_ids == []:
+ return {}
+
query = (
select(messages.c.session_id, func.count(messages.c.id))
.where(messages.c.author == "agent")
@@ -974,6 +985,14 @@ def unread_counts_by_session(
)
if platform is not None:
query = query.where(messages.c.platform == platform)
+ if allowed_scope_ids is not None:
+ query = query.where(
+ messages.c.session_id.in_(
+ select(agent_sessions.c.id).where(
+ agent_sessions.c.scope_id.in_(allowed_scope_ids)
+ )
+ )
+ )
return {session_id: int(count) for session_id, count in conn.execute(query).all()}
@@ -998,6 +1017,7 @@ def list_inbox_sessions(
limit: int = 30,
before: Optional[str] = None,
only_session: Optional[str] = None,
+ scope_ids: Optional[Iterable[str]] = None,
) -> dict[str, Any]:
"""Per-session ("Slack-like") inbox feed.
@@ -1013,6 +1033,10 @@ def list_inbox_sessions(
cursor returned as ``next_cursor``).
"""
+ allowed_scope_ids = list(dict.fromkeys(scope_ids)) if scope_ids is not None else None
+ if allowed_scope_ids == []:
+ return {"sessions": [], "next_cursor": None}
+
def _latest_message_value(
column_name: str,
*,
@@ -1112,6 +1136,8 @@ def list_inbox_sessions(
)
if only_session:
session_rows = session_rows.where(agent_sessions.c.id == only_session)
+ if allowed_scope_ids is not None:
+ session_rows = session_rows.where(agent_sessions.c.scope_id.in_(allowed_scope_ids))
session_rows_sub = session_rows.subquery()
query = select(session_rows_sub).where(session_rows_sub.c.preview_id.is_not(None))
diff --git a/storage/models.py b/storage/models.py
index 8d7d936d2..d2c6e8d6b 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from sqlalchemy import (
+ CheckConstraint,
Column,
DDL,
Float,
@@ -92,6 +93,52 @@ scope_settings = Table(
Index("ix_scope_settings_backend_model", "agent_backend", "model"),
)
+project_access_policies = Table(
+ "project_access_policies",
+ metadata,
+ Column("project_id", String, primary_key=True),
+ Column("scope_id", String, ForeignKey("scopes.id", ondelete="CASCADE"), nullable=False),
+ Column("organization_id", String, nullable=True),
+ Column("mode", String, nullable=False, server_default="inherit"),
+ Column("policy_revision", Integer, nullable=False, server_default="0"),
+ Column("last_applied_control_plane_revision", Integer, nullable=False, server_default="0"),
+ Column("created_at", String, nullable=False),
+ Column("updated_at", String, nullable=False),
+ UniqueConstraint("scope_id", name="uq_project_access_policies_scope"),
+ CheckConstraint("mode in ('inherit', 'restricted')", name="ck_project_access_policies_mode"),
+ CheckConstraint("policy_revision >= 0", name="ck_project_access_policies_revision"),
+ CheckConstraint(
+ "last_applied_control_plane_revision >= 0",
+ name="ck_project_access_policies_control_revision",
+ ),
+ Index("ix_project_access_policies_organization", "organization_id"),
+)
+
+project_access_bindings = Table(
+ "project_access_bindings",
+ metadata,
+ Column(
+ "project_id",
+ String,
+ ForeignKey("project_access_policies.project_id", ondelete="CASCADE"),
+ primary_key=True,
+ ),
+ Column("principal_kind", String, primary_key=True),
+ Column("principal_value", String, primary_key=True),
+ Column("access_role", String, nullable=False),
+ Column("created_at", String, nullable=False),
+ CheckConstraint(
+ "principal_kind in ('email', 'email_domain', 'organization_group')",
+ name="ck_project_access_bindings_kind",
+ ),
+ CheckConstraint("access_role in ('editor', 'viewer')", name="ck_project_access_bindings_role"),
+ Index(
+ "ix_project_access_bindings_principal",
+ "principal_kind",
+ "principal_value",
+ ),
+)
+
auth_codes = Table(
"auth_codes",
metadata,
diff --git a/storage/project_access_service.py b/storage/project_access_service.py
new file mode 100644
index 000000000..6d73d0df3
--- /dev/null
+++ b/storage/project_access_service.py
@@ -0,0 +1,383 @@
+"""Applied Project access policy storage and centralized role evaluation."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime, timezone
+import re
+from typing import Any, Iterable, Mapping, Sequence
+
+from sqlalchemy import delete, insert, select
+from sqlalchemy.dialects.sqlite import insert as sqlite_insert
+from sqlalchemy.engine import Connection
+
+from storage.models import (
+ agent_sessions,
+ project_access_bindings,
+ project_access_policies,
+ scope_settings,
+ scopes,
+)
+from vibe.authorization import AuthorizationContext
+
+PROJECT_SCOPE_PREFIX = "avibe::project::"
+PROJECT_ACCESS_MODES = frozenset({"inherit", "restricted"})
+PROJECT_ACCESS_ROLES = frozenset({"editor", "viewer"})
+PROJECT_PRINCIPAL_KINDS = frozenset({"email", "email_domain", "organization_group"})
+MAX_CONTROL_PLANE_REVISION = (1 << 53) - 1
+_ROLE_RANK = {"viewer": 1, "editor": 2, "owner": 3}
+_EMAIL_RE = re.compile(
+ r"^[a-z0-9._%+-]+@[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
+ r"(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*\.[a-z]{2,}$"
+)
+_DOMAIN_RE = re.compile(
+ r"^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
+ r"(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*\.[a-z]{2,}$"
+)
+
+
+class ProjectAccessIntentError(ValueError):
+ def __init__(self, code: str):
+ super().__init__(code)
+ self.code = code
+
+
+@dataclass(frozen=True)
+class ProjectAccessIntentResult:
+ project_id: str
+ revision: int
+ outcome: str
+ error_code: str | None = None
+ changed: bool = False
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def project_scope_id(project_id: str) -> str:
+ return f"{PROJECT_SCOPE_PREFIX}{project_id}"
+
+
+def project_id_from_scope_id(scope_id: Any) -> str | None:
+ if not isinstance(scope_id, str) or not scope_id.startswith(PROJECT_SCOPE_PREFIX):
+ return None
+ project_id = scope_id[len(PROJECT_SCOPE_PREFIX) :].strip()
+ return project_id or None
+
+
+def _safe_string(value: Any, *, code: str, limit: int = 240) -> str:
+ if not isinstance(value, str):
+ raise ProjectAccessIntentError(code)
+ cleaned = value.strip()
+ if (
+ not cleaned
+ or len(cleaned) > limit
+ or any(ord(char) < 32 or ord(char) == 127 for char in cleaned)
+ ):
+ raise ProjectAccessIntentError(code)
+ return cleaned
+
+
+def _revision(value: Any) -> int:
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise ProjectAccessIntentError("invalid_project_access_revision")
+ if value < 0 or value > MAX_CONTROL_PLANE_REVISION:
+ raise ProjectAccessIntentError("invalid_project_access_revision")
+ return value
+
+
+def _normalize_binding(raw: Any) -> dict[str, str]:
+ if not isinstance(raw, Mapping):
+ raise ProjectAccessIntentError("invalid_project_access_binding")
+ if set(raw) != {"principal_kind", "principal_value", "access_role"}:
+ raise ProjectAccessIntentError("invalid_project_access_binding")
+ kind = _safe_string(raw.get("principal_kind"), code="invalid_project_access_binding")
+ if kind not in PROJECT_PRINCIPAL_KINDS:
+ raise ProjectAccessIntentError("invalid_project_access_binding")
+ role = _safe_string(raw.get("access_role"), code="invalid_project_access_binding")
+ if role not in PROJECT_ACCESS_ROLES:
+ raise ProjectAccessIntentError("invalid_project_access_binding")
+ value = _safe_string(
+ raw.get("principal_value"),
+ code="invalid_project_access_binding",
+ limit=320,
+ )
+ if kind != "organization_group":
+ value = value.lower()
+ if kind == "email" and not _EMAIL_RE.fullmatch(value):
+ raise ProjectAccessIntentError("invalid_project_access_email")
+ if kind == "email_domain" and not _DOMAIN_RE.fullmatch(value):
+ raise ProjectAccessIntentError("invalid_project_access_domain")
+ if kind == "organization_group" and any(char in value for char in ("/", "\\")):
+ raise ProjectAccessIntentError("invalid_project_access_group")
+ return {"principal_kind": kind, "principal_value": value, "access_role": role}
+
+
+def validate_project_access_intent(intent: Any) -> dict[str, Any]:
+ if not isinstance(intent, Mapping):
+ raise ProjectAccessIntentError("invalid_project_access_intent")
+ if set(intent) - {"project_id", "revision", "mode", "bindings", "organization_id"}:
+ raise ProjectAccessIntentError("invalid_project_access_intent")
+ project_id = _safe_string(intent.get("project_id"), code="invalid_project_id", limit=200)
+ if any(char in project_id for char in ("/", "\\")):
+ raise ProjectAccessIntentError("invalid_project_id")
+ revision = _revision(intent.get("revision"))
+ mode = _safe_string(intent.get("mode"), code="invalid_project_access_mode")
+ if mode not in PROJECT_ACCESS_MODES:
+ raise ProjectAccessIntentError("invalid_project_access_mode")
+ raw_bindings = intent.get("bindings")
+ if not isinstance(raw_bindings, list) or len(raw_bindings) > 512:
+ raise ProjectAccessIntentError("invalid_project_access_bindings")
+ bindings = [_normalize_binding(binding) for binding in raw_bindings]
+ if mode == "inherit" and bindings:
+ raise ProjectAccessIntentError("invalid_project_access_bindings")
+ keys = {(item["principal_kind"], item["principal_value"]) for item in bindings}
+ if len(keys) != len(bindings):
+ raise ProjectAccessIntentError("duplicate_project_access_principal")
+ organization_id = intent.get("organization_id")
+ if organization_id is not None:
+ organization_id = _safe_string(
+ organization_id,
+ code="invalid_project_access_organization",
+ limit=200,
+ )
+ return {
+ "project_id": project_id,
+ "revision": revision,
+ "mode": mode,
+ "bindings": bindings,
+ "organization_id": organization_id,
+ }
+
+
+def _active_project_scope(conn: Connection, project_id: str) -> str | None:
+ scope_id = project_scope_id(project_id)
+ row = conn.execute(
+ select(scopes.c.id, scope_settings.c.enabled)
+ .select_from(scopes.outerjoin(scope_settings, scope_settings.c.scope_id == scopes.c.id))
+ .where(
+ scopes.c.id == scope_id,
+ scopes.c.platform == "avibe",
+ scopes.c.scope_type == "project",
+ )
+ .limit(1)
+ ).first()
+ if row is None or row.enabled == 0:
+ return None
+ return str(row.id)
+
+
+def apply_project_access_intent(
+ conn: Connection,
+ intent: Any,
+ *,
+ now: str | None = None,
+) -> ProjectAccessIntentResult:
+ """Atomically apply a newer validated intent or classify a replay/stale intent."""
+
+ try:
+ normalized = validate_project_access_intent(intent)
+ except ProjectAccessIntentError as error:
+ project_id = str(intent.get("project_id") or "") if isinstance(intent, Mapping) else ""
+ revision = intent.get("revision", 0) if isinstance(intent, Mapping) else 0
+ return ProjectAccessIntentResult(
+ project_id=project_id,
+ revision=revision if isinstance(revision, int) and not isinstance(revision, bool) else 0,
+ outcome="rejected",
+ error_code=error.code,
+ )
+
+ project_id = normalized["project_id"]
+ revision = normalized["revision"]
+ scope_id = _active_project_scope(conn, project_id)
+ if scope_id is None:
+ return ProjectAccessIntentResult(
+ project_id=project_id,
+ revision=revision,
+ outcome="rejected",
+ error_code="project_not_found",
+ )
+
+ current = conn.execute(
+ select(project_access_policies).where(project_access_policies.c.project_id == project_id)
+ ).mappings().first()
+ applied_revision = int(current["last_applied_control_plane_revision"] or 0) if current else 0
+ if revision < applied_revision:
+ return ProjectAccessIntentResult(
+ project_id=project_id,
+ revision=revision,
+ outcome="stale",
+ )
+ if revision == applied_revision and current is not None:
+ return ProjectAccessIntentResult(
+ project_id=project_id,
+ revision=revision,
+ outcome="applied",
+ )
+
+ timestamp = now or _utc_now_iso()
+ policy_revision = (int(current["policy_revision"] or 0) if current else 0) + 1
+ statement = sqlite_insert(project_access_policies).values(
+ project_id=project_id,
+ scope_id=scope_id,
+ organization_id=normalized["organization_id"],
+ mode=normalized["mode"],
+ policy_revision=policy_revision,
+ last_applied_control_plane_revision=revision,
+ created_at=current["created_at"] if current else timestamp,
+ updated_at=timestamp,
+ )
+ conn.execute(
+ statement.on_conflict_do_update(
+ index_elements=[project_access_policies.c.project_id],
+ set_={
+ "scope_id": scope_id,
+ "organization_id": normalized["organization_id"],
+ "mode": normalized["mode"],
+ "policy_revision": policy_revision,
+ "last_applied_control_plane_revision": revision,
+ "updated_at": timestamp,
+ },
+ )
+ )
+ conn.execute(
+ delete(project_access_bindings).where(project_access_bindings.c.project_id == project_id)
+ )
+ if normalized["bindings"]:
+ conn.execute(
+ insert(project_access_bindings),
+ [
+ {"project_id": project_id, **binding, "created_at": timestamp}
+ for binding in normalized["bindings"]
+ ],
+ )
+ return ProjectAccessIntentResult(
+ project_id=project_id,
+ revision=revision,
+ outcome="applied",
+ changed=True,
+ )
+
+
+def get_project_policy(conn: Connection, project_id: str) -> dict[str, Any] | None:
+ policy = conn.execute(
+ select(project_access_policies).where(project_access_policies.c.project_id == project_id)
+ ).mappings().first()
+ if policy is None:
+ return None
+ bindings = conn.execute(
+ select(project_access_bindings)
+ .where(project_access_bindings.c.project_id == project_id)
+ .order_by(
+ project_access_bindings.c.principal_kind,
+ project_access_bindings.c.principal_value,
+ )
+ ).mappings().all()
+ return {**dict(policy), "bindings": [dict(binding) for binding in bindings]}
+
+
+def _matching_binding_role(
+ context: AuthorizationContext,
+ policy: Mapping[str, Any],
+ bindings: Sequence[Mapping[str, Any]],
+) -> str | None:
+ email = (context.email or "").strip().lower()
+ domain = email.rsplit("@", 1)[1] if "@" in email else ""
+ policy_organization_id = str(policy.get("organization_id") or "").strip()
+ roles: list[str] = []
+ for binding in bindings:
+ kind = str(binding.get("principal_kind") or "")
+ value = str(binding.get("principal_value") or "")
+ if kind == "email" and email and value == email:
+ roles.append(str(binding.get("access_role") or ""))
+ elif kind == "email_domain" and domain and value == domain:
+ roles.append(str(binding.get("access_role") or ""))
+ elif (
+ kind == "organization_group"
+ and value in context.group_ids
+ and (not policy_organization_id or policy_organization_id == context.organization_id)
+ ):
+ roles.append(str(binding.get("access_role") or ""))
+ valid_roles = [role for role in roles if role in PROJECT_ACCESS_ROLES]
+ return max(valid_roles, key=_ROLE_RANK.__getitem__) if valid_roles else None
+
+
+def get_effective_project_role(
+ conn: Connection,
+ context: AuthorizationContext,
+ project_id: str,
+) -> str | None:
+ if context.is_instance_owner:
+ return "owner"
+ instance_role = context.instance_role
+ if instance_role not in _ROLE_RANK:
+ return None
+ policy = get_project_policy(conn, project_id)
+ if policy is None or policy["mode"] == "inherit":
+ return instance_role
+ binding_role = _matching_binding_role(context, policy, policy["bindings"])
+ if binding_role is None:
+ return None
+ return min((instance_role, binding_role), key=_ROLE_RANK.__getitem__)
+
+
+def role_allows(role: str | None, minimum_role: str) -> bool:
+ return _ROLE_RANK.get(role or "", 0) >= _ROLE_RANK.get(minimum_role, 1 << 30)
+
+
+def can_read_project(conn: Connection, context: AuthorizationContext, project_id: str) -> bool:
+ return role_allows(get_effective_project_role(conn, context, project_id), "viewer")
+
+
+def can_chat_project(conn: Connection, context: AuthorizationContext, project_id: str) -> bool:
+ return role_allows(get_effective_project_role(conn, context, project_id), "editor")
+
+
+def can_manage_project(conn: Connection, context: AuthorizationContext, project_id: str) -> bool:
+ return get_effective_project_role(conn, context, project_id) == "owner"
+
+
+def filter_accessible_projects(
+ conn: Connection,
+ context: AuthorizationContext,
+ projects: Iterable[Mapping[str, Any]],
+) -> list[dict[str, Any]]:
+ return [
+ dict(project)
+ for project in projects
+ if can_read_project(conn, context, str(project.get("id") or ""))
+ ]
+
+
+def get_effective_session_role(
+ conn: Connection,
+ context: AuthorizationContext,
+ session_id: str,
+) -> str | None:
+ scope_id = conn.execute(
+ select(agent_sessions.c.scope_id).where(agent_sessions.c.id == session_id).limit(1)
+ ).scalar_one_or_none()
+ project_id = project_id_from_scope_id(scope_id)
+ if project_id is None:
+ return "owner" if context.is_instance_owner else None
+ return get_effective_project_role(conn, context, project_id)
+
+
+def accessible_project_ids(
+ conn: Connection,
+ context: AuthorizationContext,
+ *,
+ include_archived: bool = False,
+) -> set[str]:
+ query = (
+ select(scopes.c.native_id, scope_settings.c.enabled)
+ .select_from(scopes.outerjoin(scope_settings, scope_settings.c.scope_id == scopes.c.id))
+ .where(scopes.c.platform == "avibe", scopes.c.scope_type == "project")
+ )
+ return {
+ str(row.native_id)
+ for row in conn.execute(query)
+ if (include_archived or row.enabled is None or row.enabled != 0)
+ and can_read_project(conn, context, str(row.native_id))
+ }
diff --git a/storage/projects_service.py b/storage/projects_service.py
index 2ae163cb8..e990b7594 100644
--- a/storage/projects_service.py
+++ b/storage/projects_service.py
@@ -21,6 +21,7 @@ from typing import Any, Mapping, Optional
from sqlalchemy import select, update
from sqlalchemy.engine import Connection
+from storage import project_access_service
from storage.models import agents, scope_settings, scopes
from vibe.authorization import AuthorizationContext, require_instance_role
@@ -186,7 +187,12 @@ def _write_scope_settings(conn: Connection, scope_id: str, values: dict[str, Any
conn.execute(update(scope_settings).where(scope_settings.c.scope_id == scope_id).values(**values))
-def list_projects(conn: Connection, *, include_archived: bool = False) -> list[dict[str, Any]]:
+def list_projects(
+ conn: Connection,
+ *,
+ include_archived: bool = False,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
+) -> list[dict[str, Any]]:
"""Return all avibe projects sorted by recency, optionally including archived ones."""
query = (
@@ -205,10 +211,19 @@ def list_projects(conn: Connection, *, include_archived: bool = False) -> list[d
if not include_archived and not enabled:
continue
out.append(_project_dict(row))
- return out
+ context = require_instance_role(authorization_context, "viewer")
+ return project_access_service.filter_accessible_projects(conn, context, out)
-def get_project(conn: Connection, project_id: str) -> dict[str, Any]:
+def get_project(
+ conn: Connection,
+ project_id: str,
+ *,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
+) -> dict[str, Any]:
+ context = require_instance_role(authorization_context, "viewer")
+ if not project_access_service.can_read_project(conn, context, project_id):
+ raise LookupError(f"Project not found: {project_id}")
scope_id = _make_scope_id(project_id)
return _project_payload(conn, scope_id)
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index 3d32f9964..88fdc9e76 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -24,6 +24,7 @@ from sqlalchemy import and_, func, or_, select, update
from sqlalchemy.engine import Connection
from config import paths
+from storage import project_access_service
from vibe.authorization import AuthorizationContext, require_instance_role
from storage.agent_session_rows import (
SESSION_VISIBILITIES,
@@ -123,6 +124,7 @@ def list_sessions(
limit: int = 50,
before_id: Optional[str] = None,
title_query: Optional[str] = None,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
) -> dict[str, Any]:
"""Return sessions for the workbench list. Cursor pagination via ``before_id``.
@@ -135,7 +137,18 @@ def list_sessions(
case-insensitive title LIKE match (LIKE metacharacters escaped).
"""
+ context = require_instance_role(authorization_context, "viewer")
query = select(agent_sessions).where(agent_sessions.c.visibility == "foreground")
+ if not context.is_instance_owner:
+ accessible_scope_ids = {
+ project_access_service.project_scope_id(project_id)
+ for project_id in project_access_service.accessible_project_ids(conn, context)
+ }
+ if scope_id is not None and scope_id not in accessible_scope_ids:
+ return {"sessions": [], "next_before_id": None}
+ if not accessible_scope_ids:
+ return {"sessions": [], "next_before_id": None}
+ query = query.where(agent_sessions.c.scope_id.in_(accessible_scope_ids))
if scope_id is not None:
query = query.where(agent_sessions.c.scope_id == scope_id)
if status is not None and status != "all":
@@ -205,12 +218,24 @@ def list_sessions(
return {"sessions": sessions, "next_before_id": next_cursor}
-def get_session(conn: Connection, session_id: str) -> dict[str, Any]:
+def get_session(
+ conn: Connection,
+ session_id: str,
+ *,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
+) -> dict[str, Any]:
+ context = require_instance_role(authorization_context, "viewer")
row = conn.execute(
select(agent_sessions).where(agent_sessions.c.id == session_id)
).mappings().first()
if row is None:
raise LookupError(f"Session not found: {session_id}")
+ if not context.is_instance_owner:
+ project_id = project_access_service.project_id_from_scope_id(row["scope_id"])
+ if project_id is None or not project_access_service.can_read_project(
+ conn, context, project_id
+ ):
+ raise LookupError(f"Session not found: {session_id}")
return _row_to_payload(dict(row))
@@ -291,7 +316,13 @@ def create_session(
Codex fill it on their first turn.
"""
- require_instance_role(authorization_context, "editor")
+ context = require_instance_role(authorization_context, "editor")
+ if not context.is_instance_owner:
+ project_id = project_access_service.project_id_from_scope_id(scope_id)
+ if project_id is None or not project_access_service.can_chat_project(
+ conn, context, project_id
+ ):
+ raise PermissionError("Project access denied")
scope_row: dict[str, Any] = {}
if scope_id is not None:
found = conn.execute(
@@ -404,7 +435,7 @@ def update_session(
scope_id: Any = _UNSET,
authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
) -> dict[str, Any]:
- require_instance_role(authorization_context, "editor")
+ context = require_instance_role(authorization_context, "editor")
existing = conn.execute(
select(
agent_sessions.c.id,
@@ -417,6 +448,18 @@ def update_session(
).first()
if existing is None:
raise LookupError(f"Session not found: {session_id}")
+ if not context.is_instance_owner:
+ project_id = project_access_service.project_id_from_scope_id(existing.scope_id)
+ if project_id is None or not project_access_service.can_chat_project(
+ conn, context, project_id
+ ):
+ raise LookupError(f"Session not found: {session_id}")
+ if scope_id is not _UNSET:
+ target_project_id = project_access_service.project_id_from_scope_id(scope_id)
+ if target_project_id is None or not project_access_service.can_chat_project(
+ conn, context, target_project_id
+ ):
+ raise LookupError(f"Session not found: {session_id}")
derived_backend = False
if agent_name is not _UNSET and agent_backend is _UNSET:
@@ -928,12 +971,18 @@ def archive_session(
Returns the archived session payload plus a ``reclaimed`` summary
(``{tasks, watches, runs}``) for the confirm-dialog / post-archive notice.
"""
- require_instance_role(authorization_context, "editor")
+ context = require_instance_role(authorization_context, "editor")
existing = conn.execute(
select(agent_sessions.c.id).where(agent_sessions.c.id == session_id)
).scalar_one_or_none()
if existing is None:
raise LookupError(f"Session not found: {session_id}")
+ if not context.is_instance_owner:
+ if not project_access_service.role_allows(
+ project_access_service.get_effective_session_role(conn, context, session_id),
+ "editor",
+ ):
+ raise LookupError(f"Session not found: {session_id}")
now = _utc_now_iso()
# 1) Mark archived + clear any stale "running" dot, and VACATE the thread
diff --git a/tests/test_project_access_service.py b/tests/test_project_access_service.py
new file mode 100644
index 000000000..c1791c67e
--- /dev/null
+++ b/tests/test_project_access_service.py
@@ -0,0 +1,307 @@
+from __future__ import annotations
+
+import sqlalchemy as sa
+
+from storage import project_access_service, projects_service
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import project_access_bindings, project_access_policies
+from vibe.authorization import AuthorizationContext, trusted_local_context
+
+
+def _context(
+ role: str,
+ *,
+ email: str = "[email protected]",
+ organization_id: str | None = None,
+ group_ids: tuple[str, ...] = (),
+) -> AuthorizationContext:
+ return AuthorizationContext(
+ instance_role=role,
+ email=email,
+ organization_id=organization_id,
+ group_ids=frozenset(group_ids),
+ is_remote=True,
+ )
+
+
+def _engine_with_project(tmp_path):
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ folder = tmp_path / "project"
+ folder.mkdir()
+ with engine.begin() as conn:
+ project = projects_service.create_project(conn, str(folder), display_name="Project One")
+ return engine, project
+
+
+def _intent(project_id: str, revision: int, *, mode="restricted", bindings=None):
+ return {
+ "project_id": project_id,
+ "revision": revision,
+ "mode": mode,
+ "bindings": bindings or [],
+ }
+
+
+def test_migration_creates_project_policy_schema(tmp_path) -> None:
+ engine, _project = _engine_with_project(tmp_path)
+ inspector = sa.inspect(engine)
+
+ assert "project_access_policies" in inspector.get_table_names()
+ assert "project_access_bindings" in inspector.get_table_names()
+ assert {column["name"] for column in inspector.get_columns("project_access_policies")} >= {
+ "project_id",
+ "scope_id",
+ "organization_id",
+ "mode",
+ "policy_revision",
+ "last_applied_control_plane_revision",
+ }
+ foreign_keys = inspector.get_foreign_keys("project_access_bindings")
+ assert foreign_keys[0]["referred_table"] == "project_access_policies"
+ assert foreign_keys[0]["options"]["ondelete"] == "CASCADE"
+
+
+def test_missing_and_inherit_policies_preserve_instance_role(tmp_path) -> None:
+ engine, project = _engine_with_project(tmp_path)
+ editor = _context("editor")
+
+ with engine.begin() as conn:
+ assert project_access_service.get_effective_project_role(conn, editor, project["id"]) == "editor"
+ result = project_access_service.apply_project_access_intent(
+ conn,
+ _intent(project["id"], 1, mode="inherit"),
+ )
+ assert result.outcome == "applied"
+ assert project_access_service.get_effective_project_role(conn, editor, project["id"]) == "editor"
+
+
+def test_restricted_policy_matches_email_domain_and_group(tmp_path) -> None:
+ engine, project = _engine_with_project(tmp_path)
+ intent = _intent(
+ project["id"],
+ 1,
+ bindings=[
+ {
+ "principal_kind": "email",
+ "principal_value": "[email protected]",
+ "access_role": "viewer",
+ },
+ {
+ "principal_kind": "email_domain",
+ "principal_value": "Example.com",
+ "access_role": "editor",
+ },
+ {
+ "principal_kind": "organization_group",
+ "principal_value": "grp_engineering",
+ "access_role": "editor",
+ },
+ ],
+ )
+ with engine.begin() as conn:
+ assert project_access_service.apply_project_access_intent(conn, intent).outcome == "applied"
+ assert (
+ project_access_service.get_effective_project_role(
+ conn,
+ _context("editor", email="[email protected]"),
+ project["id"],
+ )
+ == "editor"
+ )
+ assert (
+ project_access_service.get_effective_project_role(
+ conn,
+ _context("editor", email="[email protected]", group_ids=("grp_engineering",)),
+ project["id"],
+ )
+ == "editor"
+ )
+ assert (
+ project_access_service.get_effective_project_role(
+ conn,
+ _context("editor", email="[email protected]"),
+ project["id"],
+ )
+ is None
+ )
+
+
+def test_highest_match_is_capped_by_instance_role(tmp_path) -> None:
+ engine, project = _engine_with_project(tmp_path)
+ intent = _intent(
+ project["id"],
+ 1,
+ bindings=[
+ {
+ "principal_kind": "email",
+ "principal_value": "[email protected]",
+ "access_role": "viewer",
+ },
+ {
+ "principal_kind": "email_domain",
+ "principal_value": "example.com",
+ "access_role": "editor",
+ },
+ ],
+ )
+ with engine.begin() as conn:
+ project_access_service.apply_project_access_intent(conn, intent)
+ assert project_access_service.get_effective_project_role(
+ conn, _context("viewer"), project["id"]
+ ) == "viewer"
+ assert project_access_service.get_effective_project_role(
+ conn, _context("editor"), project["id"]
+ ) == "editor"
+
+
+def test_restricted_empty_bindings_is_owner_only(tmp_path) -> None:
+ engine, project = _engine_with_project(tmp_path)
+ with engine.begin() as conn:
+ project_access_service.apply_project_access_intent(
+ conn,
+ _intent(project["id"], 1),
+ )
+ assert project_access_service.can_read_project(conn, _context("editor"), project["id"]) is False
+ assert project_access_service.can_read_project(conn, trusted_local_context(), project["id"]) is True
+ assert project_access_service.can_manage_project(conn, _context("owner"), project["id"]) is True
+
+
+def test_organization_binding_respects_policy_organization(tmp_path) -> None:
+ engine, project = _engine_with_project(tmp_path)
+ intent = {
+ **_intent(
+ project["id"],
+ 1,
+ bindings=[
+ {
+ "principal_kind": "organization_group",
+ "principal_value": "grp_engineering",
+ "access_role": "editor",
+ }
+ ],
+ ),
+ "organization_id": "org_expected",
+ }
+ with engine.begin() as conn:
+ project_access_service.apply_project_access_intent(conn, intent)
+ assert project_access_service.can_chat_project(
+ conn,
+ _context(
+ "editor",
+ organization_id="org_expected",
+ group_ids=("grp_engineering",),
+ ),
+ project["id"],
+ ) is True
+ assert project_access_service.can_read_project(
+ conn,
+ _context(
+ "editor",
+ organization_id="org_other",
+ group_ids=("grp_engineering",),
+ ),
+ project["id"],
+ ) is False
+
+
+def test_newer_duplicate_and_stale_intents_are_idempotent(tmp_path) -> None:
+ engine, project = _engine_with_project(tmp_path)
+ first = _intent(
+ project["id"],
+ 3,
+ bindings=[
+ {
+ "principal_kind": "email",
+ "principal_value": "[email protected]",
+ "access_role": "viewer",
+ }
+ ],
+ )
+ with engine.begin() as conn:
+ applied = project_access_service.apply_project_access_intent(conn, first)
+ duplicate = project_access_service.apply_project_access_intent(conn, first)
+ stale = project_access_service.apply_project_access_intent(
+ conn,
+ _intent(project["id"], 2),
+ )
+ policy = project_access_service.get_project_policy(conn, project["id"])
+
+ assert applied.changed is True
+ assert duplicate == project_access_service.ProjectAccessIntentResult(
+ project_id=project["id"], revision=3, outcome="applied"
+ )
+ assert stale.outcome == "stale"
+ assert policy is not None
+ assert policy["policy_revision"] == 1
+ assert policy["last_applied_control_plane_revision"] == 3
+ assert len(policy["bindings"]) == 1
+
+
+def test_invalid_or_duplicate_bindings_fail_without_replacing_policy(tmp_path) -> None:
+ engine, project = _engine_with_project(tmp_path)
+ valid = _intent(
+ project["id"],
+ 1,
+ bindings=[
+ {
+ "principal_kind": "email",
+ "principal_value": "[email protected]",
+ "access_role": "editor",
+ }
+ ],
+ )
+ duplicate = _intent(project["id"], 2, bindings=[valid["bindings"][0], valid["bindings"][0]])
+ with engine.begin() as conn:
+ project_access_service.apply_project_access_intent(conn, valid)
+ rejected = project_access_service.apply_project_access_intent(conn, duplicate)
+ policy = project_access_service.get_project_policy(conn, project["id"])
+
+ assert rejected.outcome == "rejected"
+ assert rejected.error_code == "duplicate_project_access_principal"
+ assert policy is not None
+ assert policy["last_applied_control_plane_revision"] == 1
+ assert policy["bindings"][0]["access_role"] == "editor"
+
+
+def test_archived_or_missing_project_intent_is_rejected(tmp_path) -> None:
+ engine, project = _engine_with_project(tmp_path)
+ with engine.begin() as conn:
+ projects_service.archive_project(conn, project["id"])
+ result = project_access_service.apply_project_access_intent(
+ conn,
+ _intent(project["id"], 1),
+ )
+ assert result.outcome == "rejected"
+ assert result.error_code == "project_not_found"
+
+
+def test_policy_delete_cascades_bindings(tmp_path) -> None:
+ engine, project = _engine_with_project(tmp_path)
+ with engine.begin() as conn:
+ project_access_service.apply_project_access_intent(
+ conn,
+ _intent(
+ project["id"],
+ 1,
+ bindings=[
+ {
+ "principal_kind": "email",
+ "principal_value": "[email protected]",
+ "access_role": "editor",
+ }
+ ],
+ ),
+ )
+ conn.execute(
+ project_access_policies.delete().where(
+ project_access_policies.c.project_id == project["id"]
+ )
+ )
+ remaining = conn.execute(
+ project_access_bindings.select().where(
+ project_access_bindings.c.project_id == project["id"]
+ )
+ ).all()
+ assert remaining == []
diff --git a/tests/test_project_access_sync.py b/tests/test_project_access_sync.py
new file mode 100644
index 000000000..c77faa23c
--- /dev/null
+++ b/tests/test_project_access_sync.py
@@ -0,0 +1,292 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import requests
+
+from config.v2_config import (
+ AgentsConfig,
+ RemoteAccessConfig,
+ RuntimeConfig,
+ SlackConfig,
+ V2Config,
+)
+from storage import project_access_service, projects_service
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from vibe import project_access_sync
+
+
+@dataclass
+class _Response:
+ payload: dict
+ status_code: int = 200
+
+ @property
+ def ok(self) -> bool:
+ return 200 <= self.status_code < 300
+
+ def json(self):
+ return self.payload
+
+
+def _config() -> V2Config:
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ slack=SlackConfig(bot_token=""),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ remote_access=RemoteAccessConfig(),
+ )
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.backend_url = "https://control.example"
+ cloud.instance_id = "inst_123"
+ cloud.instance_secret = "device-secret"
+ return config
+
+
+def _create_project(tmp_path, name: str = "Project One"):
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ folder = tmp_path / name.replace(" ", "-").lower()
+ folder.mkdir()
+ with engine.begin() as conn:
+ project = projects_service.create_project(conn, str(folder), display_name=name)
+ return engine, project
+
+
+def test_project_index_descriptors_exclude_local_content(tmp_path) -> None:
+ engine, active = _create_project(tmp_path)
+ archived_folder = tmp_path / "archived"
+ archived_folder.mkdir()
+ with engine.begin() as conn:
+ archived = projects_service.create_project(
+ conn,
+ str(archived_folder),
+ display_name="Archived Project",
+ )
+ project_access_service.apply_project_access_intent(
+ conn,
+ {
+ "project_id": active["id"],
+ "revision": 4,
+ "mode": "inherit",
+ "bindings": [],
+ },
+ )
+ projects_service.archive_project(conn, archived["id"])
+
+ descriptors = project_access_sync.project_index_descriptors()
+ by_id = {descriptor["project_id"]: descriptor for descriptor in descriptors}
+
+ assert set(by_id[active["id"]]) == {
+ "project_id",
+ "display_name",
+ "metadata_revision",
+ "applied_access_revision",
+ "sync_status",
+ }
+ assert by_id[active["id"]]["applied_access_revision"] == 4
+ assert by_id[active["id"]]["sync_status"] == "in_sync"
+ assert by_id[archived["id"]]["sync_status"] == "deleted"
+ serialized = repr(descriptors)
+ assert str(tmp_path) not in serialized
+ assert "folder_path" not in serialized
+
+
+def test_sync_publishes_applies_and_acks_exact_revision(monkeypatch, tmp_path) -> None:
+ engine, project = _create_project(tmp_path)
+ calls: list[tuple[str, str, dict | None]] = []
+
+ def request(method, url, **kwargs):
+ calls.append((method, url, kwargs.get("json")))
+ assert kwargs["headers"]["X-Vibe-Device-Secret"] == "device-secret"
+ if url.endswith("/project-index"):
+ return _Response({"poll_after_seconds": 30, "projects": []})
+ if url.endswith("/project-access-intents"):
+ return _Response(
+ {
+ "poll_after_seconds": 45,
+ "intents": [
+ {
+ "project_id": project["id"],
+ "revision": 2,
+ "mode": "restricted",
+ "bindings": [
+ {
+ "principal_kind": "email",
+ "principal_value": "[email protected]",
+ "access_role": "editor",
+ }
+ ],
+ }
+ ],
+ }
+ )
+ return _Response({"project": {}})
+
+ monkeypatch.setattr(project_access_sync.requests, "request", request)
+ result = project_access_sync.sync_project_access_once(_config())
+
+ assert result == {
+ "ok": True,
+ "configured": True,
+ "projects": 1,
+ "intents": 1,
+ "applied": 1,
+ "rejected": 0,
+ "stale": 0,
+ "ack_errors": 0,
+ "poll_after_seconds": 45,
+ }
+ assert calls[-1] == (
+ "POST",
+ f"https://control.example/api/v1/instances/inst_123/project-access-acks",
+ {"project_id": project["id"], "revision": 2, "outcome": "applied"},
+ )
+ with engine.connect() as conn:
+ policy = project_access_service.get_project_policy(conn, project["id"])
+ assert policy is not None
+ assert policy["last_applied_control_plane_revision"] == 2
+
+
+def test_lost_ack_retries_without_reapplying_policy(monkeypatch, tmp_path) -> None:
+ engine, project = _create_project(tmp_path)
+ ack_attempts = 0
+
+ def request(method, url, **kwargs):
+ nonlocal ack_attempts
+ if url.endswith("/project-index"):
+ return _Response({"poll_after_seconds": 30, "projects": []})
+ if url.endswith("/project-access-intents"):
+ return _Response(
+ {
+ "poll_after_seconds": 30,
+ "intents": [
+ {
+ "project_id": project["id"],
+ "revision": 1,
+ "mode": "restricted",
+ "bindings": [],
+ }
+ ],
+ }
+ )
+ ack_attempts += 1
+ if ack_attempts == 1:
+ raise requests.ConnectionError("lost response")
+ return _Response({"project": {}})
+
+ monkeypatch.setattr(project_access_sync.requests, "request", request)
+
+ first = project_access_sync.sync_project_access_once(_config())
+ second = project_access_sync.sync_project_access_once(_config())
+
+ assert first["ack_errors"] == 1
+ assert second["ack_errors"] == 0
+ assert ack_attempts == 2
+ with engine.connect() as conn:
+ policy = project_access_service.get_project_policy(conn, project["id"])
+ assert policy is not None
+ assert policy["policy_revision"] == 1
+ assert policy["last_applied_control_plane_revision"] == 1
+
+
+def test_invalid_intent_is_rejected_with_exact_ack(monkeypatch, tmp_path) -> None:
+ _engine, project = _create_project(tmp_path)
+ ack_payloads: list[dict] = []
+
+ def request(method, url, **kwargs):
+ if url.endswith("/project-index"):
+ return _Response({"projects": []})
+ if url.endswith("/project-access-intents"):
+ return _Response(
+ {
+ "intents": [
+ {
+ "project_id": project["id"],
+ "revision": 5,
+ "mode": "unknown",
+ "bindings": [],
+ }
+ ]
+ }
+ )
+ ack_payloads.append(kwargs["json"])
+ return _Response({"project": {}})
+
+ monkeypatch.setattr(project_access_sync.requests, "request", request)
+ result = project_access_sync.sync_project_access_once(_config())
+
+ assert result["rejected"] == 1
+ assert ack_payloads == [
+ {
+ "project_id": project["id"],
+ "revision": 5,
+ "outcome": "rejected",
+ "error_code": "invalid_project_access_mode",
+ }
+ ]
+
+
+def test_stale_intent_does_not_revert_or_ack(monkeypatch, tmp_path) -> None:
+ engine, project = _create_project(tmp_path)
+ with engine.begin() as conn:
+ project_access_service.apply_project_access_intent(
+ conn,
+ {
+ "project_id": project["id"],
+ "revision": 3,
+ "mode": "inherit",
+ "bindings": [],
+ },
+ )
+ acked = False
+
+ def request(method, url, **kwargs):
+ nonlocal acked
+ if url.endswith("/project-index"):
+ return _Response({"projects": []})
+ if url.endswith("/project-access-intents"):
+ return _Response(
+ {
+ "intents": [
+ {
+ "project_id": project["id"],
+ "revision": 2,
+ "mode": "restricted",
+ "bindings": [],
+ }
+ ]
+ }
+ )
+ acked = True
+ return _Response({"project": {}})
+
+ monkeypatch.setattr(project_access_sync.requests, "request", request)
+ result = project_access_sync.sync_project_access_once(_config())
+
+ assert result["stale"] == 1
+ assert acked is False
+ with engine.connect() as conn:
+ policy = project_access_service.get_project_policy(conn, project["id"])
+ assert policy is not None
+ assert policy["mode"] == "inherit"
+ assert policy["last_applied_control_plane_revision"] == 3
+
+
+def test_unconfigured_sync_is_a_noop(monkeypatch) -> None:
+ monkeypatch.setattr(
+ project_access_sync.requests,
+ "request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("network called")),
+ )
+
+ config = _config()
+ config.remote_access.vibe_cloud.enabled = False
+ result = project_access_sync.sync_project_access_once(config)
+
+ assert result["ok"] is False
+ assert result["configured"] is False
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index e021cc304..318ac1154 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -19,7 +19,7 @@ from storage.models import metadata
from storage.settings_service import SQLiteSettingsService
-HEAD_REVISION = "20260724_0034"
+HEAD_REVISION = "20260725_0035"
def _index_sql(conn: sqlite3.Connection, name: str) -> str:
@@ -54,6 +54,8 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
assert "web_push_subscriptions" in tables
assert "vault_auth_factors" in tables
assert "vault_operation_challenges" in tables
+ assert "project_access_policies" in tables
+ assert "project_access_bindings" in tables
agent_event_indexes = {
row[1]
for row in conn.execute(
diff --git a/tests/test_ui_project_access.py b/tests/test_ui_project_access.py
new file mode 100644
index 000000000..6c53fafda
--- /dev/null
+++ b/tests/test_ui_project_access.py
@@ -0,0 +1,310 @@
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+from config.v2_config import (
+ AgentsConfig,
+ PlatformsConfig,
+ RemoteAccessConfig,
+ RuntimeConfig,
+ SlackConfig,
+ UiConfig,
+ V2Config,
+)
+from storage import media_service, messages_service, project_access_service, projects_service
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.workbench_sessions_service import create_session
+from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie
+from vibe import api, remote_access, ui_server
+from vibe.authorization import AuthorizationContext
+from vibe.ui_server import app
+
+
+REMOTE_ORIGIN = "https://alex.avibe.bot"
+REMOTE_PEER = {"REMOTE_ADDR": "203.0.113.10"}
+
+
+def _save_config() -> V2Config:
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ platform="slack",
+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),
+ slack=SlackConfig(bot_token=""),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ ui=UiConfig(),
+ remote_access=RemoteAccessConfig(),
+ )
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.public_url = REMOTE_ORIGIN
+ cloud.client_id = "vr_client_123"
+ cloud.instance_id = "inst_123"
+ cloud.session_secret = "session-secret"
+ cloud.authorization_endpoint = "https://backend.test/oauth/authorize"
+ cloud.redirect_uri = f"{REMOTE_ORIGIN}/auth/callback"
+ config.save()
+ return config
+
+
+def _intent(project_id: str, email: str, role: str = "editor") -> dict:
+ return {
+ "project_id": project_id,
+ "revision": 1,
+ "mode": "restricted",
+ "bindings": [
+ {
+ "principal_kind": "email",
+ "principal_value": email,
+ "access_role": role,
+ }
+ ],
+ }
+
+
+def _group_intent(project_id: str, group_id: str, role: str = "editor") -> dict:
+ return {
+ "project_id": project_id,
+ "revision": 1,
+ "mode": "restricted",
+ "bindings": [
+ {
+ "principal_kind": "organization_group",
+ "principal_value": group_id,
+ "access_role": role,
+ }
+ ],
+ }
+
+
+def _setup_state(tmp_path) -> tuple[V2Config, dict[str, str]]:
+ config = _save_config()
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ project_a_dir = tmp_path / "project-a"
+ project_b_dir = tmp_path / "project-b"
+ project_a_dir.mkdir()
+ project_b_dir.mkdir()
+ media_a = tmp_path / "a.txt"
+ media_b = tmp_path / "b.txt"
+ media_a.write_text("project a", encoding="utf-8")
+ media_b.write_text("project b", encoding="utf-8")
+ with engine.begin() as conn:
+ project_a = projects_service.create_project(conn, str(project_a_dir), display_name="A")
+ project_b = projects_service.create_project(conn, str(project_b_dir), display_name="B")
+ session_a = create_session(conn, scope_id=project_a["scope_id"], agent_backend="codex")
+ session_b = create_session(conn, scope_id=project_b["scope_id"], agent_backend="codex")
+ unscoped = create_session(conn, scope_id=None, agent_backend="codex")
+ for project, session in ((project_a, session_a), (project_b, session_b)):
+ messages_service.append(
+ conn,
+ scope_id=project["scope_id"],
+ session_id=session["id"],
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="shared needle",
+ )
+ media_a_token = media_service.register(
+ conn,
+ scope_id=project_a["scope_id"],
+ session_id=session_a["id"],
+ kind="file",
+ source="agent_reply",
+ local_path=str(media_a.resolve()),
+ )
+ media_b_token = media_service.register(
+ conn,
+ scope_id=project_b["scope_id"],
+ session_id=session_b["id"],
+ kind="file",
+ source="agent_reply",
+ local_path=str(media_b.resolve()),
+ )
+ project_access_service.apply_project_access_intent(
+ conn,
+ _intent(project_a["id"], "[email protected]"),
+ )
+ project_access_service.apply_project_access_intent(
+ conn,
+ _group_intent(project_b["id"], "grp_beta"),
+ )
+ engine.dispose()
+ return config, {
+ "project_a": project_a["id"],
+ "project_b": project_b["id"],
+ "session_a": session_a["id"],
+ "session_b": session_b["id"],
+ "unscoped": unscoped["id"],
+ "media_a": media_a_token,
+ "media_b": media_b_token,
+ }
+
+
+def _remote_client(config: V2Config, *, role: str, email: str):
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(config, email, f"user-{role}-{email}", role=role),
+ domain="alex.avibe.bot",
+ )
+ return client
+
+
+def _get(client, path: str):
+ return client.get(path, base_url=REMOTE_ORIGIN, environ_base=REMOTE_PEER)
+
+
+def test_remote_editor_project_access_filters_every_read_surface(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, ids = _setup_state(tmp_path)
+ client = _remote_client(config, role="editor", email="[email protected]")
+ monkeypatch.setattr(
+ api,
+ "list_show_pages",
+ lambda: {
+ "ok": True,
+ "count": 3,
+ "pages": [
+ {"session_id": ids["session_a"]},
+ {"session_id": ids["session_b"]},
+ {"session_id": ids["unscoped"]},
+ ],
+ },
+ )
+
+ assert [row["id"] for row in _get(client, "/api/projects").get_json()["projects"]] == [
+ ids["project_a"]
+ ]
+ sessions = _get(client, "/api/sessions?status=active").get_json()["sessions"]
+ assert {row["id"] for row in sessions} == {ids["session_a"]}
+ assert _get(client, f"/api/projects/{ids['project_a']}").status_code == 200
+ assert _get(client, f"/api/projects/{ids['project_b']}").status_code == 404
+ assert _get(client, f"/api/sessions/{ids['session_a']}/messages").status_code == 200
+ assert _get(client, f"/api/sessions/{ids['session_b']}/messages").status_code == 404
+ assert _get(client, f"/api/sessions/{ids['unscoped']}").status_code == 404
+
+ search = _get(client, "/api/search/messages?q=needle").get_json()
+ assert [row["session_id"] for row in search["sessions"]] == [ids["session_a"]]
+ inbox = _get(client, "/api/inbox").get_json()
+ assert [row["session_id"] for row in inbox["sessions"]] == [ids["session_a"]]
+ assert set(inbox["unread_by_session"]) == {ids["session_a"]}
+ assert _get(client, f"/api/media/{ids['media_a']}").status_code == 200
+ assert _get(client, f"/api/media/{ids['media_b']}").status_code == 404
+ show_pages = _get(client, "/api/show-pages").get_json()
+ assert show_pages["pages"] == [{"session_id": ids["session_a"]}]
+ assert show_pages["count"] == 1
+
+ headers = csrf_headers(client, REMOTE_ORIGIN)
+ allowed_action = client.post(
+ f"/api/sessions/{ids['session_a']}/attachments",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={},
+ )
+ hidden_action = client.post(
+ f"/api/sessions/{ids['session_b']}/attachments",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={},
+ )
+ assert allowed_action.status_code == 400
+ assert hidden_action.status_code == 404
+
+
+def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, ids = _setup_state(tmp_path)
+
+ viewer = _remote_client(config, role="viewer", email="[email protected]")
+ assert _get(viewer, f"/api/sessions/{ids['session_a']}").status_code == 200
+ assert _get(viewer, f"/api/sessions/{ids['session_b']}").status_code == 404
+ headers = csrf_headers(viewer, REMOTE_ORIGIN)
+ assert viewer.post(
+ "/api/sessions",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={"project_id": ids["project_a"]},
+ ).status_code == 403
+
+ no_match = _remote_client(config, role="editor", email="[email protected]")
+ assert _get(no_match, "/api/projects").get_json()["projects"] == []
+ assert _get(no_match, "/api/sessions").get_json()["sessions"] == []
+ assert _get(no_match, f"/api/sessions/{ids['session_a']}").status_code == 404
+
+ organization_member = app.test_client()
+ organization_member.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ "user-org-member",
+ role="editor",
+ access_source="organization_group",
+ organization_id="org_beta",
+ organization_member_id="member_beta",
+ organization_role="member",
+ group_ids=["grp_beta"],
+ ),
+ domain="alex.avibe.bot",
+ )
+ assert [
+ row["id"] for row in _get(organization_member, "/api/projects").get_json()["projects"]
+ ] == [ids["project_b"]]
+ assert _get(organization_member, f"/api/sessions/{ids['session_b']}").status_code == 200
+ assert _get(organization_member, f"/api/sessions/{ids['session_a']}").status_code == 404
+
+ owner = _remote_client(config, role="owner", email="[email protected]")
+ assert {row["id"] for row in _get(owner, "/api/projects").get_json()["projects"]} == {
+ ids["project_a"],
+ ids["project_b"],
+ }
+ assert _get(owner, f"/api/sessions/{ids['unscoped']}").status_code == 200
+
+ local = app.test_client()
+ local_projects = local.get("/api/projects", base_url="http://localhost").get_json()["projects"]
+ assert {row["id"] for row in local_projects} == {ids["project_a"], ids["project_b"]}
+ assert local.get(f"/api/sessions/{ids['unscoped']}", base_url="http://localhost").status_code == 200
+
+
+def test_project_access_filters_sse_and_show_websocket(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, ids = _setup_state(tmp_path)
+ context = AuthorizationContext(
+ instance_role="editor",
+ is_remote=True,
+ )
+ visible_payload = json.dumps({"type": "session.status", "data": {"session_id": ids["session_a"]}})
+ hidden_payload = json.dumps({"type": "session.status", "data": {"session_id": ids["session_b"]}})
+ assert ui_server._workbench_event_visible_to_context(context, "session.status", visible_payload) is True
+ assert ui_server._workbench_event_visible_to_context(context, "session.status", hidden_payload) is False
+ assert ui_server._workbench_event_visible_to_context(
+ context,
+ "authorization.changed",
+ json.dumps({"type": "authorization.changed", "data": {"project_ids": []}}),
+ ) is True
+
+ cookie = remote_session_cookie(config, "[email protected]", "user-editor", role="editor")
+ websocket = SimpleNamespace(
+ client=SimpleNamespace(host="203.0.113.10"),
+ headers={"host": "alex.avibe.bot"},
+ cookies={remote_access.SESSION_COOKIE_NAME: cookie},
+ url=SimpleNamespace(scheme="wss"),
+ )
+ assert ui_server._show_runtime_websocket_authorized(
+ websocket,
+ minimum_role="viewer",
+ project_session_id=ids["session_a"],
+ ) is True
+ assert ui_server._show_runtime_websocket_authorized(
+ websocket,
+ minimum_role="viewer",
+ project_session_id=ids["session_b"],
+ ) is False
diff --git a/tests/ui_server_test_helpers.py b/tests/ui_server_test_helpers.py
index 2085baf90..be83cb64c 100644
--- a/tests/ui_server_test_helpers.py
+++ b/tests/ui_server_test_helpers.py
@@ -26,14 +26,27 @@ def remote_session_cookie(
*,
role: str = "owner",
access_source: str = "owner",
+ organization_id: str | None = None,
+ organization_member_id: str | None = None,
+ organization_role: str | None = None,
+ group_ids: list[str] | None = None,
) -> str:
+ session_claims: dict[str, object] = {
+ "vibe_instance_id": config.remote_access.vibe_cloud.instance_id,
+ "vibe_instance_role": role,
+ "vibe_instance_access_source": access_source,
+ }
+ if organization_id is not None:
+ session_claims["vibe_organization_id"] = organization_id
+ if organization_member_id is not None:
+ session_claims["vibe_organization_member_id"] = organization_member_id
+ if organization_role is not None:
+ session_claims["vibe_organization_role"] = organization_role
+ if group_ids is not None:
+ session_claims["vibe_group_ids"] = group_ids
return remote_access.make_session_cookie(
config,
email,
subject,
- session_claims={
- "vibe_instance_id": config.remote_access.vibe_cloud.instance_id,
- "vibe_instance_role": role,
- "vibe_instance_access_source": access_source,
- },
+ session_claims=session_claims,
)
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 99e91215f..e1bb22107 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -1096,6 +1096,13 @@ export const ChatPage: React.FC = () => {
void syncTurnState({ quiet: true });
void refreshSessionRowUntilNativeBound();
},
+ onAuthorizationChanged: () => {
+ const currentSessionId = sessionIdRef.current;
+ if (!currentSessionId) return;
+ void api.getSession(currentSessionId, { cache: false })
+ .then((nextSession) => setSession(nextSession))
+ .catch(() => goBack());
+ },
onConnectionState: (state) => {
const connected = state === 'connected';
setEventStreamConnected(connected);
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 8d6913ca6..3e2930b4b 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -933,6 +933,7 @@ export type WorkbenchEventHandlers = {
onConnected?: (data: { sub_id: number; source?: 'browser' | 'controller' }) => void;
onConnectionState?: (state: WorkbenchEventConnectionState) => void;
onEventBridgeStatus?: (data: { connected: boolean }) => void;
+ onAuthorizationChanged?: (data: { project_ids: string[] }) => void;
onMessageNew?: (data: WorkbenchMessage) => void;
// ``visibility`` (contract A6): the backend carries the session's current
// foreground/background on visibility/scope changes so the Inbox can drop /
@@ -2030,6 +2031,22 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
dispatchToWorkbenchHandlers((handlers) => handlers.onConnected?.(connected));
}
});
+ source.addEventListener('authorization.changed', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<{ project_ids: string[] }>(e.data);
+ if (!envelope) return;
+ clearReadCacheMatching((path) =>
+ path.startsWith('/api/projects') ||
+ path.startsWith('/api/workbench/projects-bootstrap') ||
+ path.startsWith('/api/sessions') ||
+ path.startsWith('/api/inbox') ||
+ path.startsWith('/api/search') ||
+ path.startsWith('/api/show-pages'),
+ );
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onAuthorizationChanged?.(envelope.data);
+ });
+ });
source.addEventListener('message.new', (e: MessageEvent) => {
const envelope = parseWorkbenchEnvelope<WorkbenchMessage>(e.data);
if (!envelope) return;
diff --git a/ui/src/context/WorkbenchInboxContext.tsx b/ui/src/context/WorkbenchInboxContext.tsx
index a2dcb42f3..2ed32c7b1 100644
--- a/ui/src/context/WorkbenchInboxContext.tsx
+++ b/ui/src/context/WorkbenchInboxContext.tsx
@@ -227,6 +227,9 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
void reconcile();
}
const disconnect = api.connectWorkbenchEvents({
+ onAuthorizationChanged: () => {
+ void refresh();
+ },
onInboxSessionUpdated: (row) => {
setInboxSessions((prev) => upsertSession(prev, row));
setUnreadBySession((prev) => {
diff --git a/ui/src/context/WorkbenchProjectsContext.tsx b/ui/src/context/WorkbenchProjectsContext.tsx
index 2d6000da4..cc5f638e9 100644
--- a/ui/src/context/WorkbenchProjectsContext.tsx
+++ b/ui/src/context/WorkbenchProjectsContext.tsx
@@ -166,6 +166,22 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const inFlightRef = useRef<Set<string>>(new Set());
const pendingReconcileRef = useRef<Map<string, number>>(new Map());
+ const applyProjectsSnapshot = useCallback((nextProjects: WorkbenchProject[]) => {
+ const accessibleIds = new Set(nextProjects.map((project) => project.id));
+ projectsRef.current = nextProjects;
+ setProjects(nextProjects);
+ setSessions((prev) =>
+ Object.fromEntries(
+ Object.entries(prev).filter(([projectId]) => accessibleIds.has(projectId)),
+ ),
+ );
+ setExpanded((prev) => new Set([...prev].filter((projectId) => accessibleIds.has(projectId))));
+ setCreating((prev) => new Set([...prev].filter((projectId) => accessibleIds.has(projectId))));
+ for (const projectId of [...pendingReconcileRef.current.keys()]) {
+ if (!accessibleIds.has(projectId)) pendingReconcileRef.current.delete(projectId);
+ }
+ }, []);
+
const queueReconcile = useCallback((projectId: string, minCount = 0) => {
const pending = pendingReconcileRef.current.get(projectId) ?? 0;
pendingReconcileRef.current.set(projectId, Math.max(pending, minCount));
@@ -200,7 +216,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const fetchProjects = useCallback(async (options?: { cache?: boolean }) => {
try {
const result = await api.getWorkbenchProjectsBootstrap({ cache: options?.cache });
- setProjects(result.projects);
+ applyProjectsSnapshot(result.projects);
applyBootstrapSessions(result.sessions ?? {});
setProjectsError(null);
} catch (err: any) {
@@ -208,7 +224,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
// any list we had and surface the error (mobile shows a retry).
setProjectsError(err?.message ?? String(err));
}
- }, [api, applyBootstrapSessions]);
+ }, [api, applyBootstrapSessions, applyProjectsSnapshot]);
useEffect(() => {
void fetchProjects();
@@ -243,6 +259,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
beforeId: before,
cache: false,
});
+ if (!projectsRef.current?.some((project) => project.id === projectId)) return;
for (const s of res.sessions) {
if (!seen.has(s.id)) {
seen.add(s.id);
@@ -292,7 +309,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const groups = Array.from(bootstrapGroups.entries());
if (groups.length === 0) {
const result = await api.getWorkbenchProjectsBootstrap({ cache: false });
- setProjects(result.projects);
+ applyProjectsSnapshot(result.projects);
} else {
let nextProjects: WorkbenchProject[] | null = null;
const pages: Record<string, { sessions: WorkbenchSession[]; next_before_id: string | null }> = {};
@@ -313,7 +330,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
}
}
}
- if (nextProjects) setProjects(nextProjects);
+ if (nextProjects) applyProjectsSnapshot(nextProjects);
applyBootstrapSessions(pages);
}
setProjectsError(null);
@@ -327,7 +344,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
void reconcileSessions(projectId);
}
}
- }, [api, applyBootstrapSessions, queueReconcile, reconcileSessions]);
+ }, [api, applyBootstrapSessions, applyProjectsSnapshot, queueReconcile, reconcileSessions]);
const refreshCachedSessionRow = useCallback(async (sessionId: string) => {
const needsRefresh = Object.values(sessionsRef.current).some((state) =>
@@ -360,6 +377,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
try {
const beforeId = append ? sessionsRef.current[projectId]?.cursor ?? undefined : undefined;
const res = await api.listSessions({ projectId, status: 'active', limit: SESSIONS_PAGE_SIZE, beforeId });
+ if (!projectsRef.current?.some((project) => project.id === projectId)) return;
setSessions((prev) => {
const cur = prev[projectId] ?? EMPTY_SESSIONS;
const existing = append ? cur.sessions ?? [] : [];
@@ -403,6 +421,9 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
onConnected: () => {
void reconcileProjectTree();
},
+ onAuthorizationChanged: () => {
+ void reconcileProjectTree();
+ },
onSessionActivity: (data) => {
if (data.event === 'archived') {
// Terminal archive (here or in another tab) — drop the row live.
diff --git a/ui/src/lib/useMessageSearch.ts b/ui/src/lib/useMessageSearch.ts
index bbd6c2c08..85e2aee4c 100644
--- a/ui/src/lib/useMessageSearch.ts
+++ b/ui/src/lib/useMessageSearch.ts
@@ -26,7 +26,7 @@ export function useMessageSearch(
query: string,
opts?: UseMessageSearchOptions,
): UseMessageSearchState {
- const { searchMessages } = useApi();
+ const { connectWorkbenchEvents, searchMessages } = useApi();
const minLength = opts?.minLength ?? 1;
const debounceMs = opts?.debounceMs ?? 200;
@@ -38,6 +38,15 @@ export function useMessageSearch(
// still the latest. Survives re-renders so stale in-flight calls are ignored.
const seqRef = useRef(0);
+ useEffect(() => connectWorkbenchEvents({
+ onAuthorizationChanged: () => {
+ seqRef.current += 1;
+ setResults(null);
+ setLoading(false);
+ setError(null);
+ },
+ }), [connectWorkbenchEvents]);
+
useEffect(() => {
const trimmed = query.trim();
diff --git a/vibe/project_access_sync.py b/vibe/project_access_sync.py
new file mode 100644
index 000000000..f9ffb0ab9
--- /dev/null
+++ b/vibe/project_access_sync.py
@@ -0,0 +1,277 @@
+"""Device-side Project index publication and access-intent convergence."""
+
+from __future__ import annotations
+
+from datetime import datetime
+import logging
+import threading
+import time
+from typing import Any, Mapping
+
+import requests
+from sqlalchemy import select
+
+from config.v2_config import V2Config
+from storage import project_access_service
+from storage.db import create_sqlite_engine
+from storage.models import project_access_policies, scope_settings, scopes
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_POLL_SECONDS = 30
+MIN_POLL_SECONDS = 10
+MAX_POLL_SECONDS = 300
+MAX_PROJECTS_PER_REQUEST = 512
+_SYNC_LOCK = threading.Lock()
+_WORKER_LOCK = threading.Lock()
+_WORKER_STARTED = False
+
+
+class ProjectAccessSyncError(RuntimeError):
+ pass
+
+
+def _metadata_revision(value: Any) -> int:
+ if not isinstance(value, str) or not value.strip():
+ return 0
+ try:
+ parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
+ return max(0, min(int(parsed.timestamp() * 1000), project_access_service.MAX_CONTROL_PLANE_REVISION))
+ except (OverflowError, ValueError):
+ return 0
+
+
+def project_index_descriptors() -> list[dict[str, Any]]:
+ """Return the deliberately narrow Project metadata sent to the control plane."""
+
+ engine = create_sqlite_engine()
+ try:
+ with engine.connect() as conn:
+ rows = conn.execute(
+ select(
+ scopes.c.native_id,
+ scopes.c.display_name,
+ scopes.c.updated_at,
+ scope_settings.c.enabled,
+ project_access_policies.c.last_applied_control_plane_revision,
+ )
+ .select_from(
+ scopes.outerjoin(scope_settings, scope_settings.c.scope_id == scopes.c.id)
+ .outerjoin(
+ project_access_policies,
+ project_access_policies.c.scope_id == scopes.c.id,
+ )
+ )
+ .where(scopes.c.platform == "avibe", scopes.c.scope_type == "project")
+ .order_by(scopes.c.native_id)
+ ).all()
+ finally:
+ engine.dispose()
+ return [
+ {
+ "project_id": str(row.native_id),
+ "display_name": str(row.display_name or row.native_id),
+ "metadata_revision": _metadata_revision(row.updated_at),
+ "applied_access_revision": int(row.last_applied_control_plane_revision or 0),
+ "sync_status": "deleted" if row.enabled == 0 else "in_sync",
+ }
+ for row in rows
+ ]
+
+
+def _request_json(
+ method: str,
+ url: str,
+ *,
+ device_secret: str,
+ payload: Mapping[str, Any] | None = None,
+ timeout: float = 20.0,
+) -> dict[str, Any]:
+ try:
+ response = requests.request(
+ method,
+ url,
+ json=dict(payload) if payload is not None else None,
+ headers={
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ "User-Agent": "avibe/dev",
+ "X-Vibe-Device-Secret": device_secret,
+ },
+ timeout=timeout,
+ )
+ except requests.RequestException as error:
+ raise ProjectAccessSyncError("project_access_sync_unreachable") from error
+ try:
+ body = response.json()
+ except ValueError as error:
+ raise ProjectAccessSyncError("project_access_sync_invalid_response") from error
+ if not response.ok:
+ code = body.get("error") if isinstance(body, dict) else None
+ raise ProjectAccessSyncError(str(code or f"project_access_sync_http_{response.status_code}"))
+ if not isinstance(body, dict):
+ raise ProjectAccessSyncError("project_access_sync_invalid_response")
+ return body
+
+
+def _poll_seconds(payload: Mapping[str, Any]) -> int:
+ raw = payload.get("poll_after_seconds", DEFAULT_POLL_SECONDS)
+ if isinstance(raw, bool) or not isinstance(raw, (int, float)):
+ return DEFAULT_POLL_SECONDS
+ return max(MIN_POLL_SECONDS, min(int(raw), MAX_POLL_SECONDS))
+
+
+def _acknowledge(
+ endpoint: str,
+ *,
+ device_secret: str,
+ result: project_access_service.ProjectAccessIntentResult,
+) -> None:
+ payload: dict[str, Any] = {
+ "project_id": result.project_id,
+ "revision": result.revision,
+ "outcome": result.outcome,
+ }
+ if result.error_code:
+ payload["error_code"] = result.error_code
+ _request_json("POST", endpoint, device_secret=device_secret, payload=payload)
+
+
+def sync_project_access_once(config: V2Config | None = None) -> dict[str, Any]:
+ """Publish the local index, apply newer intents, and ACK exact revisions."""
+
+ config = config or V2Config.load()
+ cloud = config.remote_access.vibe_cloud
+ if not (
+ cloud.enabled
+ and cloud.backend_url
+ and cloud.instance_id
+ and cloud.instance_secret
+ ):
+ return {"ok": False, "configured": False, "poll_after_seconds": DEFAULT_POLL_SECONDS}
+
+ if not _SYNC_LOCK.acquire(blocking=False):
+ return {"ok": True, "skipped": "already_running", "poll_after_seconds": DEFAULT_POLL_SECONDS}
+ try:
+ base_url = cloud.backend_url.rstrip("/")
+ base_endpoint = f"{base_url}/api/v1/instances/{cloud.instance_id}"
+ descriptors = project_index_descriptors()
+ poll_seconds = DEFAULT_POLL_SECONDS
+ chunks = [
+ descriptors[index : index + MAX_PROJECTS_PER_REQUEST]
+ for index in range(0, len(descriptors), MAX_PROJECTS_PER_REQUEST)
+ ] or [[]]
+ for projects in chunks:
+ published = _request_json(
+ "PUT",
+ f"{base_endpoint}/project-index",
+ device_secret=cloud.instance_secret,
+ payload={"projects": projects},
+ )
+ poll_seconds = _poll_seconds(published)
+
+ intent_payload = _request_json(
+ "GET",
+ f"{base_endpoint}/project-access-intents",
+ device_secret=cloud.instance_secret,
+ )
+ poll_seconds = _poll_seconds(intent_payload)
+ raw_intents = intent_payload.get("intents")
+ if not isinstance(raw_intents, list) or len(raw_intents) > MAX_PROJECTS_PER_REQUEST:
+ raise ProjectAccessSyncError("project_access_sync_invalid_intents")
+
+ engine = create_sqlite_engine()
+ changed_project_ids: list[str] = []
+ applied = rejected = stale = ack_errors = 0
+ try:
+ for intent in raw_intents:
+ with engine.begin() as conn:
+ result = project_access_service.apply_project_access_intent(conn, intent)
+ if result.outcome == "stale":
+ stale += 1
+ continue
+ if result.outcome == "applied":
+ applied += 1
+ elif result.outcome == "rejected":
+ rejected += 1
+ else:
+ continue
+ if result.changed:
+ changed_project_ids.append(result.project_id)
+ if (
+ not result.project_id
+ or result.revision < 0
+ or result.revision > project_access_service.MAX_CONTROL_PLANE_REVISION
+ ):
+ continue
+ try:
+ _acknowledge(
+ f"{base_endpoint}/project-access-acks",
+ device_secret=cloud.instance_secret,
+ result=result,
+ )
+ except ProjectAccessSyncError:
+ ack_errors += 1
+ logger.warning(
+ "Project access ACK failed project_id=%s revision=%s",
+ result.project_id,
+ result.revision,
+ )
+ finally:
+ engine.dispose()
+
+ if changed_project_ids:
+ from vibe.sse_broker import broker
+
+ broker.publish(
+ "authorization.changed",
+ {"project_ids": sorted(set(changed_project_ids))},
+ )
+ return {
+ "ok": True,
+ "configured": True,
+ "projects": len(descriptors),
+ "intents": len(raw_intents),
+ "applied": applied,
+ "rejected": rejected,
+ "stale": stale,
+ "ack_errors": ack_errors,
+ "poll_after_seconds": poll_seconds,
+ }
+ finally:
+ _SYNC_LOCK.release()
+
+
+def _worker_loop(initial_config: V2Config | None) -> None:
+ config = initial_config
+ delay = 0
+ while True:
+ if delay:
+ time.sleep(delay)
+ try:
+ result = sync_project_access_once(config)
+ delay = int(result.get("poll_after_seconds") or DEFAULT_POLL_SECONDS)
+ except Exception:
+ logger.warning("Project access sync failed", exc_info=True)
+ delay = DEFAULT_POLL_SECONDS
+ config = None
+
+
+def start_project_access_sync(config: V2Config | None = None) -> None:
+ global _WORKER_STARTED
+
+ with _WORKER_LOCK:
+ if _WORKER_STARTED:
+ return
+ thread = threading.Thread(
+ target=_worker_loop,
+ args=(config,),
+ name="vibe-project-access-sync",
+ daemon=True,
+ )
+ _WORKER_STARTED = True
+ try:
+ thread.start()
+ except Exception:
+ _WORKER_STARTED = False
+ raise
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index f7a8587b3..5705176a1 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -1338,10 +1338,13 @@ def start_tunnel_quality_monitor(interval_seconds: float = QUALITY_SAMPLE_SECOND
def start_runtime_monitoring(config: V2Config | None = None) -> None:
- """Ensure the UI-owned heartbeat and quality workers are running."""
+ """Ensure the UI-owned heartbeat, quality, and Project sync workers are running."""
start_tunnel_quality_monitor()
start_status_heartbeat(config)
+ from vibe.project_access_sync import start_project_access_sync
+
+ start_project_access_sync(config)
def stop(config: V2Config | None = None) -> dict[str, Any]:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 786d3099b..8e634669c 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2158,6 +2158,56 @@ def enforce_instance_role_capabilities():
return None
+_PROJECT_RESOURCE_PATHS = (
+ ("project", re.compile(r"^/api/projects/([^/]+)(?:/agents-md)?$")),
+ ("session", re.compile(r"^/api/sessions/([^/]+)(?:/.*)?$")),
+ ("session", re.compile(r"^/api/show-pages/([^/]+)(?:/.*)?$")),
+ ("session", re.compile(r"^/api/show/sessions/([^/]+)(?:/.*)?$")),
+ ("session", re.compile(r"^/show/([^/]+)(?:/.*)?$")),
+)
+
+
+def _project_access_resource(path: str) -> tuple[str, str] | None:
+ for kind, pattern in _PROJECT_RESOURCE_PATHS:
+ match = pattern.fullmatch(path)
+ if match is not None:
+ return kind, unquote(match.group(1))
+ return None
+
+
+def enforce_project_role_capabilities():
+ """Narrow remote non-owner Project/session routes through applied Project ACLs."""
+ if _remote_auth_exempt_path():
+ return None
+ context = getattr(g, "authorization_context", None)
+ if context is None or context.is_instance_owner:
+ return None
+
+ from storage import project_access_service
+ from storage.db import create_sqlite_engine
+ from vibe.authorization import required_instance_role
+
+ minimum_instance_role = required_instance_role(request.method, request.path)
+ if minimum_instance_role not in {"viewer", "editor"}:
+ return None
+ resource = _project_access_resource(request.path)
+ if resource is None:
+ return None
+
+ kind, resource_id = resource
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ role = (
+ project_access_service.get_effective_project_role(conn, context, resource_id)
+ if kind == "project"
+ else project_access_service.get_effective_session_role(conn, context, resource_id)
+ )
+ if not project_access_service.role_allows(role, minimum_instance_role):
+ return jsonify({"ok": False, "error": "not_found"}), 404
+ return None
+
+
@app.before_request
def protect_mutating_ui_requests():
if request.method not in MUTATING_METHODS:
@@ -2441,7 +2491,11 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):
if not _show_runtime_hmr_origin_allowed(websocket):
await websocket.close(code=1008)
return
- if not _show_runtime_websocket_authorized(websocket, minimum_role="viewer"):
+ if not _show_runtime_websocket_authorized(
+ websocket,
+ minimum_role="viewer",
+ project_session_id=session_id,
+ ):
await websocket.close(code=1008)
return
@@ -2575,7 +2629,12 @@ def _terminal_http_request_adapter() -> SimpleNamespace:
)
-def _show_runtime_websocket_authorized(websocket: Any, *, minimum_role: str = "viewer") -> bool:
+def _show_runtime_websocket_authorized(
+ websocket: Any,
+ *,
+ minimum_role: str = "viewer",
+ project_session_id: str | None = None,
+) -> bool:
config = _load_remote_access_config()
if config is None:
return _websocket_is_local_request(websocket)
@@ -2586,9 +2645,22 @@ def _show_runtime_websocket_authorized(websocket: Any, *, minimum_role: str = "v
payload = _remote_access_websocket_session_payload(websocket, config)
if payload is None:
return False
+ from storage import project_access_service
from vibe.authorization import context_from_session_payload
- return context_from_session_payload(payload).has_role(minimum_role)
+ context = context_from_session_payload(payload)
+ if not context.has_role(minimum_role):
+ return False
+ if project_session_id is None or context.is_instance_owner:
+ return True
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ role = project_access_service.get_effective_session_role(
+ conn,
+ context,
+ project_session_id,
+ )
+ return project_access_service.role_allows(role, minimum_role)
def _show_runtime_hmr_origin_allowed(websocket: Any) -> bool:
@@ -3940,9 +4012,28 @@ def _show_page_error_response(exc):
@app.route("/api/show-pages", methods=["GET"])
def show_pages_list_get():
+ from storage import project_access_service
from vibe import api
- return jsonify(api.list_show_pages())
+ payload = api.list_show_pages()
+ context = getattr(g, "authorization_context", None)
+ if context is not None and not context.is_instance_owner:
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ payload["pages"] = [
+ page
+ for page in payload.get("pages", [])
+ if project_access_service.role_allows(
+ project_access_service.get_effective_session_role(
+ conn,
+ context,
+ str(page.get("session_id") or ""),
+ ),
+ "viewer",
+ )
+ ]
+ payload["count"] = len(payload["pages"])
+ return jsonify(payload)
@app.route("/api/show-pages/<session_id>/visibility", methods=["POST"])
@@ -5733,6 +5824,19 @@ def _projects_engine():
return create_sqlite_engine()
+def _request_accessible_project_scope_ids(conn) -> list[str] | None:
+ """Return the current remote user's Project scopes; owners need no SQL filter."""
+ from storage import project_access_service
+
+ context = getattr(g, "authorization_context", None)
+ if context is None or context.is_instance_owner:
+ return None
+ return sorted(
+ project_access_service.project_scope_id(project_id)
+ for project_id in project_access_service.accessible_project_ids(conn, context)
+ )
+
+
@app.route("/api/projects", methods=["GET"])
def projects_list():
from storage import projects_service
@@ -5740,7 +5844,15 @@ def projects_list():
include_archived = request.args.get("include_archived") in {"1", "true", "yes"}
engine = _projects_engine()
with engine.connect() as conn:
- return jsonify({"projects": projects_service.list_projects(conn, include_archived=include_archived)})
+ return jsonify(
+ {
+ "projects": projects_service.list_projects(
+ conn,
+ include_archived=include_archived,
+ authorization_context=getattr(g, "authorization_context", None),
+ )
+ }
+ )
@app.route("/api/projects", methods=["POST"])
@@ -5773,7 +5885,13 @@ def projects_get(project_id: str):
engine = _projects_engine()
try:
with engine.connect() as conn:
- return jsonify(projects_service.get_project(conn, project_id))
+ return jsonify(
+ projects_service.get_project(
+ conn,
+ project_id,
+ authorization_context=getattr(g, "authorization_context", None),
+ )
+ )
except LookupError as err:
return jsonify({"error": str(err)}), 404
@@ -6161,6 +6279,7 @@ def sessions_list():
limit=limit,
before_id=before_id,
title_query=title_query,
+ authorization_context=getattr(g, "authorization_context", None),
)
return jsonify(result)
@@ -6187,7 +6306,12 @@ def workbench_projects_bootstrap():
engine = _projects_engine()
with engine.connect() as conn:
- projects = projects_service.list_projects(conn, include_archived=include_archived)
+ authorization_context = getattr(g, "authorization_context", None)
+ projects = projects_service.list_projects(
+ conn,
+ include_archived=include_archived,
+ authorization_context=authorization_context,
+ )
project_id_set = {project["id"] for project in projects}
sessions: dict[str, Any] = {}
for project_id in project_ids:
@@ -6198,6 +6322,7 @@ def workbench_projects_bootstrap():
scope_id=_project_to_scope_id(project_id),
status=status,
limit=limit,
+ authorization_context=authorization_context,
)
return jsonify({"projects": projects, "sessions": sessions})
@@ -6341,7 +6466,13 @@ def sessions_get(session_id: str):
engine = _projects_engine()
try:
with engine.connect() as conn:
- return jsonify(workbench_sessions_service.get_session(conn, session_id))
+ return jsonify(
+ workbench_sessions_service.get_session(
+ conn,
+ session_id,
+ authorization_context=getattr(g, "authorization_context", None),
+ )
+ )
except LookupError as err:
return jsonify({"error": str(err)}), 404
@@ -6905,7 +7036,12 @@ def search_messages_list():
engine = _projects_engine()
with engine.connect() as conn:
- result = messages_service.search_messages(conn, query=query, limit=limit)
+ result = messages_service.search_messages(
+ conn,
+ query=query,
+ limit=limit,
+ scope_ids=_request_accessible_project_scope_ids(conn),
+ )
return jsonify(result)
@@ -7449,6 +7585,24 @@ def media_get(token: str):
return _registered_media_response(token)
+def _request_can_read_media_row(conn, row: dict[str, Any]) -> bool:
+ from storage import project_access_service
+
+ context = getattr(g, "authorization_context", None)
+ if context is None or context.is_instance_owner:
+ return True
+ session_id = row.get("session_id")
+ project_id = project_access_service.project_id_from_scope_id(row.get("scope_id"))
+ role = (
+ project_access_service.get_effective_session_role(conn, context, session_id)
+ if session_id
+ else project_access_service.get_effective_project_role(conn, context, project_id)
+ if project_id
+ else None
+ )
+ return project_access_service.role_allows(role, "viewer")
+
+
def _registered_media_response(
token: str,
*,
@@ -7462,6 +7616,8 @@ def _registered_media_response(
engine = _projects_engine()
with engine.connect() as conn:
row = media_service.get_by_token(conn, token)
+ if row and not _request_can_read_media_row(conn, row):
+ row = None
if not row or row.get("revoked_at"):
return jsonify({"error": "not_found"}), 404
if expected_session_id is not None and row.get("session_id") != expected_session_id:
@@ -7515,6 +7671,8 @@ def media_meta(token: str):
engine = _projects_engine()
with engine.connect() as conn:
row = media_service.get_by_token(conn, token)
+ if row and not _request_can_read_media_row(conn, row):
+ row = None
if not row or row.get("revoked_at"):
return jsonify({"error": "not_found"}), 404
return jsonify(
@@ -8055,6 +8213,39 @@ def sessions_draft_set(session_id: str):
return jsonify({"ok": True})
+def _workbench_event_visible_to_context(context, event_type: str, payload: str) -> bool:
+ if context is None or context.is_instance_owner:
+ return True
+ if event_type in {"authorization.changed", "workbench.events.bridge.status"}:
+ return True
+ try:
+ envelope = json.loads(payload)
+ except (TypeError, json.JSONDecodeError):
+ return False
+ data = envelope.get("data") if isinstance(envelope, dict) else None
+ if not isinstance(data, dict):
+ return False
+
+ from storage import project_access_service
+
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ session_id = data.get("session_id")
+ if isinstance(session_id, str) and session_id:
+ return project_access_service.role_allows(
+ project_access_service.get_effective_session_role(
+ conn,
+ context,
+ session_id,
+ ),
+ "viewer",
+ )
+ project_id = project_access_service.project_id_from_scope_id(data.get("scope_id"))
+ if project_id is not None:
+ return project_access_service.can_read_project(conn, context, project_id)
+ return False
+
+
@app.route("/api/events", methods=["GET"])
async def workbench_events():
"""Server-Sent Events stream for the workbench.
@@ -8077,6 +8268,8 @@ async def workbench_events():
from vibe.inbox_bridge import is_bridge_connected
from vibe.sse_broker import broker
+ authorization_context = getattr(g, "authorization_context", None)
+
async def generate():
sub_id, queue = broker.subscribe()
try:
@@ -8096,6 +8289,26 @@ async def workbench_events():
while True:
try:
event_type, payload = await asyncio.wait_for(queue.get(), timeout=15.0)
+ visible = await asyncio.to_thread(
+ _workbench_event_visible_to_context,
+ authorization_context,
+ event_type,
+ payload,
+ )
+ if not visible:
+ continue
+ if (
+ event_type == "authorization.changed"
+ and authorization_context is not None
+ and not authorization_context.is_instance_owner
+ ):
+ payload = json.dumps(
+ {
+ "type": "authorization.changed",
+ "data": {"project_ids": []},
+ },
+ separators=(",", ":"),
+ )
yield f"event: {event_type}\ndata: {payload}\n\n"
except asyncio.TimeoutError:
# 15s keep-alive — Cloudflare Tunnel default idle is well
@@ -8140,6 +8353,7 @@ def inbox_list():
engine = _projects_engine()
with engine.connect() as conn:
+ accessible_scope_ids = _request_accessible_project_scope_ids(conn)
result = messages_service.list_inbox_sessions(
conn,
platform=scope_filter,
@@ -8147,10 +8361,15 @@ def inbox_list():
limit=limit,
before=before,
only_session=only_session,
+ scope_ids=accessible_scope_ids,
)
# Pagination-independent unread map for the sidebar badges (a session
# with unread may sit past the first inbox page) + header totals.
- per_session = messages_service.unread_counts_by_session(conn, platform=scope_filter)
+ per_session = messages_service.unread_counts_by_session(
+ conn,
+ platform=scope_filter,
+ scope_ids=accessible_scope_ids,
+ )
result["unread_by_session"] = per_session
result["unread_total"] = sum(per_session.values())
result["unread_sessions"] = len(per_session)