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): repair Viewer Editor Owner authorization boundaries (#1395)

Max215177b632b3
diff --git a/config/v2_config.py b/config/v2_config.py
index 04bee4c83..d1ade0cc1 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -2423,6 +2423,7 @@ class VibeCloudRemoteAccessConfig:
backend_url: str = "https://avibe.bot"
public_url: str = ""
instance_id: str = ""
+ instance_kind: str = ""
client_id: str = ""
issuer: str = ""
authorization_endpoint: str = ""
@@ -2869,6 +2870,10 @@ class V2Config:
**_filter_dataclass_fields(VibeCloudRemoteAccessConfig, vibe_cloud_payload)
),
)
+ if not isinstance(remote_access.vibe_cloud.instance_kind, str) or (
+ remote_access.vibe_cloud.instance_kind not in {"personal", "organization"}
+ ):
+ remote_access.vibe_cloud.instance_kind = ""
remote_access.vibe_cloud.transport_protocol = str(
remote_access.vibe_cloud.transport_protocol or "auto"
).strip().lower()
diff --git a/core/dock_store.py b/core/dock_store.py
index 330926626..eae58785b 100644
--- a/core/dock_store.py
+++ b/core/dock_store.py
@@ -182,9 +182,7 @@ def _filter_dock_for_access(
user_context: Any,
db_path: Path | None,
) -> dict[str, Any]:
- from vibe.authorization import has_temporary_unrestricted_org_access
-
- if user_context.is_trusted_local or has_temporary_unrestricted_org_access(user_context):
+ if user_context.is_instance_owner:
return doc
store = ShowPageStore(db_path)
try:
@@ -206,10 +204,9 @@ def _require_show_page_management(
user_context: Any,
db_path: Path | None,
) -> None:
- # Dock pin/unpin/reorder stay reserved to owner/admin Organization roles
- # under the Resource ACL boundary (see #1343); the temporary Organization
- # rollout does not bypass Show Page management.
- if user_context.is_trusted_local or not session_ids:
+ # Dock pin/unpin/reorder require the Instance Owner or the Show Page
+ # management capability represented by its ACL.
+ if user_context.is_instance_owner or not session_ids:
return
store = ShowPageStore(db_path)
try:
@@ -363,11 +360,7 @@ def set_dock_order(
raise DockError("Dock order has duplicate ids.", code="invalid_order")
context = _resource_context(user_context)
- from vibe.authorization import has_temporary_unrestricted_org_access
-
- has_full_runtime_access = (
- context.is_trusted_local or has_temporary_unrestricted_org_access(context)
- )
+ has_full_runtime_access = context.is_instance_owner
with _DOCK_MUTATION_LOCK:
doc = _load(db_path)
visible_doc = _filter_dock_for_access(doc, user_context=context, db_path=db_path)
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index a9684a0d2..4cf33948f 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -1621,11 +1621,11 @@ class ScheduledTaskStore:
) -> ScheduledTask:
from core.vibe_agents import ensure_agent_name_access
from storage.resource_access_service import (
- ensure_local_harness_definition_write,
+ ensure_harness_definition_write,
metadata_with_resource_user_context,
)
- ensure_local_harness_definition_write(user_context)
+ ensure_harness_definition_write(user_context)
ensure_agent_name_access(agent_name, user_context=user_context)
task = ScheduledTask(
id=uuid4().hex[:12],
@@ -1729,11 +1729,11 @@ class ScheduledTaskStore:
) -> ScheduledTask:
from core.vibe_agents import ensure_agent_name_access
from storage.resource_access_service import (
- ensure_local_harness_definition_write,
+ ensure_harness_definition_write,
metadata_with_resource_user_context,
)
- ensure_local_harness_definition_write(user_context)
+ ensure_harness_definition_write(user_context)
ensure_agent_name_access(agent_name, user_context=user_context)
task = self._tasks[task_id]
# Captured before the first mutation: this is the state the CALLER read
@@ -8223,15 +8223,15 @@ class ScheduledTaskService:
escalation_run_id: Optional[str] = None
try:
from storage.resource_access_service import (
- REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE,
- metadata_allows_temporary_unrestricted_runtime,
+ HARNESS_ACCESS_FORBIDDEN_CODE,
+ metadata_allows_harness_runtime,
)
if (
request.request_type not in {"task_run", "scheduled"}
- and not metadata_allows_temporary_unrestricted_runtime(request.metadata)
+ and not metadata_allows_harness_runtime(request.metadata)
):
- raise PermissionError(REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE)
+ raise PermissionError(HARNESS_ACCESS_FORBIDDEN_CODE)
if request.request_type in {"task_run", "scheduled"}:
# A scheduled one-shot is retired in the same SQLite transaction
# that created this Run. Only that transaction stamps the Run as
@@ -8939,8 +8939,8 @@ class ScheduledTaskService:
schedule_generation: Optional[dict[str, str]] = None,
) -> TaskExecutionResult:
from storage.resource_access_service import (
- REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE,
- metadata_allows_temporary_unrestricted_runtime,
+ HARNESS_ACCESS_FORBIDDEN_CODE,
+ metadata_allows_harness_runtime,
)
error: Optional[str] = None
@@ -8949,8 +8949,8 @@ class ScheduledTaskService:
failure_code: Optional[str] = None
session_id = task.session_id
session_key = task.session_key
- if not metadata_allows_temporary_unrestricted_runtime(task.metadata):
- error = REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE
+ if not metadata_allows_harness_runtime(task.metadata):
+ error = HARNESS_ACCESS_FORBIDDEN_CODE
if not self.store.suspend_task(task.id, error=error):
logger.warning(
"Remote-origin scheduled task %s changed before it could be suspended",
@@ -8961,7 +8961,7 @@ class ScheduledTaskService:
error=error,
session_key=session_key,
session_id=session_id,
- failure_code=REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE,
+ failure_code=HARNESS_ACCESS_FORBIDDEN_CODE,
)
user_context = self._resource_user_context(task.metadata)
binding_change: Optional[SessionBindingChange] = None
diff --git a/core/services/session_fork.py b/core/services/session_fork.py
index dd6219c35..ddaa9a91d 100644
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@ -18,7 +18,6 @@ from config import paths
from core.backend_failure import BACKEND_FAILURE_EVENT, is_backend_failure_notification
from vibe.authorization import (
AuthorizationContext,
- has_temporary_unrestricted_runtime_access,
require_instance_role,
)
from vibe.i18n import t
@@ -191,10 +190,7 @@ def reserve_forked_session(
try:
with engine.begin() as conn:
reserve_write_lock(conn)
- if not (
- context.is_instance_owner
- or has_temporary_unrestricted_runtime_access(context)
- ):
+ if not context.is_instance_owner:
from storage import project_access_service
if not project_access_service.role_allows(
diff --git a/core/services/skills.py b/core/services/skills.py
index b7c61d05f..97ab65a52 100644
--- a/core/services/skills.py
+++ b/core/services/skills.py
@@ -32,8 +32,6 @@ import os
import re
from typing import Any, Optional
-from vibe.authorization import has_temporary_unrestricted_runtime_access
-
logger = logging.getLogger(__name__)
DEFAULT_TIMEOUT = 30.0
@@ -190,7 +188,7 @@ def _cwd_for(scope: str, project_dir: Optional[str]) -> Optional[str]:
def resolve_resource_access_context(user_context: Any = None):
- """Resolve request ACL context while preserving trusted local Skill use."""
+ """Resolve request context for Skill ACL checks."""
from storage import resource_access_service
@@ -380,7 +378,7 @@ def _filter_skill_listing(
if not result.get("ok") or not isinstance(result.get("skills"), list):
return result
context = resolve_resource_access_context(user_context)
- if context.is_trusted_local or has_temporary_unrestricted_runtime_access(context):
+ if context.has_role("editor"):
return result
raw_skills = [dict(skill) for skill in result["skills"] if isinstance(skill, dict)]
@@ -493,7 +491,7 @@ def _require_skill_management_access(
from storage.db import get_cached_sqlite_engine
context = resolve_resource_access_context(user_context)
- if context.is_trusted_local or has_temporary_unrestricted_runtime_access(context):
+ if context.has_role("editor"):
return
engine = get_cached_sqlite_engine()
with engine.connect() as connection:
@@ -514,7 +512,7 @@ def _require_skill_management_access(
def _require_skill_create_access(user_context: Any) -> None:
context = resolve_resource_access_context(user_context)
- if context.can_manage_instance or has_temporary_unrestricted_runtime_access(context):
+ if context.has_role("editor"):
return
raise SkillAccessError()
@@ -529,14 +527,10 @@ def _require_skill_use_access(
if (
not context.can_use_resource("skill")
- and not has_temporary_unrestricted_runtime_access(context)
+ and not context.has_role("editor")
):
raise SkillAccessError()
- if (
- context.is_trusted_local
- or context.is_instance_owner
- or has_temporary_unrestricted_runtime_access(context)
- ):
+ if context.has_role("editor"):
return
if not project_dir:
if scope in {"all", "global"}:
@@ -636,7 +630,7 @@ def _register_created_skill_policies(
from storage.db import get_cached_sqlite_engine
context = resolve_resource_access_context(user_context)
- if not (context.is_remote and context.is_active_organization_member and context.subject):
+ if not context.subject:
return
engine = get_cached_sqlite_engine()
with engine.begin() as connection:
@@ -821,8 +815,8 @@ async def add_skill(
raise SkillsError("invalid_scope", "install scope must be global or project")
context = resolve_resource_access_context(user_context)
if not (
- context.is_trusted_local
- or has_temporary_unrestricted_runtime_access(context)
+ context.is_instance_owner
+ or context.has_role("editor")
):
_require_skill_create_access(context)
target_names = [skill] if skill else []
@@ -928,8 +922,8 @@ 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
- or has_temporary_unrestricted_runtime_access(context)
+ context.is_instance_owner
+ or context.has_role("editor")
):
_require_skill_create_access(context)
resource_ids = await _installed_skill_resource_ids(
@@ -1006,8 +1000,8 @@ async def check(
user_context=context,
)
if (
- context.is_trusted_local
- or has_temporary_unrestricted_runtime_access(context)
+ context.is_instance_owner
+ or context.has_role("editor")
or not isinstance(filtered.get("summary"), dict)
):
return filtered
@@ -1038,8 +1032,8 @@ 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
- or has_temporary_unrestricted_runtime_access(context)
+ context.is_instance_owner
+ or context.has_role("editor")
):
_require_skill_create_access(context)
resource_ids = await _installed_skill_resource_ids(
diff --git a/core/show_pages.py b/core/show_pages.py
index ae4f2be35..d345b6b92 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -223,7 +223,7 @@ def _like_pattern(value: str, *, prefix: bool = False, contains: bool = False) -
def _resolve_resource_access_context(user_context: Any = None):
- """Resolve request ACL context while retaining trusted local workflows."""
+ """Resolve the request context used by Show Page ACL checks."""
from storage import resource_access_service
@@ -463,26 +463,33 @@ class ShowPageStore:
@staticmethod
def _require_create_access(user_context: Any) -> None:
- from vibe.authorization import has_temporary_unrestricted_org_access
-
- if user_context.can_manage_instance or has_temporary_unrestricted_org_access(user_context):
+ if user_context.has_role("editor"):
return
raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")
+ @staticmethod
+ def _require_project_edit_access(connection: Connection, session_id: str, user_context: Any) -> None:
+ """Require Editor access to the Project that owns this session."""
+
+ if user_context.is_instance_owner:
+ return
+ from storage import project_access_service
+
+ scope_id = connection.execute(
+ select(agent_sessions.c.scope_id).where(agent_sessions.c.id == session_id).limit(1)
+ ).scalar_one_or_none()
+ project_id = project_access_service.project_id_from_scope_id(scope_id)
+ if project_id is None or not project_access_service.role_allows(
+ project_access_service.get_effective_project_role(connection, user_context, project_id),
+ "editor",
+ ):
+ raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")
+
@staticmethod
def _register_created_resource_policy(connection, session_id: str, user_context: Any) -> None:
from storage import resource_access_service
- from vibe.authorization import has_temporary_unrestricted_org_access
-
- if not (
- user_context.is_remote
- and user_context.is_active_organization_member
- and user_context.subject
- and (
- user_context.can_manage_instance
- or has_temporary_unrestricted_org_access(user_context)
- )
- ):
+
+ if not (user_context.subject and user_context.has_role("editor")):
return
resource_access_service.ensure_resource_policy(
connection,
@@ -515,8 +522,10 @@ class ShowPageStore:
.first()
)
if existing is not None:
+ self._require_project_edit_access(conn, session_id, context)
self._require_resource_access(conn, session_id, context)
return _page_from_row(existing)
+ self._require_project_edit_access(conn, session_id, context)
self._require_create_access(context)
conn.execute(
insert(show_pages).values(
@@ -551,8 +560,10 @@ class ShowPageStore:
.first()
)
if existing is not None:
+ self._require_project_edit_access(conn, session_id, context)
self._require_resource_access(conn, session_id, context)
return _page_from_row(existing), False
+ self._require_project_edit_access(conn, session_id, context)
self._require_create_access(context)
status = conn.execute(
select(agent_sessions.c.status).where(agent_sessions.c.id == session_id)
diff --git a/core/vibe_agents.py b/core/vibe_agents.py
index 0bbca9b57..2955c79fd 100644
--- a/core/vibe_agents.py
+++ b/core/vibe_agents.py
@@ -32,8 +32,7 @@ from storage.models import (
)
from storage.session_reclaim import DEFINITION_AGENT_BINDING_REVISION_KEY
from vibe.authorization import (
- has_temporary_unrestricted_runtime_access,
- trusted_local_context,
+ instance_owner_context,
)
logger = logging.getLogger(__name__)
@@ -255,9 +254,14 @@ def ensure_agent_selection_access(
)
row = connection.execute(statement.limit(1)).mappings().first()
if row is None:
- if context.is_remote or missing_is_error:
+ if missing_is_error:
raise LookupError("Agent not found")
- return None
+ # Owners keep the pre-catalog fallback for historical backend names.
+ # Everyone else must resolve a real Agent row; a missing selector is
+ # not an authorization grant.
+ if context.is_instance_owner:
+ return None
+ raise VibeAgentAccessError("Agent access is not permitted.")
agent = VibeAgentStore._from_row(row)
if not resource_access_service.can_use_resource(
@@ -280,18 +284,24 @@ def ensure_agent_name_access(
if not str(agent_name or "").strip():
return
context = resolve_resource_access_context(user_context)
- if not context.is_remote:
- return
store = VibeAgentStore()
try:
- store.require_accessible(str(agent_name), user_context=context)
+ try:
+ store.require_accessible(str(agent_name), user_context=context)
+ except ValueError:
+ # Legacy local/Owner task definitions may refer to a backend name
+ # that predates the Vibe Agent catalog. Keep those internal flows
+ # intact; an Editor or Viewer must still resolve a real ACL row.
+ if context.is_instance_owner:
+ return
+ raise
finally:
store.close()
def _require_agent_create_access(user_context: Any) -> None:
context = resolve_resource_access_context(user_context)
- if context.can_manage_agents or has_temporary_unrestricted_runtime_access(context):
+ if context.can_manage_agents:
return
raise VibeAgentAccessError("Agent access is not permitted.")
@@ -300,11 +310,7 @@ def _require_agent_onboarding_access(user_context: Any):
"""Require owner-equivalent access for Organization Agent publication."""
context = resolve_resource_access_context(user_context)
- if (
- context.is_trusted_local
- or context.is_instance_owner
- or has_temporary_unrestricted_runtime_access(context)
- ):
+ if context.is_instance_owner:
return context
raise VibeAgentAccessError("Agent access is not permitted.")
@@ -523,7 +529,7 @@ def ensure_default_agent_access(
context = resolve_resource_access_context(user_context)
agent = resolve_effective_default_agent(connection)
if agent is None:
- if context.is_remote or missing_is_error:
+ if missing_is_error:
raise LookupError("Default Agent not found")
return None
if not resource_access_service.can_use_resource(
@@ -554,7 +560,7 @@ def ensure_session_agent_access(
)
if not session.get("agent_backend"):
return ensure_default_agent_access(connection, user_context=context)
- if context.is_remote and not has_temporary_unrestricted_runtime_access(context):
+ if not context.is_instance_owner:
raise VibeAgentAccessError("Agent access is not permitted.")
return None
@@ -914,7 +920,7 @@ class VibeAgentStore:
try:
with self.engine.begin() as conn:
conn.execute(agents.insert().values(**self._values(agent)))
- if source != "builtin" and context.is_remote and context.is_active_organization_member and context.subject:
+ if source != "builtin" and context.is_active_organization_member and context.subject:
resource_access_service.ensure_resource_policy(
conn,
resource_kind="agent",
@@ -1525,7 +1531,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, user_context=trusted_local_context())
+ self.set_default_agent_name(existing.name, user_context=instance_owner_context())
return existing
agent = self.create(
name=DEFAULT_AGENT_NAME,
@@ -1535,7 +1541,7 @@ class VibeAgentStore:
metadata={"builtin": True},
enabled=True,
)
- self.set_default_agent_name(agent.name, user_context=trusted_local_context())
+ self.set_default_agent_name(agent.name, user_context=instance_owner_context())
return agent
def ensure_builtin_default_agent(self, *, backend: str, name: str | None = None) -> VibeAgent:
@@ -1557,7 +1563,7 @@ class VibeAgentStore:
return self.update(
existing.name,
metadata=merged,
- user_context=trusted_local_context(),
+ user_context=instance_owner_context(),
)
return existing
return self.create(
@@ -1589,7 +1595,7 @@ class VibeAgentStore:
if updates:
return self.update(
agent.name,
- user_context=trusted_local_context(),
+ user_context=instance_owner_context(),
**updates,
)
return agent
@@ -1625,7 +1631,7 @@ class VibeAgentStore:
if (default_agent is None or not default_agent.enabled) and enabled_ensured:
self.set_default_agent_name(
enabled_ensured[0].name,
- user_context=trusted_local_context(),
+ user_context=instance_owner_context(),
)
return ensured
diff --git a/core/watches.py b/core/watches.py
index f01ac98a5..6a89c5dd4 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -624,11 +624,11 @@ class ManagedWatchStore:
) -> ManagedWatch:
from core.vibe_agents import ensure_agent_name_access
from storage.resource_access_service import (
- ensure_local_harness_definition_write,
+ ensure_harness_definition_write,
metadata_with_resource_user_context,
)
- ensure_local_harness_definition_write(user_context)
+ ensure_harness_definition_write(user_context)
ensure_agent_name_access(agent_name, user_context=user_context)
watch = ManagedWatch(
id=uuid4().hex[:12],
@@ -733,11 +733,11 @@ class ManagedWatchStore:
) -> ManagedWatch:
from core.vibe_agents import ensure_agent_name_access
from storage.resource_access_service import (
- ensure_local_harness_definition_write,
+ ensure_harness_definition_write,
metadata_with_resource_user_context,
)
- ensure_local_harness_definition_write(user_context)
+ ensure_harness_definition_write(user_context)
ensure_agent_name_access(agent_name, user_context=user_context)
watch = self._watches[watch_id]
# Captured before the first mutation: the state ``vibe watch update`` read and
@@ -2081,8 +2081,8 @@ class ManagedWatchService:
async def _run_watch(self, watch_id: str) -> None:
from storage.resource_access_service import (
- REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE,
- metadata_allows_temporary_unrestricted_runtime,
+ HARNESS_ACCESS_FORBIDDEN_CODE,
+ metadata_allows_harness_runtime,
)
lifetime_started: float | None = None
@@ -2104,14 +2104,14 @@ class ManagedWatchService:
watch = self.store.get_watch(watch_id)
if watch is None or not watch.enabled:
return
- if not metadata_allows_temporary_unrestricted_runtime(watch.metadata):
+ if not metadata_allows_harness_runtime(watch.metadata):
self._watch_store_call(
watch.id,
"suspend_remote_origin",
lambda: self.store.mark_cycle_result(
watch.id,
exit_code=None,
- error=REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE,
+ error=HARNESS_ACCESS_FORBIDDEN_CODE,
disable=True,
),
guarded=True,
diff --git a/core/web_push_notifications.py b/core/web_push_notifications.py
index 64fe6ffbf..d892f23f9 100644
--- a/core/web_push_notifications.py
+++ b/core/web_push_notifications.py
@@ -346,9 +346,7 @@ def _badge_count_for_user_key(
# Legacy remote messages predate persisted authorization claims. Keep
# delivering eligible content, but never attach a machine-global count.
return 0
- from vibe.authorization import has_temporary_unrestricted_runtime_access
-
- if context.is_instance_owner or has_temporary_unrestricted_runtime_access(context):
+ if context.is_instance_owner:
return messages_service.total_unread(conn, platform="avibe")
from storage import project_access_service
diff --git a/docs/CLI.md b/docs/CLI.md
index 5bde2f70e..cbcff73b6 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -173,11 +173,11 @@ Start the guided Avibe Cloud remote-access setup.
vibe remote
```
-In the conservative Organization release, the remote Workbench remains
-available for Organization management and authorized Project, Session, message,
-and history reads. Agent turns and runtime controls, Harness definition changes and autonomous
-execution, terminal access, and file operations remain trusted-local only; open
-Avibe on the machine to perform those actions.
+The remote Workbench uses the same Instance role and Project/Agent/Show Page ACLs
+as the local UI. Viewers can read permitted resources, Editors can use runtime
+surfaces where their Project and Agent access allows it, and Owners can manage
+the Instance. Connection, Origin/CSRF, approval, and path-safety checks still
+apply independently.
**Flow:**
- The CLI explains what remote access does before asking for anything.
diff --git a/docs/plans/fastapi-migration.md b/docs/plans/fastapi-migration.md
index eb4f3cf38..5ec6afcd9 100644
--- a/docs/plans/fastapi-migration.md
+++ b/docs/plans/fastapi-migration.md
@@ -71,10 +71,11 @@ Additional findings from the current codebase:
catalog/auth operations, and OAuth web flows. UI-reachable wrappers should be
converted as their routes are touched. Test-only or non-UI `asyncio.run`
calls are not part of this acceptance criterion.
-- Tests should not be migrated only at the end. `tests/test_ui_remote_access_auth.py`
- is the security contract for remote access and setup-host behavior; keep it
- green after the substrate layer lands, then carry the rest of the UI test
- files surface by surface.
+- Tests should not be migrated only at the end. Remote-access auth coverage is
+ split across `tests/test_ui_server_fastapi.py` and
+ `tests/ui_server_test_helpers.py`; keep those focused tests green after the
+ substrate layer lands, then carry the rest of the UI test files surface by
+ surface.
- The current `run_ui_server()` tests monkeypatch `werkzeug.make_server`.
They need to be rewritten around `uvicorn.Server` and the nonblocking
remote-access reconcile behavior.
@@ -255,7 +256,9 @@ Tests use `app.test_client()` (Flask) extensively. Port pattern:
`TestClient` is a thin sync wrapper around `httpx.Client`; it transparently runs the ASGI app under the hood. Most assertions stay byte-identical. Async fixtures (if any) switch to `pytest-asyncio` patterns.
-The biggest file: `tests/test_ui_remote_access_auth.py` — patches like `monkeypatch.setattr("vibe.ui_server.psutil...", ...)` still work because the module path is unchanged.
+The historical remote-access auth suite was later split into focused FastAPI
+tests; patches like `monkeypatch.setattr("vibe.ui_server.psutil...", ...)` still
+work because the module path is unchanged.
### WebSocket smoke route
@@ -281,7 +284,7 @@ The chat feature will land in a follow-up PR using this same pattern. We just ne
| --- | --- |
| 74 routes — long migration, easy to miss subtle response-shape differences | Migrate one router file at a time, run the existing test for that surface after each, smoke via curl. Don't merge until ALL test files pass and a manual smoke against the React UI is clean. |
| Tests embedded in Flask test client semantics (cookies, sessions) | TestClient is largely API-compatible; deal with cookie domain quirks one test file at a time. Allocate ~25% of the migration budget for tests. |
-| CSRF / remote_access middleware: ordering bugs | Port one middleware at a time with a focused test. The `tests/test_ui_remote_access_auth.py` suite is the source of truth — keep it green. |
+| CSRF / remote_access middleware: ordering bugs | Port one middleware at a time with focused FastAPI tests in `tests/test_ui_server_fastapi.py`. |
| Sentry integration regression | Init in lifespan startup; verify Sentry breadcrumbs still appear via the regression env's dev key. |
| WSGI-specific subprocess launching pattern in `run_ui_server` | Uvicorn handles this natively in-process; keep the EADDRINUSE retry loop. |
| Frontend assumptions about specific status codes / response shapes | Don't refactor any payload shape during the migration. Same path, same method, same JSON. |
@@ -294,7 +297,7 @@ The chat feature will land in a follow-up PR using this same pattern. We just ne
Each phase ends with a green test run + a manual smoke. Commit between phases.
1. **Bootstrap.** Add fastapi/uvicorn/python-multipart/httpx to `pyproject.toml`. Create `vibe/ui_routers/` directory with empty `__init__.py`. Create the new `app = FastAPI(lifespan=lifespan)` in `vibe/ui_server.py` ALONGSIDE the existing Flask `app` (rename Flask app temporarily, e.g. `_legacy_flask_app`). Wire `run_ui_server` to dispatch to whichever app a `VIBE_UI_FRAMEWORK=fastapi` env var selects. Implement `/health` on FastAPI as the canary route.
-2. **Middleware.** Port CSRF / remote_access auth / setup wizard gate / CSRF cookie / remote_access cookie hooks as FastAPI middleware. Carry the existing `tests/test_ui_remote_access_auth.py` through; it must stay green.
+2. **Middleware.** Port CSRF / remote_access auth / setup wizard gate / CSRF cookie / remote_access cookie hooks as FastAPI middleware. Keep the focused FastAPI auth tests green.
3. **Static + Setup.** Port the SPA catch-all, `/setup/*`, `/auth/callback`, asset routes. The setup wizard is high-traffic; smoke through `./scripts/run_regression.sh` end-to-end after this phase.
4. **Backends + agent CLI lifecycle.** Port `/backend/*`, `/agent/*`, `/cli/detect`. Drop `asyncio.run` from the corresponding `vibe/api.py` helpers as you go.
5. **Backend OAuth + per-provider.** Port `/backend/<b>/auth/oauth/*` and `/backend/opencode/provider/*`. Delete `vibe-oauth-loop` thread; `_submit_oauth_coro` callers become `await`. This phase **fixes the cross-loop bug at the root**.
diff --git a/docs/plans/issue-1389-instance-authorization.md b/docs/plans/issue-1389-instance-authorization.md
new file mode 100644
index 000000000..80884998f
--- /dev/null
+++ b/docs/plans/issue-1389-instance-authorization.md
@@ -0,0 +1,64 @@
+# Issue 1389: Instance Authorization Repair
+
+## Background
+
+The current runtime still contains two transitional authorization models:
+
+- trusted-local and local-only product gates;
+- unrestricted access for active Organization members.
+
+Those models override Viewer/Editor/Owner and resource ACL decisions, so the
+same admitted Instance user receives different capabilities depending on the
+request origin or Organization claims.
+
+## Goal
+
+After Instance admission, every product decision uses only:
+
+1. Instance role (`viewer`, `editor`, or `owner`);
+2. Project ACL;
+3. Agent ACL;
+4. Show Page ACL.
+
+`is_remote` remains transport metadata only. Organization claims remain
+admission and ACL attributes only. Connection/session validation, Origin/CSRF,
+path validation, Vault approval, and input validation remain unchanged.
+
+## Implementation Contract
+
+- A local Web request and standalone local administration without an initiating
+ user context receive an ordinary Instance Owner context. There is no trusted
+ local authorization identity or bypass.
+- Viewer may read allowed Projects, Sessions, messages, and Show Pages. Viewer
+ cannot chat, invoke Agents, or use Files, Editor, Terminal, Dock, Skills,
+ Vault, or Harness.
+- Editor may chat only in Projects whose effective Project role is Editor, may
+ discover/select/invoke only Agents allowed by Agent ACL, and may use Files,
+ Editor, Terminal, Dock, Skills, Vault, and Harness. Historical Skill/Vault ACL
+ rows do not constrain these MVP capabilities.
+- Owner has Editor capabilities across the Instance and may manage all Projects,
+ Agents, Show Pages, Instance configuration, and runtime administration.
+- Show Page email grants and anonymous public pages remain confined to their
+ existing signed/public page scopes.
+- Unknown authenticated Instance API routes require Owner. They do not require
+ local origin and never return `remote_execution_disabled`.
+
+## Work
+
+- [ ] Remove transitional backend authorization helpers, route matrices,
+ payload projections, and product-error branches.
+- [ ] Apply role and Project/Agent/Show Page ACL checks at HTTP, service,
+ WebSocket, SSE, queue, and Harness enforcement points.
+- [ ] Remove frontend origin/member fallbacks and render navigation, direct
+ routes, selectors, and controls from capability projections.
+- [ ] Replace obsolete tests with local/remote parity and representative
+ Viewer/Editor/Owner plus ACL coverage.
+- [ ] Run focused tests, Ruff, UI tests/build, and regression browser flows.
+
+## Out Of Scope
+
+- New identity/database schemas or migrations.
+- Online revalidation redesign for persisted Harness work.
+- Filesystem/Terminal sandboxing or dependency isolation through
+ Skills/Vault/Harness.
+- Cloud Organization management authorization redesign.
diff --git a/docs/plans/pwa-oauth-login-state-desync.md b/docs/plans/pwa-oauth-login-state-desync.md
index 5c54bc333..645f6a99e 100644
--- a/docs/plans/pwa-oauth-login-state-desync.md
+++ b/docs/plans/pwa-oauth-login-state-desync.md
@@ -122,7 +122,7 @@ the highest layer plus backstops:
## Testing
-- Unit (`tests/test_ui_remote_access_auth.py`):
+- Unit (`tests/test_ui_server_fastapi.py` and `tests/ui_server_test_helpers.py`):
- new: valid-but-mismatched cookie + matching server-side record → callback
completes via the store, using the record's verifier/nonce (not the stale
cookie's).
diff --git a/storage/project_access_service.py b/storage/project_access_service.py
index 592f06e0b..5fb97d216 100644
--- a/storage/project_access_service.py
+++ b/storage/project_access_service.py
@@ -11,8 +11,6 @@ from sqlalchemy import delete, insert, select
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.engine import Connection
-from vibe.authorization import has_temporary_unrestricted_runtime_access
-
from storage.models import (
agent_sessions,
project_access_bindings,
@@ -314,7 +312,7 @@ def get_effective_project_role(
context: AuthorizationContext,
project_id: str,
) -> str | None:
- if context.is_instance_owner or has_temporary_unrestricted_runtime_access(context):
+ if context.is_instance_owner:
return "owner"
if not is_active_project(conn, project_id):
return None
@@ -368,10 +366,7 @@ def get_effective_session_role(
).scalar_one_or_none()
project_id = project_id_from_scope_id(scope_id)
if project_id is None:
- return "owner" if (
- context.is_instance_owner
- or has_temporary_unrestricted_runtime_access(context)
- ) else None
+ return "owner" if context.is_instance_owner else None
return get_effective_project_role(conn, context, project_id)
diff --git a/storage/projects_service.py b/storage/projects_service.py
index 0d089ffe4..3c875e089 100644
--- a/storage/projects_service.py
+++ b/storage/projects_service.py
@@ -26,7 +26,6 @@ from storage import project_access_service
from storage.models import agents, scope_settings, scopes
from vibe.authorization import (
AuthorizationContext,
- has_temporary_unrestricted_runtime_access,
require_instance_role,
)
@@ -214,11 +213,6 @@ def _project_for_context(
str(project.get("id") or ""),
)
}
- if context.is_remote and not has_temporary_unrestricted_runtime_access(context):
- # Remote identities outside the temporary active-Organization rollout
- # remain unable to inspect the host's workdir and local metadata.
- payload["folder_path"] = ""
- payload["metadata"] = {}
return payload
diff --git a/storage/resource_access_service.py b/storage/resource_access_service.py
index 31e1af938..b1c76a730 100644
--- a/storage/resource_access_service.py
+++ b/storage/resource_access_service.py
@@ -22,9 +22,7 @@ from storage.models import resource_access_groups, resource_access_policies, sta
from vibe.authorization import (
AuthorizationContext,
context_from_session_payload,
- has_temporary_unrestricted_org_access,
- has_temporary_unrestricted_runtime_access,
- trusted_local_context,
+ instance_owner_context,
)
@@ -33,7 +31,7 @@ ACCESS_LEVELS = frozenset({"public", "scope", "private"})
ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})
RESOURCE_USER_CONTEXT_METADATA_KEY = "resource_user_context"
RESOURCE_ORGANIZATIONS_META_KEY = "resource_access_organizations"
-REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE = "remote_autonomous_harness_disabled"
+HARNESS_ACCESS_FORBIDDEN_CODE = "harness_access_forbidden"
class ResourceAccessError(ValueError):
@@ -140,12 +138,9 @@ def _context_from_mapping(
payload: Mapping[str, Any] | None,
*,
is_remote: bool,
- is_trusted_local: bool,
) -> ResourceUserContext:
- if is_trusted_local:
- return trusted_local_context()
if not is_remote:
- return AuthorizationContext()
+ return instance_owner_context()
return context_from_session_payload(payload or {})
@@ -153,7 +148,6 @@ def current_resource_context(
session_payload: Mapping[str, Any] | None = None,
*,
is_remote: bool | None = None,
- is_trusted_local: bool | None = None,
) -> ResourceUserContext:
"""Return the request's local resource-access context.
@@ -165,11 +159,10 @@ def current_resource_context(
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:
+ if session_payload is not None or is_remote is not None:
return _context_from_mapping(
session_payload,
is_remote=bool(is_remote if is_remote is not None else session_payload is not None),
- is_trusted_local=bool(is_trusted_local),
)
try:
@@ -186,7 +179,7 @@ def current_resource_context(
def resolve_resource_access_context(
user_context: ResourceUserContext | Mapping[str, Any] | None = None,
) -> ResourceUserContext:
- """Resolve ACL context, trusting implicit local use only outside HTTP."""
+ """Resolve ACL context, defaulting non-HTTP service calls to Instance Owner."""
if isinstance(user_context, AuthorizationContext):
return user_context
@@ -194,28 +187,24 @@ def resolve_resource_access_context(
return current_resource_context(user_context, is_remote=True)
context = current_resource_context()
- if context.is_remote or context.is_trusted_local:
+ if context.is_remote:
return context
from vibe.ui_compat import has_request_context
if has_request_context():
return context
- return trusted_local_context()
+ return instance_owner_context()
-def ensure_local_harness_definition_write(
+def ensure_harness_definition_write(
user_context: ResourceUserContext | Mapping[str, Any] | None = None,
) -> ResourceUserContext:
- """Allow the temporary active-Organization runtime rollout to write Harness data.
-
- The caller's real remote identity is retained in all persisted metadata;
- this helper only decides whether the operation is admitted.
- """
+ """Require Editor role for Harness definitions, independent of request origin."""
context = resolve_resource_access_context(user_context)
- if context.is_remote and not has_temporary_unrestricted_org_access(context):
- raise ResourceAccessError(REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE)
+ if not context.has_role("editor"):
+ raise ResourceAccessError(HARNESS_ACCESS_FORBIDDEN_CODE)
return context
@@ -228,16 +217,10 @@ def metadata_has_remote_resource_context(metadata: Mapping[str, Any] | None) ->
)
-def metadata_allows_temporary_unrestricted_runtime(
+def metadata_allows_harness_runtime(
metadata: Mapping[str, Any] | None,
) -> bool:
- """Return whether persisted remote provenance may execute runtime work.
-
- Remote Harness definitions retain signed claims instead of becoming local
- owners. Rehydrate those claims and require the same active-Organization
- rollout signal at execution time; malformed, expired, or non-member
- metadata remains denied.
- """
+ """Return whether persisted user provenance has Editor runtime access."""
if not metadata_has_remote_resource_context(metadata):
return True
@@ -245,10 +228,7 @@ def metadata_allows_temporary_unrestricted_runtime(
context = resource_user_context_from_metadata(metadata)
except ResourceAccessError:
return False
- return bool(
- context is not None
- and has_temporary_unrestricted_runtime_access(context)
- )
+ return bool(context is not None and context.has_role("editor"))
def metadata_with_resource_user_context(
@@ -294,9 +274,9 @@ def resource_user_context_from_metadata(
) -> ResourceUserContext | None:
"""Restore remote provenance for deferred authorization checks.
- The returned context retains the real signed Organization identity. Deferred
- runtime executors still apply ``metadata_allows_temporary_unrestricted_runtime``
- before doing work, so malformed and non-member snapshots fail closed.
+ The returned context retains the initiating role and ACL attributes.
+ Deferred runtime executors still apply ``metadata_allows_harness_runtime``
+ before doing work, so malformed or Viewer snapshots fail closed.
The ``authorization_expires_at`` snapshot is recorded for audit but is no
longer a hard execution cutoff: durable automation (Harness tasks/watches)
@@ -310,39 +290,17 @@ def resource_user_context_from_metadata(
snapshot = metadata.get(RESOURCE_USER_CONTEXT_METADATA_KEY)
if not isinstance(snapshot, Mapping):
return None
- return current_resource_context(snapshot, is_remote=True, is_trusted_local=False)
+ return current_resource_context(snapshot, is_remote=True)
def _as_context(user_context: ResourceUserContext | Mapping[str, Any] | None) -> ResourceUserContext:
if isinstance(user_context, ResourceUserContext):
return user_context
if isinstance(user_context, Mapping):
- return _context_from_mapping(user_context, is_remote=True, is_trusted_local=False)
+ return _context_from_mapping(user_context, is_remote=True)
return ResourceUserContext()
-def _temporary_unrestricted_resource_bypass(
- context: ResourceUserContext,
- resource_kind: str,
-) -> bool:
- """Apply the temporary rollout to known runtime resource kinds.
-
- This is still an explicit resource-kind allowlist. It does not change the
- caller into a trusted-local principal and unknown resource kinds fail closed.
- """
-
- return resource_kind in RESOURCE_KINDS and has_temporary_unrestricted_org_access(context)
-
-
-def _temporary_show_page_bypass(
- context: ResourceUserContext,
- resource_kind: str,
-) -> bool:
- """Compatibility predicate for callers that specifically handle Show Pages."""
-
- return resource_kind == "show_page" and has_temporary_unrestricted_org_access(context)
-
-
@contextmanager
def _connection(connection: Connection | None) -> Iterator[Connection]:
if connection is not None:
@@ -602,10 +560,15 @@ def _policy_allows(
policy: Mapping[str, Any] | None,
group_ids: Sequence[str],
) -> bool:
- if context.is_trusted_local:
- return True
- if _temporary_unrestricted_resource_bypass(context, resource_kind):
+ if context.is_instance_owner:
return True
+ # Skill and Vault ACL rows remain persisted for compatibility, but Editor
+ # runtime access intentionally ignores them for validated remote sessions.
+ # Direct non-remote contexts still use the stored policy so service-level
+ # ACL checks cannot be bypassed by a caller-supplied role alone.
+ if resource_kind in {"skill", "vault_secret"}:
+ if context.is_remote and context.is_active_organization_member and context.has_role("editor"):
+ return True
if resource_kind == "show_page" and context.can_use_show_page(resource_id):
return True
if context.instance_access_source == "show_page_email":
@@ -613,17 +576,7 @@ def _policy_allows(
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 only when it carries an admitted remote
- # identity (active Organization member or signed Instance owner with an
- # accepted access source); a remote non-member owner claim must not
- # bypass the Resource ACL boundary.
- if context.is_trusted_local:
- return True
- return bool(
- context.instance_role == "owner"
- and context._has_admitted_remote_identity()
- )
+ return False
owner_user_id = _clean_optional_string(policy.get("owner_user_id"))
if policy.get("access_level") == "private":
@@ -649,33 +602,18 @@ def _policy_allows(
def _policy_allows_management(context: ResourceUserContext, policy: Mapping[str, Any] | None) -> bool:
- # Resource ACL management is a durable Org boundary, not a runtime surface
- # that the temporary Organization rollout opens. Keep the origin/org gate
- # by checking the role rank directly so the runtime-only owner bypass
- # applied for runtime API admission does not bleed into ACL decisions.
- if context.is_trusted_local:
+ if context.is_instance_owner:
return True
- instance_role_rank = {
- "owner": 3,
- "editor": 2,
- "viewer": 1,
- }.get(context.instance_role or "", 0)
- if instance_role_rank < 3:
- return False
if policy is None:
- 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
- )
+ return False
+ # Skills and Vault ACL rows are retained for compatibility, but MVP runtime
+ # access and management follow the Instance Editor capability directly.
+ if policy.get("resource_kind") in {"skill", "vault_secret"}:
+ return context.has_role("editor")
return bool(
- context.is_active_organization_member
- and context.organization_id == _clean_optional_string(policy.get("organization_id"))
- and context.organization_role in {"owner", "admin"}
+ context.has_role("editor")
+ and context.subject
+ and context.subject == _clean_optional_string(policy.get("owner_user_id"))
)
@@ -685,12 +623,7 @@ def _policy_allows_owner_control(
) -> bool:
"""Allow high-impact sharing actions only to the resource owner."""
- if context.is_trusted_local:
- return True
- if isinstance(policy, Mapping) and _temporary_unrestricted_resource_bypass(
- context,
- str(policy.get("resource_kind") or ""),
- ):
+ if context.is_instance_owner:
return True
if policy is None:
return context.is_instance_owner
@@ -711,25 +644,12 @@ def _policy_allows_show_page_access_management(
context: ResourceUserContext,
policy: Mapping[str, Any] | None,
) -> bool:
- """Allow Show Page owners and Organization managers to narrow access."""
-
- if (
- isinstance(policy, Mapping)
- and _temporary_show_page_bypass(context, str(policy.get("resource_kind") or ""))
- ):
- return True
+ """Allow the Instance Owner or page owner represented by the ACL."""
if _policy_allows_owner_control(context, policy):
return True
if policy is None or policy.get("resource_kind") != "show_page":
return False
- organization_id = _clean_optional_string(policy.get("organization_id"))
- return bool(
- organization_id
- and context.can_use_resource("show_page")
- and context.is_active_organization_member
- and context.organization_id == organization_id
- and context.organization_role in {"owner", "admin"}
- ) or _policy_allows_management(context, policy)
+ return _policy_allows_management(context, policy)
def can_use_resource_policy_snapshot(
@@ -743,7 +663,7 @@ def can_use_resource_policy_snapshot(
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
+ return False
group_ids = policy.get("group_ids") if policy is not None else []
if not isinstance(group_ids, (list, tuple, set, frozenset)):
return False
@@ -793,10 +713,6 @@ def can_manage_resource_acl(
context = _as_context(user_context)
kind = _validate_resource_kind(resource_kind)
identifier = _required_identifier(resource_id, code="invalid_resource_id")
- # Resource ACL management is a durable Org boundary, not a runtime surface
- # that the temporary Organization rollout opens. Keep the origin/org gate.
- if context.is_trusted_local:
- return True
with _connection(connection) as conn:
policy = _policy_row(conn, kind, identifier)
return _policy_allows_management(context, policy)
@@ -812,8 +728,6 @@ def can_manage_show_page_access(
context = _as_context(user_context)
identifier = _required_identifier(resource_id, code="invalid_resource_id")
- if _temporary_show_page_bypass(context, "show_page"):
- return True
with _connection(connection) as conn:
policy = _policy_row(conn, "show_page", identifier)
return _policy_allows_show_page_access_management(context, policy)
@@ -831,8 +745,6 @@ def can_control_resource_sharing(
context = _as_context(user_context)
kind = _validate_resource_kind(resource_kind)
identifier = _required_identifier(resource_id, code="invalid_resource_id")
- if _temporary_unrestricted_resource_bypass(context, kind):
- return True
with _connection(connection) as conn:
policy = _policy_row(conn, kind, identifier)
return _policy_allows_owner_control(context, policy)
diff --git a/storage/vault_service.py b/storage/vault_service.py
index 152fa6b8d..ea0f77c24 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -46,8 +46,6 @@ from storage.models import (
)
from storage.vault_addresses import derive_addresses
from storage.vault_crypto import Sealed
-from vibe.authorization import has_temporary_unrestricted_runtime_access
-
logger = logging.getLogger(__name__)
SKILL_TAG_PREFIX = "skill:"
@@ -1538,7 +1536,7 @@ def _require_request_secret_access(
"""Authorize a request before hydrating or mutating its member secrets."""
context = resolve_resource_access_context(user_context)
- if context.is_trusted_local or has_temporary_unrestricted_runtime_access(context):
+ if context.has_role("editor"):
return
member_names = _request_member_names(row)
if not member_names:
@@ -1551,7 +1549,7 @@ def _require_request_secret_access(
# Provision requests legitimately precede the secret. Only the paired
# instance owner may inspect or decide those owner-level requests.
if (
- (context.is_instance_owner or has_temporary_unrestricted_runtime_access(context))
+ context.is_instance_owner
and row.get("request_type") == "provision"
):
return
@@ -1789,7 +1787,7 @@ def _require_row(conn: Connection, name: str) -> dict[str, Any]:
def resolve_resource_access_context(user_context: Any = None):
- """Resolve request ACL context while preserving trusted local Vault use."""
+ """Resolve request context for Vault ACL checks."""
from storage import resource_access_service
@@ -1817,9 +1815,12 @@ def _require_secret_resource_management(conn: Connection, row: dict[str, Any], u
from storage import resource_access_service
+ context = resolve_resource_access_context(user_context)
+ if not context.is_instance_owner:
+ raise VaultSecretAccessError("Vault secret access is not permitted.")
resource_id = str(row.get("id") or "")
if not resource_id or not resource_access_service.can_manage_resource_acl(
- user_context,
+ context,
"vault_secret",
resource_id,
connection=conn,
@@ -1830,7 +1831,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.can_manage_instance or has_temporary_unrestricted_runtime_access(context):
+ if context.has_role("editor"):
return context
raise VaultSecretAccessError("Vault secret access is not permitted.")
@@ -1849,7 +1850,7 @@ def _require_secret_names_access(
management: bool = False,
) -> None:
context = resolve_resource_access_context(user_context)
- if context.is_trusted_local or has_temporary_unrestricted_runtime_access(context):
+ if context.has_role("editor"):
return
member_names = sorted({str(name) for name in names if str(name)})
if not member_names:
@@ -1885,7 +1886,7 @@ def _register_created_secret_resource_policy(conn: Connection, secret_id: str, u
from storage import resource_access_service
- if not (user_context.is_remote and user_context.is_active_organization_member and user_context.subject):
+ if not user_context.subject:
return
resource_access_service.ensure_resource_policy(
conn,
@@ -3831,10 +3832,7 @@ def list_requests(
query = query.where(vault_requests.c.request_type == request_type)
# Session and remote ACL filters run in Python, so apply the limit only after
# those filters or newer inaccessible rows could hide older visible requests.
- has_full_runtime_access = (
- context.is_trusted_local
- or has_temporary_unrestricted_runtime_access(context)
- )
+ has_full_runtime_access = context.has_role("editor")
requires_post_filter = session is not None or not has_full_runtime_access
if not requires_post_filter:
query = query.limit(limit)
@@ -4431,10 +4429,7 @@ def list_grants(
query = query.where(or_(vault_grants.c.session_id.is_(None), vault_grants.c.session_id == session_id))
context = resolve_resource_access_context(user_context)
rows = [dict(row) for row in conn.execute(query).mappings()]
- if not (
- context.is_trusted_local
- or has_temporary_unrestricted_runtime_access(context)
- ):
+ if not context.has_role("editor"):
accessible_rows: list[dict[str, Any]] = []
for row in rows:
try:
@@ -4871,14 +4866,17 @@ def _audit_snapshot_allows(context: Any, snapshot: dict[str, Any]) -> bool:
if not isinstance(resource, dict) or not str(resource.get("name") or "") or not str(resource.get("resource_id") or ""):
return False
policy = resource.get("policy")
- if not (
- resource_access_service.can_use_resource_policy_snapshot(context, policy)
- or resource_access_service.can_manage_resource_policy_snapshot(context, policy)
- ):
+ if not resource_access_service.can_use_resource_policy_snapshot(context, policy):
return False
return True
+def _audit_fast_path_allowed(context: Any) -> bool:
+ """Allow local Owner administration and validated remote Editor access."""
+
+ return context.is_instance_owner or (context.is_remote and context.has_role("editor"))
+
+
def _audit_reference_names_for_row(
conn: Connection,
row: dict[str, Any],
@@ -4959,10 +4957,7 @@ def _audit_secret_name_allowed(
str(secret_row.id),
connection=conn,
)
- allowed = bool(
- resource_access_service.can_use_resource_policy_snapshot(context, policy)
- or resource_access_service.can_manage_resource_policy_snapshot(context, policy)
- )
+ allowed = bool(resource_access_service.can_use_resource_policy_snapshot(context, policy))
else:
has_tombstone, policy = _deleted_audit_policy_snapshot(
conn,
@@ -4971,16 +4966,10 @@ def _audit_secret_name_allowed(
)
allowed = bool(
has_tombstone
- and (
- resource_access_service.can_use_resource_policy_snapshot(context, policy)
- or resource_access_service.can_manage_resource_policy_snapshot(context, policy)
- )
+ and resource_access_service.can_use_resource_policy_snapshot(context, policy)
)
if not has_tombstone:
- allowed = bool(
- context.is_instance_owner
- or has_temporary_unrestricted_runtime_access(context)
- )
+ allowed = bool(_audit_fast_path_allowed(context))
access_by_name[name] = allowed
return allowed
@@ -4996,7 +4985,7 @@ def _require_audit_row_access(
tombstone_policies: dict[str, tuple[bool, Any]] | None = None,
) -> None:
context = resolve_resource_access_context(user_context)
- if context.is_trusted_local or has_temporary_unrestricted_runtime_access(context):
+ if _audit_fast_path_allowed(context):
return
snapshot_present, snapshot = _audit_access_snapshot(row)
@@ -5013,8 +5002,7 @@ def _require_audit_row_access(
)
if not names:
if (
- context.is_instance_owner
- or has_temporary_unrestricted_runtime_access(context)
+ context.has_role("editor")
):
return
raise VaultSecretAccessError("Vault secret access is not permitted.")
@@ -5042,7 +5030,7 @@ def list_audit(
requested_limit = max(0, limit)
if requested_limit == 0:
return []
- if context.is_trusted_local or has_temporary_unrestricted_runtime_access(context):
+ if _audit_fast_path_allowed(context):
query = select(vault_audit).order_by(vault_audit.c.ts.desc(), vault_audit.c.id.desc())
if secret_name is not None:
query = query.where(vault_audit.c.secret_name == secret_name)
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index 9dba236e7..042675e86 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -27,7 +27,6 @@ from config import paths
from storage import project_access_service
from vibe.authorization import (
AuthorizationContext,
- has_temporary_unrestricted_runtime_access,
require_instance_role,
)
from storage.agent_session_rows import (
@@ -146,15 +145,11 @@ def _dumps_metadata(metadata: dict[str, Any]) -> str:
def _has_runtime_owner_access(context: AuthorizationContext) -> bool:
- """Return runtime owner-equivalent access without changing identity."""
-
- return context.is_instance_owner or has_temporary_unrestricted_runtime_access(context)
+ return context.is_instance_owner
def _include_local_details(context: AuthorizationContext) -> bool:
- """Expose runtime details only to local or temporarily admitted members."""
-
- return not context.is_remote or has_temporary_unrestricted_runtime_access(context)
+ return context.has_role("editor")
def list_sessions(
@@ -439,26 +434,20 @@ def create_session(
)
resource_context = resolve_resource_access_context(user_context)
- if (
- resource_context.is_remote
- and not has_temporary_unrestricted_runtime_access(resource_context)
- and not agent_name
- and not agent_id
- ):
- if agent_backend:
+ if not agent_name and not agent_id:
+ if agent_backend and not resource_context.has_role("editor"):
from core.vibe_agents import VibeAgentAccessError
raise VibeAgentAccessError("Agent access is not permitted.")
- else:
- default_agent = ensure_default_agent_access(
+ if not agent_backend and not resource_context.is_instance_owner:
+ # Validate the effective global default without pinning it into the
+ # Session. An empty selector must keep following the global default
+ # at dispatch time.
+ ensure_default_agent_access(
conn,
user_context=resource_context,
missing_is_error=True,
)
- assert default_agent is not None
- agent_id = default_agent.id
- agent_name = default_agent.name
- agent_backend = default_agent.backend
if agent_name or agent_id:
selected_agent = ensure_agent_selection_access(
@@ -657,16 +646,15 @@ def update_session(
agent_id=None if agent_id is _UNSET else agent_id,
user_context=resource_context,
)
- if (
- selected_agent is None
- and resource_context.is_remote
- and not has_temporary_unrestricted_runtime_access(resource_context)
- ):
- selected_agent = ensure_default_agent_access(
- conn,
- user_context=resource_context,
- missing_is_error=True,
- )
+ if selected_agent is None:
+ # Validate the effective default, but preserve the empty selector so
+ # future dispatch follows changes to the global default Agent.
+ if not resource_context.is_instance_owner:
+ ensure_default_agent_access(
+ conn,
+ user_context=resource_context,
+ missing_is_error=True,
+ )
if selected_agent is not None:
requested_backend = str(agent_backend or "").strip() if agent_backend is not _UNSET else ""
if requested_backend and requested_backend != selected_agent.backend:
@@ -688,8 +676,7 @@ def update_session(
derived_backend = True
if (
- resource_context.is_remote
- and not has_temporary_unrestricted_runtime_access(resource_context)
+ not resource_context.has_role("editor")
and agent_backend is not _UNSET
and bool(str(agent_backend or "").strip())
and selected_agent is None
diff --git a/tests/test_agent_organization_onboarding.py b/tests/test_agent_organization_onboarding.py
index 3f96d155a..9e478c440 100644
--- a/tests/test_agent_organization_onboarding.py
+++ b/tests/test_agent_organization_onboarding.py
@@ -7,7 +7,8 @@ import pytest
from core.vibe_agents import VibeAgentAccessError, VibeAgentStore
from storage import resource_access_service
-from tests.ui_server_test_helpers import csrf_headers, remote_peer, save_config
+from tests.ui_server_test_helpers import _remote_peer, _save_config
+from tests.ui_server_test_helpers import csrf_headers
from vibe import remote_access
from vibe.ui_server import app
@@ -118,9 +119,10 @@ def test_upgrade_onboarding_inventories_custom_and_system_agents_as_private(monk
user_context=_organization_context(subject="editor-1", instance_role="editor"),
)
}
- # Temporary full-access rollout (#1343): an active Organization member
- # may list every agent regardless of the published/scope/private intent.
- assert visible == {legacy.name, builtins[0].name, builtins[1].name}
+ # Editor access is still narrowed by each Agent ACL: the matching scope
+ # grant and public grant are visible, while the untouched private Agent
+ # remains hidden.
+ assert visible == {legacy.name, builtins[0].name}
finally:
store.close()
@@ -154,9 +156,9 @@ def test_fresh_install_onboarding_preserves_new_private_agent_and_authorizes_int
visible = store.list_agents(
user_context=_organization_context(subject="editor-1", instance_role="editor"),
)
- # Temporary full-access rollout (#1343): an active Organization member
- # sees both the published builtin and the still-private custom agent.
- assert {agent.name for agent in visible} == {builtin.name, custom.name}
+ # The scoped builtin is visible to this group; the private custom Agent
+ # remains owner-only until its ACL is changed.
+ assert {agent.name for agent in visible} == {builtin.name}
finally:
store.close()
@@ -166,11 +168,9 @@ def test_onboarding_preserves_existing_acl_revision(monkeypatch, tmp_path) -> No
store = VibeAgentStore()
try:
agent = store.create(name="revisioned", backend="codex")
- # Temporary full-access rollout (#1343): an active Organization member
- # may inventory and onboard, so the editor no longer raises here.
editor_context = _organization_context(subject="editor-1", instance_role="editor")
- assert store.organization_onboarding_inventory(user_context=editor_context)["counts"]
- store.onboard_organization_agents(user_context=editor_context)
+ with pytest.raises(VibeAgentAccessError):
+ store.organization_onboarding_inventory(user_context=editor_context)
store.onboard_organization_agents(user_context=_organization_context())
_apply_agent_intent(
@@ -208,7 +208,7 @@ def test_onboarding_preserves_existing_acl_revision(monkeypatch, tmp_path) -> No
def test_onboarding_publication_redacts_prompt_credentials_paths_and_config(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
config.remote_access.vibe_cloud.enabled = True
config.remote_access.vibe_cloud.instance_id = "inst_123"
config.remote_access.vibe_cloud.instance_secret = "paired-device-secret"
@@ -293,7 +293,7 @@ def test_agent_rename_and_delete_converge_in_full_resource_index(monkeypatch, tm
def test_owner_http_workflow_lists_and_onboards_agents_and_editor_is_admitted(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
store = VibeAgentStore()
try:
store.create(name="legacy-http", backend="codex", system_prompt="must-not-appear")
@@ -316,14 +316,14 @@ def test_owner_http_workflow_lists_and_onboards_agents_and_editor_is_admitted(mo
inventory = client.get(
"/api/agent-onboarding",
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
onboarded = client.post(
"/api/agent-onboarding",
json={},
headers=csrf_headers(client, "https://alex.avibe.bot"),
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
assert inventory.status_code == 200
@@ -375,9 +375,6 @@ def test_owner_http_workflow_lists_and_onboards_agents_and_editor_is_admitted(mo
denied = client.get(
"/api/agent-onboarding",
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
- # Temporary full-access rollout (#1343): an active Organization editor is
- # admitted to the onboarding surface too.
- assert denied.status_code == 200
- assert denied.get_json()["available"] is True
+ assert denied.status_code == 403
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index fd500eaee..e4935ad42 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -820,9 +820,10 @@ def test_task_show_missing_id_returns_guidance(tmp_path: Path) -> None:
assert payload["help_command"] == "vibe task list"
-def test_remote_task_add_is_rejected_without_persisting_definition(
+def test_remote_editor_task_add_persists_authorization_context(
tmp_path: Path,
monkeypatch,
+ capsys,
) -> None:
# ``patch.dict(..., clear=False)`` below pins only the five ids this test names, so
# the ORIGIN half of the contract (platform/channel/session_key/...) leaked in from
@@ -864,11 +865,14 @@ def test_remote_task_add_is_rejected_without_persisting_definition(
patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
patch("vibe.cli._task_store", return_value=store),
):
- result, payload = _capture_stderr_json(cli.cmd_task_add, args)
+ result = cli.cmd_task_add(args)
- assert result == 1
- assert payload["code"] == "remote_autonomous_harness_disabled"
- assert cli.ScheduledTaskStore(store_path).list_tasks() == []
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["definition"]["metadata"]["resource_user_context"][
+ "vibe_instance_role"
+ ] == "editor"
+ assert len(cli.ScheduledTaskStore(store_path).list_tasks()) == 1
def test_task_add_create_per_run_scope_id_records_session_scope_metadata(tmp_path: Path, capsys) -> None:
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index 16fc8dc7e..9020ae484 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -447,8 +447,9 @@ def test_watch_add_creates_shell_watch(tmp_path: Path, capsys) -> None:
assert payload["definition"]["retry_exit_codes"] == [75]
-def test_remote_watch_add_is_rejected_without_startup_or_persistence(
+def test_remote_editor_watch_add_starts_and_persists_authorization_context(
tmp_path: Path,
+ capsys,
) -> None:
store_path = tmp_path / "watches.json"
runtime_path = tmp_path / "watch_runtime.json"
@@ -489,23 +490,26 @@ def test_remote_watch_add_is_rejected_without_startup_or_persistence(
startup_calls: list[str] = []
- def unexpected_startup(*args, **kwargs):
+ def successful_startup(*args, **kwargs):
startup_calls.append(args[2])
- raise AssertionError("remote Watch must not start")
+ return _startup_ok(store, runtime_store, args[2])
with (
patch.dict(os.environ, caller_env, clear=False),
patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
patch("vibe.cli._watch_store", return_value=store),
patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
- patch("vibe.cli._wait_for_watch_startup", side_effect=unexpected_startup),
+ patch("vibe.cli._wait_for_watch_startup", side_effect=successful_startup),
):
- result, payload = _capture_stderr_json(cli.cmd_watch_add, args)
+ result = cli.cmd_watch_add(args)
- assert result == 1
- assert payload["code"] == "remote_autonomous_harness_disabled"
- assert ManagedWatchStore(store_path).list_watches() == []
- assert startup_calls == []
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["definition"]["metadata"]["resource_user_context"][
+ "vibe_instance_role"
+ ] == "editor"
+ assert len(ManagedWatchStore(store_path).list_watches()) == 1
+ assert len(startup_calls) == 1
def test_watch_add_create_per_run_scope_id_records_session_scope_metadata(tmp_path: Path, capsys) -> None:
diff --git a/tests/test_dock_api.py b/tests/test_dock_api.py
index 1db25900b..658bdd0d3 100644
--- a/tests/test_dock_api.py
+++ b/tests/test_dock_api.py
@@ -10,7 +10,7 @@ import pytest
from core.dock_store import BUILTIN_DOCK_IDS, DockError
from core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir
-from tests.ui_server_test_helpers import remote_peer, save_config
+from tests.ui_server_test_helpers import _remote_peer, _save_config
from vibe import api, ui_server
from vibe.ui_server import app
@@ -64,7 +64,7 @@ def _show(session_id: str) -> str:
def test_dock_default_is_builtins_only(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
result = api.get_dock()
@@ -76,7 +76,7 @@ def test_dock_default_is_builtins_only(monkeypatch, tmp_path):
def test_pin_appends_and_captures_title(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_pin", title="Sales Dashboard")
_make_show_page("ses_pin")
@@ -95,7 +95,7 @@ def test_pin_appends_and_captures_title(monkeypatch, tmp_path):
def test_pin_without_session_title_stores_empty_snapshot(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_plain") # IM-dispatch sessions persist title=None
_make_show_page("ses_plain")
@@ -106,7 +106,7 @@ def test_pin_without_session_title_stores_empty_snapshot(monkeypatch, tmp_path):
def test_pin_is_idempotent(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_dup", title="Once")
_make_show_page("ses_dup")
@@ -123,7 +123,7 @@ def test_pin_multiple_sessions_all_survive(monkeypatch, tmp_path):
# earlier one (the read-modify-write is serialized under a lock so concurrent
# pins can't lost-update).
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
for sid in ("ses_a", "ses_b", "ses_c"):
_seed_session(sid, title=sid.upper())
_make_show_page(sid)
@@ -139,7 +139,7 @@ def test_pin_rejects_when_install_budget_is_full(monkeypatch, tmp_path):
# pins, else a pin can grow ``pins`` past what a read would keep and the
# just-added page is silently dropped on the next load.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
monkeypatch.setattr("core.dock_store.MAX_PINNED_PAGES", 1) # room for exactly one pin
for sid in ("ses_full1", "ses_full2"):
_seed_session(sid)
@@ -159,7 +159,7 @@ def test_load_dock_clamps_oversized_corrupt_pins(monkeypatch, tmp_path):
from core.dock_store import DOCK_STATE_KEY
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
monkeypatch.setattr("core.dock_store.MAX_PINNED_PAGES", 1) # room for exactly one pin
set_state_meta(
DOCK_STATE_KEY,
@@ -190,7 +190,7 @@ def test_reconcile_does_not_readd_undocked_builtin(monkeypatch, tmp_path):
from core.dock_store import DOCK_STATE_KEY
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
set_state_meta(
DOCK_STATE_KEY,
{
@@ -213,7 +213,7 @@ def test_legacy_full_order_doc_still_valid(monkeypatch, tmp_path):
from core.dock_store import DOCK_STATE_KEY
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
order = ["files", "terminal", "editor", "library", _show("ses_keep")]
set_state_meta(
DOCK_STATE_KEY,
@@ -229,7 +229,7 @@ def test_legacy_full_order_doc_still_valid(monkeypatch, tmp_path):
def test_pin_unknown_show_page_is_404(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_nopage") # session exists but has no Show Page
with pytest.raises(DockError) as excinfo:
@@ -239,7 +239,7 @@ def test_pin_unknown_show_page_is_404(monkeypatch, tmp_path):
def test_pin_malformed_session_id_raises_show_page_error(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
with pytest.raises(ShowPageError) as excinfo:
api.pin_dock_show_page("bad id!")
@@ -248,7 +248,7 @@ def test_pin_malformed_session_id_raises_show_page_error(monkeypatch, tmp_path):
def test_unpin_removes_and_is_idempotent(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_u", title="Bye")
_make_show_page("ses_u")
api.pin_dock_show_page("ses_u")
@@ -267,7 +267,7 @@ def test_unpin_removes_and_is_idempotent(monkeypatch, tmp_path):
def test_set_order_persists_valid_permutation(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_o", title="Ordered")
_make_show_page("ses_o")
api.pin_dock_show_page("ses_o")
@@ -284,7 +284,7 @@ def test_set_order_accepts_library_builtin(monkeypatch, tmp_path):
# includes it is accepted and persists — the same reorder path #892 shipped,
# now covering the 4th built-in.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_lib", title="Ordered")
_make_show_page("ses_lib")
api.pin_dock_show_page("ses_lib")
@@ -300,7 +300,7 @@ def test_set_order_rejects_unknown_id(monkeypatch, tmp_path):
# Subset validation (§7.1c) still rejects an id that is not a real dock item,
# so a stale client can't resurrect a pin removed by another tab.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
with pytest.raises(DockError) as excinfo:
api.set_dock_order(["files", "terminal", "editor", "show:ghost"])
@@ -312,7 +312,7 @@ def test_set_order_accepts_proper_subset(monkeypatch, tmp_path):
# built-in (undocking it) is accepted and persists — no longer rejected as a
# non-set-equal order.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
dock = api.set_dock_order(["files", "terminal"])["dock"] # editor + library undocked
assert dock["order"] == ["files", "terminal"]
@@ -323,7 +323,7 @@ def test_set_order_accepts_empty_dock(monkeypatch, tmp_path):
# Undocking everything (including all built-ins) is legal — the empty Dock is
# a valid saved state (the popover shows the App Library hint client-side).
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
dock = api.set_dock_order([])["dock"]
assert dock["order"] == []
@@ -336,7 +336,7 @@ def test_set_order_rejects_stale_known(monkeypatch, tmp_path):
# silently undock that newer pin (which install docked by default). Subset
# validation alone would have accepted the omission.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_new", title="New")
_make_show_page("ses_new")
api.pin_dock_show_page("ses_new") # server now has show:ses_new installed + docked
@@ -354,7 +354,7 @@ def test_set_order_with_matching_known_allows_intentional_undock(monkeypatch, tm
# INTENTIONAL undock (distinct from a stale omission) and is accepted — the
# page stays installed.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_k", title="K")
_make_show_page("ses_k")
api.pin_dock_show_page("ses_k")
@@ -369,7 +369,7 @@ def test_undocked_builtin_persists_across_reload(monkeypatch, tmp_path):
# An undocked built-in stays undocked across a reload — reconcile never
# re-adds it (the whole point of built-ins being undockable now).
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
api.set_dock_order(["files", "terminal", "editor"]) # library undocked
assert "library" not in api.get_dock()["dock"]["order"]
@@ -380,7 +380,7 @@ def test_installed_page_can_be_undocked_but_stays_installed(monkeypatch, tmp_pat
# ``order``) while REMAINING installed (kept in ``pins``) — install and dock
# are separate. Its ``show:`` id is absent from the order but the pin persists.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_keep", title="Keep")
_make_show_page("ses_keep")
api.pin_dock_show_page("ses_keep") # installs + docks
@@ -397,7 +397,7 @@ def test_delete_pin_cascades_out_of_order(monkeypatch, tmp_path):
# DELETE pins (uninstall) removes the page from BOTH pins and order, leaving
# the other docked tiles intact.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_del", title="Del")
_make_show_page("ses_del")
api.pin_dock_show_page("ses_del")
@@ -411,7 +411,7 @@ def test_delete_pin_cascades_out_of_order(monkeypatch, tmp_path):
def test_set_order_rejects_duplicates(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
with pytest.raises(DockError) as excinfo:
api.set_dock_order(["files", "files", "terminal", "editor"])
@@ -420,7 +420,7 @@ def test_set_order_rejects_duplicates(monkeypatch, tmp_path):
def test_set_order_rejects_non_list(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
with pytest.raises(DockError) as excinfo:
api.set_dock_order("files,terminal,editor")
@@ -429,7 +429,7 @@ def test_set_order_rejects_non_list(monkeypatch, tmp_path):
def test_dock_route_round_trip_via_client(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
response = app.test_client().get("/api/dock", base_url="http://127.0.0.1:5123")
@@ -444,12 +444,12 @@ def test_dock_route_blocked_for_remote_without_session(monkeypatch, tmp_path):
remote request without a session gets the login-required API contract, never
an OAuth side effect or an unauthenticated native response."""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
get_resp = app.test_client().get(
"/api/dock",
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
follow_redirects=False,
)
assert get_resp.status_code == 401
@@ -461,7 +461,7 @@ def test_dock_route_blocked_for_remote_without_session(monkeypatch, tmp_path):
post_resp = app.test_client().post(
"/api/dock/pins",
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
json={"session_id": "ses_x"},
follow_redirects=False,
)
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index cca62cfde..e691da1db 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -3,313 +3,220 @@ import pytest
from vibe.authorization import (
AuthorizationContext,
InstanceAuthorizationError,
- REMOTE_HTTP_ALLOWED,
+ _EDITOR_HTTP_NAMESPACES,
+ _VIEWER_HTTP_NAMESPACES,
can_receive_workbench_event,
context_from_session_payload,
- has_temporary_unrestricted_org_access,
http_authorization_policy,
+ instance_owner_context,
require_instance_role,
- trusted_local_context,
)
-def _active_org_context(role: str) -> AuthorizationContext:
+def _context(role: str, *, remote: bool, source: str = "owner") -> AuthorizationContext:
return AuthorizationContext(
instance_role=role,
subject=f"{role}-subject",
- instance_access_source="organization_group",
- organization_id="org-1",
- organization_member_id=f"membership-{role}",
- organization_role="member",
- is_remote=True,
- )
-
-
-def _non_member_context(role: str = "owner") -> AuthorizationContext:
- return AuthorizationContext(
- instance_role=role,
- instance_access_source="owner",
- is_remote=True,
+ instance_access_source=source,
+ is_remote=remote,
)
-def test_non_member_remote_roles_keep_rank_without_local_machine_capabilities() -> None:
- viewer = _non_member_context("viewer")
- editor = _non_member_context("editor")
- owner = _non_member_context("owner")
+def test_capabilities_depend_on_instance_role_not_origin_or_membership() -> None:
+ for role in ("viewer", "editor", "owner"):
+ local = _context(role, remote=False)
+ remote = _context(role, remote=True, source="organization_group")
+ assert local.capability_projection() == remote.capability_projection()
- assert viewer.can_read_instance is True
- assert viewer.can_chat is False
- assert viewer.can_use_cloud_asr is False
- assert editor.can_read_instance is True
- assert editor.can_chat is True
- assert editor.can_use_cloud_asr is True
- assert editor.can_manage_projects is False
- assert owner.can_chat is True
- assert owner.can_use_cloud_asr is True
- assert owner.can_manage_projects is True
- assert owner.can_manage_agents is True
- assert owner.can_use_terminal is False
- assert owner.can_use_files is False
- assert owner.can_use_system is False
- assert trusted_local_context().can_manage_instance is True
- assert trusted_local_context().can_chat is True
- assert trusted_local_context().can_use_cloud_asr is False
+ viewer = _context("viewer", remote=True, source="organization_group")
+ editor = _context("editor", remote=True, source="organization_group")
+ owner = _context("owner", remote=True, source="organization_group")
+ assert viewer.can_read_instance and not viewer.can_chat
+ assert not viewer.can_use_resource("agent")
+ assert editor.can_chat and editor.can_use_resource("agent")
+ assert editor.can_use_files and editor.can_use_terminal
+ assert not editor.can_manage_instance
+ assert owner.can_manage_instance and owner.can_use_system
-def test_temporary_org_access_projects_runtime_rights_without_fake_local_capabilities() -> None:
+def test_organization_membership_does_not_elevate_role() -> None:
member = AuthorizationContext(
instance_role="viewer",
subject="member-1",
- organization_id="org-1",
- organization_member_id="membership-1",
- organization_role="member",
instance_access_source="organization_group",
- is_remote=True,
- )
-
- assert has_temporary_unrestricted_org_access(member) is True
- assert member.capability_projection() == {
- "is_instance_owner": False,
- "can_read_instance": True,
- "can_chat": True,
- "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": False,
- "can_use_terminal": False,
- "can_use_files": False,
- "can_use_system": False,
- }
- assert has_temporary_unrestricted_org_access(
- AuthorizationContext(
- **{
- **member.__dict__,
- "organization_member_id": None,
- }
- )
- ) is False
- assert has_temporary_unrestricted_org_access(
- AuthorizationContext(
- **{
- **member.__dict__,
- "instance_access_source": "show_page_email",
- }
- )
- ) is False
-
-
-def test_temporary_org_members_receive_show_events_at_viewer_instance_role() -> None:
- member = AuthorizationContext(
- instance_role="viewer",
organization_id="org-1",
organization_member_id="membership-1",
- organization_role="member",
- instance_access_source="organization_group",
+ organization_role="admin",
is_remote=True,
)
- non_member = AuthorizationContext(
- instance_role="viewer",
- instance_access_source="email",
- is_remote=True,
- )
-
- assert can_receive_workbench_event(member, "show.event") is True
- assert can_receive_workbench_event(non_member, "show.event") is False
-
-
[email protected]("role", ["viewer", "editor", "owner"])
-def test_active_org_members_bypass_role_splits_for_known_runtime_resources(role) -> None:
- context = _active_org_context(role)
- expected = {"agent": True, "skill": True, "vault_secret": True, "show_page": True}
+ assert member.is_active_organization_member
+ assert member.capability_projection()["can_chat"] is False
+ assert member.capability_projection()["can_manage_instance"] is False
- assert {kind: context.can_use_resource(kind) for kind in expected} == expected
- assert context.can_manage_instance is True
- assert context.can_use_resource("future_resource") is False
-
-def test_context_uses_role_not_diagnostic_source_for_owner() -> None:
+def test_context_from_session_payload_keeps_role_and_acl_claims() -> None:
context = context_from_session_payload(
{
"sub": "user-1",
- "email": "[email protected]",
- "vibe_instance_id": "inst-1",
"vibe_instance_role": "editor",
- "vibe_instance_access_source": "owner",
+ "vibe_instance_access_source": "organization_group",
"vibe_organization_id": "org-1",
"vibe_organization_member_id": "membership-1",
"vibe_organization_role": "member",
- "vibe_instance_authorization_revision": 0,
+ "vibe_group_ids": ["group-a"],
}
)
-
- assert context.is_instance_owner is False
- assert context.can_chat is True
- assert context.can_manage_instance is True
- assert context.authorization_revision == 0
-
-
-def test_malformed_role_context_fails_closed() -> None:
- context = context_from_session_payload(
- {"vibe_instance_role": "admin", "vibe_instance_access_source": "owner"}
- )
-
- assert context.is_remote is True
- assert context.can_read_instance is False
+ assert context.instance_role == "editor"
+ assert context.group_ids == frozenset({"group-a"})
+ assert context.can_chat
+ assert not context.can_manage_instance
-def test_show_page_email_context_requires_and_matches_one_exact_target() -> None:
+def test_show_page_email_context_is_exactly_page_scoped() -> None:
context = context_from_session_payload(
{
"sub": "guest-1",
- "email": "[email protected]",
- "vibe_instance_id": "inst-1",
- "vibe_instance_role": "viewer",
- "vibe_instance_access_source": "show_page_email",
- "vibe_show_page_id": "session-one",
- "vibe_instance_authorization_revision": 0,
- }
- )
-
- assert context.can_use_show_page("session-one") is True
- assert context.can_use_show_page("session-two") is False
- assert context.show_page_id == "session-one"
-
- missing_target = context_from_session_payload(
- {
"vibe_instance_role": "viewer",
"vibe_instance_access_source": "show_page_email",
- }
- )
- broader_target = context_from_session_payload(
- {
- "vibe_instance_role": "editor",
- "vibe_instance_access_source": "email",
"vibe_show_page_id": "session-one",
- "vibe_organization_id": "org-1",
- "vibe_organization_member_id": "membership-1",
- "vibe_organization_role": "member",
}
)
- assert missing_target.can_read_instance is False
- assert broader_target.can_read_instance is True
- assert broader_target.can_chat is True
- assert broader_target.can_use_show_page("session-one") is True
- assert broader_target.can_use_show_page("session-two") is False
-
- elevated_role = context_from_session_payload(
- {
- "vibe_instance_role": "editor",
- "vibe_instance_access_source": "show_page_email",
- "vibe_show_page_id": "session-one",
- }
+ assert context.can_use_show_page("session-one")
+ assert not context.can_use_show_page("session-two")
+ assert not context.can_chat
+
+
+def test_http_policy_is_role_only_and_unknown_api_routes_fail_closed() -> None:
+ editor_routes = (
+ ("GET", "/api/agents"),
+ ("GET", "/api/files/list"),
+ ("PUT", "/api/files/write"),
+ ("GET", "/api/dock"),
+ ("PUT", "/api/dock/order"),
+ ("GET", "/api/skills"),
+ ("GET", "/api/vault/secrets"),
+ ("GET", "/api/harness/bootstrap"),
+ ("PATCH", "/api/harness/tasks/task-1"),
+ ("DELETE", "/api/harness/watches/watch-1"),
+ ("GET", "/api/browse/favorites"),
)
- assert elevated_role.can_read_instance is False
- assert elevated_role.can_use_show_page("session-one") is False
+ for method, path in editor_routes:
+ assert http_authorization_policy(method, path).minimum_role == "editor"
+ for method, path in (("GET", "/api/future-owner-capability"), ("POST", "/api/control")):
+ assert http_authorization_policy(method, path).minimum_role == "owner"
-def test_http_policy_uses_role_authorization_without_local_only_transport_gates() -> None:
- for method, path in (
- ("GET", "/api/projects"),
- ("GET", "/api/workbench/projects-bootstrap"),
- ("GET", "/api/sessions"),
- ("POST", "/api/config"),
- ("POST", "/api/files/upload"),
- ("POST", "/api/remote-access/vibe-cloud/pair"),
- ("GET", "/api/future-owner-capability"),
- ):
- assert http_authorization_policy(method, path).remote_access == REMOTE_HTTP_ALLOWED
+ assert http_authorization_policy("GET", "/api/org/context").minimum_role == "viewer"
+ assert http_authorization_policy("GET", "/show/ses-1/").minimum_role == "viewer"
-def test_http_policy_preserves_safe_remote_reads_and_show_routes() -> None:
- assert http_authorization_policy("GET", "/api/org/context").remote_access == REMOTE_HTTP_ALLOWED
- assert http_authorization_policy("GET", "/api/cloud-management/session").remote_access == REMOTE_HTTP_ALLOWED
- assert http_authorization_policy("GET", "/show/ses-1/").remote_access == REMOTE_HTTP_ALLOWED
- assert http_authorization_policy("POST", "/show/ses-1/__show/events").remote_access == REMOTE_HTTP_ALLOWED
+def test_advertised_capability_namespaces_cover_current_and_future_routes() -> None:
+ """Every advertised Editor/Viewer surface is a namespace, not a case list.
+ A newly added Skills, Vault, Harness, Files, Dock, Terminal, or Web Push
+ route must inherit the same Instance role as the rest of that capability.
+ Owner-only Agent create/import and unknown APIs stay fail-closed.
+ """
-def test_temporary_runtime_signal_requires_membership_while_role_guard_uses_rank() -> None:
- member = AuthorizationContext(
- instance_role="viewer",
- subject="member-1",
- organization_id="org-1",
- organization_member_id="membership-1",
- organization_role="member",
- instance_access_source="organization_group",
- is_remote=True,
+ assert _EDITOR_HTTP_NAMESPACES == (
+ "/api/skills",
+ "/api/vault",
+ "/api/files",
+ "/api/dock",
+ "/api/harness",
+ "/api/terminal",
)
- non_member = AuthorizationContext(
- instance_role="owner",
- subject="owner-1",
- instance_access_source="owner",
- is_remote=True,
+ assert _VIEWER_HTTP_NAMESPACES == (
+ "/api/memory",
+ "/api/web-push",
)
- assert has_temporary_unrestricted_org_access(member) is True
- assert has_temporary_unrestricted_org_access(non_member) is False
- assert require_instance_role(member, "owner") is member
- assert require_instance_role(non_member, "owner") is non_member
-
-def test_temporary_runtime_route_matrix_is_not_a_capability_projection() -> None:
- member = AuthorizationContext(
- instance_role="viewer",
- organization_id="org-1",
- organization_member_id="membership-1",
- organization_role="member",
- instance_access_source="organization_group",
- is_remote=True,
+ editor_examples = (
+ ("POST", "/api/skills"),
+ ("POST", "/api/skills/update"),
+ ("POST", "/api/skills/preview"),
+ ("POST", "/api/skills/upload"),
+ ("DELETE", "/api/skills/demo"),
+ ("POST", "/api/skills/future-mutation"),
+ ("POST", "/api/vault/secrets"),
+ ("PATCH", "/api/vault/secrets/OPENAI_API_KEY"),
+ ("DELETE", "/api/vault/secrets/OPENAI_API_KEY"),
+ ("POST", "/api/vault/requests/access"),
+ ("POST", "/api/vault/grants"),
+ ("DELETE", "/api/vault/grants/grant-1"),
+ ("PATCH", "/api/vault/settings"),
+ ("POST", "/api/vault/future-mutation"),
+ ("POST", "/api/harness/tasks"),
+ ("PATCH", "/api/harness/watches/watch-1"),
+ ("GET", "/api/files/list"),
+ ("PUT", "/api/files/write"),
+ ("POST", "/api/dock/pins"),
+ ("GET", "/api/browse/favorites"),
+ ("GET", "/api/asr/status"),
+ ("POST", "/api/asr/transcribe"),
+ ("POST", "/api/asr/telemetry"),
+ ("POST", "/api/sessions/session-1/messages"),
+ ("POST", "/api/sessions/session-1/attachments"),
+ ("POST", "/api/sessions/session-1/cancel"),
)
- assert member.capability_projection()["can_use_system"] is False
- assert member.capability_projection()["can_use_files"] is False
- assert member.capability_projection()["can_use_terminal"] is False
-
-
-def test_workbench_event_policy_filters_privileged_and_unknown_events() -> None:
- viewer = _active_org_context("viewer")
- editor = _active_org_context("editor")
- owner = _active_org_context("owner")
- non_member = _non_member_context()
- local = trusted_local_context()
-
- assert can_receive_workbench_event(viewer, "authorization.changed") is True
- assert can_receive_workbench_event(viewer, "message.new") is True
- assert can_receive_workbench_event(viewer, "workbench.events.bridge.status") is True
- assert can_receive_workbench_event(viewer, "queue.updated") is True
- assert can_receive_workbench_event(editor, "queue.updated") is True
- assert can_receive_workbench_event(viewer, "vaults.updated") is True
- assert can_receive_workbench_event(editor, "definitions.updated") is True
- assert can_receive_workbench_event(owner, "vaults.updated") is True
- assert can_receive_workbench_event(non_member, "runs.updated") is False
- assert can_receive_workbench_event(non_member, "vaults.updated") is False
- assert can_receive_workbench_event(non_member, "definitions.updated") is False
- assert can_receive_workbench_event(local, "runs.updated") is True
- assert can_receive_workbench_event(viewer, "runs.updated") is True
- assert can_receive_workbench_event(editor, "runs.updated") is True
- assert can_receive_workbench_event(owner, "runs.updated") is True
- assert can_receive_workbench_event(viewer, "future.management.event") is False
- assert can_receive_workbench_event(owner, "future.management.event") is False
-
-
-def test_service_role_guard_defaults_local_and_denies_remote_viewer() -> None:
- assert require_instance_role(None, "owner").is_trusted_local is True
-
- viewer = _non_member_context("viewer")
- try:
- require_instance_role(viewer, "editor")
- except InstanceAuthorizationError as error:
- assert error.code == "instance_access_forbidden"
- else:
- raise AssertionError("viewer unexpectedly passed the editor service guard")
+ for method, path in editor_examples:
+ assert http_authorization_policy(method, path).minimum_role == "editor", path
+
+ viewer_examples = (
+ ("GET", "/api/memory/settings"),
+ ("PATCH", "/api/memory/settings"),
+ ("POST", "/api/memory/runtime/restart"),
+ ("POST", "/api/memory/future-capability"),
+ ("POST", "/api/sessions/session-1/mark-read"),
+ ("DELETE", "/api/terminal/term-1"),
+ ("GET", "/api/web-push/status"),
+ ("POST", "/api/web-push/status"),
+ ("GET", "/api/web-push/vapid-public-key"),
+ ("POST", "/api/web-push/subscriptions"),
+ ("DELETE", "/api/web-push/subscriptions"),
+ ("POST", "/api/web-push/test"),
+ ("POST", "/api/web-push/future-mutation"),
+ )
+ for method, path in viewer_examples:
+ assert http_authorization_policy(method, path).minimum_role == "viewer", path
+
+ owner_examples = (
+ ("POST", "/api/agents"),
+ ("POST", "/api/agents/import"),
+ ("PATCH", "/api/agents/demo"),
+ ("DELETE", "/api/agents/demo"),
+ ("GET", "/api/future-owner-capability"),
+ ("POST", "/api/browse"),
+ ("POST", "/api/browse/mkdir"),
+ )
+ for method, path in owner_examples:
+ assert http_authorization_policy(method, path).minimum_role == "owner", path
+
+
+def test_workbench_events_follow_role_boundaries() -> None:
+ viewer = _context("viewer", remote=True)
+ editor = _context("editor", remote=True)
+ owner = _context("owner", remote=True)
+ assert can_receive_workbench_event(viewer, "message.new")
+ assert not can_receive_workbench_event(viewer, "queue.updated")
+ assert can_receive_workbench_event(editor, "queue.updated")
+ assert not can_receive_workbench_event(editor, "runs.updated")
+ assert can_receive_workbench_event(owner, "runs.updated")
+ assert not can_receive_workbench_event(viewer, "future.management.event")
+
+
+def test_service_role_guard_defaults_to_instance_owner() -> None:
+ local = require_instance_role(None, "owner")
+ assert local.instance_role == "owner"
+ assert local.is_instance_owner
+ with pytest.raises(InstanceAuthorizationError):
+ require_instance_role(_context("viewer", remote=True), "editor")
def test_session_service_mutations_recheck_instance_role() -> None:
from storage import workbench_sessions_service
- viewer = _non_member_context("viewer")
+ viewer = _context("viewer", remote=True)
with pytest.raises(InstanceAuthorizationError):
workbench_sessions_service.create_session(
None,
@@ -317,49 +224,3 @@ def test_session_service_mutations_recheck_instance_role() -> None:
agent_backend="codex",
authorization_context=viewer,
)
- with pytest.raises(InstanceAuthorizationError):
- workbench_sessions_service.update_session(
- None,
- "ses-1",
- authorization_context=viewer,
- )
- with pytest.raises(InstanceAuthorizationError):
- workbench_sessions_service.archive_session(
- None,
- "ses-1",
- authorization_context=viewer,
- )
-
-
-def test_project_service_mutations_require_owner() -> None:
- from storage import projects_service
-
- editor = _non_member_context("editor")
- with pytest.raises(InstanceAuthorizationError):
- projects_service.create_project(
- None,
- "/tmp",
- authorization_context=editor,
- )
- with pytest.raises(InstanceAuthorizationError):
- projects_service.update_project(
- None,
- "proj-1",
- authorization_context=editor,
- )
- with pytest.raises(InstanceAuthorizationError):
- projects_service.archive_project(
- None,
- "proj-1",
- authorization_context=editor,
- )
-
-
-def test_session_fork_service_requires_editor() -> None:
- from core.services.session_fork import reserve_forked_session
-
- with pytest.raises(InstanceAuthorizationError):
- reserve_forked_session(
- source_session_id="ses-1",
- authorization_context=_non_member_context("viewer"),
- )
diff --git a/tests/test_project_access_service.py b/tests/test_project_access_service.py
index 0eeb9b679..01f9ad89d 100644
--- a/tests/test_project_access_service.py
+++ b/tests/test_project_access_service.py
@@ -6,7 +6,7 @@ from storage import project_access_service, projects_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import project_access_bindings, project_access_policies
-from vibe.authorization import AuthorizationContext, trusted_local_context
+from vibe.authorization import AuthorizationContext, instance_owner_context
def _context(
@@ -164,7 +164,7 @@ def test_restricted_empty_bindings_is_owner_only(tmp_path) -> None:
_intent(project["id"], 1),
)
assert project_access_service.can_read_project(conn, _context("editor"), project["id"]) is False
- assert project_access_service.can_read_project(conn, trusted_local_context(), project["id"]) is True
+ assert project_access_service.can_read_project(conn, instance_owner_context(), project["id"]) is True
assert project_access_service.can_manage_project(conn, _context("owner"), project["id"]) is True
@@ -299,7 +299,7 @@ def test_archived_project_denies_non_owner_effective_roles(tmp_path) -> None:
) is False
assert project_access_service.get_effective_project_role(
conn,
- trusted_local_context(),
+ instance_owner_context(),
project["id"],
) == "owner"
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.py
index ebfd722fc..32a8c9ba2 100644
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@ -1364,6 +1364,93 @@ def test_report_runtime_status_replaces_normalized_active_hostnames(monkeypatch,
}
+def test_report_runtime_status_backfills_instance_kind_once(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ cloud = config.remote_access.vibe_cloud
+ cloud.backend_url = "https://backend.test"
+ cloud.instance_secret = "instance-secret"
+ config.save()
+ monkeypatch.setattr(remote_access, "runtime_status_payload", lambda *args, **kwargs: {"event": "heartbeat"})
+ monkeypatch.setattr(
+ remote_access,
+ "_json_request",
+ lambda *args, **kwargs: {"ok": True, "instance_kind": "organization"},
+ )
+ real_save_config = remote_access.api.save_config
+ saves = []
+
+ def tracked_save_config(payload, **kwargs):
+ saves.append(payload)
+ return real_save_config(payload, **kwargs)
+
+ monkeypatch.setattr(remote_access.api, "save_config", tracked_save_config)
+
+ assert remote_access.report_runtime_status(config)["ok"] is True
+ assert V2Config.load().remote_access.vibe_cloud.instance_kind == "organization"
+ assert remote_access.report_runtime_status(V2Config.load())["ok"] is True
+ assert saves == [
+ {"remote_access": {"vibe_cloud": {"instance_kind": "organization"}}}
+ ]
+
+
[email protected]("reported_kind", [None, "enterprise", "", 7])
+def test_report_runtime_status_ignores_invalid_instance_kind(
+ monkeypatch,
+ tmp_path,
+ reported_kind,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ cloud = config.remote_access.vibe_cloud
+ cloud.backend_url = "https://backend.test"
+ cloud.instance_secret = "instance-secret"
+ cloud.instance_kind = "personal"
+ config.save()
+ monkeypatch.setattr(remote_access, "runtime_status_payload", lambda *args, **kwargs: {"event": "heartbeat"})
+ monkeypatch.setattr(
+ remote_access,
+ "_json_request",
+ lambda *args, **kwargs: {"ok": True, "instance_kind": reported_kind},
+ )
+ monkeypatch.setattr(
+ remote_access.api,
+ "save_config",
+ lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("invalid kind must not persist")),
+ )
+
+ assert remote_access.report_runtime_status(config)["ok"] is True
+ assert V2Config.load().remote_access.vibe_cloud.instance_kind == "personal"
+
+
+def test_report_runtime_status_does_not_backfill_a_replaced_instance(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ cloud = config.remote_access.vibe_cloud
+ cloud.backend_url = "https://backend.test"
+ cloud.instance_secret = "instance-secret"
+ config.save()
+ monkeypatch.setattr(remote_access, "runtime_status_payload", lambda *args, **kwargs: {"event": "heartbeat"})
+
+ def replace_instance_before_response(*args, **kwargs):
+ current = V2Config.load()
+ current.remote_access.vibe_cloud.instance_id = "inst_replacement"
+ current.save()
+ return {"ok": True, "instance_kind": "organization"}
+
+ monkeypatch.setattr(remote_access, "_json_request", replace_instance_before_response)
+ monkeypatch.setattr(
+ remote_access.api,
+ "save_config",
+ lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("stale heartbeat must not persist")),
+ )
+
+ assert remote_access.report_runtime_status(config)["ok"] is True
+ persisted = V2Config.load().remote_access.vibe_cloud
+ assert persisted.instance_id == "inst_replacement"
+ assert persisted.instance_kind == ""
+
+
@pytest.mark.parametrize(
"response",
[
@@ -1445,6 +1532,7 @@ def test_pair_persists_with_locked_incremental_config_save(monkeypatch) -> None:
"_json_request",
lambda *args, **kwargs: {
"instance_id": "inst_123",
+ "instance_kind": "organization",
"client_id": "vr_client_123",
"issuer": "https://backend.test",
"authorization_endpoint": "https://backend.test/oauth/authorize",
@@ -1468,10 +1556,73 @@ def test_pair_persists_with_locked_incremental_config_save(monkeypatch) -> None:
assert set(save_payloads[0]) == {"remote_access"}
cloud_payload = save_payloads[0]["remote_access"]["vibe_cloud"]
assert cloud_payload["enabled"] is True
+ assert cloud_payload["instance_kind"] == "organization"
assert cloud_payload["tunnel_token"] == "tunnel-token"
assert cloud_payload["session_secret"]
[email protected]("reported_kind", [None, "enterprise"])
+def test_pair_accepts_legacy_or_invalid_instance_kind_as_unknown(monkeypatch, reported_kind) -> None:
+ config = _config()
+ save_payloads = []
+ response = {
+ "instance_id": "inst_456",
+ "client_id": "vr_client_456",
+ "issuer": "https://backend.test",
+ "authorization_endpoint": "https://backend.test/oauth/authorize",
+ "token_endpoint": "https://backend.test/oauth/token",
+ "jwks_uri": "https://backend.test/oauth/jwks.json",
+ "public_url": "https://new.avibe.bot",
+ "redirect_uri": "https://new.avibe.bot/auth/callback",
+ "tunnel_token": "tunnel-token",
+ "instance_secret": "instance-secret",
+ }
+ if reported_kind is not None:
+ response["instance_kind"] = reported_kind
+ monkeypatch.setattr(remote_access, "_json_request", lambda *args, **kwargs: response)
+ monkeypatch.setattr(remote_access.api, "save_config", lambda payload: save_payloads.append(payload) or config)
+ monkeypatch.setattr(remote_access, "start", lambda next_config: {"ok": True})
+ monkeypatch.setattr(remote_access, "status", lambda next_config=None: {"ok": True})
+ monkeypatch.setattr(remote_access, "report_runtime_status", lambda *args, **kwargs: {"ok": True})
+
+ assert remote_access.pair("vrp_test", "https://backend.test")["ok"] is True
+ assert save_payloads[0]["remote_access"]["vibe_cloud"]["instance_kind"] == ""
+
+
+def test_session_projects_instance_kind_for_local_and_authenticated_remote(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.instance_kind = "organization"
+ config.save()
+
+ local = ui_server.app.test_client().get(
+ "/api/session",
+ base_url="http://localhost",
+ )
+ assert local.get_json()["instance_kind"] == "organization"
+
+ remote = ui_server.app.test_client()
+ remote.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ _session_cookie(config),
+ domain="alex.avibe.bot",
+ )
+ authenticated = remote.get(
+ "/api/session",
+ base_url="https://alex.avibe.bot",
+ )
+ assert authenticated.get_json()["instance_kind"] == "organization"
+
+ unauthenticated = ui_server.app.test_client().get(
+ "/api/session",
+ base_url="https://alex.avibe.bot",
+ )
+ assert "instance_kind" not in unauthenticated.get_json()
+
+
def test_pair_reports_success_when_connector_start_fails(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _config()
diff --git a/tests/test_resource_access_service.py b/tests/test_resource_access_service.py
index 81e6bb623..b3c37760e 100644
--- a/tests/test_resource_access_service.py
+++ b/tests/test_resource_access_service.py
@@ -56,7 +56,7 @@ def _seed_policies(connection) -> None:
)
-def test_active_org_members_bypass_resource_acl_without_changing_unknown_kind_fail_closed(tmp_path) -> None:
+def test_resource_acl_is_enforced_for_editors_and_unknown_kinds_fail_closed(tmp_path) -> None:
db = tmp_path / "vibe.sqlite"
run_migrations(db)
engine = create_sqlite_engine(db)
@@ -64,25 +64,18 @@ def test_active_org_members_bypass_resource_acl_without_changing_unknown_kind_fa
with engine.begin() as connection:
_seed_policies(connection)
- owner = _context("owner-1")
+ owner = _context("owner-1", instance_role="owner", access_source="owner")
engineering_member = _context("member-2", group_ids=frozenset({"group-engineering"}))
member_without_groups = _context("member-3", group_ids=None)
member_other_group = _context("member-4", group_ids=frozenset({"group-sales"}))
outside_org = _context("member-5", organization_id="org-2", group_ids=frozenset({"group-engineering"}))
- for context in (owner, engineering_member, member_without_groups, member_other_group):
- assert resource_access_service.can_use_resource(
- context, "agent", "private-agent", connection=connection
- )
- assert resource_access_service.can_use_resource(
- context, "agent", "public-agent", connection=connection
- )
- assert resource_access_service.can_use_resource(
- context, "agent", "scoped-agent", connection=connection
- )
- assert resource_access_service.can_use_resource(
- outside_org, "agent", "public-agent", connection=connection
- )
+ assert resource_access_service.can_use_resource(owner, "agent", "private-agent", connection=connection)
+ assert resource_access_service.can_use_resource(owner, "agent", "public-agent", connection=connection) is True
+ assert resource_access_service.can_use_resource(engineering_member, "agent", "scoped-agent", connection=connection)
+ assert not resource_access_service.can_use_resource(member_without_groups, "agent", "scoped-agent", connection=connection)
+ assert not resource_access_service.can_use_resource(member_other_group, "agent", "scoped-agent", connection=connection)
+ assert not resource_access_service.can_use_resource(outside_org, "agent", "public-agent", connection=connection)
with pytest.raises(resource_access_service.ResourceAccessError, match="invalid_resource_kind"):
resource_access_service.can_use_resource(
engineering_member, "future_resource", "future-1", connection=connection
@@ -138,14 +131,14 @@ def test_active_org_members_can_use_legacy_resources_without_forging_local_ident
instance_role="owner",
access_source="owner",
)
- local = resource_access_service.ResourceUserContext(is_trusted_local=True)
+ local = resource_access_service.instance_owner_context()
- assert resource_access_service.can_use_resource(member, "agent", "legacy-agent", connection=connection)
+ assert not resource_access_service.can_use_resource(member, "agent", "legacy-agent", connection=connection)
assert resource_access_service.can_use_resource(owner, "agent", "legacy-agent", connection=connection)
- assert resource_access_service.can_use_resource(
+ assert not resource_access_service.can_use_resource(
diagnostic_owner, "agent", "legacy-agent", connection=connection
)
- assert not resource_access_service.can_use_resource(
+ assert resource_access_service.can_use_resource(
non_member_owner, "agent", "legacy-agent", connection=connection
)
assert resource_access_service.can_use_resource(local, "agent", "legacy-agent", connection=connection)
@@ -176,17 +169,11 @@ def test_non_member_role_rank_does_not_bypass_organization_resource_acl(tmp_path
access_source="email_invitation",
)
- assert not resource_access_service.can_use_resource(
- removed_owner,
- "agent",
- "private-agent",
- connection=connection,
+ assert resource_access_service.can_use_resource(
+ removed_owner, "agent", "private-agent", connection=connection
)
- assert not resource_access_service.can_manage_resource_acl(
- removed_owner,
- "agent",
- "private-agent",
- connection=connection,
+ assert resource_access_service.can_manage_resource_acl(
+ removed_owner, "agent", "private-agent", connection=connection
)
# Direct service calls retain ordinary role plus resource-policy
# semantics; HTTP admission rejects this non-member before runtime
@@ -214,8 +201,8 @@ def test_request_context_resolution_failure_does_not_become_trusted_local(monkey
request_context = resource_access_service.resolve_resource_access_context()
local_context = resource_access_service.resolve_resource_access_context()
- assert request_context.is_trusted_local is False
- assert local_context.is_trusted_local is True
+ assert request_context.is_instance_owner is False
+ assert local_context.is_instance_owner is True
def test_http_resource_services_reuse_the_parsed_authorization_context() -> None:
diff --git a/tests/test_resource_acl_agents.py b/tests/test_resource_acl_agents.py
index 7b2713860..5ef317ee3 100644
--- a/tests/test_resource_acl_agents.py
+++ b/tests/test_resource_acl_agents.py
@@ -7,13 +7,21 @@ import pytest
from sqlalchemy import select
from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore, TaskExecutionStore
-from core.vibe_agents import AgentImportCandidate, VibeAgent, VibeAgentAccessError, VibeAgentStore
+from core.vibe_agents import (
+ AgentImportCandidate,
+ VibeAgent,
+ VibeAgentAccessError,
+ VibeAgentStore,
+ ensure_agent_selection_access,
+ ensure_session_agent_access,
+)
from core.watches import ManagedWatchStore
from storage import resource_access_service, workbench_sessions_service
from storage.db import get_cached_sqlite_engine
from storage.models import resource_access_groups, resource_access_policies
from storage.settings_service import upsert_scope
-from tests.ui_server_test_helpers import csrf_headers, remote_peer, save_config
+from tests.ui_server_test_helpers import _remote_peer, _save_config
+from tests.ui_server_test_helpers import csrf_headers
from vibe import remote_access
from vibe.ui_server import app
@@ -115,8 +123,8 @@ def test_active_org_agent_catalog_includes_every_builtin_and_acl_shape(monkeypat
store.close()
assert owner_names == {"private-agent", "public-agent", "scope-agent"}
- assert member_names == {"private-agent", "public-agent", "scope-agent"}
- assert no_group_names == {"private-agent", "public-agent", "scope-agent"}
+ assert member_names == {"public-agent", "scope-agent"}
+ assert no_group_names == {"public-agent"}
def test_agent_removal_deletes_resource_policy_and_groups(monkeypatch, tmp_path) -> None:
@@ -156,15 +164,15 @@ def test_agent_removal_deletes_resource_policy_and_groups(monkeypatch, tmp_path)
assert groups == []
-def test_active_org_agent_creation_is_allowed_without_trusted_local_identity(monkeypatch, tmp_path) -> None:
+def test_owner_can_create_agent_without_a_trusted_local_identity(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
_organization_cookie(
config,
- subject="member-1",
+ subject="owner-1",
groups=["group-engineering"],
instance_role="owner",
),
@@ -176,7 +184,7 @@ def test_active_org_agent_creation_is_allowed_without_trusted_local_identity(mon
json={"name": "remote-private", "backend": "codex"},
headers=csrf_headers(client, "https://alex.avibe.bot"),
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
assert response.status_code in {200, 201}
@@ -274,9 +282,144 @@ def test_remote_partial_agent_updates_persist_canonical_selector_pair(monkeypatc
)
+def test_editor_clearing_session_agent_authorizes_default(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store, agents = _seed_agents_with_policies()
+ try:
+ store.set_default_agent_name(agents["private"].name)
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as connection:
+ scope_id = upsert_scope(
+ connection,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_clear_default",
+ now="2026-07-20T00:00:00Z",
+ )
+ session = workbench_sessions_service.create_session(
+ connection,
+ scope_id=scope_id,
+ agent_backend="",
+ agent_id=agents["public"].id,
+ user_context=_organization_context("member-1"),
+ )
+ with pytest.raises(VibeAgentAccessError):
+ with engine.begin() as connection:
+ workbench_sessions_service.update_session(
+ connection,
+ session["id"],
+ agent_name="",
+ agent_id="",
+ agent_backend="",
+ user_context=_organization_context("member-1"),
+ )
+ store.set_default_agent_name(agents["public"].name)
+ with engine.begin() as connection:
+ cleared = workbench_sessions_service.update_session(
+ connection,
+ session["id"],
+ agent_name="",
+ agent_id="",
+ agent_backend="",
+ user_context=_organization_context("member-1"),
+ )
+ store.set_default_agent_name(agents["scope"].name)
+ with engine.connect() as connection:
+ effective = ensure_session_agent_access(
+ connection,
+ cleared,
+ user_context=_organization_context("member-1"),
+ )
+ finally:
+ store.close()
+
+ assert (cleared["agent_id"], cleared["agent_name"], cleared["agent_backend"]) == (
+ None,
+ None,
+ "",
+ )
+ assert effective is not None
+ assert effective.id == agents["scope"].id
+
+
+def test_editor_creating_default_session_validates_without_pinning(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store, agents = _seed_agents_with_policies()
+ engine = get_cached_sqlite_engine()
+ try:
+ with engine.begin() as connection:
+ scope_id = upsert_scope(
+ connection,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_create_default",
+ now="2026-08-13T00:00:00Z",
+ )
+
+ store.set_default_agent_name(agents["private"].name)
+ with pytest.raises(VibeAgentAccessError):
+ with engine.begin() as connection:
+ workbench_sessions_service.create_session(
+ connection,
+ scope_id=scope_id,
+ agent_backend="",
+ user_context=_organization_context("member-1"),
+ )
+
+ store.set_default_agent_name(agents["public"].name)
+ with engine.begin() as connection:
+ created = workbench_sessions_service.create_session(
+ connection,
+ scope_id=scope_id,
+ agent_backend="",
+ user_context=_organization_context("member-1"),
+ )
+
+ store.set_default_agent_name(agents["scope"].name)
+ with engine.connect() as connection:
+ effective = ensure_session_agent_access(
+ connection,
+ created,
+ user_context=_organization_context("member-1"),
+ )
+ finally:
+ store.close()
+
+ assert (created["agent_id"], created["agent_name"], created["agent_backend"]) == (
+ None,
+ None,
+ "",
+ )
+ assert effective is not None
+ assert effective.id == agents["scope"].id
+
+
+def test_missing_agent_selector_fails_closed_for_editor_only(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = VibeAgentStore()
+ try:
+ with store.engine.connect() as connection:
+ with pytest.raises(VibeAgentAccessError):
+ ensure_agent_selection_access(
+ connection,
+ agent_name="deleted-legacy-agent",
+ user_context=_organization_context("member-1"),
+ )
+ assert (
+ ensure_agent_selection_access(
+ connection,
+ agent_name="deleted-legacy-agent",
+ user_context=_organization_context("owner-1", instance_role="owner"),
+ )
+ is None
+ )
+ finally:
+ store.close()
+
+
def test_active_org_agent_detail_uses_full_runtime_projection(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
store = VibeAgentStore()
try:
agent = store.create(
@@ -308,7 +451,7 @@ def test_active_org_agent_detail_uses_full_runtime_projection(monkeypatch, tmp_p
remote_response = remote.get(
"/api/agents/imported-agent",
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
local_response = app.test_client().get("/api/agents/imported-agent")
@@ -322,35 +465,38 @@ def test_active_org_agent_detail_uses_full_runtime_projection(monkeypatch, tmp_p
assert local_response.get_json()["agent"]["metadata"]["secret"] == "local-only"
-def test_active_org_agent_selection_and_harness_bindings_are_allowed(monkeypatch, tmp_path) -> None:
+def test_editor_agent_selection_and_harness_bindings_follow_acl(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
store, agents = _seed_agents_with_policies()
private_agent = agents["private"]
store.set_default_agent_name(private_agent.name)
store.close()
context = _organization_context("member-1")
- # Agent management stays reserved to admin/owner Organization roles under
- # the temporary full-access rollout (see #1343). The reads and catalog
- # remain open to all active members.
+ # Editors may read only Agents allowed by Agent ACL and cannot manage them.
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- _organization_cookie(config, subject="member-1", groups=[], instance_role="editor"),
+ _organization_cookie(
+ config,
+ subject="member-1",
+ groups=["group-engineering"],
+ instance_role="editor",
+ ),
domain="alex.avibe.bot",
)
response = client.get(
"/api/agents/private-agent",
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
- assert response.status_code == 200
- catalog = client.get("/api/agents", base_url="https://alex.avibe.bot", environ_base=remote_peer())
+ assert response.status_code == 403
+ catalog = client.get("/api/agents", base_url="https://alex.avibe.bot", environ_base=_remote_peer())
assert catalog.status_code == 200
- assert {"private-agent", "public-agent", "scope-agent"}.issubset(
- {agent["name"] for agent in catalog.get_json()["agents"]}
- )
+ assert {"public-agent", "scope-agent"} == {
+ agent["name"] for agent in catalog.get_json()["agents"]
+ }
# A plain active Organization member is denied mutations under the
# Resource ACL boundary.
denied_mutation = client.patch(
@@ -358,16 +504,16 @@ def test_active_org_agent_selection_and_harness_bindings_are_allowed(monkeypatch
json={"description": "member update"},
headers=csrf_headers(client, "https://alex.avibe.bot"),
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
assert denied_mutation.status_code == 403
- # An active Organization admin/owner can manage.
+ # Only the Instance Owner can manage Agents.
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
_organization_cookie(
config,
subject="admin-1",
- groups=[],
+ groups=["group-engineering"],
instance_role="owner",
organization_role="admin",
),
@@ -378,7 +524,7 @@ def test_active_org_agent_selection_and_harness_bindings_are_allowed(monkeypatch
json={"description": "admin update"},
headers=csrf_headers(client, "https://alex.avibe.bot"),
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
assert mutation.status_code == 200
default_mutation = client.post(
@@ -386,7 +532,7 @@ def test_active_org_agent_selection_and_harness_bindings_are_allowed(monkeypatch
json={"name": private_agent.name},
headers=csrf_headers(client, "https://alex.avibe.bot"),
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
assert default_mutation.status_code == 200
@@ -403,11 +549,11 @@ def test_active_org_agent_selection_and_harness_bindings_are_allowed(monkeypatch
connection,
scope_id=scope_id,
agent_backend="codex",
- agent_name=private_agent.name,
- agent_id=private_agent.id,
+ agent_name=agents["scope"].name,
+ agent_id=agents["scope"].id,
user_context=context,
)
- assert session["agent_id"] == private_agent.id
+ assert session["agent_id"] == agents["scope"].id
backend_only = workbench_sessions_service.create_session(
connection,
scope_id=scope_id,
@@ -423,7 +569,7 @@ def test_active_org_agent_selection_and_harness_bindings_are_allowed(monkeypatch
session_key="avibe::project::proj_acl_agents",
prompt="run",
schedule_type="cron",
- agent_name=private_agent.name,
+ agent_name=agents["scope"].name,
cron="0 * * * *",
timezone_name="UTC",
user_context=context,
@@ -442,25 +588,25 @@ def test_active_org_agent_selection_and_harness_bindings_are_allowed(monkeypatch
retry_delay_seconds=1,
post_to=None,
deliver_key=None,
- agent_name=private_agent.name,
+ agent_name=agents["scope"].name,
user_context=context,
)
- assert task.agent_name == private_agent.name
- assert watch.agent_name == private_agent.name
+ assert task.agent_name == agents["scope"].name
+ assert watch.agent_name == agents["scope"].name
finally:
pass
-def test_non_member_cannot_create_agent_but_active_org_member_can(monkeypatch, tmp_path) -> None:
+def test_only_owner_can_create_or_import_agents(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = VibeAgentStore()
try:
- created = store.create(
- name="editor-agent",
- backend="codex",
- user_context=_organization_context("member-1"),
- )
- assert created.name == "editor-agent"
+ 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",
@@ -525,10 +671,10 @@ def test_active_org_background_definitions_are_allowed_but_legacy_rows_fail_befo
)
assert task.agent_name == agents["public"].name
assert watch.agent_name == agents["public"].name
- assert resource_access_service.metadata_allows_temporary_unrestricted_runtime(
+ assert resource_access_service.metadata_allows_harness_runtime(
task.metadata
)
- assert resource_access_service.metadata_allows_temporary_unrestricted_runtime(
+ assert resource_access_service.metadata_allows_harness_runtime(
watch.metadata
)
restored = resource_access_service.resource_user_context_from_metadata(
@@ -537,7 +683,7 @@ def test_active_org_background_definitions_are_allowed_but_legacy_rows_fail_befo
assert restored is not None
assert restored.subject == context.subject
assert restored.is_remote is True
- assert restored.is_trusted_local is False
+ assert restored.is_instance_owner is False
task = task_store.add_task(
session_key="slack::channel::C123",
@@ -585,11 +731,11 @@ def test_active_org_background_definitions_are_allowed_but_legacy_rows_fail_befo
task_result = asyncio.run(
service._execute_task(task, execution_id="task-run", disable_one_shot=False)
)
- assert task_result.error == "remote_autonomous_harness_disabled"
+ assert task_result.error == "harness_access_forbidden"
stored_task = task_store.get_task(task.id)
assert stored_task is not None
assert stored_task.enabled is False
- assert stored_task.last_error == "remote_autonomous_harness_disabled"
+ assert stored_task.last_error == "harness_access_forbidden"
assert not (tmp_path / "should-not-run").exists()
request = request_store.enqueue_hook_send(
@@ -608,6 +754,357 @@ def test_active_org_background_definitions_are_allowed_but_legacy_rows_fail_befo
completed = request_store.get_run(request.id)
assert completed is not None
assert completed["status"] == "failed"
- assert completed["error"] == "remote_autonomous_harness_disabled"
+ assert completed["error"] == "harness_access_forbidden"
finally:
agent_store.close()
+
+
+def test_project_runtime_uses_acls_while_harness_remains_editor_wide(monkeypatch, tmp_path) -> None:
+ """Project-bound runtime and global Harness follow their distinct contracts.
+
+ Running Agents and the graph honor Project and Agent ACLs. Harness has no
+ additional resource ACL in this MVP, so an Editor can see and manage every
+ definition even when it references an inaccessible or deleted Agent.
+ """
+
+ from datetime import datetime, timezone
+
+ from core.services import agent_graph
+ from storage.background import SQLiteBackgroundTaskStore
+ from storage.importer import ensure_sqlite_state
+ from vibe import internal_client, ui_server
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ config = _save_config(tmp_path)
+ store, agents = _seed_agents_with_policies()
+ engine = get_cached_sqlite_engine()
+ now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+ try:
+ with engine.begin() as connection:
+ allowed_scope = upsert_scope(
+ connection,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_runtime_allowed",
+ now=now,
+ )
+ denied_scope = upsert_scope(
+ connection,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_runtime_denied",
+ now=now,
+ )
+ allowed_session = workbench_sessions_service.create_session(
+ connection,
+ scope_id=allowed_scope,
+ agent_backend="codex",
+ agent_name=agents["public"].name,
+ agent_id=agents["public"].id,
+ )
+ denied_session = workbench_sessions_service.create_session(
+ connection,
+ scope_id=denied_scope,
+ agent_backend="codex",
+ agent_name=agents["private"].name,
+ agent_id=agents["private"].id,
+ )
+ finally:
+ store.close()
+
+ harness = SQLiteBackgroundTaskStore()
+ try:
+ harness.upsert_scheduled_task(
+ {
+ "id": "task-allowed",
+ "name": "allowed task",
+ "prompt": "run allowed",
+ "schedule_type": "cron",
+ "cron": "0 * * * *",
+ "enabled": True,
+ "session_id": allowed_session["id"],
+ "agent_name": agents["public"].name,
+ "agent_id": agents["public"].id,
+ "created_at": now,
+ "updated_at": now,
+ }
+ )
+ harness.upsert_scheduled_task(
+ {
+ "id": "task-denied",
+ "name": "denied task",
+ "prompt": "run denied",
+ "schedule_type": "cron",
+ "cron": "0 * * * *",
+ "enabled": True,
+ "session_id": denied_session["id"],
+ "agent_name": agents["private"].name,
+ "agent_id": agents["private"].id,
+ "created_at": now,
+ "updated_at": now,
+ }
+ )
+ harness.upsert_watch(
+ {
+ "id": "watch-allowed",
+ "name": "allowed watch",
+ "shell_command": "true",
+ "enabled": True,
+ "session_id": allowed_session["id"],
+ "agent_name": agents["public"].name,
+ "agent_id": agents["public"].id,
+ "created_at": now,
+ "updated_at": now,
+ }
+ )
+ harness.upsert_watch(
+ {
+ "id": "watch-denied",
+ "name": "denied watch",
+ "shell_command": "true",
+ "enabled": True,
+ "session_id": denied_session["id"],
+ "agent_name": agents["private"].name,
+ "agent_id": agents["private"].id,
+ "created_at": now,
+ "updated_at": now,
+ }
+ )
+ harness.upsert_scheduled_task(
+ {
+ "id": "task-unbound-allowed",
+ "name": "unbound allowed task",
+ "prompt": "run unbound",
+ "schedule_type": "cron",
+ "cron": "0 * * * *",
+ "enabled": True,
+ "agent_name": agents["public"].name,
+ "agent_id": agents["public"].id,
+ "created_at": now,
+ "updated_at": now,
+ }
+ )
+ for index in range(3):
+ harness.upsert_scheduled_task(
+ {
+ "id": f"task-denied-page-{index}",
+ "name": f"denied page {index}",
+ "prompt": "run denied page",
+ "schedule_type": "cron",
+ "cron": "0 * * * *",
+ "enabled": True,
+ "session_id": denied_session["id"],
+ "agent_name": agents["private"].name,
+ "agent_id": agents["private"].id,
+ "created_at": f"2026-08-13T12:0{index}:00Z",
+ "updated_at": f"2026-08-13T12:0{index}:00Z",
+ }
+ )
+ harness.upsert_scheduled_task(
+ {
+ "id": "task-missing-agent",
+ "name": "missing agent task",
+ "prompt": "run missing",
+ "schedule_type": "cron",
+ "cron": "0 * * * *",
+ "enabled": True,
+ "agent_name": "deleted-legacy-agent",
+ "created_at": now,
+ "updated_at": now,
+ }
+ )
+ finally:
+ harness.close()
+
+ async def fake_list(**_kwargs):
+ return {
+ "status_code": 200,
+ "body": {
+ "agents": [
+ {
+ "session_id": allowed_session["id"],
+ "agent_name": agents["public"].name,
+ "agent_id": agents["public"].id,
+ "backend": "codex",
+ "state": "idle",
+ "title": "allowed live",
+ },
+ {
+ "session_id": denied_session["id"],
+ "agent_name": agents["private"].name,
+ "agent_id": agents["private"].id,
+ "backend": "codex",
+ "state": "active",
+ "title": "denied live",
+ },
+ ],
+ "counts": {
+ "total": 2,
+ "active": 1,
+ "idle": 1,
+ "orphan": 0,
+ "by_backend": {"codex": 2},
+ },
+ },
+ }
+
+ ended: list[dict] = []
+
+ async def fake_end(payload):
+ ended.append(payload)
+ return {"status_code": 200, "body": {"ok": True}}
+
+ monkeypatch.setattr(internal_client, "list_running_agents", fake_list)
+ monkeypatch.setattr(internal_client, "end_running_agent", fake_end)
+
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ _organization_cookie(
+ config,
+ subject="member-1",
+ groups=["group-engineering"],
+ instance_role="editor",
+ ),
+ domain="alex.avibe.bot",
+ )
+ remote = {"base_url": "https://alex.avibe.bot", "environ_base": _remote_peer()}
+
+ graph_payload = {
+ "nodes": [
+ {
+ "session_id": allowed_session["id"],
+ "agent_name": agents["public"].name,
+ "agent_id": agents["public"].id,
+ "status": "idle",
+ "live": False,
+ "visibility": "foreground",
+ },
+ {
+ "session_id": denied_session["id"],
+ "agent_name": agents["private"].name,
+ "agent_id": agents["private"].id,
+ "status": "idle",
+ "live": False,
+ "visibility": "foreground",
+ },
+ ],
+ "edges": [
+ {
+ "kind": "trigger",
+ "from": "def:task-allowed",
+ "to": allowed_session["id"],
+ },
+ {
+ "kind": "trigger",
+ "from": "def:task-denied",
+ "to": denied_session["id"],
+ },
+ ],
+ "trigger_nodes": [
+ {"definition_id": "task-allowed"},
+ {"definition_id": "task-denied"},
+ ],
+ "counts": {},
+ }
+ graph_body = ui_server._authorized_graph_payload(
+ _organization_context("member-1"),
+ graph_payload,
+ )
+ assert {node["session_id"] for node in graph_body["nodes"]} == {allowed_session["id"]}
+ assert graph_body["edges"] == [
+ {
+ "kind": "trigger",
+ "from": "def:task-allowed",
+ "to": allowed_session["id"],
+ }
+ ]
+ assert graph_body["trigger_nodes"] == [{"definition_id": "task-allowed"}]
+ assert graph_body["counts"] == agent_graph._counts(graph_body["nodes"])
+
+ running = client.get("/api/running-agents", **remote)
+ assert running.status_code == 200
+ running_body = running.get_json()
+ running_ids = {row.get("session_id") for row in running_body.get("agents") or []}
+ assert running_ids == {allowed_session["id"]}
+ assert running_body["counts"] == {
+ "total": 1,
+ "active": 0,
+ "idle": 1,
+ "orphan": 0,
+ "by_backend": {"codex": 1},
+ }
+
+ favorites = client.get("/api/browse/favorites", **remote)
+ assert favorites.status_code == 200
+ denied_browse = client.post(
+ "/api/browse",
+ json={"path": "~"},
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ **remote,
+ )
+ assert denied_browse.status_code == 403
+
+ deny_end = client.post(
+ "/api/running-agents/end",
+ json={"session_id": denied_session["id"], "agent_name": agents["private"].name},
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ **remote,
+ )
+ assert deny_end.status_code == 404
+ assert ended == []
+
+ allow_end = client.post(
+ "/api/running-agents/end",
+ json={"session_id": allowed_session["id"], "agent_name": agents["public"].name},
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ **remote,
+ )
+ assert allow_end.status_code == 200
+ assert ended
+
+ tasks = client.get("/api/harness/tasks", **remote).get_json()["tasks"]
+ watches = client.get("/api/harness/watches", **remote).get_json()["watches"]
+ assert {row["id"] for row in tasks} == {
+ "task-allowed",
+ "task-denied",
+ "task-denied-page-0",
+ "task-denied-page-1",
+ "task-denied-page-2",
+ "task-missing-agent",
+ "task-unbound-allowed",
+ }
+ assert {row["id"] for row in watches} == {"watch-allowed", "watch-denied"}
+
+ paged = client.get("/api/harness/tasks?page=1&limit=1", **remote).get_json()
+ assert len(paged["tasks"]) == 1
+ assert paged["counts"]["total"] == 7
+ assert paged["has_more"] is True
+
+ patch_response = client.patch(
+ "/api/harness/tasks/task-denied",
+ json={"enabled": False},
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ **remote,
+ )
+ delete_response = client.delete(
+ "/api/harness/watches/watch-denied",
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ **remote,
+ )
+ assert patch_response.status_code == 200
+ assert patch_response.get_json()["task"]["enabled"] is False
+ assert delete_response.status_code == 200
+
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ _organization_cookie(
+ config,
+ subject="viewer-1",
+ groups=["group-engineering"],
+ instance_role="viewer",
+ ),
+ domain="alex.avibe.bot",
+ )
+ assert client.get("/api/harness/tasks", **remote).status_code == 403
diff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.py
index f02e2e115..b24c878ca 100644
--- a/tests/test_resource_acl_show_pages.py
+++ b/tests/test_resource_acl_show_pages.py
@@ -11,7 +11,8 @@ from storage import workbench_sessions_service as sessions_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_sessions, show_pages
-from tests.ui_server_test_helpers import csrf_headers, remote_peer, save_config
+from tests.ui_server_test_helpers import _remote_peer, _save_config
+from tests.ui_server_test_helpers import csrf_headers
from vibe import api, remote_access, ui_server
from vibe.ui_server import app
@@ -96,7 +97,7 @@ def _seed_show_pages_with_policies() -> ShowPageStore:
return store
-def test_active_org_members_see_all_show_pages_during_temporary_bypass(monkeypatch, tmp_path) -> None:
+def test_show_page_catalog_follows_instance_role_and_show_page_acl(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = _seed_show_pages_with_policies()
try:
@@ -110,8 +111,8 @@ def test_active_org_members_see_all_show_pages_during_temporary_bypass(monkeypat
store.close()
assert owner_ids == {"ses-private", "ses-public", "ses-scope"}
- assert member_ids == {"ses-private", "ses-public", "ses-scope"}
- assert no_group_ids == {"ses-private", "ses-public", "ses-scope"}
+ assert member_ids == {"ses-public", "ses-scope"}
+ assert no_group_ids == {"ses-public"}
def test_show_page_email_context_bypasses_audience_only_for_its_signed_page(
@@ -191,7 +192,7 @@ def test_non_org_email_context_keeps_exact_page_entitlement_separate_from_role_r
("member-1", "viewer", "member"),
],
)
-def test_remote_org_members_can_open_all_show_pages_temporarily(
+def test_remote_show_page_access_does_not_bypass_acl(
monkeypatch,
tmp_path,
subject,
@@ -199,7 +200,7 @@ def test_remote_org_members_can_open_all_show_pages_temporarily(
organization_role,
) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
store = _seed_show_pages_with_policies()
store.close()
@@ -223,33 +224,31 @@ def test_remote_org_members_can_open_all_show_pages_temporarily(
catalog = client.get(
"/api/show-pages",
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
mutation = client.post(
"/api/show-pages/ses-public/visibility",
json={"visibility": "offline"},
headers=csrf_headers(client, "https://alex.avibe.bot"),
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
page = client.get(
"/show/ses-private/",
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
headers={"Accept": "text/html"},
follow_redirects=False,
)
assert catalog.status_code == 200
- assert {item["session_id"] for item in catalog.get_json()["pages"]} == {
- "ses-private",
- "ses-public",
- "ses-scope",
+ expected = {"ses-private", "ses-public", "ses-scope"} if instance_role == "owner" else {
+ "ses-public", "ses-scope"
}
+ assert {item["session_id"] for item in catalog.get_json()["pages"]} == expected
assert all(item.get("path") for item in catalog.get_json()["pages"])
- assert mutation.status_code == 200
- assert mutation.get_json()["visibility"] == "offline"
- assert page.status_code == 200
+ assert mutation.status_code == (200 if instance_role == "owner" else 403)
+ assert page.status_code == (200 if instance_role == "owner" else 302)
def test_remote_show_page_creation_persists_real_org_identity(monkeypatch, tmp_path) -> None:
@@ -257,11 +256,31 @@ def test_remote_show_page_creation_persists_real_org_identity(monkeypatch, tmp_p
owner_context = _organization_context("owner-1", instance_role="owner")
store = ShowPageStore()
try:
+ project_path = tmp_path / "project"
+ project_path.mkdir()
+ with store.engine.begin() as connection:
+ project = projects_service.create_project(connection, str(project_path))
+ session = sessions_service.create_session(
+ connection, scope_id=project["scope_id"], agent_backend="codex"
+ )
+ project_access_service.apply_project_access_intent(
+ connection,
+ {
+ "project_id": project["id"],
+ "revision": 1,
+ "mode": "restricted",
+ "bindings": [{
+ "principal_kind": "email",
+ "principal_value": "[email protected]",
+ "access_role": "editor",
+ }],
+ },
+ )
created = store.ensure(
- "ses-editor-created",
+ session["id"],
user_context=_organization_context("member-1", instance_role="editor"),
)
- assert created.session_id == "ses-editor-created"
+ assert created.session_id == session["id"]
with store.engine.connect() as connection:
created_policy = resource_access_service.get_resource_policy(
"show_page", created.session_id, connection=connection
@@ -299,18 +318,19 @@ def test_remote_show_page_creation_persists_real_org_identity(monkeypatch, tmp_p
store.close()
-def test_show_page_scope_without_group_context_is_open_during_temporary_bypass(monkeypatch, tmp_path) -> None:
+def test_show_page_scope_without_group_context_is_denied(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = _seed_show_pages_with_policies()
try:
- page = store.require_access("ses-scope", user_context=_organization_context("member-1", group_ids=None))
+ with pytest.raises(ShowPageError):
+ store.require_access("ses-scope", user_context=_organization_context("member-1", group_ids=None))
finally:
store.close()
- assert page.session_id == "ses-scope"
+ # Missing group claims fail closed for scoped pages.
-def test_active_organization_admin_can_manage_all_pages_temporarily(monkeypatch, tmp_path) -> None:
+def test_organization_admin_without_instance_owner_role_cannot_manage_pages(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = _seed_show_pages_with_policies()
admin = _organization_context(
@@ -322,15 +342,10 @@ def test_active_organization_admin_can_manage_all_pages_temporarily(monkeypatch,
owner = _organization_context("owner-1", instance_role="owner")
try:
public_page = store.update_visibility("ses-private", "public", user_context=owner)
- assert store.require_access("ses-private", user_context=admin).session_id == "ses-private"
- assert store.update_visibility("ses-private", "private", user_context=admin).visibility == "private"
- # Share-id operations retain their existing public-page invariant even
- # though the temporary Org policy admits the caller to the resource.
- assert store.update_visibility("ses-private", "public", user_context=admin).visibility == "public"
- admin_rotated, _ = store.rotate_share("ses-private", user_context=admin)
- admin_custom, _ = store.set_share_id("ses-private", "admin-link", user_context=admin)
- assert admin_rotated.share_id
- assert admin_custom.share_id == "admin-link"
+ with pytest.raises(ShowPageError):
+ store.require_access("ses-private", user_context=admin)
+ with pytest.raises(ShowPageError):
+ store.update_visibility("ses-private", "private", user_context=admin)
republished = store.update_visibility("ses-private", "public", user_context=owner)
rotated, previous_share_id = store.rotate_share("ses-private", user_context=owner)
@@ -342,17 +357,15 @@ def test_active_organization_admin_can_manage_all_pages_temporarily(monkeypatch,
assert rotated_share_id == rotated.share_id
assert custom.share_id == "owner-link"
- assert store.require_access("ses-scope", user_context=admin).session_id == "ses-scope"
- assert store.update_visibility("ses-scope", "offline", user_context=admin).visibility == "offline"
- restored = store.update_visibility("ses-scope", "private", user_context=admin)
- assert restored.visibility == "private"
+ with pytest.raises(ShowPageError):
+ store.require_access("ses-scope", user_context=admin)
finally:
store.close()
def test_access_only_manager_visibility_response_does_not_expose_page_payload(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
store = _seed_show_pages_with_policies()
admin = _organization_context(
"admin-1",
@@ -374,16 +387,13 @@ def test_access_only_manager_visibility_response_does_not_expose_page_payload(mo
lambda _value=None: admin,
)
- result = api.set_show_page_visibility("ses-private", "private")
-
- assert result["ok"] is True
- assert result["session_id"] == "ses-private"
- assert result["visibility"] == "private"
+ with pytest.raises(ShowPageError):
+ api.set_show_page_visibility("ses-private", "private")
def test_excluded_scoped_owner_share_mutations_do_not_expose_page_payload(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
store = _seed_show_pages_with_policies()
excluded_owner = _organization_context(
"owner-1",
@@ -404,17 +414,13 @@ def test_excluded_scoped_owner_share_mutations_do_not_expose_page_payload(monkey
customized = api.set_show_page_share_id("ses-scope", "excluded-owner-link")
assert rotated["ok"] is True
- assert rotated["session_id"] == "ses-scope"
- assert rotated["visibility"] == "public"
assert customized["ok"] is True
- assert customized["session_id"] == "ses-scope"
- assert customized["visibility"] == "public"
-def test_remote_show_page_owner_can_control_sharing_without_instance_owner_role(monkeypatch, tmp_path) -> None:
+def test_remote_show_page_editor_can_control_sharing_without_instance_owner_role(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = _seed_show_pages_with_policies()
- page_owner = _organization_context("owner-1", instance_role="viewer")
+ page_owner = _organization_context("owner-1", instance_role="editor")
try:
published = store.update_visibility("ses-private", "public", user_context=page_owner)
closed = store.update_visibility("ses-private", "private", user_context=page_owner)
@@ -435,9 +441,9 @@ def test_remote_show_page_owner_can_control_sharing_without_instance_owner_role(
store.close()
-def test_remote_show_page_owner_mutations_reach_resource_acl_as_viewer(monkeypatch, tmp_path) -> None:
+def test_remote_show_page_viewer_mutations_are_instance_role_denied(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
store = ShowPageStore()
project_path = tmp_path / "project"
project_path.mkdir()
@@ -469,7 +475,7 @@ def test_remote_show_page_owner_mutations_reach_resource_acl_as_viewer(monkeypat
request_options = {
"headers": csrf_headers(client, "https://alex.avibe.bot"),
"base_url": "https://alex.avibe.bot",
- "environ_base": remote_peer(),
+ "environ_base": _remote_peer(),
}
ensured = client.post(
@@ -493,17 +499,15 @@ def test_remote_show_page_owner_mutations_reach_resource_acl_as_viewer(monkeypat
**request_options,
)
- assert ensured.status_code == 200
- assert ensured.get_json()["existed"] is True
- assert published.status_code == 200
- assert rotated.status_code == 200
- assert customized.status_code == 200
- assert customized.get_json()["share_id"] == "viewer-owner-link"
+ assert ensured.status_code == 403
+ assert published.status_code == 403
+ assert rotated.status_code == 403
+ assert customized.status_code == 403
def test_organization_admin_can_read_show_page_access_metadata_without_use_access(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
store = _seed_show_pages_with_policies()
store.close()
admin = _organization_context(
@@ -514,13 +518,8 @@ def test_organization_admin_can_read_show_page_access_metadata_without_use_acces
)
monkeypatch.setattr(resource_access_service, "resolve_resource_access_context", lambda _value=None: admin)
- payload = api.get_show_page_access("ses-scope")
-
- assert payload["access_level"] == "scope"
- assert payload["instance_id"] is None
- assert payload["can_use"] is True
- assert payload["can_manage"] is True
- assert payload["can_publish_public"] is True
+ with pytest.raises(ShowPageError):
+ api.get_show_page_access("ses-scope")
def test_opening_existing_organization_page_does_not_register_new_policy(monkeypatch, tmp_path) -> None:
@@ -568,7 +567,7 @@ def test_show_page_access_api_distinguishes_personal_and_organization_modes(monk
"public_link_enabled": False,
}
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
store = ShowPageStore()
try:
store.ensure("ses-organization")
@@ -602,7 +601,7 @@ def test_show_page_access_api_distinguishes_personal_and_organization_modes(monk
organization = client.get(
"/api/show-pages/ses-organization/access",
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
assert organization.status_code == 200
assert organization.get_json() == {
@@ -679,7 +678,6 @@ def test_show_page_owner_can_read_and_replace_exact_email_grants(monkeypatch, tm
("subject", "organization_role", "instance_role"),
[
("member-1", "member", "viewer"),
- ("admin-1", "admin", "owner"),
],
)
def test_show_page_email_grants_reject_non_owner_without_contacting_backend(
@@ -690,7 +688,7 @@ def test_show_page_email_grants_reject_non_owner_without_contacting_backend(
instance_role: str,
) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
store = _seed_show_pages_with_policies()
store.close()
monkeypatch.setattr(
@@ -722,7 +720,7 @@ def test_show_page_email_grants_report_unavailable_without_cloud_pairing(
monkeypatch, tmp_path
) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
store = ShowPageStore()
try:
store.ensure("ses-email-access")
@@ -741,7 +739,7 @@ def test_show_page_email_grants_report_transient_device_failures_as_retryable(
monkeypatch, tmp_path
) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
store = ShowPageStore()
try:
store.ensure("ses-email-access-transient")
@@ -765,7 +763,7 @@ def test_show_page_email_grants_report_transient_device_failures_as_retryable(
def test_show_page_email_grant_device_requests_freeze_the_target(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
calls: list[tuple] = []
monkeypatch.setattr(remote_access, "_resource_acl_sync_configured", lambda _config: True)
monkeypatch.setattr(
@@ -814,7 +812,7 @@ def test_show_page_email_grant_device_requests_freeze_the_target(monkeypatch, tm
def test_show_page_email_grant_change_requires_authorization_revision(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
monkeypatch.setattr(remote_access, "_resource_acl_sync_configured", lambda _config: True)
monkeypatch.setattr(
remote_access,
@@ -835,7 +833,7 @@ def test_show_page_email_grant_change_requires_authorization_revision(monkeypatc
def test_remote_org_dock_requires_admin_owner_role(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
store = _seed_show_pages_with_policies()
store.close()
owner = _organization_context("owner-1", instance_role="owner")
@@ -856,8 +854,8 @@ def test_remote_org_dock_requires_admin_owner_role(monkeypatch, tmp_path) -> Non
dock = api.get_dock(user_context=member)["dock"]
visible_ids = {pin["session_id"] for pin in dock["pins"]}
- assert visible_ids == {"ses-private", "ses-public", "ses-scope"}
- assert "show:ses-private" in dock["order"]
+ assert visible_ids == {"ses-public", "ses-scope"}
+ assert "show:ses-private" not in dock["order"]
# Pinning additional pages (require_management) stays denied for a plain
# member; unpin and reorder are also dock mutations and stay denied.
with pytest.raises(ShowPageError):
@@ -882,7 +880,7 @@ def test_remote_org_dock_requires_admin_owner_role(monkeypatch, tmp_path) -> Non
"/api/dock/pins/ses-public",
headers=csrf_headers(client, "https://alex.avibe.bot"),
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
# A plain active Organization member is denied dock mutations under the
# Resource ACL boundary (see #1343).
@@ -891,7 +889,7 @@ def test_remote_org_dock_requires_admin_owner_role(monkeypatch, tmp_path) -> Non
def test_remote_admin_dock_order_preserves_hidden_private_pins(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
store = _seed_show_pages_with_policies()
store.close()
owner = _organization_context("owner-1", instance_role="owner")
@@ -918,7 +916,7 @@ def test_remote_admin_dock_order_preserves_hidden_private_pins(monkeypatch, tmp_
def test_untrusted_dock_context_fails_closed(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
store = _seed_show_pages_with_policies()
store.close()
owner = _organization_context("owner-1", instance_role="owner")
@@ -942,7 +940,7 @@ def test_remote_member_archive_is_denied_under_resource_acl(monkeypatch, tmp_pat
from unittest.mock import AsyncMock
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
project_dir = tmp_path / "project"
project_dir.mkdir()
ensure_sqlite_state()
@@ -995,7 +993,7 @@ def test_remote_member_archive_is_denied_under_resource_acl(monkeypatch, tmp_pat
f"/api/sessions/{session_id}",
headers=csrf_headers(client, "https://alex.avibe.bot"),
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
assert response.status_code in {403, 404}
@@ -1014,7 +1012,7 @@ def test_remote_org_show_annotation_media_temporarily_follows_open_page_policy(
) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
project_dir = tmp_path / "project"
project_dir.mkdir()
ensure_sqlite_state()
@@ -1099,17 +1097,15 @@ def test_remote_org_show_annotation_media_temporarily_follows_open_page_policy(
return client.get(
f"/api/media/{token}",
base_url="https://alex.avibe.bot",
- environ_base=remote_peer(),
+ environ_base=_remote_peer(),
)
- # Show annotation screenshots are part of the temporarily open page.
- assert _media(tokens["show_annotation:private"]).status_code == 200
- assert _media(tokens["show_annotation:public"]).status_code == 200
+ # Media access follows the associated Project and Show Page ACLs.
+ assert _media(tokens["show_annotation:private"]).status_code == 404
+ assert _media(tokens["show_annotation:public"]).status_code == 404
# An annotation with no page to check against cannot be authorized.
assert _media(orphan_token).status_code == 404
- # Active Organization members have the temporary runtime bypass for
- # project/session media as well.
- assert _media(tokens["agent_reply:private"]).status_code == 200
- assert _media(tokens["agent_reply:public"]).status_code == 200
+ assert _media(tokens["agent_reply:private"]).status_code == 404
+ assert _media(tokens["agent_reply:public"]).status_code == 404
finally:
engine.dispose()
diff --git a/tests/test_show_pages_admin_api.py b/tests/test_show_pages_admin_api.py
index 6b7e8c2b4..0f0adbef8 100644
--- a/tests/test_show_pages_admin_api.py
+++ b/tests/test_show_pages_admin_api.py
@@ -3,7 +3,7 @@
import pytest
from core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir
-from tests.ui_server_test_helpers import save_config
+from tests.ui_server_test_helpers import _save_config
from vibe import api
from vibe.ui_server import app
@@ -60,7 +60,7 @@ def _set_visibility(session_id: str, visibility: str) -> None:
def test_list_show_pages_orders_newest_first_and_joins_title(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_titled", title="Q2 funnel dashboard")
_seed_session("ses_plain")
_set_visibility("ses_titled", "public")
@@ -89,7 +89,7 @@ def test_list_show_pages_preserves_archived_agent_display_name(monkeypatch, tmp_
from storage.models import agent_sessions
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
store = VibeAgentStore()
try:
original = store.create(name="pm", backend="claude")
@@ -120,7 +120,7 @@ def test_list_show_pages_preserves_archived_agent_display_name(monkeypatch, tmp_
def test_set_show_page_visibility_public_then_offline(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_x")
_set_visibility("ses_x", "private")
@@ -137,7 +137,7 @@ def test_set_show_page_visibility_public_then_offline(monkeypatch, tmp_path):
def test_set_show_page_visibility_rejects_invalid(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_x")
with pytest.raises(ShowPageError) as excinfo:
@@ -147,7 +147,7 @@ def test_set_show_page_visibility_rejects_invalid(monkeypatch, tmp_path):
def test_rotate_share_requires_public_and_revokes_previous(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_x")
_set_visibility("ses_x", "private")
@@ -165,7 +165,7 @@ def test_rotate_share_requires_public_and_revokes_previous(monkeypatch, tmp_path
def test_show_pages_list_route_returns_payload(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
_seed_session("ses_route", title="Release notes preview")
_set_visibility("ses_route", "public")
diff --git a/tests/test_skills_service.py b/tests/test_skills_service.py
index 3241b4336..8299c2942 100644
--- a/tests/test_skills_service.py
+++ b/tests/test_skills_service.py
@@ -632,45 +632,44 @@ def test_remove_skill_deletes_only_policies_for_removed_backends(monkeypatch, tm
assert claude_policy is not None
[email protected]("operation", ["remove", "update"])
- "listing",
- [
- {"ok": False, "error": {"code": "list_failed"}},
- {"ok": True, "skills": []},
- {"ok": True, "skills": "invalid"},
- ],
-)
-def test_non_member_skill_mutations_fail_closed_when_preflight_cannot_resolve_target(
[email protected]("operation", ["add", "remove", "update"])
+def test_viewer_skill_mutations_fail_before_cli(
monkeypatch,
tmp_path,
operation: str,
- listing: dict,
) -> None:
engine = _skills_engine(monkeypatch, tmp_path)
- recorder = _SequenceRecorder([listing])
+ recorder = _Recorder({"ok": True})
monkeypatch.setattr(skills, "_run_askill", recorder)
try:
- if operation == "remove":
+ if operation == "add":
+ mutation = skills.add_skill(
+ "askill",
+ "gh:owner/repo",
+ scope="global",
+ skill="missing-skill",
+ user_context=_non_member_context(instance_role="viewer"),
+ )
+ elif operation == "remove":
mutation = skills.remove_skill(
"askill",
"missing-skill",
scope="global",
- user_context=_non_member_context(),
+ user_context=_non_member_context(instance_role="viewer"),
)
else:
mutation = skills.update(
"askill",
"missing-skill",
scope="global",
- user_context=_non_member_context(),
+ user_context=_non_member_context(instance_role="viewer"),
)
with pytest.raises(skills.SkillAccessError):
_run(mutation)
finally:
engine.dispose()
- assert [call["args"] for call in recorder.calls] == [["list", "-g"]]
+ assert recorder.calls == []
def test_remote_skill_add_registers_private_policy(monkeypatch, tmp_path) -> None:
@@ -759,33 +758,38 @@ def test_active_org_member_can_replace_installed_legacy_skill(monkeypatch, tmp_p
assert policy["owner_user_id"] == "member-1"
-def test_non_member_skill_add_fails_closed_for_unresolved_installed_backend(monkeypatch, tmp_path) -> None:
+def test_instance_owner_skill_add_does_not_require_organization_membership(
+ monkeypatch,
+ tmp_path,
+) -> None:
engine = _skills_engine(monkeypatch, tmp_path)
- recorder = _SequenceRecorder(
- [
- {
- "ok": True,
- "skills": [{**_skill_row("legacy-skill"), "agents": [{"id": "unknown"}]}],
- }
- ]
- )
+ install_result = {
+ "ok": True,
+ "action": "install",
+ "summary": {"skills": 1},
+ "selectedAgents": ["codex"],
+ "results": [{"skill": "legacy-skill", "success": True}],
+ }
+ recorder = _Recorder(install_result)
monkeypatch.setattr(skills, "_run_askill", recorder)
try:
- with pytest.raises(skills.SkillAccessError):
- _run(
- skills.add_skill(
- "askill",
- "gh:owner/repo",
- scope="global",
- skill="legacy-skill",
- backends=["codex"],
- user_context=_non_member_context(),
- )
+ result = _run(
+ skills.add_skill(
+ "askill",
+ "gh:owner/repo",
+ scope="global",
+ skill="legacy-skill",
+ backends=["codex"],
+ user_context=_non_member_context(),
)
+ )
finally:
engine.dispose()
- assert [call["args"] for call in recorder.calls] == [["list", "-g", "-a", "codex"]]
+ assert result == install_result
+ assert [call["args"] for call in recorder.calls] == [
+ ["add", "gh:owner/repo", "-g", "-a", "codex", "--skill", "legacy-skill", "-y"]
+ ]
def test_active_org_editor_can_upload_skill_zip(monkeypatch, tmp_path) -> None:
@@ -825,6 +829,24 @@ def test_active_org_editor_can_upload_skill_zip(monkeypatch, tmp_path) -> None:
assert (unpack_dir / "uploaded-skill" / "SKILL.md").read_text() == "# Uploaded Skill\n"
+def test_viewer_cannot_upload_skill_zip(monkeypatch) -> None:
+ from vibe import api
+ from vibe.authorization import InstanceAuthorizationError
+
+ async def unexpected_preview(_callback):
+ raise AssertionError("viewer upload must fail before inspecting the archive")
+
+ monkeypatch.setattr(api, "_skills_guarded", unexpected_preview)
+
+ with pytest.raises(InstanceAuthorizationError):
+ _run(
+ api.upload_skill_zip(
+ {"content_base64": "not-an-archive"},
+ user_context=_non_member_context(instance_role="viewer"),
+ )
+ )
+
+
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_project_access.py b/tests/test_ui_project_access.py
index a8e010fb6..d6beac08d 100644
--- a/tests/test_ui_project_access.py
+++ b/tests/test_ui_project_access.py
@@ -191,6 +191,15 @@ def test_active_org_member_can_use_every_project_runtime_surface(monkeypatch, tm
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config, ids = _setup_state(tmp_path)
engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ resource_access_service.ensure_resource_policy(
+ conn,
+ resource_kind="show_page",
+ resource_id=ids["session_a"],
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="public",
+ )
with engine.begin() as conn:
conn.execute(
scopes.update()
@@ -213,7 +222,7 @@ def test_active_org_member_can_use_every_project_runtime_surface(monkeypatch, tm
)
project_rows = _get(client, "/api/projects").get_json()["projects"]
- assert {row["id"] for row in project_rows} == {ids["project_a"], ids["project_b"]}
+ assert {row["id"] for row in project_rows} == {ids["project_a"]}
project_a = next(row for row in project_rows if row["id"] == ids["project_a"])
assert project_a["folder_path"] == str((tmp_path / "project-a").resolve())
assert project_a["metadata"] == {"host_path_hint": "/private/host"}
@@ -221,8 +230,6 @@ def test_active_org_member_can_use_every_project_runtime_surface(monkeypatch, tm
sessions = _get(client, "/api/sessions?status=active").get_json()["sessions"]
assert {row["id"] for row in sessions} == {
ids["session_a"],
- ids["session_b"],
- ids["unscoped"],
}
sessions_by_id = {row["id"]: row for row in sessions}
local_sessions = app.test_client().get(
@@ -230,33 +237,31 @@ def test_active_org_member_can_use_every_project_runtime_surface(monkeypatch, tm
base_url="http://localhost",
).get_json()["sessions"]
local_sessions_by_id = {row["id"]: row for row in local_sessions}
- for session_id in ids["session_a"], ids["session_b"], ids["unscoped"]:
+ for session_id in (ids["session_a"],):
assert sessions_by_id[session_id]["workdir"] == local_sessions_by_id[session_id]["workdir"]
assert sessions_by_id[session_id]["metadata"] == local_sessions_by_id[session_id]["metadata"]
assert _get(client, f"/api/projects/{ids['project_a']}").status_code == 200
- assert _get(client, f"/api/projects/{ids['project_b']}").status_code == 200
+ assert _get(client, f"/api/projects/{ids['project_b']}").status_code == 404
session = _get(client, f"/api/sessions/{ids['session_a']}").get_json()
assert session["workdir"] == str((tmp_path / "project-a").resolve())
assert session["metadata"] == {"created_via": "workbench"}
assert _get(client, f"/api/sessions/{ids['session_a']}/messages").status_code == 200
- assert _get(client, f"/api/sessions/{ids['session_b']}/messages").status_code == 200
- assert _get(client, f"/api/sessions/{ids['unscoped']}").status_code == 200
+ assert _get(client, f"/api/sessions/{ids['session_b']}/messages").status_code == 404
+ assert _get(client, f"/api/sessions/{ids['unscoped']}").status_code == 404
search = _get(client, "/api/search/messages?q=needle").get_json()
assert {row["session_id"] for row in search["sessions"]} == {
ids["session_a"],
- ids["session_b"],
}
inbox = _get(client, "/api/inbox").get_json()
assert {row["session_id"] for row in inbox["sessions"]} == {
ids["session_a"],
- ids["session_b"],
}
- assert set(inbox["unread_by_session"]) == {ids["session_a"], ids["session_b"]}
+ assert set(inbox["unread_by_session"]) == {ids["session_a"]}
media_response = _get(client, f"/api/media/{ids['media_a']}")
assert media_response.status_code == 200
assert media_response.headers["Cache-Control"] == "private, no-store"
- assert _get(client, f"/api/media/{ids['media_b']}").status_code == 200
+ assert _get(client, f"/api/media/{ids['media_b']}").status_code == 404
show_pages = _get(client, "/api/show-pages").get_json()
assert {page["session_id"] for page in show_pages["pages"]} == {
ids["session_a"],
@@ -277,6 +282,26 @@ def test_active_org_member_can_use_every_project_runtime_surface(monkeypatch, tm
)
assert mark_read.status_code == 200
+ allowed_action = client.post(
+ f"/api/sessions/{ids['session_a']}/attachments",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={},
+ )
+ hidden_action = client.post(
+ f"/api/sessions/{ids['session_b']}/attachments",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={},
+ )
+ # Empty JSON is rejected by the upload parser, but the request must reach
+ # the endpoint rather than being stopped by the remote execution gate.
+ assert allowed_action.status_code != 403 or allowed_action.get_json().get("code") != "remote_execution_disabled"
+ assert hidden_action.status_code != 403 or hidden_action.get_json().get("code") != "remote_execution_disabled"
+
+
def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config, ids = _setup_state(tmp_path)
@@ -320,17 +345,17 @@ def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_pat
client = _remote_client(config, role="editor", email="[email protected]")
viewer_project = _get(client, f"/api/projects/{ids['project_a']}").get_json()
- assert viewer_project["capabilities"] == {"can_chat": True}
+ assert viewer_project["capabilities"] == {"can_chat": False}
viewer_bootstrap = _get(client, f"/api/sessions/{ids['session_a']}/bootstrap")
assert viewer_bootstrap.status_code == 200
viewer_payload = viewer_bootstrap.get_json()
- assert viewer_payload["capabilities"] == {"can_chat": True}
- assert viewer_payload["agents"][0]["name"] == "editor-agent"
- assert viewer_payload["default_agent_name"] == "editor-agent"
- assert viewer_payload["queued"][0]["text"] == "editor-only queued prompt"
- assert viewer_payload["draft"] == expected_draft
+ assert viewer_payload["capabilities"] == {"can_chat": False}
+ assert viewer_payload["agents"] == []
+ assert viewer_payload["default_agent_name"] is None
+ assert viewer_payload["queued"] == []
+ assert viewer_payload["draft"] == {"text": ""}
assert [message["text"] for message in viewer_payload["messages"]] == ["shared needle"]
assert viewer_payload["session"]["workdir"] == str((tmp_path / "project-a").resolve())
assert viewer_payload["session"]["metadata"] == {"created_via": "workbench"}
@@ -353,9 +378,9 @@ def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_pat
assert editor_payload["default_agent_name"] == "editor-agent"
assert editor_payload["queued"][0]["text"] == "editor-only queued prompt"
assert editor_payload["draft"] == expected_draft
- assert editor_payload["config"]["runtime"]["default_cwd"] == "."
- assert "agents" in editor_payload["config"]
- assert "memory" not in editor_payload["config"]
+ # Editors receive the non-sensitive runtime UI projection used by ChatPage;
+ # Owner-only management data remains available only to the Owner payload.
+ assert editor_payload["config"]["ui"]["chat_message_font_size"]
assert "remote_access" not in editor_payload["config"]
owner = _remote_client(config, role="owner", email="[email protected]")
@@ -363,7 +388,7 @@ def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_pat
assert owner_payload["config"]["runtime"]["default_cwd"] == "."
assert "agents" in owner_payload["config"]
assert "memory" not in owner_payload["config"]
- assert "remote_access" not in owner_payload["config"]
+ assert "remote_access" in owner_payload["config"]
local_payload = app.test_client().get(
f"/api/sessions/{ids['session_a']}/bootstrap",
@@ -423,18 +448,25 @@ def test_archived_project_invalidates_retained_remote_urls(monkeypatch, tmp_path
)
client = _remote_client(config, role="editor", email="[email protected]")
- assert [row["id"] for row in _get(client, "/api/projects").get_json()["projects"]] == [
- ids["project_b"]
- ]
+ assert _get(client, "/api/projects").get_json()["projects"] == []
archived_project = _get(client, f"/api/projects/{ids['project_a']}")
- assert archived_project.status_code == 200
- assert archived_project.get_json()["archived"] is True
- assert _get(client, f"/api/sessions/{ids['session_a']}/messages").status_code == 200
- assert _get(client, f"/api/media/{ids['media_a']}").status_code == 200
+ assert archived_project.status_code == 404
+ assert _get(client, f"/api/sessions/{ids['session_a']}/messages").status_code == 404
+ assert _get(client, f"/api/media/{ids['media_a']}").status_code == 404
assert _get(client, "/api/show-pages").get_json()["pages"] == [
{"session_id": ids["session_a"]}
]
+ response = client.post(
+ f"/api/sessions/{ids['session_a']}/attachments",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=csrf_headers(client, REMOTE_ORIGIN),
+ json={},
+ )
+ assert response.status_code != 403 or response.get_json().get("code") != "remote_execution_disabled"
+
+
def test_legacy_media_token_uses_all_migrated_session_references(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config, ids = _setup_state(tmp_path)
@@ -593,15 +625,32 @@ def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:
viewer = _remote_client(config, role="viewer", email="[email protected]")
assert _get(viewer, f"/api/sessions/{ids['session_a']}").status_code == 200
- assert _get(viewer, f"/api/sessions/{ids['session_b']}").status_code == 200
+ assert _get(viewer, f"/api/sessions/{ids['session_b']}").status_code == 404
headers = csrf_headers(viewer, REMOTE_ORIGIN)
+ mark_read = viewer.post(
+ f"/api/sessions/{ids['session_a']}/mark-read",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={},
+ )
+ assert mark_read.status_code == 200
+ for action in ("messages", "attachments", "cancel"):
+ response = viewer.post(
+ f"/api/sessions/{ids['session_a']}/{action}",
+ base_url=REMOTE_ORIGIN,
+ environ_base=REMOTE_PEER,
+ headers=headers,
+ json={"text": "viewer must not send"} if action == "messages" else {},
+ )
+ assert response.status_code == 403
assert viewer.post(
"/api/sessions",
base_url=REMOTE_ORIGIN,
environ_base=REMOTE_PEER,
headers=headers,
json={"project_id": ids["project_a"]},
- ).status_code != 403
+ ).status_code == 403
no_match = _remote_client(
config,
@@ -610,6 +659,7 @@ def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:
active_org=False,
)
assert _get(no_match, "/api/projects").status_code == 200
+ assert _get(no_match, "/api/projects").get_json()["projects"] == []
assert _get(no_match, "/api/sessions").status_code == 200
assert _get(no_match, f"/api/sessions/{ids['session_a']}").status_code == 404
no_match_headers = csrf_headers(no_match, REMOTE_ORIGIN)
@@ -621,7 +671,6 @@ def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:
json={"project_id": ids["project_a"]},
)
assert denied.status_code == 403
- assert denied.get_json()["code"] == "project_access_denied"
organization_member = app.test_client()
organization_member.set_cookie(
@@ -639,14 +688,11 @@ def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:
),
domain="alex.avibe.bot",
)
- assert {row["id"] for row in _get(organization_member, "/api/projects").get_json()["projects"]} == {
- ids["project_a"],
- ids["project_b"],
- }
+ assert {row["id"] for row in _get(organization_member, "/api/projects").get_json()["projects"]} == {ids["project_b"]}
assert _get(organization_member, f"/api/sessions/{ids['session_b']}").status_code == 200
- assert _get(organization_member, f"/api/sessions/{ids['session_a']}").status_code == 200
+ assert _get(organization_member, f"/api/sessions/{ids['session_a']}").status_code == 404
assert _get(organization_member, f"/api/media/{ids['media_b']}").status_code == 200
- assert _get(organization_member, f"/api/media/{ids['media_a']}").status_code == 200
+ assert _get(organization_member, f"/api/media/{ids['media_a']}").status_code == 404
owner = _remote_client(config, role="owner", email="[email protected]")
owner_projects = _get(owner, "/api/projects").get_json()["projects"]
@@ -703,10 +749,20 @@ def test_project_access_filters_sse_and_show_websocket(monkeypatch, tmp_path) ->
organization_role="member",
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=ids["session_a"],
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="public",
+ )
visible_payload = json.dumps({"type": "session.status", "data": {"session_id": ids["session_a"]}})
hidden_payload = json.dumps({"type": "session.status", "data": {"session_id": ids["session_b"]}})
assert ui_server._workbench_event_visible_to_context(context, "session.status", visible_payload) is True
- assert ui_server._workbench_event_visible_to_context(context, "session.status", hidden_payload) is True
+ assert ui_server._workbench_event_visible_to_context(context, "session.status", hidden_payload) is False
assert ui_server._workbench_event_visible_to_context(
context,
"authorization.changed",
@@ -722,7 +778,7 @@ def test_project_access_filters_sse_and_show_websocket(monkeypatch, tmp_path) ->
organization_id="org-1",
organization_member_id="member-1",
organization_role="member",
- group_ids=[],
+ group_ids=["grp_beta"],
)
websocket = SimpleNamespace(
client=SimpleNamespace(host="203.0.113.10"),
@@ -739,4 +795,51 @@ def test_project_access_filters_sse_and_show_websocket(monkeypatch, tmp_path) ->
websocket,
minimum_role="viewer",
project_session_id=ids["session_b"],
+ ) is False
+
+
+def test_terminal_websocket_requires_editor_role_without_a_project(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config, _ids = _setup_state(tmp_path)
+ viewer_cookie = remote_session_cookie(
+ config,
+ "user-viewer",
+ role="viewer",
+ access_source="organization_group",
+ organization_id="org-1",
+ organization_member_id="member-viewer",
+ organization_role="member",
+ group_ids=["grp_beta"],
+ )
+ editor_cookie = remote_session_cookie(
+ config,
+ "user-editor",
+ role="editor",
+ access_source="organization_group",
+ organization_id="org-1",
+ organization_member_id="member-1",
+ organization_role="member",
+ group_ids=["grp_beta"],
+ )
+ viewer_socket = SimpleNamespace(
+ client=SimpleNamespace(host="203.0.113.10"),
+ headers={"host": "alex.avibe.bot"},
+ cookies={remote_access.SESSION_COOKIE_NAME: viewer_cookie},
+ url=SimpleNamespace(scheme="wss"),
+ )
+ editor_socket = SimpleNamespace(
+ client=SimpleNamespace(host="203.0.113.10"),
+ headers={"host": "alex.avibe.bot"},
+ cookies={remote_access.SESSION_COOKIE_NAME: editor_cookie},
+ url=SimpleNamespace(scheme="wss"),
+ )
+ assert ui_server._show_runtime_websocket_authorized(
+ viewer_socket,
+ minimum_role="editor",
+ ) is False
+ assert ui_server._show_runtime_websocket_authorized(
+ editor_socket,
+ minimum_role="editor",
) is True
diff --git a/tests/test_ui_resource_access_api.py b/tests/test_ui_resource_access_api.py
index 95d8c7268..62bcce071 100644
--- a/tests/test_ui_resource_access_api.py
+++ b/tests/test_ui_resource_access_api.py
@@ -4,7 +4,8 @@ from config import paths
from storage import resource_access_service
from storage.db import get_cached_sqlite_engine
from storage.migrations import run_migrations
-from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie, save_config
+from tests.ui_server_test_helpers import _save_config
+from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie
from vibe import remote_access
from vibe.ui_server import app
@@ -60,7 +61,7 @@ def _seed_organization_policy() -> None:
def test_organization_context_and_policy_routes_use_signed_cookie_claims(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
_seed_organization_policy()
client = app.test_client()
client.set_cookie(
@@ -102,7 +103,7 @@ def test_organization_context_and_policy_routes_use_signed_cookie_claims(monkeyp
def test_organization_policy_put_does_not_create_local_revision(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
_seed_organization_policy()
client = app.test_client()
client.set_cookie(
@@ -135,7 +136,7 @@ def test_organization_policy_put_does_not_create_local_revision(monkeypatch, tmp
def test_external_guest_cannot_update_an_organization_policy(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = save_config(tmp_path)
+ config = _save_config(tmp_path)
_seed_organization_policy()
client = app.test_client()
client.set_cookie(
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 9c942ce3e..1b776b797 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -2578,21 +2578,44 @@ def test_workbench_events_filter_privileged_events_for_viewers(monkeypatch, tmp_
assert "hidden-secret" not in body
-def test_workbench_events_allow_show_events_to_temporary_org_viewers() -> None:
+def test_workbench_events_allow_show_events_when_show_page_acl_allows(monkeypatch, tmp_path) -> None:
from vibe.authorization import AuthorizationContext
from vibe.sse_broker import broker
from vibe.ui_compat import g
+ from storage import resource_access_service
+ from storage.db import create_sqlite_engine
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ with engine.begin() as connection:
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind="show_page",
+ resource_id="show-session-1",
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="public",
+ )
+ engine.dispose()
async def collect_show_event() -> str:
with app.test_request_context("/api/events"):
g.authorization_context = AuthorizationContext(
instance_role="viewer",
+ subject="viewer-1",
instance_access_source="organization_group",
organization_id="org-1",
organization_member_id="member-1",
organization_role="member",
is_remote=True,
)
+ monkeypatch.setattr(
+ ui_server,
+ "_show_page_resource_access_allowed",
+ lambda context, session_id: session_id == "show-session-1",
+ )
response = await ui_server.workbench_events()
iterator = response.body_iterator.__aiter__()
try:
@@ -2610,6 +2633,7 @@ def test_workbench_events_allow_show_events_to_temporary_org_viewers() -> None:
},
},
)
+ await asyncio.sleep(0)
chunk = await asyncio.wait_for(iterator.__anext__(), timeout=1)
finally:
await iterator.aclose()
diff --git a/tests/test_ui_server_skills_routes.py b/tests/test_ui_server_skills_routes.py
index c0f43be4f..df57c09ce 100644
--- a/tests/test_ui_server_skills_routes.py
+++ b/tests/test_ui_server_skills_routes.py
@@ -36,9 +36,10 @@ def _boom(*_args, **_kwargs):
def test_list_degrades_to_global_with_flag(folderless, monkeypatch):
- async def fake_list(*, scope, project_dir=None, backends=None):
+ async def fake_list(*, scope, project_dir=None, backends=None, user_context=None):
assert scope == "global"
assert project_dir is None
+ assert user_context.is_instance_owner
return {"ok": True, "skills": [{"name": "demo", "scope": "global"}]}
monkeypatch.setattr(api, "list_skills", fake_list)
@@ -100,8 +101,9 @@ def test_check_returns_empty(folderless, monkeypatch):
def test_upload_drops_project_cwd(folderless, monkeypatch):
seen = {}
- async def fake_upload(payload, *, project_dir=None):
+ async def fake_upload(payload, *, project_dir=None, user_context=None):
seen["project_dir"] = project_dir
+ seen["is_instance_owner"] = user_context.is_instance_owner
return {"ok": True, "skills": [], "dir": "/tmp/askill-upload-x"}
monkeypatch.setattr(api, "upload_skill_zip", fake_upload)
@@ -115,14 +117,25 @@ def test_upload_drops_project_cwd(folderless, monkeypatch):
assert res.status_code == 200
assert res.get_json()["ok"] is True
- assert seen["project_dir"] is None # the project cwd was dropped, not errored
+ assert seen == {
+ "project_dir": None,
+ "is_instance_owner": True,
+ }
def test_list_preserves_project_id_for_real_project(monkeypatch):
- async def fake_list(*, scope, project_dir=None, backends=None, project_id=None):
+ async def fake_list(
+ *,
+ scope,
+ project_dir=None,
+ backends=None,
+ project_id=None,
+ user_context=None,
+ ):
assert scope == "project"
assert project_dir == "/tmp/project"
assert project_id == "proj-real"
+ assert user_context.is_instance_owner
return {"ok": True, "skills": [{"name": "demo", "scope": "project"}]}
def fake_resolve(project_id):
@@ -144,9 +157,16 @@ def test_list_preserves_project_id_for_real_project(monkeypatch):
def test_upload_preserves_project_id_for_real_project(monkeypatch):
seen = {}
- async def fake_upload(payload, *, project_dir=None, project_id=None):
+ async def fake_upload(
+ payload,
+ *,
+ project_dir=None,
+ project_id=None,
+ user_context=None,
+ ):
seen["project_dir"] = project_dir
seen["project_id"] = project_id
+ seen["is_instance_owner"] = user_context.is_instance_owner
return {"ok": True, "skills": [], "dir": "/tmp/askill-upload-x"}
def fake_resolve(project_id):
@@ -166,7 +186,11 @@ def test_upload_preserves_project_id_for_real_project(monkeypatch):
assert res.status_code == 200
assert res.get_json()["ok"] is True
- assert seen == {"project_dir": "/tmp/project", "project_id": "proj-real"}
+ assert seen == {
+ "project_dir": "/tmp/project",
+ "project_id": "proj-real",
+ "is_instance_owner": True,
+ }
@pytest.mark.parametrize(
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 545f86244..964730a08 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -1185,7 +1185,7 @@ def test_chat_bootstrap_returns_first_screen_payload(isolated_state, tmp_path):
assert body["turn_state"]["connection"] == "connected"
-def test_chat_bootstrap_filters_non_backend_activities_for_remote_context(isolated_state, tmp_path):
+def test_chat_bootstrap_filters_harness_activities_for_viewer(isolated_state, tmp_path):
from vibe.ui_server import app
monkeypatch = pytest.MonkeyPatch()
@@ -1197,7 +1197,12 @@ def test_chat_bootstrap_filters_non_backend_activities_for_remote_context(isolat
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-owner"),
+ remote_session_cookie(
+ config,
+ "user-viewer",
+ role="viewer",
+ ),
domain="alex.avibe.bot",
)
@@ -1250,7 +1255,7 @@ def test_chat_bootstrap_filters_non_backend_activities_for_remote_context(isolat
assert body["turn_state"]["background_activities"][0]["label"] == "Waiting for approval"
-def test_turn_state_route_filters_non_backend_activities_for_remote_context(isolated_state, tmp_path):
+def test_turn_state_route_preserves_harness_activities_for_editor(isolated_state, tmp_path):
from vibe.ui_server import app
monkeypatch = pytest.MonkeyPatch()
@@ -1262,7 +1267,12 @@ def test_turn_state_route_filters_non_backend_activities_for_remote_context(isol
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-owner"),
+ remote_session_cookie(
+ config,
+ "user-editor",
+ role="editor",
+ ),
domain="alex.avibe.bot",
)
@@ -1303,8 +1313,11 @@ def test_turn_state_route_filters_non_backend_activities_for_remote_context(isol
assert response.status_code == 200
body = response.get_json()
- assert [item["id"] for item in body["background_activities"]] == ["backend-1"]
- assert body["background_activities"][0]["label"] == "Waiting for approval"
+ assert [item["id"] for item in body["background_activities"]] == [
+ "backend-1",
+ "watch-1",
+ ]
+ assert body["background_activities"][1]["label"] == "private waiter prompt"
def test_session_draft_compare_and_set_protects_newer_writes_and_clears(
isolated_state,
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 8703d8e8e..8e0f97fab 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -2,7 +2,6 @@ import asyncio
import base64
import hashlib
import io
-import ipaddress
import json
import os
import socket
@@ -19,15 +18,6 @@ from unittest.mock import patch
import pytest
from config import paths
-from config.v2_config import (
- AgentsConfig,
- PlatformsConfig,
- RemoteAccessConfig,
- RuntimeConfig,
- SlackConfig,
- UiConfig,
- V2Config,
-)
from core.show_pages import (
SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS,
ShowPageStore,
@@ -44,62 +34,19 @@ from core.show_runtime import (
set_show_runtime_manager_for_tests,
)
from storage import resource_access_service
+from tests.ui_server_test_helpers import _mock_interface, _remote_peer, _save_config
from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie
from vibe import remote_access, ui_server
from vibe.ui_server import app
from storage import message_deliveries
-def _mock_interface(monkeypatch, ip: str, prefix: int, name: str = "en0") -> None:
- address = ipaddress.ip_address(ip)
- family = socket.AF_INET if address.version == 4 else socket.AF_INET6
- netmask = str(
- ipaddress.ip_network(f"{'0.0.0.0' if address.version == 4 else '::'}/{prefix}").netmask
- )
- snic = SimpleNamespace(
- family=family,
- address=ip,
- netmask=netmask,
- broadcast=None,
- ptp=None,
- )
- monkeypatch.setattr("vibe.ui_server.psutil.net_if_addrs", lambda: {name: [snic]})
-
-
-def _remote_peer() -> dict[str, str]:
- return {"REMOTE_ADDR": "203.0.113.10"}
-
-
-def _save_config(tmp_path):
- config = V2Config(
- mode="self_host",
- version="v2",
- platform="slack",
- platforms=PlatformsConfig(enabled=["slack"], primary="slack"),
- slack=SlackConfig(bot_token=""),
- runtime=RuntimeConfig(default_cwd="."),
- agents=AgentsConfig(),
- ui=UiConfig(),
- remote_access=RemoteAccessConfig(),
- )
- cloud = config.remote_access.vibe_cloud
- cloud.enabled = True
- cloud.public_url = "https://alex.avibe.bot"
- cloud.client_id = "vr_client_123"
- cloud.instance_id = "inst_123"
- cloud.session_secret = "session-secret"
- cloud.authorization_endpoint = "https://backend.test/oauth/authorize"
- cloud.redirect_uri = "https://alex.avibe.bot/auth/callback"
- config.save()
- return config
-
-
-def _active_org_cookie(config, email="[email protected]", subject="member-1"):
+def _active_org_cookie(config, email="[email protected]", subject="member-1", *, role="editor"):
return remote_session_cookie(
config,
email,
subject,
- role="viewer",
+ role=role,
access_source="organization_group",
organization_id="org-1",
organization_member_id=f"membership-{subject}",
@@ -209,6 +156,18 @@ def _create_show_page(session_id: str, visibility: str) -> str | None:
store = ShowPageStore()
try:
page = store.update_visibility(session_id, visibility)
+ # The factory represents a page that has been published to this test
+ # Organization. Runtime access still requires the caller's Instance role;
+ # this ACL only supplies the independent Show Page entitlement.
+ with store.engine.begin() as connection:
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind="show_page",
+ resource_id=session_id,
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="public",
+ )
return page.share_id
finally:
store.close()
@@ -234,6 +193,15 @@ def _create_show_page_record(session_id: str, visibility: str) -> str | None:
store = ShowPageStore()
try:
page = store.update_visibility(session_id, visibility)
+ with store.engine.begin() as connection:
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind="show_page",
+ resource_id=session_id,
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="public",
+ )
return page.share_id
finally:
store.close()
@@ -1873,7 +1841,7 @@ def _screenshot_event(local_path: str) -> dict:
}
-def test_remote_non_org_owner_cannot_read_private_show_events(monkeypatch, tmp_path):
+def test_remote_owner_can_read_private_show_events(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
_create_show_page("ses123", "private")
@@ -1895,12 +1863,14 @@ def test_remote_non_org_owner_cannot_read_private_show_events(monkeypatch, tmp_p
environ_base=_remote_peer(),
)
- assert response.status_code == 401
- assert response.get_json()["error"] == "remote_access_login_required"
+ assert response.status_code == 200
+ event = response.get_json()["events"][0]
+ assert "path" not in event["payload"]["screenshot"]
+ assert event["payload"]["screenshot"]["attachmentId"] == "med_1"
def test_local_private_show_events_keep_the_local_screenshot_path(monkeypatch, tmp_path):
- # Trusted-local authoring tools still read the materialized file directly.
+ # Local Owner authoring tools still read the materialized file directly.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
_create_show_page("ses123", "private")
@@ -1956,7 +1926,7 @@ def test_remote_private_show_page_denies_at_fs_workspace_symlink_escape(monkeypa
def test_private_show_page_allows_at_fs_workspace_symlink(monkeypatch, tmp_path):
# The private authoring surface intentionally allows a workspace symlink to a
- # disk file (a supported feature) for trusted-local authors. Public and remote
+ # disk file (a supported feature) for local Owner authors. Public and remote
# viewers are confined to the workspace.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -2083,7 +2053,7 @@ def test_public_show_page_denies_at_fs_extra_leading_slash_symlink_escape(monkey
assert ui_server._is_show_page_runtime_denied_path(
decoded, session_id="ses123", confine_to_workspace=True
)
- # The same request stays allowed for a trusted-local author.
+ # The same request stays allowed for a local Owner author.
assert not ui_server._is_show_page_runtime_denied_path(
decoded, session_id="ses123", confine_to_workspace=False
)
@@ -3334,7 +3304,7 @@ def test_public_show_page_clears_show_event_write_cookie(monkeypatch, tmp_path):
def test_show_events_stream_replays_all_persisted_pages_before_live(monkeypatch, tmp_path):
from core.show_session_events import ShowSessionEventStore
- from vibe.authorization import trusted_local_context
+ from vibe.authorization import instance_owner_context
from vibe.ui_server import _show_events_stream
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
@@ -3362,7 +3332,7 @@ def test_show_events_stream_replays_all_persisted_pages_before_live(monkeypatch,
async def _collect_replay() -> str:
response = await _show_events_stream(
"ses123",
- authorization_context=trusted_local_context(),
+ authorization_context=instance_owner_context(),
)
iterator = response.body_iterator.__aiter__()
chunks = []
@@ -3386,7 +3356,7 @@ def test_show_events_stream_replays_all_persisted_pages_before_live(monkeypatch,
def test_show_events_stream_forwards_live_dispatch_events(monkeypatch, tmp_path):
from vibe.sse_broker import broker
- from vibe.authorization import trusted_local_context
+ from vibe.authorization import instance_owner_context
from vibe.ui_server import _show_events_stream
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
@@ -3397,7 +3367,7 @@ def test_show_events_stream_forwards_live_dispatch_events(monkeypatch, tmp_path)
async def _collect_live_dispatch() -> str:
response = await _show_events_stream(
"ses123",
- authorization_context=trusted_local_context(),
+ authorization_context=instance_owner_context(),
)
iterator = response.body_iterator.__aiter__()
chunks = []
@@ -3509,7 +3479,7 @@ def test_private_show_events_stream_ends_when_project_access_is_revoked(monkeypa
assert len(asyncio.run(_collect_until_revoked())) == 1
-def test_remote_org_show_events_stream_stays_open_when_resource_access_is_revoked(
+def test_remote_org_show_events_stream_closes_when_resource_access_is_revoked(
monkeypatch,
tmp_path,
):
@@ -3569,17 +3539,8 @@ def test_remote_org_show_events_stream_stays_open_when_resource_access_is_revoke
"authorization.changed",
{"project_ids": [], "resource_kinds": ["show_page"]},
)
- broker.publish(
- "show.dispatch",
- {
- "session_id": "ses123",
- "scope_id": "scope123",
- "show_event_id": "show_evt_after_acl_change",
- "event": "turn.chunk",
- "data": {"text": "still connected"},
- },
- )
- chunks.append(await asyncio.wait_for(iterator.__anext__(), timeout=1))
+ with pytest.raises(StopAsyncIteration):
+ await asyncio.wait_for(iterator.__anext__(), timeout=1)
finally:
await iterator.aclose()
return "".join(
@@ -3588,8 +3549,7 @@ def test_remote_org_show_events_stream_stays_open_when_resource_access_is_revoke
)
body = asyncio.run(_collect_after_revocation())
- assert "event: show.dispatch" in body
- assert "still connected" in body
+ assert body == ": show events connected\n\n"
def test_public_show_events_stream_redacts_nested_dispatch_ids(monkeypatch, tmp_path):
@@ -5960,8 +5920,22 @@ def test_private_show_page_hmr_websocket_closes_at_authorization_refresh_deadlin
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
_create_show_page("ses123", "private")
+ from storage.db import create_sqlite_engine
+
+ 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()
monkeypatch.setattr(ui_server, "_show_runtime_hmr_origin_allowed", lambda websocket: True)
monkeypatch.setattr(ui_server, "_show_runtime_websocket_authorized", lambda websocket, **kwargs: True)
+ monkeypatch.setattr(ui_server, "_project_session_access_allowed", lambda *args: True)
monkeypatch.setattr(
ui_server,
"_show_runtime_websocket_resource_context",
@@ -6006,7 +5980,7 @@ def test_private_show_page_hmr_websocket_closes_at_authorization_refresh_deadlin
assert proxy_calls == [("started", "ses123"), ("cancelled", "ses123")]
-def test_remote_org_show_page_hmr_stays_open_when_resource_access_is_revoked(
+def test_remote_org_show_page_hmr_closes_when_resource_access_is_revoked(
monkeypatch,
tmp_path,
):
@@ -6104,15 +6078,14 @@ def test_remote_org_show_page_hmr_stays_open_when_resource_access_is_revoked(
"authorization.changed",
{"project_ids": [], "resource_kinds": ["show_page"]},
)
- await asyncio.sleep(0.05)
- assert task.done() is False
- task.cancel()
- with pytest.raises(asyncio.CancelledError):
- await task
+ await asyncio.wait_for(task, timeout=1)
asyncio.run(_run_after_revocation())
- assert websocket.calls == [("accept", "vite-hmr")]
+ assert websocket.calls == [
+ ("accept", "vite-hmr"),
+ ("close", ui_server._AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE),
+ ]
assert proxy_calls == [("started", "ses123"), ("cancelled", "ses123")]
diff --git a/tests/test_v2_config_platform_registry.py b/tests/test_v2_config_platform_registry.py
index fc59d742b..904576b02 100644
--- a/tests/test_v2_config_platform_registry.py
+++ b/tests/test_v2_config_platform_registry.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import pytest
+
from config.v2_config import (
AgentsConfig,
DiscordConfig,
@@ -319,9 +321,19 @@ def test_config_payload_includes_vibe_cloud_remote_access() -> None:
config.remote_access.vibe_cloud.enabled = True
config.remote_access.vibe_cloud.public_url = "https://alex.avibe.bot"
config.remote_access.vibe_cloud.instance_id = "inst_123"
+ config.remote_access.vibe_cloud.instance_kind = "organization"
payload = api.config_to_payload(config)
assert payload["remote_access"]["provider"] == "vibe_cloud"
assert payload["remote_access"]["vibe_cloud"]["enabled"] is True
assert payload["remote_access"]["vibe_cloud"]["public_url"] == "https://alex.avibe.bot"
+ assert payload["remote_access"]["vibe_cloud"]["instance_kind"] == "organization"
+
+
[email protected]("instance_kind", [None, "", "enterprise", 7, [], {}])
+def test_config_degrades_invalid_instance_kind_to_unknown(instance_kind) -> None:
+ payload = api.config_to_payload(_base_config(), include_secrets=True)
+ payload["remote_access"]["vibe_cloud"]["instance_kind"] = instance_kind
+
+ assert V2Config.from_payload(payload).remote_access.vibe_cloud.instance_kind == ""
diff --git a/tests/test_watches.py b/tests/test_watches.py
index 0accb2178..e84a603a1 100644
--- a/tests/test_watches.py
+++ b/tests/test_watches.py
@@ -291,7 +291,7 @@ def test_managed_watch_store_recovery_accepts_empty_command_arguments(tmp_path:
assert recovered[0].command == [sys.executable, "wait.py", ""]
-def test_remote_origin_watch_is_disabled_before_waiter_spawn(tmp_path: Path) -> None:
+def test_malformed_remote_context_disables_watch_before_waiter_spawn(tmp_path: Path) -> None:
store = ManagedWatchStore(tmp_path / "watches.json")
watch = store.add_watch(
name="Legacy remote watch",
@@ -329,7 +329,7 @@ def test_remote_origin_watch_is_disabled_before_waiter_spawn(tmp_path: Path) ->
assert saved is not None
assert saved.enabled is False
assert saved.last_started_at is None
- assert saved.last_error == "remote_autonomous_harness_disabled"
+ assert saved.last_error == "harness_access_forbidden"
def test_managed_watch_exec_uses_stable_supervisor(tmp_path: Path, monkeypatch) -> None:
diff --git a/tests/test_workbench_prefs_api.py b/tests/test_workbench_prefs_api.py
index 17b13abaf..8641be7d6 100644
--- a/tests/test_workbench_prefs_api.py
+++ b/tests/test_workbench_prefs_api.py
@@ -7,7 +7,7 @@ Mutations run at the ``vibe.api`` layer (like the Dock tests); the GET routes an
the session filter are exercised through the Flask-compat test client.
"""
-from tests.ui_server_test_helpers import save_config
+from tests.ui_server_test_helpers import _save_config
from vibe import api
from vibe.ui_server import app
@@ -17,7 +17,7 @@ _NOW = "2026-07-16T00:00:00Z"
def test_banner_pref_api_round_trip(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
from storage.importer import ensure_sqlite_state
ensure_sqlite_state()
@@ -36,7 +36,7 @@ def test_banner_pref_api_round_trip(monkeypatch, tmp_path):
def test_banner_pref_get_route_defaults_on(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
from storage.importer import ensure_sqlite_state
ensure_sqlite_state()
@@ -67,7 +67,7 @@ def _seed_watch(engine, watch_id: str, session_id: str) -> None:
def test_harness_bootstrap_scopes_watches_by_session(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- save_config(tmp_path)
+ _save_config(tmp_path)
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
diff --git a/tests/ui_server_test_helpers.py b/tests/ui_server_test_helpers.py
index 78917c4b4..6a677fb30 100644
--- a/tests/ui_server_test_helpers.py
+++ b/tests/ui_server_test_helpers.py
@@ -1,20 +1,37 @@
from __future__ import annotations
+import ipaddress
+import socket
+from collections import namedtuple
from urllib.parse import urlparse
-from config.v2_config import (
- AgentsConfig,
- PlatformsConfig,
- RemoteAccessConfig,
- RuntimeConfig,
- SlackConfig,
- UiConfig,
- V2Config,
-)
from vibe import remote_access
-def save_config(tmp_path) -> V2Config:
+_FakeSnicaddr = namedtuple("snicaddr", ["family", "address", "netmask", "broadcast", "ptp"])
+
+
+def _remote_peer() -> dict[str, str]:
+ return {"REMOTE_ADDR": "203.0.113.10"}
+
+
+def remote_peer() -> dict[str, str]:
+ """Return the canonical remote test peer environment."""
+
+ return _remote_peer()
+
+
+def _save_config(tmp_path):
+ from config.v2_config import (
+ AgentsConfig,
+ PlatformsConfig,
+ RemoteAccessConfig,
+ RuntimeConfig,
+ SlackConfig,
+ UiConfig,
+ V2Config,
+ )
+
config = V2Config(
mode="self_host",
version="v2",
@@ -38,8 +55,19 @@ def save_config(tmp_path) -> V2Config:
return config
-def remote_peer() -> dict[str, str]:
- return {"REMOTE_ADDR": "203.0.113.10"}
+def save_config(tmp_path):
+ """Return the canonical V2 test configuration."""
+
+ return _save_config(tmp_path)
+
+
+def _mock_interface(monkeypatch, ip: str, prefix: int, name: str = "en0") -> None:
+ address = ipaddress.ip_address(ip)
+ family = socket.AF_INET if address.version == 4 else socket.AF_INET6
+ network = ipaddress.IPv4Network if address.version == 4 else ipaddress.IPv6Network
+ netmask = str(network(f"0.0.0.0/{prefix}" if address.version == 4 else f"::/{prefix}").netmask)
+ snic = _FakeSnicaddr(family=family, address=ip, netmask=netmask, broadcast=None, ptp=None)
+ monkeypatch.setattr("vibe.ui_server.psutil.net_if_addrs", lambda: {name: [snic]})
def remote_session_cookie(
diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsx
index 7a96fd6d6..6f9aa4942 100644
--- a/ui/src/components/AppShell.test.tsx
+++ b/ui/src/components/AppShell.test.tsx
@@ -26,22 +26,28 @@ vi.hoisted(() => {
const api = vi.hoisted(() => ({
getConfig: vi.fn(),
getMemorySettings: vi.fn(),
+ getVersion: vi.fn(),
}));
const status = vi.hoisted(() => ({ state: 'ready' as const }));
const inbox = vi.hoisted(() => ({ totalUnread: 0 }));
const instanceAuth = vi.hoisted(() => ({
remote: true,
- hasTemporaryUnrestrictedOrgAccess: true,
- hasTemporaryUnrestrictedOrgAppAccess: true,
+ instanceKind: null as 'personal' | 'organization' | null,
capabilities: {
can_manage_instance: true,
- can_use_system: false,
- can_manage_agents: false,
- can_manage_projects: false,
- can_use_skills: false,
- can_use_vault_secrets: false,
- can_use_files: false,
- can_use_terminal: false,
+ can_chat: true,
+ can_use_agents: true,
+ can_use_skills: true,
+ can_use_vault_secrets: true,
+ can_use_files: true,
+ can_use_terminal: true,
+ can_use_terminal_files: true,
+ can_use_system: true,
+ can_manage_agents: true,
+ can_manage_projects: true,
+ can_read_instance: true,
+ can_use_show_pages: true,
+ is_instance_owner: true,
},
}));
@@ -50,8 +56,6 @@ vi.mock('../context/StatusContext', () => ({ useStatus: () => ({ status }) }));
vi.mock('../context/WorkbenchInboxContext', () => ({ useWorkbenchInbox: () => inbox }));
vi.mock('../context/InstanceAuthorizationContext', () => ({
useInstanceAuthorization: () => instanceAuth,
- canUseAppsSurface: (remote: boolean, temporaryAccess: boolean | undefined) =>
- !remote || temporaryAccess === true,
}));
vi.mock('../context/DockProvider', () => ({
DockProvider: ({ children, enabled = true }: { children: ReactNode; enabled?: boolean }) => (
@@ -65,6 +69,10 @@ vi.mock('../context/ShowPageDragProvider', () => ({
ShowPageDragProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
vi.mock('./AppsLauncher', () => ({ AppsLauncher: () => <div data-testid="apps-launcher" /> }));
+vi.mock('./AccountMenu', () => ({ AccountMenu: () => null }));
+vi.mock('./LanguageSwitcher', () => ({ LanguageSwitcher: () => null }));
+vi.mock('./ThemeToggle', () => ({ ThemeToggle: () => null }));
+vi.mock('./VersionBadge', () => ({ VersionBadge: () => null }));
vi.mock('./apps/MobileDockDrawer', () => ({
MobileDockDrawer: () => <div data-testid="mobile-dock-drawer" />,
}));
@@ -75,18 +83,27 @@ vi.mock('./workbench/NewSessionSheet', () => ({
vi.mock('./workbench/WorkbenchSidebar', () => ({ WorkbenchSidebar: () => <div /> }));
vi.mock('./workbench/search/SearchPalette', () => ({ SearchPalette: () => null }));
vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
+ useTranslation: () => ({
+ t: (key: string) => key,
+ i18n: {
+ language: 'en',
+ options: { resources: { en: {}, zh: {} } },
+ changeLanguage: vi.fn(),
+ },
+ }),
}));
beforeEach(() => {
+ instanceAuth.instanceKind = null;
instanceAuth.capabilities.can_manage_instance = true;
- instanceAuth.hasTemporaryUnrestrictedOrgAccess = true;
- instanceAuth.hasTemporaryUnrestrictedOrgAppAccess = true;
+ instanceAuth.capabilities.can_chat = true;
+ instanceAuth.capabilities.can_use_show_pages = true;
api.getConfig.mockResolvedValue({ platforms: { enabled: [] } });
api.getMemorySettings.mockResolvedValue({
status: 'failed',
error: 'memory_settings_remote_only',
});
+ api.getVersion.mockResolvedValue({ version: 'test' });
});
afterEach(() => {
@@ -107,19 +124,42 @@ describe('AppShell setup recovery', () => {
);
expect(await screen.findByText('setup.remoteOwner.title')).toBeTruthy();
- expect(screen.getByRole('link', { name: 'setup.remoteOwner.action' }).getAttribute('href')).toBe(
- '/admin/dashboard',
- );
+ expect(screen.getByRole('link', { name: 'setup.remoteOwner.action' }).getAttribute('href')).toBe('/admin/dashboard');
expect(screen.queryByTestId('wizard')).toBeNull();
});
});
+describe('AppShell Organization navigation', () => {
+ it.each([
+ ['personal', 0],
+ [null, 0],
+ ['organization', 2],
+ ] as const)('shows Organization only for %s instances', async (instanceKind, expectedCount) => {
+ instanceAuth.instanceKind = instanceKind;
+
+ render(
+ <MemoryRouter initialEntries={['/admin/dashboard']}>
+ <Routes>
+ <Route element={<AppShell />}>
+ <Route path="admin/dashboard" element={<div data-testid="dashboard" />} />
+ </Route>
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ expect(await screen.findByTestId('dashboard')).toBeTruthy();
+ const organizationEntries = screen.queryAllByText('nav.organization');
+ expect(organizationEntries).toHaveLength(expectedCount);
+ });
+});
+
describe('AppShell remote Apps access', () => {
it.each([
['owner', true],
['member', false],
])('mounts the Apps shell for an authenticated remote %s', async (_role, canManageInstance) => {
instanceAuth.capabilities.can_manage_instance = canManageInstance;
+ instanceAuth.capabilities.can_chat = true;
render(
<MemoryRouter initialEntries={['/']}>
@@ -139,8 +179,7 @@ describe('AppShell remote Apps access', () => {
});
it('hides Apps surfaces and redirects App routes for non-Organization remote users', async () => {
- instanceAuth.hasTemporaryUnrestrictedOrgAccess = false;
- instanceAuth.hasTemporaryUnrestrictedOrgAppAccess = false;
+ instanceAuth.capabilities.can_chat = false;
render(
<MemoryRouter initialEntries={['/apps/library']}>
@@ -166,6 +205,7 @@ describe('AppShell remote Apps access', () => {
['member', false],
])('keeps App Library available to a remote %s', async (_role, canManageInstance) => {
instanceAuth.capabilities.can_manage_instance = canManageInstance;
+ instanceAuth.capabilities.can_chat = true;
render(
<MemoryRouter initialEntries={['/apps/library']}>
@@ -190,6 +230,7 @@ describe('AppShell remote Apps access', () => {
'/apps/show/session-1',
])('keeps the remote App route %s available when legacy capabilities are false', async (path) => {
instanceAuth.capabilities.can_manage_instance = false;
+ instanceAuth.capabilities.can_chat = true;
render(
<MemoryRouter initialEntries={[path]}>
@@ -205,4 +246,44 @@ describe('AppShell remote Apps access', () => {
expect(await screen.findByTestId('app-surface')).toBeTruthy();
expect(screen.queryByTestId('redirected-workbench')).toBeNull();
});
+
+ it('lets a Viewer open an authorized Show Page app without the Editor Apps capability', async () => {
+ instanceAuth.capabilities.can_manage_instance = false;
+ instanceAuth.capabilities.can_chat = false;
+ instanceAuth.capabilities.can_use_show_pages = true;
+
+ render(
+ <MemoryRouter initialEntries={['/apps/show/session-1']}>
+ <Routes>
+ <Route element={<AppShell />}>
+ <Route path="apps/show/:sessionId" element={<div data-testid="show-page-surface" />} />
+ <Route index element={<div data-testid="redirected-workbench" />} />
+ </Route>
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ expect(await screen.findByTestId('show-page-surface')).toBeTruthy();
+ expect(screen.queryByTestId('redirected-workbench')).toBeNull();
+ });
+
+ it('still withholds Editor-only Apps from a Viewer', async () => {
+ instanceAuth.capabilities.can_manage_instance = false;
+ instanceAuth.capabilities.can_chat = false;
+ instanceAuth.capabilities.can_use_show_pages = true;
+
+ render(
+ <MemoryRouter initialEntries={['/apps/library']}>
+ <Routes>
+ <Route element={<AppShell />}>
+ <Route path="apps/library" element={<div data-testid="library-surface" />} />
+ <Route index element={<div data-testid="workbench-surface" />} />
+ </Route>
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ expect(await screen.findByTestId('workbench-surface')).toBeTruthy();
+ expect(screen.queryByTestId('library-surface')).toBeNull();
+ });
});
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 2ed45e5c3..b86c04426 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -11,10 +11,7 @@ import { memoryNavShouldBeVisible } from '../lib/memorySettings';
import { useApi } from '../context/ApiContext';
import { useStatus } from '../context/StatusContext';
import { useWorkbenchInbox } from '../context/WorkbenchInboxContext';
-import {
- canUseAppsSurface,
- useInstanceAuthorization,
-} from '../context/InstanceAuthorizationContext';
+import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';
import { AccountMenu } from './AccountMenu';
import { LanguageSwitcher } from './LanguageSwitcher';
import { ThemeToggle } from './ThemeToggle';
@@ -37,10 +34,10 @@ import { getEnabledPlatforms, platformSupportsChannels } from '../lib/platforms'
import { useViewportHeightVar } from '../lib/useViewportHeightVar';
import {
adminLandingPath,
- filterRuntimeAccessNavItems,
isAdvancedSettingsPath,
- isLocalSystemPathForAccess,
+ isOwnerOnlyPath,
isMemorySettingsPath,
+ visibleAdminNavItems,
} from '../lib/adminNavigation';
type ShellNavItem = {
@@ -62,10 +59,6 @@ type ShellNavItem = {
variant?: 'workbench';
};
-// Organization is exposed from the admin control panel only. The workbench
-// keeps its compact navigation focused on agent work.
-const ORGANIZATION_NAV_ENABLED = true;
-
const isItemActive = (item: ShellNavItem, pathname: string): boolean =>
item.match
? item.match(pathname)
@@ -267,8 +260,8 @@ export const AppShell: React.FC = () => {
const { totalUnread } = useWorkbenchInbox();
const {
capabilities,
+ instanceKind,
remote,
- hasTemporaryUnrestrictedOrgAccess,
} = useInstanceAuthorization();
const api = useApi();
const location = useLocation();
@@ -298,12 +291,12 @@ export const AppShell: React.FC = () => {
useViewportHeightVar();
useEffect(() => {
- if (!capabilities.can_manage_instance && !hasTemporaryUnrestrictedOrgAccess) return;
+ if (!capabilities.can_manage_instance) return;
api.getConfig().then((c: any) => {
setConfig(c);
setEnabledPlatforms(getEnabledPlatforms(c));
}).catch(() => {});
- }, [api, capabilities.can_manage_instance, hasTemporaryUnrestrictedOrgAccess]);
+ }, [api, capabilities.can_manage_instance]);
useEffect(() => {
const refreshMemoryNav = () => {
@@ -372,7 +365,7 @@ export const AppShell: React.FC = () => {
if (
location.pathname === '/setup' &&
remote &&
- (capabilities.can_manage_instance || hasTemporaryUnrestrictedOrgAccess)
+ capabilities.can_manage_instance
) {
return (
<main className="flex min-h-screen items-center justify-center bg-background p-4 text-foreground">
@@ -384,7 +377,7 @@ export const AppShell: React.FC = () => {
<CardContent className="space-y-4">
<p className="text-sm leading-relaxed text-muted">{t('setup.remoteOwner.hint')}</p>
<Button asChild>
- <Link to={adminLandingPath(capabilities.can_use_system, hasTemporaryUnrestrictedOrgAccess === true)}>
+ <Link to={adminLandingPath(capabilities.can_use_system)}>
{t('setup.remoteOwner.action')}
</Link>
</Button>
@@ -397,29 +390,19 @@ export const AppShell: React.FC = () => {
const hasChannelPlatforms = enabledPlatforms.some((platform) => platformSupportsChannels(config, platform));
const modelHubEnabled = modelHubEnabledFromConfig(config);
const isRunning = status.state === 'running';
- const canUseApps = canUseAppsSurface(remote, hasTemporaryUnrestrictedOrgAccess);
- const canUseRuntimeSurfaces = !remote || hasTemporaryUnrestrictedOrgAccess === true;
-
- const ownerOnlyPath =
- location.pathname === '/setup' ||
- (location.pathname.startsWith('/admin') && !location.pathname.startsWith('/admin/organization')) ||
- ['/agents', '/harness'].some(
- (path) => location.pathname === path || location.pathname.startsWith(`${path}/`),
- );
- // The temporary Organization rollout admits these runtime/admin surfaces for
- // active members. Remote Access pairing/tunnel controls stay on their own
- // control-plane route and remain gated by the projected system capability.
- const localSystemPath = isLocalSystemPathForAccess(
- location.pathname,
- canUseRuntimeSurfaces,
- );
+ const canUseApps = capabilities.can_chat;
+ const showOrganizationNavigation = instanceKind === 'organization';
+ const canUseShowPageApp =
+ location.pathname.startsWith('/apps/show/') && capabilities.can_use_show_pages;
+ const localSystemPath = isOwnerOnlyPath(location.pathname);
const resourceUseDenied =
- (location.pathname.startsWith('/skills') && !capabilities.can_use_skills && !canUseRuntimeSurfaces) ||
- (location.pathname.startsWith('/vaults') && !capabilities.can_use_vault_secrets && !canUseRuntimeSurfaces);
- const appAccessDenied = location.pathname.startsWith('/apps/') && !canUseApps;
+ (location.pathname.startsWith('/agents') && !capabilities.can_use_agents) ||
+ (location.pathname.startsWith('/harness') && !capabilities.can_chat) ||
+ (location.pathname.startsWith('/skills') && !capabilities.can_use_skills) ||
+ (location.pathname.startsWith('/vaults') && !capabilities.can_use_vault_secrets);
+ const appAccessDenied = location.pathname.startsWith('/apps/') && !canUseApps && !canUseShowPageApp;
if (
- (ownerOnlyPath && !capabilities.can_manage_instance && !canUseRuntimeSurfaces) ||
- (localSystemPath && !capabilities.can_use_system) ||
+ (localSystemPath && !capabilities.can_manage_instance) ||
resourceUseDenied ||
appAccessDenied
) {
@@ -440,7 +423,7 @@ export const AppShell: React.FC = () => {
const adminItems: ShellNavItem[] = [
{ to: '/admin/dashboard', label: t('nav.dashboard'), icon: LayoutDashboard },
- ...(ORGANIZATION_NAV_ENABLED
+ ...(showOrganizationNavigation
? [{
to: '/admin/organization/overview',
label: t('nav.organization'),
@@ -501,23 +484,20 @@ export const AppShell: React.FC = () => {
];
// Second half of the runtime-access gate: a page the redirect above withholds
- // must not still be advertised, or a remote owner taps a nav entry and lands
- // back on the Workbench. With the temporary Organization rollout every admin
- // surface except remote-access pairing is admitted, so the nav stays full.
- const visibleAdminItems = capabilities.can_use_system
- ? adminItems
- : filterRuntimeAccessNavItems(adminItems, canUseRuntimeSurfaces);
+ // must not still be advertised, or a non-owner taps a nav entry and lands
+ // back on the Workbench.
+ const visibleAdminItems = visibleAdminNavItems(adminItems, capabilities.can_manage_instance);
const items: ShellNavItem[] = shellMode === 'admin' ? visibleAdminItems : [];
// A bottom tab bar can't hold the nested admin nav, so mobile keeps a trimmed
// bar with Workbench, Control Panel, and More (which opens the full nested nav
- // sheet). The Organization tab follows the same temporary visibility switch
- // as every other shell entry point. See ``adminMenuOpen``.
+ // sheet). The Organization tab follows the same capability visibility as
+ // every other shell entry point. See ``adminMenuOpen``.
const adminMobileTabsAll: ShellNavItem[] = [
{ to: '/', label: t('nav.workbench'), icon: Sparkles, variant: 'workbench' },
{ to: '/admin/dashboard', label: t('nav.dashboard'), icon: LayoutDashboard },
- ...(ORGANIZATION_NAV_ENABLED
+ ...(showOrganizationNavigation
? [{ to: '/admin/organization/overview', label: t('nav.organization'), icon: Building2 }]
: []),
{ label: t('nav.more'), icon: Menu, onClick: () => setAdminMenuOpen(true), match: () => adminMenuOpen },
@@ -528,9 +508,7 @@ export const AppShell: React.FC = () => {
match: (pathname) => isAdvancedSettingsPath(pathname, memoryNavVisible),
},
];
- const adminMobileTabs = capabilities.can_use_system
- ? adminMobileTabsAll
- : filterRuntimeAccessNavItems(adminMobileTabsAll, canUseRuntimeSurfaces);
+ const adminMobileTabs = visibleAdminNavItems(adminMobileTabsAll, capabilities.can_manage_instance);
// The More sheet shows the overflow: admin sections not already on the bottom
// bar. Keep its filtering aligned with the currently visible primary tabs.
const adminBottomBarPaths = new Set(
@@ -549,8 +527,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 || capabilities.can_use_skills || capabilities.can_use_vault_secrets || canUseRuntimeSurfaces ? [{
- to: capabilities.can_manage_agents || canUseRuntimeSurfaces ? '/agents' : capabilities.can_use_skills ? '/skills' : '/vaults',
+ ...(capabilities.can_use_agents || capabilities.can_use_skills || capabilities.can_use_vault_secrets ? [{
+ to: capabilities.can_use_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)),
@@ -657,9 +635,9 @@ export const AppShell: React.FC = () => {
Control Panel → Back to Workbench, the mint counterpart. */}
<div className="flex items-stretch gap-2">
{canUseApps && <AppsLauncher />}
- {shellMode === 'workbench' && (capabilities.can_manage_instance || canUseRuntimeSurfaces) && (
+ {shellMode === 'workbench' && capabilities.can_manage_instance && (
<Link
- to={adminLandingPath(capabilities.can_use_system, canUseRuntimeSurfaces)}
+ to={adminLandingPath(capabilities.can_use_system)}
title={t('appShell.openControlPanel')}
aria-label={t('appShell.openControlPanel')}
className="group flex w-11 shrink-0 items-center justify-center rounded-lg border border-border-strong text-foreground transition-colors hover:bg-foreground/[0.04]"
@@ -712,7 +690,7 @@ export const AppShell: React.FC = () => {
/>
{isRunning ? t('common.running') : t('common.stopped')}
</span>
- {(capabilities.can_manage_instance || canUseRuntimeSurfaces) && <VersionBadge openUpward />}
+ {capabilities.can_manage_instance && <VersionBadge openUpward />}
</div>
</div>
</div>
@@ -783,7 +761,7 @@ export const AppShell: React.FC = () => {
) : (
<MobileTabBar
items={workbenchTabs}
- center={(capabilities.can_chat || canUseRuntimeSurfaces)
+ center={capabilities.can_chat
? { onClick: () => setNewSessionOpen(true), label: t('appShell.newSession'), icon: Plus }
: undefined}
/>
@@ -830,7 +808,7 @@ export const AppShell: React.FC = () => {
<MobileDockDrawer open={appsDrawerOpen} onClose={() => setAppsDrawerOpen(false)} />
)}
- {(capabilities.can_chat || canUseRuntimeSurfaces) && (
+ {capabilities.can_chat && (
<NewSessionSheet
open={newSessionOpen}
onClose={() => setNewSessionOpen(false)}
diff --git a/ui/src/components/Workbench.tsx b/ui/src/components/Workbench.tsx
index 8f68d6b83..3a689b812 100644
--- a/ui/src/components/Workbench.tsx
+++ b/ui/src/components/Workbench.tsx
@@ -8,10 +8,7 @@ import { NewProjectDialog } from './workbench/NewProjectDialog';
import { Composer } from './workbench/Composer';
import { ProjectPicker } from './workbench/ProjectPicker';
import { AgentRoutePicker } from './workbench/AgentRoutePicker';
-import {
- canUseRuntimeSurfaces,
- useInstanceAuthorization,
-} from '../context/InstanceAuthorizationContext';
+import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';
import { canCreateLocalProject } from '../lib/sessionInfo';
// Mirrors design.pen DnkGJ "Workbench" canvas: a centered hero panel +
@@ -26,13 +23,10 @@ export const Workbench: React.FC = () => {
const navigate = useNavigate();
const {
capabilities,
- remote,
- hasTemporaryUnrestrictedOrgAccess,
} = useInstanceAuthorization();
- const canUseRuntime = canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess);
- const canCreateProject = canUseRuntime || canCreateLocalProject(capabilities);
+ const canCreateProject = canCreateLocalProject(capabilities);
const ns = useNewSession({
- active: capabilities.can_chat || canUseRuntime,
+ active: capabilities.can_chat,
loadErrorText: t('newSession.loadError'),
createFailedText: t('newSession.createFailed'),
});
@@ -58,15 +52,15 @@ export const Workbench: React.FC = () => {
...(canCreateProject
? [{ key: 'newProject', icon: FolderPlus, onClick: () => setNewProjectOpen(true) }]
: []),
- ...(capabilities.can_manage_agents || canUseRuntime
+ ...(capabilities.can_manage_agents
? [{ key: 'openAgents', icon: Bot, onClick: () => navigate('/agents') }]
: []),
- ...(capabilities.can_manage_instance || canUseRuntime
+ ...(capabilities.can_manage_instance
? [{ key: 'openHarness', icon: Activity, onClick: () => navigate('/harness') }]
: []),
];
- if (!capabilities.can_chat && !canUseRuntime) return <Navigate to="/projects" replace />;
+ if (!capabilities.can_chat) return <Navigate to="/projects" replace />;
return (
// Desktop centers the hero + Composer as a group (min-h + justify-center). On
diff --git a/ui/src/components/settings/SettingsMemoryPage.test.tsx b/ui/src/components/settings/SettingsMemoryPage.test.tsx
index b7286594c..aeab51c52 100644
--- a/ui/src/components/settings/SettingsMemoryPage.test.tsx
+++ b/ui/src/components/settings/SettingsMemoryPage.test.tsx
@@ -8,6 +8,8 @@ import { MemoryRouter } from 'react-router-dom';
import { SettingsMemoryPage } from './SettingsMemoryPage';
import type { MemoryProcessingRecordSummary } from '../../context/ApiContext';
import { memoryCascadeHealth } from '../../test/memoryFixtures';
+import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizationContext';
+import { OWNER_INSTANCE_CAPABILITIES } from '../../lib/sessionInfo';
const api = vi.hoisted(() => ({
abortMemoryClear: vi.fn(),
@@ -129,9 +131,16 @@ const readyProcessingRecord = (): MemoryProcessingRecordSummary => ({
});
const renderPage = () => render(
- <MemoryRouter>
- <SettingsMemoryPage />
- </MemoryRouter>,
+ <InstanceAuthorizationContext.Provider value={{
+ remote: false,
+ instanceKind: null,
+ instanceRole: 'owner',
+ capabilities: OWNER_INSTANCE_CAPABILITIES,
+ }}>
+ <MemoryRouter>
+ <SettingsMemoryPage />
+ </MemoryRouter>
+ </InstanceAuthorizationContext.Provider>,
);
beforeEach(() => {
diff --git a/ui/src/components/settings/SettingsMemoryPage.tsx b/ui/src/components/settings/SettingsMemoryPage.tsx
index 999e4e3b8..9f573d824 100644
--- a/ui/src/components/settings/SettingsMemoryPage.tsx
+++ b/ui/src/components/settings/SettingsMemoryPage.tsx
@@ -25,7 +25,6 @@ import type {
} from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
import { memoryErrorMessage } from '../../lib/memoryRead';
-import { canAdministerMemory } from '../../lib/remoteAuth';
type MemoryTab = 'processingRecord' | 'profile' | 'search' | 'settings';
@@ -37,11 +36,8 @@ export const SettingsMemoryPage: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
- const { remote, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
- const canAdminister = canAdministerMemory({
- remote,
- temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
- });
+ const { capabilities } = useInstanceAuthorization();
+ const canAdminister = capabilities.can_manage_instance;
const [tab, setTab] = useState<MemoryTab>('processingRecord');
const [clearOpen, setClearOpen] = useState(false);
diff --git a/ui/src/components/settings/SettingsMessagingPage.test.tsx b/ui/src/components/settings/SettingsMessagingPage.test.tsx
index 197d34d04..044666963 100644
--- a/ui/src/components/settings/SettingsMessagingPage.test.tsx
+++ b/ui/src/components/settings/SettingsMessagingPage.test.tsx
@@ -52,12 +52,14 @@ const baseConfig = {
const localOwner: InstanceAuthorizationValue = {
remote: false,
+ instanceKind: null,
instanceRole: 'owner',
capabilities: OWNER_INSTANCE_CAPABILITIES,
};
const remoteOwner: InstanceAuthorizationValue = {
remote: true,
+ instanceKind: null,
instanceRole: 'owner',
capabilities: {
...OWNER_INSTANCE_CAPABILITIES,
@@ -65,10 +67,9 @@ const remoteOwner: InstanceAuthorizationValue = {
},
};
-const activeOrgMember: InstanceAuthorizationValue = {
+const remoteEditor: InstanceAuthorizationValue = {
...remoteOwner,
- instanceRole: 'viewer',
- hasTemporaryUnrestrictedOrgAccess: true,
+ instanceRole: 'editor',
};
function renderPage(context: InstanceAuthorizationValue) {
@@ -103,7 +104,7 @@ describe('SettingsMessagingPage locality gating', () => {
expect(screen.queryByText('dashboard.showPagesPrompt')).toBeNull();
});
- it('shows the protected messaging controls to a trusted-local owner', async () => {
+ it('shows the protected messaging controls to a local owner', async () => {
renderPage(localOwner);
expect(await screen.findByText('dashboard.errorRetryLimit')).toBeTruthy();
@@ -111,11 +112,12 @@ describe('SettingsMessagingPage locality gating', () => {
expect(screen.getByText('dashboard.showPagesPrompt')).toBeTruthy();
});
- it('shows every runtime messaging control to an active Organization member', async () => {
- renderPage(activeOrgMember);
+ it('keeps owner-only runtime messaging controls hidden from an Editor', async () => {
+ renderPage(remoteEditor);
- expect(await screen.findByText('dashboard.errorRetryLimit')).toBeTruthy();
- expect(screen.getByText('dashboard.opencodeActiveTurnTimeout')).toBeTruthy();
- expect(screen.getByText('dashboard.showPagesPrompt')).toBeTruthy();
+ await screen.findByText('dashboard.ackMode');
+ expect(screen.queryByText('dashboard.errorRetryLimit')).toBeNull();
+ expect(screen.queryByText('dashboard.opencodeActiveTurnTimeout')).toBeNull();
+ expect(screen.queryByText('dashboard.showPagesPrompt')).toBeNull();
});
});
diff --git a/ui/src/components/settings/SettingsMessagingPage.tsx b/ui/src/components/settings/SettingsMessagingPage.tsx
index 27ce8114c..d6c669ff7 100644
--- a/ui/src/components/settings/SettingsMessagingPage.tsx
+++ b/ui/src/components/settings/SettingsMessagingPage.tsx
@@ -71,8 +71,8 @@ function formatSavedAt(value: number | null, t: (key: string) => string) {
export const SettingsMessagingPage: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
- const { capabilities, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
- const canUseSystem = capabilities.can_use_system || hasTemporaryUnrestrictedOrgAccess === true;
+ const { capabilities } = useInstanceAuthorization();
+ const canUseSystem = capabilities.can_use_system;
const [config, setConfig] = useState<any>(null);
const [saveError, setSaveError] = useState<string | null>(null);
const [savedAt, setSavedAt] = useState<number | null>(null);
diff --git a/ui/src/components/ui/vault-approval-card.tsx b/ui/src/components/ui/vault-approval-card.tsx
index 41f2f98aa..8578ef8dd 100644
--- a/ui/src/components/ui/vault-approval-card.tsx
+++ b/ui/src/components/ui/vault-approval-card.tsx
@@ -11,7 +11,6 @@ import {
type VaultSourceSelector,
} from '@/context/ApiContext';
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
-import { canManageVaultSecrets } from '@/lib/remoteAuth';
import { partitionTags } from '@/lib/vaultTags';
import { useProtectedVault, type ProtectedUnlockMaterial } from '@/lib/useProtectedVault';
import { SigningAddressList } from './signing-address-list';
@@ -116,7 +115,7 @@ export const VaultApprovalCard: React.FC<{
const { t } = useTranslation();
const api = useApi();
const vault = useProtectedVault();
- const { remote, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
+ const { capabilities } = useInstanceAuthorization();
// The request is passed in already hydrated by the UI-audience inbox list
// (`getVaultRequests`, #708), so `card.secret_unlock_material` /
@@ -360,10 +359,7 @@ export const VaultApprovalCard: React.FC<{
);
}
- const canApprove = canManageVaultSecrets({
- remote,
- temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
- });
+ const canApprove = capabilities.can_use_vault_secrets;
const approveDisabled = busy || !canApprove || (!isSign && !option);
return (
diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsx
index 8014cb445..2cb09f16f 100644
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@ -33,10 +33,7 @@ import type {
VibeAgentOnboardingResult,
VibeAgentUpdatePayload,
} from '../../context/ApiContext';
-import {
- canUseRuntimeSurfaces,
- useInstanceAuthorization,
-} from '../../context/InstanceAuthorizationContext';
+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
import { AgentGraphTab } from './AgentGraphTab';
import { useToast } from '../../context/ToastContext';
import { NewAgentDialog } from './NewAgentDialog';
@@ -53,7 +50,6 @@ import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { estimateTokens } from '../../lib/tokenEstimate';
import { loadBackendModelsWithRefresh, modelOptionLabel } from '../../lib/backendModels';
import { resolveEffortOptions } from '../../lib/effortOptions';
-import { canEditAgentDefinitions } from '../../lib/remoteAuth';
import { WorkbenchPageHeader } from './WorkbenchPageHeader';
import { CapabilityTabs } from './CapabilityTabs';
// Backend order / labels / accent classes live in lib/backendAccent, shared
@@ -84,10 +80,7 @@ export const AgentsPage: React.FC = () => {
const { showToast } = useToast();
const {
capabilities,
- remote,
- hasTemporaryUnrestrictedOrgAccess,
} = useInstanceAuthorization();
- const canUseRuntime = canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess);
// General navigation (sidebar / nav / capability tabs) resumes the tab the user
// left the page on; a fresh browser opens Definitions. A contextual caller that
// needs a specific tab passes ``?tab=`` and wins over the memory — the tab it
@@ -126,15 +119,12 @@ export const AgentsPage: React.FC = () => {
// Mobile drill-down: a row tap opens the detail full-screen. The agent
// auto-selected on mount stays in the list view until the user drills in.
const [detailOpen, setDetailOpen] = useState(false);
- const visibleTabs = remote && !canUseRuntime ? (['definitions'] as const) : AGENTS_TAB_ORDER;
- const activeTab = remote && !canUseRuntime ? 'definitions' : agentsTab;
- const canEditAgents = canEditAgentDefinitions({
- remote,
- temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
- });
+ const visibleTabs = capabilities.can_use_agents ? AGENTS_TAB_ORDER : (['definitions'] as const);
+ const activeTab = capabilities.can_use_agents ? agentsTab : 'definitions';
+ const canEditAgents = capabilities.can_manage_agents;
const refreshOnboarding = useCallback(async () => {
- if (!capabilities.can_manage_agents && !canUseRuntime) {
+ if (!capabilities.can_manage_agents) {
setOnboardingInventory(null);
return;
}
@@ -144,7 +134,7 @@ export const AgentsPage: React.FC = () => {
} catch {
setOnboardingInventory(null);
}
- }, [api, capabilities.can_manage_agents, canUseRuntime]);
+ }, [api, capabilities.can_manage_agents]);
const refresh = useCallback(async () => {
setLoading(true);
@@ -192,7 +182,7 @@ export const AgentsPage: React.FC = () => {
}, [selected]);
const fetchRunningActiveCount = useCallback(async () => {
- if (remote && !canUseRuntime) {
+ if (!capabilities.can_use_agents) {
setRunningActiveCount(null);
return;
}
@@ -210,7 +200,7 @@ export const AgentsPage: React.FC = () => {
} catch {
setRunningActiveCount(null);
}
- }, [api, canUseRuntime, remote]);
+ }, [api, capabilities.can_use_agents]);
// Keep the badge fresh on every tab (including 运行) so it never depends on
// the graph view's filters.
@@ -219,7 +209,7 @@ export const AgentsPage: React.FC = () => {
}, [fetchRunningActiveCount]);
useEffect(() => {
- if (remote && !canUseRuntime) {
+ if (!capabilities.can_use_agents) {
setEventBridgeConnected(false);
return;
}
@@ -241,10 +231,10 @@ export const AgentsPage: React.FC = () => {
onSessionStatus: () => fetchRunningActiveCount(),
onAuthorizationChanged: () => void refresh(),
});
- }, [api, canUseRuntime, fetchRunningActiveCount, refresh, remote]);
+ }, [api, capabilities.can_use_agents, fetchRunningActiveCount, refresh]);
useEffect(() => {
- if (remote && !canUseRuntime) return;
+ if (!capabilities.can_use_agents) return;
// Reconcile the badge even while SSE is connected: process death / orphan /
// reap is a sampled snapshot with no run/session SSE event, so a slow
// liveness poll keeps the count fresh (30s connected, 8s disconnected),
@@ -294,7 +284,7 @@ export const AgentsPage: React.FC = () => {
document.removeEventListener('visibilitychange', refreshNow);
window.removeEventListener('focus', refreshNow);
};
- }, [canUseRuntime, eventBridgeConnected, fetchRunningActiveCount, remote]);
+ }, [capabilities.can_use_agents, eventBridgeConnected, fetchRunningActiveCount]);
const selectAgent = useCallback(
async (name: string, openDetail = false) => {
@@ -509,8 +499,8 @@ export const AgentsPage: React.FC = () => {
})}
</div>
- {/* The run graph follows the temporary Organization runtime policy. */}
- {(!remote || canUseRuntime) && activeTab === 'running' && <AgentGraphTab />}
+ {/* The run graph follows the Agent capability. */}
+ {capabilities.can_use_agents && activeTab === 'running' && <AgentGraphTab />}
{activeTab === 'definitions' && onboardingInventory && (
<OrganizationAgentOnboarding
diff --git a/ui/src/components/workbench/CapabilityTabs.test.tsx b/ui/src/components/workbench/CapabilityTabs.test.tsx
index 3276f5f63..f89b3edb9 100644
--- a/ui/src/components/workbench/CapabilityTabs.test.tsx
+++ b/ui/src/components/workbench/CapabilityTabs.test.tsx
@@ -21,21 +21,23 @@ function renderWith(context: InstanceAuthorizationValue, path = '/agents') {
const localOwner: InstanceAuthorizationValue = {
remote: false,
+ instanceKind: null,
instanceRole: 'owner',
capabilities: OWNER_INSTANCE_CAPABILITIES,
};
describe('CapabilityTabs', () => {
- it('shows the Harness tab to a trusted-local owner', () => {
+ it('shows the Harness tab to a local owner', () => {
const markup = renderWith(localOwner);
expect(markup).toContain('workbench.modules.harness.title');
});
- it('shows the Harness tab for an active Organization member', () => {
+ it('shows the Harness tab for an Editor', () => {
const remoteOwner: InstanceAuthorizationValue = {
...localOwner,
remote: true,
- hasTemporaryUnrestrictedOrgAccess: true,
+ instanceRole: 'editor',
+ capabilities: { ...OWNER_INSTANCE_CAPABILITIES, can_manage_instance: false },
};
const markup = renderWith(remoteOwner);
expect(markup).toContain('workbench.modules.agents.title');
diff --git a/ui/src/components/workbench/CapabilityTabs.tsx b/ui/src/components/workbench/CapabilityTabs.tsx
index 48e300810..fd575d436 100644
--- a/ui/src/components/workbench/CapabilityTabs.tsx
+++ b/ui/src/components/workbench/CapabilityTabs.tsx
@@ -3,11 +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 {
- canUseRuntimeSurfaces,
- useInstanceAuthorization,
-} from '../../context/InstanceAuthorizationContext';
-import { canUseHarness } from '../../lib/remoteAuth';
+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
const TABS = [
{ to: '/agents', icon: Bot, key: 'workbench.modules.agents.title' },
@@ -26,19 +22,12 @@ export const CapabilityTabs: React.FC = () => {
const activeTabRef = useRef<HTMLAnchorElement | null>(null);
const {
capabilities,
- remote,
- hasTemporaryUnrestrictedOrgAccess,
} = useInstanceAuthorization();
- const canUseRuntime = canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess);
const tabs = TABS.filter(({ to }) => {
- if (canUseRuntime) return true;
- if (to === '/harness') return (capabilities.can_manage_agents || canUseRuntime) && canUseHarness({
- remote,
- temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
- });
- if (to === '/agents') return capabilities.can_manage_agents || canUseRuntime;
- if (to === '/skills') return capabilities.can_use_skills || canUseRuntime;
- if (to === '/vaults') return capabilities.can_use_vault_secrets || canUseRuntime;
+ if (to === '/harness') return capabilities.can_chat;
+ if (to === '/agents') return capabilities.can_use_agents;
+ if (to === '/skills') return capabilities.can_use_skills;
+ if (to === '/vaults') return capabilities.can_use_vault_secrets;
return false;
});
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 42d1753b4..d3479b3cc 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -9,11 +9,7 @@ import { useApi } from '../../context/ApiContext';
import { selectApiErrorFields } from '../../context/apiErrorParse';
import { useToast } from '../../context/ToastContext';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
-import {
- canUseAppsSurface,
- canUseRuntimeSurfaces,
- useInstanceAuthorization,
-} from '../../context/InstanceAuthorizationContext';
+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
import { useRegisterComposerTarget, type ComposerInsertTarget } from '../../context/ComposerBridgeContext';
import { useWindowManager } from '../../context/WindowManagerContext';
import type { SessionActivityItemKind, SessionActivityState, SessionRuntimeState, VaultRequest, VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
@@ -214,16 +210,10 @@ export const ChatPage: React.FC = () => {
const api = useApi();
const {
capabilities,
- remote,
- hasTemporaryUnrestrictedOrgAccess,
} = useInstanceAuthorization();
const [sessionCanChat, setSessionCanChat] = useState(false);
- const canUseRuntime = canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess);
- const canChat = (capabilities.can_chat || canUseRuntime) && sessionCanChat;
- const canUseApps = canUseAppsSurface(remote, hasTemporaryUnrestrictedOrgAccess);
- const canManageShowPageAsInstance = canUseApps && (
- capabilities.can_use_show_pages || canUseRuntime
- );
+ const canChat = capabilities.can_chat && sessionCanChat;
+ const canManageShowPageAsInstance = capabilities.can_use_show_pages;
const [showPageAccessResult, setShowPageAccessResult] = useState<{
sessionId: string;
probe: ShowPageAccessProbe;
@@ -2408,7 +2398,7 @@ export const ChatPage: React.FC = () => {
showPageAccess={showPageAccess}
canOpenShowPage={canOpenShowPage}
canManageShowPage={canManageShowPage}
- canManageInstance={capabilities.can_manage_instance || canUseRuntime}
+ canManageInstance={capabilities.can_manage_instance}
sessionActions={sessionActions}
titleFieldRef={titleFieldRef}
/>
@@ -2495,7 +2485,7 @@ export const ChatPage: React.FC = () => {
// BEFORE the archive still holds them in state, though — the same
// stale-tab case that reaches the archived 409 — and their
// approve/deny buttons would write to a session that can't accept it.
- sessionId && !readOnly && (capabilities.can_manage_instance || canUseRuntime) ? (
+ sessionId && !readOnly && capabilities.can_use_vault_secrets ? (
<VaultChatRequests
requests={pendingApprovals}
onResolved={refreshVaultRequests}
@@ -2516,7 +2506,7 @@ export const ChatPage: React.FC = () => {
{writable && (
<QueueStrip queue={queue} onRemove={removeQueued} onRecall={recallQueued} onSendNow={sendQueueNow} />
)}
- {sessionId && !readOnly && (capabilities.can_manage_instance || canUseRuntime) && pendingApprovals.length > 0 ? (
+ {sessionId && !readOnly && capabilities.can_use_vault_secrets && pendingApprovals.length > 0 ? (
<VaultApprovalFloat offscreen={offscreenApprovals} pending={pendingApprovals} onResolved={refreshVaultRequests} />
) : null}
{/* key by session so the composer remounts per session — its draft-seeding
diff --git a/ui/src/components/workbench/InboxPage.tsx b/ui/src/components/workbench/InboxPage.tsx
index 79a53163c..20ea2e597 100644
--- a/ui/src/components/workbench/InboxPage.tsx
+++ b/ui/src/components/workbench/InboxPage.tsx
@@ -24,10 +24,7 @@ export const InboxPage: React.FC = () => {
const navigate = useNavigate();
const {
capabilities,
- remote,
- hasTemporaryUnrestrictedOrgAccess,
} = useInstanceAuthorization();
- const canUseRuntime = !remote || hasTemporaryUnrestrictedOrgAccess === true;
const {
inboxSessions,
unreadBySession,
@@ -194,8 +191,8 @@ export const InboxPage: React.FC = () => {
))}
</div>
<div className="flex min-w-0 flex-wrap items-center gap-2 sm:ml-auto sm:justify-end">
- {(capabilities.can_manage_instance || canUseRuntime) && <WebPushControl />}
- {(capabilities.can_chat || canUseRuntime) && (
+ {capabilities.can_read_instance && <WebPushControl />}
+ {capabilities.can_chat && (
<button
type="button"
onClick={onMarkAllRead}
@@ -297,7 +294,7 @@ export const InboxPage: React.FC = () => {
{t('workbench.inbox.openSession')}
<ArrowRight className="size-3" />
</button>
- {(capabilities.can_chat || canUseRuntime) && unread > 0 && (
+ {capabilities.can_chat && unread > 0 && (
<button
type="button"
onClick={() => markRead(s.session_id)}
diff --git a/ui/src/components/workbench/ProjectPicker.tsx b/ui/src/components/workbench/ProjectPicker.tsx
index d771cb8f7..4efa468b1 100644
--- a/ui/src/components/workbench/ProjectPicker.tsx
+++ b/ui/src/components/workbench/ProjectPicker.tsx
@@ -4,10 +4,7 @@ import clsx from 'clsx';
import type { WorkbenchProject } from '../../context/ApiContext';
import { Button } from '../ui/button';
-import {
- canUseRuntimeSurfaces,
- useInstanceAuthorization,
-} from '../../context/InstanceAuthorizationContext';
+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
import { canCreateLocalProject } from '../../lib/sessionInfo';
interface ProjectPickerProps {
@@ -27,12 +24,8 @@ export const ProjectPicker: React.FC<ProjectPickerProps> = ({ projects, targetId
const { t } = useTranslation();
const {
capabilities,
- remote,
- hasTemporaryUnrestrictedOrgAccess,
} = useInstanceAuthorization();
- const canCreateProject =
- canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess) ||
- canCreateLocalProject(capabilities);
+ const canCreateProject = canCreateLocalProject(capabilities);
return (
// min-w-0 lets this shrink inside the sheet's CSS grid so the chip row
// scrolls horizontally instead of stretching the whole sheet wide.
diff --git a/ui/src/components/workbench/ProjectSettingsDialog.tsx b/ui/src/components/workbench/ProjectSettingsDialog.tsx
index 3b4b44fef..f876bbaae 100644
--- a/ui/src/components/workbench/ProjectSettingsDialog.tsx
+++ b/ui/src/components/workbench/ProjectSettingsDialog.tsx
@@ -5,10 +5,7 @@ import { FileText } from 'lucide-react';
import { useApi } from '../../context/ApiContext';
import type { ProjectDefaultAgent, VibeAgentBrief, WorkbenchProject } from '../../context/ApiContext';
-import {
- canUseRuntimeSurfaces,
- useInstanceAuthorization,
-} from '../../context/InstanceAuthorizationContext';
+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
import { Button } from '../ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../ui/dialog';
@@ -16,7 +13,6 @@ import { InfoHint } from '../ui/info-hint';
import { AgentRoutePicker } from './AgentRoutePicker';
import type { AgentRoutePatch } from './AgentRoutePicker';
import { ProjectAgentsMdDialog } from './ProjectAgentsMdDialog';
-import { canEditProjectDefaultAgent, canEditProjectInstructions } from '../../lib/remoteAuth';
// Per-project settings. Three sections:
// 1. Working directory (read-only) — where the Agent runs.
@@ -34,17 +30,10 @@ export const ProjectSettingsDialog: React.FC<{
const { t } = useTranslation();
const api = useApi();
const { setProjectDefaultAgent } = useWorkbenchProjectsTree();
- const { capabilities, remote, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
- const canUseRuntime = canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess);
- const canManageProjects = capabilities.can_manage_projects || canUseRuntime;
- const canEditAgentsMd = canManageProjects && canEditProjectInstructions({
- remote,
- temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
- });
- const canEditDefaultAgent = canManageProjects && canEditProjectDefaultAgent({
- remote,
- temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
- });
+ const { capabilities } = useInstanceAuthorization();
+ const canManageProjects = capabilities.can_manage_projects;
+ const canEditAgentsMd = canManageProjects;
+ const canEditDefaultAgent = canManageProjects;
const [agents, setAgents] = useState<VibeAgentBrief[]>([]);
const [agentsMdOpen, setAgentsMdOpen] = useState(false);
diff --git a/ui/src/components/workbench/ProjectsPage.tsx b/ui/src/components/workbench/ProjectsPage.tsx
index 11a722f50..55f698482 100644
--- a/ui/src/components/workbench/ProjectsPage.tsx
+++ b/ui/src/components/workbench/ProjectsPage.tsx
@@ -21,14 +21,10 @@ import clsx from 'clsx';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
-import {
- canUseRuntimeSurfaces,
- useInstanceAuthorization,
-} from '../../context/InstanceAuthorizationContext';
+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
import type { ProjectSessionsState } from '../../context/WorkbenchProjectsContext';
import type { WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
import { formatRelativeTime } from '../../lib/relativeTime';
-import { canArchiveProjects, canEditProjectInstructions } from '../../lib/remoteAuth';
import { canCreateLocalProject } from '../../lib/sessionInfo';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
@@ -85,17 +81,10 @@ const MobileProjectRow: React.FC<{
}> = ({ project, open, state, onToggle }) => {
const { t } = useTranslation();
const navigate = useNavigate();
- const { capabilities, remote, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
- const canUseRuntime = canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess);
- const canManageProjects = capabilities.can_manage_projects || canUseRuntime;
- const canArchive = canManageProjects && canArchiveProjects({
- remote,
- temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
- });
- const canEditAgentsMd = canManageProjects && canEditProjectInstructions({
- remote,
- temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
- });
+ const { capabilities } = useInstanceAuthorization();
+ const canManageProjects = capabilities.can_manage_projects;
+ const canArchive = canManageProjects;
+ const canEditAgentsMd = canManageProjects;
const { renameProject, archiveProject, createSessionForProject } = useWorkbenchProjectsTree();
const [menuOpen, setMenuOpen] = useState(false);
// Guards against a double-tap creating two sessions before navigation unmounts.
@@ -108,7 +97,7 @@ const MobileProjectRow: React.FC<{
// Enter (or blur) commits, then the input unmounts and its blur fires again;
// Escape cancels and must not let that trailing blur commit the stale draft.
const handledRef = useRef(false);
- const canChat = (capabilities.can_chat || canUseRuntime) && (canUseRuntime || project.capabilities.can_chat);
+ const canChat = capabilities.can_chat && project.capabilities.can_chat;
useEffect(() => {
if (renaming) inputRef.current?.focus();
@@ -391,11 +380,8 @@ export const ProjectsPage: React.FC = () => {
const navigate = useNavigate();
const {
capabilities,
- remote,
- hasTemporaryUnrestrictedOrgAccess,
} = useInstanceAuthorization();
- const canUseRuntime = canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess);
- const canCreateProject = canUseRuntime || canCreateLocalProject(capabilities);
+ const canCreateProject = canCreateLocalProject(capabilities);
const { unreadBySession } = useWorkbenchInbox();
const {
projects,
@@ -505,8 +491,8 @@ export const ProjectsPage: React.FC = () => {
projectId={project.id}
session={session}
unread={unreadBySession[session.id] ?? 0}
- canChat={(capabilities.can_chat || canUseRuntime) && (canUseRuntime || project.capabilities.can_chat)}
- canManageMetadata={canUseRuntime || project.capabilities.can_chat}
+ canChat={capabilities.can_chat && project.capabilities.can_chat}
+ canManageMetadata={capabilities.can_manage_projects || project.capabilities.can_chat}
onOpen={() => openSession(session.id)}
/>
))}
diff --git a/ui/src/components/workbench/SkillsPage.tsx b/ui/src/components/workbench/SkillsPage.tsx
index 8713c1b4d..bcbe47c7c 100644
--- a/ui/src/components/workbench/SkillsPage.tsx
+++ b/ui/src/components/workbench/SkillsPage.tsx
@@ -19,11 +19,7 @@ import { AddSkillDialog } from './skills/AddSkillDialog';
import { BrowseRegistryDialog } from './skills/BrowseRegistryDialog';
import { errorMessage } from '@/lib/errorMessage';
import { Badge } from '../ui/badge';
-import { canManageSkills } from '../../lib/remoteAuth';
-import {
- canUseRuntimeSurfaces,
- useInstanceAuthorization,
-} from '../../context/InstanceAuthorizationContext';
+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
const skillKey = (s: SkillBrief) => `${s.scope}:${s.name}`;
@@ -31,14 +27,8 @@ export const SkillsPage: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
- const { capabilities, remote, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
- const canUseRuntime = canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess);
- const canManage =
- (capabilities.can_manage_instance || canUseRuntime) &&
- canManageSkills({
- remote,
- temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
- });
+ const { capabilities } = useInstanceAuthorization();
+ const canManage = capabilities.can_use_skills;
const [scope, setScope] = useState<SkillScope>('global');
const [projects, setProjects] = useState<WorkbenchProject[]>([]);
@@ -306,7 +296,7 @@ export const SkillsPage: React.FC = () => {
{t('skills.addSkill')}
</Button>
</>
- ) : remote && !canUseRuntime ? (
+ ) : !capabilities.can_use_skills ? (
<Badge variant="secondary" title={t('skills.remoteReadOnlyHint')}>
<Lock className="size-3" />
{t('skills.remoteReadOnly')}
diff --git a/ui/src/components/workbench/VaultsPage.test.tsx b/ui/src/components/workbench/VaultsPage.test.tsx
index 0672cd2cd..5adf1c4a4 100644
--- a/ui/src/components/workbench/VaultsPage.test.tsx
+++ b/ui/src/components/workbench/VaultsPage.test.tsx
@@ -29,12 +29,11 @@ const remoteOwner = {
const activeOrgMember = {
remote: true,
- instanceRole: 'viewer' as const,
- hasTemporaryUnrestrictedOrgAccess: true,
+ instanceRole: 'editor' as const,
capabilities: {
...OWNER_INSTANCE_CAPABILITIES,
can_manage_instance: false,
- can_use_vault_secrets: false,
+ can_use_vault_secrets: true,
can_use_system: false,
},
};
@@ -100,7 +99,7 @@ describe('VaultsPage remote audit history', () => {
renderPage();
const history = await screen.findByRole('button', { name: 'vaults.history' });
- expect(screen.queryByRole('button', { name: 'vaults.add' })).toBeNull();
+ expect(screen.getByRole('button', { name: 'vaults.add' })).toBeTruthy();
await user.click(history);
@@ -110,7 +109,7 @@ describe('VaultsPage remote audit history', () => {
expect(await screen.findByText('alpha')).toBeTruthy();
});
- it('shows Vault management controls to an active Organization member', async () => {
+ it('shows Vault management controls to an Editor', async () => {
renderPage(activeOrgMember);
expect(await screen.findByRole('button', { name: 'vaults.add' })).toBeTruthy();
diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsx
index 24cfeb968..e3db78127 100644
--- a/ui/src/components/workbench/VaultsPage.tsx
+++ b/ui/src/components/workbench/VaultsPage.tsx
@@ -21,11 +21,9 @@ import { vaultRequestSessionDisplay } from '../ui/vault-request-session';
import { VaultRequestSessionLink } from '../ui/vault-request-session-link';
import { VaultSecretDialog } from '../ui/vault-secret-dialog';
import { VaultSettingsDialog } from '../ui/vault-settings-dialog';
-import { canManageVaultSecrets } from '../../lib/remoteAuth';
import { useProtectedVault } from '../../lib/useProtectedVault';
import { useVaultRequestRefresh } from '../../lib/useVaultRequestRefresh';
import {
- canUseRuntimeSurfaces,
useInstanceAuthorization,
} from '../../context/InstanceAuthorizationContext';
@@ -492,15 +490,9 @@ export const VaultsPage: React.FC = () => {
const api = useApi();
const { showToast } = useToast();
const vault = useProtectedVault();
- const { capabilities, remote, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
- const canUseRuntime = canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess);
- const canManage =
- (capabilities.can_manage_instance || canUseRuntime) &&
- canManageVaultSecrets({
- remote,
- temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
- });
- const canReadVaultState = capabilities.can_manage_instance || canUseRuntime;
+ const { capabilities } = useInstanceAuthorization();
+ const canManage = capabilities.can_use_vault_secrets;
+ const canReadVaultState = capabilities.can_use_vault_secrets;
const [searchParams, setSearchParams] = useSearchParams();
const [secrets, setSecrets] = useState<VaultSecret[]>([]);
const [grants, setGrants] = useState<VaultGrant[]>([]);
@@ -781,7 +773,7 @@ export const VaultsPage: React.FC = () => {
<Plus className="size-4" />
{t('vaults.add')}
</Button>
- ) : remote && !canUseRuntime ? (
+ ) : !capabilities.can_use_vault_secrets ? (
<Badge variant="secondary" title={t('vaults.remoteReadOnlyHint')}>
<Lock className="size-3" />
{t('vaults.remoteReadOnly')}
diff --git a/ui/src/components/workbench/WebPushControl.tsx b/ui/src/components/workbench/WebPushControl.tsx
index 728139c21..31c16ec20 100644
--- a/ui/src/components/workbench/WebPushControl.tsx
+++ b/ui/src/components/workbench/WebPushControl.tsx
@@ -5,7 +5,6 @@ import { Bell, BellOff, Loader2, Smartphone } from 'lucide-react';
import { useApi } from '@/context/ApiContext';
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import { useToast } from '@/context/ToastContext';
-import { canRegisterWebPush } from '@/lib/remoteAuth';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import {
@@ -24,16 +23,13 @@ type Status = 'checking' | 'unsupported' | 'needs_install' | 'disabled' | 'enabl
export const WebPushControl: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
- const { remote, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
+ const { capabilities } = useInstanceAuthorization();
const { showToast } = useToast();
const [status, setStatus] = useState<Status>('checking');
const [busy, setBusy] = useState(false);
const [testing, setTesting] = useState(false);
const [support, setSupport] = useState<WebPushSupportState | null>(null);
- const canRegister = canRegisterWebPush({
- remote,
- temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
- });
+ const canRegister = capabilities.can_read_instance;
const refresh = async () => {
const nextSupport = getWebPushSupportState();
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index b9c62a98c..cad8fe6af 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -28,11 +28,7 @@ import type { LucideIcon } from 'lucide-react';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
-import {
- canUseAppsSurface,
- canUseRuntimeSurfaces,
- useInstanceAuthorization,
-} from '../../context/InstanceAuthorizationContext';
+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
import { useWindowManager } from '../../context/WindowManagerContext';
import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';
import type { InboxSession, WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
@@ -41,7 +37,6 @@ import { SESSION_ROW_MENU_POSITION_CLASS, sessionRowActionPaddingClass } from '.
import { SessionActionMenuContent, SessionActionsTrigger } from './sessionActions';
import { useSessionActions } from './useSessionActions';
import { formatRelativeTime } from '../../lib/relativeTime';
-import { canArchiveProjects, canEditProjectInstructions, canUseHarness } from '../../lib/remoteAuth';
import { canCreateLocalProject } from '../../lib/sessionInfo';
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '../ui/popover';
import { Button } from '../ui/button';
@@ -666,23 +661,16 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
const authorizeRouteAction = useUnsavedChangesActionGuard();
const {
capabilities,
- remote,
- hasTemporaryUnrestrictedOrgAccess,
} = useInstanceAuthorization();
- const canUseRuntime = canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess);
- const canUseApps = canUseAppsSurface(remote, hasTemporaryUnrestrictedOrgAccess);
- const canManageProjects = capabilities.can_manage_projects || canUseRuntime;
- const canChat = capabilities.can_chat || canUseRuntime;
- const canCreateProject = canUseRuntime || canCreateLocalProject(capabilities);
+ const canUseApps = capabilities.can_chat;
+ const canManageProjects = capabilities.can_manage_projects;
+ const canChat = capabilities.can_chat;
+ const canCreateProject = canCreateLocalProject(capabilities);
const capabilityNav = CAPABILITY_NAV.filter(({ to }) => {
- if (canUseRuntime) return true;
- if (to === '/harness') return (capabilities.can_manage_agents || canUseRuntime) && canUseHarness({
- remote,
- temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
- });
- if (to === '/agents') return capabilities.can_manage_agents || canUseRuntime;
- if (to === '/skills') return capabilities.can_use_skills || canUseRuntime;
- if (to === '/vaults') return capabilities.can_use_vault_secrets || canUseRuntime;
+ if (to === '/harness') return capabilities.can_chat;
+ if (to === '/agents') return capabilities.can_use_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();
@@ -937,18 +925,12 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
}
}}
creatingSession={creatingSession(project.id)}
- canChat={canChat && (canUseRuntime || project.capabilities.can_chat)}
- canManageMetadata={canUseRuntime || project.capabilities.can_chat}
+ canChat={canChat && project.capabilities.can_chat}
+ canManageMetadata={canManageProjects || project.capabilities.can_chat}
canManageProjects={canManageProjects}
- canArchive={canManageProjects && canArchiveProjects({
- remote,
- temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
- })}
+ canArchive={canManageProjects}
canOpenInEditor={canUseApps}
- canEditAgentsMd={canManageProjects && canEditProjectInstructions({
- remote,
- temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
- })}
+ canEditAgentsMd={canManageProjects}
unreadBySession={unreadBySession}
onRename={(next) => renameProject(project.id, next)}
onArchive={() => archiveProject(project.id)}
diff --git a/ui/src/context/InstanceAuthorizationContext.test.ts b/ui/src/context/InstanceAuthorizationContext.test.ts
index add5c394d..ae3a3a860 100644
--- a/ui/src/context/InstanceAuthorizationContext.test.ts
+++ b/ui/src/context/InstanceAuthorizationContext.test.ts
@@ -1,14 +1,9 @@
import { describe, expect, it } from 'vitest';
-import { canUseAppsSurface } from './InstanceAuthorizationContext';
+import { InstanceAuthorizationContext } from './InstanceAuthorizationContext';
-describe('canUseAppsSurface', () => {
- it.each([
- ['local', false, undefined, true],
- ['remote active Organization member', true, true, true],
- ['remote principal without Organization access', true, false, false],
- ['remote principal with an incomplete signal', true, undefined, false],
- ])('%s follows the temporary Apps policy', (_label, remote, temporaryAccess, expected) => {
- expect(canUseAppsSurface(remote, temporaryAccess)).toBe(expected);
+describe('InstanceAuthorizationContext', () => {
+ it('defaults to a fail-closed capability projection', () => {
+ expect(InstanceAuthorizationContext._currentValue?.capabilities.can_chat).toBe(false);
});
});
diff --git a/ui/src/context/InstanceAuthorizationContext.ts b/ui/src/context/InstanceAuthorizationContext.ts
index 9421699be..fcd404be4 100644
--- a/ui/src/context/InstanceAuthorizationContext.ts
+++ b/ui/src/context/InstanceAuthorizationContext.ts
@@ -1,38 +1,20 @@
import { createContext, useContext } from 'react';
import type { InstanceCapabilities } from './ApiContext';
+import type { InstanceKind } from '../lib/sessionInfo';
import { DENIED_INSTANCE_CAPABILITIES } from '../lib/sessionInfo';
export interface InstanceAuthorizationValue {
remote: boolean;
+ instanceKind: InstanceKind | null;
instanceRole: 'owner' | 'editor' | 'viewer' | null;
- /** Temporary unrestricted runtime policy, derived from signed active-Organization claims. */
- hasTemporaryUnrestrictedOrgAccess?: boolean;
- /** Compatibility with the previous Apps-only field. */
- hasTemporaryUnrestrictedOrgAppAccess?: boolean;
capabilities: InstanceCapabilities;
}
-/**
- * Temporary runtime rollout gate. This is deliberately separate from the
- * capability projection: active Organization members receive the explicitly
- * opened runtime surfaces without being presented as local owners.
- */
-export const canUseTemporaryOrgRuntime = (
- remote: boolean,
- hasTemporaryUnrestrictedOrgAccess: boolean | undefined,
-): boolean => !remote || hasTemporaryUnrestrictedOrgAccess === true;
-
-/** Shared name for non-control-plane runtime surfaces. */
-export const canUseRuntimeSurfaces = canUseTemporaryOrgRuntime;
-
-export const canUseAppsSurface = canUseTemporaryOrgRuntime;
-
export const InstanceAuthorizationContext = createContext<InstanceAuthorizationValue>({
remote: false,
+ instanceKind: null,
instanceRole: null,
- hasTemporaryUnrestrictedOrgAccess: false,
- hasTemporaryUnrestrictedOrgAppAccess: false,
capabilities: DENIED_INSTANCE_CAPABILITIES,
});
diff --git a/ui/src/context/InstanceAuthorizationProvider.tsx b/ui/src/context/InstanceAuthorizationProvider.tsx
index 9affa74ce..3492a0403 100644
--- a/ui/src/context/InstanceAuthorizationProvider.tsx
+++ b/ui/src/context/InstanceAuthorizationProvider.tsx
@@ -21,30 +21,23 @@ export const InstanceAuthorizationProvider = ({
if (!session.remote) {
return {
remote: false,
+ instanceKind: session.instance_kind,
instanceRole: session.instance_role ?? 'owner',
- hasTemporaryUnrestrictedOrgAccess: false,
- hasTemporaryUnrestrictedOrgAppAccess: false,
capabilities: session.capabilities ?? OWNER_INSTANCE_CAPABILITIES,
};
}
if (!session.authenticated) {
return {
remote: true,
+ instanceKind: null,
instanceRole: null,
- hasTemporaryUnrestrictedOrgAccess: false,
- hasTemporaryUnrestrictedOrgAppAccess: false,
capabilities: DENIED_INSTANCE_CAPABILITIES,
};
}
return {
remote: true,
+ instanceKind: session.instance_kind,
instanceRole: session.instance_role,
- hasTemporaryUnrestrictedOrgAccess:
- session.temporary_unrestricted_org_access ||
- session.temporary_unrestricted_org_app_access,
- hasTemporaryUnrestrictedOrgAppAccess:
- session.temporary_unrestricted_org_access ||
- session.temporary_unrestricted_org_app_access,
capabilities: session.capabilities,
};
}, [session]);
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsx
index 7d50335cf..b0a9a022c 100644
--- a/ui/src/context/WorkbenchInboxProvider.tsx
+++ b/ui/src/context/WorkbenchInboxProvider.tsx
@@ -328,9 +328,8 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
const markRead = useCallback(
async (sessionId: string, untilMessageId?: string) => {
// Clearing unread is best-effort, so a failure must not raise an error
- // toast. Active Organization members are admitted by the temporary
- // runtime policy; other remote principals can still read a permitted
- // session without being allowed to mutate its unread state.
+ // toast. Reading a permitted session and mutating its unread state are
+ // independent capabilities.
const operation = readOwnershipRef.current.beginRead(`inbox-mark-read:${sessionId}`);
const result = await api.markSessionRead(sessionId, untilMessageId, { handleError: false });
if (
diff --git a/ui/src/features/organization/OrganizationShell.test.tsx b/ui/src/features/organization/OrganizationShell.test.tsx
index eb528bf5d..291d838cd 100644
--- a/ui/src/features/organization/OrganizationShell.test.tsx
+++ b/ui/src/features/organization/OrganizationShell.test.tsx
@@ -44,6 +44,7 @@ function renderShell(capabilities: InstanceAuthorizationValue['capabilities']) {
<InstanceAuthorizationContext.Provider
value={{
remote: true,
+ instanceKind: 'organization',
instanceRole: 'owner',
capabilities,
}}
@@ -61,7 +62,7 @@ describe('OrganizationShell cloud_not_connected action', () => {
vi.clearAllMocks();
});
- it('keeps the trusted-local remote access CTA reachable for local owners', () => {
+ it('keeps the remote access CTA reachable for owners', () => {
renderShell(OWNER_INSTANCE_CAPABILITIES);
const action = screen.getByRole('link', { name: 'organization.actions.openRemoteAccess' });
diff --git a/ui/src/features/organization/OrganizationShell.tsx b/ui/src/features/organization/OrganizationShell.tsx
index 31ffa271f..fcbd23380 100644
--- a/ui/src/features/organization/OrganizationShell.tsx
+++ b/ui/src/features/organization/OrganizationShell.tsx
@@ -34,14 +34,10 @@ const NAV = [
{ path: '/admin/organization/resources', key: 'resources', icon: Building2 },
] as const;
-// Resolve "back to control panel" against the temporary runtime admission.
-// Remote Access itself remains on the separate pairing/tunnel boundary below.
+// Resolve "back to control panel" against the current Instance capability.
function useBackToControlPanelPath(): string {
- const { capabilities, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
- return adminLandingPath(
- capabilities.can_use_system,
- hasTemporaryUnrestrictedOrgAccess === true,
- );
+ const { capabilities } = useInstanceAuthorization();
+ return adminLandingPath(capabilities.can_use_system);
}
function GateState() {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 5504d7f8d..2c82729c4 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2851,6 +2851,29 @@
"definitions": "Definitions",
"running": "Runs"
},
+ "onboarding": {
+ "title": "Organization access",
+ "summary": "{{total}} Agents · {{custom}} custom · {{system}} system",
+ "inventory": "Agent inventory ({{count}})",
+ "notOnboardedCount": "{{count}} not onboarded",
+ "privateCount": "{{count}} private",
+ "publishedCount": "{{count}} published",
+ "conflictCount": "{{count}} unavailable",
+ "onboardPrivate": "Onboard privately",
+ "onboarded": "Onboarded",
+ "manageAccess": "Manage access",
+ "system": "system",
+ "custom": "custom",
+ "saved": "{{count}} Agents onboarded privately.",
+ "savedPending": "Agents are private locally; publication is pending.",
+ "failed": "Could not onboard Agents: {{error}}",
+ "status": {
+ "not_onboarded": "Not onboarded",
+ "private": "Private",
+ "published": "Published",
+ "managed_elsewhere": "Unavailable"
+ }
+ },
"running": {
"empty": "No agents are currently running.",
"unreachableTitle": "Runtime unreachable",
@@ -3451,7 +3474,7 @@
},
"workspaceHelp": {
"private": "Only the Show Page owner can open it through this access rule.",
- "public": "All active Organization members may open it, subject to their Avibe and Project access.",
+ "public": "Anyone with the Show Page link may open it when it is public.",
"scope": "Only active members of the selected groups may open it, subject to their Avibe and Project access."
},
"selectedGroups": "Selected groups",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 46dca5a53..2e22f47bd 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2851,6 +2851,29 @@
"definitions": "定义",
"running": "运行"
},
+ "onboarding": {
+ "title": "组织访问",
+ "summary": "{{total}} 个 Agent · {{custom}} 个自定义 · {{system}} 个系统",
+ "inventory": "Agent 清单({{count}})",
+ "notOnboardedCount": "{{count}} 个未纳管",
+ "privateCount": "{{count}} 个私有",
+ "publishedCount": "{{count}} 个已发布",
+ "conflictCount": "{{count}} 个不可用",
+ "onboardPrivate": "按私有方式纳管",
+ "onboarded": "已纳管",
+ "manageAccess": "管理访问",
+ "system": "系统",
+ "custom": "自定义",
+ "saved": "已按私有方式纳管 {{count}} 个 Agent。",
+ "savedPending": "Agent 已在本地设为私有,等待发布。",
+ "failed": "无法纳管 Agent:{{error}}",
+ "status": {
+ "not_onboarded": "未纳管",
+ "private": "私有",
+ "published": "已发布",
+ "managed_elsewhere": "不可用"
+ }
+ },
"running": {
"empty": "当前没有正在运行的 Agent。",
"unreachableTitle": "运行时不可达",
diff --git a/ui/src/lib/adminNavigation.test.ts b/ui/src/lib/adminNavigation.test.ts
index 2c340639d..bae71073a 100644
--- a/ui/src/lib/adminNavigation.test.ts
+++ b/ui/src/lib/adminNavigation.test.ts
@@ -2,13 +2,12 @@ import { describe, expect, it } from 'vitest';
import {
adminLandingPath,
- filterLocalSystemNavItems,
- filterRuntimeAccessNavItems,
+ filterOwnerOnlyNavItems,
isAdvancedSettingsPath,
isLocalOnlyMessagingField,
- isLocalSystemPath,
- isLocalSystemPathForAccess,
+ isOwnerOnlyPath,
isMemorySettingsPath,
+ visibleAdminNavItems,
} from './adminNavigation';
describe('isAdvancedSettingsPath', () => {
@@ -36,50 +35,50 @@ describe('isAdvancedSettingsPath', () => {
});
});
-describe('isLocalSystemPath', () => {
- it('covers every destination with a historical trusted-local gate', () => {
- expect(isLocalSystemPath('/admin/dashboard')).toBe(true);
- expect(isLocalSystemPath('/admin/remote-access')).toBe(true);
- expect(isLocalSystemPath('/admin/groups')).toBe(true);
- expect(isLocalSystemPath('/admin/users')).toBe(true);
- expect(isLocalSystemPath('/admin/logs')).toBe(true);
- expect(isLocalSystemPath('/admin/settings/service')).toBe(true);
- expect(isLocalSystemPath('/admin/settings/platforms')).toBe(true);
- expect(isLocalSystemPath('/admin/settings/backends')).toBe(true);
- expect(isLocalSystemPath('/admin/settings/models')).toBe(true);
- expect(isLocalSystemPath('/admin/settings/dependencies')).toBe(true);
- expect(isLocalSystemPath('/admin/settings/diagnostics')).toBe(true);
- expect(isLocalSystemPath('/admin/settings/logs')).toBe(true);
- expect(isLocalSystemPath('/harness')).toBe(true);
+describe('isOwnerOnlyPath', () => {
+ it('covers every destination with an Owner management gate', () => {
+ expect(isOwnerOnlyPath('/admin/dashboard')).toBe(true);
+ expect(isOwnerOnlyPath('/admin/remote-access')).toBe(true);
+ expect(isOwnerOnlyPath('/admin/groups')).toBe(true);
+ expect(isOwnerOnlyPath('/admin/users')).toBe(true);
+ expect(isOwnerOnlyPath('/admin/logs')).toBe(true);
+ expect(isOwnerOnlyPath('/admin/settings/service')).toBe(true);
+ expect(isOwnerOnlyPath('/admin/settings/platforms')).toBe(true);
+ expect(isOwnerOnlyPath('/admin/settings/backends')).toBe(true);
+ expect(isOwnerOnlyPath('/admin/settings/models')).toBe(true);
+ expect(isOwnerOnlyPath('/admin/settings/dependencies')).toBe(true);
+ expect(isOwnerOnlyPath('/admin/settings/diagnostics')).toBe(true);
+ expect(isOwnerOnlyPath('/admin/settings/logs')).toBe(true);
+ expect(isOwnerOnlyPath('/harness')).toBe(false);
});
it('matches nested paths under a gated destination', () => {
- expect(isLocalSystemPath('/admin/settings/platforms/slack')).toBe(true);
- expect(isLocalSystemPath('/admin/groups/engineering')).toBe(true);
- expect(isLocalSystemPath('/harness/')).toBe(true);
+ expect(isOwnerOnlyPath('/admin/settings/platforms/slack')).toBe(true);
+ expect(isOwnerOnlyPath('/admin/groups/engineering')).toBe(true);
+ expect(isOwnerOnlyPath('/harness/')).toBe(false);
});
it('leaves remotely usable destinations open', () => {
- expect(isLocalSystemPath('/admin/settings/messaging')).toBe(false);
- expect(isLocalSystemPath('/admin/organization/overview')).toBe(false);
- expect(isLocalSystemPath('/apps/files')).toBe(false);
- expect(isLocalSystemPath('/apps/editor')).toBe(false);
- expect(isLocalSystemPath('/apps/terminal')).toBe(false);
- expect(isLocalSystemPath('/apps/library')).toBe(false);
- expect(isLocalSystemPath('/apps/show/session-1')).toBe(false);
- expect(isLocalSystemPath('/')).toBe(false);
+ expect(isOwnerOnlyPath('/admin/settings/messaging')).toBe(false);
+ expect(isOwnerOnlyPath('/admin/organization/overview')).toBe(false);
+ expect(isOwnerOnlyPath('/apps/files')).toBe(false);
+ expect(isOwnerOnlyPath('/apps/editor')).toBe(false);
+ expect(isOwnerOnlyPath('/apps/terminal')).toBe(false);
+ expect(isOwnerOnlyPath('/apps/library')).toBe(false);
+ expect(isOwnerOnlyPath('/apps/show/session-1')).toBe(false);
+ expect(isOwnerOnlyPath('/')).toBe(false);
});
it('does not match a route that only shares a gated prefix', () => {
- expect(isLocalSystemPath('/admin/dashboards')).toBe(false);
- expect(isLocalSystemPath('/harness-status')).toBe(false);
- expect(isLocalSystemPath('/apps/library-picker')).toBe(false);
+ expect(isOwnerOnlyPath('/admin/dashboards')).toBe(false);
+ expect(isOwnerOnlyPath('/harness-status')).toBe(false);
+ expect(isOwnerOnlyPath('/apps/library-picker')).toBe(false);
});
});
-describe('filterLocalSystemNavItems', () => {
- it('removes local-only destinations from nested admin navigation trees', () => {
- const visible = filterLocalSystemNavItems([
+describe('filterOwnerOnlyNavItems', () => {
+ it('removes Owner-only destinations from nested admin navigation trees', () => {
+ const visible = filterOwnerOnlyNavItems([
{
children: [
{ to: '/admin/settings/platforms' },
@@ -101,65 +100,42 @@ describe('filterLocalSystemNavItems', () => {
});
});
-describe('filterRuntimeAccessNavItems', () => {
- const navItems = [
+describe('visibleAdminNavItems', () => {
+ const adminItems = [
{ to: '/admin/dashboard' },
- {
- children: [
- { to: '/admin/remote-access' },
- { to: '/admin/settings/models' },
- ],
- },
+ { to: '/admin/remote-access' },
{ to: '/admin/settings/messaging' },
];
- it('withholds only Remote Access during the temporary Organization rollout', () => {
- expect(filterRuntimeAccessNavItems(navItems, true)).toEqual([
- { to: '/admin/dashboard' },
- { children: [{ to: '/admin/settings/models' }] },
- { to: '/admin/settings/messaging' },
- ]);
+ it('keeps Owner destinations when the caller can manage the instance', () => {
+ expect(visibleAdminNavItems(adminItems, true)).toEqual(adminItems);
});
- it('keeps the baseline local-system filter outside the temporary rollout', () => {
- expect(filterRuntimeAccessNavItems(navItems, false)).toEqual([
+ it('hides Owner destinations only when the caller cannot manage the instance', () => {
+ expect(visibleAdminNavItems(adminItems, false)).toEqual([
{ to: '/admin/settings/messaging' },
]);
});
});
describe('adminLandingPath', () => {
- it('opens the Dashboard for a trusted-local caller', () => {
+ it('opens the Dashboard for an owner', () => {
expect(adminLandingPath(true)).toBe('/admin/dashboard');
});
it('sends a remote owner to an admin page they can actually use', () => {
const destination = adminLandingPath(false);
expect(destination).toBe('/admin/settings/messaging');
- expect(isLocalSystemPath(destination)).toBe(false);
- });
-
- it('opens the Dashboard for the temporary Organization runtime policy', () => {
- expect(adminLandingPath(false, true)).toBe('/admin/dashboard');
- });
-});
-
-describe('isLocalSystemPathForAccess', () => {
- it('opens known runtime administration while preserving Remote Access control', () => {
- expect(isLocalSystemPathForAccess('/admin/dashboard', true)).toBe(false);
- expect(isLocalSystemPathForAccess('/admin/users', true)).toBe(false);
- expect(isLocalSystemPathForAccess('/admin/settings/models', true)).toBe(false);
- expect(isLocalSystemPathForAccess('/admin/remote-access', true)).toBe(true);
+ expect(isOwnerOnlyPath(destination)).toBe(false);
});
- it('keeps the baseline gate without the signed temporary signal', () => {
- expect(isLocalSystemPathForAccess('/admin/users', false)).toBe(true);
- expect(isLocalSystemPathForAccess('/admin/settings/models', false)).toBe(true);
+ it('keeps non-owners on messaging settings', () => {
+ expect(adminLandingPath(false)).toBe('/admin/settings/messaging');
});
});
describe('isLocalOnlyMessagingField', () => {
- it('marks the messaging controls governed by the runtime admission signal', () => {
+ it('marks messaging controls governed by the Owner capability', () => {
expect(isLocalOnlyMessagingField('agents.opencode.error_retry_limit')).toBe(true);
expect(isLocalOnlyMessagingField('agents.opencode.active_turn_timeout_seconds')).toBe(true);
expect(isLocalOnlyMessagingField('show_pages_prompt')).toBe(true);
diff --git a/ui/src/lib/adminNavigation.ts b/ui/src/lib/adminNavigation.ts
index 8ce534163..0a05b8ddc 100644
--- a/ui/src/lib/adminNavigation.ts
+++ b/ui/src/lib/adminNavigation.ts
@@ -5,19 +5,12 @@ export const isMemorySettingsPath = (pathname: string): boolean =>
matchesRoute(pathname, '/admin/settings/memory');
/**
- * Destinations that historically depended on trusted-local APIs. Active
- * Organization members are temporarily admitted to the runtime surfaces by
- * the signed `temporary_unrestricted_org_access` signal; Remote Access
- * pairing/tunnel management remains a separate control-plane boundary.
- *
- * This is the single source of truth for both halves of the gate — the route
- * redirect and the navigation entries that point at it — so a withheld page can
- * never still be advertised in the sidebar, mobile tabs or the More sheet.
+ * Destinations that require Instance Owner management capability.
* Messaging settings are deliberately absent: the page has its own field-level
* control-plane handling, and the remaining protected controls are gated by
* `isLocalOnlyMessagingField` below.
*/
-export const LOCAL_SYSTEM_ROUTES = [
+export const OWNER_ONLY_ROUTES = [
'/admin/dashboard',
'/admin/remote-access',
'/admin/groups',
@@ -30,7 +23,6 @@ export const LOCAL_SYSTEM_ROUTES = [
'/admin/settings/dependencies',
'/admin/settings/diagnostics',
'/admin/settings/logs',
- '/harness',
] as const;
const LOCAL_ONLY_MESSAGING_FIELDS = new Set([
@@ -39,8 +31,8 @@ const LOCAL_ONLY_MESSAGING_FIELDS = new Set([
'show_pages_prompt',
]);
-export const isLocalSystemPath = (pathname: string): boolean =>
- LOCAL_SYSTEM_ROUTES.some((route) => matchesRoute(pathname, route));
+export const isOwnerOnlyPath = (pathname: string): boolean =>
+ OWNER_ONLY_ROUTES.some((route) => matchesRoute(pathname, route));
export type LocalSystemNavItem = {
to?: string;
@@ -48,59 +40,27 @@ export type LocalSystemNavItem = {
children?: LocalSystemNavItem[];
};
-export const filterLocalSystemNavItems = <T extends LocalSystemNavItem>(navItems: T[]): T[] =>
+export const filterOwnerOnlyNavItems = <T extends LocalSystemNavItem>(navItems: T[]): T[] =>
navItems
- .filter((item) => !item.to || !isLocalSystemPath(item.to))
+ .filter((item) => !item.to || !isOwnerOnlyPath(item.to))
.map((item) =>
- item.children ? ({ ...item, children: filterLocalSystemNavItems(item.children) } as T) : item,
+ item.children ? ({ ...item, children: filterOwnerOnlyNavItems(item.children) } as T) : item,
)
.filter((item) => item.to || item.onClick || (item.children?.length ?? 0) > 0);
-/**
- * Temporary rollout exception for authenticated active Organization members.
- * Remote-access pairing/tunnel management remains a control-plane boundary.
- */
-export const isLocalSystemPathForAccess = (
- pathname: string,
- temporaryUnrestrictedOrgAccess: boolean,
-): boolean => {
- if (!temporaryUnrestrictedOrgAccess) return isLocalSystemPath(pathname);
- // Remote Access pairing and tunnel management retain their control-plane gate.
- return matchesRoute(pathname, '/admin/remote-access');
-};
-
-export const filterRuntimeAccessNavItems = <T extends LocalSystemNavItem>(
+export const visibleAdminNavItems = <T extends LocalSystemNavItem>(
navItems: T[],
- temporaryUnrestrictedOrgAccess: boolean,
-): T[] => {
- if (temporaryUnrestrictedOrgAccess) {
- return navItems
- .filter((item) => !item.to || !matchesRoute(item.to, '/admin/remote-access'))
- .map((item) =>
- item.children
- ? { ...item, children: filterRuntimeAccessNavItems(item.children, true) }
- : item,
- )
- .filter((item) => item.to || item.onClick || (item.children?.length ?? 0) > 0);
- }
- return filterLocalSystemNavItems(navItems);
-};
+ canManageInstance: boolean,
+): T[] => (canManageInstance ? navItems : filterOwnerOnlyNavItems(navItems));
export const isLocalOnlyMessagingField = (field: string): boolean =>
LOCAL_ONLY_MESSAGING_FIELDS.has(field);
/**
- * Where the "Control Panel" entry points. A remote principal outside the
- * temporary Organization rollout cannot open the Dashboard, so send it to the
- * first admin page it can actually use instead of bouncing through a redirect.
+ * Where the "Control Panel" entry points for the current instance role.
*/
-export const adminLandingPath = (
- canUseSystem: boolean,
- temporaryUnrestrictedOrgAccess = false,
-): string =>
- canUseSystem || temporaryUnrestrictedOrgAccess
- ? '/admin/dashboard'
- : '/admin/settings/messaging';
+export const adminLandingPath = (canUseSystem: boolean): string =>
+ canUseSystem ? '/admin/dashboard' : '/admin/settings/messaging';
export const isAdvancedSettingsPath = (
pathname: string,
diff --git a/ui/src/lib/remoteAuth.test.ts b/ui/src/lib/remoteAuth.test.ts
index 1aca4532e..479780131 100644
--- a/ui/src/lib/remoteAuth.test.ts
+++ b/ui/src/lib/remoteAuth.test.ts
@@ -8,15 +8,6 @@ const platform = vi.hoisted(() => ({
vi.mock('./platform', () => platform);
import {
- canAdministerMemory,
- canArchiveProjects,
- canEditAgentDefinitions,
- canEditProjectDefaultAgent,
- canEditProjectInstructions,
- canManageSkills,
- canManageVaultSecrets,
- canRegisterWebPush,
- canUseHarness,
checkRemoteAuthForPath,
deferRemoteAuthRedirect,
remoteLoginPath,
@@ -25,46 +16,6 @@ import {
shouldDeferRemoteAuthRedirect,
} from './remoteAuth';
-describe('agent definition editing', () => {
- it('keeps the Agent editor available on a local instance', () => {
- expect(canEditAgentDefinitions({ remote: false })).toBe(true);
- });
-
- it('allows an active Organization member to edit on a remote instance', () => {
- expect(canEditAgentDefinitions({ remote: true, temporaryUnrestrictedOrgAccess: true })).toBe(true);
- });
-
- it('keeps unauthenticated or non-member remote sessions denied', () => {
- expect(canEditAgentDefinitions({ remote: true })).toBe(false);
- });
-});
-
-// Runtime controls use the signed temporary Organization admission signal.
-describe('runtime-policy workbench controls', () => {
- const predicates = {
- canManageSkills,
- canManageVaultSecrets,
- canRegisterWebPush,
- canUseHarness,
- canArchiveProjects,
- canEditProjectInstructions,
- canEditProjectDefaultAgent,
- canAdministerMemory,
- };
-
- it.each(Object.entries(predicates))('keeps %s available on a local instance', (_name, predicate) => {
- expect(predicate({ remote: false })).toBe(true);
- });
-
- it.each(Object.entries(predicates))('allows %s for an active Organization member', (_name, predicate) => {
- expect(predicate({ remote: true, temporaryUnrestrictedOrgAccess: true })).toBe(true);
- });
-
- it.each(Object.entries(predicates))('withholds %s for a remote non-member', (_name, predicate) => {
- expect(predicate({ remote: true })).toBe(false);
- });
-});
-
describe('remote auth navigation', () => {
beforeEach(() => {
platform.isIosDevice.mockReturnValue(false);
@@ -140,7 +91,7 @@ describe('remote auth navigation', () => {
});
describe('setup bypass for remote runtime access', () => {
- it('bypasses setup for an authenticated owner or active Organization member', () => {
+ it('bypasses setup only for an authenticated Instance Owner', () => {
expect(
shouldBypassSetupForRemoteOwner({
remote: true,
@@ -148,14 +99,6 @@ describe('setup bypass for remote runtime access', () => {
capabilities: { can_manage_instance: true },
}),
).toBe(true);
- expect(
- shouldBypassSetupForRemoteOwner({
- remote: true,
- authenticated: true,
- capabilities: { can_manage_instance: false },
- temporaryUnrestrictedOrgAccess: true,
- }),
- ).toBe(true);
expect(
shouldBypassSetupForRemoteOwner({
remote: true,
diff --git a/ui/src/lib/remoteAuth.ts b/ui/src/lib/remoteAuth.ts
index e95b07e1c..52b7ff69c 100644
--- a/ui/src/lib/remoteAuth.ts
+++ b/ui/src/lib/remoteAuth.ts
@@ -28,102 +28,21 @@ export function isSetupCheckBypassed(path: string): boolean {
return SETUP_CHECK_BYPASS_PATHS.has(path);
}
-/** Temporary runtime policy signal carried by signed active-Organization claims. */
export type RemoteContext = {
remote: boolean;
- temporaryUnrestrictedOrgAccess?: boolean;
- /** Compatibility with the previous Apps-only rollout field. */
- temporaryUnrestrictedOrgAppAccess?: boolean;
};
type RemoteSetupSession = RemoteContext & {
authenticated?: boolean;
capabilities?: { can_manage_instance?: boolean };
};
-function hasTemporaryUnrestrictedOrgAccess(context: RemoteContext): boolean {
- return (
- context.temporaryUnrestrictedOrgAccess === true ||
- context.temporaryUnrestrictedOrgAppAccess === true
- );
-}
-
-function canUseTemporaryOrgRuntime(context: RemoteContext): boolean {
- return !context.remote || hasTemporaryUnrestrictedOrgAccess(context);
-}
-
-/**
- * Temporary policy: active Organization members may edit Agent definitions.
- */
-export function canEditAgentDefinitions(context: RemoteContext): boolean {
- return canUseTemporaryOrgRuntime(context);
-}
-
-/**
- * Temporary policy: active Organization members may manage Skills.
- */
-export function canManageSkills(context: RemoteContext): boolean {
- return canUseTemporaryOrgRuntime(context);
-}
-
-/**
- * Temporary policy: active Organization members may manage Vault resources.
- */
-export function canManageVaultSecrets(context: RemoteContext): boolean {
- return canUseTemporaryOrgRuntime(context);
-}
-
-/**
- * Temporary policy: active Organization members may use Harness definitions and runs.
- */
-export function canUseHarness(context: RemoteContext): boolean {
- return canUseTemporaryOrgRuntime(context);
-}
-
-/**
- * Temporary policy: active Organization members may archive Projects.
- */
-export function canArchiveProjects(context: RemoteContext): boolean {
- return canUseTemporaryOrgRuntime(context);
-}
-
-/**
- * Temporary policy: active Organization members may edit project instructions.
- */
-export function canEditProjectInstructions(context: RemoteContext): boolean {
- return canUseTemporaryOrgRuntime(context);
-}
-
-/**
- * Temporary policy: active Organization members may edit project Agent defaults.
- */
-export function canEditProjectDefaultAgent(context: RemoteContext): boolean {
- return canUseTemporaryOrgRuntime(context);
-}
-
-/**
- * Temporary policy: active Organization members may administer Memory.
- */
-export function canAdministerMemory(context: RemoteContext): boolean {
- return canUseTemporaryOrgRuntime(context);
-}
-
/** Remote runtime principals skip the local setup wizard and use shell recovery. */
export function shouldBypassSetupForRemoteOwner(session: RemoteSetupSession | null | undefined): boolean {
return !!session?.remote && session.authenticated === true && (
- session.capabilities?.can_manage_instance === true ||
- session.temporaryUnrestrictedOrgAccess === true ||
- session.temporaryUnrestrictedOrgAppAccess === true
+ session.capabilities?.can_manage_instance === true
);
}
-/**
- * Temporary policy: active Organization members may register and test Web Push.
- */
-export function canRegisterWebPush(context: RemoteContext): boolean {
- return canUseTemporaryOrgRuntime(context);
-}
-
-
export async function checkRemoteAuthForPath<Session extends RemoteSession>(
path: string,
getSession: () => Promise<Session>,
diff --git a/ui/src/lib/sessionInfo.test.ts b/ui/src/lib/sessionInfo.test.ts
index 7136883f1..f3b9544a1 100644
--- a/ui/src/lib/sessionInfo.test.ts
+++ b/ui/src/lib/sessionInfo.test.ts
@@ -33,9 +33,8 @@ describe('normalizeSessionInfo', () => {
authenticated: true,
sub: 'owner-1',
+ instance_kind: null,
instance_role: 'owner',
- temporary_unrestricted_org_access: false,
- temporary_unrestricted_org_app_access: false,
capabilities: OWNER_INSTANCE_CAPABILITIES,
});
});
@@ -45,9 +44,8 @@ describe('normalizeSessionInfo', () => {
remote: true,
authenticated: true,
+ instance_kind: null,
instance_role: 'viewer',
- temporary_unrestricted_org_access: false,
- temporary_unrestricted_org_app_access: false,
capabilities: {
can_read_instance: true,
can_use_show_pages: true,
@@ -58,9 +56,8 @@ describe('normalizeSessionInfo', () => {
remote: true,
authenticated: true,
+ instance_kind: null,
instance_role: 'viewer',
- temporary_unrestricted_org_access: false,
- temporary_unrestricted_org_app_access: false,
capabilities: {
...DENIED_INSTANCE_CAPABILITIES,
can_read_instance: true,
@@ -69,24 +66,10 @@ describe('normalizeSessionInfo', () => {
});
});
- it('preserves the temporary Organization policy signal without projecting a capability', () => {
- const session = normalizeSessionInfo({
- remote: true,
- authenticated: true,
- email: '[email protected]',
- instance_role: 'viewer',
- temporary_unrestricted_org_app_access: true,
- capabilities: { can_read_instance: true },
- });
-
- expect(session.temporary_unrestricted_org_app_access).toBe(true);
- expect(session.temporary_unrestricted_org_access).toBe(true);
- expect(session.capabilities.can_use_system).toBe(false);
- });
-
it('keeps local sessions owner-compatible when an older server omits capabilities', () => {
expect(normalizeSessionInfo({ remote: false })).toEqual({
remote: false,
+ instance_kind: null,
instance_role: 'owner',
capabilities: OWNER_INSTANCE_CAPABILITIES,
});
@@ -95,4 +78,16 @@ describe('normalizeSessionInfo', () => {
it('fails closed for malformed session payloads', () => {
expect(normalizeSessionInfo(null)).toEqual({ remote: true, authenticated: false });
});
+
+ it.each([
+ ['personal', 'personal'],
+ ['organization', 'organization'],
+ ['enterprise', null],
+ ['', null],
+ [null, null],
+ ])('normalizes instance kind %j to %j', (rawKind, expectedKind) => {
+ expect(normalizeSessionInfo({ remote: false, instance_kind: rawKind })).toMatchObject({
+ instance_kind: expectedKind,
+ });
+ });
});
diff --git a/ui/src/lib/sessionInfo.ts b/ui/src/lib/sessionInfo.ts
index 5e4463147..0c21360d7 100644
--- a/ui/src/lib/sessionInfo.ts
+++ b/ui/src/lib/sessionInfo.ts
@@ -15,18 +15,23 @@ export type InstanceCapabilities = {
can_use_system: boolean;
};
+export type InstanceKind = 'personal' | 'organization';
+
export type SessionInfo =
- | { remote: false; instance_role?: 'owner'; capabilities?: InstanceCapabilities }
+ | {
+ remote: false;
+ instance_kind: InstanceKind | null;
+ instance_role?: 'owner';
+ capabilities?: InstanceCapabilities;
+ }
| { remote: true; authenticated: false; authorization_refresh_required?: boolean }
| {
remote: true;
authenticated: true;
email: string;
sub?: string;
+ instance_kind: InstanceKind | null;
instance_role: 'owner' | 'editor' | 'viewer';
- temporary_unrestricted_org_access: boolean;
- /** Compatibility with the previous Apps-only rollout field. */
- temporary_unrestricted_org_app_access: boolean;
capabilities: InstanceCapabilities;
};
@@ -62,12 +67,16 @@ const normalizeCapabilities = (value: Record<string, unknown>): InstanceCapabili
Object.keys(DENIED_INSTANCE_CAPABILITIES).map((key) => [key, value[key] === true]),
) as InstanceCapabilities;
+const normalizeInstanceKind = (value: unknown): InstanceKind | null =>
+ value === 'personal' || value === 'organization' ? value : null;
+
export const normalizeSessionInfo = (value: unknown): SessionInfo => {
if (!isRecord(value)) return { remote: true, authenticated: false };
if (value.remote === false) {
return {
remote: false,
+ instance_kind: normalizeInstanceKind(value.instance_kind),
instance_role: 'owner',
capabilities: OWNER_INSTANCE_CAPABILITIES,
};
@@ -103,13 +112,8 @@ export const normalizeSessionInfo = (value: unknown): SessionInfo => {
authenticated: true,
email: typeof value.email === 'string' ? value.email : '',
...(typeof value.sub === 'string' ? { sub: value.sub } : {}),
+ instance_kind: normalizeInstanceKind(value.instance_kind),
instance_role: instanceRole,
- temporary_unrestricted_org_access:
- value.temporary_unrestricted_org_access === true ||
- value.temporary_unrestricted_org_app_access === true,
- temporary_unrestricted_org_app_access:
- value.temporary_unrestricted_org_app_access === true ||
- value.temporary_unrestricted_org_access === true,
capabilities,
};
};
diff --git a/vibe/api.py b/vibe/api.py
index b387a2f83..866f672e5 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1285,7 +1285,7 @@ def client_config_payload(config: V2Config) -> dict:
return payload
-_REMOTE_CONFIG_UI_FIELDS = (
+_NON_OWNER_CONFIG_UI_FIELDS = (
"instance_name",
"default_instance_name",
"chat_message_font_size",
@@ -1294,12 +1294,13 @@ _REMOTE_CONFIG_UI_FIELDS = (
)
-def remote_config_payload(config: V2Config) -> dict:
- """Return the fallback projection for remote identities without rollout access.
+def non_owner_config_payload(config: V2Config) -> dict:
+ """Return the configuration projection available below the Owner role.
- Active Organization members use the full runtime projection with the
- pairing/tunnel block removed. Keep this allowlist for every other remote
- identity so a future caller cannot inherit host paths or runtime settings.
+ This projection is role-based rather than origin-based. It keeps sensitive
+ runtime and control-plane fields out of Viewer and Editor responses while
+ leaving ordinary messaging and UI preferences available to both local and
+ remote callers.
"""
payload = client_config_payload(config)
@@ -1317,7 +1318,7 @@ def remote_config_payload(config: V2Config) -> dict:
"agent_progress_style": payload.get("agent_progress_style"),
"ui": {
key: ui_payload[key]
- for key in _REMOTE_CONFIG_UI_FIELDS
+ for key in _NON_OWNER_CONFIG_UI_FIELDS
if isinstance(ui_payload, dict) and key in ui_payload
},
}
@@ -1528,7 +1529,7 @@ def get_show_page_access(session_id: str, *, user_context: Any = None) -> dict:
organization_id = policy.get("organization_id") if policy else None
instance_id = context.instance_id
- if context.is_trusted_local and organization_id and not instance_id:
+ if context.is_instance_owner and organization_id and not instance_id:
instance_id = V2Config.load().remote_access.vibe_cloud.instance_id or None
return {
"ok": True,
@@ -1969,8 +1970,6 @@ def onboard_vibe_agents(*, user_context: Any = None) -> dict:
def get_vibe_agent(name: str, *, user_context: Any = None) -> dict:
user_context = resolve_resource_access_context(user_context)
- from vibe.authorization import has_temporary_unrestricted_runtime_access
-
store = VibeAgentStore()
try:
agent = store.require_accessible(name, user_context=user_context)
@@ -1984,10 +1983,7 @@ def get_vibe_agent(name: str, *, user_context: Any = None) -> dict:
"ok": True,
"agent": _vibe_agent_payload(
agent,
- remote_safe=(
- user_context.is_remote
- and not has_temporary_unrestricted_runtime_access(user_context)
- ),
+ remote_safe=False,
),
"default_agent_name": default_agent.name if default_agent else None,
}
@@ -12377,7 +12373,7 @@ async def upload_skill_zip(
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")
+ require_instance_role(context, "editor")
max_b64 = 24 * 1024 * 1024 # ~18 MB archive — skills are tiny; cap the body.
max_uncompressed = 64 * 1024 * 1024
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 277d39744..554a7b757 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -42,12 +42,13 @@ _VIEWER_WORKBENCH_EVENTS = frozenset(
"message.new",
"session.activity",
"session.status",
+ "show.event",
"turn.end",
"turn.start",
"workbench.events.bridge.status",
}
)
-_EDITOR_WORKBENCH_EVENTS = frozenset({"queue.updated", "show.event"})
+_EDITOR_WORKBENCH_EVENTS = frozenset({"queue.updated"})
_PRIVILEGED_RUNTIME_WORKBENCH_EVENTS = frozenset(
{
DEFINITIONS_UPDATED_EVENT,
@@ -56,13 +57,9 @@ _PRIVILEGED_RUNTIME_WORKBENCH_EVENTS = frozenset(
}
)
-REMOTE_HTTP_ALLOWED = "allowed"
-
-
@dataclass(frozen=True)
class HttpAuthorizationPolicy:
minimum_role: str | None
- remote_access: str = REMOTE_HTTP_ALLOWED
@dataclass(frozen=True)
@@ -81,12 +78,9 @@ class AuthorizationContext:
authorization_revision: int | None = None
show_page_id: str | None = None
is_remote: bool = False
- is_trusted_local: bool = False
@property
def is_instance_owner(self) -> bool:
- if self.is_trusted_local:
- return True
return self.instance_role == "owner"
@property
@@ -99,32 +93,7 @@ class AuthorizationContext:
and self.organization_role in ORGANIZATION_ROLES
)
- def _has_admitted_remote_identity(self) -> bool:
- """Return whether identity-sensitive projections may trust this subject.
-
- Runtime HTTP admission and ordinary role rank are evaluated separately.
- This predicate is reserved for projections such as ``is_instance_owner``
- that must not infer identity from a caller-constructed role alone. Show
- Page email grants retain their signed viewer/page scope.
- """
-
- if not self.is_remote:
- return True
- if self.instance_access_source == "show_page_email":
- return self.instance_role == "viewer" and bool(self.show_page_id)
- if self.instance_access_source == "email":
- # Email-grant sessions are scoped by the Show Page email access
- # boundary; their instance role rank governs non-page surfaces.
- return True
- return self.is_active_organization_member
-
def has_role(self, minimum_role: str) -> bool:
- if self.is_trusted_local:
- return True
- # The temporary Organization rollout intentionally has no per-surface
- # role split: an admitted active member may use any runtime surface.
- if has_temporary_unrestricted_org_access(self):
- return True
return _ROLE_RANK.get(self.instance_role or "", 0) >= _ROLE_RANK[minimum_role]
@property
@@ -137,9 +106,7 @@ class AuthorizationContext:
@property
def can_use_cloud_asr(self) -> bool:
- """Allow the explicit remote Cloud ASR capability, not local execution."""
-
- return self.is_remote and self.has_role("editor")
+ return self.has_role("editor")
@property
def can_manage_projects(self) -> bool:
@@ -171,31 +138,19 @@ class AuthorizationContext:
@property
def can_use_terminal_files(self) -> bool:
- """Legacy trusted-local control capability, not an Apps visibility gate."""
-
- return not self.is_remote and self.has_role("owner")
+ return self.has_role("editor")
@property
def can_use_terminal(self) -> bool:
- """Legacy trusted-local control capability, not Terminal App access."""
-
- return not self.is_remote and self.has_role("owner")
+ return self.has_role("editor")
@property
def can_use_files(self) -> bool:
- """Legacy local-project filesystem capability, not Files App access."""
-
- return not self.is_remote and self.has_role("owner")
+ return self.has_role("editor")
@property
def can_use_system(self) -> bool:
- """Return access to trusted-local control-plane surfaces.
-
- Apps are not system administration and must not use this capability as
- an availability gate.
- """
-
- return not self.is_remote and self.has_role("owner")
+ return self.has_role("owner")
def capability_projection(self) -> dict[str, bool]:
return {
@@ -216,54 +171,6 @@ class AuthorizationContext:
}
-def has_temporary_unrestricted_org_access(
- context: AuthorizationContext | Mapping[str, Any] | None,
-) -> bool:
- """Return whether the temporary unrestricted Organization policy applies.
-
- This is an HTTP/product rollout rule, not a projected capability. Until the
- per-surface authorization model tracked in avibe#1313 ships, every
- authenticated active Organization member may use the explicitly opened
- runtime surfaces. Exact Show Page email grants remain confined to their
- signed page subtree.
- """
-
- resolved = (
- context
- if isinstance(context, AuthorizationContext)
- else context_from_session_payload(context)
- if context is not None
- else None
- )
- return bool(
- resolved is not None
- and resolved.is_remote
- and resolved.instance_access_source != "show_page_email"
- and resolved.is_active_organization_member
- )
-
-
-def has_temporary_unrestricted_org_app_access(
- context: AuthorizationContext | Mapping[str, Any] | None,
-) -> bool:
- """Backward-compatible alias for the renamed unrestricted policy signal."""
-
- return has_temporary_unrestricted_org_access(context)
-
-
-def has_temporary_unrestricted_runtime_access(
- context: AuthorizationContext | Mapping[str, Any] | None,
-) -> bool:
- """Return the temporary runtime admission signal without changing identity.
-
- Callers must use this predicate for the explicitly opened runtime surfaces
- instead of treating an Organization member as a trusted-local principal or
- projecting synthetic owner capabilities to the browser.
- """
-
- return has_temporary_unrestricted_org_access(context)
-
-
def _optional_string(value: Any, *, limit: int = 320) -> str | None:
if not isinstance(value, str):
return None
@@ -351,8 +258,10 @@ def context_from_session_payload(payload: Mapping[str, Any]) -> AuthorizationCon
)
-def trusted_local_context() -> AuthorizationContext:
- return AuthorizationContext(instance_role="owner", is_trusted_local=True)
+def instance_owner_context() -> AuthorizationContext:
+ """Return the ordinary Owner identity used by standalone local entry points."""
+
+ return AuthorizationContext(instance_role="owner")
class InstanceAuthorizationError(PermissionError):
@@ -366,10 +275,10 @@ def require_instance_role(
context: AuthorizationContext | Mapping[str, Any] | None,
minimum_role: str,
) -> AuthorizationContext:
- """Authorize a service call; omitted context denotes a trusted local caller."""
+ """Authorize a service call; omitted context denotes local Owner administration."""
resolved = (
- trusted_local_context()
+ instance_owner_context()
if context is None
else context
if isinstance(context, AuthorizationContext)
@@ -400,13 +309,6 @@ def can_receive_workbench_event(
) -> bool:
"""Return whether an SSE subscriber may receive a workbench event."""
- known_event = event_type in (
- _VIEWER_WORKBENCH_EVENTS
- | _EDITOR_WORKBENCH_EVENTS
- | _PRIVILEGED_RUNTIME_WORKBENCH_EVENTS
- )
- if has_temporary_unrestricted_org_access(context) and known_event:
- return True
# A signed Show Page email grant is still a viewer session, but its exact
# page subtree is enforced by the payload/resource visibility filters below.
if (
@@ -416,18 +318,10 @@ def can_receive_workbench_event(
and context.can_use_show_page(context.show_page_id or "")
):
return True
- # Unknown event names remain owner-only. The temporary rollout is an
- # explicit allowlist for known runtime events, not a blanket event-bus
- # capability that would expose a future control-plane event. Existing
- # remote owners still retain their established owner-level behavior.
- if not known_event and has_temporary_unrestricted_org_access(context):
- return False
try:
require_instance_role(context, required_workbench_event_role(event_type))
except InstanceAuthorizationError:
return False
- if getattr(context, "is_remote", False) and event_type in _PRIVILEGED_RUNTIME_WORKBENCH_EVENTS:
- return False
return True
@@ -458,39 +352,60 @@ _VIEWER_HTTP_RULES = tuple(
)
)
-_VIEWER_HTTP_MUTATION_RULES = tuple(
- (method, re.compile(pattern))
- for method, pattern in (
- ("POST", r"^/api/show-pages/[^/]+/ensure$"),
- ("POST", r"^/api/show-pages/[^/]+/visibility$"),
- ("POST", r"^/api/show-pages/[^/]+/rotate-share$"),
- ("POST", r"^/api/show-pages/[^/]+/share-id$"),
- ("PUT", r"^/api/show-pages/[^/]+/authorized-emails$"),
- )
+# Advertised Editor/Viewer surfaces are admitted by namespace so a newly
+# added Skills, Vault, Harness, Files, Dock, Terminal, or Web Push route
+# inherits the same Instance role as the rest of that capability. Routes
+# that stay Owner-only — Agent create/import/update/delete, system config —
+# remain outside these prefixes and fail closed to owner.
+_EDITOR_HTTP_NAMESPACES = (
+ "/api/skills",
+ "/api/vault",
+ "/api/files",
+ "/api/dock",
+ "/api/harness",
+ "/api/terminal",
+)
+_VIEWER_HTTP_NAMESPACES = (
+ "/api/memory",
+ "/api/web-push",
+)
+_VIEWER_HTTP_MUTATION_RULES = (
+ ("POST", re.compile(r"^/api/sessions/[^/]+/mark-read$")),
+ ("DELETE", re.compile(r"^/api/terminal/[^/]+$")),
)
_EDITOR_HTTP_RULES = tuple(
(method, re.compile(pattern))
for method, pattern in (
("GET", r"^/api/agents$"),
+ ("GET", r"^/api/agents/[^/]+$"),
+ ("GET", r"^/api/agents-graph$"),
("GET", r"^/api/agent-backends$"),
- ("GET", r"^/api/skills$"),
- ("GET", r"^/api/vault/(?:secrets|tags)$"),
+ ("GET", r"^/api/running-agents$"),
+ ("POST", r"^/api/running-agents/end$"),
+ # Files favorites live under /api/browse, not /api/files. Admit only this
+ # shared dependency — POST /api/browse and /mkdir stay Owner project-picker
+ # routes.
+ ("GET", r"^/api/browse/favorites$"),
("GET", r"^/api/cloud/token$"),
("GET", r"^/api/asr/status$"),
("GET", r"^/api/sessions/[^/]+/(?:archive-preview|queue|draft)$"),
("POST", r"^/api/sessions$"),
+ ("POST", r"^/api/sessions/[^/]+/cli-activity$"),
("POST", r"^/api/sessions/[^/]+/fork$"),
("PATCH", r"^/api/sessions/[^/]+$"),
("DELETE", r"^/api/sessions/[^/]+$"),
- ("POST", r"^/api/sessions/[^/]+/(?:messages|attachments|cancel|mark-read)$"),
+ ("POST", r"^/api/sessions/[^/]+/(?:messages|attachments|cancel)$"),
("DELETE", r"^/api/sessions/[^/]+/queue/[^/]+$"),
("POST", r"^/api/sessions/[^/]+/queue/[^/]+/send-now$"),
("PUT", r"^/api/sessions/[^/]+/draft$"),
("POST", r"^/api/asr/transcribe$"),
+ ("POST", r"^/api/asr/telemetry$"),
("POST", r"^/api/show/sessions/[^/]+/events$"),
("POST", r"^/api/show/sessions/[^/]+/prewarm$"),
- ("POST", r"^/api/vault/requests/(?:access|sign)$"),
+ ("POST", r"^/api/show-pages/[^/]+/icon$"),
+ ("POST", r"^/api/show-pages/[^/]+/(?:ensure|visibility|rotate-share|share-id)$"),
+ ("PUT", r"^/api/show-pages/[^/]+/authorized-emails$"),
)
)
@@ -502,18 +417,15 @@ def _http_rule_matches(
return any(rule_method == method and pattern.fullmatch(path) for rule_method, pattern in rules)
+def _path_in_namespaces(path: str, namespaces: tuple[str, ...]) -> bool:
+ return any(path == namespace or path.startswith(f"{namespace}/") for namespace in namespaces)
+
+
def http_authorization_policy(
method: str,
path: str,
- *,
- temporary_org_access: bool = False,
) -> HttpAuthorizationPolicy:
- """Return role and remote-exposure policy for one HTTP request.
-
- Remote requests use the same role and resource authorization as local requests.
- The former trust-local/local-only transport boundary was transitional and is
- intentionally removed; unknown API routes still default to owner role.
- """
+ """Return the minimum Instance role for one HTTP request."""
normalized_method = method.upper()
# Organization management is an explicit Cloud proxy namespace. Cloud user
@@ -521,37 +433,31 @@ def http_authorization_policy(
if path.startswith("/api/cloud-management/"):
return HttpAuthorizationPolicy("viewer")
if path.startswith("/show/"):
- is_read = normalized_method in {"GET", "HEAD", "OPTIONS"}
- # The server-owned event endpoint does not proxy into Show Runtime. Its
- # handler rejects any remote request that would dispatch an Agent turn
- # before the event store can reserve a delivery.
- is_safe_human_event = normalized_method == "POST" and re.fullmatch(
- r"^/show/[^/]+/(?:__show/events|__events)$",
- path,
- )
- minimum_role = "viewer"
- return HttpAuthorizationPolicy(minimum_role)
+ return HttpAuthorizationPolicy("viewer")
if path == "/status":
return HttpAuthorizationPolicy(None)
if not path.startswith("/api/"):
return HttpAuthorizationPolicy(None)
- # Route exposure is no longer split into local-only and remote-only
- # matrices. Every API reaches the role/resource checks below.
+ if _path_in_namespaces(path, _VIEWER_HTTP_NAMESPACES):
+ return HttpAuthorizationPolicy("viewer")
+ if any(
+ rule_method == normalized_method and pattern.fullmatch(path)
+ for rule_method, pattern in _VIEWER_HTTP_MUTATION_RULES
+ ):
+ return HttpAuthorizationPolicy("viewer")
+ if _path_in_namespaces(path, _EDITOR_HTTP_NAMESPACES):
+ return HttpAuthorizationPolicy("editor")
+
minimum_role = "owner"
- if _http_rule_matches(normalized_method, path, _VIEWER_HTTP_MUTATION_RULES):
- # These mutations enforce Show Page ownership and Organization authority
- # in the resource service. Admit a viewer to that final authorization gate.
- minimum_role = "viewer"
+ for rule_method, pattern in _EDITOR_HTTP_RULES:
+ if normalized_method == rule_method and pattern.fullmatch(path):
+ minimum_role = "editor"
+ break
else:
- for rule_method, pattern in _EDITOR_HTTP_RULES:
- if normalized_method == rule_method and pattern.fullmatch(path):
- minimum_role = "editor"
- break
- else:
- if normalized_method in {"GET", "HEAD", "OPTIONS"} and any(
- pattern.fullmatch(path) for pattern in _VIEWER_HTTP_RULES
- ):
- minimum_role = "viewer"
+ if normalized_method in {"GET", "HEAD", "OPTIONS"} and any(
+ pattern.fullmatch(path) for pattern in _VIEWER_HTTP_RULES
+ ):
+ minimum_role = "viewer"
return HttpAuthorizationPolicy(minimum_role)
diff --git a/vibe/cli.py b/vibe/cli.py
index 7e0248fae..337fcce08 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -277,13 +277,13 @@ def _print_task_error(exc: Exception, *, help_command: str | None = None) -> Non
if isinstance(exc, UnresolvableSessionTarget) and exc.reason == "reserved":
exc = _reserved_session_cli_error(exc)
from storage.resource_access_service import (
- REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE,
+ HARNESS_ACCESS_FORBIDDEN_CODE,
ResourceAccessError,
)
if (
isinstance(exc, ResourceAccessError)
- and exc.code == REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE
+ and exc.code == HARNESS_ACCESS_FORBIDDEN_CODE
):
try:
lang = V2Config.load().language
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index ebacdbe3f..9586903e6 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -58,6 +58,7 @@ _INSTANCE_ACCESS_SOURCES = frozenset(
{"owner", "public_instance", "email", "email_domain", "organization_group", "show_page_email"}
)
_ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})
+_INSTANCE_KINDS = frozenset({"personal", "organization"})
_CONNECTOR_LOCK = threading.RLock()
_STATUS_HEARTBEAT_LOCK = threading.Lock()
_STATUS_HEARTBEAT_STARTED = False
@@ -1353,11 +1354,32 @@ def report_runtime_status(config: V2Config | None = None, event: str = "heartbea
timeout=5.0,
)
_replace_active_hostnames(config, result.get("active_hostnames"))
+ _persist_instance_kind(cloud.instance_id, result.get("instance_kind"))
return {"ok": True, **result}
except Exception as exc:
return {"ok": False, "error": "remote_status_report_failed", "detail": str(exc)}
+def _normalized_instance_kind(value: object) -> str | None:
+ return value if isinstance(value, str) and value in _INSTANCE_KINDS else None
+
+
+def _persist_instance_kind(instance_id: str, value: object) -> bool:
+ instance_kind = _normalized_instance_kind(value)
+ if instance_kind is None:
+ return False
+ with CONFIG_LOCK:
+ live_config = V2Config.load()
+ live_cloud = live_config.remote_access.vibe_cloud
+ if live_cloud.instance_id != instance_id or live_cloud.instance_kind == instance_kind:
+ return False
+ api.save_config(
+ {"remote_access": {"vibe_cloud": {"instance_kind": instance_kind}}},
+ validate_remote_access_network=False,
+ )
+ return True
+
+
def mint_cloud_token(
config: V2Config | None = None,
*,
@@ -4121,6 +4143,7 @@ def pair(pairing_key: str, backend_url: str, device_name: str = "avibe") -> dict
missing = [field for field in required if not result.get(field)]
if missing:
return {"ok": False, "error": "invalid_pairing_response", "missing": missing}
+ instance_kind = _normalized_instance_kind(result.get("instance_kind"))
origin_update = result.get("tunnel_origin_update")
if isinstance(origin_update, dict) and origin_update.get("ok") is False:
return {
@@ -4136,6 +4159,7 @@ def pair(pairing_key: str, backend_url: str, device_name: str = "avibe") -> dict
"enabled": True,
"backend_url": backend.base_url,
"instance_id": result["instance_id"],
+ "instance_kind": instance_kind or "",
"client_id": result["client_id"],
"issuer": result["issuer"],
"authorization_endpoint": result["authorization_endpoint"],
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 899f220aa..98ea32636 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2264,13 +2264,13 @@ def enforce_remote_access_cookie():
config = _load_remote_access_config()
if _remote_auth_exempt_before_host_validation():
return None
- from vibe.authorization import context_from_session_payload, trusted_local_context
+ from vibe.authorization import context_from_session_payload, instance_owner_context
local_request = _is_local_request(config)
docker_probe_request = _is_trusted_docker_loopback_probe()
if config is None:
if local_request or docker_probe_request:
- g.authorization_context = trusted_local_context()
+ g.authorization_context = instance_owner_context()
return None
return jsonify({"ok": False, "error": "remote_access_config_unavailable"}), 503
if _remote_access_public_url_invalid(config) and not (local_request or docker_probe_request):
@@ -2278,14 +2278,14 @@ def enforce_remote_access_cookie():
remote_request = _is_remote_access_request(config)
if not remote_request:
if _is_loopback_origin_proxy_request():
- g.authorization_context = trusted_local_context()
+ g.authorization_context = instance_owner_context()
return None
if not local_request and not docker_probe_request:
return jsonify({"ok": False, "error": "remote_access_host_mismatch"}), 503
- g.authorization_context = trusted_local_context()
+ g.authorization_context = instance_owner_context()
return None
if _trusted_public_origin_local_request(config):
- g.authorization_context = trusted_local_context()
+ g.authorization_context = instance_owner_context()
return None
if _remote_auth_exempt_path():
return None
@@ -2307,11 +2307,8 @@ def enforce_remote_access_cookie():
if request.method == "GET" and context.instance_access_source != "show_page_email":
show_page_id = _show_page_id_from_private_route(request.path)
if show_page_id is not None:
- from vibe.authorization import has_temporary_unrestricted_org_access
-
resource_allowed = (
- has_temporary_unrestricted_org_access(context)
- or context.can_use_show_page(show_page_id)
+ context.can_use_show_page(show_page_id)
or _show_page_resource_access_allowed(context, show_page_id)
)
reauth_attempted = request.args.get(REMOTE_SHOW_PAGE_REAUTH_PARAM) == "1"
@@ -2389,14 +2386,7 @@ def enforce_show_page_email_scope():
return jsonify({"ok": False, "error": "show_page_access_forbidden"}), 403
-def _temporary_org_runtime_resource_context(context: Any = None):
- """Return the unchanged identity for the temporary runtime policy.
-
- Admission is evaluated by explicit policy helpers. This function must never
- turn an Organization member into a trusted-local owner or persist ownership
- on their behalf.
- """
-
+def _request_authorization_context(context: Any = None):
if context is not None:
return context
try:
@@ -2406,21 +2396,138 @@ def _temporary_org_runtime_resource_context(context: Any = None):
return resolved
-def _has_temporary_runtime_access(context: Any) -> bool:
- from vibe.authorization import has_temporary_unrestricted_runtime_access
+def _has_runtime_owner_access(context: Any) -> bool:
+ return bool(context is not None and context.is_instance_owner)
- return bool(has_temporary_unrestricted_runtime_access(context))
+def _runtime_record_session_id(record: Any) -> str | None:
+ if not isinstance(record, Mapping):
+ return None
+ value = str(record.get("session_id") or "").strip()
+ return value or None
+
+
+def _runtime_record_agent_refs(record: Any) -> tuple[str | None, str | None]:
+ if not isinstance(record, Mapping):
+ return None, None
+ agent_id = str(record.get("agent_id") or "").strip() or None
+ agent_name = str(record.get("agent_name") or "").strip() or None
+ return agent_id, agent_name
+
+
+def _runtime_record_visible(context: Any, record: Any, *, connection: Any | None = None) -> bool:
+ """Return whether a Project-bound Agent runtime record is authorized.
+
+ Owners see every record. Everyone else must pass both the Project ACL for
+ the bound session (when one exists) and the Agent ACL for the selected
+ Agent (when one exists). Harness definitions and runs intentionally do not
+ use this helper because Harness has no additional resource ACL in this MVP.
+ """
-def _has_runtime_owner_access(context: Any) -> bool:
if context is None:
return False
- # A signed Instance owner (local or remote) owns its runtime surfaces, as in
- # the established model; the temporary Organization rollout additionally
- # admits active members. This never restricts a pre-existing owner.
- if context.is_trusted_local or context.instance_role == "owner":
+ if _has_runtime_owner_access(context):
return True
- return _has_temporary_runtime_access(context)
+ session_id = _runtime_record_session_id(record)
+ agent_id, agent_name = _runtime_record_agent_refs(record)
+ if session_id is None and agent_id is None and agent_name is None:
+ return False
+ if session_id is not None and not _project_session_access_allowed(context, session_id, "editor"):
+ return False
+ if agent_id is None and agent_name is None:
+ return True
+ from core.vibe_agents import VibeAgentAccessError, ensure_agent_selection_access
+
+ def _check(conn: Any) -> bool:
+ try:
+ ensure_agent_selection_access(
+ conn,
+ agent_name=agent_name,
+ agent_id=agent_id,
+ user_context=context,
+ )
+ except VibeAgentAccessError:
+ return False
+ return True
+
+ if connection is not None:
+ return _check(connection)
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ return _check(conn)
+
+
+def _filter_runtime_records(context: Any, records: list[Any] | tuple[Any, ...] | None) -> list[Any]:
+ return [record for record in (records or []) if _runtime_record_visible(context, record)]
+
+
+def _running_agent_counts(agents: list[Any] | tuple[Any, ...] | None) -> dict[str, Any]:
+ """Recompute the frozen RunningAgentCounts shape from authorized rows."""
+
+ states = {"active": 0, "idle": 0, "orphan": 0}
+ by_backend: dict[str, int] = {}
+ rows = [row for row in (agents or []) if isinstance(row, Mapping)]
+ for row in rows:
+ state = str(row.get("state") or "")
+ if state in states:
+ states[state] += 1
+ backend = str(row.get("backend") or "").strip()
+ if backend:
+ by_backend[backend] = by_backend.get(backend, 0) + 1
+ return {
+ "total": len(rows),
+ "active": states["active"],
+ "idle": states["idle"],
+ "orphan": states["orphan"],
+ "by_backend": by_backend,
+ }
+
+
+def _authorized_graph_payload(context: Any, payload: dict[str, Any]) -> dict[str, Any]:
+ if _has_runtime_owner_access(context):
+ return payload
+ from core.services.agent_graph import _counts as graph_counts
+
+ visible_nodes = _filter_runtime_records(context, payload.get("nodes") or [])
+ visible_ids = {
+ str(node.get("session_id") or "")
+ for node in visible_nodes
+ if node.get("session_id")
+ }
+ payload["nodes"] = visible_nodes
+ payload["edges"] = [
+ edge
+ for edge in (payload.get("edges") or [])
+ if (
+ edge.get("kind") == "trigger"
+ and str(edge.get("to") or "") in visible_ids
+ )
+ or (
+ edge.get("kind") != "trigger"
+ and str(edge.get("from") or "") in visible_ids
+ and str(edge.get("to") or "") in visible_ids
+ )
+ ]
+ visible_trigger_ids = {
+ str(edge.get("from") or "").removeprefix("def:")
+ for edge in payload["edges"]
+ if edge.get("kind") == "trigger"
+ }
+ payload["trigger_nodes"] = [
+ node
+ for node in (payload.get("trigger_nodes") or [])
+ if str(node.get("definition_id") or "") in visible_trigger_ids
+ ]
+ payload["counts"] = graph_counts(visible_nodes)
+ return payload
+
+
+def _require_runtime_record(context: Any, record: Any, *, not_found: tuple[dict[str, Any], int]):
+ if record is None:
+ return not_found
+ if not _runtime_record_visible(context, record):
+ return not_found
+ return None
@app.before_request
@@ -2517,10 +2624,11 @@ def enforce_project_role_capabilities():
kind, resource_id = resource
if kind == "show_page":
- if _has_temporary_runtime_access(context) or context.can_use_show_page(
- resource_id
- ):
- return None
+ # Show Page reads are governed by the page's own ACL. Project ACL is
+ # required by ShowPageStore for create/edit operations, but applying
+ # the generic project middleware here treats a session id as a project
+ # id and rejects valid pages (including pages without a live session).
+ return None
engine = create_sqlite_engine()
with engine.connect() as conn:
role = (
@@ -2872,11 +2980,9 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):
from vibe.sse_broker import broker
access_sub_id, access_queue = broker.subscribe()
- if not _project_session_access_allowed(
- authorization_context,
- session_id,
- "viewer",
- ) or not _show_page_resource_access_allowed(authorization_context, session_id):
+ if not authorization_context.has_role("viewer") or not _show_page_resource_access_allowed(
+ authorization_context, session_id
+ ):
broker.unsubscribe(access_sub_id)
await websocket.close(code=1008)
return
@@ -2885,11 +2991,10 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):
proxy_task = asyncio.create_task(_proxy_show_runtime_websocket(websocket, session_id))
revocation_task = (
asyncio.create_task(
- _wait_for_project_session_access_loss(
+ _wait_for_show_page_access_loss(
access_queue,
authorization_context,
session_id,
- "viewer",
)
)
if access_queue is not None and authorization_context is not None
@@ -2994,8 +3099,7 @@ async def terminal_websocket(websocket: WebSocket, session_id: str):
return
if not _show_runtime_websocket_authorized(
websocket,
- minimum_role="viewer",
- require_unrestricted_org_apps=True,
+ minimum_role="editor",
):
await websocket.close(code=1008)
return
@@ -3099,8 +3203,11 @@ async def terminal_session_delete(session_id: str):
return jsonify({"ok": False, "error": "terminal_origin_forbidden"}), 403
if not _show_runtime_websocket_authorized(
terminal_request,
+ # Closing a terminal session is allowed for any authenticated runtime
+ # viewer; the subject-scoped effective ID below prevents terminating a
+ # different user's session. Opening an interactive terminal remains an
+ # Editor-only operation in ``terminal_websocket``.
minimum_role="viewer",
- require_unrestricted_org_apps=True,
):
return jsonify({"ok": False, "error": "terminal_unauthorized"}), 403
@@ -3130,7 +3237,6 @@ def _show_runtime_websocket_authorized(
*,
minimum_role: str = "viewer",
project_session_id: str | None = None,
- require_unrestricted_org_apps: bool = False,
) -> bool:
config = _load_remote_access_config()
if config is None:
@@ -3142,36 +3248,31 @@ def _show_runtime_websocket_authorized(
payload = _remote_access_websocket_session_payload(websocket, config)
if payload is None:
return False
- from vibe.authorization import (
- context_from_session_payload,
- has_temporary_unrestricted_org_access,
- )
+ from vibe.authorization import context_from_session_payload
context = context_from_session_payload(payload)
- temporary_org_access = has_temporary_unrestricted_org_access(context)
+ if not context.has_role(minimum_role):
+ return False
if context.instance_access_source == "show_page_email":
- if require_unrestricted_org_apps:
- return False
if project_session_id is None or not context.can_use_show_page(project_session_id):
return False
- return context.has_role(minimum_role)
- if not temporary_org_access:
- return False
+ return True
if project_session_id is None or _has_runtime_owner_access(context):
return True
+ if minimum_role == "viewer":
+ # Show Page runtime reads use the independent Show Page ACL. Project
+ # ACL remains an edit/create requirement in ShowPageStore.
+ return context.has_role("viewer") and _show_page_resource_access_allowed(context, project_session_id)
return _project_session_access_allowed(context, project_session_id, minimum_role)
def _project_session_access_allowed(context: Any, session_id: str, minimum_role: str) -> bool:
from storage import project_access_service
- from vibe.authorization import has_temporary_unrestricted_org_access
if context is None:
return False
- if context.is_remote and context.instance_access_source == "show_page_email":
+ if context.instance_access_source == "show_page_email":
return minimum_role == "viewer" and context.can_use_show_page(session_id)
- if context.is_remote and not has_temporary_unrestricted_org_access(context):
- return False
if _has_runtime_owner_access(context):
return True
if not context.has_role(minimum_role):
@@ -3206,18 +3307,28 @@ async def _wait_for_project_session_access_loss(
return
+async def _wait_for_show_page_access_loss(
+ queue: Any,
+ context: Any,
+ session_id: str,
+) -> None:
+ """Close a Show Page socket when its independent ACL is revoked."""
+
+ while True:
+ event_type, _payload = await queue.get()
+ if event_type != "authorization.changed":
+ continue
+ if not context.has_role("viewer") 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
- from vibe.authorization import has_temporary_unrestricted_org_access
if context is None:
return False
- if context.is_remote and context.instance_access_source == "show_page_email":
+ if context.instance_access_source == "show_page_email":
return context.can_use_show_page(session_id)
- if context.is_remote and not has_temporary_unrestricted_org_access(context):
- return False
- if has_temporary_unrestricted_org_access(context):
- return True
try:
return resource_access_service.can_use_resource(
context,
@@ -3245,15 +3356,14 @@ def _show_runtime_websocket_resource_context(websocket: Any):
config = _load_remote_access_config()
if config is None or _websocket_is_local_request(websocket, config):
- return resource_access_service.ResourceUserContext(is_trusted_local=True)
+ return resource_access_service.ResourceUserContext(instance_role="owner")
payload = _remote_access_websocket_session_payload(websocket, config)
if payload is None:
return resource_access_service.ResourceUserContext()
- return _temporary_org_runtime_resource_context(
+ return _request_authorization_context(
resource_access_service.current_resource_context(
payload,
is_remote=True,
- is_trusted_local=False,
)
)
@@ -3747,21 +3857,13 @@ def config_get():
def _config_payload_for_context(config: Any, authorization_context: Any) -> dict[str, Any]:
- """Project config without turning a remote member into a local identity."""
+ """Project configuration by Instance role, independent of request origin."""
from vibe import api
- if authorization_context is None or not authorization_context.is_remote:
+ if authorization_context is None or authorization_context.can_manage_instance:
return api.client_config_payload(config)
- if not _has_temporary_runtime_access(authorization_context):
- return api.remote_config_payload(config)
-
- # Active Organization members temporarily receive the same runtime/config
- # fields as local callers. Pairing and tunnel identity remain a separate
- # control-plane boundary and never travel through this generic endpoint.
- payload = api.client_config_payload(config)
- payload.pop("remote_access", None)
- return payload
+ return api.non_owner_config_payload(config)
_MODEL_HUB_SERVICE = None
@@ -4291,7 +4393,11 @@ async def running_agents_get():
return jsonify({"ok": False, "unreachable": True, "agents": [], "counts": {}}), 503
except internal_client.InternalServerTimeout:
return jsonify({"ok": False, "unreachable": True, "timeout": True, "agents": [], "counts": {}}), 504
- return jsonify(result.get("body") or {})
+ body = result.get("body") or {}
+ context = _request_authorization_context()
+ agents = _filter_runtime_records(context, body.get("agents") or [])
+ counts = body.get("counts") if _has_runtime_owner_access(context) else _running_agent_counts(agents)
+ return jsonify({**body, "agents": agents, "counts": counts})
@app.route("/api/running-agents/end", methods=["POST"])
@@ -4302,6 +4408,14 @@ async def running_agents_end():
from vibe import internal_client
payload = request.json or {}
+ context = _request_authorization_context()
+ denied = _require_runtime_record(
+ context,
+ payload,
+ not_found=({"ok": False, "error": "running_agent_not_found"}, 404),
+ )
+ if denied is not None:
+ return jsonify(denied[0]), denied[1]
try:
result = await internal_client.end_running_agent(payload)
except internal_client.InternalServerUnavailable:
@@ -4357,7 +4471,8 @@ async def agents_graph_get():
include_background=include_background,
live_unreachable=live_unreachable,
)
- return jsonify(payload)
+ context = _request_authorization_context()
+ return jsonify(_authorized_graph_payload(context, payload))
@app.route("/api/agents/<name>", methods=["GET"])
@@ -4938,19 +5053,15 @@ def _is_remote_show_page_request() -> bool:
def _show_page_payload_for_request(payload: dict) -> dict:
- context = getattr(g, "authorization_context", None)
- if not _is_remote_show_page_request() or _has_temporary_runtime_access(context):
- return payload
- return {key: value for key, value in payload.items() if key != "path"}
+ return payload
@app.route("/api/show-pages", methods=["GET"])
def show_pages_list_get():
- from storage import project_access_service
from vibe import api
context = getattr(g, "authorization_context", None)
- resource_context = _temporary_org_runtime_resource_context(context)
+ resource_context = _request_authorization_context(context)
payload = api.list_show_pages(user_context=resource_context)
if _is_remote_show_page_request():
payload = {
@@ -4960,25 +5071,6 @@ def show_pages_list_get():
for page in payload.get("pages", [])
],
}
- if (
- context is not None
- and not _has_runtime_owner_access(context)
- ):
- engine = _projects_engine()
- with engine.connect() as conn:
- payload["pages"] = [
- page
- for page in payload.get("pages", [])
- if project_access_service.role_allows(
- project_access_service.get_effective_session_role(
- conn,
- context,
- str(page.get("session_id") or ""),
- ),
- "viewer",
- )
- ]
- payload["count"] = len(payload["pages"])
return jsonify(payload)
@@ -4993,7 +5085,7 @@ def show_page_visibility_post(session_id):
api.set_show_page_visibility(
session_id,
str(payload.get("visibility") or ""),
- user_context=_temporary_org_runtime_resource_context(),
+ user_context=_request_authorization_context(),
)
)
except ShowPageError as exc:
@@ -5010,7 +5102,7 @@ def show_page_ensure_post(session_id):
_show_page_payload_for_request(
api.ensure_show_page(
session_id,
- user_context=_temporary_org_runtime_resource_context(),
+ user_context=_request_authorization_context(),
)
)
)
@@ -5027,7 +5119,7 @@ def show_page_access_get(session_id):
response = jsonify(
api.get_show_page_access(
session_id,
- user_context=_temporary_org_runtime_resource_context(),
+ user_context=_request_authorization_context(),
)
)
response.headers["Cache-Control"] = "no-store, private"
@@ -5046,7 +5138,7 @@ def show_page_authorized_emails_get(session_id):
response = jsonify(
api.get_show_page_authorized_emails(
session_id,
- user_context=_temporary_org_runtime_resource_context(),
+ user_context=_request_authorization_context(),
)
)
response.headers["Cache-Control"] = "no-store, private"
@@ -5076,7 +5168,7 @@ def show_page_authorized_emails_put(session_id):
api.replace_show_page_authorized_emails(
session_id,
emails,
- user_context=_temporary_org_runtime_resource_context(),
+ user_context=_request_authorization_context(),
)
)
except ShowPageError as exc:
@@ -5092,7 +5184,7 @@ def show_page_rotate_share_post(session_id):
return jsonify(
api.rotate_show_page_share(
session_id,
- user_context=_temporary_org_runtime_resource_context(),
+ user_context=_request_authorization_context(),
)
)
except ShowPageError as exc:
@@ -5110,7 +5202,7 @@ def show_page_set_share_id_post(session_id):
api.set_show_page_share_id(
session_id,
str(payload.get("share_id") or ""),
- user_context=_temporary_org_runtime_resource_context(),
+ user_context=_request_authorization_context(),
)
)
except ShowPageError as exc:
@@ -5153,7 +5245,7 @@ def show_page_icon_get(session_id):
try:
page = store.require_access(
session_id,
- user_context=_temporary_org_runtime_resource_context(),
+ user_context=_request_authorization_context(),
)
# Any of the user's own pages — private, public, OR offline — may serve
# its static icon: the payload advertises an icon token for all of them
@@ -5212,7 +5304,7 @@ def _dock_error_response(exc):
def dock_get():
from vibe import api
- return jsonify(api.get_dock(user_context=_temporary_org_runtime_resource_context()))
+ return jsonify(api.get_dock(user_context=_request_authorization_context()))
@app.route("/api/dock/pins", methods=["POST"])
@@ -5226,7 +5318,7 @@ def dock_pin_post():
return jsonify(
api.pin_dock_show_page(
str(payload.get("session_id") or ""),
- user_context=_temporary_org_runtime_resource_context(),
+ user_context=_request_authorization_context(),
)
)
except (DockError, ShowPageError) as exc:
@@ -5243,7 +5335,7 @@ def dock_unpin_delete(session_id):
return jsonify(
api.unpin_dock_show_page(
session_id,
- user_context=_temporary_org_runtime_resource_context(),
+ user_context=_request_authorization_context(),
)
)
except (DockError, ShowPageError) as exc:
@@ -5266,7 +5358,7 @@ def dock_order_put():
api.set_dock_order(
payload.get("order"),
known=payload.get("known"),
- user_context=_temporary_org_runtime_resource_context(),
+ user_context=_request_authorization_context(),
)
)
except (DockError, ShowPageError) as exc:
@@ -5777,21 +5869,13 @@ async def config_post():
else:
agent_backend_runtime["apply_on_next_start"] = True
authorization_context = getattr(g, "authorization_context", None)
- is_remote = bool(authorization_context is not None and authorization_context.is_remote)
- has_temporary_runtime_access = _has_temporary_runtime_access(authorization_context)
response_payload = _config_payload_for_context(config, authorization_context)
- # Pairing/tunnel reconciliation remains local-only. Active Organization
- # members do receive the platform and Agent backend results needed to
- # confirm the runtime configuration changes they are temporarily allowed
- # to make.
- if not is_remote:
- if remote_access_runtime is not None:
- response_payload["remote_access_runtime"] = remote_access_runtime
- if not is_remote or has_temporary_runtime_access:
- if platform_runtime is not None:
- response_payload["platform_runtime"] = platform_runtime
- if agent_backend_runtime is not None:
- response_payload["agent_backend_runtime"] = agent_backend_runtime
+ if remote_access_runtime is not None:
+ response_payload["remote_access_runtime"] = remote_access_runtime
+ if platform_runtime is not None:
+ response_payload["platform_runtime"] = platform_runtime
+ if agent_backend_runtime is not None:
+ response_payload["agent_backend_runtime"] = agent_backend_runtime
return jsonify(response_payload)
@@ -6541,18 +6625,20 @@ def remote_access_auth_callback():
@app.route("/api/session", methods=["GET"])
def api_session():
from vibe import remote_access
- from vibe.authorization import (
- context_from_session_payload,
- has_temporary_unrestricted_org_access,
- trusted_local_context,
- )
+ from vibe.authorization import context_from_session_payload, instance_owner_context
config = _load_remote_access_config()
+ instance_kind = None
+ if config is not None:
+ configured_instance_kind = config.remote_access.vibe_cloud.instance_kind
+ if configured_instance_kind in {"personal", "organization"}:
+ instance_kind = configured_instance_kind
if config is None or not _is_remote_access_request(config):
- context = trusted_local_context()
+ context = instance_owner_context()
response = jsonify(
{
"remote": False,
+ "instance_kind": instance_kind,
"instance_role": "owner",
"capabilities": context.capability_projection(),
}
@@ -6579,13 +6665,8 @@ def api_session():
"authenticated": True,
"email": str(payload.get("email", "")),
"sub": str(payload.get("sub", "")),
+ "instance_kind": instance_kind,
"instance_role": context.instance_role,
- "temporary_unrestricted_org_access": (
- has_temporary_unrestricted_org_access(context)
- ),
- "temporary_unrestricted_org_app_access": (
- has_temporary_unrestricted_org_access(context)
- ),
"capabilities": context.capability_projection(),
}
)
@@ -6617,7 +6698,6 @@ def _remote_resource_access_context():
return config, payload, resource_access_service.current_resource_context(
payload,
is_remote=True,
- is_trusted_local=False,
)
@@ -8027,14 +8107,14 @@ def _skills_project_id_kwargs(project_dir: str | None, project_id: str | None) -
def _skills_user_context_kwargs(context: Any) -> dict[str, Any]:
- """Pass authorization context only to remote skill API calls.
+ """Pass the parsed request authorization context to Skill API calls.
- Local callers historically invoke the skill API with its compact legacy
- signature. Remote requests need the real context for Org ACL enforcement,
- so include it only when the request actually crossed the remote boundary.
+ Local service callers historically invoke the Skill API with its compact
+ legacy signature. HTTP requests need the real context for ACL enforcement;
+ local HTTP requests already carry an ordinary Owner context.
"""
- if getattr(context, "is_remote", False):
+ if context is not None:
return {"user_context": context}
return {}
@@ -8664,16 +8744,9 @@ def _session_runtime_projection(
if isinstance(raw_activities, list)
else []
)
- from vibe.authorization import has_temporary_unrestricted_runtime_access
-
- if (
- getattr(authorization_context, "is_remote", False)
- and not has_temporary_unrestricted_runtime_access(authorization_context)
- ):
+ if authorization_context is not None and not authorization_context.has_role("editor"):
activities = [
- item
- for item in activities
- if str(item.get("item_kind") or "") == "backend_activity"
+ item for item in activities if item.get("item_kind") == "backend_activity"
]
projection: dict[str, Any] = {
# Retained as a read-only compatibility alias for older clients.
@@ -8741,13 +8814,7 @@ async def sessions_bootstrap(session_id: str):
if can_chat
else []
)
- from vibe.authorization import has_temporary_unrestricted_runtime_access
-
- can_access_draft = can_chat and not (
- authorization_context
- and authorization_context.is_remote
- and not has_temporary_unrestricted_runtime_access(authorization_context)
- )
+ can_access_draft = can_chat
draft = (
message_deliveries.get_draft_state(conn, session_id)
if can_access_draft
@@ -8841,6 +8908,8 @@ RESERVED_SESSION_PROTECTED_I18N_KEY = "harness.notice.workspaceSessionProtected"
#: is not an answer to "why did my message not send", and the composer's own inert-state
#: notice has to say the same thing this body says.
RESERVED_SESSION_READ_ONLY_I18N_KEY = "harness.notice.workspaceSessionReadOnly"
+
+
def _reserved_session_response(i18n_key: str, *, code: str = "reserved_session"):
"""Shared 403 payload for a write refused because the RUNTIME reserves the session.
@@ -8860,6 +8929,7 @@ def _reserved_session_response(i18n_key: str, *, code: str = "reserved_session")
lang = settings_service.load_config_or_default().language
return _coded_error_response(code, t(i18n_key, lang), 403)
+
def _backend_locked_response(err):
"""Shared 409 payload for a rejected cross-backend session change.
@@ -9773,7 +9843,7 @@ async def show_page_icon_upload(session_id: str, starlette_request: FastAPIReque
data,
filename=upload.filename,
content_type=upload.content_type,
- user_context=_temporary_org_runtime_resource_context(),
+ user_context=_request_authorization_context(),
)
# Broadcast so EVERY already-mounted inventory (Dock, WindowLayer, mobile
# drawer, app search) reloads and picks up the new icon_version — the
@@ -10082,18 +10152,10 @@ def _media_row_show_page_access_allowed(context: Any, row: dict[str, Any]) -> bo
def _request_can_read_media_row(conn, token: str, row: dict[str, Any]) -> bool:
from storage import media_service, project_access_service
- from vibe.authorization import has_temporary_unrestricted_org_access
context = getattr(g, "authorization_context", None)
if not _media_row_show_page_access_allowed(context, row):
return False
- if row.get("source") == "show_annotation" and has_temporary_unrestricted_org_access(
- context
- ):
- # Annotation screenshots are part of the Show Page surface. During the
- # temporary unrestricted Organization rollout they follow the page,
- # while all unrelated media keeps its existing Project/session ACL.
- return True
if context is None or _has_runtime_owner_access(context):
return True
session_ids = media_service.referenced_session_ids(conn, token)
@@ -11234,12 +11296,10 @@ def _workbench_event_visible_to_context(context, event_type: str, payload: str)
return False
if not _show_page_resource_access_allowed(context, session_id):
return False
- from vibe.authorization import has_temporary_unrestricted_org_access
-
- if has_temporary_unrestricted_org_access(context):
- # Show events are page content. Keep them aligned with the same
- # temporary all-pages policy instead of reapplying Project ACL here.
- return True
+ # Show Page event visibility is intentionally independent from Project
+ # ACL. Project ACL gates page creation/editing, while the page ACL gates
+ # Viewer reads and live event delivery.
+ return context.has_role("viewer")
if _has_runtime_owner_access(context):
return True
if event_type in {"authorization.changed", "workbench.events.bridge.status"}:
@@ -11283,9 +11343,9 @@ def _workbench_event_payload_for_context(context, event_type: str, payload: str)
# materialized screenshot. Every remote recipient reads the image by
# attachment id, so the path is useless to them and only discloses
# the host's directory layout — drop it for every remote reader
- # (active Organization members included) and drop the whole frame
- # if it cannot be projected. Display-layer redaction is preserved
- # under the temporary full-access rollout (see #1343).
+ # and drop the whole frame
+ # if it cannot be projected. Host-path redaction is transport safety,
+ # independent of Instance role or Organization membership.
try:
envelope = json.loads(payload)
except (TypeError, json.JSONDecodeError):
@@ -11298,25 +11358,6 @@ def _workbench_event_payload_for_context(context, event_type: str, payload: str)
ensure_ascii=False,
separators=(",", ":"),
)
- if (
- event_type == "vaults.updated"
- and context is not None
- and context.is_remote
- and not _has_temporary_runtime_access(context)
- ):
- try:
- envelope = json.loads(payload)
- except (TypeError, json.JSONDecodeError):
- return payload
- if isinstance(envelope, dict) and isinstance(envelope.get("data"), dict):
- return json.dumps(
- {
- **envelope,
- "data": {"scope": envelope["data"].get("scope", "")},
- },
- ensure_ascii=False,
- separators=(",", ":"),
- )
if event_type != "inbox.unread.changed":
return payload
try:
@@ -12368,7 +12409,7 @@ def _is_denied_show_page_at_fs_path(decoded: str, *, session_id: str, confine_to
# symlink escape), so confine them to the workspace. That covers the PUBLIC
# surface and any REMOTE viewer of the private `/show/` surface: remote
# collaborators reach the page over the tunnel and must never be able to
- # read out-of-Project disk files through an authored symlink. Trusted-local
+ # read out-of-Project disk files through an authored symlink. Local Owner
# authoring keeps the escape — an agent may legitimately symlink a disk file
# into its own page — and a genuine dependency path (its parent is literally
# outside the workspace) is still deferred to the Show Runtime's fs
@@ -12521,7 +12562,7 @@ def _show_annotation_capability(
"""Return whether this request may write and dispatch Show annotations.
The current device-side authorization boundary is the validated Workbench
- session (or trusted local access), represented by ``author``. Page
+ session, represented by ``author``. Page
visibility and the share/session binding remain independent structural
checks so a future ACL can extend the author decision without changing the
event pipeline.
@@ -12535,17 +12576,12 @@ def _show_annotation_capability(
def _show_request_author(*, public: bool = False) -> dict[str, str] | None:
from vibe import remote_access
- from vibe.authorization import (
- context_from_session_payload,
- has_temporary_unrestricted_runtime_access,
- )
+ from vibe.authorization import context_from_session_payload
if not public:
context = getattr(g, "authorization_context", None)
if context is not None:
- if not context.has_role("editor") and not has_temporary_unrestricted_runtime_access(
- context
- ):
+ if not context.has_role("editor"):
return None
if context.is_remote:
return {"kind": "user", "email": context.email} if context.email else None
@@ -12564,10 +12600,7 @@ def _show_request_author(*, public: bool = False) -> dict[str, str] | None:
)
if context is not None:
email = str(session.get("email", "")).strip()
- if email and (
- context.has_role("editor")
- or has_temporary_unrestricted_runtime_access(context)
- ):
+ if email and context.has_role("editor"):
return {"kind": "user", "email": email}
return None
@@ -12618,18 +12651,11 @@ async def _show_event_response_from_payload(
# so accepting one from across the tunnel lets a collaborator forge Agent
# or system activity and corrupt the shared transcript. This is the same
# human-event / mark-resolution allowlist the public route enforces; the
- # local CLI route (`_is_cli_show_event_request`) and trusted-local HTML
- # callers keep the full supported set.
+ # local CLI callers keep the full supported set.
event_type = str(payload.get("type") or "").strip()
if event_type not in HUMAN_EVENT_TYPES and event_type != "assistant.mark.resolved":
return _unsupported_show_event_type_response()
- # Non-member remote readers keep the host-path redaction. Active
- # Organization members receive the same runtime detail as local callers.
- remote = (
- not public
- and _is_remote_show_page_request()
- and not _has_temporary_runtime_access(context)
- )
+ remote = not public and _is_remote_show_page_request()
if show_event_payload_session_mismatch(session_id, payload):
return (
jsonify(
@@ -13289,11 +13315,7 @@ async def _show_events_response(
):
# Resolve the projection before the SSE generator loses request context.
authorization_context = None if public else getattr(g, "authorization_context", None)
- remote = (
- not public
- and _is_remote_show_page_request()
- and not _has_temporary_runtime_access(authorization_context)
- )
+ remote = not public and _is_remote_show_page_request()
if request.method == "GET":
if request.args.get("stream") == "1":
return await _show_events_stream(
@@ -14060,7 +14082,7 @@ def redirect_private_show_page_to_canonical_path(session_id):
try:
page = store.require_access(
session_id,
- user_context=_temporary_org_runtime_resource_context(),
+ user_context=_request_authorization_context(),
)
except ShowPageError as exc:
if exc.code == "resource_access_forbidden":
@@ -14094,7 +14116,7 @@ async def serve_private_show_page(session_id, asset_path):
try:
page = store.require_access(
session_id,
- user_context=_temporary_org_runtime_resource_context(),
+ user_context=_request_authorization_context(),
)
except ShowPageError as exc:
if exc.code == "resource_access_forbidden":