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.

fix(auth): separate resource use from management

Maxvint58388b848485
diff --git a/core/services/skills.py b/core/services/skills.py
index fc6e941a4..d3bc7ea1e 100644
--- a/core/services/skills.py
+++ b/core/services/skills.py
@@ -429,13 +429,60 @@ def _require_skill_management_access(
def _require_skill_create_access(user_context: Any) -> None:
context = resolve_resource_access_context(user_context)
- if context.is_trusted_local or context.is_instance_owner:
- return
- if context.is_remote and context.is_active_organization_member and context.subject:
+ if context.can_manage_instance:
return
raise SkillAccessError()
+def _require_skill_use_access(
+ context: Any,
+ *,
+ scope: str,
+ project_dir: Optional[str],
+) -> None:
+ """Require Instance use and Project chat access before invoking askill."""
+
+ if not context.can_use_resource("skill"):
+ raise SkillAccessError()
+ if context.is_trusted_local or context.is_instance_owner or scope == "global":
+ return
+ if not project_dir:
+ if scope == "all":
+ return
+ raise SkillAccessError()
+
+ from sqlalchemy import select
+
+ from storage import project_access_service
+ from storage.db import get_cached_sqlite_engine
+ from storage.models import scope_settings, scopes
+
+ resolved_dir = os.path.realpath(os.path.abspath(os.path.expanduser(project_dir)))
+ engine = get_cached_sqlite_engine()
+ with engine.connect() as connection:
+ project_id = connection.execute(
+ select(scopes.c.native_id)
+ .select_from(scopes.join(scope_settings, scope_settings.c.scope_id == scopes.c.id))
+ .where(
+ scopes.c.platform == "avibe",
+ scopes.c.scope_type == "project",
+ scope_settings.c.workdir == resolved_dir,
+ )
+ .limit(1)
+ ).scalar_one_or_none()
+ role = (
+ project_access_service.get_effective_project_role(
+ connection,
+ context,
+ str(project_id),
+ )
+ if project_id
+ else None
+ )
+ if not project_access_service.role_allows(role, "editor"):
+ raise SkillAccessError()
+
+
def _skill_names_from_payload(payload: dict[str, Any]) -> list[str]:
names: list[str] = []
direct = payload.get("skill")
@@ -616,6 +663,8 @@ async def list_skills(
repo's ``.agents/skills``. Each item carries description / version / tags /
source / installSource / timestamps natively (askill v0.1.13+).
"""
+ context = resolve_resource_access_context(user_context)
+ _require_skill_use_access(context, scope=scope, project_dir=project_dir)
args = ["list", *_list_scope_flag(scope), *_agent_flags(backends)]
result = await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))
return _filter_skill_listing(
@@ -623,7 +672,7 @@ async def list_skills(
scope=scope,
project_dir=project_dir,
backends=backends,
- user_context=user_context,
+ user_context=context,
)
@@ -632,6 +681,7 @@ async def preview_source(
source: str,
*,
project_dir: Optional[str] = None,
+ user_context: Any = None,
) -> dict[str, Any]:
"""Discover the skills a source contains without installing.
@@ -640,6 +690,7 @@ async def preview_source(
"""
if not source:
raise SkillsError("missing_source", "no source provided")
+ _require_skill_create_access(resolve_resource_access_context(user_context))
return await _run_askill(askill_path, ["add", source, "--list"], cwd=project_dir)
@@ -768,6 +819,7 @@ async def remove_skill(
raise SkillsError("invalid_scope", "remove scope must be global or project")
context = resolve_resource_access_context(user_context)
if not context.is_trusted_local:
+ _require_skill_create_access(context)
resource_ids = await _installed_skill_resource_ids(
askill_path,
name,
@@ -795,12 +847,18 @@ async def remove_skill(
return result
-async def find_skills(askill_path: str, query: str = "") -> dict[str, Any]:
+async def find_skills(
+ askill_path: str,
+ query: str = "",
+ *,
+ user_context: Any = None,
+) -> dict[str, Any]:
"""Search the askill.sh registry. Maps to ``askill find <query>``.
Returns ``{ok, query, filters, sort, pagination, count, skills[]}`` where
each skill carries ``aiScore`` / ``aiBreakdown`` / ``stars`` / ``tags``.
"""
+ _require_skill_create_access(resolve_resource_access_context(user_context))
args = ["find"]
if query:
args.append(query)
@@ -820,9 +878,10 @@ async def check(
each skill has ``status`` (``update_available`` | ``up_to_date`` |
``uncheckable``) plus ``localVersion`` / ``remoteVersion``.
"""
+ context = resolve_resource_access_context(user_context)
+ _require_skill_use_access(context, scope=scope, project_dir=project_dir)
args = ["check", *_target_scope_flag(scope)]
result = await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))
- context = resolve_resource_access_context(user_context)
filtered = _filter_skill_listing(
result,
scope=scope,
@@ -858,6 +917,7 @@ async def update(
raise SkillsError("invalid_scope", "update scope must be global or project")
context = resolve_resource_access_context(user_context)
if not context.is_trusted_local:
+ _require_skill_create_access(context)
resource_ids = await _installed_skill_resource_ids(
askill_path,
name,
diff --git a/core/show_pages.py b/core/show_pages.py
index de0071d36..ce9bfba88 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -368,9 +368,7 @@ class ShowPageStore:
@staticmethod
def _require_create_access(user_context: Any) -> None:
- if user_context.is_trusted_local or user_context.is_instance_owner:
- return
- if user_context.is_remote and user_context.is_active_organization_member and user_context.subject:
+ if user_context.can_manage_instance:
return
raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")
diff --git a/core/vibe_agents.py b/core/vibe_agents.py
index 9cc0e7121..66535aad4 100644
--- a/core/vibe_agents.py
+++ b/core/vibe_agents.py
@@ -20,6 +20,7 @@ from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
from storage.migrations import guard_source_checkout_default_state_migration, run_migrations
from storage.models import agent_sessions, agents, run_definitions, scope_settings, state_meta
+from vibe.authorization import trusted_local_context
logger = logging.getLogger(__name__)
@@ -139,9 +140,7 @@ def ensure_agent_name_access(agent_name: str | None, *, user_context: Any = None
def _require_agent_create_access(user_context: Any) -> None:
- if user_context.is_trusted_local or user_context.is_instance_owner:
- return
- if user_context.is_remote and user_context.is_active_organization_member and user_context.subject:
+ if user_context.can_manage_agents:
return
raise VibeAgentAccessError("Agent access is not permitted.")
@@ -430,8 +429,9 @@ class VibeAgentStore:
system_prompt: Any = _UNSET,
metadata: Any = _UNSET,
enabled: Any = _UNSET,
+ user_context: Any = None,
) -> VibeAgent:
- existing = self.require(name)
+ existing = self.require_manageable(name, user_context=user_context)
values: dict[str, Any] = {"updated_at": _utc_now_iso()}
if description is not _UNSET:
values["description"] = _clean_optional(description)
@@ -449,15 +449,16 @@ class VibeAgentStore:
conn.execute(agents.update().where(agents.c.id == existing.id).values(**values))
return self.require(name)
- def set_enabled(self, name: str, enabled: bool) -> VibeAgent:
- return self.update(name, enabled=enabled)
+ def set_enabled(self, name: str, enabled: bool, *, user_context: Any = None) -> VibeAgent:
+ return self.update(name, enabled=enabled, user_context=user_context)
- def remove(self, name: str) -> bool:
+ def remove(self, name: str, *, user_context: Any = None) -> bool:
from storage import resource_access_service
agent = self.get(name)
if agent is None:
return False
+ self.require_manageable(name, user_context=user_context)
if is_builtin_default_agent(agent):
raise ValueError(f"agent '{agent.name}' is built in and cannot be deleted")
normalized = agent.normalized_name
@@ -526,7 +527,7 @@ class VibeAgentStore:
def ensure_default_agent(self, *, backend: str = "claude") -> VibeAgent:
existing = self.get(DEFAULT_AGENT_NAME)
if existing:
- self.set_default_agent_name(existing.name)
+ self.set_default_agent_name(existing.name, user_context=trusted_local_context())
return existing
agent = self.create(
name=DEFAULT_AGENT_NAME,
@@ -536,7 +537,7 @@ class VibeAgentStore:
metadata={"builtin": True},
enabled=True,
)
- self.set_default_agent_name(agent.name)
+ self.set_default_agent_name(agent.name, user_context=trusted_local_context())
return agent
def ensure_builtin_default_agent(self, *, backend: str, name: str | None = None) -> VibeAgent:
@@ -555,7 +556,11 @@ class VibeAgentStore:
return existing
merged = {**existing.metadata, **metadata}
if existing.source != "builtin" or existing.metadata != merged:
- return self.update(existing.name, metadata=merged)
+ return self.update(
+ existing.name,
+ metadata=merged,
+ user_context=trusted_local_context(),
+ )
return existing
return self.create(
name=agent_name,
@@ -584,7 +589,11 @@ class VibeAgentStore:
elif should_disable:
updates["enabled"] = False
if updates:
- return self.update(agent.name, **updates)
+ return self.update(
+ agent.name,
+ user_context=trusted_local_context(),
+ **updates,
+ )
return agent
def ensure_builtin_default_agents(
@@ -616,7 +625,10 @@ class VibeAgentStore:
default_agent = self.get(default_name) if default_name else None
enabled_ensured = [agent for agent in ensured if agent.enabled]
if (default_agent is None or not default_agent.enabled) and enabled_ensured:
- self.set_default_agent_name(enabled_ensured[0].name)
+ self.set_default_agent_name(
+ enabled_ensured[0].name,
+ user_context=trusted_local_context(),
+ )
return ensured
def get_builtin_default_agent_for_backend(self, backend: str, *, enabled_only: bool = True) -> Optional[VibeAgent]:
@@ -646,8 +658,10 @@ class VibeAgentStore:
payload = _json_loads(value, None)
return str(payload).strip() if payload else None
- def set_default_agent_name(self, name: str) -> None:
- agent = self.require_enabled(name)
+ def set_default_agent_name(self, name: str, *, user_context: Any = None) -> None:
+ agent = self.require_manageable(name, user_context=user_context)
+ if not agent.enabled:
+ raise ValueError(f"agent '{agent.name}' is disabled")
now = _utc_now_iso()
with self.engine.begin() as conn:
conn.execute(state_meta.delete().where(state_meta.c.key == DEFAULT_AGENT_META_KEY))
diff --git a/docs/plans/issue-1055-resource-use-vs-manage.md b/docs/plans/issue-1055-resource-use-vs-manage.md
new file mode 100644
index 000000000..c63930987
--- /dev/null
+++ b/docs/plans/issue-1055-resource-use-vs-manage.md
@@ -0,0 +1,47 @@
+# Issue 1055: Resource Use vs Management
+
+## Background
+
+Organization Resource ACL already filters Agents, Skills, Vault secrets, and
+Show Pages at several domain-service boundaries. Instance authorization still
+classifies much of the resource surface as owner-only, while the resource ACL
+service maintains a second authorization context and does not consistently
+enforce the Instance role when called directly.
+
+## Goal
+
+Make resource use a first-class Instance capability, separate from owner-only
+resource management. Authorized editors may discover and use Agents, Skills,
+and Vault secrets; viewers may only read the approved Show Page projection.
+Every resource service combines that Instance capability with the current
+effective Resource ACL.
+
+## Solution
+
+- Add a resource-kind-aware `AuthorizationContext.can_use_resource()` contract
+ and expose its per-kind projections to the Web UI.
+- Use `AuthorizationContext` as the identity passed through HTTP, SSE,
+ WebSocket, and resource services instead of reparsing a parallel request
+ context.
+- Enforce owner-only creation and management in resource services, and require
+ both the Instance use capability and effective Resource ACL for discovery,
+ selection, session creation, and invocation.
+- Project those rules onto HTTP routes and UI navigation/actions.
+- Publish `authorization.changed` after a narrowing Resource ACL sync and clear
+ Agent, Skill, Vault, and Show Page read caches in open clients.
+
+## Scope Boundary with Issue 1057
+
+This change re-evaluates the currently applied Resource ACL whenever a resource
+is selected or invoked, and invalidates open-client resource caches when an ACL
+is narrowed. Signed-claim revalidation, authorization watermarks, and
+cross-host active-session invalidation remain owned by issue 1057.
+
+## Todo
+
+- [x] Add the central resource-use capability contract.
+- [x] Unify resource services on `AuthorizationContext` and enforce use/manage.
+- [x] Update route and UI projections.
+- [x] Invalidate open-client caches after authorization narrowing.
+- [x] Add owner/editor/viewer matrices and direct-service security tests.
+- [x] Run focused tests, Ruff, and the UI build.
diff --git a/storage/resource_access_service.py b/storage/resource_access_service.py
index 2a149bbab..b268b90e0 100644
--- a/storage/resource_access_service.py
+++ b/storage/resource_access_service.py
@@ -11,7 +11,6 @@ import json
import time
from collections.abc import Mapping, Sequence
from contextlib import contextmanager
-from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any, Iterator
@@ -20,6 +19,11 @@ from sqlalchemy.engine import Connection
from storage.db import get_cached_sqlite_engine
from storage.models import resource_access_groups, resource_access_policies, state_meta
+from vibe.authorization import (
+ AuthorizationContext,
+ context_from_session_payload,
+ trusted_local_context,
+)
RESOURCE_KINDS = frozenset({"agent", "vault_secret", "skill", "show_page"})
@@ -37,32 +41,9 @@ class ResourceAccessError(ValueError):
self.code = code
-@dataclass(frozen=True)
-class ResourceUserContext:
- subject: str | None = None
- email: str | None = None
- organization_id: str | None = None
- organization_member_id: str | None = None
- organization_role: str | None = None
- group_ids: frozenset[str] | None = None
- membership_version: str | None = None
- claims_issued_at: int | None = None
- instance_role: str | None = None
- instance_access_source: str | None = None
- is_remote: bool = False
- is_trusted_local: bool = False
-
- @property
- def is_active_organization_member(self) -> bool:
- return bool(
- self.organization_id
- and self.organization_member_id
- and self.organization_role in ORGANIZATION_ROLES
- )
-
- @property
- def is_instance_owner(self) -> bool:
- return self.instance_role == "owner" and bool(self.subject)
+# Compatibility name for callers that predate the shared authorization
+# context. Resource services and transports now pass the same immutable object.
+ResourceUserContext = AuthorizationContext
def _utc_now_iso() -> str:
@@ -158,37 +139,11 @@ def _context_from_mapping(
is_remote: bool,
is_trusted_local: bool,
) -> ResourceUserContext:
- data = payload or {}
- organization_id = _clean_optional_string(data.get("vibe_organization_id", data.get("organization_id")))
- raw_groups = data.get("vibe_group_ids", data.get("group_ids"))
- group_ids: frozenset[str] | None = None
- if organization_id and isinstance(raw_groups, (list, tuple, set, frozenset)):
- cleaned_groups = [_clean_optional_string(value) for value in raw_groups]
- if all(value is not None for value in cleaned_groups):
- group_ids = frozenset(value for value in cleaned_groups if value is not None)
- role = _clean_optional_string(data.get("vibe_organization_role", data.get("organization_role")))
- if role not in ORGANIZATION_ROLES:
- role = None
- return ResourceUserContext(
- subject=_clean_optional_string(data.get("sub")),
- email=_clean_optional_string(data.get("email"), limit=320),
- organization_id=organization_id,
- organization_member_id=_clean_optional_string(
- data.get("vibe_organization_member_id", data.get("organization_member_id"))
- ),
- organization_role=role,
- group_ids=group_ids,
- membership_version=_clean_optional_string(
- data.get("vibe_membership_version", data.get("membership_version"))
- ),
- claims_issued_at=_clean_positive_int(data.get("claims_issued_at", data.get("iat"))),
- instance_role=_clean_optional_string(data.get("vibe_instance_role", data.get("instance_role"))),
- instance_access_source=_clean_optional_string(
- data.get("vibe_instance_access_source", data.get("instance_access_source"))
- ),
- is_remote=is_remote,
- is_trusted_local=is_trusted_local,
- )
+ if is_trusted_local:
+ return trusted_local_context()
+ if not is_remote:
+ return AuthorizationContext()
+ return context_from_session_payload(payload or {})
def current_resource_context(
@@ -205,6 +160,8 @@ def current_resource_context(
an untrusted anonymous context rather than guessing at an identity.
"""
+ if isinstance(session_payload, AuthorizationContext):
+ return session_payload
if session_payload is not None or is_remote is not None or is_trusted_local is not None:
return _context_from_mapping(
session_payload,
@@ -213,27 +170,14 @@ def current_resource_context(
)
try:
- from vibe import remote_access, ui_server
+ from vibe.ui_compat import g, has_request_context
- config = ui_server._load_remote_access_config()
- remote_request = bool(
- config is not None
- and ui_server._is_remote_access_request(config)
- and not ui_server._is_local_request(config)
- )
- if remote_request and config is not None:
- payload = remote_access.parse_session_cookie(
- config,
- ui_server.request.cookies.get(remote_access.SESSION_COOKIE_NAME),
- )
- return _context_from_mapping(payload, is_remote=True, is_trusted_local=False)
- return _context_from_mapping(
- None,
- is_remote=False,
- is_trusted_local=bool(ui_server._is_local_request(config)),
- )
+ if has_request_context():
+ context = getattr(g, "authorization_context", None)
+ return context if isinstance(context, AuthorizationContext) else AuthorizationContext(is_remote=True)
except Exception:
- return ResourceUserContext()
+ pass
+ return AuthorizationContext()
def resolve_resource_access_context(
@@ -241,7 +185,7 @@ def resolve_resource_access_context(
) -> ResourceUserContext:
"""Resolve ACL context, trusting implicit local use only outside HTTP."""
- if isinstance(user_context, ResourceUserContext):
+ if isinstance(user_context, AuthorizationContext):
return user_context
if isinstance(user_context, Mapping):
return current_resource_context(user_context, is_remote=True)
@@ -254,7 +198,7 @@ def resolve_resource_access_context(
if has_request_context():
return context
- return ResourceUserContext(is_trusted_local=True)
+ return trusted_local_context()
def metadata_with_resource_user_context(
@@ -568,9 +512,14 @@ def _replace_policy_groups(
)
-def _policy_allows(context: ResourceUserContext, policy: Mapping[str, Any] | None, group_ids: Sequence[str]) -> bool:
- if context.is_trusted_local:
- return True
+def _policy_allows(
+ context: ResourceUserContext,
+ resource_kind: str,
+ policy: Mapping[str, Any] | None,
+ group_ids: Sequence[str],
+) -> bool:
+ if not context.can_use_resource(resource_kind):
+ return False
if policy is None:
# A legacy no-policy resource is local-private. The paired instance's
# owner retains legacy access, while remote organization members do not.
@@ -602,14 +551,17 @@ def _policy_allows(context: ResourceUserContext, policy: Mapping[str, Any] | Non
def _policy_allows_management(context: ResourceUserContext, policy: Mapping[str, Any] | None) -> bool:
if context.is_trusted_local:
return True
+ if not context.has_role("owner"):
+ return False
if policy is None:
- return context.is_instance_owner
+ return True
owner_user_id = _clean_optional_string(policy.get("owner_user_id"))
if owner_user_id and context.subject and owner_user_id == context.subject:
organization_id = _clean_optional_string(policy.get("organization_id"))
return bool(
not organization_id
- or context.is_active_organization_member and context.organization_id == organization_id
+ or context.is_active_organization_member
+ and context.organization_id == organization_id
)
return bool(
context.is_active_organization_member
@@ -627,10 +579,18 @@ def can_use_resource_policy_snapshot(
context = _as_context(user_context)
if policy is not None and not isinstance(policy, Mapping):
return False
+ resource_kind = policy.get("resource_kind") if policy is not None else None
+ if resource_kind not in RESOURCE_KINDS:
+ return context.is_trusted_local
group_ids = policy.get("group_ids") if policy is not None else []
if not isinstance(group_ids, (list, tuple, set, frozenset)):
return False
- return _policy_allows(context, policy, [str(group_id) for group_id in group_ids])
+ return _policy_allows(
+ context,
+ str(resource_kind),
+ policy,
+ [str(group_id) for group_id in group_ids],
+ )
def can_manage_resource_policy_snapshot(
@@ -657,7 +617,7 @@ def can_use_resource(
with _connection(connection) as conn:
policy = _policy_row(conn, kind, identifier)
groups = _policy_groups(conn, kind, identifier) if policy else []
- return _policy_allows(context, policy, groups)
+ return _policy_allows(context, kind, policy, groups)
def can_manage_resource_acl(
@@ -726,10 +686,42 @@ def filter_accessible_resources(
return [
row
for row, identifier in candidates
- if identifier is not None and _policy_allows(context, policies.get(identifier), groups.get(identifier, []))
+ if identifier is not None
+ and _policy_allows(context, kind, policies.get(identifier), groups.get(identifier, []))
]
+def resource_policy_narrowed(
+ previous: Mapping[str, Any] | None,
+ updated: Mapping[str, Any] | None,
+) -> bool:
+ """Return whether an applied policy removes any previously granted use."""
+
+ if not previous or not updated:
+ return False
+ previous_level = str(previous.get("access_level") or "")
+ updated_level = str(updated.get("access_level") or "")
+ if previous_level == "public":
+ return updated_level in {"scope", "private"}
+ if previous_level != "scope":
+ return False
+ if updated_level == "private":
+ return True
+ if updated_level != "scope":
+ return False
+ previous_groups = {
+ str(group_id)
+ for group_id in previous.get("group_ids") or []
+ if isinstance(group_id, str)
+ }
+ updated_groups = {
+ str(group_id)
+ for group_id in updated.get("group_ids") or []
+ if isinstance(group_id, str)
+ }
+ return not previous_groups.issubset(updated_groups)
+
+
def apply_control_plane_intent(
connection: Connection,
*,
diff --git a/storage/vault_service.py b/storage/vault_service.py
index 233269ab7..a1b2cee7e 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -1792,9 +1792,7 @@ def _require_secret_resource_management(conn: Connection, row: dict[str, Any], u
def require_secret_create_access(*, user_context: Any = None):
context = resolve_resource_access_context(user_context)
- if context.is_trusted_local or context.is_instance_owner:
- return context
- if context.is_remote and context.is_active_organization_member and context.subject:
+ if context.can_manage_instance:
return context
raise VaultSecretAccessError("Vault secret access is not permitted.")
@@ -4484,21 +4482,9 @@ def revoke_session_grants(
def resource_policy_narrowed(previous: dict[str, Any] | None, updated: dict[str, Any] | None) -> bool:
"""Whether a Vault ACL update removes access granted by the prior policy."""
- if not previous or not updated:
- return False
- previous_level = str(previous.get("access_level") or "")
- updated_level = str(updated.get("access_level") or "")
- if previous_level == "public":
- return updated_level in {"scope", "private"}
- if previous_level != "scope":
- return False
- if updated_level == "private":
- return True
- if updated_level != "scope":
- return False
- previous_groups = {str(group_id) for group_id in previous.get("group_ids") or [] if isinstance(group_id, str)}
- updated_groups = {str(group_id) for group_id in updated.get("group_ids") or [] if isinstance(group_id, str)}
- return not previous_groups.issubset(updated_groups)
+ from storage import resource_access_service
+
+ return resource_access_service.resource_policy_narrowed(previous, updated)
def revoke_active_grants_for_secret_resource(
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index 01ef5c5c0..8439cd96b 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -30,6 +30,31 @@ def test_role_capabilities_are_monotonic() -> None:
assert trusted_local_context().can_manage_instance is True
+ ("role", "expected"),
+ [
+ (
+ "viewer",
+ {"agent": False, "skill": False, "vault_secret": False, "show_page": True},
+ ),
+ (
+ "editor",
+ {"agent": True, "skill": True, "vault_secret": True, "show_page": True},
+ ),
+ (
+ "owner",
+ {"agent": True, "skill": True, "vault_secret": True, "show_page": True},
+ ),
+ ],
+)
+def test_resource_use_capability_is_distinct_from_owner_management(role, expected) -> None:
+ context = _remote_context(role)
+
+ assert {kind: context.can_use_resource(kind) for kind in expected} == expected
+ assert context.can_manage_instance is (role == "owner")
+ assert context.can_use_resource("future_resource") is False
+
+
def test_context_uses_role_not_diagnostic_source_for_owner() -> None:
context = context_from_session_payload(
{
@@ -60,6 +85,14 @@ def test_http_policy_defaults_unknown_api_to_owner() -> None:
assert required_instance_role("GET", "/api/projects/proj-1") == "viewer"
assert required_instance_role("GET", "/api/projects/proj-1/agents-md") == "owner"
assert required_instance_role("GET", "/api/agents") == "editor"
+ assert required_instance_role("GET", "/api/skills") == "editor"
+ assert required_instance_role("GET", "/api/vault/secrets") == "editor"
+ assert required_instance_role("GET", "/api/vault/tags") == "editor"
+ assert required_instance_role("POST", "/api/vault/requests/access") == "editor"
+ assert required_instance_role("POST", "/api/vault/requests/sign") == "editor"
+ assert required_instance_role("POST", "/api/vault/secrets") == "owner"
+ assert required_instance_role("POST", "/api/skills") == "owner"
+ assert required_instance_role("GET", "/api/show-pages") == "viewer"
assert required_instance_role("GET", "/api/config") == "viewer"
assert required_instance_role("GET", "/api/workbench/prefs") == "viewer"
assert required_instance_role("PUT", "/api/workbench/prefs") == "owner"
diff --git a/tests/test_remote_resource_acl_sync.py b/tests/test_remote_resource_acl_sync.py
index ba1559f68..d3cc8eede 100644
--- a/tests/test_remote_resource_acl_sync.py
+++ b/tests/test_remote_resource_acl_sync.py
@@ -265,6 +265,84 @@ def test_malformed_intent_keeps_empty_organization_queued_for_retry(monkeypatch)
assert resource_access_service.list_resource_organization_ids() == ["org-1"]
+def test_acl_narrowing_publishes_one_authorization_change_for_all_resource_caches(monkeypatch) -> None:
+ paths.ensure_data_dirs()
+ run_migrations()
+ engine = get_cached_sqlite_engine()
+ resource_ids = {
+ "agent": "agent-cache-revocation",
+ "skill": "skill-cache-revocation",
+ "vault_secret": "vault-cache-revocation",
+ "show_page": "show-cache-revocation",
+ }
+ with engine.begin() as connection:
+ for resource_kind, resource_id in resource_ids.items():
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind=resource_kind,
+ resource_id=resource_id,
+ organization_id="org-cache-revocation",
+ owner_user_id="owner-1",
+ access_level="public",
+ policy_revision=1,
+ last_applied_control_plane_revision=1,
+ )
+
+ monkeypatch.setattr(
+ remote_access,
+ "publish_resource_index",
+ lambda *_args, **_kwargs: {
+ "organization_id": "org-cache-revocation",
+ "resources": [],
+ },
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "pull_resource_acl_intents",
+ lambda *_args, **_kwargs: {
+ "organization_id": "org-cache-revocation",
+ "intents": [
+ {
+ "resource_kind": resource_kind,
+ "resource_id": resource_id,
+ "revision": 2,
+ "access_level": "private",
+ "group_ids": [],
+ }
+ for resource_kind, resource_id in resource_ids.items()
+ ],
+ },
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "acknowledge_resource_acl_intent",
+ lambda *_args, **_kwargs: {},
+ )
+ events: list[tuple[str, dict[str, Any]]] = []
+ monkeypatch.setattr(
+ "vibe.sse_broker.broker.publish",
+ lambda event_type, data: events.append((event_type, data)),
+ )
+
+ result = remote_access._sync_one_organization(
+ None,
+ organization_id="org-cache-revocation",
+ resources=[],
+ )
+
+ assert result["ok"] is True
+ assert result["applied"] == 4
+ assert events == [
+ (
+ "authorization.changed",
+ {
+ "project_ids": [],
+ "resource_kinds": ["agent", "show_page", "skill", "vault_secret"],
+ },
+ )
+ ]
+
+
def test_transient_apply_failure_leaves_intent_unacknowledged(monkeypatch) -> None:
_seed_policy()
config = _config()
diff --git a/tests/test_resource_access_service.py b/tests/test_resource_access_service.py
index 13b0d610b..a1faddb81 100644
--- a/tests/test_resource_access_service.py
+++ b/tests/test_resource_access_service.py
@@ -13,7 +13,7 @@ def _context(
organization_id: str | None = "org-1",
group_ids: frozenset[str] | None = frozenset(),
role: str | None = "member",
- instance_role: str = "viewer",
+ instance_role: str = "editor",
access_source: str = "organization_group",
) -> resource_access_service.ResourceUserContext:
return resource_access_service.ResourceUserContext(
@@ -136,6 +136,7 @@ def test_removed_org_owner_loses_org_private_resources_but_keeps_personal_resour
"owner-1",
organization_id=None,
role=None,
+ instance_role="owner",
access_source="email_invitation",
)
@@ -184,6 +185,18 @@ def test_request_context_resolution_failure_does_not_become_trusted_local(monkey
assert local_context.is_trusted_local is True
+def test_http_resource_services_reuse_the_parsed_authorization_context() -> None:
+ from vibe.ui_compat import g
+ from vibe.ui_server import app
+
+ context = _context("member-1")
+ with app.test_request_context("/api/agents", base_url="https://alex.avibe.bot"):
+ g.authorization_context = context
+
+ assert resource_access_service.current_resource_context() is context
+ assert resource_access_service.resolve_resource_access_context() is context
+
+
def test_deferred_remote_context_expires_at_authorization_refresh_boundary() -> None:
from vibe import remote_access
diff --git a/tests/test_resource_acl_agents.py b/tests/test_resource_acl_agents.py
index b40763452..9e4b4986f 100644
--- a/tests/test_resource_acl_agents.py
+++ b/tests/test_resource_acl_agents.py
@@ -23,6 +23,7 @@ def _organization_context(
subject: str,
*,
group_ids: frozenset[str] | None = frozenset({"group-engineering"}),
+ instance_role: str = "editor",
) -> resource_access_service.ResourceUserContext:
return resource_access_service.ResourceUserContext(
subject=subject,
@@ -31,7 +32,7 @@ def _organization_context(
organization_member_id=f"member-{subject}",
organization_role="member",
group_ids=group_ids,
- instance_role="viewer",
+ instance_role=instance_role,
instance_access_source="organization_group",
is_remote=True,
)
@@ -188,6 +189,29 @@ def test_remote_agent_creation_defaults_to_private_organization_policy(monkeypat
assert policy["access_level"] == "private"
+def test_agent_management_is_enforced_inside_the_store(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store, agents = _seed_agents_with_policies()
+ editor = _organization_context("member-1")
+ owner = _organization_context("owner-1", instance_role="owner")
+ try:
+ with pytest.raises(VibeAgentAccessError):
+ store.update(agents["public"].name, description="denied", user_context=editor)
+ with pytest.raises(VibeAgentAccessError):
+ store.remove(agents["public"].name, user_context=editor)
+ with pytest.raises(VibeAgentAccessError):
+ store.set_default_agent_name(agents["public"].name, user_context=editor)
+
+ updated = store.update(
+ agents["private"].name,
+ description="owner update",
+ user_context=owner,
+ )
+ assert updated.description == "owner update"
+ finally:
+ store.close()
+
+
def test_remote_partial_agent_updates_persist_canonical_selector_pair(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store, agents = _seed_agents_with_policies()
@@ -450,6 +474,12 @@ def test_remote_external_guest_cannot_create_agent(monkeypatch, tmp_path) -> Non
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = VibeAgentStore()
try:
+ with pytest.raises(VibeAgentAccessError):
+ store.create(
+ name="editor-agent",
+ backend="codex",
+ user_context=_organization_context("member-1"),
+ )
with pytest.raises(VibeAgentAccessError):
store.create(
name="guest-agent",
diff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.py
index c6c26a92f..30ea61e95 100644
--- a/tests/test_resource_acl_show_pages.py
+++ b/tests/test_resource_acl_show_pages.py
@@ -22,6 +22,7 @@ def _organization_context(
*,
group_ids: frozenset[str] | None = frozenset({"group-engineering"}),
organization_role: str = "member",
+ instance_role: str = "viewer",
) -> resource_access_service.ResourceUserContext:
return resource_access_service.ResourceUserContext(
subject=subject,
@@ -30,7 +31,7 @@ def _organization_context(
organization_member_id=f"member-{subject}",
organization_role=organization_role,
group_ids=group_ids,
- instance_role="viewer",
+ instance_role=instance_role,
instance_access_source="organization_group",
is_remote=True,
)
@@ -158,9 +159,14 @@ def test_remote_show_page_list_and_direct_requests_enforce_policy(monkeypatch, t
def test_remote_show_page_creation_defaults_private_and_org_public_does_not_share(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- owner_context = _organization_context("owner-1")
+ owner_context = _organization_context("owner-1", instance_role="owner")
store = ShowPageStore()
try:
+ with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
+ store.ensure(
+ "ses-editor-denied",
+ user_context=_organization_context("member-1", instance_role="editor"),
+ )
page = store.ensure("ses-org-public", user_context=owner_context)
with store.engine.begin() as connection:
policy = resource_access_service.get_resource_policy(
@@ -202,13 +208,14 @@ def test_show_page_scope_without_group_context_fails_closed(monkeypatch, tmp_pat
assert excinfo.value.code == "resource_access_forbidden"
-def test_remote_admin_can_manage_pages_without_use_access(monkeypatch, tmp_path) -> None:
+def test_remote_instance_owner_admin_can_manage_pages_without_use_access(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = _seed_show_pages_with_policies()
admin = _organization_context(
"admin-1",
group_ids=frozenset({"group-sales"}),
organization_role="admin",
+ instance_role="owner",
)
try:
with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
@@ -234,12 +241,13 @@ def test_remote_dock_filters_private_pins_and_authorizes_mutations(monkeypatch,
config = _save_config(tmp_path)
store = _seed_show_pages_with_policies()
store.close()
- owner = _organization_context("owner-1")
+ owner = _organization_context("owner-1", instance_role="owner")
member = _organization_context("member-1")
admin = _organization_context(
"admin-1",
group_ids=frozenset({"group-sales"}),
organization_role="admin",
+ instance_role="owner",
)
with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
api.pin_dock_show_page("ses-public", user_context=member)
@@ -284,8 +292,8 @@ def test_remote_admin_dock_order_preserves_hidden_private_pins(monkeypatch, tmp_
_save_config(tmp_path)
store = _seed_show_pages_with_policies()
store.close()
- owner = _organization_context("owner-1")
- admin = _organization_context("admin-1", organization_role="admin")
+ owner = _organization_context("owner-1", instance_role="owner")
+ admin = _organization_context("admin-1", organization_role="admin", instance_role="owner")
for session_id in ("ses-private", "ses-public", "ses-scope"):
api.pin_dock_show_page(session_id, user_context=owner)
@@ -311,7 +319,7 @@ def test_untrusted_dock_context_fails_closed(monkeypatch, tmp_path) -> None:
_save_config(tmp_path)
store = _seed_show_pages_with_policies()
store.close()
- owner = _organization_context("owner-1")
+ owner = _organization_context("owner-1", instance_role="owner")
api.pin_dock_show_page("ses-public", user_context=owner)
unresolved = resource_access_service.ResourceUserContext()
diff --git a/tests/test_resource_acl_vaults.py b/tests/test_resource_acl_vaults.py
index 2454f2c81..13c23ff30 100644
--- a/tests/test_resource_acl_vaults.py
+++ b/tests/test_resource_acl_vaults.py
@@ -25,7 +25,7 @@ def _context(
*,
group_ids: frozenset[str] | None = frozenset({"group-engineering"}),
role: str = "member",
- instance_role: str = "viewer",
+ instance_role: str = "editor",
) -> resource_access_service.ResourceUserContext:
return resource_access_service.ResourceUserContext(
subject=subject,
@@ -123,8 +123,37 @@ def test_vault_list_filters_acl_rows_without_returning_envelopes(vault) -> None:
assert "wrap_meta" not in serialized
+def test_editor_vault_use_keeps_protected_secret_behind_approval(vault) -> None:
+ editor = _context("member-1")
+ with vault.begin() as conn:
+ _create_secret(conn, "PROTECTED_USE", protection="protected")
+ _set_policy(conn, "PROTECTED_USE", access_level="public")
+
+ metadata_payload = vault_service.get_secret_meta(
+ conn,
+ "PROTECTED_USE",
+ user_context=editor,
+ )
+ access = vault_service.resolve_secret_access(
+ conn,
+ "PROTECTED_USE",
+ session_id="ses-editor",
+ user_context=editor,
+ )
+
+ assert metadata_payload["name"] == "PROTECTED_USE"
+ assert access["status"] == "approval_required"
+ assert access["request"]["status"] == "pending"
+ assert access.get("envelope") is None
+ assert access["request"]["card"]["value"] is None
+ serialized_metadata = json.dumps(metadata_payload)
+ assert "ciphertext-PROTECTED_USE" not in serialized_metadata
+ assert "nonce-PROTECTED_USE" not in serialized_metadata
+ assert "wrap-PROTECTED_USE" not in serialized_metadata
+
+
def test_inaccessible_vault_requests_and_grants_fail_before_mutating_state(vault) -> None:
- owner = _context("owner-1")
+ owner = _context("owner-1", instance_role="owner")
member = _context("member-1")
with vault.begin() as conn:
_create_secret(conn, "PRIVATE_ACCESS", protection="protected")
@@ -164,7 +193,7 @@ def test_inaccessible_vault_requests_and_grants_fail_before_mutating_state(vault
def test_vault_request_reads_and_denial_enforce_member_secret_acls(vault) -> None:
- owner = _context("owner-1")
+ owner = _context("owner-1", instance_role="owner")
member = _context("member-1")
with vault.begin() as conn:
_create_secret(conn, "PRIVATE_REQUEST", protection="protected")
@@ -235,7 +264,7 @@ def test_pending_provision_lookups_require_instance_owner(vault, monkeypatch) ->
def test_vault_request_limit_applies_after_acl_filtering(vault) -> None:
- owner = _context("owner-1")
+ owner = _context("owner-1", instance_role="owner")
member = _context("member-1")
with vault.begin() as conn:
_create_secret(conn, "VISIBLE_REQUEST", protection="protected")
@@ -251,8 +280,9 @@ def test_vault_request_limit_applies_after_acl_filtering(vault) -> None:
def test_vault_grant_reads_and_revocation_enforce_all_member_secret_acls(vault) -> None:
- owner = _context("owner-1")
+ owner = _context("owner-1", instance_role="owner")
member = _context("member-1")
+ member_owner = _context("member-1", instance_role="owner")
with vault.begin() as conn:
_create_secret(conn, "OWNER_GRANT", protection="protected")
_create_secret(conn, "MEMBER_GRANT", protection="protected")
@@ -269,7 +299,9 @@ def test_vault_grant_reads_and_revocation_enforce_all_member_secret_acls(vault)
owner_status = conn.execute(
select(vault_grants.c.status).where(vault_grants.c.id == owner_grant["id"])
).scalar_one()
- revoked = vault_service.revoke_grant(conn, member_grant["id"], user_context=member)
+ with pytest.raises(vault_service.VaultSecretAccessError):
+ vault_service.revoke_grant(conn, member_grant["id"], user_context=member)
+ revoked = vault_service.revoke_grant(conn, member_grant["id"], user_context=member_owner)
assert [grant["id"] for grant in visible] == [member_grant["id"]]
assert owner_status == "active"
@@ -277,7 +309,7 @@ def test_vault_grant_reads_and_revocation_enforce_all_member_secret_acls(vault)
def test_vault_audit_filters_secret_request_and_grant_metadata_before_limit(vault) -> None:
- owner = _context("owner-1")
+ owner = _context("owner-1", instance_role="owner")
member = _context("member-1")
with vault.begin() as conn:
_create_secret(conn, "OWNER_AUDIT", protection="protected")
@@ -303,8 +335,8 @@ def test_vault_audit_filters_secret_request_and_grant_metadata_before_limit(vaul
def test_deleted_secret_audit_history_uses_acl_tombstone_without_exposing_it(vault) -> None:
- owner = _context("member-1")
- admin = _context("admin-1", role="admin")
+ owner = _context("member-1", instance_role="owner")
+ admin = _context("admin-1", role="admin", instance_role="owner")
outsider = _context("member-2")
with vault.begin() as conn:
_create_secret(conn, "DELETED_AUDIT", protection="protected")
@@ -348,7 +380,7 @@ def test_remote_audit_uses_bounded_keyset_batches_until_limit_is_visible(vault,
def test_vault_api_grant_and_audit_endpoints_use_current_resource_context(vault, monkeypatch) -> None:
- owner = _context("owner-1")
+ owner = _context("owner-1", instance_role="owner")
member = _context("member-1")
with vault.begin() as conn:
_create_secret(conn, "API_OWNER", protection="protected")
@@ -411,7 +443,7 @@ def test_cli_selector_resolution_rejects_inaccessible_secrets(vault, selector: d
def test_remote_created_secret_registers_private_organization_policy(vault) -> None:
- creator = _context("member-1")
+ creator = _context("member-1", instance_role="owner")
with vault.begin() as conn:
_create_secret(conn, "REMOTE_CREATED", user_context=creator)
policy = resource_access_service.get_resource_policy(
@@ -436,7 +468,11 @@ def test_vault_secret_removal_deletes_resource_policy_and_groups(vault) -> None:
group_ids=["group-engineering"],
)
- vault_service.delete_secret(conn, "REMOVED_SECRET", user_context=_context("owner-1"))
+ vault_service.delete_secret(
+ conn,
+ "REMOVED_SECRET",
+ user_context=_context("owner-1", instance_role="owner"),
+ )
policies = conn.execute(
select(resource_access_policies).where(
resource_access_policies.c.resource_kind == "vault_secret",
@@ -482,7 +518,7 @@ def test_public_vault_use_does_not_grant_management(vault) -> None:
conn,
"PUBLIC_MANAGEMENT",
description="owner update",
- user_context=_context("owner-1"),
+ user_context=_context("owner-1", instance_role="owner"),
)
assert updated["description"] == "owner update"
@@ -497,6 +533,12 @@ def test_remote_external_guest_cannot_create_vault_secret(vault) -> None:
)
with vault.begin() as conn:
+ with pytest.raises(vault_service.VaultSecretAccessError):
+ _create_secret(
+ conn,
+ "EDITOR_CREATED",
+ user_context=_context("member-1"),
+ )
with pytest.raises(vault_service.VaultSecretAccessError):
_create_secret(conn, "GUEST_CREATED", user_context=guest)
assert conn.execute(select(vault_secrets).where(vault_secrets.c.name == "GUEST_CREATED")).first() is None
@@ -517,7 +559,7 @@ def test_narrowed_vault_policy_revokes_active_grants(
updated_level: str,
updated_groups: list[str],
) -> None:
- owner = _context("owner-1")
+ owner = _context("owner-1", instance_role="owner")
with vault.begin() as conn:
_create_secret(conn, "NARROWED_KEY", protection="protected")
resource_id = _set_policy(
@@ -569,7 +611,7 @@ def test_narrowed_vault_policy_revokes_active_grants(
def test_narrowed_vault_release_failure_stays_pending_until_retry_succeeds(vault, monkeypatch) -> None:
- owner = _context("owner-1")
+ owner = _context("owner-1", instance_role="owner")
with vault.begin() as conn:
_create_secret(conn, "RETRY_RELEASE_KEY", protection="protected")
resource_id = _set_policy(conn, "RETRY_RELEASE_KEY", access_level="public")
diff --git a/tests/test_skills_service.py b/tests/test_skills_service.py
index 00f832ba9..fe265fe7a 100644
--- a/tests/test_skills_service.py
+++ b/tests/test_skills_service.py
@@ -12,7 +12,7 @@ import asyncio
import os
import pytest
-from storage import resource_access_service
+from storage import project_access_service, projects_service, resource_access_service
from storage.db import create_sqlite_engine
from storage.models import metadata
@@ -50,7 +50,7 @@ def _organization_context(
*,
group_ids: frozenset[str] | None = frozenset({"group-engineering"}),
role: str = "member",
- instance_role: str = "viewer",
+ instance_role: str = "editor",
) -> resource_access_service.ResourceUserContext:
return resource_access_service.ResourceUserContext(
subject=subject,
@@ -321,7 +321,87 @@ def test_check_skills_filters_acl_rows_and_recomputes_summary(monkeypatch, tmp_p
assert missing_groups["summary"] == {"total": 1, "updateAvailable": 0, "upToDate": 1, "uncheckable": 0}
-def test_remote_skill_mutations_require_owner_or_organization_admin(monkeypatch, tmp_path) -> None:
+def test_project_skill_use_requires_editor_access_to_the_project(monkeypatch, tmp_path) -> None:
+ engine = _skills_engine(monkeypatch, tmp_path)
+ project_dir = tmp_path / "project"
+ project_dir.mkdir()
+ listing = {
+ "ok": True,
+ "skills": [
+ {
+ **_skill_row("project-skill"),
+ "scope": "project",
+ "path": str(project_dir / ".agents" / "skills" / "project-skill"),
+ }
+ ],
+ }
+ try:
+ with engine.begin() as connection:
+ project = projects_service.create_project(connection, str(project_dir))
+ result = project_access_service.apply_project_access_intent(
+ connection,
+ {
+ "project_id": project["id"],
+ "revision": 1,
+ "mode": "restricted",
+ "organization_id": "org-1",
+ "bindings": [
+ {
+ "principal_kind": "organization_group",
+ "principal_value": "group-engineering",
+ "access_role": "editor",
+ }
+ ],
+ },
+ )
+ assert result.outcome == "applied"
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind="skill",
+ resource_id=skills.skill_resource_id(
+ "codex",
+ scope="project",
+ project_dir=str(project_dir),
+ name="project-skill",
+ ),
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="scope",
+ group_ids=["group-engineering"],
+ )
+
+ allowed_recorder = _Recorder(listing)
+ monkeypatch.setattr(skills, "_run_askill", allowed_recorder)
+ allowed = _run(
+ skills.list_skills(
+ "askill",
+ scope="project",
+ project_dir=str(project_dir),
+ user_context=_organization_context("member-1"),
+ )
+ )
+ assert [item["name"] for item in allowed["skills"]] == ["project-skill"]
+
+ denied_recorder = _Recorder(listing)
+ monkeypatch.setattr(skills, "_run_askill", denied_recorder)
+ with pytest.raises(skills.SkillAccessError):
+ _run(
+ skills.list_skills(
+ "askill",
+ scope="project",
+ project_dir=str(project_dir),
+ user_context=_organization_context(
+ "member-2",
+ group_ids=frozenset({"group-sales"}),
+ ),
+ )
+ )
+ assert denied_recorder.calls == []
+ finally:
+ engine.dispose()
+
+
+def test_remote_skill_mutations_require_instance_owner_and_resource_management(monkeypatch, tmp_path) -> None:
engine = _skills_engine(monkeypatch, tmp_path)
listing = {"ok": True, "skills": [_skill_row("private-skill")]}
try:
@@ -340,7 +420,20 @@ def test_remote_skill_mutations_require_owner_or_organization_admin(monkeypatch,
)
)
assert member_error.value.code == "resource_access_forbidden"
- assert [call["args"] for call in member_recorder.calls] == [["list", "-g"]]
+ assert member_recorder.calls == []
+
+ admin_editor_recorder = _SequenceRecorder([listing])
+ monkeypatch.setattr(skills, "_run_askill", admin_editor_recorder)
+ with pytest.raises(skills.SkillAccessError):
+ _run(
+ skills.update(
+ "askill",
+ "private-skill",
+ scope="global",
+ user_context=_organization_context("member-2", role="admin"),
+ )
+ )
+ assert admin_editor_recorder.calls == []
owner_recorder = _SequenceRecorder([listing, {"ok": True}])
monkeypatch.setattr(skills, "_run_askill", owner_recorder)
@@ -349,7 +442,7 @@ def test_remote_skill_mutations_require_owner_or_organization_admin(monkeypatch,
"askill",
"private-skill",
scope="global",
- user_context=_organization_context("owner-1"),
+ user_context=_organization_context("owner-1", instance_role="owner"),
)
) == {"ok": True}
assert [call["args"] for call in owner_recorder.calls] == [["list", "-g"], ["remove", "private-skill", "-g"]]
@@ -370,7 +463,7 @@ def test_remote_skill_mutations_require_owner_or_organization_admin(monkeypatch,
"askill",
"private-skill",
scope="global",
- user_context=_organization_context("member-2", role="admin"),
+ user_context=_organization_context("member-2", role="admin", instance_role="owner"),
)
) == {"ok": True}
assert [call["args"] for call in admin_recorder.calls] == [["list", "-g"], ["update", "private-skill", "-g", "-y"]]
@@ -434,7 +527,7 @@ def test_remove_skill_deletes_only_policies_for_removed_backends(monkeypatch, tm
"shared-skill",
scope="global",
backends=["codex", "claude"],
- user_context=_organization_context("owner-1"),
+ user_context=_organization_context("owner-1", instance_role="owner"),
)
)
with engine.connect() as connection:
@@ -472,14 +565,14 @@ def test_remote_skill_mutations_fail_closed_when_preflight_cannot_resolve_target
"askill",
"missing-skill",
scope="global",
- user_context=_organization_context("owner-1"),
+ user_context=_organization_context("owner-1", instance_role="owner"),
)
else:
mutation = skills.update(
"askill",
"missing-skill",
scope="global",
- user_context=_organization_context("owner-1"),
+ user_context=_organization_context("owner-1", instance_role="owner"),
)
with pytest.raises(skills.SkillAccessError):
_run(mutation)
@@ -513,7 +606,7 @@ def test_remote_skill_add_registers_private_policy(monkeypatch, tmp_path) -> Non
scope="global",
skill="new-skill",
backends=["codex"],
- user_context=_organization_context("member-1"),
+ user_context=_organization_context("member-1", instance_role="owner"),
)
)
with engine.connect() as connection:
@@ -575,7 +668,7 @@ def test_remote_skill_add_requires_instance_owner_for_installed_legacy_skill(mon
finally:
engine.dispose()
- assert [call["args"] for call in member_recorder.calls] == [["list", "-g", "-a", "codex"]]
+ assert member_recorder.calls == []
assert [call["args"] for call in owner_recorder.calls] == [
["list", "-g", "-a", "codex"],
["add", "gh:owner/repo", "-g", "-a", "codex", "--skill", "legacy-skill", "-y"],
@@ -603,7 +696,7 @@ def test_remote_skill_add_fails_closed_for_unresolved_installed_backend(monkeypa
scope="global",
skill="legacy-skill",
backends=["codex"],
- user_context=_organization_context("member-1"),
+ user_context=_organization_context("member-1", instance_role="owner"),
)
)
finally:
@@ -612,6 +705,27 @@ def test_remote_skill_add_fails_closed_for_unresolved_installed_backend(monkeypa
assert [call["args"] for call in recorder.calls] == [["list", "-g", "-a", "codex"]]
+def test_skill_zip_upload_rejects_editor_before_filesystem_work(monkeypatch) -> None:
+ import tempfile
+
+ from vibe import api
+ from vibe.authorization import InstanceAuthorizationError
+
+ monkeypatch.setattr(
+ tempfile,
+ "gettempdir",
+ lambda: pytest.fail("upload touched the filesystem before authorization"),
+ )
+
+ with pytest.raises(InstanceAuthorizationError):
+ _run(
+ api.upload_skill_zip(
+ {},
+ user_context=_organization_context("member-1"),
+ )
+ )
+
+
def test_invalid_backend_raises(monkeypatch):
monkeypatch.setattr(skills, "_run_askill", _Recorder({"ok": True}))
with pytest.raises(skills.SkillsError) as info:
diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.py
index ef2db3627..645195dc7 100644
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@ -801,6 +801,10 @@ def test_remote_session_info_includes_authenticated_subject(monkeypatch, tmp_pat
"can_manage_projects": True,
"can_manage_agents": True,
"can_manage_instance": True,
+ "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,
@@ -840,11 +844,19 @@ def test_remote_viewer_can_read_but_cannot_use_management_api(monkeypatch, tmp_p
@pytest.mark.parametrize(
- ("role", "agents_status", "conversation_status", "project_status"),
+ (
+ "role",
+ "agents_status",
+ "skills_status",
+ "vault_status",
+ "show_pages_status",
+ "conversation_status",
+ "project_status",
+ ),
[
- ("viewer", 403, 403, 403),
- ("editor", 200, 400, 403),
- ("owner", 200, 400, 400),
+ ("viewer", 403, 403, 403, 200, 403, 403),
+ ("editor", 200, 200, 200, 200, 400, 403),
+ ("owner", 200, 200, 200, 200, 400, 400),
],
)
def test_remote_instance_role_route_matrix(
@@ -852,6 +864,9 @@ def test_remote_instance_role_route_matrix(
tmp_path,
role,
agents_status,
+ skills_status,
+ vault_status,
+ show_pages_status,
conversation_status,
project_status,
):
@@ -870,6 +885,9 @@ def test_remote_instance_role_route_matrix(
read_response = client.get("/api/projects", base_url="https://alex.avibe.bot")
agents_response = client.get("/api/agents", base_url="https://alex.avibe.bot")
+ skills_response = client.get("/api/skills", base_url="https://alex.avibe.bot")
+ vault_response = client.get("/api/vault/secrets", base_url="https://alex.avibe.bot")
+ show_pages_response = client.get("/api/show-pages", base_url="https://alex.avibe.bot")
config_response = client.get("/api/config", base_url="https://alex.avibe.bot")
prefs_read_response = client.get("/api/workbench/prefs", base_url="https://alex.avibe.bot")
prefs_write_response = client.put(
@@ -893,6 +911,9 @@ def test_remote_instance_role_route_matrix(
assert read_response.status_code == 200
assert agents_response.status_code == agents_status
+ assert skills_response.status_code == skills_status
+ assert vault_response.status_code == vault_status
+ assert show_pages_response.status_code == show_pages_status
assert config_response.status_code == 200
assert prefs_read_response.status_code == 200
assert prefs_read_response.get_json()["background_work_banner_enabled"] is True
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index f5e29237d..823098a8c 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -2541,9 +2541,22 @@ def test_private_show_events_stream_ends_when_project_access_is_revoked(monkeypa
_create_show_page("ses123", "private")
context = AuthorizationContext(
instance_role="editor",
+ subject="remote-editor",
+ instance_access_source="email",
is_remote=True,
)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ resource_access_service.ensure_resource_policy(
+ conn,
+ resource_kind="show_page",
+ resource_id="ses123",
+ organization_id=None,
+ owner_user_id="remote-editor",
+ access_level="private",
+ )
+ engine.dispose()
async def _collect_until_revoked() -> list[str | bytes]:
response = await _show_events_stream(
@@ -2575,6 +2588,72 @@ def test_private_show_events_stream_ends_when_project_access_is_revoked(monkeypa
assert len(asyncio.run(_collect_until_revoked())) == 1
+def test_private_show_events_stream_ends_when_resource_access_is_revoked(monkeypatch, tmp_path):
+ from storage.db import create_sqlite_engine
+ from vibe.authorization import AuthorizationContext
+ from vibe.sse_broker import broker
+ from vibe.ui_server import _show_events_stream
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ context = AuthorizationContext(
+ instance_role="editor",
+ subject="remote-editor",
+ organization_id="org-1",
+ organization_member_id="member-remote-editor",
+ organization_role="member",
+ group_ids=frozenset({"group-engineering"}),
+ instance_access_source="organization_group",
+ is_remote=True,
+ )
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ resource_access_service.ensure_resource_policy(
+ conn,
+ resource_kind="show_page",
+ resource_id="ses123",
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="public",
+ )
+ engine.dispose()
+
+ async def _collect_until_revoked() -> list[str | bytes]:
+ response = await _show_events_stream(
+ "ses123",
+ authorization_context=context,
+ )
+ iterator = response.body_iterator.__aiter__()
+ try:
+ chunks = [await iterator.__anext__()]
+ revoke_engine = create_sqlite_engine()
+ with revoke_engine.begin() as conn:
+ resource_access_service.apply_control_plane_intent(
+ conn,
+ organization_id="org-1",
+ resource_kind="show_page",
+ resource_id="ses123",
+ revision=1,
+ access_level="private",
+ group_ids=[],
+ )
+ revoke_engine.dispose()
+ broker.publish(
+ "authorization.changed",
+ {"project_ids": [], "resource_kinds": ["show_page"]},
+ )
+ with pytest.raises(StopAsyncIteration):
+ await asyncio.wait_for(iterator.__anext__(), timeout=1)
+ finally:
+ await iterator.aclose()
+ return chunks
+
+ assert len(asyncio.run(_collect_until_revoked())) == 1
+
+
def test_public_show_events_stream_redacts_nested_dispatch_ids(monkeypatch, tmp_path):
from vibe.sse_broker import broker
from vibe.ui_server import _show_events_stream
@@ -4889,8 +4968,7 @@ def test_private_show_page_hmr_websocket_closes_at_authorization_refresh_deadlin
assert proxy_calls == [("started", "ses123"), ("cancelled", "ses123")]
-def test_private_show_page_hmr_websocket_closes_when_project_access_is_revoked(monkeypatch, tmp_path):
- from storage import project_access_service
+def test_private_show_page_hmr_websocket_closes_when_resource_access_is_revoked(monkeypatch, tmp_path):
from storage.db import create_sqlite_engine
from vibe.sse_broker import broker
@@ -4926,9 +5004,9 @@ def test_private_show_page_hmr_websocket_closes_when_project_access_is_revoked(m
conn,
resource_kind="show_page",
resource_id="ses123",
- organization_id=None,
- owner_user_id="remote-editor",
- access_level="private",
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="public",
)
engine.dispose()
monkeypatch.setattr(ui_server, "_show_runtime_hmr_origin_allowed", lambda websocket: True)
@@ -4940,7 +5018,11 @@ def test_private_show_page_hmr_websocket_closes_when_project_access_is_revoked(m
"sub": "remote-editor",
"email": "[email protected]",
"vibe_instance_role": "editor",
- "vibe_instance_access_source": "email",
+ "vibe_instance_access_source": "organization_group",
+ "vibe_organization_id": "org-1",
+ "vibe_organization_member_id": "member-remote-editor",
+ "vibe_organization_role": "member",
+ "vibe_group_ids": ["group-engineering"],
},
)
monkeypatch.setattr(
@@ -4949,8 +5031,12 @@ def test_private_show_page_hmr_websocket_closes_when_project_access_is_revoked(m
lambda websocket: resource_access_service.ResourceUserContext(
subject="remote-editor",
+ organization_id="org-1",
+ organization_member_id="member-remote-editor",
+ organization_role="member",
+ group_ids=frozenset({"group-engineering"}),
instance_role="editor",
- instance_access_source="email",
+ instance_access_source="organization_group",
is_remote=True,
),
)
@@ -4962,18 +5048,21 @@ def test_private_show_page_hmr_websocket_closes_when_project_access_is_revoked(m
await asyncio.wait_for(proxy_started.wait(), timeout=1)
revoke_engine = create_sqlite_engine()
with revoke_engine.begin() as conn:
- result = project_access_service.apply_project_access_intent(
+ result = resource_access_service.apply_control_plane_intent(
conn,
- {
- "project_id": "proj_show",
- "revision": 1,
- "mode": "restricted",
- "bindings": [],
- },
+ organization_id="org-1",
+ resource_kind="show_page",
+ resource_id="ses123",
+ revision=1,
+ access_level="private",
+ group_ids=[],
)
revoke_engine.dispose()
- assert result.changed is True
- broker.publish("authorization.changed", {"project_ids": ["proj_show"]})
+ assert result["status"] == "applied"
+ broker.publish(
+ "authorization.changed",
+ {"project_ids": [], "resource_kinds": ["show_page"]},
+ )
await asyncio.wait_for(task, timeout=1)
asyncio.run(_run_until_revoked())
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 8df242940..2df581165 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -284,14 +284,18 @@ export const AppShell: React.FC = () => {
const ownerOnlyPath =
location.pathname === '/setup' ||
location.pathname.startsWith('/admin') ||
- ['/agents', '/skills', '/harness', '/vaults', '/apps/library'].some(
+ ['/agents', '/harness', '/apps/library'].some(
(path) => location.pathname === path || location.pathname.startsWith(`${path}/`),
);
+ const resourceUseDenied =
+ (location.pathname.startsWith('/skills') && !capabilities.can_use_skills) ||
+ (location.pathname.startsWith('/vaults') && !capabilities.can_use_vault_secrets);
const fileOnlyPath =
location.pathname.startsWith('/apps/files') || location.pathname.startsWith('/apps/editor');
const terminalOnlyPath = location.pathname.startsWith('/apps/terminal');
if (
(ownerOnlyPath && !capabilities.can_manage_instance) ||
+ resourceUseDenied ||
(fileOnlyPath && !capabilities.can_use_files) ||
(terminalOnlyPath && !capabilities.can_use_terminal)
) {
@@ -407,8 +411,8 @@ export const AppShell: React.FC = () => {
const workbenchTabs: ShellNavItem[] = [
{ to: '/inbox', label: t('nav.inbox'), icon: Inbox, badge: totalUnread },
{ to: '/projects', label: t('nav.projects'), icon: FolderTree },
- ...(capabilities.can_manage_agents ? [{
- to: '/agents',
+ ...(capabilities.can_manage_agents || capabilities.can_use_skills || capabilities.can_use_vault_secrets ? [{
+ to: capabilities.can_manage_agents ? '/agents' : capabilities.can_use_skills ? '/skills' : '/vaults',
label: t('nav.capabilities'),
icon: LayoutGrid,
match: (p: string) => ['/agents', '/skills', '/harness', '/vaults'].some((x) => p.startsWith(x)),
diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsx
index d63afc672..e9beeef54 100644
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@ -163,8 +163,9 @@ export const AgentsPage: React.FC = () => {
onTurnStart: () => fetchRunningActiveCount(),
onTurnEnd: () => fetchRunningActiveCount(),
onSessionStatus: () => fetchRunningActiveCount(),
+ onAuthorizationChanged: () => void refresh(),
});
- }, [api, fetchRunningActiveCount]);
+ }, [api, fetchRunningActiveCount, refresh]);
useEffect(() => {
// Reconcile the badge even while SSE is connected: process death / orphan /
diff --git a/ui/src/components/workbench/CapabilityTabs.tsx b/ui/src/components/workbench/CapabilityTabs.tsx
index 99f223aa9..772b33221 100644
--- a/ui/src/components/workbench/CapabilityTabs.tsx
+++ b/ui/src/components/workbench/CapabilityTabs.tsx
@@ -3,6 +3,7 @@ import { NavLink, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Activity, Bot, KeyRound, WandSparkles } from 'lucide-react';
import clsx from 'clsx';
+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
const TABS = [
{ to: '/agents', icon: Bot, key: 'workbench.modules.agents.title' },
@@ -19,6 +20,13 @@ export const CapabilityTabs: React.FC = () => {
const { t } = useTranslation();
const { pathname } = useLocation();
const activeTabRef = useRef<HTMLAnchorElement | null>(null);
+ const { capabilities } = useInstanceAuthorization();
+ const tabs = TABS.filter(({ to }) => {
+ if (to === '/agents' || to === '/harness') return capabilities.can_manage_agents;
+ if (to === '/skills') return capabilities.can_use_skills;
+ if (to === '/vaults') return capabilities.can_use_vault_secrets;
+ return false;
+ });
useEffect(() => {
activeTabRef.current?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
@@ -26,7 +34,7 @@ export const CapabilityTabs: React.FC = () => {
return (
<div className="-mx-4 flex gap-2 overflow-x-auto px-4 pb-0.5 md:hidden">
- {TABS.map(({ to, icon: Icon, key }) => {
+ {tabs.map(({ to, icon: Icon, key }) => {
const active = pathname.startsWith(to);
return (
<NavLink
diff --git a/ui/src/components/workbench/SkillsPage.tsx b/ui/src/components/workbench/SkillsPage.tsx
index dc20dd20d..f3dfc7aec 100644
--- a/ui/src/components/workbench/SkillsPage.tsx
+++ b/ui/src/components/workbench/SkillsPage.tsx
@@ -17,6 +17,7 @@ import { SkillDetailPanel } from './skills/SkillDetailPanel';
import { ProjectPicker } from './skills/ProjectPicker';
import { AddSkillDialog } from './skills/AddSkillDialog';
import { BrowseRegistryDialog } from './skills/BrowseRegistryDialog';
+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
const skillKey = (s: SkillBrief) => `${s.scope}:${s.name}`;
@@ -24,6 +25,8 @@ export const SkillsPage: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
+ const { capabilities } = useInstanceAuthorization();
+ const canManage = capabilities.can_manage_instance;
const [scope, setScope] = useState<SkillScope>('global');
const [projects, setProjects] = useState<WorkbenchProject[]>([]);
@@ -103,10 +106,12 @@ export const SkillsPage: React.FC = () => {
refresh();
}, [refresh]);
+ useEffect(() => api.connectWorkbenchEvents({ onAuthorizationChanged: () => refresh() }), [api, refresh]);
+
// Fetch update status (askill check) once the list loads so rows can show an
// "update available" badge. Best-effort; failures just clear it.
useEffect(() => {
- if (notInstalled || (scope === 'project' && !projectId)) {
+ if (!canManage || notInstalled || (scope === 'project' && !projectId)) {
setCheckMap({});
return;
}
@@ -133,7 +138,7 @@ export const SkillsPage: React.FC = () => {
return () => {
cancelled = true;
};
- }, [api, scope, projectId, skills, notInstalled]);
+ }, [api, scope, projectId, skills, notInstalled, canManage]);
const matches = useCallback(
(skill: SkillBrief) => {
@@ -278,14 +283,14 @@ export const SkillsPage: React.FC = () => {
<BackendFilter value={backendFilter} onChange={setBackendFilter} />
- <Button type="button" variant="outline" size="xs" onClick={() => setShowBrowse(true)}>
+ {canManage ? <Button type="button" variant="outline" size="xs" onClick={() => setShowBrowse(true)}>
<Compass className="size-3.5 text-cyan" />
{t('skills.browseRegistry')}
- </Button>
- <Button type="button" variant="brand" size="xs" onClick={() => setShowAdd(true)}>
+ </Button> : null}
+ {canManage ? <Button type="button" variant="brand" size="xs" onClick={() => setShowAdd(true)}>
<Plus />
{t('skills.addSkill')}
- </Button>
+ </Button> : null}
</div>
{scope === 'project' && activeProject?.folder_path ? (
@@ -306,7 +311,7 @@ export const SkillsPage: React.FC = () => {
<Terminal className="size-7 text-muted" />
<div className="text-[14px] font-semibold text-foreground">{t('skills.notInstalled')}</div>
<div className="max-w-md font-mono text-[11.5px] text-muted">{t('skills.notInstalledHint')}</div>
- <Button
+ {canManage ? <Button
variant="brand"
size="sm"
className="mt-1"
@@ -330,7 +335,7 @@ export const SkillsPage: React.FC = () => {
>
{installingAskill ? <Loader2 className="size-3.5 animate-spin" /> : <Download className="size-3.5" />}
{installingAskill ? t('skills.installing') : t('skills.installAskill')}
- </Button>
+ </Button> : null}
</div>
) : (
// `minmax(0,1fr)` (not bare `1fr`) lets the list column shrink below its
@@ -393,12 +398,13 @@ export const SkillsPage: React.FC = () => {
onToggleBackend={onToggleBackend}
onUpdate={onUpdate}
onRemove={onRemove}
+ canManage={canManage}
/>
) : null}
</div>
)}
- {showAdd ? (
+ {canManage && showAdd ? (
<AddSkillDialog
defaultScope={scope}
projectId={addDialogProjectId}
@@ -407,7 +413,7 @@ export const SkillsPage: React.FC = () => {
onInstalled={afterDialog}
/>
) : null}
- {showBrowse ? (
+ {canManage && showBrowse ? (
<BrowseRegistryDialog
scope={browseScope}
projectId={browseProjectId}
diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsx
index 4fa537991..23000ae87 100644
--- a/ui/src/components/workbench/VaultsPage.tsx
+++ b/ui/src/components/workbench/VaultsPage.tsx
@@ -22,6 +22,7 @@ import { VaultSecretDialog } from '../ui/vault-secret-dialog';
import { VaultSettingsDialog } from '../ui/vault-settings-dialog';
import { useProtectedVault } from '../../lib/useProtectedVault';
import { useVaultRequestRefresh } from '../../lib/useVaultRequestRefresh';
+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
const PENDING_REQUEST_EXPIRY_GRACE_MS = 100;
const MAX_BROWSER_TIMEOUT_MS = 2_147_483_647;
@@ -38,7 +39,8 @@ const SecretRow: React.FC<{
onEdit: (secret: VaultSecret) => void;
onDelete: (secret: VaultSecret) => void;
onReveal: (secret: VaultSecret) => void;
-}> = ({ secret: s, onEdit, onDelete, onReveal }) => {
+ canManage: boolean;
+}> = ({ secret: s, onEdit, onDelete, onReveal, canManage }) => {
const { t } = useTranslation();
const [menuOpen, setMenuOpen] = useState(false);
const isKeypair = s.kind === 'keypair';
@@ -95,7 +97,7 @@ const SecretRow: React.FC<{
</span>
{isKeypair && s.signing_addresses ? <SigningAddressList addresses={s.signing_addresses} className="mt-1" /> : null}
</div>
- <div className="ml-auto">
+ {canManage ? <div className="ml-auto">
<Popover open={menuOpen} onOpenChange={setMenuOpen}>
<PopoverTrigger asChild>
<Button variant="ghost" size="icon" aria-label={t('vaults.rowActions')} aria-haspopup="menu">
@@ -161,7 +163,7 @@ const SecretRow: React.FC<{
</button>
</PopoverContent>
</Popover>
- </div>
+ </div> : null}
</div>
);
};
@@ -479,6 +481,8 @@ export const VaultsPage: React.FC = () => {
const api = useApi();
const { showToast } = useToast();
const vault = useProtectedVault();
+ const { capabilities } = useInstanceAuthorization();
+ const canManage = capabilities.can_manage_instance;
const [searchParams, setSearchParams] = useSearchParams();
const [secrets, setSecrets] = useState<VaultSecret[]>([]);
const [grants, setGrants] = useState<VaultGrant[]>([]);
@@ -516,6 +520,10 @@ export const VaultsPage: React.FC = () => {
} finally {
setLoading(false);
}
+ if (!canManage) {
+ setGrants([]);
+ return;
+ }
// Active grants are a best-effort control strip; a grants failure (e.g. an
// older backend without the route) must neither blank out the secret
// inventory nor surface an error toast, so suppress error handling here.
@@ -525,7 +533,7 @@ export const VaultsPage: React.FC = () => {
} catch {
setGrants([]);
}
- }, [api]);
+ }, [api, canManage]);
useEffect(() => {
refresh();
@@ -545,6 +553,7 @@ export const VaultsPage: React.FC = () => {
},
onError: () => setEventBridgeConnected(false),
onVaultsUpdated: () => refresh(),
+ onAuthorizationChanged: () => refresh(),
});
}, [api, refresh]);
@@ -721,8 +730,8 @@ export const VaultsPage: React.FC = () => {
stackActionsOnMobile
actions={
<>
- <VaultLockIndicator className="max-sm:order-last max-sm:w-full max-sm:justify-between" />
- <Button
+ {canManage ? <VaultLockIndicator className="max-sm:order-last max-sm:w-full max-sm:justify-between" /> : null}
+ {canManage ? <Button
variant={showAudit ? 'secondary' : 'ghost'}
size="icon"
className="max-sm:border max-sm:border-border max-sm:bg-surface"
@@ -730,8 +739,8 @@ export const VaultsPage: React.FC = () => {
aria-label={t('vaults.history')}
>
<History className="size-4" />
- </Button>
- <Button
+ </Button> : null}
+ {canManage ? <Button
variant={showSettings ? 'secondary' : 'ghost'}
size="icon"
className="max-sm:border max-sm:border-border max-sm:bg-surface"
@@ -739,7 +748,7 @@ export const VaultsPage: React.FC = () => {
aria-label={t('vaults.settings.title')}
>
<Settings className="size-4" />
- </Button>
+ </Button> : null}
<Button
variant="ghost"
size="icon"
@@ -749,18 +758,18 @@ export const VaultsPage: React.FC = () => {
>
<RefreshCw className="size-4" />
</Button>
- <Button className="max-sm:flex-1" onClick={() => setAdding(true)}>
+ {canManage ? <Button className="max-sm:flex-1" onClick={() => setAdding(true)}>
<Plus className="size-4" />
{t('vaults.add')}
- </Button>
+ </Button> : null}
</>
}
/>
{error && (
<div className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">{error}</div>
)}
- <PendingRequestsSection onResolved={refresh} focusRequestId={focusRequestId} onFocusRequestOpened={clearFocusedRequest} />
- {grants.length > 0 && (
+ {canManage ? <PendingRequestsSection onResolved={refresh} focusRequestId={focusRequestId} onFocusRequestOpened={clearFocusedRequest} /> : null}
+ {canManage && grants.length > 0 && (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2 px-1">
<ShieldCheck className="size-4 text-mint" />
@@ -819,11 +828,18 @@ export const VaultsPage: React.FC = () => {
) : (
<div className="flex flex-col gap-2">
{visibleSecrets.map((s) => (
- <SecretRow key={s.name} secret={s} onEdit={onEdit} onDelete={onDelete} onReveal={revealSecret} />
+ <SecretRow
+ key={s.name}
+ secret={s}
+ onEdit={onEdit}
+ onDelete={onDelete}
+ onReveal={revealSecret}
+ canManage={canManage}
+ />
))}
</div>
)}
- {showAudit && (
+ {canManage && showAudit && (
<div className="rounded-2xl border border-border bg-surface p-4">
<div className="mb-2 text-sm font-semibold">{t('vaults.audit.title')}</div>
{audit.length === 0 ? (
@@ -841,8 +857,8 @@ export const VaultsPage: React.FC = () => {
)}
</div>
)}
- <VaultSettingsDialog open={showSettings} onOpenChange={setShowSettings} />
- <VaultSecretDialog
+ {canManage ? <VaultSettingsDialog open={showSettings} onOpenChange={setShowSettings} /> : null}
+ {canManage ? <VaultSecretDialog
open={adding}
onOpenChange={(o) => {
if (!o) setAdding(false);
@@ -853,8 +869,8 @@ export const VaultsPage: React.FC = () => {
showToast(t('vaults.created', { name }), 'success');
refresh();
}}
- />
- <VaultSecretDialog
+ /> : null}
+ {canManage ? <VaultSecretDialog
open={editTarget != null}
editSecret={editTarget}
onOpenChange={(o) => {
@@ -867,7 +883,7 @@ export const VaultsPage: React.FC = () => {
showToast(t('vaults.saved', { name }), 'success');
refresh();
}}
- />
+ /> : null}
<ConfirmDialog
open={deleteTarget != null}
onOpenChange={(open) => {
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index 694464e74..14b7968e3 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -769,6 +769,12 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
const navigate = useNavigate();
const authorizeRouteAction = useUnsavedChangesActionGuard();
const { capabilities } = useInstanceAuthorization();
+ const capabilityNav = CAPABILITY_NAV.filter(({ to }) => {
+ if (to === '/agents' || to === '/harness') return capabilities.can_manage_agents;
+ if (to === '/skills') return capabilities.can_use_skills;
+ if (to === '/vaults') return capabilities.can_use_vault_secrets;
+ return false;
+ });
const { totalUnread, unreadSessions, inboxSessions, markRead, unreadBySession } = useWorkbenchInbox();
// Projects/sessions tree — shared with the mobile ProjectsPage via the provider
// (one EventSource + one cache, not a per-component reimplementation). The
@@ -909,7 +915,7 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
/>
</Popover>
- {capabilities.can_manage_agents && <div className="flex flex-col gap-1.5">
+ {capabilityNav.length > 0 && <div className="flex flex-col gap-1.5">
<button
type="button"
onClick={toggleCaps}
@@ -921,7 +927,7 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
</button>
{!capsCollapsed && (
<nav className="flex flex-col gap-0.5">
- {CAPABILITY_NAV.map(({ to, i18nKey, icon: Icon }) => (
+ {capabilityNav.map(({ to, i18nKey, icon: Icon }) => (
<NavLink
key={to}
to={to}
diff --git a/ui/src/components/workbench/skills/SkillDetailPanel.tsx b/ui/src/components/workbench/skills/SkillDetailPanel.tsx
index 9a31c7814..278ea9d78 100644
--- a/ui/src/components/workbench/skills/SkillDetailPanel.tsx
+++ b/ui/src/components/workbench/skills/SkillDetailPanel.tsx
@@ -19,6 +19,7 @@ export interface SkillDetailPanelProps {
onToggleBackend: (backend: Backend, next: boolean) => void;
onUpdate?: () => void;
onRemove: () => void;
+ canManage?: boolean;
}
function Eyebrow({ children }: { children: ReactNode }) {
@@ -42,6 +43,7 @@ export function SkillDetailPanel({
onToggleBackend,
onUpdate,
onRemove,
+ canManage = true,
}: SkillDetailPanelProps) {
const { t } = useTranslation();
const linked = new Set(backendsFromAgents(skill.agents));
@@ -97,7 +99,12 @@ export function SkillDetailPanel({
{busy ? (
<Loader2 className="size-3.5 animate-spin text-muted" />
) : (
- <Switch checked={on} onCheckedChange={(next) => onToggleBackend(backend, next)} label={BACKEND_LABEL[backend]} />
+ <Switch
+ checked={on}
+ disabled={!canManage}
+ onCheckedChange={(next) => onToggleBackend(backend, next)}
+ label={BACKEND_LABEL[backend]}
+ />
)}
</div>
);
@@ -105,7 +112,7 @@ export function SkillDetailPanel({
</div>
</div>
- <div className="flex items-center gap-2 pt-1">
+ {canManage ? <div className="flex items-center gap-2 pt-1">
{updateAvailable ? (
<Button type="button" variant="brand-gold" size="xs" onClick={onUpdate} disabled={updating} title={versionDelta}>
{updating ? <Loader2 className="size-3 animate-spin" /> : <ArrowUp className="size-3" />}
@@ -117,7 +124,7 @@ export function SkillDetailPanel({
<Trash2 className="size-3" />
{t('skills.detail.remove')}
</Button>
- </div>
+ </div> : null}
</div>
);
}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index c91f56e3a..67dabf343 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -2,6 +2,7 @@ import React, { createContext, useContext, useEffect, useMemo, useRef } from 're
import { useTranslation } from 'react-i18next';
import { useToast } from './ToastContext';
import { apiFetch, recoverRemoteAuthFromSessionProbe } from '../lib/apiFetch';
+import { isAuthorizationSensitiveReadPath } from '../lib/authorizationCache';
import type { TurnActivityGroupWire } from '../lib/agentActivity';
import type { AgentGraphParams, AgentGraphResult, AgentGraphVisibility } from '../lib/agentGraph';
import { visibilityActivityEvents } from '../lib/sessionVisibilityEvents';
@@ -944,7 +945,7 @@ export type WorkbenchEventHandlers = {
onConnected?: (data: { sub_id: number; source?: 'browser' | 'controller' }) => void;
onConnectionState?: (state: WorkbenchEventConnectionState) => void;
onEventBridgeStatus?: (data: { connected: boolean }) => void;
- onAuthorizationChanged?: (data: { project_ids: string[] }) => void;
+ onAuthorizationChanged?: (data: { project_ids: string[]; resource_kinds?: string[] }) => void;
onMessageNew?: (data: WorkbenchMessage) => void;
// ``visibility`` (contract A6): the backend carries the session's current
// foreground/background on visibility/scope changes so the Inbox can drop /
@@ -1409,6 +1410,10 @@ export type InstanceCapabilities = {
can_manage_projects: boolean;
can_manage_agents: boolean;
can_manage_instance: boolean;
+ can_use_agents: boolean;
+ can_use_skills: boolean;
+ can_use_vault_secrets: boolean;
+ can_use_show_pages: boolean;
can_use_terminal_files: boolean;
can_use_terminal: boolean;
can_use_files: boolean;
@@ -2172,16 +2177,9 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
}
});
source.addEventListener('authorization.changed', (e: MessageEvent) => {
- const envelope = parseWorkbenchEnvelope<{ project_ids: string[] }>(e.data);
+ const envelope = parseWorkbenchEnvelope<{ project_ids: string[]; resource_kinds?: string[] }>(e.data);
if (!envelope) return;
- clearReadCacheMatching((path) =>
- path.startsWith('/api/projects') ||
- path.startsWith('/api/workbench/projects-bootstrap') ||
- path.startsWith('/api/sessions') ||
- path.startsWith('/api/inbox') ||
- path.startsWith('/api/search') ||
- path.startsWith('/api/show-pages'),
- );
+ clearReadCacheMatching(isAuthorizationSensitiveReadPath);
dispatchToWorkbenchHandlers((handlers) => {
handlers.onAny?.(envelope);
handlers.onAuthorizationChanged?.(envelope.data);
diff --git a/ui/src/context/InstanceAuthorizationContext.tsx b/ui/src/context/InstanceAuthorizationContext.tsx
index 4f6044099..fe2410011 100644
--- a/ui/src/context/InstanceAuthorizationContext.tsx
+++ b/ui/src/context/InstanceAuthorizationContext.tsx
@@ -10,6 +10,10 @@ const DENIED_CAPABILITIES: InstanceCapabilities = {
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: false,
can_use_terminal_files: false,
can_use_terminal: false,
can_use_files: false,
diff --git a/ui/src/lib/authorizationCache.test.ts b/ui/src/lib/authorizationCache.test.ts
new file mode 100644
index 000000000..a3c4925bb
--- /dev/null
+++ b/ui/src/lib/authorizationCache.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest';
+
+import { isAuthorizationSensitiveReadPath } from './authorizationCache';
+
+describe('isAuthorizationSensitiveReadPath', () => {
+ it.each([
+ '/api/agents',
+ '/api/skills?scope=global',
+ '/api/vault/secrets',
+ '/api/show-pages',
+ ])('invalidates the %s resource cache after authorization changes', (path) => {
+ expect(isAuthorizationSensitiveReadPath(path)).toBe(true);
+ });
+
+ it('does not flush unrelated stable reads', () => {
+ expect(isAuthorizationSensitiveReadPath('/api/version')).toBe(false);
+ });
+});
diff --git a/ui/src/lib/authorizationCache.ts b/ui/src/lib/authorizationCache.ts
new file mode 100644
index 000000000..590f32828
--- /dev/null
+++ b/ui/src/lib/authorizationCache.ts
@@ -0,0 +1,17 @@
+const AUTHORIZATION_SENSITIVE_READ_PREFIXES = [
+ '/api/projects',
+ '/api/workbench/projects-bootstrap',
+ '/api/sessions',
+ '/api/inbox',
+ '/api/search',
+ '/api/show-pages',
+ '/api/agents',
+ '/api/skills',
+ '/api/vault/',
+] as const;
+
+export function isAuthorizationSensitiveReadPath(path: string): boolean {
+ return AUTHORIZATION_SENSITIVE_READ_PREFIXES.some((prefix) =>
+ path.startsWith(prefix),
+ );
+}
diff --git a/ui/src/lib/showPagesStore.test.ts b/ui/src/lib/showPagesStore.test.ts
index b1f0d5d1e..55dd8eb54 100644
--- a/ui/src/lib/showPagesStore.test.ts
+++ b/ui/src/lib/showPagesStore.test.ts
@@ -205,6 +205,35 @@ describe('ShowPagesInventoryStore', () => {
release();
});
+ it('revalidates and removes revoked pages after authorization changes', async () => {
+ let handlers: EventHandlers | undefined;
+ const getShowPages = vi
+ .fn()
+ .mockResolvedValueOnce({ pages: [page()] })
+ .mockResolvedValueOnce({ pages: [] });
+ const store = new ShowPagesInventoryStore({
+ getShowPages,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ });
+
+ const release = store.activate();
+ await store.reload();
+ expect(store.getSnapshot().pages).toHaveLength(1);
+
+ handlers?.onAuthorizationChanged?.({
+ project_ids: [],
+ resource_kinds: ['show_page'],
+ });
+ await store.reload();
+
+ expect(getShowPages).toHaveBeenCalledTimes(2);
+ expect(store.getSnapshot().pages).toEqual([]);
+ release();
+ });
+
it('reconciles after a mutation instead of letting an older read overwrite it', async () => {
const stale = deferred<{ pages: ShowPage[] }>();
const reconciled = deferred<{ pages: ShowPage[] }>();
diff --git a/ui/src/lib/showPagesStore.ts b/ui/src/lib/showPagesStore.ts
index a3ec612b1..eeee3316f 100644
--- a/ui/src/lib/showPagesStore.ts
+++ b/ui/src/lib/showPagesStore.ts
@@ -229,6 +229,7 @@ export class ShowPagesInventoryStore {
// Normal session/user-message events do not change this inventory.
if (data.event === 'show_event') this.invalidateAndReload();
},
+ onAuthorizationChanged: () => this.invalidateAndReload(),
});
}
}
diff --git a/ui/src/lib/useNewSession.ts b/ui/src/lib/useNewSession.ts
index cdcf2ccef..e2672d116 100644
--- a/ui/src/lib/useNewSession.ts
+++ b/ui/src/lib/useNewSession.ts
@@ -79,27 +79,41 @@ export function useNewSession({ active = true, loadErrorText, createFailedText }
);
const loaded = rawProjects !== null;
- // Agents rarely change → fetch once per mount (not per sheet-open). Feeds the
- // shared AgentRoutePicker so the user can pick agent + model + effort instead
- // of always falling back to the server default.
+ // Keep the authorized Agent projection live. Authorization changes clear the
+ // API cache before this handler runs, so the refresh cannot retain a revoked
+ // Agent in an already-open picker.
useEffect(() => {
if (!active) return;
let cancelled = false;
- api
- .listVibeAgents({ includeDisabled: false })
- .then((res) => {
- if (cancelled) return;
- setAgents(res.agents);
- setDefaultAgentName(res.default_agent_name);
- })
- .catch(() => {
- if (!cancelled) {
- setAgents([]);
- setDefaultAgentName(null);
- }
- });
+ const loadAgents = () => {
+ void api
+ .listVibeAgents({ includeDisabled: false })
+ .then((res) => {
+ if (cancelled) return;
+ setAgents(res.agents);
+ setDefaultAgentName(res.default_agent_name);
+ setUserPick((current) => {
+ if (!current.agent_name || res.agents.some((agent) => agent.name === current.agent_name)) {
+ return current;
+ }
+ return {};
+ });
+ })
+ .catch(() => {
+ if (!cancelled) {
+ setAgents([]);
+ setDefaultAgentName(null);
+ setUserPick({});
+ }
+ });
+ };
+ loadAgents();
+ const disconnect = api.connectWorkbenchEvents({
+ onAuthorizationChanged: loadAgents,
+ });
return () => {
cancelled = true;
+ disconnect();
};
}, [active, api]);
@@ -128,7 +142,7 @@ export function useNewSession({ active = true, loadErrorText, createFailedText }
// The selected project's default Agent as a route (empty when it has none).
const projectDefaultRoute = useMemo<AgentRouteSelection>(() => {
const def = target?.default_agent;
- return def
+ return def && agents.some((agent) => agent.name === def.agent_name)
? {
agent_name: def.agent_name,
agent_variant: def.agent_variant,
@@ -136,7 +150,7 @@ export function useNewSession({ active = true, loadErrorText, createFailedText }
reasoning_effort: def.reasoning_effort,
}
: {};
- }, [target?.default_agent]);
+ }, [agents, target?.default_agent]);
// The GLOBAL default Agent resolved to a concrete route, looked up from the
// agents list by name. The picker needs a concrete route to render the model
diff --git a/vibe/api.py b/vibe/api.py
index 14add97e5..27dc5ae04 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1498,8 +1498,8 @@ def update_vibe_agent(name: str, payload: dict) -> dict:
store = VibeAgentStore()
try:
- store.require_manageable(name, user_context=resolve_resource_access_context())
- agent = store.update(name, **kwargs)
+ context = resolve_resource_access_context()
+ agent = store.update(name, user_context=context, **kwargs)
return {"ok": True, "agent": _vibe_agent_payload(agent)}
finally:
store.close()
@@ -1508,7 +1508,8 @@ def update_vibe_agent(name: str, payload: dict) -> dict:
def remove_vibe_agent(name: str) -> dict:
store = VibeAgentStore()
try:
- store.require_manageable(name, user_context=resolve_resource_access_context())
+ context = resolve_resource_access_context()
+ store.require_manageable(name, user_context=context)
counts = store.reference_counts(name)
if any(counts.values()):
return {
@@ -1518,7 +1519,7 @@ def remove_vibe_agent(name: str) -> dict:
"references": counts,
}
try:
- removed = store.remove(name)
+ removed = store.remove(name, user_context=context)
except ValueError as exc:
return {
"ok": False,
@@ -1535,10 +1536,11 @@ def remove_vibe_agent(name: str) -> dict:
def set_default_vibe_agent(name: str) -> dict:
store = VibeAgentStore()
try:
- agent = store.require_manageable(name, user_context=resolve_resource_access_context())
+ context = resolve_resource_access_context()
+ agent = store.require_manageable(name, user_context=context)
if not agent.enabled:
raise ValueError(f"agent '{agent.name}' is disabled")
- store.set_default_agent_name(name)
+ store.set_default_agent_name(name, user_context=context)
return {"ok": True, "default_agent_name": agent.name, "agent": _vibe_agent_payload(agent, brief=True)}
finally:
store.close()
@@ -11523,8 +11525,21 @@ async def list_skills(
)
-async def preview_skill_source(source: str, *, project_dir: Optional[str] = None) -> dict:
- return await _skills_guarded(lambda askill, svc: svc.preview_source(askill, source, project_dir=project_dir))
+async def preview_skill_source(
+ source: str,
+ *,
+ project_dir: Optional[str] = None,
+ user_context: Any = None,
+) -> dict:
+ context = resolve_resource_access_context() if user_context is None else user_context
+ return await _skills_guarded(
+ lambda askill, svc: svc.preview_source(
+ askill,
+ source,
+ project_dir=project_dir,
+ user_context=context,
+ )
+ )
async def add_skill(
@@ -11575,8 +11590,11 @@ async def remove_skill(
)
-async def find_skills(query: str = "") -> dict:
- return await _skills_guarded(lambda askill, svc: svc.find_skills(askill, query))
+async def find_skills(query: str = "", *, user_context: Any = None) -> dict:
+ context = resolve_resource_access_context() if user_context is None else user_context
+ return await _skills_guarded(
+ lambda askill, svc: svc.find_skills(askill, query, user_context=context)
+ )
async def check_skills(
@@ -11615,7 +11633,12 @@ async def update_skill(
)
-async def upload_skill_zip(payload: dict, *, project_dir: Optional[str] = None) -> dict:
+async def upload_skill_zip(
+ payload: dict,
+ *,
+ project_dir: Optional[str] = None,
+ user_context: Any = None,
+) -> dict:
"""Decode a base64 .zip, unpack it to a temp dir, and preview its skills.
The UI then calls add_skill with ``source`` = the returned ``dir``. The
@@ -11630,6 +11653,11 @@ async def upload_skill_zip(payload: dict, *, project_dir: Optional[str] = None)
import time
import zipfile
+ from vibe.authorization import require_instance_role
+
+ context = resolve_resource_access_context() if user_context is None else user_context
+ require_instance_role(context, "owner")
+
max_b64 = 24 * 1024 * 1024 # ~18 MB archive — skills are tiny; cap the body.
max_uncompressed = 64 * 1024 * 1024
max_entries = 2000
@@ -11690,7 +11718,14 @@ async def upload_skill_zip(payload: dict, *, project_dir: Optional[str] = None)
shutil.rmtree(workdir, ignore_errors=True)
return {"ok": False, "error": {"code": "bad_zip", "message": f"could not extract archive: {exc}"}}
- preview = await _skills_guarded(lambda askill, svc: svc.preview_source(askill, unpack, project_dir=project_dir))
+ preview = await _skills_guarded(
+ lambda askill, svc: svc.preview_source(
+ askill,
+ unpack,
+ project_dir=project_dir,
+ user_context=context,
+ )
+ )
if preview.get("ok"):
preview["dir"] = unpack
else:
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 424d1a84a..af1d6e2bd 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -13,6 +13,12 @@ INSTANCE_ACCESS_SOURCES = frozenset(
)
ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})
_ROLE_RANK = {"viewer": 1, "editor": 2, "owner": 3}
+_RESOURCE_USE_MINIMUM_ROLES = {
+ "agent": "editor",
+ "skill": "editor",
+ "vault_secret": "editor",
+ "show_page": "viewer",
+}
_VIEWER_WORKBENCH_EVENTS = frozenset(
{
@@ -51,6 +57,14 @@ class AuthorizationContext:
def is_instance_owner(self) -> bool:
return self.is_trusted_local or self.instance_role == "owner"
+ @property
+ def is_active_organization_member(self) -> bool:
+ return bool(
+ self.organization_id
+ and self.organization_member_id
+ and self.organization_role in ORGANIZATION_ROLES
+ )
+
def has_role(self, minimum_role: str) -> bool:
if self.is_trusted_local:
return True
@@ -76,6 +90,17 @@ class AuthorizationContext:
def can_manage_instance(self) -> bool:
return self.has_role("owner")
+ def can_use_resource(self, resource_kind: str) -> bool:
+ """Return whether the Instance role may use this resource kind.
+
+ Effective Resource ACL is a separate, mandatory check performed by the
+ resource service. Unknown kinds fail closed so adding a resource type
+ never makes it editor-visible by accident.
+ """
+
+ minimum_role = _RESOURCE_USE_MINIMUM_ROLES.get(resource_kind)
+ return minimum_role is not None and self.has_role(minimum_role)
+
@property
def can_use_terminal_files(self) -> bool:
return self.has_role("owner")
@@ -100,6 +125,10 @@ class AuthorizationContext:
"can_manage_projects": self.can_manage_projects,
"can_manage_agents": self.can_manage_agents,
"can_manage_instance": self.can_manage_instance,
+ "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"),
+ "can_use_show_pages": self.can_use_resource("show_page"),
"can_use_terminal_files": self.can_use_terminal_files,
"can_use_terminal": self.can_use_terminal,
"can_use_files": self.can_use_files,
@@ -129,19 +158,23 @@ def _optional_positive_int(value: Any) -> int | None:
def context_from_session_payload(payload: Mapping[str, Any]) -> AuthorizationContext:
- role = _optional_string(payload.get("vibe_instance_role"))
+ role = _optional_string(payload.get("vibe_instance_role", payload.get("instance_role")))
if role not in INSTANCE_ROLES:
return AuthorizationContext(is_remote=True)
- access_source = _optional_string(payload.get("vibe_instance_access_source"))
+ access_source = _optional_string(
+ payload.get("vibe_instance_access_source", payload.get("instance_access_source"))
+ )
if access_source not in INSTANCE_ACCESS_SOURCES:
return AuthorizationContext(is_remote=True)
- raw_groups = payload.get("vibe_group_ids", [])
+ raw_groups = payload.get("vibe_group_ids", payload.get("group_ids", []))
group_ids = (
frozenset(value for item in raw_groups if (value := _optional_string(item)) is not None)
if isinstance(raw_groups, list)
else frozenset()
)
- organization_role = _optional_string(payload.get("vibe_organization_role"))
+ organization_role = _optional_string(
+ payload.get("vibe_organization_role", payload.get("organization_role"))
+ )
if organization_role not in ORGANIZATION_ROLES:
organization_role = None
return AuthorizationContext(
@@ -150,11 +183,17 @@ def context_from_session_payload(payload: Mapping[str, Any]) -> AuthorizationCon
email=_optional_string(payload.get("email")),
instance_id=_optional_string(payload.get("vibe_instance_id", payload.get("instance_id"))),
instance_access_source=access_source,
- organization_id=_optional_string(payload.get("vibe_organization_id")),
- organization_member_id=_optional_string(payload.get("vibe_organization_member_id")),
+ organization_id=_optional_string(
+ payload.get("vibe_organization_id", payload.get("organization_id"))
+ ),
+ organization_member_id=_optional_string(
+ payload.get("vibe_organization_member_id", payload.get("organization_member_id"))
+ ),
organization_role=organization_role,
group_ids=group_ids,
- membership_version=_optional_string(payload.get("vibe_membership_version")),
+ membership_version=_optional_string(
+ payload.get("vibe_membership_version", payload.get("membership_version"))
+ ),
claims_issued_at=_optional_positive_int(
payload.get("claims_issued_at", payload.get("iat"))
),
@@ -248,6 +287,8 @@ _EDITOR_HTTP_RULES = tuple(
for method, pattern in (
("GET", r"^/api/agents$"),
("GET", r"^/api/agent-backends$"),
+ ("GET", r"^/api/skills$"),
+ ("GET", r"^/api/vault/(?:secrets|tags)$"),
("GET", r"^/api/cloud/token$"),
("GET", r"^/api/asr/status$"),
("GET", r"^/api/sessions/[^/]+/(?:archive-preview|queue|draft)$"),
@@ -262,6 +303,7 @@ _EDITOR_HTTP_RULES = tuple(
("POST", r"^/api/asr/transcribe$"),
("POST", r"^/api/show/sessions/[^/]+/events$"),
("POST", r"^/api/show/sessions/[^/]+/prewarm$"),
+ ("POST", r"^/api/vault/requests/(?:access|sign)$"),
)
)
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index 5f026d231..446325871 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -1038,6 +1038,7 @@ def _sync_one_organization(
acknowledged = 0
skipped = 0
ack_errors = 0
+ narrowed_resource_kinds: set[str] = set()
engine = get_cached_sqlite_engine()
for raw_intent in intents:
try:
@@ -1070,10 +1071,19 @@ def _sync_one_organization(
access_level=access_level,
group_ids=group_ids,
)
+ policy_narrowed = bool(
+ outcome["status"] == "applied"
+ and resource_access_service.resource_policy_narrowed(
+ previous_policy,
+ outcome["policy"],
+ )
+ )
+ if policy_narrowed:
+ narrowed_resource_kinds.add(resource_kind)
if resource_kind == "vault_secret" and outcome["status"] == "applied":
from storage import vault_service
- if vault_service.resource_policy_narrowed(previous_policy, outcome["policy"]):
+ if policy_narrowed:
revoked_rows = vault_service.revoke_active_grants_for_secret_resource(
connection,
resource_id,
@@ -1146,6 +1156,16 @@ def _sync_one_organization(
except Exception:
logger.warning("failed to clear published empty resource organization", exc_info=True)
ack_errors += 1
+ if narrowed_resource_kinds:
+ from vibe.sse_broker import broker
+
+ broker.publish(
+ "authorization.changed",
+ {
+ "project_ids": [],
+ "resource_kinds": sorted(narrowed_resource_kinds),
+ },
+ )
return {
"organization_id": organization,
"ok": ack_errors == 0,
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index cff596372..23acec2e9 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2590,11 +2590,15 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):
access_sub_id = None
access_queue = None
- if authorization_context is not None and not authorization_context.is_instance_owner:
+ if authorization_context is not None:
from vibe.sse_broker import broker
access_sub_id, access_queue = broker.subscribe()
- if not _project_session_access_allowed(authorization_context, session_id, "viewer"):
+ if not _project_session_access_allowed(
+ authorization_context,
+ session_id,
+ "viewer",
+ ) or not _show_page_resource_access_allowed(authorization_context, session_id):
broker.unsubscribe(access_sub_id)
await websocket.close(code=1008)
return
@@ -2634,7 +2638,7 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):
await proxy_task
else:
await revocation_task
- logger.info("show_runtime.project_access_revoked session=%s", session_id)
+ logger.info("show_runtime.authorization_revoked session=%s", session_id)
await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)
except Exception:
logger.debug("Show runtime HMR websocket unavailable", exc_info=True)
@@ -2834,10 +2838,27 @@ async def _wait_for_project_session_access_loss(
event_type, _payload = await queue.get()
if event_type != "authorization.changed":
continue
- if not _project_session_access_allowed(context, session_id, minimum_role):
+ if not _project_session_access_allowed(
+ context,
+ session_id,
+ minimum_role,
+ ) or not _show_page_resource_access_allowed(context, session_id):
return
+def _show_page_resource_access_allowed(context: Any, session_id: str) -> bool:
+ from storage import resource_access_service
+
+ try:
+ return resource_access_service.can_use_resource(
+ context,
+ "show_page",
+ session_id,
+ )
+ except resource_access_service.ResourceAccessError:
+ return False
+
+
def _show_runtime_websocket_resource_context(websocket: Any):
"""Build the ACL context from the same signed session used by the socket gate."""
@@ -10313,10 +10334,16 @@ async def _show_events_stream(
try:
cursor = after_id
yield ": show events connected\n\n"
- if not public and not _project_session_access_allowed(
- authorization_context,
- session_id,
- "viewer",
+ if not public and (
+ not _project_session_access_allowed(
+ authorization_context,
+ session_id,
+ "viewer",
+ )
+ or not _show_page_resource_access_allowed(
+ authorization_context,
+ session_id,
+ )
):
return
while True:
@@ -10361,6 +10388,9 @@ async def _show_events_stream(
authorization_context,
session_id,
"viewer",
+ ) or not _show_page_resource_access_allowed(
+ authorization_context,
+ session_id,
):
return
elif event_type == "show.event" and isinstance(event_payload, dict) and _event_visible(event_payload):