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): add instance access role member (#1598)

Max2b18734a4caf
diff --git a/core/vibe_agents.py b/core/vibe_agents.py
index 2955c79fd..2146fc64d 100644
--- a/core/vibe_agents.py
+++ b/core/vibe_agents.py
@@ -307,7 +307,20 @@ def _require_agent_create_access(user_context: Any) -> None:
def _require_agent_onboarding_access(user_context: Any):
- """Require owner-equivalent access for Organization Agent publication."""
+ """Require Instance Owner identity for Organization Agent onboarding.
+
+ Onboarding is a one-way bulk migration over *every* Agent row in the
+ instance, not a per-resource action: the inventory discloses Agents the
+ caller cannot otherwise see, and the write claims every policy-less Agent --
+ built-ins and legacy/local rows nobody owns -- under the caller's private
+ ACL, which hides them from everyone else and can fence an existing default
+ route.
+
+ It is deliberately NOT gated on ``can_manage_access_members``: this is a
+ migration tool, not member management, so it does not belong to that
+ capability even though both happen to be Owner-only today. Owner identity is
+ the gate because the migration's blast radius is the whole instance.
+ """
context = resolve_resource_access_context(user_context)
if context.is_instance_owner:
@@ -516,15 +529,83 @@ def resolve_effective_default_agent(connection, *, enabled_only: bool = True) ->
return VibeAgentStore._from_row(row) if row is not None else None
+# Default routing surfaces -- the instance-wide default Agent and a project's
+# default Agent -- are resolved on behalf of whoever starts an unpinned session,
+# never on behalf of whoever configured them. Validating the assignment against
+# the resource policy's *shape* was tried and abandoned: no predicate over
+# {public, scope, private, absent} is both sound and usable. `private` and
+# `scope` narrow the audience; `absent` is the normal shape on a personal
+# install, where no Agent carries an ACL row at all, so rejecting it refuses
+# every Agent on the primary local-first deployment; and `public` still admits
+# only active members of the policy's organization, while instance and project
+# access are also granted to email and email-domain principals.
+#
+# So a default is advisory, and the ACL is enforced where it is meaningful: at
+# use time, against the principal actually resolving it. A default that some
+# principal cannot use degrades for that principal instead of being refused for
+# everyone at assignment time.
+def resolve_usable_default_agent(
+ connection,
+ *,
+ context,
+ agent: VibeAgent | None,
+) -> VibeAgent | None:
+ """Degrade a resolved default to one this caller may actually use.
+
+ A default is configured by one principal and resolved by another, so the
+ configurer can perfectly well name an Agent some of the audience cannot use.
+ Refusing the assignment cannot fix that (see the note above), and refusing
+ the session is worse than it looks: for a project default it means nobody
+ except the configurer can start a normal session there.
+
+ So fall back instead. Prefer a builtin, then any other enabled Agent the
+ caller can use, so an unpinned session keeps working. Return ``None`` when
+ nothing is usable and let the caller raise the existing machine-readable
+ access error, which is the signal the UI uses to prompt for an explicit
+ choice.
+
+ This is the *unpinned* path only. An explicit Agent selection is a stated
+ intent, not an advisory hint, so ``ensure_agent_selection_access`` still
+ errors rather than silently substituting a different Agent.
+ """
+
+ from storage import resource_access_service
+
+ def _usable(candidate: VibeAgent | None) -> bool:
+ return candidate is not None and resource_access_service.can_use_resource(
+ context,
+ "agent",
+ candidate.id,
+ connection=connection,
+ )
+
+ if _usable(agent):
+ return agent
+
+ rows = (
+ connection.execute(select(agents).where(agents.c.enabled == 1).order_by(agents.c.name))
+ .mappings()
+ .all()
+ )
+ candidates = [VibeAgentStore._from_row(row) for row in rows]
+ # Builtins first: they are the shape every install has and the one a caller
+ # is most likely to be entitled to.
+ candidates.sort(key=lambda item: 0 if item.source == "builtin" else 1)
+ for candidate in candidates:
+ if agent is not None and candidate.id == agent.id:
+ continue
+ if _usable(candidate):
+ return candidate
+ return None
+
+
def ensure_default_agent_access(
connection,
*,
user_context: Any = None,
missing_is_error: bool = False,
) -> VibeAgent | None:
- """Resolve and authorize the effective default Agent for a remote caller."""
-
- from storage import resource_access_service
+ """Resolve the effective default Agent for a caller, degrading if needed."""
context = resolve_resource_access_context(user_context)
agent = resolve_effective_default_agent(connection)
@@ -532,14 +613,10 @@ def ensure_default_agent_access(
if missing_is_error:
raise LookupError("Default Agent not found")
return None
- if not resource_access_service.can_use_resource(
- context,
- "agent",
- agent.id,
- connection=connection,
- ):
+ usable = resolve_usable_default_agent(connection, context=context, agent=agent)
+ if usable is None:
raise VibeAgentAccessError("Agent access is not permitted.")
- return agent
+ return usable
def ensure_session_agent_access(
@@ -920,7 +997,11 @@ class VibeAgentStore:
try:
with self.engine.begin() as conn:
conn.execute(agents.insert().values(**self._values(agent)))
- if source != "builtin" and context.is_active_organization_member and context.subject:
+ # Register a private ACL for any creating subject, including a
+ # Personal/email member. Organization *use* still follows the
+ # stored policy; omitting the row hid the Agent from its creator
+ # because missing-policy fails closed for non-owners.
+ if source != "builtin" and context.subject:
resource_access_service.ensure_resource_policy(
conn,
resource_kind="agent",
@@ -1665,6 +1746,9 @@ class VibeAgentStore:
user_context: Any = None,
) -> None:
normalized = normalize_agent_name(name)
+ context = resolve_resource_access_context(user_context)
+ if not context.can_manage_access_members:
+ raise VibeAgentAccessError("Agent access is not permitted.")
now = _utc_now_iso()
with self.engine.begin() as conn:
reserve_write_lock(conn)
@@ -1687,6 +1771,9 @@ class VibeAgentStore:
agent_name=agent.name,
reason="disabled",
)
+ # No audience validation here: the default is advisory and the ACL
+ # is enforced per-principal at use time. The Owner-only gate on this
+ # setter is what bounds who may point instance-wide routing.
self._write_default_agent_name(conn, agent.name, now=now)
def get_default_agent(self, *, enabled_only: bool = True) -> Optional[VibeAgent]:
diff --git a/storage/project_access_service.py b/storage/project_access_service.py
index 7b9bae451..ffc298f5c 100644
--- a/storage/project_access_service.py
+++ b/storage/project_access_service.py
@@ -25,7 +25,7 @@ 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}
+_ROLE_RANK = {"viewer": 1, "editor": 2, "member": 3, "owner": 4}
_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,}$"
diff --git a/storage/projects_service.py b/storage/projects_service.py
index 0dc885925..d81648838 100644
--- a/storage/projects_service.py
+++ b/storage/projects_service.py
@@ -59,8 +59,12 @@ def _resolve_folder(folder_path: str) -> Path:
return folder
-def _find_project_by_workdir(conn: Connection, workdir: str) -> Optional[dict[str, Any]]:
- """Find an existing avibe *project* scope whose folder matches ``workdir``.
+def _find_project_by_workdir(
+ conn: Connection,
+ context: AuthorizationContext,
+ workdir: str,
+) -> Optional[dict[str, Any]]:
+ """Find the visible avibe *project* scope whose folder matches ``workdir``.
Only avibe project scopes are considered: IM channel scopes can carry
their own ``scope_settings.workdir``, so matching across all scopes would
@@ -69,6 +73,15 @@ def _find_project_by_workdir(conn: Connection, workdir: str) -> Optional[dict[st
so it lines up with how projects are stored. When legacy duplicates share a
path, prefer an active row, then the most recently seen, so the pick is
deterministic.
+
+ The visibility check lives *here* rather than in the caller, because a
+ folder path is a lookup key exactly as much as a project id is. Gating the
+ one caller would leave the next one free to skip it; gating the resolver
+ means every way of reaching a project row goes through the same check
+ ``list_projects`` applies. A hidden match raises ``LookupError`` — the same
+ 404 the id-keyed paths answer with — rather than reporting "no match":
+ reporting no match would mint a second project scope over a folder a
+ restricted project already owns, which is a worse outcome than refusing.
"""
row = (
@@ -96,6 +109,7 @@ def _find_project_by_workdir(conn: Connection, workdir: str) -> Optional[dict[st
)
if row is None:
return None
+ _require_visible_project(conn, context, str(row["native_id"]))
return {"scope_id": row["scope_id"], "native_id": row["native_id"], "enabled": row["enabled"]}
@@ -140,6 +154,23 @@ class ProjectAgentUnavailableError(ValueError):
self.agent_name = agent_name
+class ProjectAgentAudienceError(ProjectAgentUnavailableError):
+ """Retained for the coded 400 contract; no longer raised at assignment time.
+
+ A project default used to be rejected unless its resource policy was
+ audience-wide. That check was removed: no predicate over policy shape is
+ both sound and usable (see ``core.vibe_agents`` above
+ ``resolve_usable_default_agent``). The ACL is now enforced per-principal at
+ use time, where a default the caller cannot use degrades to one they can.
+
+ The class stays so the ``project_agent_audience_restricted`` code remains a
+ recognized, machine-distinguishable member of the coded 400 family for any
+ client that still branches on it.
+ """
+
+ code = "project_agent_audience_restricted"
+
+
# Single source of truth for the columns every project payload reads, so
# ``list_projects`` and ``_project_payload`` can never select different shapes.
_PROJECT_COLUMNS = (
@@ -280,6 +311,34 @@ def list_projects(
]
+def _require_visible_project(
+ conn: Connection,
+ context: AuthorizationContext,
+ project_id: str,
+) -> None:
+ """Refuse a Project the caller cannot see, exactly as ``list_projects`` hides it.
+
+ The instance role says whether a principal may administer Projects at all;
+ it does not say *which* Projects. Those are two different questions, and
+ answering only the first is what let a caller who knows an id mutate a
+ restricted Project that ``list_projects`` correctly omits for them.
+
+ ``get_effective_project_role`` is the same helper the list path applies, so
+ the floor here is the visibility floor rather than a second predicate:
+ Instance Owner and Personal installs short-circuit inside it (a Personal
+ install has no Project ACL, so the instance role stays sufficient), an
+ ``inherit`` or absent policy yields the instance role, and a restricted
+ policy yields the caller's binding or nothing at all.
+
+ ``LookupError`` rather than a refusal, matching ``get_project``: a Project
+ the caller may not see must not be distinguishable from one that does not
+ exist, or the 403/404 split enumerates the restricted Projects.
+ """
+
+ if not project_access_service.can_read_project(conn, context, project_id):
+ raise LookupError(f"Project not found: {project_id}")
+
+
def get_project(
conn: Connection,
project_id: str,
@@ -330,13 +389,18 @@ def create_project(
after archiving, without a dedicated unarchive endpoint. The caller's
``display_name`` is intentionally ignored on reuse so re-opening a folder
never clobbers a name the user set earlier; renaming stays explicit.
+
+ Reuse is a project lookup, so it carries the same visibility rule as every
+ other one: ``_find_project_by_workdir`` refuses a match the caller cannot
+ see, which is what stops a folder path from being a side door onto a
+ restricted project's payload — or onto reviving an archived one.
"""
- context = require_instance_role(authorization_context, "owner")
+ context = require_instance_role(authorization_context, "member")
folder = _resolve_folder(folder_path)
now = _utc_now_iso()
- existing = _find_project_by_workdir(conn, str(folder))
+ existing = _find_project_by_workdir(conn, context, str(folder))
if existing is not None:
scope_id = existing["scope_id"]
if not existing["enabled"]:
@@ -415,8 +479,14 @@ def update_project(
lets Project Settings clear the default back to "follow the global default"
by sending ``None``s. Empty strings normalize to ``None`` so an empty pick
clears too.
+
+ A newly selected default is checked for existence and availability only. It
+ is deliberately not validated against the project audience: the ACL is
+ enforced per-principal at use time, where a default a caller cannot use
+ degrades to one they can (``core.vibe_agents.resolve_usable_default_agent``).
"""
- context = require_instance_role(authorization_context, "owner")
+ context = require_instance_role(authorization_context, "member")
+ _require_visible_project(conn, context, project_id)
reserve_write_lock(conn)
scope_id = _make_scope_id(project_id)
existing = conn.execute(select(scopes.c.id).where(scopes.c.id == scope_id)).scalar_one_or_none()
@@ -466,10 +536,9 @@ def update_project(
if selected_agent is None:
raise ProjectAgentUnavailableError(agent_name=cleaned_agent_id)
preserves_current_identity = cleaned_agent_id == current_agent_id
- if not preserves_current_identity and (
- not bool(selected_agent["enabled"]) or selected_agent["archived_at"] is not None
- ):
- raise ProjectAgentUnavailableError(agent_name=selected_agent["name"])
+ if not preserves_current_identity:
+ if not bool(selected_agent["enabled"]) or selected_agent["archived_at"] is not None:
+ raise ProjectAgentUnavailableError(agent_name=selected_agent["name"])
agent_name = selected_agent["name"]
elif agent_name is not _UNSET:
requested_agent = str(agent_name or "").strip() or None
@@ -481,15 +550,15 @@ def update_project(
except ValueError as exc:
raise ProjectAgentUnavailableError(agent_name=requested_agent) from exc
available_agent = conn.execute(
- select(agents.c.name)
+ select(agents.c.id, agents.c.name)
.where(agents.c.normalized_name == normalized_agent)
.where(agents.c.enabled == 1)
.where(agents.c.archived_at.is_(None))
.limit(1)
- ).scalar_one_or_none()
+ ).mappings().first()
if available_agent is None:
raise ProjectAgentUnavailableError(agent_name=requested_agent)
- agent_name = available_agent
+ agent_name = available_agent["name"]
for field_name, value in (
("agent_name", agent_name),
("agent_variant", agent_variant),
@@ -510,7 +579,8 @@ def archive_project(
*,
authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
) -> dict[str, Any]:
- context = require_instance_role(authorization_context, "owner")
+ context = require_instance_role(authorization_context, "member")
+ _require_visible_project(conn, context, project_id)
scope_id = _make_scope_id(project_id)
existing = conn.execute(select(scopes.c.id).where(scopes.c.id == scope_id)).scalar_one_or_none()
if existing is None:
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index c58dcd664..dd98c777f 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -416,7 +416,9 @@ def create_session(
# the global default (see ``update_session``). No project default → the
# fields stay empty and dispatch falls back to the global default Vibe
# Agent. An explicit caller backend always wins.
+ inherited_project_default = False
if not agent_name and not agent_backend and scope_row.get("agent_name") and scope_row.get("agent_backend"):
+ inherited_project_default = True
agent_backend = str(scope_row["agent_backend"])
if agent_name is None:
agent_name = scope_row.get("agent_name")
@@ -428,26 +430,67 @@ def create_session(
reasoning_effort = scope_row.get("reasoning_effort")
from core.vibe_agents import (
+ VibeAgentAccessError,
ensure_agent_selection_access,
ensure_default_agent_access,
+ resolve_effective_default_agent,
resolve_resource_access_context,
)
resource_context = resolve_resource_access_context(user_context)
+ if inherited_project_default:
+ # The project default is a hint from whoever configured the project, not
+ # a choice by this caller, so an Agent they cannot use degrades rather
+ # than refusing the session -- otherwise one narrow default locks every
+ # other member out of starting a normal session in the project. Drop
+ # back to the unpinned path, which resolves the instance default and
+ # degrades again if needed.
+ try:
+ ensure_agent_selection_access(
+ conn,
+ agent_name=agent_name,
+ agent_id=agent_id,
+ user_context=resource_context,
+ )
+ except VibeAgentAccessError:
+ agent_name = None
+ agent_backend = ""
+ agent_variant = None
+ model = None
+ reasoning_effort = None
if not agent_name and not agent_id:
if agent_backend and not resource_context.has_role("editor"):
- from core.vibe_agents import VibeAgentAccessError
-
raise VibeAgentAccessError("Agent access is not permitted.")
if not agent_backend and not resource_context.is_instance_owner:
- # Validate the effective global default without pinning it into the
- # Session. An empty selector must keep following the global default
- # at dispatch time.
- ensure_default_agent_access(
+ # Resolve the effective global default *for this caller*. An empty
+ # selector normally stays empty, so the Session keeps following the
+ # global default at dispatch time -- but a default that degraded has
+ # to be written down, because the substitute exists only in this
+ # caller's frame of reference.
+ #
+ # Dispatch short-circuits on the durable binding
+ # (``SessionTurnManager._resolve_delivery_backend``). A Session left
+ # unpinned instead reaches
+ # ``Controller.resolve_vibe_agent_for_context``, which carries no
+ # principal, re-resolves the raw configured default, and pins that
+ # inaccessible Agent -- after which the remote execution recheck in
+ # ``_remote_delivery_execution_denial`` sees an explicit binding the
+ # caller cannot use and retires their first message. Persisting the
+ # substitute is what makes the degradation actually execute.
+ usable_default = ensure_default_agent_access(
conn,
user_context=resource_context,
missing_is_error=True,
)
+ configured_default = resolve_effective_default_agent(conn)
+ if (
+ usable_default is not None
+ and configured_default is not None
+ and usable_default.id != configured_default.id
+ ):
+ agent_id = usable_default.id
+ agent_name = usable_default.name
+ agent_backend = usable_default.backend
if agent_name or agent_id:
selected_agent = ensure_agent_selection_access(
diff --git a/tests/test_agent_organization_onboarding.py b/tests/test_agent_organization_onboarding.py
index 9e478c440..b2cf801ad 100644
--- a/tests/test_agent_organization_onboarding.py
+++ b/tests/test_agent_organization_onboarding.py
@@ -168,9 +168,15 @@ def test_onboarding_preserves_existing_acl_revision(monkeypatch, tmp_path) -> No
store = VibeAgentStore()
try:
agent = store.create(name="revisioned", backend="codex")
- editor_context = _organization_context(subject="editor-1", instance_role="editor")
- with pytest.raises(VibeAgentAccessError):
- store.organization_onboarding_inventory(user_context=editor_context)
+ # Bulk onboarding claims every policy-less Agent under the caller, so it
+ # is Owner-only. Seed every non-Owner role rather than naming one, so a
+ # role added later is covered here without editing this test.
+ for role in ("viewer", "editor", "member"):
+ context = _organization_context(subject=f"{role}-1", instance_role=role)
+ with pytest.raises(VibeAgentAccessError):
+ store.organization_onboarding_inventory(user_context=context)
+ with pytest.raises(VibeAgentAccessError):
+ store.onboard_organization_agents(user_context=context)
store.onboard_organization_agents(user_context=_organization_context())
_apply_agent_intent(
diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.py
index e65e32b54..946da579f 100644
--- a/tests/test_api_save_config_merge.py
+++ b/tests/test_api_save_config_merge.py
@@ -1619,6 +1619,42 @@ def test_unreadable_optional_feature_fields_never_load_the_feature_back_on(tmp_p
assert recovered.ui.instance_name == "kept"
+ "remote_access",
+ (
+ None,
+ False,
+ [],
+ 0,
+ "",
+ {
+ "provider": "vibe_cloud",
+ "vibe_cloud": {
+ "instance_id": "inst-hijacked",
+ "backend_url": "https://attacker.example",
+ "future_pairing_field": "new-secret",
+ },
+ },
+ ),
+)
+def test_non_owner_config_write_refuses_pairing_identity_in_any_value_shape(remote_access):
+ """Pairing identity is Owner-only, in every value shape, by the same allowlist.
+
+ This used to be a dedicated ``remote_access`` strip applied to non-owner
+ writes. It is now the closed allowlist doing it: ``remote_access`` is not a
+ field any writer below Owner may set, so the write is refused rather than
+ silently accepted with one key removed -- which is also what stops a falsy
+ patch from wiping stored pairing.
+ """
+
+ payload = {"ack_mode": "message", "remote_access": remote_access}
+
+ with pytest.raises(ValueError) as excinfo:
+ api.editor_config_write_payload(payload)
+
+ assert api.editor_config_write_error_code(excinfo.value) == "editor_config_write_forbidden"
+
+
def test_editor_config_write_payload_keeps_messaging_fields_only():
projected = api.editor_config_write_payload(
{
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index 1183bcfed..c3f194553 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -1,9 +1,14 @@
+import re
+
import pytest
from vibe.authorization import (
AuthorizationContext,
InstanceAuthorizationError,
_EDITOR_HTTP_NAMESPACES,
+ _MEMBER_HTTP_RULES,
+ _REMOTE_ACCESS_HTTP_NAMESPACE,
+ _REMOTE_ACCESS_MEMBER_HTTP_RULES,
_VIEWER_HTTP_NAMESPACES,
can_receive_workbench_event,
context_from_session_payload,
@@ -22,21 +27,126 @@ def _context(role: str, *, remote: bool, source: str = "owner") -> Authorization
)
+# Frozen master-era capability bits for editor/viewer. Seeded so a later
+# role or capability cannot silently rewrite those ranks; member is asserted
+# independently below rather than by enumerating every new key.
+_PRE_MEMBER_EDITOR_VIEWER_CAPABILITIES = {
+ "viewer": {
+ "is_instance_owner": False,
+ "can_read_instance": True,
+ "can_chat": False,
+ "can_manage_projects": False,
+ "can_manage_agents": False,
+ "can_manage_instance": False,
+ "can_use_agents": False,
+ "can_use_skills": False,
+ "can_use_vault_secrets": False,
+ "can_use_show_pages": True,
+ "can_use_terminal_files": False,
+ "can_use_terminal": False,
+ "can_use_files": False,
+ "can_use_system": False,
+ },
+ "editor": {
+ "is_instance_owner": False,
+ "can_read_instance": True,
+ "can_chat": True,
+ "can_manage_projects": False,
+ "can_manage_agents": False,
+ "can_manage_instance": False,
+ "can_use_agents": True,
+ "can_use_skills": True,
+ "can_use_vault_secrets": True,
+ "can_use_show_pages": True,
+ "can_use_terminal_files": True,
+ "can_use_terminal": True,
+ "can_use_files": True,
+ "can_use_system": False,
+ },
+}
+
+
def test_capabilities_depend_on_instance_role_not_origin_or_membership() -> None:
- for role in ("viewer", "editor", "owner"):
+ for role in ("viewer", "editor", "member", "owner"):
local = _context(role, remote=False)
remote = _context(role, remote=True, source="organization_group")
assert local.capability_projection() == remote.capability_projection()
viewer = _context("viewer", remote=True, source="organization_group")
editor = _context("editor", remote=True, source="organization_group")
+ member = _context("member", remote=True, source="organization_group")
owner = _context("owner", remote=True, source="organization_group")
assert viewer.can_read_instance and not viewer.can_chat
assert not viewer.can_use_resource("agent")
assert editor.can_chat and editor.can_use_resource("agent")
assert editor.can_use_files and editor.can_use_terminal
assert not editor.can_manage_instance
+ assert member.can_manage_instance and member.can_use_system
+ assert member.has_role("editor") and member.can_use_resource("agent")
+ assert not member.can_manage_access_members
+ assert not member.is_instance_owner
assert owner.can_manage_instance and owner.can_use_system
+ assert owner.can_manage_access_members and owner.is_instance_owner
+
+
+def test_editor_and_viewer_capabilities_match_pre_member_master() -> None:
+ """Editor/viewer bits stay bitwise-equal to master; new keys may appear."""
+
+ for role, expected in _PRE_MEMBER_EDITOR_VIEWER_CAPABILITIES.items():
+ projection = _context(role, remote=True).capability_projection()
+ for key, value in expected.items():
+ assert projection[key] is value, (role, key)
+ assert projection["can_manage_access_members"] is False
+
+
+def test_member_is_owner_minus_member_management() -> None:
+ member = _context("member", remote=True).capability_projection()
+ owner = _context("owner", remote=True).capability_projection()
+ assert set(member) == set(owner)
+ for key, value in owner.items():
+ if key in {"is_instance_owner", "can_manage_access_members"}:
+ assert member[key] is False
+ else:
+ assert member[key] is value
+
+
+def test_unknown_instance_role_fails_closed() -> None:
+ context = context_from_session_payload(
+ {
+ "sub": "user-1",
+ "vibe_instance_role": "admin",
+ "vibe_instance_access_source": "email",
+ }
+ )
+ assert context.instance_role is None
+ projection = context.capability_projection()
+ assert all(value is False for value in projection.values())
+
+
+def test_pre_member_payload_without_member_role_still_loads() -> None:
+ context = context_from_session_payload(
+ {
+ "sub": "user-1",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ }
+ )
+ assert context.instance_role == "editor"
+ assert context.can_chat
+ assert not context.can_manage_instance
+
+
+def test_member_session_payload_is_accepted() -> None:
+ context = context_from_session_payload(
+ {
+ "sub": "user-1",
+ "vibe_instance_role": "member",
+ "vibe_instance_access_source": "email",
+ }
+ )
+ assert context.instance_role == "member"
+ assert context.can_manage_instance
+ assert not context.can_manage_access_members
def test_organization_membership_does_not_elevate_role() -> None:
@@ -127,7 +237,17 @@ def test_http_policy_is_role_only_and_unknown_api_routes_fail_closed() -> None:
for method, path in (("GET", "/api/future-owner-capability"), ("POST", "/api/control")):
assert http_authorization_policy(method, path).minimum_role == "owner"
+ assert (
+ http_authorization_policy("PUT", "/api/permissions/authorized-users").minimum_role
+ == "owner"
+ )
assert http_authorization_policy("GET", "/show/ses-1/").minimum_role == "viewer"
+ assert http_authorization_policy("POST", "/api/remote-access/vibe-cloud/pair").minimum_role == "owner"
+ assert http_authorization_policy("POST", "/api/remote-access/start").minimum_role == "owner"
+ assert http_authorization_policy("POST", "/api/remote-access/stop").minimum_role == "owner"
+ assert http_authorization_policy("POST", "/api/remote-access/settings").minimum_role == "owner"
+ assert http_authorization_policy("POST", "/api/remote-access/future-unpair").minimum_role == "owner"
+ assert http_authorization_policy("GET", "/api/remote-access/status").minimum_role == "member"
def test_advertised_capability_namespaces_cover_current_and_future_routes() -> None:
@@ -135,7 +255,9 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> N
A newly added Skills, Vault, Harness, Files, Dock, Terminal, or Web Push
route must inherit the same Instance role as the rest of that capability.
- Owner-only Agent create/import and unknown APIs stay fail-closed.
+ The member surface is the opposite shape: an explicit allow-list, so an
+ unknown API fails closed to Owner along with allowlist mutation,
+ pairing-identity writes, and instance-wide default-agent routing.
"""
assert _EDITOR_HTTP_NAMESPACES == (
@@ -208,27 +330,134 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> N
for method, path in viewer_examples:
assert http_authorization_policy(method, path).minimum_role == "viewer", path
- owner_examples = (
+ member_examples = (
("POST", "/api/agents"),
("POST", "/api/agents/import"),
("PATCH", "/api/agents/demo"),
("DELETE", "/api/agents/demo"),
+ ("PUT", "/api/models/agents/codex/chain"),
+ ("PUT", "/api/global-prompts"),
+ ("POST", "/api/projects"),
+ ("PATCH", "/api/projects/project-1"),
+ ("PUT", "/api/projects/project-1/agents-md"),
+ ("GET", "/api/settings"),
+ ("GET", "/api/users"),
+ ("GET", "/api/remote-access/status"),
+ ("GET", "/api/remote-access/network-interfaces"),
+ ("POST", "/api/remote-access/optimize-route"),
+ ("POST", "/api/remote-access/diagnostics"),
+ )
+ for method, path in member_examples:
+ assert http_authorization_policy(method, path).minimum_role == "member", path
+
+ owner_examples = (
+ # Unknown APIs, present and future, keep the role they had before the
+ # member rank existed.
("GET", "/api/future-owner-capability"),
+ ("POST", "/api/control"),
+ ("POST", "/api/upgrade"),
+ ("POST", "/api/logs"),
+ ("POST", "/api/backend/codex/auth"),
+ # Access administration and bearer credentials.
+ ("PUT", "/api/permissions/authorized-users"),
+ ("GET", "/api/users/bind-codes"),
+ ("POST", "/api/users/first-bind-code"),
+ # ACL writes and the IM access boundary.
+ ("PUT", "/api/permissions/projects/project-1/access"),
+ ("PUT", "/api/permissions/resources/agent/agent-1/access"),
+ ("POST", "/api/settings"),
+ ("POST", "/api/settings/thread"),
+ # Host reach.
("POST", "/api/browse"),
("POST", "/api/browse/mkdir"),
+ # Instance-wide Agent routing and bulk migration.
+ ("POST", "/api/agents/default"),
+ ("GET", "/api/agent-onboarding"),
+ ("POST", "/api/agent-onboarding"),
)
for method, path in owner_examples:
assert http_authorization_policy(method, path).minimum_role == "owner", path
+ assert _REMOTE_ACCESS_HTTP_NAMESPACE == "/api/remote-access"
+ assert {(method, pattern.pattern) for method, pattern in _REMOTE_ACCESS_MEMBER_HTTP_RULES} == {
+ ("GET", r"^/api/remote-access/status$"),
+ ("GET", r"^/api/remote-access/network-interfaces$"),
+ ("POST", r"^/api/remote-access/optimize-route$"),
+ ("POST", r"^/api/remote-access/diagnostics$"),
+ }
+
+
+def test_member_reachable_routes_are_bounded_by_declaration() -> None:
+ """Sweep the live router: nothing is member-reachable except by declaration.
+
+ The member rank was first added as the *fallback* for an unclassified
+ ``/api`` route. That inverted default-deny: every management route no other
+ table happened to name was silently widened -- ``POST /api/control``,
+ ``POST /api/upgrade``, the ``/api/backend/*/auth`` routes, the ACL PUTs, and
+ a hundred more. Review could only find them one head at a time, because a
+ list of Owner exceptions is never more complete than the last audit.
+
+ So the fallback is Owner and the member surface is the allow-list, and this
+ is the property that replaces those exceptions: every registered ``/api``
+ route resolves to an explicit tier; a route resolves to member only because
+ ``_MEMBER_HTTP_RULES`` or the remote-access ops quartet says so; and a route
+ the router does not have yet resolves to Owner. A management route added
+ tomorrow therefore keeps exactly the role it would have had before this rank
+ existed.
+ """
+
+ from vibe.ui_server import app
+
+ def _member_declared(method: str, path: str) -> bool:
+ return any(
+ rule_method == method and pattern.fullmatch(path)
+ for rule_method, pattern in (*_MEMBER_HTTP_RULES, *_REMOTE_ACCESS_MEMBER_HTTP_RULES)
+ )
+
+ seen_member = False
+ swept = 0
+ for route in app.routes:
+ raw_path = getattr(route, "path", None) or ""
+ if not raw_path.startswith("/api/") and raw_path != "/api":
+ continue
+ path = _sample_path(raw_path)
+ for method in sorted(getattr(route, "methods", None) or ()):
+ method = method.upper()
+ if method in {"HEAD", "OPTIONS"}:
+ continue
+ swept += 1
+ policy = http_authorization_policy(method, path)
+ assert policy is not None, f"{method} {path}"
+ assert policy.minimum_role in {"viewer", "editor", "member", "owner"}, f"{method} {path}"
+ if policy.minimum_role == "member":
+ seen_member = True
+ assert _member_declared(method, path), (
+ f"{method} {path} is member-reachable without a declared rule"
+ )
+ assert swept > 100, "router sweep found too few /api routes to be meaningful"
+ assert seen_member, "the member surface must be reachable from the live router"
+
+ # A route nobody has classified -- including one that does not exist yet --
+ # is Owner, not member.
+ for method in ("GET", "POST", "PUT", "PATCH", "DELETE"):
+ synthetic = http_authorization_policy(method, "/api/route-added-after-the-member-rank")
+ assert synthetic is not None
+ assert synthetic.minimum_role == "owner", method
+
def test_workbench_events_follow_role_boundaries() -> None:
viewer = _context("viewer", remote=True)
editor = _context("editor", remote=True)
+ member = _context("member", remote=True)
owner = _context("owner", remote=True)
assert can_receive_workbench_event(viewer, "message.new")
assert not can_receive_workbench_event(viewer, "queue.updated")
assert can_receive_workbench_event(editor, "queue.updated")
assert not can_receive_workbench_event(editor, "runs.updated")
+ assert can_receive_workbench_event(member, "runs.updated")
+ assert can_receive_workbench_event(member, "definitions.updated")
+ assert can_receive_workbench_event(member, "vaults.updated")
+ assert not can_receive_workbench_event(member, "future.management.event")
assert can_receive_workbench_event(owner, "runs.updated")
assert not can_receive_workbench_event(viewer, "future.management.event")
@@ -252,3 +481,750 @@ def test_session_service_mutations_recheck_instance_role() -> None:
agent_backend="codex",
authorization_context=viewer,
)
+
+
+def test_advertised_manage_capabilities_are_honored_by_service_guards() -> None:
+ """Project CRUD follows can_manage_projects, not owner identity.
+
+ Seed every existing instance role so a leftover require_instance_role(...,
+ "owner") or is_instance_owner check cannot silently deny member while the
+ capability projection still advertises the surface. Bulk Agent onboarding is
+ asserted separately below: it is an instance-wide migration rather than an
+ advertised management surface, so it stays on Owner identity.
+ """
+
+ for role in ("viewer", "editor", "member", "owner"):
+ context = _context(role, remote=True)
+ if context.can_manage_projects:
+ assert require_instance_role(context, "member") is context
+ else:
+ with pytest.raises(InstanceAuthorizationError):
+ require_instance_role(context, "member")
+
+
+def test_bulk_agent_onboarding_follows_owner_identity() -> None:
+ """Onboarding is a migration tool, so only the Instance Owner may run it.
+
+ Seed every existing instance role rather than naming the rejected ones, so a
+ role added later is covered here without editing this test: the property is
+ that exactly the Owner passes. Deliberately not gated on
+ ``can_manage_access_members`` -- claiming every policy-less Agent is not
+ member management, it is an instance-wide one-way migration.
+ """
+
+ from core.vibe_agents import VibeAgentAccessError, _require_agent_onboarding_access
+
+ for role in ("viewer", "editor", "member", "owner"):
+ context = _context(role, remote=True)
+ if context.is_instance_owner:
+ assert _require_agent_onboarding_access(context) is context
+ else:
+ with pytest.raises(VibeAgentAccessError):
+ _require_agent_onboarding_access(context)
+
+
+_REMOTE_ACCESS_MEMBER_OPS = frozenset(
+ {
+ ("GET", "/api/remote-access/status"),
+ ("GET", "/api/remote-access/network-interfaces"),
+ ("POST", "/api/remote-access/optimize-route"),
+ ("POST", "/api/remote-access/diagnostics"),
+ }
+)
+
+
+def _registered_remote_access_routes():
+ from vibe.ui_server import app
+
+ routes = []
+ for route in app.routes:
+ path = getattr(route, "path", None)
+ methods = getattr(route, "methods", None) or ()
+ if not path or not path.startswith("/api/remote-access"):
+ continue
+ for method in methods:
+ if method in {"HEAD", "OPTIONS"}:
+ continue
+ routes.append((method.upper(), path))
+ return tuple(sorted(set(routes)))
+
+
+def _remote_access_ok_payload(method: str, path: str) -> dict:
+ if method == "GET" and path.endswith("/status"):
+ return {"ok": True, "paired": True, "running": False}
+ if method == "GET" and path.endswith("/network-interfaces"):
+ return {"ok": True, "interfaces": []}
+ if path.endswith("/optimize-route"):
+ return {"ok": True}
+ if path.endswith("/diagnostics"):
+ return {"ok": True, "checks": []}
+ return {"ok": True}
+
+
+def _install_remote_access_handler_stubs(monkeypatch) -> None:
+ from vibe import remote_access
+
+ monkeypatch.setattr(
+ remote_access,
+ "status",
+ lambda *args, **kwargs: _remote_access_ok_payload("GET", "/api/remote-access/status"),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "network_interfaces",
+ lambda *args, **kwargs: _remote_access_ok_payload(
+ "GET", "/api/remote-access/network-interfaces"
+ ),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "optimize_route",
+ lambda *args, **kwargs: _remote_access_ok_payload(
+ "POST", "/api/remote-access/optimize-route"
+ ),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "connectivity_diagnostics",
+ lambda *args, **kwargs: _remote_access_ok_payload(
+ "POST", "/api/remote-access/diagnostics"
+ ),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "pair",
+ lambda *args, **kwargs: _remote_access_ok_payload(
+ "POST", "/api/remote-access/vibe-cloud/pair"
+ ),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "start",
+ lambda *args, **kwargs: _remote_access_ok_payload("POST", "/api/remote-access/start"),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "stop",
+ lambda *args, **kwargs: _remote_access_ok_payload("POST", "/api/remote-access/stop"),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "apply_settings",
+ lambda *args, **kwargs: _remote_access_ok_payload(
+ "POST", "/api/remote-access/settings"
+ ),
+ )
+
+
+def _request_remote_access(client, method: str, path: str, headers: dict[str, str]):
+ from tests.ui_server_test_helpers import remote_peer
+
+ kwargs = {
+ "headers": headers,
+ "base_url": "https://alex.avibe.bot",
+ "environ_base": remote_peer(),
+ }
+ if method not in {"GET", "HEAD", "OPTIONS"}:
+ kwargs["json"] = {}
+ return client.request(method, path, **kwargs)
+
+
+def test_registered_remote_access_writes_default_to_owner(monkeypatch, tmp_path) -> None:
+ """Every registered /api/remote-access write is owner unless it is a named ops route.
+
+ Introspect the live router so a newly added pair/unpair/settings sibling
+ fails this test until it is classified. Viewer and editor stay 403 on the
+ whole namespace, matching master. Member keeps the four ops that cannot
+ change pairing identity.
+ """
+
+ from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie, save_config
+ from vibe import remote_access
+ from vibe.ui_server import app
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = save_config(tmp_path)
+ _install_remote_access_handler_stubs(monkeypatch)
+
+ routes = _registered_remote_access_routes()
+ assert routes, "router must expose /api/remote-access"
+ for method, path in _REMOTE_ACCESS_MEMBER_OPS:
+ assert (method, path) in routes, f"{method} {path} must remain registered"
+
+ for method, path in routes:
+ policy = http_authorization_policy(method, path)
+ if (method, path) in _REMOTE_ACCESS_MEMBER_OPS:
+ assert policy.minimum_role == "member", f"{method} {path}"
+ else:
+ assert policy.minimum_role == "owner", (
+ f"{method} {path} must default-deny to owner"
+ )
+
+ for role in ("viewer", "editor", "member", "owner"):
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ f"{role}@example.com",
+ f"{role}-1",
+ role=role,
+ access_source="email" if role != "owner" else "owner",
+ ),
+ domain="alex.avibe.bot",
+ )
+ headers = csrf_headers(client, base_url="https://alex.avibe.bot")
+ for method, path in routes:
+ response = _request_remote_access(client, method, path, headers)
+ policy_role = http_authorization_policy(method, path).minimum_role
+ admitted = _context(role, remote=True).has_role(policy_role or "owner")
+ if admitted:
+ assert response.status_code != 403, f"{role} {method} {path}"
+ else:
+ assert response.status_code == 403, f"{role} {method} {path}"
+ assert response.get_json()["error"] == "instance_access_forbidden"
+
+
+# Namespaces whose routes decide who reaches this instance at all. Contract
+# amendment (issue #1596): the member set an Owner controls is cloud allowlist
+# entries AND multi-platform IM bound users, so the IM bound-user and bind-code
+# routes are member management. ``/api/agent-onboarding`` is in the sweep for a
+# different reason -- it is an instance-wide one-way Agent migration -- but the
+# assertion is the same: Owner-only.
+_ACCESS_ADMINISTRATION_NAMESPACES = (
+ "/api/users",
+ "/api/bind-codes",
+ "/api/setup/first-bind-code",
+ "/api/agent-onboarding",
+)
+
+# The only route in those namespaces allowed below Owner: it discloses the member
+# set without disclosing or minting a credential, matching the cloud allowlist
+# whose GET is member and whose PUT is Owner. Everything else registered in the
+# namespaces now or later must be Owner, which is what the sweep asserts.
+_ACCESS_ADMINISTRATION_MEMBER_READS = frozenset({("GET", "/api/users")})
+
+
+def _registered_access_administration_routes():
+ from vibe.ui_server import app
+
+ routes = []
+ for route in app.routes:
+ path = getattr(route, "path", None) or ""
+ if not path.startswith(_ACCESS_ADMINISTRATION_NAMESPACES):
+ continue
+ for method in getattr(route, "methods", None) or ():
+ if method in {"HEAD", "OPTIONS"}:
+ continue
+ routes.append((method.upper(), path))
+ return tuple(sorted(set(routes)))
+
+
+def _sample_path(path: str) -> str:
+ """Fill router path parameters so the route can actually be requested."""
+
+ return re.sub(r"\{[^}]+\}", "sample-1", path)
+
+
+def _install_access_administration_stubs(monkeypatch) -> None:
+ """Stub the handlers so only the authorization outcome is under test."""
+
+ from vibe import api
+
+ ok = {"ok": True}
+ for name in (
+ "get_users",
+ "save_users",
+ "toggle_admin",
+ "remove_user",
+ "get_bind_codes",
+ "create_bind_code",
+ "delete_bind_code",
+ "get_first_bind_code",
+ "get_vibe_agent_onboarding",
+ "onboard_vibe_agents",
+ ):
+ monkeypatch.setattr(api, name, lambda *args, **kwargs: dict(ok))
+
+
+def test_registered_access_administration_routes_are_owner_only(monkeypatch, tmp_path) -> None:
+ """Minting or mutating instance access is Owner-only, at policy and handler.
+
+ Enumerated from the live router rather than from a list of known routes, so a
+ bind-code, bound-user, or onboarding sibling added later is covered the day it
+ is registered -- it inherits Owner from the unknown-route default and only a
+ deliberate ``_MEMBER_HTTP_RULES`` entry can widen it. Editor and viewer stay
+ 403 across the whole set, matching master, where every one of these routes was
+ already above their rank.
+ """
+
+ from tests.ui_server_test_helpers import (
+ csrf_headers,
+ remote_peer,
+ remote_session_cookie,
+ save_config,
+ )
+ from vibe import remote_access
+ from vibe.ui_server import app
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = save_config(tmp_path)
+ _install_access_administration_stubs(monkeypatch)
+
+ routes = _registered_access_administration_routes()
+ assert routes, "router must expose the access-administration namespaces"
+
+ for method, path in routes:
+ policy = http_authorization_policy(method, _sample_path(path))
+ if (method, path) in _ACCESS_ADMINISTRATION_MEMBER_READS:
+ assert policy.minimum_role == "member", f"{method} {path}"
+ else:
+ assert policy.minimum_role == "owner", f"{method} {path} must be Owner-only"
+
+ for role in ("viewer", "editor", "member", "owner"):
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ f"{role}@example.com",
+ f"{role}-1",
+ role=role,
+ access_source="email" if role != "owner" else "owner",
+ ),
+ domain="alex.avibe.bot",
+ )
+ headers = csrf_headers(client, base_url="https://alex.avibe.bot")
+ for method, path in routes:
+ request_path = _sample_path(path)
+ kwargs = {
+ "headers": headers,
+ "base_url": "https://alex.avibe.bot",
+ "environ_base": remote_peer(),
+ }
+ if method not in {"GET", "HEAD", "OPTIONS"}:
+ kwargs["json"] = {}
+ response = client.request(method, request_path, **kwargs)
+ policy_role = http_authorization_policy(method, request_path).minimum_role
+ admitted = _context(role, remote=True).has_role(policy_role or "owner")
+ if admitted:
+ assert response.status_code != 403, f"{role} {method} {request_path}"
+ else:
+ assert response.status_code == 403, f"{role} {method} {request_path}"
+ assert response.get_json()["error"] == "instance_access_forbidden"
+
+
+def test_agent_cli_install_is_owner_only(monkeypatch, tmp_path) -> None:
+ """Installing a backend CLI is host lifecycle, so it stays above member.
+
+ The handler shells out to a package manager, a self-update, or a curl
+ script, records the resulting CLI path, and can restart the backend. That is
+ the "dependency installs" bullet the member policy declares Owner, and it
+ had been on the member allow-list while the comment above that table said
+ otherwise -- the table is hand-written, so the policy and its entries can
+ disagree silently.
+
+ Enforcement is by absence: neither route is declared, so both inherit the
+ unknown-route Owner default and need no exception entry. Asserting the
+ absence *and* the 403 it produces keeps those two from drifting apart, and
+ the owner leg proves the routes are still live rather than unreachable for
+ everyone. The install implementation is stubbed, so no package manager runs
+ and the assertion at the end is what proves it: only the owner leg ever
+ reached the handler.
+ """
+
+ from tests.ui_server_test_helpers import (
+ csrf_headers,
+ remote_peer,
+ remote_session_cookie,
+ save_config,
+ )
+ from vibe import api, remote_access
+ from vibe.ui_server import app
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = save_config(tmp_path)
+
+ reached: list[tuple[str, str]] = []
+
+ def _start(name: str) -> dict:
+ reached.append(("start", name))
+ return {"ok": True, "job_id": "job-1", "backend": name, "status": "running"}
+
+ def _status(job_id: str, *, backend: str) -> dict:
+ reached.append(("status", job_id))
+ return {"ok": True, "job_id": job_id, "backend": backend, "status": "success"}
+
+ monkeypatch.setattr(api, "start_agent_install_job", _start)
+ monkeypatch.setattr(api, "get_agent_install_job", _status)
+
+ routes = (
+ ("POST", "/api/agent/claude/install"),
+ ("GET", "/api/agent/claude/install/job-1"),
+ )
+ for method, path in routes:
+ assert not any(
+ rule_method == method and pattern.fullmatch(path)
+ for rule_method, pattern in _MEMBER_HTTP_RULES
+ ), f"{method} {path} must not be declared on the member allow-list"
+ assert http_authorization_policy(method, path).minimum_role == "owner", f"{method} {path}"
+
+ for role in ("viewer", "editor", "member", "owner"):
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ f"{role}@example.com",
+ f"{role}-1",
+ role=role,
+ access_source="email" if role != "owner" else "owner",
+ ),
+ domain="alex.avibe.bot",
+ )
+ headers = csrf_headers(client, base_url="https://alex.avibe.bot")
+ for method, path in routes:
+ kwargs = {
+ "headers": headers,
+ "base_url": "https://alex.avibe.bot",
+ "environ_base": remote_peer(),
+ }
+ if method != "GET":
+ kwargs["json"] = {}
+ response = client.request(method, path, **kwargs)
+ if role == "owner":
+ assert response.status_code == 200, f"{role} {method} {path}"
+ assert response.get_json()["ok"] is True, f"{role} {method} {path}"
+ else:
+ assert response.status_code == 403, f"{role} {method} {path}"
+ assert response.get_json()["error"] == "instance_access_forbidden"
+
+ assert reached == [("start", "claude"), ("status", "job-1")], (
+ "only the owner leg may reach the install handler"
+ )
+
+
+def test_access_administration_handlers_gate_without_the_route_policy(monkeypatch, tmp_path) -> None:
+ """The handler gate stands on its own, not only the route policy table.
+
+ Two layers answer one question, so this drives the handlers with the policy
+ table neutralised: a route re-registered under a path the table does not
+ recognise must still refuse a member.
+ """
+
+ from tests.ui_server_test_helpers import (
+ csrf_headers,
+ remote_peer,
+ remote_session_cookie,
+ save_config,
+ )
+ from vibe import authorization, remote_access
+ from vibe.authorization import HttpAuthorizationPolicy
+ from vibe.ui_server import app
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = save_config(tmp_path)
+ _install_access_administration_stubs(monkeypatch)
+ # The request hook imports this by name at call time, so replacing the
+ # module attribute really does disarm the policy layer for this test.
+ monkeypatch.setattr(
+ authorization,
+ "http_authorization_policy",
+ lambda *args, **kwargs: HttpAuthorizationPolicy("member"),
+ )
+
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ "member-1",
+ role="member",
+ access_source="email",
+ ),
+ domain="alex.avibe.bot",
+ )
+ headers = csrf_headers(client, base_url="https://alex.avibe.bot")
+ for method, path in _registered_access_administration_routes():
+ if (method, path) in _ACCESS_ADMINISTRATION_MEMBER_READS:
+ continue
+ request_path = _sample_path(path)
+ kwargs = {
+ "headers": headers,
+ "base_url": "https://alex.avibe.bot",
+ "environ_base": remote_peer(),
+ }
+ if method not in {"GET", "HEAD", "OPTIONS"}:
+ kwargs["json"] = {}
+ response = client.request(method, request_path, **kwargs)
+ assert response.status_code == 403, f"member {method} {request_path}"
+
+
+ "remote_access_payload",
+ (
+ None,
+ False,
+ [],
+ 0,
+ "",
+ {
+ "vibe_cloud": {
+ "instance_id": "inst-hijacked",
+ "backend_url": "https://attacker.example",
+ "instance_secret": "stolen-secret",
+ "tunnel_token": "stolen-tunnel",
+ "session_secret": "stolen-session",
+ "enabled": False,
+ }
+ },
+ ),
+)
+def test_member_config_write_cannot_change_pairing_identity(
+ monkeypatch, tmp_path, remote_access_payload
+) -> None:
+ """Member POST /api/config cannot change pairing identity in any value shape.
+
+ The refusal is the Editor allowlist, which every writer below Owner now runs:
+ ``remote_access`` is not a field they may set, so the write is rejected
+ outright rather than accepted with one key quietly removed. Stored pairing is
+ asserted unchanged either way — the point is the identity, not the status code.
+ """
+
+ from config.v2_config import V2Config
+ from tests.ui_server_test_helpers import csrf_headers, remote_peer, remote_session_cookie, save_config
+ from vibe import remote_access
+ from vibe.ui_server import app
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = save_config(tmp_path)
+ cloud = config.remote_access.vibe_cloud
+ cloud.backend_url = "https://backend.example"
+ cloud.instance_secret = "device-secret"
+ cloud.tunnel_token = "tunnel-token"
+ config.save()
+ remote_access._replace_authorization_revision(config, 1) # noqa: SLF001
+ cookie = remote_session_cookie(
+ config,
+ "member-1",
+ role="member",
+ access_source="email",
+ session_claims={
+ "vibe_instance_id": cloud.instance_id,
+ "vibe_instance_role": "member",
+ "vibe_instance_access_source": "email",
+ "vibe_instance_authorization_revision": 1,
+ },
+ )
+ before = V2Config.load().remote_access.vibe_cloud
+ monkeypatch.setattr(remote_access, "reconcile", lambda: {"ok": True})
+
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ cookie,
+ domain="alex.avibe.bot",
+ )
+ headers = csrf_headers(client, base_url="https://alex.avibe.bot")
+ response = client.post(
+ "/api/config",
+ json={"remote_access": remote_access_payload},
+ headers=headers,
+ base_url="https://alex.avibe.bot",
+ environ_base=remote_peer(),
+ )
+
+ assert response.status_code == 400
+ assert response.get_json()["error"] == {
+ "code": "editor_config_write_forbidden",
+ "message": "editor_config_write_forbidden",
+ }
+ after = V2Config.load().remote_access.vibe_cloud
+ assert after.instance_id == before.instance_id == "inst_123"
+ assert after.backend_url == before.backend_url == "https://backend.example"
+ assert after.instance_secret == before.instance_secret == "device-secret"
+ assert after.tunnel_token == before.tunnel_token == "tunnel-token"
+ assert after.session_secret == before.session_secret == "session-secret"
+ assert after.enabled is True
+
+
+def test_pair_is_forbidden_for_member_and_succeeds_for_owner(monkeypatch, tmp_path) -> None:
+ from tests.ui_server_test_helpers import csrf_headers, remote_peer, remote_session_cookie, save_config
+ from vibe import remote_access
+ from vibe.ui_server import app
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = save_config(tmp_path)
+ paired: list[tuple[str, str, str]] = []
+
+ def pair(pairing_key, backend_url, device_name):
+ paired.append((pairing_key, backend_url, device_name))
+ return {"ok": True, "instance_id": "inst_new"}
+
+ monkeypatch.setattr(remote_access, "pair", pair)
+
+ member_client = app.test_client()
+ member_client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ "member-1",
+ role="member",
+ access_source="email",
+ ),
+ domain="alex.avibe.bot",
+ )
+ member_headers = csrf_headers(member_client, base_url="https://alex.avibe.bot")
+ member_response = member_client.post(
+ "/api/remote-access/vibe-cloud/pair",
+ json={"pairing_key": "key", "backend_url": "https://avibe.bot"},
+ headers=member_headers,
+ base_url="https://alex.avibe.bot",
+ environ_base=remote_peer(),
+ )
+ assert member_response.status_code == 403
+ assert member_response.get_json()["error"] == "instance_access_forbidden"
+ assert paired == []
+
+ owner_client = app.test_client()
+ owner_client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ "owner-1",
+ role="owner",
+ access_source="owner",
+ ),
+ domain="alex.avibe.bot",
+ )
+ owner_headers = csrf_headers(owner_client, base_url="https://alex.avibe.bot")
+ owner_response = owner_client.post(
+ "/api/remote-access/vibe-cloud/pair",
+ json={"pairing_key": "key", "backend_url": "https://avibe.bot", "device_name": "avibe"},
+ headers=owner_headers,
+ base_url="https://alex.avibe.bot",
+ environ_base=remote_peer(),
+ )
+ assert owner_response.status_code == 200
+ assert owner_response.get_json()["ok"] is True
+ assert paired == [("key", "https://avibe.bot", "avibe")]
+
+
+def test_member_cannot_set_instance_default_agent(monkeypatch, tmp_path) -> None:
+ """Instance-wide default routing is Owner-only, and that is the whole gate.
+
+ A member is refused twice over -- by the store's own permission check and by
+ the route policy -- and the Owner may then point routing at any Agent,
+ including one narrower than the instance audience. Nothing about the target's
+ policy shape is validated here: a default is advisory and the ACL is enforced
+ per-principal at use time (``core.vibe_agents.resolve_usable_default_agent``),
+ which is covered in ``tests/test_resource_acl_agents.py``.
+ """
+
+ from core.vibe_agents import VibeAgentAccessError, VibeAgentStore
+ from tests.ui_server_test_helpers import csrf_headers, remote_peer, remote_session_cookie, save_config
+ from vibe import remote_access
+ from vibe.ui_server import app
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = save_config(tmp_path)
+ member = AuthorizationContext(
+ instance_role="member",
+ subject="member-1",
+ instance_access_source="email",
+ is_remote=True,
+ )
+ store = VibeAgentStore()
+ try:
+ default_agent = store.ensure_builtin_default_agent(backend="codex")
+ store.set_default_agent_name(default_agent.name)
+ before = store.get_default_agent_name()
+ private_agent = store.create(
+ name="member-private",
+ backend="codex",
+ user_context=member,
+ )
+ with pytest.raises(VibeAgentAccessError):
+ store.set_default_agent_name(private_agent.name, user_context=member)
+ assert store.get_default_agent_name() == before
+ finally:
+ store.close()
+
+ member_client = app.test_client()
+ member_client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ "member-1",
+ role="member",
+ access_source="email",
+ ),
+ domain="alex.avibe.bot",
+ )
+ member_headers = csrf_headers(member_client, base_url="https://alex.avibe.bot")
+ member_response = member_client.post(
+ "/api/agents/default",
+ json={"name": "member-private"},
+ headers=member_headers,
+ base_url="https://alex.avibe.bot",
+ environ_base=remote_peer(),
+ )
+ assert member_response.status_code == 403
+ assert member_response.get_json()["error"] == "instance_access_forbidden"
+ store = VibeAgentStore()
+ try:
+ assert store.get_default_agent_name() == before
+ finally:
+ store.close()
+
+ owner_client = app.test_client()
+ owner_client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ "owner-1",
+ role="owner",
+ access_source="owner",
+ ),
+ domain="alex.avibe.bot",
+ )
+ owner_headers = csrf_headers(owner_client, base_url="https://alex.avibe.bot")
+ # Owner-only is the whole gate. The same Agent the member could not publish
+ # is accepted from the Owner, because the target's audience is a use-time
+ # question rather than a bind-time one.
+ owner_response = owner_client.post(
+ "/api/agents/default",
+ json={"name": "member-private"},
+ headers=owner_headers,
+ base_url="https://alex.avibe.bot",
+ environ_base=remote_peer(),
+ )
+ assert owner_response.status_code == 200
+ store = VibeAgentStore()
+ try:
+ assert store.get_default_agent_name() == "member-private"
+ store.create(name="team-shared", backend="codex")
+ finally:
+ store.close()
+
+ shared_response = owner_client.post(
+ "/api/agents/default",
+ json={"name": "team-shared"},
+ headers=owner_headers,
+ base_url="https://alex.avibe.bot",
+ environ_base=remote_peer(),
+ )
+ assert shared_response.status_code == 200
+ assert shared_response.get_json()["ok"] is True
+ store = VibeAgentStore()
+ try:
+ assert store.get_default_agent_name() == "team-shared"
+ finally:
+ store.close()
diff --git a/tests/test_permissions.py b/tests/test_permissions.py
index d32470825..00d2272ef 100644
--- a/tests/test_permissions.py
+++ b/tests/test_permissions.py
@@ -2325,6 +2325,8 @@ def test_permissions_http_policy_allows_viewer_reads_but_owner_only_mutations()
http_authorization_policy("PUT", "/api/permissions/authorized-users").minimum_role
== "owner"
)
+ # An ACL write decides who may reach a resource, so it sits with access
+ # administration rather than with the resource's own management capability.
assert (
http_authorization_policy("PUT", "/api/permissions/projects/project-1/access").minimum_role
== "owner"
@@ -2508,6 +2510,162 @@ def test_permissions_same_origin_route_surfaces_a_changed_pairing(monkeypatch) -
}
+def test_member_cannot_write_either_access_control_list(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """Deciding who may reach a resource is access administration, so Owner-only.
+
+ The member rank grants Agent and project *management*, not the authority to
+ widen who can reach them. Both ACL writes are refused at the route policy, so
+ neither handler is entered; the Owner keeps both.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = save_config(tmp_path)
+ authorized_users_called = False
+ project_access_called = False
+
+ def replace(_payload):
+ nonlocal authorized_users_called
+ authorized_users_called = True
+ return {"ok": True, "instance_id": "inst-123", "entries": [], "authorization_revision": 4}
+
+ def update(_project_id, _payload):
+ nonlocal project_access_called
+ project_access_called = True
+ return {
+ "ok": True,
+ "instance_id": "inst-123",
+ "project": _complete_projection()["projects"][0],
+ "authorization_revision": 4,
+ }
+
+ monkeypatch.setattr(permissions, "replace_authorized_users", replace)
+ monkeypatch.setattr(permissions, "update_project_access", update)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ "member-1",
+ role="member",
+ access_source="email",
+ ),
+ domain="alex.avibe.bot",
+ )
+ headers = csrf_headers(client, base_url="https://alex.avibe.bot")
+
+ project_response = client.put(
+ "/api/permissions/projects/project-1/access",
+ json={
+ "mode": "inherit",
+ "bindings": [],
+ "if_match_revision": 3,
+ "if_match_instance_id": "inst-123",
+ },
+ headers=headers,
+ base_url="https://alex.avibe.bot",
+ environ_base=remote_peer(),
+ )
+ users_response = client.put(
+ "/api/permissions/authorized-users",
+ json={
+ "entries": [],
+ "if_match_revision": 3,
+ "if_match_instance_id": "inst-123",
+ },
+ headers=headers,
+ base_url="https://alex.avibe.bot",
+ environ_base=remote_peer(),
+ )
+
+ assert project_response.status_code == 403
+ assert project_response.get_json()["error"] == "instance_access_forbidden"
+ assert project_access_called is False
+ assert users_response.status_code == 403
+ assert users_response.get_json()["error"] == "instance_access_forbidden"
+ assert authorized_users_called is False
+
+ owner_client = app.test_client()
+ owner_client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ "owner-1",
+ role="owner",
+ access_source="owner",
+ ),
+ domain="alex.avibe.bot",
+ )
+ owner_response = owner_client.put(
+ "/api/permissions/projects/project-1/access",
+ json={
+ "mode": "inherit",
+ "bindings": [],
+ "if_match_revision": 3,
+ "if_match_instance_id": "inst-123",
+ },
+ headers=csrf_headers(owner_client, base_url="https://alex.avibe.bot"),
+ base_url="https://alex.avibe.bot",
+ environ_base=remote_peer(),
+ )
+ assert owner_response.status_code == 200
+ assert project_access_called is True
+
+
+def test_owner_can_mutate_authorized_users(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = save_config(tmp_path)
+ called = False
+
+ def replace(payload):
+ nonlocal called
+ called = True
+ assert payload["entries"] == [
+ {"kind": "email", "value": "[email protected]", "role": "member"}
+ ]
+ return {
+ "ok": True,
+ "instance_id": "inst-123",
+ "entries": payload["entries"],
+ "authorization_revision": 5,
+ }
+
+ monkeypatch.setattr(permissions, "replace_authorized_users", replace)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ "owner-1",
+ role="owner",
+ access_source="owner",
+ ),
+ domain="alex.avibe.bot",
+ )
+ headers = csrf_headers(client, base_url="https://alex.avibe.bot")
+ response = client.put(
+ "/api/permissions/authorized-users",
+ json={
+ "entries": [
+ {"kind": "email", "value": "[email protected]", "role": "member"}
+ ],
+ "if_match_revision": 4,
+ "if_match_instance_id": "inst-123",
+ },
+ headers=headers,
+ base_url="https://alex.avibe.bot",
+ environ_base=remote_peer(),
+ )
+
+ assert response.status_code == 200
+ assert called is True
+
+
def test_resource_access_same_origin_routes_forward_exact_identity_and_conflict(
monkeypatch,
) -> None:
diff --git a/tests/test_project_access_service.py b/tests/test_project_access_service.py
index 626c250a3..b6c72fe87 100644
--- a/tests/test_project_access_service.py
+++ b/tests/test_project_access_service.py
@@ -77,6 +77,9 @@ def test_missing_and_inherit_policies_preserve_instance_role(tmp_path) -> None:
)
assert result.outcome == "applied"
assert project_access_service.get_effective_project_role(conn, editor, project["id"]) == "editor"
+ assert project_access_service.get_effective_project_role(
+ conn, _context("member"), project["id"]
+ ) == "member"
def test_restricted_policy_matches_email_domain_and_group(tmp_path) -> None:
@@ -194,6 +197,33 @@ def test_highest_match_is_capped_by_instance_role(tmp_path) -> None:
assert project_access_service.get_effective_project_role(
conn, _context("editor"), project["id"]
) == "editor"
+ assert project_access_service.get_effective_project_role(
+ conn, _context("member"), project["id"]
+ ) == "editor"
+
+
+def test_project_binding_rejects_member_access_role(tmp_path) -> None:
+ engine, project = _engine_with_project(tmp_path)
+ with engine.begin() as conn:
+ result = project_access_service.apply_project_access_intent(
+ conn,
+ _intent(
+ project["id"],
+ 1,
+ bindings=[
+ {
+ "principal_kind": "email",
+ "principal_value": "[email protected]",
+ "access_role": "member",
+ }
+ ],
+ ),
+ )
+ policy = project_access_service.get_project_policy(conn, project["id"])
+
+ assert result.outcome == "rejected"
+ assert result.error_code == "invalid_project_access_binding"
+ assert policy is None
def test_restricted_empty_bindings_is_owner_only(tmp_path) -> None:
diff --git a/tests/test_projects_service.py b/tests/test_projects_service.py
index 17f53e6f4..3074285c7 100644
--- a/tests/test_projects_service.py
+++ b/tests/test_projects_service.py
@@ -14,11 +14,17 @@ import pytest
from sqlalchemy import event, select
from sqlalchemy.exc import OperationalError
-from core.vibe_agents import VibeAgentStore
-from storage import projects_service
+from core.vibe_agents import VibeAgentAccessError, VibeAgentStore, ensure_session_agent_access
+from storage import (
+ project_access_service,
+ projects_service,
+ resource_access_service,
+ workbench_sessions_service,
+)
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import scope_settings, scopes
+from vibe.authorization import AuthorizationContext, InstanceAuthorizationError
@pytest.fixture
@@ -40,6 +46,402 @@ def _ensure_agent(name: str, backend: str) -> str:
store.close()
+def _remote_context(role: str) -> AuthorizationContext:
+ return AuthorizationContext(
+ instance_role=role,
+ subject=f"{role}-subject",
+ instance_access_source="email",
+ is_remote=True,
+ )
+
+
+def test_project_crud_follows_can_manage_projects(engine, tmp_path):
+ """Every existing role: member/owner mutate; editor/viewer stay denied."""
+
+ created_folder = tmp_path / "member-proj"
+ created_folder.mkdir()
+ rename_folder = tmp_path / "owner-proj"
+ rename_folder.mkdir()
+
+ with engine.begin() as conn:
+ created = projects_service.create_project(
+ conn,
+ str(created_folder),
+ display_name="Member Project",
+ authorization_context=_remote_context("member"),
+ )
+ assert created["display_name"] == "Member Project"
+ renamed = projects_service.update_project(
+ conn,
+ created["id"],
+ display_name="Member Renamed",
+ authorization_context=_remote_context("member"),
+ )
+ assert renamed["display_name"] == "Member Renamed"
+ owner_created = projects_service.create_project(
+ conn,
+ str(rename_folder),
+ display_name="Owner Project",
+ authorization_context=_remote_context("owner"),
+ )
+ projects_service.archive_project(
+ conn,
+ owner_created["id"],
+ authorization_context=_remote_context("member"),
+ )
+
+ with engine.connect() as conn:
+ listed = {project["id"] for project in projects_service.list_projects(conn)}
+ assert created["id"] in listed
+ assert owner_created["id"] not in listed
+
+ for role in ("viewer", "editor"):
+ denied_folder = tmp_path / f"{role}-proj"
+ denied_folder.mkdir()
+ with engine.begin() as conn:
+ with pytest.raises(InstanceAuthorizationError):
+ projects_service.create_project(
+ conn,
+ str(denied_folder),
+ authorization_context=_remote_context(role),
+ )
+ with pytest.raises(InstanceAuthorizationError):
+ projects_service.update_project(
+ conn,
+ created["id"],
+ display_name="Denied",
+ authorization_context=_remote_context(role),
+ )
+ with pytest.raises(InstanceAuthorizationError):
+ projects_service.archive_project(
+ conn,
+ created["id"],
+ authorization_context=_remote_context(role),
+ )
+
+
+def _acl_context(
+ role: str,
+ *,
+ email: str,
+ instance_kind: str | None = "organization",
+) -> AuthorizationContext:
+ return AuthorizationContext(
+ instance_role=role,
+ subject=email,
+ email=email,
+ instance_access_source="email",
+ is_remote=True,
+ instance_kind=instance_kind,
+ )
+
+
+def _restrict_project_to(conn, project_id: str, email: str, *, access_role: str = "editor") -> None:
+ result = project_access_service.apply_project_access_intent(
+ conn,
+ {
+ "project_id": project_id,
+ "revision": 1,
+ "mode": "restricted",
+ "bindings": [
+ {
+ "principal_kind": "email",
+ "principal_value": email,
+ "access_role": access_role,
+ }
+ ],
+ },
+ )
+ assert result.outcome == "applied"
+
+
+def test_project_mutations_follow_the_acl_that_hides_them(engine, tmp_path):
+ """Whether a member administers Projects and *which* are separate questions.
+
+ ``can_manage_projects`` answers the first; the Project ACL answers the second.
+ Checking only the first is what let a member who knew a Project id PATCH or
+ archive a restricted Project that ``list_projects`` and ``get_project``
+ correctly hide from them -- the read half was ACL-checked and the write half
+ was not, which is the wrong way round for an asymmetry to fall.
+
+ The floor is the ACL's *visibility* floor rather than a second predicate: a
+ member holding an explicit editor binding has an effective Project role of
+ editor, so demanding a "member" Project role would refuse exactly the
+ Projects the list shows them.
+ """
+
+ folder = tmp_path / "restricted"
+ folder.mkdir()
+ with engine.begin() as conn:
+ project = projects_service.create_project(
+ conn,
+ str(folder),
+ display_name="Restricted",
+ authorization_context=_remote_context("owner"),
+ )
+ _restrict_project_to(conn, project["id"], "[email protected]")
+
+ excluded = _acl_context("member", email="[email protected]")
+ included = _acl_context("member", email="[email protected]")
+
+ with engine.connect() as conn:
+ visible_to_excluded = {
+ listed["id"] for listed in projects_service.list_projects(conn, authorization_context=excluded)
+ }
+ visible_to_included = {
+ listed["id"] for listed in projects_service.list_projects(conn, authorization_context=included)
+ }
+ assert project["id"] not in visible_to_excluded
+ assert project["id"] in visible_to_included
+
+ # Hidden by the list, hidden by every mutation: LookupError, the same signal
+ # ``get_project`` already raises, so a 404 does not enumerate the Projects a
+ # caller is excluded from.
+ with engine.begin() as conn:
+ with pytest.raises(LookupError):
+ projects_service.get_project(conn, project["id"], authorization_context=excluded)
+ with pytest.raises(LookupError):
+ projects_service.update_project(
+ conn,
+ project["id"],
+ display_name="Stolen",
+ authorization_context=excluded,
+ )
+ with pytest.raises(LookupError):
+ projects_service.archive_project(
+ conn,
+ project["id"],
+ authorization_context=excluded,
+ )
+
+ with engine.connect() as conn:
+ assert projects_service.get_project(conn, project["id"])["display_name"] == "Restricted"
+
+ # A bound member and the Instance Owner are both unaffected.
+ with engine.begin() as conn:
+ assert (
+ projects_service.update_project(
+ conn,
+ project["id"],
+ display_name="Insider Renamed",
+ authorization_context=included,
+ )["display_name"]
+ == "Insider Renamed"
+ )
+ assert (
+ projects_service.update_project(
+ conn,
+ project["id"],
+ display_name="Owner Renamed",
+ authorization_context=_remote_context("owner"),
+ )["display_name"]
+ == "Owner Renamed"
+ )
+ projects_service.archive_project(
+ conn,
+ project["id"],
+ authorization_context=included,
+ )
+
+
+def test_every_project_entry_point_resolves_through_the_visibility_check():
+ """Every way into a Project row goes through the check ``list_projects`` uses.
+
+ The enumeration is taken from the module, not written down here: each round
+ of review found one more entry point that resolved a Project without the
+ ACL -- first mutation by id, then create-or-reuse by folder path -- because
+ each fix named the paths it knew about. Reading the call graph instead means
+ an entry point added later is covered on the day it is added, and one that
+ stops applying the check fails here rather than in a review.
+
+ "Reaching" is transitive on purpose: ``create_project`` never calls the
+ check itself, it calls the resolver that does, which is exactly where the
+ check belongs -- at the lookup rather than at each of its callers.
+ """
+
+ import ast
+ import inspect
+
+ gates = {"_require_visible_project", "can_read_project", "filter_accessible_projects"}
+ tree = ast.parse(inspect.getsource(projects_service))
+ functions = {
+ node.name: node
+ for node in tree.body
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ }
+
+ def _calls(node: ast.AST) -> set[str]:
+ names: set[str] = set()
+ for child in ast.walk(node):
+ if not isinstance(child, ast.Call):
+ continue
+ func = child.func
+ if isinstance(func, ast.Name):
+ names.add(func.id)
+ elif isinstance(func, ast.Attribute):
+ names.add(func.attr)
+ return names
+
+ def _reaches_gate(name: str, seen: frozenset[str] = frozenset()) -> bool:
+ if name in seen or name not in functions:
+ return False
+ called = _calls(functions[name])
+ if called & gates:
+ return True
+ return any(_reaches_gate(callee, seen | {name}) for callee in called)
+
+ # Public + takes a Connection: that is precisely the set of functions that
+ # return or mutate Project rows on behalf of an HTTP caller. ``make_directory``
+ # touches no rows and takes no connection, so it falls out by construction.
+ entry_points = {
+ name
+ for name, node in functions.items()
+ if not name.startswith("_")
+ and any(arg.arg == "conn" for arg in node.args.args)
+ }
+ assert entry_points >= {
+ "list_projects",
+ "get_project",
+ "get_project_workdir",
+ "create_project",
+ "update_project",
+ "archive_project",
+ }
+ ungated = sorted(name for name in entry_points if not _reaches_gate(name))
+ assert ungated == [], f"Project entry points that never reach a visibility check: {ungated}"
+
+
+def test_folder_path_is_not_a_side_door_onto_a_hidden_project(engine, tmp_path):
+ """Create-or-reuse is a Project lookup, so it carries the visibility rule too.
+
+ A folder path is a lookup key exactly as much as a Project id is. Reuse
+ resolved the match without the ACL, so a member who submitted the folder of
+ a restricted Project they are excluded from got its payload back -- and,
+ when the Project was archived, revived it on the way, since reuse is also
+ the unarchive path.
+
+ Applying the *same* check the list applies carries one declared consequence:
+ ``get_effective_project_role`` returns nothing for an inactive Project below
+ the Instance Owner, so restoring an archived Project by re-opening its
+ folder is Owner-only. That is not a new rule, it is the existing one finally
+ reaching this path -- ``list_projects(include_archived=True)``,
+ ``get_project``, ``update_project``, and ``archive_project`` already answer
+ a non-owner with nothing for an archived Project.
+ """
+
+ folder = tmp_path / "hidden"
+ folder.mkdir()
+ owner = _remote_context("owner")
+ with engine.begin() as conn:
+ project = projects_service.create_project(
+ conn,
+ str(folder),
+ display_name="Hidden",
+ authorization_context=owner,
+ )
+ _restrict_project_to(conn, project["id"], "[email protected]")
+
+ excluded = _acl_context("member", email="[email protected]")
+ included = _acl_context("member", email="[email protected]")
+
+ with engine.begin() as conn:
+ with pytest.raises(LookupError):
+ projects_service.create_project(
+ conn,
+ str(folder),
+ display_name="Stolen",
+ authorization_context=excluded,
+ )
+
+ # The bound member reaches the same folder normally, so the refusal above is
+ # the ACL talking and not create-or-reuse breaking for everyone.
+ with engine.begin() as conn:
+ reused = projects_service.create_project(
+ conn,
+ str(folder),
+ display_name="Ignored On Reuse",
+ authorization_context=included,
+ )
+ assert reused["id"] == project["id"]
+ assert reused["display_name"] == "Hidden"
+
+ # Archived: invisible to every non-owner, so reuse cannot revive it either.
+ with engine.begin() as conn:
+ projects_service.archive_project(conn, project["id"], authorization_context=owner)
+ for context in (excluded, included):
+ with pytest.raises(LookupError):
+ projects_service.create_project(
+ conn,
+ str(folder),
+ display_name="Revived",
+ authorization_context=context,
+ )
+
+ # Refused without side effects: still archived, still named as its owner
+ # left it, and no duplicate scope minted over the same folder.
+ with engine.connect() as conn:
+ owned = projects_service.list_projects(
+ conn,
+ include_archived=True,
+ authorization_context=owner,
+ )
+ assert len(owned) == 1
+ assert owned[0]["id"] == project["id"]
+ assert owned[0]["display_name"] == "Hidden"
+ assert owned[0]["archived"] is True
+
+ # The Owner still restores it the documented way, by re-opening the folder.
+ with engine.begin() as conn:
+ restored = projects_service.create_project(
+ conn,
+ str(folder),
+ authorization_context=owner,
+ )
+ assert restored["id"] == project["id"]
+ assert restored["archived"] is False
+
+
+def test_personal_instance_member_mutates_without_a_project_acl(engine, tmp_path):
+ """A Personal install has no Project ACL, so the instance role stays sufficient.
+
+ ``get_effective_project_role`` short-circuits on Personal, which is why the
+ visibility floor above needs no Personal special case -- even with a
+ restricted policy row present, a Personal member keeps the role they came in
+ with.
+ """
+
+ folder = tmp_path / "personal"
+ folder.mkdir()
+ with engine.begin() as conn:
+ project = projects_service.create_project(
+ conn,
+ str(folder),
+ display_name="Personal",
+ authorization_context=_remote_context("owner"),
+ )
+ _restrict_project_to(conn, project["id"], "[email protected]")
+
+ personal_member = _acl_context("member", email="[email protected]", instance_kind="personal")
+ with engine.connect() as conn:
+ assert project["id"] in {
+ listed["id"]
+ for listed in projects_service.list_projects(conn, authorization_context=personal_member)
+ }
+ with engine.begin() as conn:
+ renamed = projects_service.update_project(
+ conn,
+ project["id"],
+ display_name="Personal Renamed",
+ authorization_context=personal_member,
+ )
+ assert renamed["display_name"] == "Personal Renamed"
+ projects_service.archive_project(
+ conn,
+ project["id"],
+ authorization_context=personal_member,
+ )
+
+
def test_create_project_is_idempotent_by_path(engine, tmp_path):
folder = tmp_path / "proj"
folder.mkdir()
@@ -145,7 +547,10 @@ def test_path_lookup_ignores_non_project_scopes(engine, tmp_path):
with engine.begin() as conn:
# The channel sharing the path is not a project match...
- assert projects_service._find_project_by_workdir(conn, workdir) is None
+ assert (
+ projects_service._find_project_by_workdir(conn, _remote_context("owner"), workdir)
+ is None
+ )
# ...so creating a project for it mints a real avibe project scope.
proj = projects_service.create_project(conn, workdir)
@@ -246,7 +651,7 @@ def test_duplicate_path_pick_prefers_active_then_recent(engine, tmp_path):
_insert_project("avibe::project::proj_active", enabled=1, last_seen="2026-05-01T00:00:00Z")
with engine.begin() as conn:
- found = projects_service._find_project_by_workdir(conn, workdir)
+ found = projects_service._find_project_by_workdir(conn, _remote_context("owner"), workdir)
# Active wins over the more-recent archived row.
assert found is not None
@@ -504,3 +909,204 @@ def test_set_default_agent_on_folderless_project_inserts_row(engine):
)
assert updated["default_agent"]["agent_backend"] == "opencode"
assert updated["default_agent"]["model"] == "grok-code"
+
+
+def _organization_context(subject: str, *, instance_role: str) -> AuthorizationContext:
+ return AuthorizationContext(
+ subject=subject,
+ email=f"{subject}@example.com",
+ organization_id="org-1",
+ organization_member_id=f"member-{subject}",
+ organization_role="member",
+ group_ids=frozenset({"group-engineering"}),
+ instance_role=instance_role,
+ instance_access_source="organization_group",
+ is_remote=True,
+ )
+
+
+def _agent_with_policy(engine, *, name: str, access_level: str, owner_user_id: str) -> str:
+ """Create an Agent and give it one ACL shape, returning its stable id."""
+
+ store = VibeAgentStore()
+ try:
+ agent = store.create(name=name, backend="codex")
+ finally:
+ store.close()
+ with engine.begin() as conn:
+ resource_access_service.ensure_resource_policy(
+ conn,
+ resource_kind="agent",
+ resource_id=agent.id,
+ organization_id="org-1",
+ owner_user_id=owner_user_id,
+ access_level=access_level,
+ # Only ``scope`` consumes groups; the value is irrelevant to the rule
+ # under test, because no group set is wide enough to back a default.
+ group_ids=["group-platform"] if access_level == "scope" else None,
+ )
+ return agent.id
+
+
+def _restricted_access_levels() -> list[str]:
+ """Every access level that admits less than the project's whole audience.
+
+ Derived from the source of truth rather than listed, so an access level added
+ later is covered by these tests without editing them.
+ """
+
+ return sorted(resource_access_service.ACCESS_LEVELS - {"public"})
+
+
+def _stored_project_default(engine, scope_id: str) -> str | None:
+ with engine.connect() as conn:
+ return conn.execute(
+ select(scope_settings.c.agent_name).where(scope_settings.c.scope_id == scope_id)
+ ).scalar_one()
+
+
+def test_project_default_agent_is_advisory_and_degrades_at_use_time(engine, tmp_path):
+ """A project default is a hint; the ACL is enforced against whoever resolves it.
+
+ Validating the assignment against the default's policy *shape* was tried and
+ removed: no predicate over {public, scope, private, absent} is both sound and
+ usable (see the note above ``core.vibe_agents.resolve_usable_default_agent``).
+ So a member may point the project at any Agent they can manage, however they
+ name it — by stable id or by public name — including one narrower than the
+ project's audience.
+
+ What that costs is paid at use time instead of at bind time. Another member
+ who cannot use the default still starts a normal unpinned session: the hint
+ degrades and dispatch follows an Agent they can use, rather than one narrow
+ default locking everyone else out of the project. The restricted set is
+ derived, not listed, so a future access level is covered without editing
+ this test.
+ """
+
+ member = _organization_context("member-1", instance_role="member")
+ other = _organization_context("member-2", instance_role="editor")
+ shared_id = _agent_with_policy(
+ engine, name="team-shared", access_level="public", owner_user_id="member-1"
+ )
+ restricted = {
+ level: _agent_with_policy(
+ engine,
+ name=f"member-{level}",
+ access_level=level,
+ owner_user_id="member-1",
+ )
+ for level in _restricted_access_levels()
+ }
+ assert set(restricted) >= {"private", "scope"}
+
+ folder = tmp_path / "shared-proj"
+ folder.mkdir()
+ with engine.begin() as conn:
+ project = projects_service.create_project(
+ conn, str(folder), authorization_context=member
+ )
+ accepted = projects_service.update_project(
+ conn,
+ project["id"],
+ agent_id=shared_id,
+ authorization_context=member,
+ )
+ assert accepted["default_agent"]["agent_id"] == shared_id
+
+ for level, agent_id in restricted.items():
+ for kwargs in ({"agent_id": agent_id}, {"agent_name": f"member-{level}"}):
+ with engine.begin() as conn:
+ projects_service.update_project(
+ conn,
+ project["id"],
+ agent_name=None,
+ agent_id=None,
+ authorization_context=member,
+ )
+ bound = projects_service.update_project(
+ conn,
+ project["id"],
+ authorization_context=member,
+ **kwargs,
+ )
+ assert bound["default_agent"]["agent_id"] == agent_id
+ assert _stored_project_default(engine, project["scope_id"]) == f"member-{level}"
+
+ # ``member-2`` shares neither the private owner nor the scoped group,
+ # so the default is unusable for them. The session is still created;
+ # it drops the project's hint and falls back to an Agent this caller
+ # may actually use, which is written into the row so dispatch runs it
+ # rather than re-deriving the hint without a principal.
+ with engine.begin() as conn:
+ session = workbench_sessions_service.create_session(
+ conn,
+ scope_id=project["scope_id"],
+ agent_backend="",
+ user_context=other,
+ )
+ assert session["agent_id"] != agent_id
+ assert session["agent_name"] != f"member-{level}"
+ with engine.connect() as conn:
+ assert (
+ ensure_session_agent_access(conn, session, user_context=other) is not None
+ )
+
+ # Degrading applies to the advisory hint only. Naming the same Agent
+ # explicitly is a stated intent and still fails closed.
+ with engine.begin() as conn:
+ with pytest.raises(VibeAgentAccessError):
+ workbench_sessions_service.create_session(
+ conn,
+ scope_id=project["scope_id"],
+ agent_backend="codex",
+ agent_id=agent_id,
+ user_context=other,
+ )
+
+
+def test_owner_project_default_accepts_every_policy_shape(engine, tmp_path):
+ """The Owner is bound by the same advisory rule, and resolves any default.
+
+ Assignment is caller-independent now that it validates nothing about policy
+ shape, and the Instance Owner bypasses ACL checks when *using* a resource, so
+ an Owner's unpinned session adopts even a private default rather than
+ degrading away from it.
+ """
+
+ owner = _organization_context("owner-1", instance_role="owner")
+ restricted = {
+ level: _agent_with_policy(
+ engine,
+ name=f"owner-{level}",
+ access_level=level,
+ owner_user_id="owner-1",
+ )
+ for level in _restricted_access_levels()
+ }
+
+ folder = tmp_path / "owner-proj"
+ folder.mkdir()
+ with engine.begin() as conn:
+ project = projects_service.create_project(
+ conn, str(folder), authorization_context=owner
+ )
+
+ for level, agent_id in restricted.items():
+ with engine.begin() as conn:
+ accepted = projects_service.update_project(
+ conn,
+ project["id"],
+ agent_id=agent_id,
+ authorization_context=owner,
+ )
+ assert accepted["default_agent"]["agent_id"] == agent_id
+ assert _stored_project_default(engine, project["scope_id"]) == f"owner-{level}"
+
+ with engine.begin() as conn:
+ session = workbench_sessions_service.create_session(
+ conn,
+ scope_id=project["scope_id"],
+ agent_backend="",
+ user_context=owner,
+ )
+ assert session["agent_name"] == f"owner-{level}"
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.py
index 639eba273..f651ae86d 100644
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@ -272,9 +272,13 @@ def test_session_claims_reject_missing_or_unknown_instance_role() -> None:
remote_access.session_claims_from_oidc(config, base_claims)
with pytest.raises(remote_access.OAuthCodeExchangeError, match="invalid_instance_role"):
remote_access.session_claims_from_oidc(config, {**base_claims, "vibe_instance_role": "admin"})
+ claims = remote_access.session_claims_from_oidc(
+ config, {**base_claims, "vibe_instance_role": "member"}
+ )
+ assert claims["vibe_instance_role"] == "member"
[email protected]("instance_role", ["editor", "owner"])
[email protected]("instance_role", ["editor", "member", "owner"])
def test_session_claims_reject_elevated_show_page_email_roles(instance_role: str) -> None:
config = _config()
diff --git a/tests/test_resource_access_service.py b/tests/test_resource_access_service.py
index 7a7f777a4..a5029c298 100644
--- a/tests/test_resource_access_service.py
+++ b/tests/test_resource_access_service.py
@@ -1728,6 +1728,71 @@ def test_released_migration_marker_shapes_stay_idempotent_and_fail_closed(
assert json.loads(stored)["state"] == expected_state
finally:
store.close()
+
+
+def test_member_resource_user_context_snapshot_round_trips() -> None:
+ context = resource_access_service.ResourceUserContext(
+ subject="member-1",
+ organization_id="org-1",
+ organization_member_id="organization-member-1",
+ organization_role="member",
+ group_ids=frozenset({"group-engineering"}),
+ membership_version="membership-v2",
+ instance_role="member",
+ instance_access_source="email",
+ claims_issued_at=1_700_000_000,
+ is_remote=True,
+ )
+ metadata = resource_access_service.metadata_with_resource_user_context({}, context)
+ restored = resource_access_service.resource_user_context_from_metadata(metadata)
+ assert restored is not None
+ assert restored.instance_role == "member"
+ assert restored.can_manage_instance
+ assert not restored.can_manage_access_members
+ assert restored.has_role("editor")
+
+
+def test_pre_member_resource_user_context_snapshot_keeps_editor_role() -> None:
+ context = resource_access_service.ResourceUserContext(
+ subject="editor-1",
+ organization_id="org-1",
+ organization_member_id="organization-member-1",
+ organization_role="member",
+ instance_role="editor",
+ instance_access_source="email",
+ claims_issued_at=1_700_000_000,
+ is_remote=True,
+ )
+ metadata = resource_access_service.metadata_with_resource_user_context({}, context)
+ restored = resource_access_service.resource_user_context_from_metadata(metadata)
+ assert restored is not None
+ assert restored.instance_role == "editor"
+ assert not restored.can_manage_instance
+
+
+def test_organization_member_remains_subject_to_resource_acl_for_use(tmp_path) -> None:
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ try:
+ with engine.begin() as connection:
+ _seed_policies(connection)
+ member = _context(
+ "member-2",
+ instance_role="member",
+ group_ids=frozenset({"group-sales"}),
+ )
+ assert member.can_manage_instance
+ assert not resource_access_service.can_use_resource(
+ member, "agent", "private-agent", connection=connection
+ )
+ assert resource_access_service.can_use_resource(
+ member, "agent", "public-agent", connection=connection
+ )
+ assert not resource_access_service.can_use_resource(
+ member, "agent", "scoped-agent", connection=connection
+ )
+ finally:
engine.dispose()
diff --git a/tests/test_resource_acl_agents.py b/tests/test_resource_acl_agents.py
index 9efb0228b..780bd1825 100644
--- a/tests/test_resource_acl_agents.py
+++ b/tests/test_resource_acl_agents.py
@@ -13,9 +13,13 @@ from core.vibe_agents import (
VibeAgentAccessError,
VibeAgentStore,
ensure_agent_selection_access,
+ ensure_default_agent_access,
ensure_session_agent_access,
+ resolve_effective_default_agent,
)
+from core.session_turns import SessionTurnManager
from core.watches import ManagedWatchStore
+from modules.im import MessageContext
from storage import resource_access_service, workbench_sessions_service
from storage.db import get_cached_sqlite_engine
from storage.models import resource_access_groups, resource_access_policies
@@ -112,6 +116,37 @@ def _seed_agents_with_policies() -> tuple[VibeAgentStore, dict[str, VibeAgent]]:
return store, agents
+def _restricted_agent_keys() -> list[str]:
+ """Seeded Agents whose policy admits less than the whole instance.
+
+ Derived from the access levels themselves rather than listed, so a level
+ added later is covered by the tests below without editing them. The seeder
+ keys are the access levels, and the assertion keeps it that way: a new level
+ must be seeded before these tests can pass.
+ """
+
+ levels = sorted(resource_access_service.ACCESS_LEVELS - {"public"})
+ assert set(levels) >= {"private", "scope"}
+ return levels
+
+
+def _set_default_agent_row(store: VibeAgentStore, agent_name: str) -> None:
+ """Point instance-wide routing at an Agent, bypassing the Owner-only gate.
+
+ Defaults are advisory: the setter accepts any Agent its caller may manage,
+ including one whose policy admits less than the whole instance. Writing the
+ row directly keeps these tests focused on what happens when such a default is
+ *resolved*, without threading an Owner session through every caller.
+ """
+
+ with store.engine.begin() as connection:
+ store._write_default_agent_name( # noqa: SLF001
+ connection,
+ agent_name,
+ now="2026-07-20T00:00:00Z",
+ )
+
+
def test_active_org_agent_catalog_includes_every_builtin_and_acl_shape(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store, _agents = _seed_agents_with_policies()
@@ -224,8 +259,15 @@ def test_active_org_agent_management_is_allowed_inside_the_store(monkeypatch, tm
store.remove(agents["public"].name, user_context=member)
updated = store.update(agents["public"].name, description="admin update", user_context=admin)
assert updated.description == "admin update"
- store.set_default_agent_name(agents["private"].name, user_context=admin)
- assert store.get_default_agent_name() == agents["private"].name
+ store.set_default_agent_name(agents["public"].name, user_context=admin)
+ assert store.get_default_agent_name() == agents["public"].name
+ # A default is advisory: an Agent narrower than the whole audience is a
+ # legitimate assignment, because the ACL is enforced per-principal at use
+ # time (see ``resolve_usable_default_agent``) rather than at bind time.
+ for key in _restricted_agent_keys():
+ store.set_default_agent_name(agents[key].name, user_context=admin)
+ assert store.get_default_agent_name() == agents[key].name
+ store.set_default_agent_name(agents["public"].name, user_context=admin)
assert store.remove(agents["public"].name, user_context=admin) is True
owner_updated = store.update(
agents["private"].name,
@@ -289,7 +331,7 @@ def test_editor_clearing_session_agent_authorizes_default(monkeypatch, tmp_path)
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store, agents = _seed_agents_with_policies()
try:
- store.set_default_agent_name(agents["private"].name)
+ _set_default_agent_row(store, agents["private"].name)
engine = get_cached_sqlite_engine()
with engine.begin() as connection:
scope_id = upsert_scope(
@@ -306,16 +348,19 @@ def test_editor_clearing_session_agent_authorizes_default(monkeypatch, tmp_path)
agent_id=agents["public"].id,
user_context=_organization_context("member-1"),
)
- with pytest.raises(VibeAgentAccessError):
- with engine.begin() as connection:
- workbench_sessions_service.update_session(
- connection,
- session["id"],
- agent_name="",
- agent_id="",
- agent_backend="",
- user_context=_organization_context("member-1"),
- )
+ # The instance default is another owner's private Agent. Clearing the
+ # selector still succeeds: the default is advisory, so it degrades to an
+ # Agent this caller may use rather than stranding the session.
+ with engine.begin() as connection:
+ degraded = workbench_sessions_service.update_session(
+ connection,
+ session["id"],
+ agent_name="",
+ agent_id="",
+ agent_backend="",
+ user_context=_organization_context("member-1"),
+ )
+ assert (degraded["agent_id"], degraded["agent_name"]) == (None, None)
store.set_default_agent_name(agents["public"].name)
with engine.begin() as connection:
cleared = workbench_sessions_service.update_session(
@@ -326,7 +371,10 @@ def test_editor_clearing_session_agent_authorizes_default(monkeypatch, tmp_path)
agent_backend="",
user_context=_organization_context("member-1"),
)
- store.set_default_agent_name(agents["scope"].name)
+ # A scoped Agent is a legitimate instance default. The read path must
+ # resolve it for a caller inside the scope rather than degrading away
+ # from a default the caller can in fact use.
+ _set_default_agent_row(store, agents["scope"].name)
with engine.connect() as connection:
effective = ensure_session_agent_access(
connection,
@@ -359,15 +407,20 @@ def test_editor_creating_default_session_validates_without_pinning(monkeypatch,
now="2026-08-13T00:00:00Z",
)
- store.set_default_agent_name(agents["private"].name)
- with pytest.raises(VibeAgentAccessError):
- with engine.begin() as connection:
- workbench_sessions_service.create_session(
- connection,
- scope_id=scope_id,
- agent_backend="",
- user_context=_organization_context("member-1"),
- )
+ # An unusable instance default degrades on create -- and the substitute is
+ # written into the row, because it exists only in this caller's frame of
+ # reference. See
+ # ``test_unpinned_session_dispatches_the_agent_the_default_degraded_to``.
+ _set_default_agent_row(store, agents["private"].name)
+ with engine.begin() as connection:
+ degraded = workbench_sessions_service.create_session(
+ connection,
+ scope_id=scope_id,
+ agent_backend="",
+ user_context=_organization_context("member-1"),
+ )
+ assert degraded["agent_id"] not in (None, agents["private"].id)
+ assert degraded["agent_backend"]
store.set_default_agent_name(agents["public"].name)
with engine.begin() as connection:
@@ -378,7 +431,9 @@ def test_editor_creating_default_session_validates_without_pinning(monkeypatch,
user_context=_organization_context("member-1"),
)
- store.set_default_agent_name(agents["scope"].name)
+ # Same shape as above on the create path: a scoped default resolves for a
+ # caller inside the scope.
+ _set_default_agent_row(store, agents["scope"].name)
with engine.connect() as connection:
effective = ensure_session_agent_access(
connection,
@@ -397,6 +452,148 @@ def test_editor_creating_default_session_validates_without_pinning(monkeypatch,
assert effective.id == agents["scope"].id
+def test_unpinned_session_dispatches_the_agent_the_default_degraded_to(monkeypatch, tmp_path) -> None:
+ """Dispatch runs the substitute the default degraded to, not the raw default.
+
+ ``resolve_usable_default_agent`` answers a question about one principal, so
+ its answer only means anything while that principal is in scope. Leaving the
+ Session unpinned threw the answer away: dispatch re-derives the route from
+ ``Controller.resolve_vibe_agent_for_context``, which carries no principal and
+ resolves the *configured* default, pins that inaccessible Agent, and the
+ execution-time recheck in ``_remote_delivery_execution_denial`` then retires
+ the caller's first message. Degrading and not persisting the result is the
+ same as not degrading at all.
+
+ The lock is the real dispatch chokepoint rather than a re-read of the row:
+ ``_delivery_backend_in_transaction`` must satisfy itself from the durable
+ binding and never call the resolver, whose raw answer is still the Agent this
+ caller cannot use.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store, agents = _seed_agents_with_policies()
+ engine = get_cached_sqlite_engine()
+ member = _organization_context("member-1", instance_role="member")
+ try:
+ # The configured instance default is another owner's private Agent; the
+ # caller is entitled to others.
+ _set_default_agent_row(store, agents["private"].name)
+ with engine.begin() as connection:
+ scope_id = upsert_scope(
+ connection,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_dispatch_default",
+ now="2026-08-21T00:00:00Z",
+ )
+ session = workbench_sessions_service.create_session(
+ connection,
+ scope_id=scope_id,
+ agent_backend="",
+ user_context=member,
+ )
+ assert session["agent_id"] not in (None, agents["private"].id)
+ assert session["agent_backend"]
+
+ resolver_calls: list[str] = []
+
+ def _resolve_raw_default(context, **kwargs):
+ """Stand in for ``Controller.resolve_vibe_agent_for_context``.
+
+ Same behaviour as the real one for an unpinned avibe Session with no
+ override: the configured default, resolved with no principal at all.
+ """
+
+ resolver_calls.append(str(getattr(context, "channel_id", "")))
+ with store.engine.connect() as connection:
+ return resolve_effective_default_agent(connection)
+
+ manager = SessionTurnManager(
+ controller=SimpleNamespace(resolve_vibe_agent_for_context=_resolve_raw_default)
+ )
+ context = MessageContext(user_id="member-1", channel_id=session["id"], platform="avibe")
+ context.platform_specific = {"agent_session_id": session["id"]}
+ with engine.begin() as connection:
+ backend, _resolved = manager._delivery_backend_in_transaction( # noqa: SLF001
+ connection,
+ session["id"],
+ context,
+ )
+ assert backend == session["agent_backend"]
+ assert resolver_calls == []
+
+ # The gate that retired the first message: the Agent the Session is bound
+ # to is one this caller may actually use.
+ with engine.connect() as connection:
+ reloaded = workbench_sessions_service.get_session(connection, session["id"])
+ effective = ensure_session_agent_access(connection, reloaded, user_context=member)
+ assert effective is not None
+ assert effective.id == session["agent_id"]
+
+ # The configured default is untouched -- degrading is per caller, not a
+ # rewrite of instance routing.
+ with store.engine.connect() as connection:
+ assert resolve_effective_default_agent(connection).id == agents["private"].id
+
+ # An explicit pick is a stated intent, not an advisory hint, so the same
+ # inaccessible Agent still errors instead of silently substituting.
+ with engine.begin() as connection:
+ with pytest.raises(VibeAgentAccessError):
+ workbench_sessions_service.create_session(
+ connection,
+ scope_id=scope_id,
+ agent_backend="",
+ agent_id=agents["private"].id,
+ user_context=member,
+ )
+ finally:
+ store.close()
+
+
+def test_personal_install_default_routing_never_degrades(monkeypatch, tmp_path) -> None:
+ """A personal install resolves whatever default it was given, unchanged.
+
+ No Agent on a personal install carries an ACL row, which is exactly the shape
+ a bind-time audience predicate would have had to reject. Use-time enforcement
+ has no such problem: the local boot path resolves as the Instance Owner, and
+ a remote personal-install principal is evaluated against the Agent-use
+ capability rather than against a policy that was never written. Neither
+ degrades away from the configured Agent, so ``vibe agent default`` keeps
+ meaning what it says.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = VibeAgentStore()
+ try:
+ builtin = store.ensure_builtin_default_agent(backend="codex")
+ chosen = store.create(name="local-favourite", backend="codex")
+ store.set_default_agent_name(chosen.name)
+ assert store.get_default_agent_name() == chosen.name
+ assert builtin.name != chosen.name
+
+ personal_member = resource_access_service.ResourceUserContext(
+ subject="member-1",
+ instance_role="member",
+ instance_access_source="email",
+ instance_kind="personal",
+ is_remote=True,
+ )
+ with store.engine.connect() as connection:
+ # The local boot path passes no principal at all and resolves as the
+ # Instance Owner.
+ assert ensure_default_agent_access(connection).id == chosen.id
+ assert (
+ ensure_default_agent_access(
+ connection,
+ user_context=personal_member,
+ ).id
+ == chosen.id
+ )
+ finally:
+ store.close()
+
+
def test_missing_agent_selector_fails_closed_for_editor_only(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = VibeAgentStore()
@@ -473,7 +670,7 @@ def test_editor_agent_selection_and_harness_bindings_follow_acl(monkeypatch, tmp
config = _save_config(tmp_path, paired=True, instance_kind="organization")
store, agents = _seed_agents_with_policies()
private_agent = agents["private"]
- store.set_default_agent_name(private_agent.name)
+ _set_default_agent_row(store, private_agent.name)
store.close()
context = _organization_context("member-1")
@@ -530,14 +727,27 @@ def test_editor_agent_selection_and_harness_bindings_follow_acl(monkeypatch, tmp
environ_base=_remote_peer(),
)
assert mutation.status_code == 200
- default_mutation = client.post(
+ # Instance-wide default routing is Owner-only, but the Agent it points at is
+ # not constrained by policy shape: the default is advisory and the ACL is
+ # enforced per-principal at use time, so a narrower Agent is accepted here
+ # and degrades for whoever cannot use it.
+ for key in _restricted_agent_keys():
+ default_mutation = client.post(
+ "/api/agents/default",
+ json={"name": agents[key].name},
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ assert default_mutation.status_code == 200
+ shared_default = client.post(
"/api/agents/default",
- json={"name": private_agent.name},
+ json={"name": agents["public"].name},
headers=csrf_headers(client, "https://alex.avibe.bot"),
base_url="https://alex.avibe.bot",
environ_base=_remote_peer(),
)
- assert default_mutation.status_code == 200
+ assert shared_default.status_code == 200
engine = get_cached_sqlite_engine()
with engine.begin() as connection:
@@ -635,6 +845,76 @@ def test_only_owner_can_create_or_import_agents(monkeypatch, tmp_path) -> None:
store.close()
+def _create_acl_principal(role: str, *, organization: bool) -> resource_access_service.ResourceUserContext:
+ if organization:
+ return _organization_context(f"{role}-org", instance_role=role)
+ return resource_access_service.ResourceUserContext(
+ subject=f"{role}-personal",
+ email=f"{role}[email protected]",
+ instance_role=role,
+ instance_access_source="email",
+ is_remote=True,
+ )
+
+
+def test_agent_create_registers_acl_for_every_creating_subject(monkeypatch, tmp_path) -> None:
+ """Create-path ACL follows the creating subject, not org membership.
+
+ Seed every existing instance role on Personal (email) and Organization so a
+ later create path cannot skip the policy for a newly admitted principal.
+ Organization *use* of another member's private Agent stays denied.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = VibeAgentStore()
+ try:
+ created: list[tuple[resource_access_service.ResourceUserContext, VibeAgent]] = []
+ for organization in (False, True):
+ for role in ("viewer", "editor", "member", "owner"):
+ context = _create_acl_principal(role, organization=organization)
+ name = f"{role}-{'org' if organization else 'personal'}-agent"
+ if not context.can_manage_agents:
+ with pytest.raises(VibeAgentAccessError):
+ store.create(name=name, backend="codex", user_context=context)
+ continue
+ agent = store.create(name=name, backend="codex", user_context=context)
+ created.append((context, agent))
+ with store.engine.connect() as connection:
+ policy = resource_access_service.get_resource_policy(
+ "agent",
+ agent.id,
+ connection=connection,
+ )
+ assert policy is not None
+ assert policy["owner_user_id"] == context.subject
+ assert policy["access_level"] == "private"
+ if organization:
+ assert policy["organization_id"] == context.organization_id
+ else:
+ assert not policy["organization_id"]
+ visible = {item.id for item in store.list_agents(user_context=context)}
+ assert agent.id in visible
+
+ org_member = next(ctx for ctx, _agent in created if ctx.instance_role == "member" and ctx.organization_id)
+ personal_member_agent = next(
+ agent for ctx, agent in created if ctx.instance_role == "member" and not ctx.organization_id
+ )
+ org_member_agent = next(
+ agent for ctx, agent in created if ctx.instance_role == "member" and ctx.organization_id
+ )
+ org_editor = _create_acl_principal("editor", organization=True)
+ org_visible = {item.id for item in store.list_agents(user_context=org_editor)}
+ assert org_member_agent.id not in org_visible
+ personal_visible = {
+ item.id
+ for item in store.list_agents(user_context=_create_acl_principal("editor", organization=False))
+ }
+ assert personal_member_agent.id not in personal_visible
+ assert org_member.can_manage_agents
+ finally:
+ store.close()
+
+
def test_active_org_background_definitions_are_allowed_but_legacy_rows_fail_before_dispatch(
monkeypatch,
tmp_path,
diff --git a/tests/test_ui_project_access.py b/tests/test_ui_project_access.py
index 9a5b1e728..adb13c10e 100644
--- a/tests/test_ui_project_access.py
+++ b/tests/test_ui_project_access.py
@@ -293,6 +293,115 @@ def test_active_org_member_can_use_every_project_runtime_surface(monkeypatch, tm
assert hidden_action.status_code != 403 or hidden_action.get_json().get("code") != "remote_execution_disabled"
+def test_member_project_mutations_are_bounded_by_the_acl_that_hides_them(monkeypatch, tmp_path) -> None:
+ """Instance role admits the route; the Project ACL still picks the Project.
+
+ ``can_manage_projects`` is instance-wide Project administration, but every
+ one of these routes names a single Project, and the instance role says
+ nothing about which. The middleware used to skip member-tier routes
+ entirely, so a member who knew an id could PATCH or archive a Project that
+ ``GET /api/projects`` and ``GET /api/projects/<id>`` already hid from them.
+
+ 404 on every hidden Project, matching the read path: a 403/404 split would
+ let a caller enumerate the restricted Projects they are excluded from.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, ids = _setup_state(tmp_path)
+
+ def _patch(client, project_id, headers, name):
+ return client.patch(
+ f"/api/projects/{project_id}",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={"display_name": name},
+ )
+
+ def _archive(client, project_id, headers):
+ return client.delete(
+ f"/api/projects/{project_id}",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ )
+
+ # Bound to neither Project: the list is empty, and so is what they can touch.
+ excluded = _remote_client(config, role="member", email="[email protected]")
+ excluded_headers = csrf_headers(excluded, REMOTE_ORIGIN)
+ assert _get(excluded, "/api/projects").get_json()["projects"] == []
+ for project_id in (ids["project_a"], ids["project_b"]):
+ assert _get(excluded, f"/api/projects/{project_id}").status_code == 404
+ assert _patch(excluded, project_id, excluded_headers, "Stolen").status_code == 404
+ assert _archive(excluded, project_id, excluded_headers).status_code == 404
+
+ # An explicit editor binding is below "member", and that is the point: the
+ # floor for these routes is the ACL's visibility floor, so the Projects the
+ # list shows are exactly the Projects that can be mutated.
+ included = _remote_client(config, role="member", email="[email protected]")
+ included_headers = csrf_headers(included, REMOTE_ORIGIN)
+ assert {row["id"] for row in _get(included, "/api/projects").get_json()["projects"]} == {
+ ids["project_a"]
+ }
+ renamed = _patch(included, ids["project_a"], included_headers, "Alice Renamed")
+ assert renamed.status_code == 200
+ assert renamed.get_json()["display_name"] == "Alice Renamed"
+ assert _patch(included, ids["project_b"], included_headers, "Stolen").status_code == 404
+ assert _archive(included, ids["project_b"], included_headers).status_code == 404
+ assert _archive(included, ids["project_a"], included_headers).status_code == 200
+
+
+def test_member_cannot_reach_a_hidden_project_through_its_folder(monkeypatch, tmp_path) -> None:
+ """``POST /api/projects`` is create-or-reuse, so it is also a Project lookup.
+
+ The middleware only sees routes that name a Project id, and this one names a
+ folder, so the whole visibility rule for it lives in the service. A member
+ excluded from the Project gets the same 404 the id-keyed routes answer with
+ -- not its payload, and not a revived copy of it.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, ids = _setup_state(tmp_path)
+ project_b_dir = str((tmp_path / "project-b").resolve())
+
+ # ``alice`` is bound to project_a only; project_b is restricted to a group
+ # she is not in, so it is hidden from her exactly as the list shows.
+ alice = _remote_client(config, role="member", email="[email protected]")
+ headers = csrf_headers(alice, REMOTE_ORIGIN)
+ assert {row["id"] for row in _get(alice, "/api/projects").get_json()["projects"]} == {
+ ids["project_a"]
+ }
+
+ hidden = alice.post(
+ "/api/projects",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={"folder_path": project_b_dir, "display_name": "Stolen"},
+ )
+ assert hidden.status_code == 404
+ assert "project_b" not in json.dumps(hidden.get_json())
+
+ owner = _remote_client(config, role="owner", email="[email protected]")
+ owner_view = {
+ row["id"]: row for row in _get(owner, "/api/projects").get_json()["projects"]
+ }
+ assert owner_view[ids["project_b"]]["display_name"] == "B"
+
+ # Reuse still works for a folder the caller can see, so the refusal above is
+ # the ACL and not create-or-reuse breaking.
+ project_a_dir = str((tmp_path / "project-a").resolve())
+ visible = alice.post(
+ "/api/projects",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={"folder_path": project_a_dir, "display_name": "Ignored On Reuse"},
+ )
+ assert visible.status_code == 201
+ assert visible.get_json()["id"] == ids["project_a"]
+
+
def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config, ids = _setup_state(tmp_path)
@@ -460,6 +569,85 @@ def test_editor_config_write_always_answers_with_a_renderable_code(monkeypatch,
assert V2Config.load().runtime.default_cwd == "."
+def test_no_non_owner_can_persist_a_credential_through_the_config_write(monkeypatch, tmp_path) -> None:
+ """Persisting a secret is an Owner act, and the allowlist closes that by shape.
+
+ The write schema used to be selected with ``can_manage_instance``, which
+ stopped being an owner test once a member held that capability: the member
+ fell past the Editor allowlist into a filter that removed only
+ ``remote_access``, so platform bot tokens and gateway secrets reached the
+ save path and were reconciled onto the live platform.
+
+ The enumeration comes from ``api._PLATFORM_SECRET_FIELDS`` and
+ ``api._GATEWAY_SECRET_FIELDS`` rather than from the four fields a review
+ happened to name, and the assertion is over the allowlist rather than over
+ those tables: a secret added to either table -- or a credential-bearing
+ section nobody has written down yet -- is unreachable below Owner because
+ it is absent from ``_EDITOR_CONFIG_WRITE_FIELDS``, not because someone
+ remembered to strip it. ``remote_access`` rides the same rule, which is why
+ the pairing-specific filter it used to need is gone.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, _ids = _setup_state(tmp_path)
+
+ secret_sections = {
+ section: fields for section, fields in api._PLATFORM_SECRET_FIELDS.items()
+ }
+ secret_sections["remote_access"] = ("provider",)
+ secret_sections["gateway"] = api._GATEWAY_SECRET_FIELDS
+ assert set(secret_sections) & api._EDITOR_CONFIG_WRITE_FIELDS == set()
+
+ def _stored_secrets() -> dict:
+ loaded = V2Config.load()
+ state = {
+ f"{section}.{field}": getattr(getattr(loaded, section, None), field, None)
+ for section, fields in secret_sections.items()
+ if section != "remote_access"
+ for field in fields
+ }
+ cloud = loaded.remote_access.vibe_cloud
+ state["remote_access.instance_id"] = cloud.instance_id
+ state["remote_access.client_id"] = cloud.client_id
+ state["remote_access.session_secret"] = cloud.session_secret
+ return state
+
+ baseline = _stored_secrets()
+ assert baseline["slack.bot_token"] == ""
+ assert baseline["remote_access.instance_id"] == "inst_123"
+
+ for role in ("member", "editor"):
+ client = _remote_client(config, role=role, email=f"{role}@example.com")
+ headers = csrf_headers(client, REMOTE_ORIGIN)
+ for section, fields in secret_sections.items():
+ for field in fields:
+ response = client.post(
+ "/api/config",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={section: {field: "stolen-credential"}},
+ )
+ assert response.status_code == 400, (role, section, field)
+ assert response.get_json()["error"] == {
+ "code": "editor_config_write_forbidden",
+ "message": "editor_config_write_forbidden",
+ }, (role, section, field)
+
+ # Refused, not merely unpersisted: the allowlisted preference still
+ # saves, so the refusals above are the schema and not a dead endpoint.
+ accepted = client.post(
+ "/api/config",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={"ack_mode": "reaction"},
+ )
+ assert accepted.status_code == 200, role
+
+ assert _stored_secrets() == baseline
+ assert V2Config.load().ack_mode == "reaction"
+
+
def test_config_write_requires_an_object_body_whatever_the_role(monkeypatch, tmp_path) -> None:
"""A config write is a patch object, and a body that is not one is refused.
diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsx
index fb01cf3a4..7bf8e728e 100644
--- a/ui/src/components/AppShell.test.tsx
+++ b/ui/src/components/AppShell.test.tsx
@@ -44,6 +44,7 @@ const instanceAuth = vi.hoisted(() => ({
instanceKind: null as 'personal' | 'organization' | null,
capabilities: {
can_manage_instance: true,
+ can_manage_access_members: true,
can_chat: true,
can_use_agents: true,
can_use_skills: true,
diff --git a/ui/src/components/workbench/CapabilityTabs.test.tsx b/ui/src/components/workbench/CapabilityTabs.test.tsx
index f89b3edb9..d665b7b7c 100644
--- a/ui/src/components/workbench/CapabilityTabs.test.tsx
+++ b/ui/src/components/workbench/CapabilityTabs.test.tsx
@@ -37,7 +37,11 @@ describe('CapabilityTabs', () => {
...localOwner,
remote: true,
instanceRole: 'editor',
- capabilities: { ...OWNER_INSTANCE_CAPABILITIES, can_manage_instance: false },
+ capabilities: {
+ ...OWNER_INSTANCE_CAPABILITIES,
+ can_manage_instance: false,
+ can_manage_access_members: false,
+ },
};
const markup = renderWith(remoteOwner);
expect(markup).toContain('workbench.modules.agents.title');
diff --git a/ui/src/context/InstanceAuthorizationContext.ts b/ui/src/context/InstanceAuthorizationContext.ts
index fcd404be4..171bf26bb 100644
--- a/ui/src/context/InstanceAuthorizationContext.ts
+++ b/ui/src/context/InstanceAuthorizationContext.ts
@@ -1,13 +1,13 @@
import { createContext, useContext } from 'react';
import type { InstanceCapabilities } from './ApiContext';
-import type { InstanceKind } from '../lib/sessionInfo';
+import type { InstanceKind, InstanceRole } from '../lib/sessionInfo';
import { DENIED_INSTANCE_CAPABILITIES } from '../lib/sessionInfo';
export interface InstanceAuthorizationValue {
remote: boolean;
instanceKind: InstanceKind | null;
- instanceRole: 'owner' | 'editor' | 'viewer' | null;
+ instanceRole: InstanceRole | null;
capabilities: InstanceCapabilities;
}
diff --git a/ui/src/features/permissions/PermissionsPage.test.tsx b/ui/src/features/permissions/PermissionsPage.test.tsx
index 119e0e8dd..7a9211143 100644
--- a/ui/src/features/permissions/PermissionsPage.test.tsx
+++ b/ui/src/features/permissions/PermissionsPage.test.tsx
@@ -88,15 +88,24 @@ const response = (overrides: Partial<PermissionsResponse> = {}): PermissionsResp
...overrides,
});
-function renderPage(canManage = true) {
+function renderPage(
+ canManage = true,
+ capabilities = canManage
+ ? OWNER_INSTANCE_CAPABILITIES
+ : {
+ ...OWNER_INSTANCE_CAPABILITIES,
+ can_manage_instance: false,
+ can_manage_access_members: false,
+ is_instance_owner: false,
+ },
+ instanceRole: 'owner' | 'member' | 'editor' | 'viewer' = canManage ? 'owner' : 'viewer',
+) {
return render(
<InstanceAuthorizationContext.Provider value={{
remote: true,
instanceKind: 'organization',
- instanceRole: canManage ? 'owner' : 'viewer',
- capabilities: canManage
- ? OWNER_INSTANCE_CAPABILITIES
- : { ...OWNER_INSTANCE_CAPABILITIES, can_manage_instance: false, is_instance_owner: false },
+ instanceRole,
+ capabilities,
}}>
<PermissionsPage />
</InstanceAuthorizationContext.Provider>,
@@ -272,6 +281,41 @@ describe('PermissionsPage state model', () => {
expect(screen.queryByRole('button', { name: /permissions.actions.addAccess/ })).toBeNull();
});
+ it('shows an Instance Member both access tabs read-only', async () => {
+ const withMember = response();
+ withMember.projection.access.entries = [{
+ kind: 'email',
+ value: '[email protected]',
+ role: 'member',
+ }];
+ api.getPermissions.mockResolvedValue(withMember);
+ const user = userEvent.setup();
+ renderPage(false, {
+ ...OWNER_INSTANCE_CAPABILITIES,
+ can_manage_access_members: false,
+ is_instance_owner: false,
+ }, 'member');
+
+ expect(await screen.findByText('permissions.states.readOnlyTitle')).toBeTruthy();
+ expect(screen.getByText('permissions.roles.member')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /permissions.actions.addAccess/ })).toBeNull();
+
+ // Project access decides who may reach a project, which is access
+ // administration rather than project management, so it stays Owner-only
+ // and the member sees the same read-only surface on both tabs.
+ await user.click(screen.getByRole('tab', { name: /permissions.tabs.projects/ }));
+ expect(screen.getByText('permissions.states.readOnlyTitle')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'permissions.actions.manage' })).toBeNull();
+ });
+
+ it('offers Instance Member in the access role picker for owners', async () => {
+ const user = userEvent.setup();
+ renderPage();
+
+ await user.click(await screen.findByRole('button', { name: 'permissions.actions.addAccess' }));
+ expect(screen.getByRole('radio', { name: 'permissions.roles.member' })).toBeTruthy();
+ });
+
it('gates every edit surface on the Backend mutation capability', async () => {
const readOnly = response();
readOnly.projection.capabilities = ['instance.permissions.read'];
@@ -1191,6 +1235,24 @@ describe('PermissionsPage conflict handling', () => {
role: 'editor',
})).toBe(false);
+ expect(requiresAccessNarrowing({
+ kind: 'email',
+ value: '[email protected]',
+ role: 'member',
+ }, {
+ kind: 'email',
+ value: '[email protected]',
+ role: 'editor',
+ })).toBe(true);
+ expect(requiresAccessNarrowing({
+ kind: 'email',
+ value: '[email protected]',
+ role: 'editor',
+ }, {
+ kind: 'email',
+ value: '[email protected]',
+ role: 'member',
+ })).toBe(false);
});
it('reconciles an access draft by principal after the authoritative list is reordered', async () => {
diff --git a/ui/src/features/permissions/PermissionsPage.tsx b/ui/src/features/permissions/PermissionsPage.tsx
index 72d5cea06..1381b99e3 100644
--- a/ui/src/features/permissions/PermissionsPage.tsx
+++ b/ui/src/features/permissions/PermissionsPage.tsx
@@ -61,6 +61,7 @@ import type {
AccessEntry,
AccessRole,
DirectoryGroup,
+ ProjectAccessRole,
PermissionProject,
PermissionsResponse,
PrincipalKind,
@@ -585,6 +586,7 @@ function AccessEntryDialog({
options={[
{ id: 'viewer', label: t('permissions.roles.viewer') },
{ id: 'editor', label: t('permissions.roles.editor') },
+ { id: 'member', label: t('permissions.roles.member') },
]}
/>
</div>
@@ -854,7 +856,7 @@ function ProjectAccessDialog({
<Select
aria-label={t('permissions.fields.role')}
value={binding.access_role}
- onChange={(event) => setBindings((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, access_role: event.target.value as AccessRole } : item))}
+ onChange={(event) => setBindings((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, access_role: event.target.value as ProjectAccessRole } : item))}
>
<option value="viewer">{t('permissions.roles.viewer')}</option>
<option value="editor">{t('permissions.roles.editor')}</option>
@@ -892,6 +894,13 @@ function ProjectAccessDialog({
export function PermissionsPage() {
const { t } = useTranslation();
const { capabilities } = useInstanceAuthorization();
+ const canManageAccessMembers = capabilities.can_manage_access_members;
+ // Deciding who may reach a project is access administration, not project
+ // management, so it follows the same capability as the instance access list
+ // rather than can_manage_projects. The PUT behind it is Owner-only for the
+ // same reason, and a control that is enabled here but refused there is worse
+ // than one that is honestly disabled.
+ const canManageProjectAccess = capabilities.can_manage_access_members;
const [state, setState] = useState<PageState>({ kind: 'loading' });
const [tab, setTab] = useState<'access' | 'projects'>('access');
const [editingAccess, setEditingAccess] = useState<string | null | undefined>(undefined);
@@ -1074,10 +1083,11 @@ export function PermissionsPage() {
const { response } = state;
const projection = response.projection;
const groups = projection.directory.groups;
- const editable = capabilities.can_manage_instance
- && projection.instance.local_mutation_allowed
+ const mutationAllowed = projection.instance.local_mutation_allowed
&& projection.capabilities.includes('instance.permissions.mutate')
&& !response.offline;
+ const accessMembersEditable = canManageAccessMembers && mutationAllowed;
+ const projectAccessEditable = canManageProjectAccess && mutationAllowed;
const applying = projectionIsApplying(response);
const instanceName = projection.instance.name?.trim() || t('permissions.currentInstance');
const instanceInitial = Array.from(instanceName)[0]?.toUpperCase() || 'A';
@@ -1122,7 +1132,7 @@ export function PermissionsPage() {
};
const removeAccess = async () => {
- if (!editable || removingAccess === null || removalInstanceId === null) return;
+ if (!accessMembersEditable || removingAccess === null || removalInstanceId === null) return;
if (removalRefreshRequired) {
await refreshRemovalConflict();
return;
@@ -1227,7 +1237,9 @@ export function PermissionsPage() {
title={t('permissions.states.cloudTitle')}
body={t('permissions.states.cloudBody')}
/>
- ) : !editable ? (
+ ) : tab === 'access' && !accessMembersEditable ? (
+ <Notice tone="neutral" icon={Eye} title={t('permissions.states.readOnlyTitle')} body={t('permissions.states.readOnlyBody')} />
+ ) : tab === 'projects' && !projectAccessEditable ? (
<Notice tone="neutral" icon={Eye} title={t('permissions.states.readOnlyTitle')} body={t('permissions.states.readOnlyBody')} />
) : null}
@@ -1276,7 +1288,7 @@ export function PermissionsPage() {
<h2 className="text-[15px] font-semibold">{t('permissions.access.title')}</h2>
<p className="mt-0.5 text-[12px] text-muted">{t('permissions.access.description')}</p>
</div>
- {editable ? <Button type="button" variant="brand" size="sm" onClick={() => setEditingAccess(null)}><Plus className="size-4" />{t('permissions.actions.addAccess')}</Button> : null}
+ {accessMembersEditable ? <Button type="button" variant="brand" size="sm" onClick={() => setEditingAccess(null)}><Plus className="size-4" />{t('permissions.actions.addAccess')}</Button> : null}
</div>
<div className="flex items-center gap-3 rounded-lg border border-violet/35 bg-violet/10 px-4 py-3">
<ShieldCheck className="size-5 shrink-0 text-violet-ink" />
@@ -1316,9 +1328,9 @@ export function PermissionsPage() {
<span className="truncate text-[12px] font-semibold">{displayPrincipal(entry.kind, entry.value, groups)}</span>
</div>
<Badge variant="secondary">{t(`permissions.principals.${entry.kind}`)}</Badge>
- <Badge variant={entry.role === 'editor' ? 'success' : 'secondary'}>{entry.role === 'editor' ? <Pencil className="size-3" /> : <Eye className="size-3" />}{t(`permissions.roles.${entry.role}`)}</Badge>
+ <Badge variant={entry.role === 'viewer' ? 'secondary' : 'success'}>{entry.role === 'viewer' ? <Eye className="size-3" /> : <Pencil className="size-3" />}{t(`permissions.roles.${entry.role}`)}</Badge>
<div className="flex justify-end gap-1">
- {editable ? <><Button type="button" size="icon" variant="ghost" aria-label={t('permissions.actions.editAccess')} onClick={() => setEditingAccess(entryKey)}><Pencil className="size-4" /></Button><Button type="button" size="icon" variant="ghost" aria-label={t('permissions.actions.removeAccess')} onClick={() => { setRemovingAccess(entryKey); setRemovalInstanceId(projection.instance.id); setRemovalConflict(false); setRemovalRefreshRequired(false); setRemovalError(undefined); }}><Trash2 className="size-4 text-destructive-ink" /></Button></> : null}
+ {accessMembersEditable ? <><Button type="button" size="icon" variant="ghost" aria-label={t('permissions.actions.editAccess')} onClick={() => setEditingAccess(entryKey)}><Pencil className="size-4" /></Button><Button type="button" size="icon" variant="ghost" aria-label={t('permissions.actions.removeAccess')} onClick={() => { setRemovingAccess(entryKey); setRemovalInstanceId(projection.instance.id); setRemovalConflict(false); setRemovalRefreshRequired(false); setRemovalError(undefined); }}><Trash2 className="size-4 text-destructive-ink" /></Button></> : null}
</div>
</div>
);
@@ -1347,7 +1359,7 @@ export function PermissionsPage() {
<Badge variant={mode === 'owner_only' ? 'warning' : mode === 'restricted' ? 'info' : 'secondary'}>{mode === 'owner_only' ? <LockKeyhole className="size-3" /> : mode === 'restricted' ? <ShieldCheck className="size-3" /> : <Users className="size-3" />}{t(`permissions.projects.modes.${mode}`)}</Badge>
<span className="truncate text-[12px] text-muted">{mode === 'restricted' ? t('permissions.projects.bindingCount', { count: project.access.bindings.length }) : t(`permissions.projects.audience.${mode}`)}</span>
<SyncBadge status={project.sync.status} />
- {editable ? <Button type="button" size="sm" variant="outline" onClick={() => setEditingProject(project)}>{t('permissions.actions.manage')}</Button> : <span />}
+ {projectAccessEditable ? <Button type="button" size="sm" variant="outline" onClick={() => setEditingProject(project)}>{t('permissions.actions.manage')}</Button> : <span />}
</div>
);
})}
@@ -1360,7 +1372,7 @@ export function PermissionsPage() {
open={editingAccess !== undefined}
editingKey={editingAccess ?? null}
response={response}
- editable={editable}
+ editable={accessMembersEditable}
onOpenChange={(open) => { if (!open) setEditingAccess(undefined); }}
onRefresh={refreshReady}
onSaved={(instanceId, result) => installMutationAcknowledgement(instanceId, result.instance_id, (current) => ({
@@ -1376,7 +1388,7 @@ export function PermissionsPage() {
project={editingProject}
instanceId={projection.instance.id}
groups={groups}
- editable={editable}
+ editable={projectAccessEditable}
onOpenChange={(open) => { if (!open) setEditingProject(null); }}
onRefresh={refreshReady}
onSaved={(instanceId, result) => installMutationAcknowledgement(
@@ -1392,7 +1404,7 @@ export function PermissionsPage() {
description={t('permissions.access.removeBody')}
destructive
confirmLabel={t('permissions.actions.removeAccess')}
- confirmDisabled={!editable}
+ confirmDisabled={!accessMembersEditable}
onConfirm={removeAccess}
>
{removalConflict ? (
diff --git a/ui/src/features/permissions/policy.ts b/ui/src/features/permissions/policy.ts
index 4120a4ba3..43f791cac 100644
--- a/ui/src/features/permissions/policy.ts
+++ b/ui/src/features/permissions/policy.ts
@@ -24,6 +24,12 @@ export function hasDuplicateAccessEntries(entries: AccessEntry[]): boolean {
return new Set(keys).size !== keys.length;
}
+const ACCESS_ROLE_RANK: Record<AccessEntry['role'], number> = {
+ viewer: 1,
+ editor: 2,
+ member: 3,
+};
+
export function requiresAccessNarrowing(
current: AccessEntry | null,
next: AccessEntry,
@@ -35,7 +41,7 @@ export function requiresAccessNarrowing(
) {
return true;
}
- return current.role === 'editor' && next.role === 'viewer';
+ return ACCESS_ROLE_RANK[next.role] < ACCESS_ROLE_RANK[current.role];
}
export function hasDuplicateProjectBindings(bindings: ProjectBinding[]): boolean {
diff --git a/ui/src/features/permissions/types.ts b/ui/src/features/permissions/types.ts
index 105d1f35a..bf730d306 100644
--- a/ui/src/features/permissions/types.ts
+++ b/ui/src/features/permissions/types.ts
@@ -1,4 +1,4 @@
-export type AccessRole = 'viewer' | 'editor';
+export type AccessRole = 'viewer' | 'editor' | 'member';
export type PrincipalKind = 'email' | 'email_domain' | 'organization_group';
export type ProjectSyncStatus = 'in_sync' | 'pending' | 'offline' | 'error' | 'deleted';
export type ResourceAccessLevel = 'public' | 'scope' | 'private';
@@ -23,10 +23,12 @@ export type DirectoryGroup = {
archived_at: string | null;
};
+export type ProjectAccessRole = 'viewer' | 'editor';
+
export type ProjectBinding = {
principal_kind: PrincipalKind;
principal_value: string;
- access_role: AccessRole;
+ access_role: ProjectAccessRole;
};
export type PermissionProject = {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 75380c740..9091a6e4e 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -4736,6 +4736,7 @@
},
"roles": {
"owner": "Owner",
+ "member": "Instance Member",
"editor": "Editor",
"viewer": "Viewer"
},
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 2675979b5..ea6d916e1 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -4736,6 +4736,7 @@
},
"roles": {
"owner": "所有者",
+ "member": "Avibe 成员",
"editor": "编辑者",
"viewer": "查看者"
},
diff --git a/ui/src/lib/sessionInfo.test.ts b/ui/src/lib/sessionInfo.test.ts
index 5c14850cb..d429c7dc9 100644
--- a/ui/src/lib/sessionInfo.test.ts
+++ b/ui/src/lib/sessionInfo.test.ts
@@ -102,6 +102,53 @@ describe('normalizeSessionInfo', () => {
expect(normalizeSessionInfo(null)).toEqual({ remote: true, authenticated: false });
});
+ it('preserves an explicit member role and capability', () => {
+ const session = normalizeSessionInfo({
+ remote: true,
+ authenticated: true,
+ email: '[email protected]',
+ instance_kind: 'organization',
+ instance_role: 'member',
+ capabilities: {
+ ...OWNER_INSTANCE_CAPABILITIES,
+ can_manage_access_members: false,
+ is_instance_owner: false,
+ },
+ });
+
+ expect(session).toMatchObject({
+ instance_role: 'member',
+ capabilities: {
+ ...OWNER_INSTANCE_CAPABILITIES,
+ can_manage_access_members: false,
+ is_instance_owner: false,
+ },
+ });
+ });
+
+ it('does not grant can_manage_access_members from a pre-member payload', () => {
+ const session = normalizeSessionInfo({
+ remote: true,
+ authenticated: true,
+ email: '[email protected]',
+ instance_role: 'owner',
+ capabilities: {
+ is_instance_owner: true,
+ can_manage_instance: true,
+ },
+ });
+
+ expect(session).toMatchObject({
+ instance_role: 'owner',
+ capabilities: {
+ ...DENIED_INSTANCE_CAPABILITIES,
+ is_instance_owner: true,
+ can_manage_instance: true,
+ can_manage_access_members: false,
+ },
+ });
+ });
+
it.each([
['personal', 'personal'],
['organization', 'organization'],
diff --git a/ui/src/lib/sessionInfo.ts b/ui/src/lib/sessionInfo.ts
index 2aba431a4..5c03e86f9 100644
--- a/ui/src/lib/sessionInfo.ts
+++ b/ui/src/lib/sessionInfo.ts
@@ -1,3 +1,5 @@
+export type InstanceRole = 'owner' | 'member' | 'editor' | 'viewer';
+
export type InstanceCapabilities = {
is_instance_owner: boolean;
can_read_instance: boolean;
@@ -5,6 +7,7 @@ export type InstanceCapabilities = {
can_manage_projects: boolean;
can_manage_agents: boolean;
can_manage_instance: boolean;
+ can_manage_access_members: boolean;
can_use_agents: boolean;
can_use_skills: boolean;
can_use_vault_secrets: boolean;
@@ -40,7 +43,7 @@ export type SessionInfo =
email: string;
sub?: string;
instance_kind: InstanceKind | null;
- instance_role: 'owner' | 'editor' | 'viewer';
+ instance_role: InstanceRole;
capabilities: InstanceCapabilities;
authorization_state: 'current';
};
@@ -52,6 +55,7 @@ export const DENIED_INSTANCE_CAPABILITIES: InstanceCapabilities = {
can_manage_projects: false,
can_manage_agents: false,
can_manage_instance: false,
+ can_manage_access_members: false,
can_use_agents: false,
can_use_skills: false,
can_use_vault_secrets: false,
@@ -121,6 +125,7 @@ export const normalizeSessionInfo = (value: unknown): SessionInfo => {
: OWNER_INSTANCE_CAPABILITIES;
const instanceRole =
value.instance_role === 'owner' ||
+ value.instance_role === 'member' ||
value.instance_role === 'editor' ||
value.instance_role === 'viewer'
? value.instance_role
diff --git a/vibe/api.py b/vibe/api.py
index c1612ebe4..ae13a1f17 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1391,6 +1391,18 @@ def _remote_access_pairing_projection(payload: dict) -> dict:
return {"vibe_cloud": {"paired": paired}}
+# ``strip_pairing_identity_from_config_write`` used to sit here: a non-owner
+# config write had ``remote_access`` removed and everything else was persisted.
+# It is gone rather than kept beside the allowlist, because a subtractive filter
+# and a closed allowlist cannot both be the non-owner write schema — the
+# subtractive one is only ever as complete as the last section somebody
+# remembered, and that is precisely how credential-bearing sections stayed
+# writable for a member. ``editor_config_write_payload`` is now the single
+# schema for every writer below Owner, and pairing identity is covered by it the
+# same way every other Owner-only section is: ``remote_access`` is not on the
+# allowlist, so the write is refused.
+
+
def _audio_asr_preference_projection(payload: dict) -> dict:
audio_asr = payload.get("audio_asr")
if not isinstance(audio_asr, dict):
diff --git a/vibe/authorization.py b/vibe/authorization.py
index c600d6487..31aeee6da 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -13,7 +13,7 @@ from core.inbox_events import (
)
-INSTANCE_ROLES = frozenset({"owner", "editor", "viewer"})
+INSTANCE_ROLES = frozenset({"owner", "member", "editor", "viewer"})
INSTANCE_ACCESS_SOURCES = frozenset(
{
"owner",
@@ -26,7 +26,7 @@ INSTANCE_ACCESS_SOURCES = frozenset(
)
ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})
INSTANCE_KINDS = frozenset({"personal", "organization"})
-_ROLE_RANK = {"viewer": 1, "editor": 2, "owner": 3}
+_ROLE_RANK = {"viewer": 1, "editor": 2, "member": 3, "owner": 4}
def recognized_instance_kind(value: object) -> str | None:
@@ -52,6 +52,8 @@ def instance_kind_is_unsupported(value: object) -> bool:
if not isinstance(value, str):
return True
return value.strip() not in {"", *INSTANCE_KINDS}
+
+
_RESOURCE_USE_MINIMUM_ROLES = {
"agent": "editor",
"skill": "editor",
@@ -144,14 +146,18 @@ class AuthorizationContext:
@property
def can_manage_projects(self) -> bool:
- return self.has_role("owner")
+ return self.has_role("member")
@property
def can_manage_agents(self) -> bool:
- return self.has_role("owner")
+ return self.has_role("member")
@property
def can_manage_instance(self) -> bool:
+ return self.has_role("member")
+
+ @property
+ def can_manage_access_members(self) -> bool:
return self.has_role("owner")
def can_use_resource(self, resource_kind: str) -> bool:
@@ -184,7 +190,7 @@ class AuthorizationContext:
@property
def can_use_system(self) -> bool:
- return self.has_role("owner")
+ return self.has_role("member")
def capability_projection(self) -> dict[str, bool]:
return {
@@ -194,6 +200,7 @@ class AuthorizationContext:
"can_manage_projects": self.can_manage_projects,
"can_manage_agents": self.can_manage_agents,
"can_manage_instance": self.can_manage_instance,
+ "can_manage_access_members": self.can_manage_access_members,
"can_use_agents": self.can_use_resource("agent"),
"can_use_skills": self.can_use_resource("skill"),
"can_use_vault_secrets": self.can_use_resource("vault_secret"),
@@ -340,6 +347,8 @@ def required_workbench_event_role(event_type: str) -> str:
return "viewer"
if event_type in _EDITOR_WORKBENCH_EVENTS:
return "editor"
+ if event_type in _PRIVILEGED_RUNTIME_WORKBENCH_EVENTS:
+ return "member"
return "owner"
@@ -393,9 +402,8 @@ _VIEWER_HTTP_RULES = tuple(
# Advertised Editor/Viewer surfaces are admitted by namespace so a newly
# added Skills, Vault, Harness, Files, Dock, Terminal, or Web Push route
-# inherits the same Instance role as the rest of that capability. Routes
-# that stay Owner-only — Agent create/import/update/delete, system config —
-# remain outside these prefixes and fail closed to owner.
+# inherits the same Instance role as the rest of that capability. Remaining
+# unknown APIs fail closed to Owner; see _MEMBER_HTTP_RULES.
_EDITOR_HTTP_NAMESPACES = (
"/api/skills",
"/api/vault",
@@ -413,6 +421,100 @@ _VIEWER_HTTP_MUTATION_RULES = (
("DELETE", re.compile(r"^/api/terminal/[^/]+$")),
)
+# Pairing identity, member set, and ownership stay Owner-only. Writes under
+# /api/remote-access default to owner so a newly added pair/unpair/settings
+# sibling cannot slip through as member. The ops below cannot change instance
+# id, backend URL, or secrets, so member keeps them.
+_REMOTE_ACCESS_HTTP_NAMESPACE = "/api/remote-access"
+_REMOTE_ACCESS_MEMBER_HTTP_RULES = tuple(
+ (method, re.compile(pattern))
+ for method, pattern in (
+ ("GET", r"^/api/remote-access/status$"),
+ ("GET", r"^/api/remote-access/network-interfaces$"),
+ ("POST", r"^/api/remote-access/optimize-route$"),
+ ("POST", r"^/api/remote-access/diagnostics$"),
+ )
+)
+
+# The member surface is an allow-list, and the unknown-route default is Owner.
+#
+# Enumerating the Owner exceptions instead was tried and does not converge: with
+# an unknown route defaulting to member, adding the member rank silently widened
+# every `/api/*` route that no other table classified -- 112 of them, including
+# `POST /api/control`, `POST /api/upgrade`, every `/api/backend/*/auth` route,
+# and the resource/project ACL PUTs. Review found members of that set one head at
+# a time because a list of exceptions is only ever as complete as the last audit.
+#
+# Inverting makes the omission safe in the other direction: a route absent from
+# this table keeps exactly the role it had before the member rank existed, so a
+# newly added management route cannot become member-reachable by accident and the
+# blast radius of this capability is bounded by what is written here.
+#
+# What belongs here: the routes backing the capabilities the member rank is
+# defined to grant -- ``can_manage_agents`` (Agent CRUD and the model routing an
+# Agent is configured against) and ``can_manage_projects``, plus read-only
+# instance state. What deliberately does not, and is therefore Owner:
+# * anything that mints, revokes, or promotes instance access -- the cloud
+# allowlist, IM bound users, and bind codes. A bind code is a bearer
+# credential, so *listing* them is equivalent to minting and stays Owner
+# while ``GET /api/users`` is a member read.
+# * anything holding or minting a credential -- `/api/backend/*/auth`, model
+# source credentials and OAuth, and the platform `auth_test`/channel probes
+# that take a bot token.
+# * instance lifecycle and host reach -- control, upgrade, ui/reload, logs,
+# doctor writes, dependency installs, and the filesystem browse routes.
+# * anything that changes an ACL or the IM access boundary -- the resource and
+# project access PUTs, and the channel/thread settings writes that carry
+# ``require_bind``.
+# * bulk Agent onboarding, a one-way instance-wide migration whose GET
+# discloses every Agent row and whose POST claims every policy-less one under
+# the caller's private ACL, and instance-wide default routing.
+_MEMBER_HTTP_RULES = tuple(
+ (method, re.compile(pattern))
+ for method, pattern in (
+ # can_manage_agents: Agent CRUD. /api/agents/default and
+ # /api/agent-onboarding are instance-wide and stay Owner by default.
+ #
+ # ``/api/agent/<name>/install`` is absent on purpose, and so is its job
+ # status sibling: the handler runs a package manager, a self-update, or a
+ # curl script on the host, persists the resulting CLI path, and may
+ # restart the backend. That is the "dependency installs" bullet above --
+ # host lifecycle, not Agent CRUD -- and it reached member only because
+ # this table was written by hand while the policy sat in a comment. There
+ # is no owner exception listed for it because none is needed: an absent
+ # route keeps the role it had before the member rank existed, which is
+ # Owner.
+ ("POST", r"^/api/agents$"),
+ ("PATCH", r"^/api/agents/[^/]+$"),
+ ("DELETE", r"^/api/agents/[^/]+$"),
+ ("POST", r"^/api/agents/import$"),
+ # can_manage_agents: selecting among already-authenticated model sources.
+ # Adding or re-authenticating a source is credential work and stays Owner.
+ ("GET", r"^/api/models/agents$"),
+ ("GET", r"^/api/models/agents/[^/]+/chain$"),
+ ("PUT", r"^/api/models/agents/[^/]+/chain$"),
+ ("GET", r"^/api/models/agents/[^/]+/sources$"),
+ ("PUT", r"^/api/models/agents/[^/]+/sources$"),
+ ("PUT", r"^/api/models/agents/opencode/menu$"),
+ ("PATCH", r"^/api/models/agents/[^/]+/mode$"),
+ ("POST", r"^/api/models/agents/[^/]+/chains/reorder$"),
+ ("GET", r"^/api/models/sources$"),
+ # can_manage_agents: instance-wide prompt text, not a credential.
+ ("GET", r"^/api/global-prompts$"),
+ ("PUT", r"^/api/global-prompts$"),
+ # can_manage_projects. Project ACL lives under /api/permissions and is
+ # Owner; agents-md is project content.
+ ("POST", r"^/api/projects$"),
+ ("PATCH", r"^/api/projects/[^/]+$"),
+ ("DELETE", r"^/api/projects/[^/]+$"),
+ ("GET", r"^/api/projects/[^/]+/agents-md$"),
+ ("PUT", r"^/api/projects/[^/]+/agents-md$"),
+ # Read-only instance state. The member set is readable, not writable.
+ ("GET", r"^/api/settings$"),
+ ("GET", r"^/api/users$"),
+ )
+)
+
_EDITOR_HTTP_RULES = tuple(
(method, re.compile(pattern))
for method, pattern in (
@@ -484,7 +586,15 @@ def http_authorization_policy(
return HttpAuthorizationPolicy("viewer")
if _path_in_namespaces(path, _EDITOR_HTTP_NAMESPACES):
return HttpAuthorizationPolicy("editor")
-
+ if _path_in_namespaces(path, (_REMOTE_ACCESS_HTTP_NAMESPACE,)):
+ if _http_rule_matches(normalized_method, path, _REMOTE_ACCESS_MEMBER_HTTP_RULES):
+ return HttpAuthorizationPolicy("member")
+ return HttpAuthorizationPolicy("owner")
+ if _http_rule_matches(normalized_method, path, _MEMBER_HTTP_RULES):
+ return HttpAuthorizationPolicy("member")
+
+ # Default deny: an unclassified /api route is Owner-only, so adding the
+ # member rank cannot widen a route nobody listed. See _MEMBER_HTTP_RULES.
minimum_role = "owner"
for rule_method, pattern in _EDITOR_HTTP_RULES:
if normalized_method == rule_method and pattern.fullmatch(path):
@@ -503,8 +613,12 @@ def required_instance_role(method: str, path: str) -> str | None:
"""Return the minimum role for a remote HTTP request.
Non-API page/static reads are handled by the authenticated shell. Unknown
- API routes deliberately default to owner so a newly added management route
- cannot accidentally become available to editors or viewers.
+ API routes deliberately default to owner, so a newly added management route
+ is never reachable by a role that predates it. The member rank widens only
+ the routes listed in ``_MEMBER_HTTP_RULES`` plus the read/ops quartet under
+ ``/api/remote-access``; access administration, credential and lifecycle
+ routes, ACL writes, bulk Agent migration, and instance-wide default-agent
+ routing are Owner by that default rather than by per-route exception.
"""
return http_authorization_policy(method, path).minimum_role
diff --git a/vibe/permissions.py b/vibe/permissions.py
index fc96df163..8784cec67 100644
--- a/vibe/permissions.py
+++ b/vibe/permissions.py
@@ -35,7 +35,8 @@ _ACCESS_MODES = frozenset({"allowlist", "public"})
_PERMISSION_AUTHORITIES = frozenset({"instance", "cloud"})
_REQUIRED_PERMISSION_CAPABILITY = "instance.permissions.read"
_PRINCIPAL_KINDS = frozenset({"email", "email_domain", "organization_group"})
-_ACCESS_ROLES = frozenset({"viewer", "editor"})
+_ACCESS_ROLES = frozenset({"viewer", "editor", "member"})
+_PROJECT_ACCESS_ROLES = frozenset({"viewer", "editor"})
_ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})
_PROJECT_ACCESS_MODES = frozenset({"inherit", "restricted"})
_PROJECT_SYNC_STATUSES = frozenset({"in_sync", "pending", "offline", "error", "deleted"})
@@ -275,7 +276,7 @@ def _validate_project(value: Any) -> dict[str, Any]:
_require_keys(binding, "principal_kind", "principal_value", "access_role")
_require_enum(binding["principal_kind"], _PRINCIPAL_KINDS)
_require_nonempty_string(binding["principal_value"])
- _require_enum(binding["access_role"], _ACCESS_ROLES)
+ _require_enum(binding["access_role"], _PROJECT_ACCESS_ROLES)
binding_identities.append(
_principal_identity(binding["principal_kind"], binding["principal_value"])
)
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index 54d604743..34813db9d 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -63,7 +63,7 @@ _SESSION_AUTHORIZATION_REFERENCE_RE = re.compile(r"\A[A-Za-z0-9_-]{24,64}\Z")
_SESSION_BROWSER_ID_KEY = "browser_session_id"
_SESSION_BROWSER_ID_RE = re.compile(r"\A[A-Za-z0-9_-]{24,64}\Z")
OAUTH_ID_TOKEN_CLOCK_LEEWAY_SECONDS = 30
-_INSTANCE_ACCESS_ROLES = frozenset({"owner", "editor", "viewer"})
+_INSTANCE_ACCESS_ROLES = frozenset({"owner", "member", "editor", "viewer"})
_INSTANCE_ACCESS_SOURCES = frozenset(
{"owner", "public_instance", "email", "email_domain", "organization_group", "show_page_email"}
)
@@ -151,7 +151,7 @@ _RESOURCE_ACL_ACCESS_LEVELS = frozenset({"public", "scope", "private"})
_RESOURCE_ACL_SYNC_STATUSES = frozenset({"in_sync", "pending", "offline", "error", "deleted"})
_RESOURCE_ACL_MAX_REVISION = (1 << 53) - 1
_RESOURCE_ACL_PENDING_VAULT_RELEASE_PREFIX = "resource_acl_pending_vault_release:"
-_INSTANCE_ACCESS_ROLES = frozenset({"owner", "editor", "viewer"})
+_INSTANCE_ACCESS_ROLES = frozenset({"owner", "member", "editor", "viewer"})
_INSTANCE_ACCESS_SOURCES = frozenset(
{"owner", "public_instance", "email", "email_domain", "organization_group", "show_page_email"}
)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 84a484df5..68103af5a 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2498,6 +2498,23 @@ def _has_runtime_owner_access(context: Any) -> bool:
return bool(context is not None and context.is_instance_owner)
+def _access_administration_forbidden(context: Any = None):
+ """Return a 403 response unless the caller may administer instance access.
+
+ The route policy table (``authorization._ACCESS_ADMINISTRATION_HTTP_RULES``)
+ is one layer; this is the one that travels with the handler, so a route
+ re-registered under a different path keeps the gate. Both answer the same
+ question: may this caller change who reaches the instance? The member set is
+ cloud allowlist entries *and* multi-platform IM bound users, so IM bind codes
+ and bound-user mutation are member management.
+ """
+
+ resolved = _request_authorization_context(context)
+ if resolved is not None and resolved.can_manage_access_members:
+ return None
+ return jsonify({"ok": False, "error": "instance_access_forbidden"}), 403
+
+
def _runtime_record_session_id(record: Any) -> str | None:
if not isinstance(record, Mapping):
return None
@@ -2763,7 +2780,7 @@ async def current_instance_permissions_authorized_users_put(
from vibe import permissions
authorization_context = getattr(g, "authorization_context", None)
- if authorization_context is None or not authorization_context.can_manage_instance:
+ if authorization_context is None or not authorization_context.can_manage_access_members:
return jsonify({"ok": False, "error": "instance_access_forbidden"}), 403
try:
body = await starlette_request.body()
@@ -2933,8 +2950,21 @@ def enforce_project_role_capabilities():
if minimum_instance_role is not None
else required_instance_role(request.method, request.path)
)
- if minimum_instance_role not in {"viewer", "editor"}:
+ if minimum_instance_role not in {"viewer", "editor", "member"}:
return None
+ # A ``member`` route is instance-wide Project administration, but it still
+ # names one Project, and the instance role does not say *which* Projects the
+ # caller may touch. Ceiling this at "editor" is what let a member mutate a
+ # restricted Project by id that ``list_projects`` hides from them.
+ #
+ # The floor for those routes is the Project ACL's *visibility* floor, not
+ # "member": a member holding an explicit editor binding on a restricted
+ # Project has an effective Project role of editor, so demanding a "member"
+ # Project role would refuse the very Projects the list shows them. The
+ # instance-role half of the authorization is already enforced by the HTTP
+ # policy before this hook runs; this half only asks whether the Project is
+ # theirs to see.
+ required_project_role = "viewer" if minimum_instance_role == "member" else minimum_instance_role
resource = _project_access_resource(request.path)
if resource is None:
return None
@@ -2954,7 +2984,7 @@ def enforce_project_role_capabilities():
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):
+ if not project_access_service.role_allows(role, required_project_role):
return jsonify({"ok": False, "error": "not_found"}), 404
return None
@@ -4990,6 +5020,12 @@ def vibe_agent_onboarding():
try:
user_context = getattr(g, "authorization_context", None)
+ # Owner identity rather than can_manage_access_members: this is an
+ # instance-wide one-way Agent migration, not member management. The store
+ # repeats the check in ``_require_agent_onboarding_access`` so non-HTTP
+ # callers are gated too; both layers ask the same question.
+ if not _has_runtime_owner_access(user_context):
+ return jsonify({"ok": False, "error": "instance_access_forbidden"}), 403
if request.method == "POST":
return jsonify(api.onboard_vibe_agents(user_context=user_context))
return jsonify(api.get_vibe_agent_onboarding(user_context=user_context))
@@ -6594,8 +6630,26 @@ async def config_post():
# falsy shapes that happen to exist today.
payload = request.json
authorization_context = getattr(g, "authorization_context", None)
- editor_write = authorization_context is not None and not authorization_context.can_manage_instance
- if editor_write:
+ # Persisting a credential is an Owner act, so the write schema is selected
+ # by ownership and by nothing else. ``can_manage_instance`` used to pick it,
+ # which stopped being an owner test the moment a member acquired that
+ # capability: a member fell past this branch into a filter that removed only
+ # ``remote_access``, and every other section — ``slack.bot_token``,
+ # ``discord.bot_token``, ``lark.app_secret``, gateway secrets — reached the
+ # save path and was reconciled onto the live platform.
+ #
+ # There is one non-owner write schema and it is ``_EDITOR_CONFIG_WRITE_FIELDS``,
+ # a closed allowlist of non-secret preferences. Closed is the whole point:
+ # no credential-bearing section has to be enumerated here, and a secret
+ # added to ``api._PLATFORM_SECRET_FIELDS`` (or to any config section) is
+ # unreachable below Owner by construction rather than by remembering to add
+ # it to a strip list. Pairing identity is covered by the same rule —
+ # ``remote_access`` is not on the allowlist, so it is refused outright
+ # instead of silently dropped.
+ non_owner_write = (
+ authorization_context is not None and not authorization_context.can_manage_access_members
+ )
+ if non_owner_write:
try:
payload = api.editor_config_write_payload(payload)
except ValueError as exc:
@@ -6613,11 +6667,11 @@ async def config_post():
payload,
)
except ValueError as exc:
- # Same chokepoint as the allowlist rejection above: an Editor write
+ # Same chokepoint as the allowlist rejection above: a non-owner write
# answers with a stable code whichever layer refused it, including
# value validation raised deep inside ``V2Config.from_payload``. Owner
# saves keep the descriptive message the Settings pages already show.
- if editor_write:
+ if non_owner_write:
code = api.editor_config_write_error_code(exc)
return jsonify({"ok": False, "error": {"code": code, "message": code}}), 400
message = str(exc)
@@ -6735,6 +6789,9 @@ def remote_access_status():
def remote_access_vibe_cloud_pair():
from vibe import remote_access
+ authorization_context = getattr(g, "authorization_context", None)
+ if authorization_context is None or not authorization_context.can_manage_access_members:
+ return jsonify({"ok": False, "error": "instance_access_forbidden"}), 403
payload = request.json or {}
result = remote_access.pair(
payload.get("pairing_key", ""),
@@ -8128,6 +8185,11 @@ def projects_create():
)
except (FileNotFoundError, NotADirectoryError) as err:
return jsonify({"error": str(err)}), 400
+ except LookupError as err:
+ # The folder is already held by a Project this caller cannot see, so
+ # create-or-reuse answers exactly as the id-keyed routes do rather than
+ # reusing, reviving, or duplicating it.
+ return jsonify({"error": str(err)}), 404
return jsonify(project), 201
@@ -12378,6 +12440,9 @@ def users_post():
from vibe import api
from storage.settings_service import ScopeAgentUnavailableError, StaleScopeAgentBindingError
+ forbidden = _access_administration_forbidden()
+ if forbidden is not None:
+ return forbidden
payload = request.json or {}
try:
return jsonify(api.save_users(payload))
@@ -12391,6 +12456,9 @@ def users_post():
def users_toggle_admin(user_id):
from vibe import api
+ forbidden = _access_administration_forbidden()
+ if forbidden is not None:
+ return forbidden
payload = request.json or {}
return jsonify(api.toggle_admin(user_id, payload.get("is_admin", False), payload.get("platform") or None))
@@ -12399,6 +12467,9 @@ def users_toggle_admin(user_id):
def users_delete(user_id):
from vibe import api
+ forbidden = _access_administration_forbidden()
+ if forbidden is not None:
+ return forbidden
result = api.remove_user(user_id, request.args.get("platform") or None)
if not result.get("ok"):
return jsonify(result), 400
@@ -12409,6 +12480,10 @@ def users_delete(user_id):
def bind_codes_get():
from vibe import api
+ # The listing carries the codes themselves, so reading it mints access.
+ forbidden = _access_administration_forbidden()
+ if forbidden is not None:
+ return forbidden
return jsonify(api.get_bind_codes())
@@ -12416,6 +12491,9 @@ def bind_codes_get():
def bind_codes_post():
from vibe import api
+ forbidden = _access_administration_forbidden()
+ if forbidden is not None:
+ return forbidden
payload = request.json or {}
result = api.create_bind_code(
code_type=payload.get("type", "one_time"),
@@ -12430,6 +12508,9 @@ def bind_codes_post():
def bind_codes_delete(code):
from vibe import api
+ forbidden = _access_administration_forbidden()
+ if forbidden is not None:
+ return forbidden
result = api.delete_bind_code(code)
if not result.get("ok"):
return jsonify(result), 404
@@ -12440,6 +12521,10 @@ def bind_codes_delete(code):
def setup_first_bind_code():
from vibe import api
+ # Named "setup", but it mints a live bind code rather than reporting state.
+ forbidden = _access_administration_forbidden()
+ if forbidden is not None:
+ return forbidden
return jsonify(api.get_first_bind_code())