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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(acl): enforce agent resource access
Maxvint9be49d6918b3
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 1376aecee..292606a24 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -709,7 +709,11 @@ class ScheduledTaskStore:run_at: Optional[str] = None,timezone_name: str,metadata: Optional[dict[str, Any]] = None,+ user_context: Any = None,) -> ScheduledTask:+ from core.vibe_agents import ensure_agent_name_access++ ensure_agent_name_access(agent_name, user_context=user_context)task = ScheduledTask(id=uuid4().hex[:12],name=name,@@ -768,7 +772,11 @@ class ScheduledTaskStore:cwd: Optional[str] = None,update_cwd: bool = False,metadata: Optional[dict[str, Any]] = None,+ user_context: Any = None,) -> ScheduledTask:+ from core.vibe_agents import ensure_agent_name_access++ ensure_agent_name_access(agent_name, user_context=user_context)task = self._tasks[task_id]task.name = nametask.session_key = session_keydiff --git a/core/vibe_agents.py b/core/vibe_agents.pyindex 088aaeb5c..5e58d991d 100644--- a/core/vibe_agents.py+++ b/core/vibe_agents.py@@ -31,6 +31,10 @@ SUPPORTED_AGENT_BACKENDS = {"codex", "claude", "opencode"}_UNSET = object()+class VibeAgentAccessError(PermissionError):+ """Raised when the caller is not allowed to use a Vibe Agent."""++def _utc_now_iso() -> str:return datetime.now(timezone.utc).isoformat()@@ -63,6 +67,91 @@ def _json_loads(value: str | None, default: Any) -> Any:return default+def resolve_resource_access_context(user_context: Any = None):+ """Resolve a request context while preserving local service behavior.++ Domain services are also called from the local CLI and background workers,+ where there is no HTTP request to inspect. Those callers are local by+ construction. Remote requests always carry an explicit remote context, so+ they remain subject to the local ACL projection.+ """++ from storage import resource_access_service++ if isinstance(user_context, resource_access_service.ResourceUserContext):+ return user_context+ if user_context is not None:+ return resource_access_service.current_resource_context(user_context, is_remote=True)++ context = resource_access_service.current_resource_context()+ if context.is_remote or context.is_trusted_local:+ return context+ return resource_access_service.ResourceUserContext(is_trusted_local=True)+++def ensure_agent_selection_access(+ connection,+ *,+ agent_name: str | None = None,+ agent_id: str | None = None,+ user_context: Any = None,+ missing_is_error: bool = False,+) -> "VibeAgent | None":+ """Return a selected Agent only when the request may use it.++ ``agent_id`` is the ACL resource identifier. A supplied name and id must+ resolve to the same row so a caller cannot authorize one Agent and persist+ another in a session or background definition.+ """++ from storage import resource_access_service++ selected_name = str(agent_name or "").strip()+ selected_id = str(agent_id or "").strip()+ if not selected_name and not selected_id:+ return None++ context = resolve_resource_access_context(user_context)+ statement = select(agents)+ if selected_id:+ statement = statement.where(agents.c.id == selected_id)+ if selected_name:+ statement = statement.where(agents.c.normalized_name == normalize_agent_name(selected_name))+ row = connection.execute(statement.limit(1)).mappings().first()+ if row is None:+ if context.is_remote or missing_is_error:+ raise LookupError("Agent not found")+ # Older local callers may hold a backend/name pairing that predates the+ # Vibe Agent catalog. Preserve that local compatibility; a remote+ # request never receives the same exception.+ return None++ agent = VibeAgentStore._from_row(row)+ if not resource_access_service.can_use_resource(context, "agent", agent.id, connection=connection):+ raise VibeAgentAccessError("Agent access is not permitted.")+ return agent+++def ensure_agent_name_access(agent_name: str | None, *, user_context: Any = None) -> None:+ """Reject a remote task/watch binding to an inaccessible named Agent.++ Local task and watch definitions are created outside an HTTP request and+ intentionally retain their existing trusted-local behavior. A remote+ request gets the same id-backed authorization used by session creation.+ """++ if not str(agent_name or "").strip():+ return+ context = resolve_resource_access_context(user_context)+ if not context.is_remote:+ return+ store = VibeAgentStore()+ try:+ store.require_accessible(str(agent_name), user_context=context)+ finally:+ store.close()++@dataclass(frozen=True)class VibeAgent:id: str@@ -122,12 +211,21 @@ class VibeAgentStore:def maybe_reload(self) -> bool:return self._probe.has_external_write()- def list_agents(self, *, include_disabled: bool = True) -> list[VibeAgent]:+ def list_agents(self, *, include_disabled: bool = True, user_context: Any = None) -> list[VibeAgent]:+ from storage import resource_access_service++ context = resolve_resource_access_context(user_context)with self.engine.connect() as conn:stmt = select(agents).order_by(agents.c.name)if not include_disabled:stmt = stmt.where(agents.c.enabled == 1)- rows = conn.execute(stmt).mappings()+ rows = conn.execute(stmt).mappings().all()+ rows = resource_access_service.filter_accessible_resources(+ context,+ "agent",+ rows,+ connection=conn,+ )return [self._from_row(row) for row in rows]def get(self, name: str) -> Optional[VibeAgent]:@@ -150,6 +248,21 @@ class VibeAgentStore:raise ValueError(f"agent '{agent.name}' is disabled")return agent+ def require_accessible(self, name: str, *, user_context: Any = None, enabled_only: bool = False) -> VibeAgent:+ """Return an Agent only when the caller may use its ACL resource."""++ with self.engine.connect() as conn:+ agent = ensure_agent_selection_access(+ conn,+ agent_name=name,+ user_context=user_context,+ missing_is_error=True,+ )+ assert agent is not None+ if enabled_only and not agent.enabled:+ raise ValueError(f"agent '{agent.name}' is disabled")+ return agent+def create(self,*,@@ -163,8 +276,12 @@ class VibeAgentStore:source_ref: Optional[str] = None,metadata: Optional[dict[str, Any]] = None,enabled: bool = True,+ user_context: Any = None,) -> VibeAgent:+ from storage import resource_access_service+normalized = normalize_agent_name(name)+ context = resolve_resource_access_context(user_context)now = _utc_now_iso()agent = VibeAgent(id=uuid4().hex[:12],@@ -185,6 +302,18 @@ class VibeAgentStore:try:with self.engine.begin() as conn:conn.execute(agents.insert().values(**self._values(agent)))+ if source != "builtin" and context.is_remote and context.is_active_organization_member and context.subject:+ resource_access_service.ensure_resource_policy(+ conn,+ resource_kind="agent",+ resource_id=agent.id,+ organization_id=context.organization_id,+ owner_user_id=context.subject,+ owner_email=context.email,+ access_level="private",+ created_by_user_id=context.subject,+ updated_by_user_id=context.subject,+ )except IntegrityError as exc:raise ValueError(f"agent '{name}' already exists") from excreturn agent@@ -426,7 +555,14 @@ class VibeAgentStore:if fallback is not None and (fallback.enabled or not enabled_only):return fallbackif enabled_only:- agents_list = self.list_agents(include_disabled=False)+ # This resolver maintains the instance-wide default. It must not let+ # one remote caller's ACL-filtered catalog rewrite that global state.+ from storage.resource_access_service import ResourceUserContext++ agents_list = self.list_agents(+ include_disabled=False,+ user_context=ResourceUserContext(is_trusted_local=True),+ )return agents_list[0] if agents_list else Nonereturn Nonediff --git a/core/watches.py b/core/watches.pyindex 97aa32953..e6dce22ed 100644--- a/core/watches.py+++ b/core/watches.py@@ -225,7 +225,11 @@ class ManagedWatchStore:session_policy: Optional[str] = None,message: Optional[str] = None,metadata: Optional[dict[str, Any]] = None,+ user_context: Any = None,) -> ManagedWatch:+ from core.vibe_agents import ensure_agent_name_access++ ensure_agent_name_access(agent_name, user_context=user_context)watch = ManagedWatch(id=uuid4().hex[:12],name=name,@@ -291,7 +295,11 @@ class ManagedWatchStore:session_policy: Optional[str] = None,message: Optional[str] = None,metadata: Optional[dict[str, Any]] = None,+ user_context: Any = None,) -> ManagedWatch:+ from core.vibe_agents import ensure_agent_name_access++ ensure_agent_name_access(agent_name, user_context=user_context)watch = self._watches[watch_id]watch.name = namewatch.session_key = session_keydiff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.pyindex 383b0b071..789893f5c 100644--- a/storage/workbench_sessions_service.py+++ b/storage/workbench_sessions_service.py@@ -281,6 +281,7 @@ def create_session(title: Optional[str] = None,visibility: str = "foreground",metadata: Optional[dict[str, Any]] = None,+ user_context: Any = None,) -> dict[str, Any]:"""Create a session in a Scope or as a standalone session.@@ -334,6 +335,16 @@ def create_session(if reasoning_effort is None:reasoning_effort = scope_row.get("reasoning_effort")+ if agent_name or agent_id:+ from core.vibe_agents import ensure_agent_selection_access++ ensure_agent_selection_access(+ conn,+ agent_name=agent_name,+ agent_id=agent_id,+ user_context=user_context,+ )+now = _utc_now_iso()variant = agent_variant or agent_backend or "default"metadata_payload = {"created_via": "workbench"}@@ -399,6 +410,7 @@ def update_session(visibility: Any = _UNSET,pinned: Any = _UNSET,scope_id: Any = _UNSET,+ user_context: Any = None,) -> dict[str, Any]:existing = conn.execute(select(@@ -418,6 +430,16 @@ def update_session(agent_backend = _backend_for_agent_name(conn, str(agent_name or "")) if agent_name else Nonederived_backend = True+ if agent_name is not _UNSET or agent_id is not _UNSET:+ from core.vibe_agents import ensure_agent_selection_access++ ensure_agent_selection_access(+ conn,+ agent_name=None if agent_name is _UNSET else agent_name,+ agent_id=None if agent_id is _UNSET else agent_id,+ user_context=user_context,+ )+# Backend is pinned once a NATIVE conversation exists: the native can only# be resumed by the backend that created it, so switching (or clearing) the# backend would strand it. A RUNNING turn locks it too — the first turn isdiff --git a/tests/test_resource_acl_agents.py b/tests/test_resource_acl_agents.pynew file mode 100644index 000000000..07ec58d74--- /dev/null+++ b/tests/test_resource_acl_agents.py@@ -0,0 +1,212 @@+from __future__ import annotations++import pytest++from core.scheduled_tasks import ScheduledTaskStore+from core.vibe_agents import VibeAgent, VibeAgentAccessError, VibeAgentStore+from core.watches import ManagedWatchStore+from storage import resource_access_service, workbench_sessions_service+from storage.db import get_cached_sqlite_engine+from storage.settings_service import upsert_scope+from tests.test_ui_remote_access_auth import _remote_peer, _save_config+from tests.ui_server_test_helpers import csrf_headers+from vibe import remote_access+from vibe.ui_server import app+++def _organization_context(+ subject: str,+ *,+ group_ids: frozenset[str] | None = frozenset({"group-engineering"}),+) -> resource_access_service.ResourceUserContext:+ return resource_access_service.ResourceUserContext(+ subject=subject,+ email=f"{subject}@example.com",+ organization_id="org-1",+ organization_member_id=f"member-{subject}",+ organization_role="member",+ group_ids=group_ids,+ instance_access_source="organization_group",+ is_remote=True,+ )+++def _organization_cookie(config, *, subject: str, groups: list[str] | None = None) -> str:+ claims = {+ "vibe_instance_id": "inst_123",+ "vibe_instance_access_source": "organization_group",+ "vibe_organization_id": "org-1",+ "vibe_organization_member_id": f"member-{subject}",+ "vibe_organization_role": "member",+ "vibe_membership_version": "membership-v2",+ }+ if groups is not None:+ claims["vibe_group_ids"] = groups+ return remote_access.make_session_cookie(+ config,+ f"{subject}@example.com",+ subject,+ session_claims=claims,+ )+++def _seed_agents_with_policies() -> tuple[VibeAgentStore, dict[str, VibeAgent]]:+ store = VibeAgentStore()+ agents = {+ "private": store.create(name="private-agent", backend="codex"),+ "public": store.create(name="public-agent", backend="codex"),+ "scope": store.create(name="scope-agent", backend="codex"),+ }+ with store.engine.begin() as connection:+ resource_access_service.ensure_resource_policy(+ connection,+ resource_kind="agent",+ resource_id=agents["private"].id,+ organization_id="org-1",+ owner_user_id="owner-1",+ access_level="private",+ )+ resource_access_service.ensure_resource_policy(+ connection,+ resource_kind="agent",+ resource_id=agents["public"].id,+ organization_id="org-1",+ owner_user_id="owner-1",+ access_level="public",+ )+ resource_access_service.ensure_resource_policy(+ connection,+ resource_kind="agent",+ resource_id=agents["scope"].id,+ organization_id="org-1",+ owner_user_id="owner-1",+ access_level="scope",+ group_ids=["group-engineering"],+ )+ return store, agents+++def test_agent_catalog_filters_private_public_scope_and_missing_group_context(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ store, _agents = _seed_agents_with_policies()+ try:+ owner_names = {agent.name for agent in store.list_agents(user_context=_organization_context("owner-1"))}+ member_names = {agent.name for agent in store.list_agents(user_context=_organization_context("member-1"))}+ no_group_names = {+ agent.name+ for agent in store.list_agents(user_context=_organization_context("member-2", group_ids=None))+ }+ finally:+ store.close()++ assert owner_names == {"private-agent", "public-agent", "scope-agent"}+ assert member_names == {"public-agent", "scope-agent"}+ assert no_group_names == {"public-agent"}+++def test_remote_agent_creation_defaults_to_private_organization_policy(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ _organization_cookie(config, subject="member-1", groups=["group-engineering"]),+ domain="alex.avibe.bot",+ )++ response = client.post(+ "/api/agents",+ json={"name": "remote-private", "backend": "codex"},+ headers=csrf_headers(client, "https://alex.avibe.bot"),+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )++ assert response.status_code == 200+ agent_id = response.get_json()["agent"]["id"]+ engine = get_cached_sqlite_engine()+ with engine.connect() as connection:+ policy = resource_access_service.get_resource_policy("agent", agent_id, connection=connection)+ assert policy is not None+ assert policy["organization_id"] == "org-1"+ assert policy["owner_user_id"] == "member-1"+ assert policy["access_level"] == "private"+++def test_remote_agent_request_and_selection_reject_inaccessible_agent(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ store, agents = _seed_agents_with_policies()+ store.close()+ private_agent = agents["private"]+ context = _organization_context("member-1")++ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ _organization_cookie(config, subject="member-1", groups=["group-engineering"]),+ domain="alex.avibe.bot",+ )+ response = client.get(+ "/api/agents/private-agent",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )++ assert response.status_code == 403+ assert response.get_json()["code"] == "agent_access_forbidden"+ catalog = client.get(+ "/api/agents",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ assert catalog.status_code == 200+ assert {agent["name"] for agent in catalog.get_json()["agents"]} == {"public-agent", "scope-agent"}++ engine = get_cached_sqlite_engine()+ with engine.begin() as connection:+ scope_id = upsert_scope(+ connection,+ platform="avibe",+ scope_type="project",+ native_id="proj_acl_agents",+ now="2026-07-20T00:00:00Z",+ )+ with pytest.raises(VibeAgentAccessError):+ workbench_sessions_service.create_session(+ connection,+ scope_id=scope_id,+ agent_backend="codex",+ agent_name=private_agent.name,+ agent_id=private_agent.id,+ user_context=context,+ )++ with pytest.raises(VibeAgentAccessError):+ ScheduledTaskStore(tmp_path / "tasks.json").add_task(+ session_key="avibe::project::proj_acl_agents",+ prompt="run",+ schedule_type="cron",+ agent_name=private_agent.name,+ cron="0 * * * *",+ timezone_name="UTC",+ user_context=context,+ )+ with pytest.raises(VibeAgentAccessError):+ ManagedWatchStore(tmp_path / "watches.json").add_watch(+ name="acl watch",+ session_key="avibe::project::proj_acl_agents",+ command=["true"],+ shell_command=None,+ prefix=None,+ cwd=str(tmp_path),+ mode="once",+ timeout_seconds=1,+ lifetime_timeout_seconds=0,+ retry_exit_codes=[75],+ retry_delay_seconds=1,+ post_to=None,+ deliver_key=None,+ agent_name=private_agent.name,+ user_context=context,+ )diff --git a/vibe/api.py b/vibe/api.pyindex 704982a3e..57007213d 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -68,9 +68,11 @@ from modules.agents.catalog import ()from modules.agents.subagent_router import list_codex_subagentsfrom core.vibe_agents import (+ VibeAgentAccessError,VibeAgentStore,iter_global_agent_files,parse_agent_file,+ resolve_resource_access_context,validate_agent_backend,)from core.process_isolation import isolated_subprocess_kwargs, signal_process_tree, KILL_SIGNAL@@ -1330,13 +1332,19 @@ def _parse_agent_enabled_field(payload: dict, *, default: Optional[bool] = None)def get_vibe_agents(*, backend: Optional[str] = None, include_disabled: bool = False) -> dict:_ensure_builtin_default_agents()+ user_context = resolve_resource_access_context()store = VibeAgentStore()try:normalized_backend = validate_agent_backend(backend) if backend else None- agents = store.list_agents(include_disabled=include_disabled)+ agents = store.list_agents(include_disabled=include_disabled, user_context=user_context)if normalized_backend:agents = [agent for agent in agents if agent.backend == normalized_backend]default_agent = store.get_default_agent()+ if default_agent is not None:+ try:+ default_agent = store.require_accessible(default_agent.name, user_context=user_context)+ except VibeAgentAccessError:+ default_agent = Nonereturn {"ok": True,"agents": [_vibe_agent_payload(agent, brief=True) for agent in agents],@@ -1347,10 +1355,16 @@ def get_vibe_agents(*, backend: Optional[str] = None, include_disabled: bool = Fdef get_vibe_agent(name: str) -> dict:+ user_context = resolve_resource_access_context()store = VibeAgentStore()try:- agent = store.require(name)+ agent = store.require_accessible(name, user_context=user_context)default_agent = store.get_default_agent()+ if default_agent is not None:+ try:+ default_agent = store.require_accessible(default_agent.name, user_context=user_context)+ except VibeAgentAccessError:+ default_agent = Nonereturn {"ok": True,"agent": _vibe_agent_payload(agent),@@ -1377,6 +1391,7 @@ def create_vibe_agent(payload: dict) -> dict:system_prompt=payload.get("system_prompt"),metadata=metadata,enabled=_parse_agent_enabled_field(payload, default=True),+ user_context=resolve_resource_access_context(),)return {"ok": True, "agent": _vibe_agent_payload(agent)}finally:@@ -1427,6 +1442,7 @@ def update_vibe_agent(name: str, payload: dict) -> dict:store = VibeAgentStore()try:+ store.require_accessible(name, user_context=resolve_resource_access_context())agent = store.update(name, **kwargs)return {"ok": True, "agent": _vibe_agent_payload(agent)}finally:@@ -1436,6 +1452,7 @@ def update_vibe_agent(name: str, payload: dict) -> dict:def remove_vibe_agent(name: str) -> dict:store = VibeAgentStore()try:+ store.require_accessible(name, user_context=resolve_resource_access_context())counts = store.reference_counts(name)if any(counts.values()):return {@@ -1462,6 +1479,7 @@ def remove_vibe_agent(name: str) -> dict:def set_default_vibe_agent(name: str) -> dict:store = VibeAgentStore()try:+ store.require_accessible(name, user_context=resolve_resource_access_context(), enabled_only=True)store.set_default_agent_name(name)agent = store.require(name)return {"ok": True, "default_agent_name": agent.name, "agent": _vibe_agent_payload(agent, brief=True)}diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex b5a48ecc5..dce8b298b 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3329,8 +3329,10 @@ def agent_backends_get():return jsonify(api.get_agent_backend_catalog())-def _vibe_agent_error_response(exc: ValueError):+def _vibe_agent_error_response(exc: Exception):message = str(exc)+ if isinstance(exc, PermissionError):+ return jsonify({"ok": False, "code": "agent_access_forbidden", "message": message}), 403lowered = message.lower()if "not found" in lowered:return jsonify({"ok": False, "code": "agent_not_found", "message": message}), 404@@ -3368,7 +3370,7 @@ def vibe_agents_get():"yes",}return jsonify(api.get_vibe_agents(backend=request.args.get("backend") or None, include_disabled=include_disabled))- except ValueError as exc:+ except (ValueError, PermissionError) as exc:return _vibe_agent_error_response(exc)@@ -3463,7 +3465,7 @@ def vibe_agent_get(name):try:return jsonify(api.get_vibe_agent(name))- except ValueError as exc:+ except (ValueError, PermissionError) as exc:return _vibe_agent_error_response(exc)@@ -3473,7 +3475,7 @@ def vibe_agents_post():try:return jsonify(api.create_vibe_agent(request.json or {}))- except ValueError as exc:+ except (ValueError, PermissionError) as exc:return _vibe_agent_error_response(exc)@@ -3483,7 +3485,7 @@ def vibe_agents_import_post():try:return _vibe_agent_result_response(api.import_vibe_agents(request.json or {}))- except ValueError as exc:+ except (ValueError, PermissionError) as exc:return _vibe_agent_error_response(exc)@@ -3494,7 +3496,7 @@ def vibe_agents_default_post():payload = request.json or {}try:return jsonify(api.set_default_vibe_agent(payload.get("name") or ""))- except ValueError as exc:+ except (ValueError, PermissionError) as exc:return _vibe_agent_error_response(exc)@@ -3504,7 +3506,7 @@ def vibe_agent_patch(name):try:return jsonify(api.update_vibe_agent(name, request.json or {}))- except ValueError as exc:+ except (ValueError, PermissionError) as exc:return _vibe_agent_error_response(exc)@@ -3514,7 +3516,7 @@ def vibe_agent_delete(name):try:return _vibe_agent_result_response(api.remove_vibe_agent(name))- except ValueError as exc:+ except (ValueError, PermissionError) as exc:return _vibe_agent_error_response(exc)@@ -6773,8 +6775,10 @@ async def sessions_update(session_id: str):session = workbench_sessions_service.update_session(conn, session_id, **updatable)except LookupError as err:return jsonify({"error": str(err)}), 404- except (ValueError, PermissionError) as err:+ except ValueError as err:return jsonify({"error": str(err)}), 400+ except PermissionError as err:+ return jsonify({"error": str(err)}), 403except workbench_sessions_service.SessionBackendLockedError as err:# A session is pinned to its backend once it has a conversation (or a# running turn); the UI may switch the agent within the same backend,