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): remove trusted-local gating for org runtime access

Maxf37061542e25
diff --git a/core/dock_store.py b/core/dock_store.py
index 77aeb2554..a26e9ca6b 100644
--- a/core/dock_store.py
+++ b/core/dock_store.py
@@ -182,7 +182,9 @@ def _filter_dock_for_access(
user_context: Any,
db_path: Path | None,
) -> dict[str, Any]:
- if user_context.is_trusted_local:
+ from vibe.authorization import has_temporary_unrestricted_org_access
+
+ if user_context.is_trusted_local or has_temporary_unrestricted_org_access(user_context):
return doc
store = ShowPageStore(db_path)
try:
@@ -204,7 +206,13 @@ def _require_show_page_management(
user_context: Any,
db_path: Path | None,
) -> None:
- if user_context.is_trusted_local or not session_ids:
+ from vibe.authorization import has_temporary_unrestricted_org_access
+
+ if (
+ user_context.is_trusted_local
+ or has_temporary_unrestricted_org_access(user_context)
+ or not session_ids
+ ):
return
store = ShowPageStore(db_path)
try:
@@ -358,10 +366,15 @@ 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)
+ )
with _DOCK_MUTATION_LOCK:
doc = _load(db_path)
visible_doc = _filter_dock_for_access(doc, user_context=context, db_path=db_path)
- known_doc = doc if context.is_trusted_local else visible_doc
+ known_doc = doc if has_full_runtime_access else visible_doc
server_known = set(BUILTIN_DOCK_IDS) | {_show_id(pin["session_id"]) for pin in known_doc["pins"]}
if known is not None:
if not isinstance(known, list) or not all(isinstance(item, str) for item in known):
@@ -380,7 +393,7 @@ def set_dock_order(
merged_order = (
_merge_visible_order(doc["order"], order, server_known)
- if not context.is_trusted_local
+ if not has_full_runtime_access
else list(order)
)
doc = {"order": merged_order, "pins": doc["pins"]}
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 44efe419d..db0c72fed 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -7760,12 +7760,12 @@ class ScheduledTaskService:
try:
from storage.resource_access_service import (
REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE,
- metadata_has_remote_resource_context,
+ metadata_allows_temporary_unrestricted_runtime,
)
if (
request.request_type not in {"task_run", "scheduled"}
- and metadata_has_remote_resource_context(request.metadata)
+ and not metadata_allows_temporary_unrestricted_runtime(request.metadata)
):
raise PermissionError(REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE)
if request.request_type in {"task_run", "scheduled"}:
@@ -8436,7 +8436,7 @@ class ScheduledTaskService:
) -> TaskExecutionResult:
from storage.resource_access_service import (
REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE,
- metadata_has_remote_resource_context,
+ metadata_allows_temporary_unrestricted_runtime,
)
error: Optional[str] = None
@@ -8445,7 +8445,7 @@ class ScheduledTaskService:
failure_code: Optional[str] = None
session_id = task.session_id
session_key = task.session_key
- if metadata_has_remote_resource_context(task.metadata):
+ if not metadata_allows_temporary_unrestricted_runtime(task.metadata):
error = REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE
if not self.store.suspend_task(task.id, error=error):
logger.warning(
diff --git a/core/services/session_fork.py b/core/services/session_fork.py
index bdd0b9407..dd6219c35 100644
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@ -16,7 +16,11 @@ from typing import Any, Mapping, Optional
from config import paths
from core.backend_failure import BACKEND_FAILURE_EVENT, is_backend_failure_notification
-from vibe.authorization import AuthorizationContext, require_instance_role
+from vibe.authorization import (
+ AuthorizationContext,
+ has_temporary_unrestricted_runtime_access,
+ require_instance_role,
+)
from vibe.i18n import t
from vibe.message_identity import INPUT_TURN_AUTHOR_TYPES, is_input_turn
from vibe.message_types import spec_for, types_with
@@ -187,7 +191,10 @@ def reserve_forked_session(
try:
with engine.begin() as conn:
reserve_write_lock(conn)
- if not context.is_instance_owner:
+ if not (
+ context.is_instance_owner
+ or has_temporary_unrestricted_runtime_access(context)
+ ):
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 a75fbd3b3..b7c61d05f 100644
--- a/core/services/skills.py
+++ b/core/services/skills.py
@@ -32,6 +32,8 @@ 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
@@ -378,7 +380,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:
+ if context.is_trusted_local or has_temporary_unrestricted_runtime_access(context):
return result
raw_skills = [dict(skill) for skill in result["skills"] if isinstance(skill, dict)]
@@ -491,7 +493,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:
+ if context.is_trusted_local or has_temporary_unrestricted_runtime_access(context):
return
engine = get_cached_sqlite_engine()
with engine.connect() as connection:
@@ -512,7 +514,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:
+ if context.can_manage_instance or has_temporary_unrestricted_runtime_access(context):
return
raise SkillAccessError()
@@ -525,9 +527,16 @@ def _require_skill_use_access(
) -> None:
"""Require Instance use and Project chat access before invoking askill."""
- if not context.can_use_resource("skill"):
+ if (
+ not context.can_use_resource("skill")
+ and not has_temporary_unrestricted_runtime_access(context)
+ ):
raise SkillAccessError()
- if context.is_trusted_local or context.is_instance_owner:
+ if (
+ context.is_trusted_local
+ or context.is_instance_owner
+ or has_temporary_unrestricted_runtime_access(context)
+ ):
return
if not project_dir:
if scope in {"all", "global"}:
@@ -811,7 +820,10 @@ async def add_skill(
if scope not in ("global", "project"):
raise SkillsError("invalid_scope", "install scope must be global or project")
context = resolve_resource_access_context(user_context)
- if not context.is_trusted_local:
+ if not (
+ context.is_trusted_local
+ or has_temporary_unrestricted_runtime_access(context)
+ ):
_require_skill_create_access(context)
target_names = [skill] if skill else []
if not target_names:
@@ -915,7 +927,10 @@ async def remove_skill(
if scope not in ("global", "project"):
raise SkillsError("invalid_scope", "remove scope must be global or project")
context = resolve_resource_access_context(user_context)
- if not context.is_trusted_local:
+ if not (
+ context.is_trusted_local
+ or has_temporary_unrestricted_runtime_access(context)
+ ):
_require_skill_create_access(context)
resource_ids = await _installed_skill_resource_ids(
askill_path,
@@ -990,7 +1005,11 @@ async def check(
backends=list(BACKEND_TO_AGENT),
user_context=context,
)
- if context.is_trusted_local or not isinstance(filtered.get("summary"), dict):
+ if (
+ context.is_trusted_local
+ or has_temporary_unrestricted_runtime_access(context)
+ or not isinstance(filtered.get("summary"), dict)
+ ):
return filtered
skills = filtered.get("skills") if isinstance(filtered.get("skills"), list) else []
statuses = [str(skill.get("status") or "") for skill in skills if isinstance(skill, dict)]
@@ -1018,7 +1037,10 @@ async def update(
if scope not in ("global", "project"):
raise SkillsError("invalid_scope", "update scope must be global or project")
context = resolve_resource_access_context(user_context)
- if not context.is_trusted_local:
+ if not (
+ context.is_trusted_local
+ or has_temporary_unrestricted_runtime_access(context)
+ ):
_require_skill_create_access(context)
resource_ids = await _installed_skill_resource_ids(
askill_path,
diff --git a/core/show_pages.py b/core/show_pages.py
index 1a7da79db..ae4f2be35 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -463,19 +463,25 @@ class ShowPageStore:
@staticmethod
def _require_create_access(user_context: Any) -> None:
- if user_context.can_manage_instance:
+ from vibe.authorization import has_temporary_unrestricted_org_access
+
+ if user_context.can_manage_instance or has_temporary_unrestricted_org_access(user_context):
return
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.can_manage_instance
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)
+ )
):
return
resource_access_service.ensure_resource_policy(
@@ -509,7 +515,6 @@ class ShowPageStore:
.first()
)
if existing is not None:
- self._register_created_resource_policy(conn, session_id, context)
self._require_resource_access(conn, session_id, context)
return _page_from_row(existing)
self._require_create_access(context)
@@ -546,7 +551,6 @@ class ShowPageStore:
.first()
)
if existing is not None:
- self._register_created_resource_policy(conn, session_id, context)
self._require_resource_access(conn, session_id, context)
return _page_from_row(existing), False
self._require_create_access(context)
diff --git a/core/vibe_agents.py b/core/vibe_agents.py
index bd2c0932f..0bbca9b57 100644
--- a/core/vibe_agents.py
+++ b/core/vibe_agents.py
@@ -31,7 +31,10 @@ from storage.models import (
state_meta,
)
from storage.session_reclaim import DEFINITION_AGENT_BINDING_REVISION_KEY
-from vibe.authorization import trusted_local_context
+from vibe.authorization import (
+ has_temporary_unrestricted_runtime_access,
+ trusted_local_context,
+)
logger = logging.getLogger(__name__)
@@ -287,7 +290,8 @@ def ensure_agent_name_access(
def _require_agent_create_access(user_context: Any) -> None:
- if user_context.can_manage_agents:
+ context = resolve_resource_access_context(user_context)
+ if context.can_manage_agents or has_temporary_unrestricted_runtime_access(context):
return
raise VibeAgentAccessError("Agent access is not permitted.")
@@ -296,7 +300,11 @@ 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:
+ if (
+ context.is_trusted_local
+ or context.is_instance_owner
+ or has_temporary_unrestricted_runtime_access(context)
+ ):
return context
raise VibeAgentAccessError("Agent access is not permitted.")
@@ -546,7 +554,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:
+ if context.is_remote and not has_temporary_unrestricted_runtime_access(context):
raise VibeAgentAccessError("Agent access is not permitted.")
return None
diff --git a/core/watches.py b/core/watches.py
index e5c4a0272..529ed2d97 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -2077,7 +2077,7 @@ class ManagedWatchService:
async def _run_watch(self, watch_id: str) -> None:
from storage.resource_access_service import (
REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE,
- metadata_has_remote_resource_context,
+ metadata_allows_temporary_unrestricted_runtime,
)
lifetime_started: float | None = None
@@ -2099,7 +2099,7 @@ class ManagedWatchService:
watch = self.store.get_watch(watch_id)
if watch is None or not watch.enabled:
return
- if metadata_has_remote_resource_context(watch.metadata):
+ if not metadata_allows_temporary_unrestricted_runtime(watch.metadata):
self._watch_store_call(
watch.id,
"suspend_remote_origin",
diff --git a/core/web_push_notifications.py b/core/web_push_notifications.py
index d892f23f9..64fe6ffbf 100644
--- a/core/web_push_notifications.py
+++ b/core/web_push_notifications.py
@@ -346,7 +346,9 @@ 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
- if context.is_instance_owner:
+ from vibe.authorization import has_temporary_unrestricted_runtime_access
+
+ if context.is_instance_owner or has_temporary_unrestricted_runtime_access(context):
return messages_service.total_unread(conn, platform="avibe")
from storage import project_access_service
diff --git a/storage/project_access_service.py b/storage/project_access_service.py
index 5fb97d216..592f06e0b 100644
--- a/storage/project_access_service.py
+++ b/storage/project_access_service.py
@@ -11,6 +11,8 @@ 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,
@@ -312,7 +314,7 @@ def get_effective_project_role(
context: AuthorizationContext,
project_id: str,
) -> str | None:
- if context.is_instance_owner:
+ if context.is_instance_owner or has_temporary_unrestricted_runtime_access(context):
return "owner"
if not is_active_project(conn, project_id):
return None
@@ -366,7 +368,10 @@ 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 else None
+ return "owner" if (
+ context.is_instance_owner
+ or has_temporary_unrestricted_runtime_access(context)
+ ) else None
return get_effective_project_role(conn, context, project_id)
diff --git a/storage/projects_service.py b/storage/projects_service.py
index 3411b6942..0d089ffe4 100644
--- a/storage/projects_service.py
+++ b/storage/projects_service.py
@@ -24,7 +24,11 @@ from sqlalchemy.engine import Connection
from storage.agent_session_rows import reserve_write_lock
from storage import project_access_service
from storage.models import agents, scope_settings, scopes
-from vibe.authorization import AuthorizationContext, require_instance_role
+from vibe.authorization import (
+ AuthorizationContext,
+ has_temporary_unrestricted_runtime_access,
+ require_instance_role,
+)
PROJECT_PLATFORM = "avibe"
@@ -210,9 +214,9 @@ def _project_for_context(
str(project.get("id") or ""),
)
}
- if context.is_remote:
- # A remote Instance owner is still not trusted to inspect the host's
- # absolute workdir or arbitrary local metadata.
+ 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
@@ -288,6 +292,27 @@ def get_project(
return _project_for_context(conn, context, _project_payload(conn, scope_id))
+def get_project_workdir(
+ conn: Connection,
+ project_id: str,
+ *,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
+) -> str:
+ """Return the authorized Project workdir for internal runtime execution.
+
+ Remote Project payloads deliberately redact host paths. Runtime services
+ such as Skills and the project instruction editor still need the real cwd
+ after authorization, so keep that internal lookup separate from the HTTP
+ response projection instead of weakening ``get_project`` redaction.
+ """
+
+ context = require_instance_role(authorization_context, "viewer")
+ if not project_access_service.can_read_project(conn, context, project_id):
+ raise LookupError(f"Project not found: {project_id}")
+ project = _project_payload(conn, _make_scope_id(project_id))
+ return str(project.get("folder_path") or "")
+
+
def create_project(
conn: Connection,
folder_path: str,
diff --git a/storage/resource_access_service.py b/storage/resource_access_service.py
index 9f6c7d98b..cebaaebd1 100644
--- a/storage/resource_access_service.py
+++ b/storage/resource_access_service.py
@@ -22,6 +22,8 @@ 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,
)
@@ -205,10 +207,14 @@ def resolve_resource_access_context(
def ensure_local_harness_definition_write(
user_context: ResourceUserContext | Mapping[str, Any] | None = None,
) -> ResourceUserContext:
- """Keep executable Harness definitions on the trusted-local side."""
+ """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.
+ """
context = resolve_resource_access_context(user_context)
- if context.is_remote:
+ if context.is_remote and not has_temporary_unrestricted_org_access(context):
raise ResourceAccessError(REMOTE_AUTONOMOUS_HARNESS_DISABLED_CODE)
return context
@@ -222,6 +228,29 @@ def metadata_has_remote_resource_context(metadata: Mapping[str, Any] | None) ->
)
+def metadata_allows_temporary_unrestricted_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.
+ """
+
+ if not metadata_has_remote_resource_context(metadata):
+ return True
+ try:
+ context = resource_user_context_from_metadata(metadata)
+ except ResourceAccessError:
+ return False
+ return bool(
+ context is not None
+ and has_temporary_unrestricted_runtime_access(context)
+ )
+
+
def metadata_with_resource_user_context(
metadata: Mapping[str, Any] | None,
user_context: ResourceUserContext | Mapping[str, Any] | None = None,
@@ -263,10 +292,11 @@ def resource_user_context_from_metadata(
*,
now: int | None = None,
) -> ResourceUserContext | None:
- """Restore remote provenance for non-executable compatibility callers.
+ """Restore unexpired remote provenance for deferred authorization checks.
- The returned object is not autonomous execution authority. Task and Watch
- executors reject metadata carrying this provenance before calling here.
+ The returned context retains the real signed Organization identity. Deferred
+ runtime executors still apply ``metadata_allows_temporary_unrestricted_runtime``
+ before doing work, so malformed, expired, and non-member snapshots fail closed.
"""
if not isinstance(metadata, Mapping):
@@ -288,6 +318,28 @@ def _as_context(user_context: ResourceUserContext | Mapping[str, Any] | None) ->
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:
@@ -549,6 +601,8 @@ def _policy_allows(
) -> bool:
if context.is_trusted_local:
return True
+ if _temporary_unrestricted_resource_bypass(context, resource_kind):
+ 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":
@@ -586,6 +640,11 @@ def _policy_allows(
def _policy_allows_management(context: ResourceUserContext, policy: Mapping[str, Any] | None) -> bool:
if context.is_trusted_local:
return True
+ if isinstance(policy, Mapping) and _temporary_unrestricted_resource_bypass(
+ context,
+ str(policy.get("resource_kind") or ""),
+ ):
+ return True
if not context.has_role("owner"):
return False
if policy is None:
@@ -613,6 +672,11 @@ def _policy_allows_owner_control(
if context.is_trusted_local:
return True
+ if isinstance(policy, Mapping) and _temporary_unrestricted_resource_bypass(
+ context,
+ str(policy.get("resource_kind") or ""),
+ ):
+ return True
if policy is None:
return context.is_instance_owner
if not context.can_use_resource(str(policy.get("resource_kind") or "")):
@@ -634,6 +698,11 @@ def _policy_allows_show_page_access_management(
) -> 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
if _policy_allows_owner_control(context, policy):
return True
if policy is None or policy.get("resource_kind") != "show_page":
@@ -709,7 +778,7 @@ 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")
- if context.is_trusted_local:
+ if context.is_trusted_local or _temporary_unrestricted_resource_bypass(context, kind):
return True
with _connection(connection) as conn:
policy = _policy_row(conn, kind, identifier)
@@ -726,6 +795,8 @@ 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)
@@ -743,6 +814,8 @@ 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 3eec3c361..152fa6b8d 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -46,6 +46,7 @@ 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__)
@@ -1537,7 +1538,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:
+ if context.is_trusted_local or has_temporary_unrestricted_runtime_access(context):
return
member_names = _request_member_names(row)
if not member_names:
@@ -1549,7 +1550,10 @@ def _require_request_secret_access(
if set(secret_rows) != set(member_names):
# Provision requests legitimately precede the secret. Only the paired
# instance owner may inspect or decide those owner-level requests.
- if context.is_instance_owner and row.get("request_type") == "provision":
+ if (
+ (context.is_instance_owner or has_temporary_unrestricted_runtime_access(context))
+ and row.get("request_type") == "provision"
+ ):
return
raise VaultSecretAccessError("Vault secret access is not permitted.")
require = _require_secret_resource_management if management else _require_secret_resource_access
@@ -1826,7 +1830,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:
+ if context.can_manage_instance or has_temporary_unrestricted_runtime_access(context):
return context
raise VaultSecretAccessError("Vault secret access is not permitted.")
@@ -1845,7 +1849,7 @@ def _require_secret_names_access(
management: bool = False,
) -> None:
context = resolve_resource_access_context(user_context)
- if context.is_trusted_local:
+ if context.is_trusted_local or has_temporary_unrestricted_runtime_access(context):
return
member_names = sorted({str(name) for name in names if str(name)})
if not member_names:
@@ -3827,13 +3831,17 @@ 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.
- requires_post_filter = session is not None or not context.is_trusted_local
+ has_full_runtime_access = (
+ context.is_trusted_local
+ or has_temporary_unrestricted_runtime_access(context)
+ )
+ requires_post_filter = session is not None or not has_full_runtime_access
if not requires_post_filter:
query = query.limit(limit)
rows = [dict(row) for row in conn.execute(query).mappings()]
if session is not None:
rows = [row for row in rows if _request_session_id(row) == session]
- if not context.is_trusted_local:
+ if not has_full_runtime_access:
accessible_rows: list[dict[str, Any]] = []
for row in rows:
try:
@@ -4423,7 +4431,10 @@ 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:
+ if not (
+ context.is_trusted_local
+ or has_temporary_unrestricted_runtime_access(context)
+ ):
accessible_rows: list[dict[str, Any]] = []
for row in rows:
try:
@@ -4966,7 +4977,10 @@ def _audit_secret_name_allowed(
)
)
if not has_tombstone:
- allowed = bool(context.is_instance_owner)
+ allowed = bool(
+ context.is_instance_owner
+ or has_temporary_unrestricted_runtime_access(context)
+ )
access_by_name[name] = allowed
return allowed
@@ -4982,7 +4996,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:
+ if context.is_trusted_local or has_temporary_unrestricted_runtime_access(context):
return
snapshot_present, snapshot = _audit_access_snapshot(row)
@@ -4998,7 +5012,10 @@ def _require_audit_row_access(
grant_members=grant_members if grant_members is not None else {},
)
if not names:
- if context.is_instance_owner:
+ if (
+ context.is_instance_owner
+ or has_temporary_unrestricted_runtime_access(context)
+ ):
return
raise VaultSecretAccessError("Vault secret access is not permitted.")
name_access = access_by_name if access_by_name is not None else {}
@@ -5025,7 +5042,7 @@ def list_audit(
requested_limit = max(0, limit)
if requested_limit == 0:
return []
- if context.is_trusted_local:
+ if context.is_trusted_local or has_temporary_unrestricted_runtime_access(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 3d5427d1a..d00ff7888 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -25,7 +25,11 @@ from sqlalchemy.engine import Connection
from config import paths
from storage import project_access_service
-from vibe.authorization import AuthorizationContext, require_instance_role
+from vibe.authorization import (
+ AuthorizationContext,
+ has_temporary_unrestricted_runtime_access,
+ require_instance_role,
+)
from storage.agent_session_rows import (
ASSIGNABLE_SESSION_VISIBILITIES,
WORKSPACE_NOTICE_SESSION_ID,
@@ -141,6 +145,18 @@ def _dumps_metadata(metadata: dict[str, Any]) -> str:
return json.dumps(metadata)
+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)
+
+
+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)
+
+
def list_sessions(
conn: Connection,
*,
@@ -170,7 +186,7 @@ def list_sessions(
context = require_instance_role(authorization_context, "viewer")
query = select(agent_sessions).where(agent_sessions.c.visibility == "foreground")
- if not context.is_instance_owner:
+ if not _has_runtime_owner_access(context):
accessible_scope_ids = {
project_access_service.project_scope_id(project_id)
for project_id in project_access_service.accessible_project_ids(conn, context)
@@ -242,7 +258,7 @@ def list_sessions(
query = query.order_by(*order_columns).limit(effective_limit)
rows = [dict(row) for row in conn.execute(query).mappings().all()]
sessions = [
- _row_to_payload(row, include_local_details=context.is_trusted_local)
+ _row_to_payload(row, include_local_details=_include_local_details(context))
for row in rows
]
# Use the clamped page size for the cursor check — comparing against
@@ -264,7 +280,7 @@ def get_session(
).mappings().first()
if row is None:
raise LookupError(f"Session not found: {session_id}")
- if not context.is_instance_owner:
+ if not _has_runtime_owner_access(context):
project_id = project_access_service.project_id_from_scope_id(row["scope_id"])
if project_id is None or not project_access_service.can_read_project(
conn, context, project_id
@@ -272,7 +288,7 @@ def get_session(
raise LookupError(f"Session not found: {session_id}")
return _row_to_payload(
dict(row),
- include_local_details=context.is_trusted_local,
+ include_local_details=_include_local_details(context),
)
@@ -358,7 +374,7 @@ def create_session(
"""
authorization = require_instance_role(authorization_context, "editor")
- if not authorization.is_instance_owner:
+ if not _has_runtime_owner_access(authorization):
project_id = project_access_service.project_id_from_scope_id(scope_id)
if project_id is None or not project_access_service.can_chat_project(
conn, authorization, project_id
@@ -423,7 +439,12 @@ def create_session(
)
resource_context = resolve_resource_access_context(user_context)
- if resource_context.is_remote and not agent_name and not agent_id:
+ 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:
from core.vibe_agents import VibeAgentAccessError
@@ -605,7 +626,7 @@ def update_session(
# reads). Same split as ``sessions_service.bind_agent_session_by_id``.
if existing.status == "archived":
raise SessionArchivedError(session_id)
- if not authorization.is_instance_owner:
+ if not _has_runtime_owner_access(authorization):
project_id = project_access_service.project_id_from_scope_id(existing.scope_id)
if project_id is None or not project_access_service.can_chat_project(
conn, authorization, project_id
@@ -636,7 +657,11 @@ 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:
+ 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,
@@ -664,6 +689,7 @@ def update_session(
if (
resource_context.is_remote
+ and not has_temporary_unrestricted_runtime_access(resource_context)
and agent_backend is not _UNSET
and bool(str(agent_backend or "").strip())
and selected_agent is None
@@ -1303,7 +1329,7 @@ def archive_session(
).scalar_one_or_none()
if existing is None:
raise LookupError(f"Session not found: {session_id}")
- if not context.is_instance_owner:
+ if not _has_runtime_owner_access(context):
if not project_access_service.role_allows(
project_access_service.get_effective_session_role(conn, context, session_id),
"editor",
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index 2530f43e8..9fc548dd2 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -6,25 +6,39 @@ from vibe.authorization import (
REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER,
REMOTE_HTTP_ALLOWED,
REMOTE_HTTP_LOCAL_ONLY,
- REMOTE_HTTP_PAYLOAD_FILTERED,
can_receive_workbench_event,
context_from_session_payload,
has_temporary_unrestricted_org_app_access,
http_authorization_policy,
require_instance_role,
- required_instance_role,
trusted_local_context,
)
def _remote_context(role: str) -> AuthorizationContext:
- return AuthorizationContext(instance_role=role, is_remote=True)
+ 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,
+ )
def test_remote_roles_allow_chat_without_enabling_local_machine_capabilities() -> None:
- viewer = AuthorizationContext(instance_role="viewer", is_remote=True)
- editor = AuthorizationContext(instance_role="editor", is_remote=True)
- owner = AuthorizationContext(instance_role="owner", is_remote=True)
+ viewer = _remote_context("viewer")
+ editor = _remote_context("editor")
+ owner = _remote_context("owner")
assert viewer.can_read_instance is True
assert viewer.can_chat is False
@@ -143,6 +157,9 @@ def test_context_uses_role_not_diagnostic_source_for_owner() -> None:
"vibe_instance_id": "inst-1",
"vibe_instance_role": "editor",
"vibe_instance_access_source": "owner",
+ "vibe_organization_id": "org-1",
+ "vibe_organization_member_id": "membership-1",
+ "vibe_organization_role": "member",
"vibe_instance_authorization_revision": 0,
}
)
@@ -190,6 +207,9 @@ def test_show_page_email_context_requires_and_matches_one_exact_target() -> None
"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
@@ -209,411 +229,137 @@ def test_show_page_email_context_requires_and_matches_one_exact_target() -> None
assert elevated_role.can_use_show_page("session-one") is False
-def test_http_policy_defaults_unknown_api_to_owner() -> None:
- assert required_instance_role("GET", "/api/projects") == "viewer"
- assert required_instance_role("GET", "/api/projects/proj-1") == "viewer"
- assert required_instance_role("GET", "/api/projects/proj-1/agents-md") == "owner"
- assert required_instance_role("GET", "/api/agents") == "editor"
- assert required_instance_role("GET", "/api/skills") == "editor"
- assert required_instance_role("GET", "/api/vault/secrets") == "editor"
- assert required_instance_role("GET", "/api/vault/tags") == "editor"
- assert required_instance_role("POST", "/api/vault/requests/access") == "editor"
- assert required_instance_role("POST", "/api/vault/requests/sign") == "editor"
- assert required_instance_role("POST", "/api/vault/secrets") == "owner"
- assert required_instance_role("POST", "/api/skills") == "owner"
- assert required_instance_role("GET", "/api/show-pages") == "viewer"
- assert required_instance_role("POST", "/api/show-pages/ses-1/visibility") == "viewer"
- assert required_instance_role("POST", "/api/show-pages/ses-1/rotate-share") == "viewer"
- assert required_instance_role("POST", "/api/show-pages/ses-1/share-id") == "viewer"
- assert required_instance_role("POST", "/api/show-pages/ses-1/ensure") == "viewer"
- assert required_instance_role("GET", "/api/config") == "viewer"
- assert required_instance_role("GET", "/api/workbench/prefs") == "viewer"
- assert required_instance_role("PUT", "/api/workbench/prefs") == "owner"
- assert required_instance_role("GET", "/api/org/context") == "viewer"
- assert required_instance_role("GET", "/api/org/groups") == "viewer"
- assert required_instance_role("GET", "/api/resource-policies") == "viewer"
- assert required_instance_role("PUT", "/api/resource-policies/agent/agent-1") == "owner"
- assert required_instance_role("GET", "/api/sessions/ses-1/draft") == "editor"
- assert required_instance_role("POST", "/api/sessions/ses-1/messages") == "editor"
- assert required_instance_role("POST", "/api/sessions/ses-1/fork") == "editor"
- assert required_instance_role("POST", "/api/projects") == "owner"
- assert required_instance_role("GET", "/api/new-management-surface") == "owner"
- assert required_instance_role("GET", "/api/dock") == "viewer"
- assert required_instance_role("GET", "/status") is None
- assert required_instance_role("GET", "/show/ses-1/") == "viewer"
- assert required_instance_role("POST", "/show/ses-1/api/action") == "viewer"
- assert required_instance_role("GET", "/assets/app.js") is None
-
-
- ("method", "path"),
- [
- ("GET", "/api/backend/codex/runtime"),
- ("GET", "/api/backend/claude/auth"),
- ("GET", "/api/backend/codex/auth"),
- ("GET", "/api/opencode/permission-status"),
- ("GET", "/api/harness/tasks"),
- ("GET", "/api/harness/watches"),
- ("GET", "/api/global-prompts"),
- ("GET", "/api/harness/runs"),
- ("GET", "/api/harness/runs/run-1"),
+def test_http_policy_keeps_unknown_routes_fail_closed_and_runtime_matrix_explicit() -> None:
+ runtime_routes = (
("GET", "/api/harness/bootstrap"),
- ("GET", "/api/vault/pubkey"),
- ("GET", "/api/vault/agent/pubkey"),
- ("GET", "/api/vault/sandbox/root-metadata"),
- ("GET", "/api/vault/vmk"),
- ("GET", "/api/doctor"),
- ("POST", "/api/doctor"),
- ("POST", "/api/logs"),
- ("POST", "/api/ui/reload"),
- ("POST", "/api/opencode/options"),
- ("POST", "/api/opencode/setup-permission"),
- ("POST", "/api/vault/secrets"),
+ ("PATCH", "/api/harness/tasks/task-1"),
+ ("POST", "/api/agents"),
+ ("POST", "/api/skills"),
("PATCH", "/api/vault/secrets/secret-1"),
- ("DELETE", "/api/vault/grants/grant-1"),
- ("POST", "/api/vault/grants"),
- ("POST", "/api/vault/sign"),
- ("POST", "/api/skills/preview"),
- ("POST", "/api/users"),
- ("POST", "/api/users/user-1/admin"),
- ("DELETE", "/api/users/user-1"),
- ("POST", "/api/bind-codes"),
- ("DELETE", "/api/bind-codes/code-1"),
- ("GET", "/api/vault/future-capability"),
- ("GET", "/api/dock/future-capability"),
- ("GET", "/api/web-push/future-capability"),
- ("GET", "/api/models/future-capability"),
- ("GET", "/api/harness/future-capability"),
- ("GET", "/api/users/future-capability"),
- ("GET", "/api/bind-codes/future-capability"),
- ("GET", "/api/future-owner-capability"),
- ("POST", "/api/future-owner-capability"),
- ("GET", "/api/memory/future-capability"),
- ("POST", "/api/memory/future-capability"),
- ],
-)
-def test_remote_http_policy_defaults_local_machine_and_unknown_routes_to_local_only(
- method,
- path,
-) -> None:
- policy = http_authorization_policy(method, path)
-
- assert policy.minimum_role == "owner"
- assert policy.remote_access == REMOTE_HTTP_LOCAL_ONLY
-
-
- ("method", "path", "expected"),
- [
- ("GET", "/api/projects", REMOTE_HTTP_ALLOWED),
- ("POST", "/api/sessions/ses-1/messages", REMOTE_HTTP_ALLOWED),
- ("GET", "/api/workbench/prefs", REMOTE_HTTP_ALLOWED),
- ("PUT", "/api/workbench/prefs", REMOTE_HTTP_LOCAL_ONLY),
- ("PUT", "/api/resource-policies/agent/agent-1", REMOTE_HTTP_ALLOWED),
- ("GET", "/api/models/runtime/status", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/models/agents/codex/chain", REMOTE_HTTP_ALLOWED),
- ("GET", "/api/models/turns/turn-1/provenance", REMOTE_HTTP_ALLOWED),
- # Only the local owner can start an OAuth flow, and a status poll hands
- # back that flow's authorization URL and device code - plus, once a Model
- # Hub flow succeeds, the credential and account payload `/api/models/
- # sources` keeps local. Polling follows its flow and stays local too.
- ("GET", "/api/models/oauth/status/oaf_test0001", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/backend/codex/auth/oauth/status/flow-1", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/backend/codex/runtime", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/opencode/permission-status", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/vault/audit", REMOTE_HTTP_ALLOWED),
- ("GET", "/api/dock", REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER),
- ("POST", "/api/dock/pins", REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER),
- ("PUT", "/api/dock/order", REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER),
- # A push endpoint is caller-supplied and `send_web_push()` fetches it
- # from this host, so registering or testing one from across the tunnel
- # would let a remote caller aim an outbound request at loopback, a
- # private LAN host or a rebinding name. Status reads stay remote: they
- # report the caller's own subscription and reach no endpoint.
- ("GET", "/api/web-push/status", REMOTE_HTTP_ALLOWED),
- ("POST", "/api/web-push/status", REMOTE_HTTP_ALLOWED),
- ("GET", "/api/web-push/vapid-public-key", REMOTE_HTTP_ALLOWED),
- ("POST", "/api/web-push/subscriptions", REMOTE_HTTP_LOCAL_ONLY),
- ("DELETE", "/api/web-push/subscriptions", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/web-push/test", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/harness/runs/run-1", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/users", REMOTE_HTTP_LOCAL_ONLY),
- ("HEAD", "/api/users", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/skills/check", REMOTE_HTTP_LOCAL_ONLY),
- ("HEAD", "/api/skills/find", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/vault/requests/access", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/vault/requests/sign", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/show-pages/ses-1/visibility", REMOTE_HTTP_ALLOWED),
- ("POST", "/api/show-pages/ses-1/rotate-share", REMOTE_HTTP_ALLOWED),
- ("POST", "/api/show-pages/ses-1/share-id", REMOTE_HTTP_ALLOWED),
- ("GET", "/api/sessions/ses-1/draft", REMOTE_HTTP_LOCAL_ONLY),
- ("PUT", "/api/sessions/ses-1/draft", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/sessions/ses-1/mark-read", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/status", REMOTE_HTTP_LOCAL_ONLY),
- ("HEAD", "/status", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/show-pages/ses-1/ensure", REMOTE_HTTP_ALLOWED),
- ("GET", "/api/memory/settings", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/memory/failures", REMOTE_HTTP_LOCAL_ONLY),
- ("HEAD", "/api/memory/log/entry", REMOTE_HTTP_LOCAL_ONLY),
- ("PATCH", "/api/memory/settings", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/memory/search", REMOTE_HTTP_ALLOWED),
- ("POST", "/api/memory/runtime/restart", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/memory/clear", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/projects/proj-1/agents-md", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/show/ses-1/", REMOTE_HTTP_ALLOWED),
- ("POST", "/show/ses-1/__show/events", REMOTE_HTTP_ALLOWED),
- ("POST", "/api/config", REMOTE_HTTP_PAYLOAD_FILTERED),
- ("PATCH", "/api/projects/proj-1", REMOTE_HTTP_PAYLOAD_FILTERED),
- ("PATCH", "/api/sessions/ses-1", REMOTE_HTTP_PAYLOAD_FILTERED),
- ("GET", "/api/settings", REMOTE_HTTP_LOCAL_ONLY),
- ("HEAD", "/api/settings", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/settings", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/settings/thread", REMOTE_HTTP_LOCAL_ONLY),
- ("DELETE", "/api/settings/thread", REMOTE_HTTP_LOCAL_ONLY),
- ("GET", "/api/bind-codes", REMOTE_HTTP_LOCAL_ONLY),
- ("DELETE", "/api/projects/proj-1", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/api/sessions/ses-1/fork", REMOTE_HTTP_LOCAL_ONLY),
- ("POST", "/show/ses-1/api/action", REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER),
- ],
-)
-def test_remote_http_policy_keeps_approved_management_and_read_surfaces(
- method,
- path,
- expected,
-) -> None:
- assert http_authorization_policy(method, path).remote_access == expected
-
-
- ("method", "path"),
- [
- ("POST", "/api/dock/pins"),
- ("GET", "/api/dock"),
- ("DELETE", "/api/dock/pins/ses-1"),
- ("PUT", "/api/dock/order"),
- ("GET", "/api/files/list"),
- ("HEAD", "/api/files/meta"),
- ("GET", "/api/files/content"),
- ("GET", "/api/files/search"),
- ("GET", "/api/files/search_names"),
+ ("PATCH", "/api/memory/settings"),
+ ("POST", "/api/control"),
+ ("POST", "/api/config"),
+ ("GET", "/api/models/sources"),
+ ("POST", "/api/models/runtime/start"),
+ ("POST", "/api/backend/codex/restart"),
+ ("POST", "/api/backend/claude/auth/oauth/start"),
+ ("GET", "/api/dependencies"),
+ ("POST", "/api/dependencies/avault/install"),
+ ("PUT", "/api/projects/proj-1/agents-md"),
("POST", "/api/files/upload"),
- ("POST", "/api/files/mkdir"),
- ("POST", "/api/files/rename"),
- ("POST", "/api/files/move"),
- ("POST", "/api/files/copy"),
- ("POST", "/api/files/delete"),
- ("POST", "/api/files/delete/undo"),
- ("POST", "/api/files/search/replace"),
- ("POST", "/api/files/search/undo"),
- ("PUT", "/api/files/write"),
- ("GET", "/api/browse/favorites"),
("DELETE", "/api/terminal/term-1"),
("POST", "/api/show-pages/ses-1/icon"),
("POST", "/show/ses-1/api/action"),
- ("PUT", "/show/ses-1/api/settings"),
- ("DELETE", "/show/ses-1/api/item"),
- ],
-)
-def test_temporary_org_app_policy_covers_only_the_explicit_app_endpoints(
- method: str,
- path: str,
-) -> None:
- policy = http_authorization_policy(method, path)
-
- assert policy.minimum_role == "viewer"
- assert policy.remote_access == REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER
-
+ ("GET", "/api/users"),
+ ("POST", "/api/users/user-1/admin"),
+ ("DELETE", "/api/users/user-1"),
+ ("GET", "/api/bind-codes"),
+ ("POST", "/api/bind-codes"),
+ ("DELETE", "/api/bind-codes/code-1"),
+ ("GET", "/api/setup/first-bind-code"),
+ ("GET", "/status"),
+ )
+ for method, path in runtime_routes:
+ policy = http_authorization_policy(method, path)
+ assert policy.remote_access == REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER, (method, path)
- ("method", "path"),
- [
- ("POST", "/api/files/list"),
- ("GET", "/api/files/future-operation"),
- ("POST", "/api/browse"),
- ("POST", "/api/browse/mkdir"),
- ("GET", "/api/terminal/term-1"),
- ("POST", "/api/dock/order"),
- ("POST", "/api/show-pages/ses-1/icon/extra"),
- ("POST", "/api/config"),
- ("POST", "/api/control"),
- ("POST", "/api/vault/secrets"),
- ("GET", "/api/future-local-app-like-route"),
- ],
-)
-def test_temporary_org_app_policy_does_not_open_adjacent_or_sensitive_endpoints(
- method: str,
- path: str,
-) -> None:
- assert (
- http_authorization_policy(method, path).remote_access
- != REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER
+ for method, path in (
+ ("GET", "/api/future-owner-capability"),
+ ("POST", "/api/harness/future-capability"),
+ ("GET", "/api/opencode/future-capability"),
+ ("GET", "/api/backend/future/runtime"),
+ ("GET", "/api/users/user-1"),
+ ("POST", "/api/bind-codes/code-1"),
+ ):
+ policy = http_authorization_policy(method, path)
+ assert policy.minimum_role == "owner"
+ assert policy.remote_access == REMOTE_HTTP_LOCAL_ONLY
+
+ for method, path in (
+ ("POST", "/api/remote-access/vibe-cloud/pair"),
+ ("POST", "/api/remote-access/start"),
+ ("POST", "/api/remote-access/stop"),
+ ("POST", "/api/remote-access/optimize-route"),
+ ("POST", "/api/remote-access/settings"),
+ ("POST", "/api/remote-access/diagnostics"),
+ ("GET", "/api/remote-access/network-interfaces"),
+ ):
+ assert http_authorization_policy(method, path).remote_access == REMOTE_HTTP_LOCAL_ONLY
+
+
+def test_http_policy_preserves_safe_remote_reads_and_show_routes() -> None:
+ assert http_authorization_policy("GET", "/api/projects").remote_access == REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER
+ 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_temporary_runtime_admission_requires_active_organization_membership() -> 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,
+ )
+ non_member = AuthorizationContext(
+ instance_role="owner",
+ subject="owner-1",
+ instance_access_source="owner",
+ is_remote=True,
)
+ assert require_instance_role(member, "owner") is member
+ with pytest.raises(InstanceAuthorizationError):
+ require_instance_role(non_member, "owner")
- ("gate", "method", "path", "expected"),
- [
- # canManageSkills: read-only catalog remotely, every mutation local.
- ("canManageSkills", "GET", "/api/skills", REMOTE_HTTP_ALLOWED),
- ("canManageSkills", "POST", "/api/skills", REMOTE_HTTP_LOCAL_ONLY),
- ("canManageSkills", "POST", "/api/skills/askill/update", REMOTE_HTTP_LOCAL_ONLY),
- ("canManageSkills", "DELETE", "/api/skills/askill", REMOTE_HTTP_LOCAL_ONLY),
- (
- "canManageSkills",
- "POST",
- "/api/dependencies/askill/install",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- # canManageVaultSecrets: inventory and audit reads stay remote, mutations
- # and key material do not.
- ("canManageVaultSecrets", "GET", "/api/vault/secrets", REMOTE_HTTP_ALLOWED),
- ("canManageVaultSecrets", "GET", "/api/vault/settings", REMOTE_HTTP_ALLOWED),
- ("canManageVaultSecrets", "GET", "/api/vault/grants", REMOTE_HTTP_ALLOWED),
- ("canManageVaultSecrets", "POST", "/api/vault/secrets", REMOTE_HTTP_LOCAL_ONLY),
- (
- "canManageVaultSecrets",
- "PATCH",
- "/api/vault/secrets/prod",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- (
- "canManageVaultSecrets",
- "DELETE",
- "/api/vault/secrets/prod",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- ("canManageVaultSecrets", "POST", "/api/vault/vmk", REMOTE_HTTP_LOCAL_ONLY),
- # canUseHarness: the page cannot even bootstrap remotely.
- ("canUseHarness", "GET", "/api/harness/bootstrap", REMOTE_HTTP_LOCAL_ONLY),
- # canArchiveProjects: list and rename stay remote, archive does not.
- ("canArchiveProjects", "GET", "/api/projects", REMOTE_HTTP_ALLOWED),
- (
- "canArchiveProjects",
- "PATCH",
- "/api/projects/proj-1",
- REMOTE_HTTP_PAYLOAD_FILTERED,
- ),
- ("canArchiveProjects", "DELETE", "/api/projects/proj-1", REMOTE_HTTP_LOCAL_ONLY),
- # canEditProjectInstructions: local in both directions, because an
- # AGENTS.md / CLAUDE.md symlink can resolve outside the Project.
- (
- "canEditProjectInstructions",
- "GET",
- "/api/projects/proj-1/agents-md",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- (
- "canEditProjectInstructions",
- "PUT",
- "/api/projects/proj-1/agents-md",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- # canEditAgentDefinitions: catalog reads remotely, definition writes locally.
- ("canEditAgentDefinitions", "GET", "/api/agents", REMOTE_HTTP_ALLOWED),
- ("canEditAgentDefinitions", "POST", "/api/agents", REMOTE_HTTP_LOCAL_ONLY),
- # canAdministerMemory: principal-scoped reads and search stay remote,
- # the cross-principal admin log and the sidecar administration do not.
- ("canAdministerMemory", "GET", "/api/memory/status", REMOTE_HTTP_ALLOWED),
- ("canAdministerMemory", "GET", "/api/memory/profile", REMOTE_HTTP_ALLOWED),
- ("canAdministerMemory", "POST", "/api/memory/search", REMOTE_HTTP_ALLOWED),
- ("canAdministerMemory", "GET", "/api/memory/log", REMOTE_HTTP_LOCAL_ONLY),
- ("canAdministerMemory", "GET", "/api/memory/log/entry", REMOTE_HTTP_LOCAL_ONLY),
- ("canAdministerMemory", "PATCH", "/api/memory/settings", REMOTE_HTTP_LOCAL_ONLY),
- (
- "canAdministerMemory",
- "POST",
- "/api/memory/runtime/restart",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- ("canAdministerMemory", "POST", "/api/memory/clear", REMOTE_HTTP_LOCAL_ONLY),
- # Dock is temporarily writable by active Organization members while
- # Workbench preferences remain a trusted-local control.
- (
- "dockAndWorkbenchPrefs",
- "GET",
- "/api/dock",
- REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER,
- ),
- ("dockAndWorkbenchPrefs", "GET", "/api/workbench/prefs", REMOTE_HTTP_ALLOWED),
- (
- "dockAndWorkbenchPrefs",
- "POST",
- "/api/dock/pins",
- REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER,
- ),
- (
- "dockAndWorkbenchPrefs",
- "DELETE",
- "/api/dock/pins/ses-1",
- REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER,
- ),
- (
- "dockAndWorkbenchPrefs",
- "PUT",
- "/api/dock/order",
- REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER,
- ),
- ("dockAndWorkbenchPrefs", "PUT", "/api/workbench/prefs", REMOTE_HTTP_LOCAL_ONLY),
- # canRegisterWebPush: status reads stay remote, but registering or
- # testing an endpoint this host will call does not.
- ("canRegisterWebPush", "GET", "/api/web-push/status", REMOTE_HTTP_ALLOWED),
- ("canRegisterWebPush", "POST", "/api/web-push/status", REMOTE_HTTP_ALLOWED),
- (
- "canRegisterWebPush",
- "POST",
- "/api/web-push/subscriptions",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- (
- "canRegisterWebPush",
- "DELETE",
- "/api/web-push/subscriptions",
- REMOTE_HTTP_LOCAL_ONLY,
- ),
- ("canRegisterWebPush", "POST", "/api/web-push/test", REMOTE_HTTP_LOCAL_ONLY),
- ],
-)
-def test_local_only_workbench_gates_match_the_remote_http_policy(
- gate,
- method,
- path,
- expected,
-) -> None:
- """Pin the endpoint classifications the Workbench UI gates are derived from.
-
- `can_manage_instance` / `can_manage_agents` / `can_manage_projects` stay true
- for a remote Instance owner, so `ui/src/lib/remoteAuth.ts` adds a locality
- check for every control whose endpoint is local-only. If one of these routes
- is reclassified, that UI gate is stale and must be revisited with it.
- """
- assert http_authorization_policy(method, path).remote_access == expected, gate
+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,
+ )
+ 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 = _remote_context("viewer")
editor = _remote_context("editor")
owner = _remote_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 False
+ 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(editor, "vaults.updated") is False
+ 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 False
- assert can_receive_workbench_event(editor, "runs.updated") is False
- assert can_receive_workbench_event(owner, "runs.updated") is False
+ 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 True
+ 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 = AuthorizationContext(instance_role="viewer", is_remote=True)
+ viewer = _non_member_context("viewer")
try:
require_instance_role(viewer, "editor")
except InstanceAuthorizationError as error:
@@ -625,7 +371,7 @@ def test_service_role_guard_defaults_local_and_denies_remote_viewer() -> None:
def test_session_service_mutations_recheck_instance_role() -> None:
from storage import workbench_sessions_service
- viewer = _remote_context("viewer")
+ viewer = _non_member_context("viewer")
with pytest.raises(InstanceAuthorizationError):
workbench_sessions_service.create_session(
None,
@@ -650,7 +396,7 @@ def test_session_service_mutations_recheck_instance_role() -> None:
def test_project_service_mutations_require_owner() -> None:
from storage import projects_service
- editor = _remote_context("editor")
+ editor = _non_member_context("editor")
with pytest.raises(InstanceAuthorizationError):
projects_service.create_project(
None,
@@ -677,5 +423,5 @@ def test_session_fork_service_requires_editor() -> None:
with pytest.raises(InstanceAuthorizationError):
reserve_forked_session(
source_session_id="ses-1",
- authorization_context=_remote_context("viewer"),
+ authorization_context=_non_member_context("viewer"),
)
diff --git a/tests/test_resource_access_service.py b/tests/test_resource_access_service.py
index 2088db10c..666a36c6e 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_policy_evaluation_private_public_scope_and_missing_group_context(tmp_path) -> None:
+def test_active_org_members_bypass_resource_acl_without_changing_unknown_kind_fail_closed(tmp_path) -> None:
db = tmp_path / "vibe.sqlite"
run_migrations(db)
engine = create_sqlite_engine(db)
@@ -70,25 +70,23 @@ def test_policy_evaluation_private_public_scope_and_missing_group_context(tmp_pa
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"}))
- assert resource_access_service.can_use_resource(owner, "agent", "private-agent", connection=connection)
- assert not resource_access_service.can_use_resource(
- engineering_member, "agent", "private-agent", connection=connection
- )
-
- assert resource_access_service.can_use_resource(
- engineering_member, "agent", "public-agent", connection=connection
- )
- assert not resource_access_service.can_use_resource(outside_org, "agent", "public-agent", connection=connection)
-
+ 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(
- 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
+ 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
+ )
finally:
engine.dispose()
@@ -124,7 +122,7 @@ def test_resource_policy_narrowing_matrix(
)
-def test_no_policy_is_local_private_but_instance_owner_keeps_legacy_access(tmp_path) -> None:
+def test_active_org_members_can_use_legacy_resources_without_forging_local_identity(tmp_path) -> None:
db = tmp_path / "vibe.sqlite"
run_migrations(db)
engine = create_sqlite_engine(db)
@@ -133,22 +131,29 @@ def test_no_policy_is_local_private_but_instance_owner_keeps_legacy_access(tmp_p
member = _context("member-1", group_ids=frozenset({"group-engineering"}))
owner = _context("owner-1", instance_role="owner", access_source="owner")
diagnostic_owner = _context("member-2", instance_role="viewer", access_source="owner")
+ non_member_owner = _context(
+ "legacy-owner",
+ organization_id=None,
+ role=None,
+ instance_role="owner",
+ access_source="owner",
+ )
local = resource_access_service.ResourceUserContext(is_trusted_local=True)
- assert not resource_access_service.can_use_resource(member, "agent", "legacy-agent", connection=connection)
+ assert 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(
+ diagnostic_owner, "agent", "legacy-agent", connection=connection
+ )
assert not resource_access_service.can_use_resource(
- diagnostic_owner,
- "agent",
- "legacy-agent",
- connection=connection,
+ non_member_owner, "agent", "legacy-agent", connection=connection
)
assert resource_access_service.can_use_resource(local, "agent", "legacy-agent", connection=connection)
finally:
engine.dispose()
-def test_removed_org_owner_loses_org_private_resources_but_keeps_personal_resources(tmp_path) -> None:
+def test_inactive_remote_identity_cannot_use_resources_even_with_owner_claim(tmp_path) -> None:
db = tmp_path / "vibe.sqlite"
run_migrations(db)
engine = create_sqlite_engine(db)
@@ -183,17 +188,11 @@ def test_removed_org_owner_loses_org_private_resources_but_keeps_personal_resour
"private-agent",
connection=connection,
)
- assert resource_access_service.can_use_resource(
- removed_owner,
- "agent",
- "personal-agent",
- connection=connection,
+ assert not resource_access_service.can_use_resource(
+ removed_owner, "agent", "personal-agent", connection=connection
)
- assert resource_access_service.can_manage_resource_acl(
- removed_owner,
- "agent",
- "personal-agent",
- connection=connection,
+ assert not resource_access_service.can_manage_resource_acl(
+ removed_owner, "agent", "personal-agent", connection=connection
)
finally:
engine.dispose()
diff --git a/tests/test_resource_acl_agents.py b/tests/test_resource_acl_agents.py
index b6971bab5..676648b4a 100644
--- a/tests/test_resource_acl_agents.py
+++ b/tests/test_resource_acl_agents.py
@@ -100,7 +100,7 @@ def _seed_agents_with_policies() -> tuple[VibeAgentStore, dict[str, VibeAgent]]:
return store, agents
-def test_agent_catalog_filters_private_public_scope_and_missing_group_context(monkeypatch, tmp_path) -> None:
+def test_active_org_agent_catalog_includes_every_builtin_and_acl_shape(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store, _agents = _seed_agents_with_policies()
try:
@@ -114,8 +114,8 @@ def test_agent_catalog_filters_private_public_scope_and_missing_group_context(mo
store.close()
assert owner_names == {"private-agent", "public-agent", "scope-agent"}
- assert member_names == {"public-agent", "scope-agent"}
- assert no_group_names == {"public-agent"}
+ assert member_names == {"private-agent", "public-agent", "scope-agent"}
+ assert no_group_names == {"private-agent", "public-agent", "scope-agent"}
def test_agent_removal_deletes_resource_policy_and_groups(monkeypatch, tmp_path) -> None:
@@ -155,7 +155,7 @@ def test_agent_removal_deletes_resource_policy_and_groups(monkeypatch, tmp_path)
assert groups == []
-def test_remote_agent_creation_is_blocked_by_conservative_execution_gate(monkeypatch, tmp_path) -> None:
+def test_active_org_agent_creation_is_allowed_without_trusted_local_identity(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
client = app.test_client()
@@ -178,34 +178,31 @@ def test_remote_agent_creation_is_blocked_by_conservative_execution_gate(monkeyp
environ_base=_remote_peer(),
)
- assert response.status_code == 403
- assert response.get_json()["code"] == "remote_execution_disabled"
+ assert response.status_code in {200, 201}
store = VibeAgentStore()
try:
- assert store.get("remote-private") is None
+ assert store.get("remote-private") is not None
finally:
store.close()
-def test_agent_management_is_enforced_inside_the_store(monkeypatch, tmp_path) -> None:
+def test_active_org_agent_management_is_allowed_inside_the_store(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store, agents = _seed_agents_with_policies()
editor = _organization_context("member-1")
owner = _organization_context("owner-1", instance_role="owner")
try:
- with pytest.raises(VibeAgentAccessError):
- store.update(agents["public"].name, description="denied", user_context=editor)
- with pytest.raises(VibeAgentAccessError):
- store.remove(agents["public"].name, user_context=editor)
- with pytest.raises(VibeAgentAccessError):
- store.set_default_agent_name(agents["public"].name, user_context=editor)
-
- updated = store.update(
+ updated = store.update(agents["public"].name, description="member update", user_context=editor)
+ assert updated.description == "member update"
+ store.set_default_agent_name(agents["private"].name, user_context=editor)
+ assert store.get_default_agent_name() == agents["private"].name
+ assert store.remove(agents["public"].name, user_context=editor) is True
+ owner_updated = store.update(
agents["private"].name,
description="owner update",
user_context=owner,
)
- assert updated.description == "owner update"
+ assert owner_updated.description == "owner update"
finally:
store.close()
@@ -258,7 +255,7 @@ def test_remote_partial_agent_updates_persist_canonical_selector_pair(monkeypatc
)
-def test_remote_agent_detail_uses_safe_projection(monkeypatch, tmp_path) -> None:
+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)
store = VibeAgentStore()
@@ -299,19 +296,18 @@ def test_remote_agent_detail_uses_safe_projection(monkeypatch, tmp_path) -> None
assert remote_response.status_code == 200
remote_agent = remote_response.get_json()["agent"]
assert remote_agent["system_prompt"] == "Safe remote prompt"
- assert remote_agent["metadata"] == {}
- assert "source_ref" not in remote_agent
- assert "normalized_name" not in remote_agent
+ assert remote_agent["metadata"]["secret"] == "local-only"
+ assert remote_agent["source_ref"] == "/Users/alex/private/AGENT.md"
+ assert remote_agent["normalized_name"] == "imported-agent"
assert local_response.get_json()["agent"]["source_ref"] == "/Users/alex/private/AGENT.md"
assert local_response.get_json()["agent"]["metadata"]["secret"] == "local-only"
-def test_remote_agent_request_and_selection_reject_inaccessible_agent(monkeypatch, tmp_path) -> None:
+def test_active_org_agent_selection_and_harness_bindings_are_allowed(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
store, agents = _seed_agents_with_policies()
private_agent = agents["private"]
- public_agent = agents["public"]
store.set_default_agent_name(private_agent.name)
store.close()
context = _organization_context("member-1")
@@ -319,12 +315,7 @@ def test_remote_agent_request_and_selection_reject_inaccessible_agent(monkeypatc
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- _organization_cookie(
- config,
- subject="member-1",
- groups=["group-engineering"],
- instance_role="editor",
- ),
+ _organization_cookie(config, subject="member-1", groups=[], instance_role="editor"),
domain="alex.avibe.bot",
)
response = client.get(
@@ -332,39 +323,28 @@ def test_remote_agent_request_and_selection_reject_inaccessible_agent(monkeypatc
base_url="https://alex.avibe.bot",
environ_base=_remote_peer(),
)
-
- assert response.status_code == 403
- assert response.get_json()["error"] == "instance_access_forbidden"
- catalog = client.get(
- "/api/agents",
- base_url="https://alex.avibe.bot",
- 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 catalog.status_code == 200
+ assert {"private-agent", "public-agent", "scope-agent"}.issubset(
+ {agent["name"] for agent in catalog.get_json()["agents"]}
)
- public_mutation = client.patch(
+ mutation = client.patch(
"/api/agents/public-agent",
- json={"description": "not allowed"},
+ json={"description": "member update"},
headers=csrf_headers(client, "https://alex.avibe.bot"),
base_url="https://alex.avibe.bot",
environ_base=_remote_peer(),
)
- assert catalog.status_code == 200
- assert {agent["name"] for agent in catalog.get_json()["agents"]} == {"public-agent", "scope-agent"}
- assert public_mutation.status_code == 403
- assert public_mutation.get_json()["error"] == "instance_access_forbidden"
+ assert mutation.status_code == 200
default_mutation = client.post(
"/api/agents/default",
- json={"name": public_agent.name},
+ json={"name": private_agent.name},
headers=csrf_headers(client, "https://alex.avibe.bot"),
base_url="https://alex.avibe.bot",
environ_base=_remote_peer(),
)
- assert default_mutation.status_code == 403
- assert default_mutation.get_json()["error"] == "instance_access_forbidden"
- store = VibeAgentStore()
- try:
- assert store.get_default_agent_name() == private_agent.name
- finally:
- store.close()
+ assert default_mutation.status_code == 200
engine = get_cached_sqlite_engine()
with engine.begin() as connection:
@@ -375,122 +355,27 @@ def test_remote_agent_request_and_selection_reject_inaccessible_agent(monkeypatc
native_id="proj_acl_agents",
now="2026-07-20T00:00:00Z",
)
- with pytest.raises(VibeAgentAccessError):
- workbench_sessions_service.create_session(
- connection,
- scope_id=scope_id,
- agent_backend="codex",
- agent_name=private_agent.name,
- agent_id=private_agent.id,
- user_context=context,
- )
- with pytest.raises(VibeAgentAccessError):
- workbench_sessions_service.create_session(
- connection,
- scope_id=scope_id,
- agent_backend="",
- user_context=context,
- )
- with pytest.raises(VibeAgentAccessError):
- workbench_sessions_service.create_session(
- connection,
- scope_id=scope_id,
- agent_backend="codex",
- user_context=context,
- )
- backend_only_session = workbench_sessions_service.create_session(
+ session = workbench_sessions_service.create_session(
connection,
scope_id=scope_id,
agent_backend="codex",
- user_context=resource_access_service.ResourceUserContext(is_trusted_local=True),
+ agent_name=private_agent.name,
+ agent_id=private_agent.id,
+ user_context=context,
)
- with pytest.raises(VibeAgentAccessError):
- workbench_sessions_service.update_session(
- connection,
- backend_only_session["id"],
- agent_backend="claude",
- agent_name=None,
- user_context=context,
- )
- blocked_default = client.post(
- "/api/sessions",
- json={"project_id": "proj_acl_agents"},
- headers=csrf_headers(client, "https://alex.avibe.bot"),
- base_url="https://alex.avibe.bot",
- environ_base=_remote_peer(),
- )
- assert blocked_default.status_code == 403
- blocked_backend_only = client.post(
- "/api/sessions",
- json={"project_id": "proj_acl_agents", "agent_backend": "codex"},
- headers=csrf_headers(client, "https://alex.avibe.bot"),
- base_url="https://alex.avibe.bot",
- environ_base=_remote_peer(),
- )
- assert blocked_backend_only.status_code == 403
-
- store = VibeAgentStore()
- try:
- store.set_default_agent_name(public_agent.name)
- finally:
- store.close()
- allowed_default = client.post(
- "/api/sessions",
- json={"project_id": "proj_acl_agents"},
- headers=csrf_headers(client, "https://alex.avibe.bot"),
- base_url="https://alex.avibe.bot",
- environ_base=_remote_peer(),
- )
- assert allowed_default.status_code == 201
- session = allowed_default.get_json()
- assert session["agent_id"] == public_agent.id
- assert session["agent_name"] == public_agent.name
- assert session["agent_backend"] == public_agent.backend
-
- dispatch_calls = []
-
- async def dispatch_async(payload):
- dispatch_calls.append(payload)
- return {"status_code": 202, "body": {}}
-
- monkeypatch.setattr("vibe.internal_client.dispatch_async", dispatch_async)
- blocked_legacy_turn = client.post(
- f"/api/sessions/{backend_only_session['id']}/messages",
- json={"text": "must not dispatch"},
- headers=csrf_headers(client, "https://alex.avibe.bot"),
- base_url="https://alex.avibe.bot",
- environ_base=_remote_peer(),
- )
- assert blocked_legacy_turn.status_code == 403
- assert blocked_legacy_turn.get_json()["code"] == "agent_access_forbidden"
- assert dispatch_calls == []
-
- with engine.begin() as connection:
- resource_access_service.apply_control_plane_intent(
+ assert session["agent_id"] == private_agent.id
+ backend_only = workbench_sessions_service.create_session(
connection,
- organization_id="org-1",
- resource_kind="agent",
- resource_id=public_agent.id,
- revision=1,
- access_level="private",
- group_ids=[],
+ scope_id=scope_id,
+ agent_backend="codex",
+ user_context=context,
)
- revoked_turn = client.post(
- f"/api/sessions/{session['id']}/messages",
- json={"text": "must not dispatch"},
- headers=csrf_headers(client, "https://alex.avibe.bot"),
- base_url="https://alex.avibe.bot",
- environ_base=_remote_peer(),
- )
- assert revoked_turn.status_code == 403
- assert revoked_turn.get_json()["code"] == "agent_access_forbidden"
- assert dispatch_calls == []
-
- with pytest.raises(
- resource_access_service.ResourceAccessError,
- match="remote_autonomous_harness_disabled",
- ):
- ScheduledTaskStore(tmp_path / "tasks.json").add_task(
+ assert backend_only["agent_backend"] == "codex"
+
+ task_store = ScheduledTaskStore(tmp_path / "tasks.json")
+ watch_store = ManagedWatchStore(tmp_path / "watches.json")
+ try:
+ task = task_store.add_task(
session_key="avibe::project::proj_acl_agents",
prompt="run",
schedule_type="cron",
@@ -499,11 +384,7 @@ def test_remote_agent_request_and_selection_reject_inaccessible_agent(monkeypatc
timezone_name="UTC",
user_context=context,
)
- with pytest.raises(
- resource_access_service.ResourceAccessError,
- match="remote_autonomous_harness_disabled",
- ):
- ManagedWatchStore(tmp_path / "watches.json").add_watch(
+ watch = watch_store.add_watch(
name="acl watch",
session_key="avibe::project::proj_acl_agents",
command=["true"],
@@ -520,18 +401,22 @@ def test_remote_agent_request_and_selection_reject_inaccessible_agent(monkeypatc
agent_name=private_agent.name,
user_context=context,
)
+ assert task.agent_name == private_agent.name
+ assert watch.agent_name == private_agent.name
+ finally:
+ pass
-def test_remote_external_guest_cannot_create_agent(monkeypatch, tmp_path) -> None:
+def test_non_member_cannot_create_agent_but_active_org_member_can(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = VibeAgentStore()
try:
- with pytest.raises(VibeAgentAccessError):
- store.create(
- name="editor-agent",
- backend="codex",
- user_context=_organization_context("member-1"),
- )
+ 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="guest-agent",
@@ -557,7 +442,7 @@ def test_remote_external_guest_cannot_create_agent(monkeypatch, tmp_path) -> Non
store.close()
-def test_remote_background_definitions_are_rejected_and_legacy_rows_fail_before_dispatch(
+def test_active_org_background_definitions_are_allowed_but_legacy_rows_fail_before_dispatch(
monkeypatch,
tmp_path,
) -> None:
@@ -568,42 +453,47 @@ def test_remote_background_definitions_are_rejected_and_legacy_rows_fail_before_
watch_store = ManagedWatchStore(tmp_path / "watches.json")
request_store = TaskExecutionStore(tmp_path / "task_requests")
try:
- with pytest.raises(
- resource_access_service.ResourceAccessError,
- match="remote_autonomous_harness_disabled",
- ):
- task_store.add_task(
- session_key="slack::channel::C123",
- prompt="run task",
- schedule_type="cron",
- agent_name=agents["public"].name,
- cron="0 * * * *",
- timezone_name="UTC",
- user_context=context,
- )
- with pytest.raises(
- resource_access_service.ResourceAccessError,
- match="remote_autonomous_harness_disabled",
- ):
- watch_store.add_watch(
- name="acl watch",
- session_key="slack::channel::C123",
- command=["true"],
- shell_command=None,
- prefix=None,
- cwd=str(tmp_path),
- mode="once",
- timeout_seconds=1,
- lifetime_timeout_seconds=0,
- retry_exit_codes=[75],
- retry_delay_seconds=1,
- post_to=None,
- deliver_key=None,
- agent_name=agents["public"].name,
- user_context=context,
- )
- assert task_store.list_tasks() == []
- assert watch_store.list_watches() == []
+ task = task_store.add_task(
+ session_key="slack::channel::C123",
+ prompt="run task",
+ schedule_type="cron",
+ agent_name=agents["public"].name,
+ cron="0 * * * *",
+ timezone_name="UTC",
+ user_context=context,
+ )
+ watch = watch_store.add_watch(
+ name="acl watch",
+ session_key="slack::channel::C123",
+ command=["true"],
+ shell_command=None,
+ prefix=None,
+ cwd=str(tmp_path),
+ mode="once",
+ timeout_seconds=1,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=1,
+ post_to=None,
+ deliver_key=None,
+ agent_name=agents["public"].name,
+ user_context=context,
+ )
+ assert task.agent_name == agents["public"].name
+ assert watch.agent_name == agents["public"].name
+ assert resource_access_service.metadata_allows_temporary_unrestricted_runtime(
+ task.metadata
+ )
+ assert resource_access_service.metadata_allows_temporary_unrestricted_runtime(
+ watch.metadata
+ )
+ restored = resource_access_service.resource_user_context_from_metadata(
+ task.metadata
+ )
+ assert restored is not None
+ assert restored.subject == context.subject
+ assert restored.is_remote is True
+ assert restored.is_trusted_local is False
task = task_store.add_task(
session_key="slack::channel::C123",
diff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.py
index 9cf514b7b..53b9bddc1 100644
--- a/tests/test_resource_acl_show_pages.py
+++ b/tests/test_resource_acl_show_pages.py
@@ -97,7 +97,7 @@ def _seed_show_pages_with_policies() -> ShowPageStore:
return store
-def test_show_page_list_filters_private_public_scope_and_missing_group_context(monkeypatch, tmp_path) -> None:
+def test_active_org_members_see_all_show_pages_during_temporary_bypass(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = _seed_show_pages_with_policies()
try:
@@ -111,8 +111,8 @@ def test_show_page_list_filters_private_public_scope_and_missing_group_context(m
store.close()
assert owner_ids == {"ses-private", "ses-public", "ses-scope"}
- assert member_ids == {"ses-public", "ses-scope"}
- assert no_group_ids == {"ses-public"}
+ assert member_ids == {"ses-private", "ses-public", "ses-scope"}
+ assert no_group_ids == {"ses-private", "ses-public", "ses-scope"}
def test_show_page_email_context_bypasses_audience_only_for_its_signed_page(
@@ -152,7 +152,7 @@ def test_show_page_email_context_bypasses_audience_only_for_its_signed_page(
store.close()
-def test_broader_instance_context_unions_its_signed_show_page_entitlement(
+def test_non_org_remote_context_keeps_only_signed_show_page_entitlement(
monkeypatch, tmp_path
) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
@@ -179,8 +179,8 @@ def test_broader_instance_context_unions_its_signed_show_page_entitlement(
"ses-scope",
connection=connection,
)
- assert context.can_chat
- assert context.can_use_resource("agent")
+ assert not context.can_chat
+ assert not context.can_use_resource("agent")
finally:
store.close()
@@ -247,22 +247,30 @@ def test_remote_org_members_can_open_all_show_pages_temporarily(
"ses-public",
"ses-scope",
}
- assert all("path" not in item for item in catalog.get_json()["pages"])
+ 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
-def test_remote_show_page_creation_defaults_private_and_org_public_does_not_share(monkeypatch, tmp_path) -> None:
+def test_remote_show_page_creation_persists_real_org_identity(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
owner_context = _organization_context("owner-1", instance_role="owner")
store = ShowPageStore()
try:
- with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
- store.ensure(
- "ses-editor-denied",
- user_context=_organization_context("member-1", instance_role="editor"),
+ created = store.ensure(
+ "ses-editor-created",
+ user_context=_organization_context("member-1", instance_role="editor"),
+ )
+ assert created.session_id == "ses-editor-created"
+ with store.engine.connect() as connection:
+ created_policy = resource_access_service.get_resource_policy(
+ "show_page", created.session_id, connection=connection
)
+ assert created_policy is not None
+ assert created_policy["organization_id"] == "org-1"
+ assert created_policy["owner_user_id"] == "member-1"
+ assert "is_trusted_local" not in created_policy
page = store.ensure("ses-org-public", user_context=owner_context)
with store.engine.begin() as connection:
policy = resource_access_service.get_resource_policy(
@@ -292,19 +300,18 @@ def test_remote_show_page_creation_defaults_private_and_org_public_does_not_shar
store.close()
-def test_show_page_scope_without_group_context_fails_closed(monkeypatch, tmp_path) -> None:
+def test_show_page_scope_without_group_context_is_open_during_temporary_bypass(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = _seed_show_pages_with_policies()
try:
- with pytest.raises(ShowPageError, match="Show Page access is not permitted") as excinfo:
- store.require_access("ses-scope", user_context=_organization_context("member-1", group_ids=None))
+ page = store.require_access("ses-scope", user_context=_organization_context("member-1", group_ids=None))
finally:
store.close()
- assert excinfo.value.code == "resource_access_forbidden"
+ assert page.session_id == "ses-scope"
-def test_remote_organization_admin_can_restrict_pages_without_use_access(monkeypatch, tmp_path) -> None:
+def test_active_organization_admin_can_manage_all_pages_temporarily(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = _seed_show_pages_with_policies()
admin = _organization_context(
@@ -315,17 +322,16 @@ def test_remote_organization_admin_can_restrict_pages_without_use_access(monkeyp
)
owner = _organization_context("owner-1", instance_role="owner")
try:
- with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
- store.require_access("ses-private", user_context=admin)
- with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
- store.update_visibility("ses-private", "public", user_context=admin)
-
public_page = store.update_visibility("ses-private", "public", user_context=owner)
- with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
- store.rotate_share("ses-private", user_context=admin)
- with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
- store.set_share_id("ses-private", "admin-link", user_context=admin)
+ 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"
republished = store.update_visibility("ses-private", "public", user_context=owner)
rotated, previous_share_id = store.rotate_share("ses-private", user_context=owner)
@@ -337,16 +343,9 @@ def test_remote_organization_admin_can_restrict_pages_without_use_access(monkeyp
assert rotated_share_id == rotated.share_id
assert custom.share_id == "owner-link"
- with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
- store.require_access("ses-scope", user_context=admin)
+ 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"
- with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
- store.update_visibility("ses-scope", "private", user_context=admin)
- restored = store.update_visibility(
- "ses-scope",
- "private",
- user_context=_organization_context("owner-1", instance_role="viewer"),
- )
+ restored = store.update_visibility("ses-scope", "private", user_context=admin)
assert restored.visibility == "private"
finally:
store.close()
@@ -378,7 +377,9 @@ def test_access_only_manager_visibility_response_does_not_expose_page_payload(mo
result = api.set_show_page_visibility("ses-private", "private")
- assert result == {"ok": True, "public_link_enabled": False}
+ assert result["ok"] is True
+ assert result["session_id"] == "ses-private"
+ assert result["visibility"] == "private"
def test_excluded_scoped_owner_share_mutations_do_not_expose_page_payload(monkeypatch, tmp_path) -> None:
@@ -403,8 +404,12 @@ def test_excluded_scoped_owner_share_mutations_do_not_expose_page_payload(monkey
rotated = api.rotate_show_page_share("ses-scope")
customized = api.set_show_page_share_id("ses-scope", "excluded-owner-link")
- assert rotated == {"ok": True, "public_link_enabled": True}
- assert customized == {"ok": True, "public_link_enabled": True}
+ 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:
@@ -514,12 +519,12 @@ def test_organization_admin_can_read_show_page_access_metadata_without_use_acces
assert payload["access_level"] == "scope"
assert payload["instance_id"] is None
- assert payload["can_use"] is False
+ assert payload["can_use"] is True
assert payload["can_manage"] is True
- assert payload["can_publish_public"] is False
+ assert payload["can_publish_public"] is True
-def test_existing_organization_page_is_registered_privately_by_the_instance_owner(monkeypatch, tmp_path) -> None:
+def test_opening_existing_organization_page_does_not_register_new_policy(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = ShowPageStore()
try:
@@ -534,10 +539,7 @@ def test_existing_organization_page_is_registered_privately_by_the_instance_owne
page.session_id,
connection=connection,
)
- assert policy is not None
- assert policy["organization_id"] == "org-1"
- assert policy["owner_user_id"] == "owner-1"
- assert policy["access_level"] == "private"
+ assert policy is None
finally:
store.close()
@@ -689,15 +691,18 @@ 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)
store = _seed_show_pages_with_policies()
store.close()
monkeypatch.setattr(
resource_access_service,
"resolve_resource_access_context",
- lambda _value=None: _organization_context(
- subject,
- organization_role=organization_role,
+ lambda _value=None: resource_access_service.ResourceUserContext(
+ subject=subject,
+ email=f"{subject}@example.com",
instance_role=instance_role,
+ instance_access_source="email",
+ is_remote=True,
),
)
monkeypatch.setattr(
@@ -842,22 +847,18 @@ def test_remote_org_dock_temporarily_bypasses_show_page_acl(monkeypatch, tmp_pat
organization_role="admin",
instance_role="owner",
)
- with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
- api.pin_dock_show_page("ses-public", user_context=member)
+ api.pin_dock_show_page("ses-public", user_context=member)
api.pin_dock_show_page("ses-scope", user_context=admin)
for session_id in ("ses-private", "ses-public", "ses-scope"):
api.pin_dock_show_page(session_id, user_context=owner)
dock = api.get_dock(user_context=member)["dock"]
visible_ids = {pin["session_id"] for pin in dock["pins"]}
- assert visible_ids == {"ses-public", "ses-scope"}
- assert "show:ses-private" not in dock["order"]
- with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
- api.pin_dock_show_page("ses-private", user_context=member)
- with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
- api.unpin_dock_show_page("ses-public", user_context=member)
- with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
- api.set_dock_order([], user_context=member)
+ assert visible_ids == {"ses-private", "ses-public", "ses-scope"}
+ assert "show:ses-private" in dock["order"]
+ api.pin_dock_show_page("ses-private", user_context=member)
+ api.unpin_dock_show_page("ses-public", user_context=member)
+ api.set_dock_order([], user_context=member)
client = app.test_client()
client.set_cookie(
@@ -906,8 +907,8 @@ def test_remote_admin_dock_order_preserves_hidden_private_pins(monkeypatch, tmp_
assert updated["order"] == submitted
owner_dock = api.get_dock(user_context=owner)["dock"]
- assert "show:ses-private" in owner_dock["order"]
- assert [item for item in owner_dock["order"] if item != "show:ses-private"] == submitted
+ assert "show:ses-private" not in owner_dock["order"]
+ assert owner_dock["order"] == submitted
def test_untrusted_dock_context_fails_closed(monkeypatch, tmp_path) -> None:
@@ -932,7 +933,7 @@ def test_untrusted_dock_context_fails_closed(monkeypatch, tmp_path) -> None:
)
-def test_remote_member_cannot_archive_session_with_another_owners_page(monkeypatch, tmp_path) -> None:
+def test_remote_member_can_archive_session_with_another_owners_page_temporarily(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
project_dir = tmp_path / "project"
@@ -981,15 +982,14 @@ def test_remote_member_cannot_archive_session_with_another_owners_page(monkeypat
environ_base=_remote_peer(),
)
- assert response.status_code == 403
- assert response.get_json()["code"] == "remote_execution_disabled"
+ assert response.status_code in {200, 204}
with engine.connect() as connection:
assert connection.execute(
select(agent_sessions.c.status).where(agent_sessions.c.id == session_id)
- ).scalar_one() == "active"
+ ).scalar_one() == "archived"
assert connection.execute(
select(show_pages.c.visibility).where(show_pages.c.session_id == session_id)
- ).scalar_one() == "private"
+ ).scalar_one() == "offline"
finally:
engine.dispose()
@@ -1093,8 +1093,9 @@ def test_remote_org_show_annotation_media_temporarily_follows_open_page_policy(
assert _media(tokens["show_annotation:public"]).status_code == 200
# An annotation with no page to check against cannot be authorized.
assert _media(orphan_token).status_code == 404
- # Unrelated media keeps Project/session authorization as its gate.
- assert _media(tokens["agent_reply:private"]).status_code == 404
- assert _media(tokens["agent_reply:public"]).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
finally:
engine.dispose()
diff --git a/tests/test_ui_memory_routes.py b/tests/test_ui_memory_routes.py
index 69dbda2ce..d93987c4e 100644
--- a/tests/test_ui_memory_routes.py
+++ b/tests/test_ui_memory_routes.py
@@ -134,12 +134,13 @@ def test_memory_authenticated_avibe_cloud_uses_the_remote_workbench_principal(
calls.append(("profile", user_key))
return {"status_code": 200, "body": {"status": "ok", "items": []}}
- async def clear(*, user_key: str): # pragma: no cover - must stay unreached
+ async def clear(*, user_key: str):
calls.append(("clear", user_key))
return {"status_code": 200, "body": {"status": "completed", "epoch": 2}}
- async def failures(): # pragma: no cover - must stay unreached
- raise AssertionError("remote memory failures reached the local sidecar")
+ async def failures():
+ calls.append(("failures", "avibe:remote:user-1"))
+ return {"status_code": 200, "body": {"status": "ok", "items": []}}
monkeypatch.setattr(internal_client, "memory_profile", profile)
monkeypatch.setattr(internal_client, "memory_clear", clear)
@@ -147,7 +148,17 @@ def test_memory_authenticated_avibe_cloud_uses_the_remote_workbench_principal(
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ remote_session_cookie(
+ config,
+ "user-1",
+ role="viewer",
+ access_source="organization_group",
+ organization_id="org-1",
+ organization_member_id="member-1",
+ organization_role="member",
+ group_ids=[],
+ ),
domain="alex.avibe.bot",
)
remote_headers = {"Origin": "https://alex.avibe.bot"}
@@ -178,36 +189,35 @@ def test_memory_authenticated_avibe_cloud_uses_the_remote_workbench_principal(
environ_base={"REMOTE_ADDR": "203.0.113.10"},
)
- assert settings_response.status_code == 403
- assert settings_response.get_json()["code"] == "remote_execution_disabled"
- assert failures_response.status_code == 403
- assert failures_response.get_json()["code"] == "remote_execution_disabled"
+ assert settings_response.status_code == 200
+ assert failures_response.status_code == 200
assert profile_response.status_code == 200
- # The profile read is genuinely scoped to the remote principal, so it keeps
- # crossing the tunnel under that principal's user key. `clear` only carries
- # the key as proof of identity: the internal route discards it and calls the
- # global `runtime.clear()`, which would erase every principal's memcells and
- # the provider root, so the remote boundary refuses it before the handler.
- assert clear_response.status_code == 403
- assert clear_response.get_json()["code"] == "remote_execution_disabled"
- assert calls == [("profile", "avibe:remote:user-1")]
-
-
-def test_memory_settings_patch_is_rejected_for_remote_ui(monkeypatch, tmp_path) -> None:
- """A remote principal cannot patch Memory settings at all, diagnostics included.
-
- The patch repoints the shared LLM and embedding endpoints and immediately
- reconciles the local sidecar, so the remote boundary refuses it before the
- payload is even parsed; the diagnostics field it used to reject by hand is
- only the most sensitive part of a record that is process-global throughout.
- """
+ assert clear_response.status_code == 200
+ assert calls == [
+ ("failures", "avibe:remote:user-1"),
+ ("profile", "avibe:remote:user-1"),
+ ("clear", "avibe:remote:user-1"),
+ ]
+
+
+def test_active_org_member_can_patch_memory_settings(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_remote_config(tmp_path)
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ remote_session_cookie(
+ config,
+ "user-1",
+ role="viewer",
+ access_source="organization_group",
+ organization_id="org-1",
+ organization_member_id="member-1",
+ organization_role="member",
+ group_ids=[],
+ ),
domain="alex.avibe.bot",
)
calls: list[bool] = []
@@ -219,16 +229,15 @@ def test_memory_settings_patch_is_rejected_for_remote_ui(monkeypatch, tmp_path)
monkeypatch.setattr(internal_client, "reconcile_memory", reconcile)
response = client.patch(
"/api/memory/settings",
- json={"enabled": False, "diagnostics": {"log_provider_calls": True}},
+ json={"enabled": False},
headers=csrf_headers(client, "https://alex.avibe.bot"),
base_url="https://alex.avibe.bot",
environ_base={"REMOTE_ADDR": "203.0.113.10"},
)
- assert response.status_code == 403
- assert response.get_json()["code"] == "remote_execution_disabled"
- assert calls == []
- assert V2Config.load().memory.diagnostics.log_provider_calls is True
+ assert response.status_code == 200
+ assert calls == [True]
+ assert V2Config.load().memory.enabled is False
def test_memory_diagnostics_patch_is_rejected_for_local_ui(monkeypatch, tmp_path) -> None:
@@ -854,14 +863,13 @@ def test_memory_restart_route_refuses_concurrent_remote_principals(
monkeypatch,
tmp_path,
) -> None:
- """Restarting the sidecar is local-only, so no remote caller reaches the task.
+ """Non-member remote callers cannot reach the shared restart task.
This route once served remote principals, and its retained request task made
two concurrent remote callers share one Response, which mixed their session
- cookie renewals. A restart acts on the whole local sidecar rather than on one
- principal, so the boundary now refuses it outright and that cross-principal
- renewal is unreachable rather than merely fixed - which is what this asserts,
- with two overlapping remote callers so a partial gate cannot pass.
+ cookie renewals. Active Organization member admission is covered separately;
+ this regression keeps two overlapping legacy identities outside that policy,
+ so a partial membership gate cannot pass.
"""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
diff --git a/tests/test_ui_project_access.py b/tests/test_ui_project_access.py
index b14d7bf04..b8f082c66 100644
--- a/tests/test_ui_project_access.py
+++ b/tests/test_ui_project_access.py
@@ -153,11 +153,31 @@ def _setup_state(tmp_path) -> tuple[V2Config, dict[str, str]]:
}
-def _remote_client(config: V2Config, *, role: str, email: str):
+def _remote_client(
+ config: V2Config,
+ *,
+ role: str,
+ email: str,
+ active_org: bool = True,
+):
client = app.test_client()
+ if active_org:
+ cookie = remote_session_cookie(
+ config,
+ email,
+ f"user-{role}-{email}",
+ role=role,
+ access_source="organization_group",
+ organization_id="org-1",
+ organization_member_id=f"member-{email}",
+ organization_role="member",
+ group_ids=[],
+ )
+ else:
+ cookie = remote_session_cookie(config, email, f"user-{role}-{email}", role=role)
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, email, f"user-{role}-{email}", role=role),
+ cookie,
domain="alex.avibe.bot",
)
return client
@@ -167,7 +187,7 @@ def _get(client, path: str):
return client.get(path, base_url=REMOTE_ORIGIN, environ_base=REMOTE_PEER)
-def test_remote_editor_project_access_filters_every_read_surface(monkeypatch, tmp_path) -> None:
+def test_active_org_member_can_use_every_project_runtime_surface(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config, ids = _setup_state(tmp_path)
engine = create_sqlite_engine()
@@ -193,35 +213,57 @@ def test_remote_editor_project_access_filters_every_read_surface(monkeypatch, tm
)
project_rows = _get(client, "/api/projects").get_json()["projects"]
- assert [row["id"] for row in project_rows] == [ids["project_a"]]
- assert project_rows[0]["folder_path"] == ""
- assert project_rows[0]["metadata"] == {}
- assert project_rows[0]["capabilities"] == {"can_chat": True}
+ assert {row["id"] for row in project_rows} == {ids["project_a"], ids["project_b"]}
+ 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"}
+ assert project_a["capabilities"] == {"can_chat": True}
sessions = _get(client, "/api/sessions?status=active").get_json()["sessions"]
- assert {row["id"] for row in sessions} == {ids["session_a"]}
- assert sessions[0]["workdir"] is None
- assert sessions[0]["metadata"] == {}
+ 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(
+ "/api/sessions?status=active",
+ 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"]:
+ 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 == 404
+ assert _get(client, f"/api/projects/{ids['project_b']}").status_code == 200
session = _get(client, f"/api/sessions/{ids['session_a']}").get_json()
- assert session["workdir"] is None
- assert session["metadata"] == {}
+ 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 == 404
- assert _get(client, f"/api/sessions/{ids['unscoped']}").status_code == 404
+ assert _get(client, f"/api/sessions/{ids['session_b']}/messages").status_code == 200
+ assert _get(client, f"/api/sessions/{ids['unscoped']}").status_code == 200
search = _get(client, "/api/search/messages?q=needle").get_json()
- assert [row["session_id"] for row in search["sessions"]] == [ids["session_a"]]
+ 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"]]
- assert set(inbox["unread_by_session"]) == {ids["session_a"]}
+ 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"]}
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 == 404
+ assert _get(client, f"/api/media/{ids['media_b']}").status_code == 200
show_pages = _get(client, "/api/show-pages").get_json()
- assert show_pages["pages"] == [{"session_id": ids["session_a"]}]
- assert show_pages["count"] == 1
+ assert {page["session_id"] for page in show_pages["pages"]} == {
+ ids["session_a"],
+ ids["session_b"],
+ ids["unscoped"],
+ }
+ assert show_pages["count"] == 3
published = []
monkeypatch.setattr(broker, "publish", lambda event_type, data: published.append((event_type, data)))
@@ -233,9 +275,7 @@ def test_remote_editor_project_access_filters_every_read_surface(monkeypatch, tm
headers=headers,
json={},
)
- assert mark_read.status_code == 403
- assert mark_read.get_json()["code"] == "remote_execution_disabled"
- assert published == []
+ assert mark_read.status_code == 200
allowed_action = client.post(
f"/api/sessions/{ids['session_a']}/attachments",
@@ -251,10 +291,10 @@ def test_remote_editor_project_access_filters_every_read_surface(monkeypatch, tm
headers=headers,
json={},
)
- assert allowed_action.status_code == 403
- assert allowed_action.get_json()["code"] == "remote_execution_disabled"
- assert hidden_action.status_code == 403
- assert hidden_action.get_json()["code"] == "remote_execution_disabled"
+ # 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:
@@ -293,20 +333,20 @@ 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": False}
+ assert viewer_project["capabilities"] == {"can_chat": True}
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": False}
- assert viewer_payload["agents"] == []
- assert viewer_payload["default_agent_name"] is None
- assert viewer_payload["queued"] == []
- assert viewer_payload["draft"] == {"text": ""}
+ 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"] == {"text": "editor-only draft"}
assert [message["text"] for message in viewer_payload["messages"]] == ["shared needle"]
- assert viewer_payload["session"]["workdir"] is None
- assert viewer_payload["session"]["metadata"] == {}
+ assert viewer_payload["session"]["workdir"] == str((tmp_path / "project-a").resolve())
+ assert viewer_payload["session"]["metadata"] == {"created_via": "workbench"}
with engine.begin() as conn:
project_access_service.apply_project_access_intent(
@@ -325,13 +365,18 @@ def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_pat
assert editor_payload["agents"][0]["name"] == "editor-agent"
assert editor_payload["default_agent_name"] == "editor-agent"
assert editor_payload["queued"][0]["text"] == "editor-only queued prompt"
- assert editor_payload["draft"] == {"text": ""}
- assert editor_payload["config"] == api.remote_config_payload(config)
+ assert editor_payload["draft"] == {"text": "editor-only draft"}
+ assert editor_payload["config"]["runtime"]["default_cwd"] == "."
+ assert "agents" in editor_payload["config"]
+ assert "memory" not in editor_payload["config"]
+ assert "remote_access" not in editor_payload["config"]
owner = _remote_client(config, role="owner", email="[email protected]")
owner_payload = _get(owner, f"/api/sessions/{ids['session_a']}/bootstrap").get_json()
- assert owner_payload["config"] == api.remote_config_payload(config)
- assert "runtime" not in owner_payload["config"]
+ 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"]
local_payload = app.test_client().get(
f"/api/sessions/{ids['session_a']}/bootstrap",
@@ -347,12 +392,11 @@ def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_pat
headers=csrf_headers(client, REMOTE_ORIGIN),
json={"text": "remote overwrite"},
)
- assert draft_get.status_code == 403
- assert draft_get.get_json()["code"] == "remote_execution_disabled"
- assert draft_put.status_code == 403
- assert draft_put.get_json()["code"] == "remote_execution_disabled"
+ assert draft_get.status_code == 200
+ assert draft_get.get_json() == {"text": "editor-only draft"}
+ assert draft_put.status_code == 200
with engine.connect() as conn:
- assert message_deliveries.get_draft(conn, ids["session_a"])["text"] == "editor-only draft"
+ assert message_deliveries.get_draft(conn, ids["session_a"])["text"] == "remote overwrite"
editor_project = _get(client, f"/api/projects/{ids['project_a']}").get_json()
assert editor_project["capabilities"] == {"can_chat": True}
@@ -389,11 +433,17 @@ def test_archived_project_invalidates_retained_remote_urls(monkeypatch, tmp_path
)
client = _remote_client(config, role="editor", email="[email protected]")
- assert _get(client, "/api/projects").get_json()["projects"] == []
- assert _get(client, f"/api/projects/{ids['project_a']}").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"] == []
+ assert [row["id"] for row in _get(client, "/api/projects").get_json()["projects"]] == [
+ ids["project_b"]
+ ]
+ 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 _get(client, "/api/show-pages").get_json()["pages"] == [
+ {"session_id": ids["session_a"]}
+ ]
response = client.post(
f"/api/sessions/{ids['session_a']}/attachments",
@@ -402,8 +452,7 @@ def test_archived_project_invalidates_retained_remote_urls(monkeypatch, tmp_path
headers=csrf_headers(client, REMOTE_ORIGIN),
json={},
)
- assert response.status_code == 403
- assert response.get_json()["code"] == "remote_execution_disabled"
+ 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:
@@ -564,7 +613,7 @@ 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 == 404
+ assert _get(viewer, f"/api/sessions/{ids['session_b']}").status_code == 200
headers = csrf_headers(viewer, REMOTE_ORIGIN)
assert viewer.post(
"/api/sessions",
@@ -572,12 +621,17 @@ def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:
environ_base=REMOTE_PEER,
headers=headers,
json={"project_id": ids["project_a"]},
- ).status_code == 403
+ ).status_code != 403
- no_match = _remote_client(config, role="editor", email="[email protected]")
- assert _get(no_match, "/api/projects").get_json()["projects"] == []
- assert _get(no_match, "/api/sessions").get_json()["sessions"] == []
- assert _get(no_match, f"/api/sessions/{ids['session_a']}").status_code == 404
+ no_match = _remote_client(
+ config,
+ role="editor",
+ active_org=False,
+ )
+ assert _get(no_match, "/api/projects").status_code == 403
+ assert _get(no_match, "/api/sessions").status_code == 403
+ assert _get(no_match, f"/api/sessions/{ids['session_a']}").status_code == 403
no_match_headers = csrf_headers(no_match, REMOTE_ORIGIN)
denied = no_match.post(
"/api/sessions",
@@ -587,15 +641,7 @@ 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() == {
- "ok": False,
- "error": {
- "code": "project_access_denied",
- "message": "你没有权限在这个项目中创建会话。",
- },
- "code": "project_access_denied",
- "message": "你没有权限在这个项目中创建会话。",
- }
+ assert denied.get_json()["code"] == "remote_execution_disabled"
organization_member = app.test_client()
organization_member.set_cookie(
@@ -613,13 +659,14 @@ 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_b"]]
+ assert {row["id"] for row in _get(organization_member, "/api/projects").get_json()["projects"]} == {
+ ids["project_a"],
+ ids["project_b"],
+ }
assert _get(organization_member, f"/api/sessions/{ids['session_b']}").status_code == 200
- assert _get(organization_member, f"/api/sessions/{ids['session_a']}").status_code == 404
+ assert _get(organization_member, f"/api/sessions/{ids['session_a']}").status_code == 200
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 == 404
+ assert _get(organization_member, f"/api/media/{ids['media_a']}").status_code == 200
owner = _remote_client(config, role="owner", email="[email protected]")
owner_projects = _get(owner, "/api/projects").get_json()["projects"]
@@ -627,22 +674,25 @@ def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:
ids["project_a"],
ids["project_b"],
}
- assert all(row["folder_path"] == "" and row["metadata"] == {} for row in owner_projects)
+ owner_project_a = next(row for row in owner_projects if row["id"] == ids["project_a"])
+ assert owner_project_a["folder_path"] == str((tmp_path / "project-a").resolve())
+ assert owner_project_a["metadata"] == {"host_path_hint": "/private/host"}
owner_project = _get(owner, f"/api/projects/{ids['project_a']}").get_json()
- assert owner_project["folder_path"] == ""
- assert owner_project["metadata"] == {}
+ assert owner_project["folder_path"] == str((tmp_path / "project-a").resolve())
+ assert owner_project["metadata"] == {"host_path_hint": "/private/host"}
owner_bootstrap = _get(owner, "/api/workbench/projects-bootstrap").get_json()
- assert all(
- row["folder_path"] == "" and row["metadata"] == {}
- for row in owner_bootstrap["projects"]
+ bootstrap_project_a = next(
+ row for row in owner_bootstrap["projects"] if row["id"] == ids["project_a"]
)
+ assert bootstrap_project_a["folder_path"] == str((tmp_path / "project-a").resolve())
+ assert bootstrap_project_a["metadata"] == {"host_path_hint": "/private/host"}
owner_sessions = _get(owner, "/api/sessions").get_json()["sessions"]
owner_session_a = next(row for row in owner_sessions if row["id"] == ids["session_a"])
- assert owner_session_a["workdir"] is None
- assert owner_session_a["metadata"] == {}
+ assert owner_session_a["workdir"] == str((tmp_path / "project-a").resolve())
+ assert owner_session_a["metadata"] == {"host_session_hint": "/private/session"}
owner_session_a = _get(owner, f"/api/sessions/{ids['session_a']}").get_json()
- assert owner_session_a["workdir"] is None
- assert owner_session_a["metadata"] == {}
+ assert owner_session_a["workdir"] == str((tmp_path / "project-a").resolve())
+ assert owner_session_a["metadata"] == {"host_session_hint": "/private/session"}
assert _get(owner, f"/api/sessions/{ids['unscoped']}").status_code == 200
local = app.test_client()
@@ -666,19 +716,34 @@ def test_project_access_filters_sse_and_show_websocket(monkeypatch, tmp_path) ->
context = AuthorizationContext(
instance_role="editor",
+ subject="user-editor",
+ instance_access_source="organization_group",
+ organization_id="org-1",
+ organization_member_id="member-1",
+ organization_role="member",
is_remote=True,
)
visible_payload = json.dumps({"type": "session.status", "data": {"session_id": ids["session_a"]}})
hidden_payload = json.dumps({"type": "session.status", "data": {"session_id": ids["session_b"]}})
assert ui_server._workbench_event_visible_to_context(context, "session.status", visible_payload) is True
- assert ui_server._workbench_event_visible_to_context(context, "session.status", hidden_payload) is False
+ assert ui_server._workbench_event_visible_to_context(context, "session.status", hidden_payload) is True
assert ui_server._workbench_event_visible_to_context(
context,
"authorization.changed",
json.dumps({"type": "authorization.changed", "data": {"project_ids": []}}),
) is True
- cookie = remote_session_cookie(config, "[email protected]", "user-editor", role="editor")
+ 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=[],
+ )
websocket = SimpleNamespace(
client=SimpleNamespace(host="203.0.113.10"),
headers={"host": "alex.avibe.bot"},
@@ -694,4 +759,4 @@ def test_project_access_filters_sse_and_show_websocket(monkeypatch, tmp_path) ->
websocket,
minimum_role="viewer",
project_session_id=ids["session_b"],
- ) is False
+ ) is True
diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.py
index 6c3dc4e8d..648ddca8d 100644
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@ -122,6 +122,32 @@ def _cloudflare_headers() -> dict[str, str]:
return {"CF-Connecting-IP": "198.51.100.10", "CF-Ray": "test-ray"}
+def _org_session_cookie(
+ config: V2Config,
+ email: str,
+ subject: str,
+ *,
+ role: str = "viewer",
+ organization_id: str = "org-1",
+ organization_member_id: str | None = None,
+ organization_role: str = "member",
+ group_ids: list[str] | None = None,
+) -> str:
+ """Create a signed active-Organization member session for runtime tests."""
+
+ return remote_session_cookie(
+ config,
+ email,
+ subject,
+ role=role,
+ access_source="organization_group",
+ organization_id=organization_id,
+ organization_member_id=organization_member_id or f"member-{subject}",
+ organization_role=organization_role,
+ group_ids=[] if group_ids is None else group_ids,
+ )
+
+
def _mock_ui_dist(monkeypatch, tmp_path):
ui_dist = tmp_path / "ui-dist"
ui_dist.mkdir()
@@ -1112,7 +1138,7 @@ def test_remote_host_allows_valid_remote_session(monkeypatch, tmp_path):
assert response.status_code != 302
-def test_remote_generic_config_omits_memory_projection(monkeypatch, tmp_path):
+def test_active_org_config_omits_memory_projection(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
config.memory.processing.llm.base_url = "https://llm.example.test/v1"
@@ -1121,7 +1147,7 @@ def test_remote_generic_config_omits_memory_projection(monkeypatch, tmp_path):
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ _org_session_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
@@ -1135,7 +1161,7 @@ def test_remote_generic_config_omits_memory_projection(monkeypatch, tmp_path):
assert "memory" not in response.get_json()
-def test_remote_config_uses_the_safe_projection_for_an_instance_owner(monkeypatch, tmp_path):
+def test_active_org_config_uses_runtime_projection_without_remote_access(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
config.runtime.default_cwd = "/private/local-agent-workdir"
@@ -1144,7 +1170,7 @@ def test_remote_config_uses_the_safe_projection_for_an_instance_owner(monkeypatc
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-owner", role="owner"),
+ _org_session_cookie(config, "[email protected]", "user-owner", role="owner", organization_role="owner"),
domain="alex.avibe.bot",
)
@@ -1158,12 +1184,13 @@ def test_remote_config_uses_the_safe_projection_for_an_instance_owner(monkeypatc
payload = response.get_json()
assert payload["mode"] == "self_host"
assert payload["ui"]["instance_name"] == config.ui.instance_name
- assert "runtime" not in payload
- assert "agents" not in payload
+ assert payload["runtime"]["default_cwd"] == "/private/local-agent-workdir"
+ assert payload["agents"]["codex"]["cli_path"] == "/opt/avibe/bin/codex"
assert "memory" not in payload
+ assert "remote_access" not in payload
-def test_remote_config_post_uses_the_safe_projection_for_an_instance_owner(monkeypatch, tmp_path):
+def test_active_org_config_post_uses_runtime_projection_without_remote_access(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
config.runtime.default_cwd = "/private/local-agent-workdir"
@@ -1178,7 +1205,7 @@ def test_remote_config_post_uses_the_safe_projection_for_an_instance_owner(monke
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-owner", role="owner"),
+ _org_session_cookie(config, "[email protected]", "user-owner", role="owner", organization_role="owner"),
domain="alex.avibe.bot",
)
@@ -1193,69 +1220,44 @@ def test_remote_config_post_uses_the_safe_projection_for_an_instance_owner(monke
assert response.status_code == 200
payload = response.get_json()
assert payload["ui"]["instance_name"] == "Remote Workbench"
- assert set(payload) == {
- "ack_mode",
- "agent_progress_style",
- "include_time_info",
- "include_user_info",
- "language",
- "mode",
- "reply_enhancements",
- "setup_state",
- "show_duration",
- "ui",
- "version",
- }
assert payload["ack_mode"] == "reaction"
assert payload["show_duration"] is False
assert payload["include_time_info"] is False
assert payload["include_user_info"] is True
assert payload["reply_enhancements"] is False
assert payload["agent_progress_style"] == "concise"
- assert "runtime" not in payload
- assert "agents" not in payload
+ assert payload["runtime"]["default_cwd"] == "/private/local-agent-workdir"
+ assert payload["agents"]["codex"]["cli_path"] == "/opt/avibe/bin/codex"
assert "memory" not in payload
+ assert "remote_access" not in payload
assert "remote_access_runtime" not in payload
- assert "platform_runtime" not in payload
- assert "agent_backend_runtime" not in payload
-def test_remote_session_info_includes_authenticated_subject(monkeypatch, tmp_path):
+def test_remote_session_info_projects_active_org_signal_without_fake_capabilities(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ _org_session_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
response = client.get("/api/session", base_url="https://alex.avibe.bot")
assert response.status_code == 200
- assert response.get_json() == {
- "remote": True,
- "authenticated": True,
- "email": "[email protected]",
- "sub": "user-1",
- "instance_role": "owner",
- "temporary_unrestricted_org_app_access": False,
- "capabilities": {
- "is_instance_owner": True,
- "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,
- },
- }
+ payload = response.get_json()
+ assert payload["remote"] is True
+ assert payload["authenticated"] is True
+ assert payload["email"] == "[email protected]"
+ assert payload["sub"] == "user-1"
+ assert payload["instance_role"] == "viewer"
+ assert payload["temporary_unrestricted_org_access"] is True
+ assert payload["temporary_unrestricted_org_app_access"] is True
+ # The temporary signal admits runtime routes; it never fabricates owner or
+ # trusted-local capability bits in the browser projection.
+ assert payload["capabilities"]["is_instance_owner"] is False
+ assert payload["capabilities"]["can_manage_instance"] is False
+ assert payload["capabilities"]["can_use_system"] is False
def test_non_org_remote_file_api_is_blocked_while_local_file_browsing_still_works(
@@ -1340,6 +1342,23 @@ def test_remote_org_members_can_use_files_editor_and_builtin_apps(
base_url="https://alex.avibe.bot",
environ_base=_remote_peer(),
)
+ show_path = str(tmp_path / ".avibe" / "show-pages" / "ses-org")
+ monkeypatch.setattr(
+ api,
+ "ensure_show_page",
+ lambda session_id, **_kwargs: {
+ "ok": True,
+ "existed": True,
+ "session_id": session_id,
+ "path": show_path,
+ },
+ )
+ show_response = client.post(
+ "/api/show-pages/ses-org/ensure",
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
assert list_response.status_code == 200
assert list_response.get_json()["path"] == str(workspace.resolve())
@@ -1352,6 +1371,8 @@ def test_remote_org_members_can_use_files_editor_and_builtin_apps(
"editor",
"library",
]
+ assert show_response.status_code == 200
+ assert show_response.get_json()["path"] == show_path
session_response = client.get(
"/api/session",
base_url="https://alex.avibe.bot",
@@ -1363,13 +1384,16 @@ def test_remote_org_members_can_use_files_editor_and_builtin_apps(
@pytest.mark.parametrize(
("method", "path", "json_body"),
[
- ("GET", "/api/harness/bootstrap", None),
- ("POST", "/api/settings", {"platform": "slack", "channels": {}}),
- ("POST", "/api/vault/secrets", {}),
- ("POST", "/api/control", {"action": "restart"}),
+ ("POST", "/api/remote-access/vibe-cloud/pair", {}),
+ ("POST", "/api/remote-access/start", {}),
+ ("POST", "/api/remote-access/stop", {}),
+ ("POST", "/api/remote-access/optimize-route", {}),
+ ("POST", "/api/remote-access/settings", {}),
+ ("POST", "/api/remote-access/diagnostics", {}),
+ ("GET", "/api/remote-access/network-interfaces", None),
],
)
-def test_temporary_org_app_access_does_not_open_sensitive_control_plane(
+def test_active_org_access_preserves_identity_control_plane_boundary(
monkeypatch,
tmp_path,
method,
@@ -1777,28 +1801,34 @@ def test_remote_execution_config_changes_are_blocked_before_runtime_reconcile(
assert response.get_json()["code"] == "remote_execution_disabled"
-def test_remote_session_and_project_metadata_predicates_remain_allowed():
+def test_temporary_org_runtime_routes_are_not_payload_filtered():
assert not ui_server._is_remote_local_execution_request(
"PATCH", "/api/sessions/ses-local", {"title": "renamed"}
)
- assert ui_server._is_remote_local_execution_request(
+ assert not ui_server._is_remote_local_execution_request(
"PATCH", "/api/sessions/ses-local", {"visibility": "background"}
)
- assert ui_server._is_remote_local_execution_request(
+ assert not ui_server._is_remote_local_execution_request(
"PATCH", "/api/sessions/ses-local", {"pinned": True}
)
assert not ui_server._is_remote_local_execution_request(
"PATCH", "/api/projects/proj-local", {"display_name": "renamed"}
)
+ assert not ui_server._is_remote_local_execution_request("GET", "/api/users")
+ assert not ui_server._is_remote_local_execution_request("POST", "/api/bind-codes")
+ assert not ui_server._is_remote_local_execution_request("GET", "/api/setup/first-bind-code")
+ assert ui_server._is_remote_local_execution_request(
+ "POST", "/api/future-local-control", {}
+ )
-def test_remote_turn_state_filters_harness_activity_labels(monkeypatch, tmp_path):
+def test_active_org_turn_state_includes_harness_activity_labels(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-owner"),
+ _org_session_cookie(config, "[email protected]", "user-member"),
domain="alex.avibe.bot",
)
@@ -1836,8 +1866,12 @@ def test_remote_turn_state_filters_harness_activity_labels(monkeypatch, tmp_path
assert response.status_code == 200
body = response.get_json()
- assert [item["id"] for item in body["background_activities"]] == ["backend-1"]
+ assert [item["id"] for item in body["background_activities"]] == [
+ "backend-1",
+ "task-1",
+ ]
assert body["background_activities"][0]["label"] == "Waiting for turn"
+ assert body["background_activities"][1]["label"] == "private prompt head"
@pytest.mark.parametrize(
@@ -1863,18 +1897,13 @@ def test_remote_turn_state_filters_harness_activity_labels(monkeypatch, tmp_path
"settings": {"enabled": True, "future_route": "codex"},
},
),
- (
- "POST",
- "/api/users",
- {"platform": "slack", "users": {"U1": {"enabled": True, "future_route": "codex"}}},
- ),
],
)
-def test_remote_payload_filtered_routes_reject_unknown_fields(method, path, payload):
- assert ui_server._is_remote_local_execution_request(method, path, payload)
+def test_temporary_org_runtime_routes_accept_complete_payloads(method, path, payload):
+ assert not ui_server._is_remote_local_execution_request(method, path, payload)
-def test_remote_config_allows_only_explicit_preferences_and_unchanged_round_trip(
+def test_temporary_org_config_policy_accepts_runtime_fields_but_not_identity_routes(
monkeypatch,
tmp_path,
):
@@ -1884,21 +1913,17 @@ def test_remote_config_allows_only_explicit_preferences_and_unchanged_round_trip
assert not ui_server._is_remote_local_execution_request(
"POST",
"/api/config",
- {"language": "zh", "ui": {"instance_name": "Remote label"}},
- )
- assert not ui_server._is_remote_local_execution_request(
- "POST",
- "/api/config",
- json.loads(json.dumps(api.config_to_payload(config))),
+ {
+ **json.loads(json.dumps(api.config_to_payload(config))),
+ "future_runtime": {"enabled": True},
+ },
)
assert ui_server._is_remote_local_execution_request(
- "POST",
- "/api/config",
- {"ui": {"future_setting": True}},
+ "POST", "/api/remote-access/settings", {"enabled": True}
)
-def test_remote_config_strips_protected_round_trip_fields_before_persistence(
+def test_active_org_config_preserves_runtime_fields_but_strips_remote_access_identity(
monkeypatch,
tmp_path,
):
@@ -1907,7 +1932,7 @@ def test_remote_config_strips_protected_round_trip_fields_before_persistence(
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-owner"),
+ _org_session_cookie(config, "[email protected]", "user-member"),
domain="alex.avibe.bot",
)
payload = json.loads(json.dumps(api.config_to_payload(config)))
@@ -1931,15 +1956,11 @@ def test_remote_config_strips_protected_round_trip_fields_before_persistence(
assert response.status_code == 200
assert len(observed) == 1
assert observed[0]["language"] == "zh"
- assert observed[0]["ui"] == {
- field: payload["ui"][field]
- for field in ui_server._REMOTE_UI_CONFIG_MUTABLE_FIELDS
- }
- assert set(observed[0]).issubset(
- ui_server._REMOTE_CONFIG_MUTABLE_FIELDS | {"ui"}
- )
- assert "runtime" not in observed[0]
- assert "agents" not in observed[0]
+ expected = dict(payload)
+ expected.pop("remote_access")
+ assert observed[0] == expected
+ assert "runtime" in observed[0]
+ assert "agents" in observed[0]
assert "remote_access" not in observed[0]
@@ -2182,7 +2203,10 @@ def test_remote_org_members_can_reach_show_page_icon_upload(
assert response.status_code == 200
assert len(calls) == 1
assert calls[0][0] == ("ses-remote", b"<svg/>")
- assert calls[0][1]["user_context"].is_trusted_local is True
+ user_context = calls[0][1]["user_context"]
+ assert user_context.is_remote is True
+ assert user_context.is_trusted_local is False
+ assert user_context.is_active_organization_member is True
@pytest.mark.parametrize(
@@ -2215,7 +2239,7 @@ def test_remote_show_page_public_link_mutations_reach_resource_authorization(
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-owner"),
+ _org_session_cookie(config, "[email protected]", "user-member"),
domain="alex.avibe.bot",
)
@@ -2245,14 +2269,14 @@ def test_remote_show_page_public_link_mutations_reach_resource_authorization(
@pytest.mark.parametrize(
("path", "local_only"),
[
- ("/api/models/runtime/status", True),
+ ("/api/models/runtime/status", False),
("/api/models/agents", False),
- ("/api/models/sources", True),
- ("/api/backend/codex/runtime", True),
- ("/api/backend/codex/auth", True),
+ ("/api/models/sources", False),
+ ("/api/backend/codex/runtime", False),
+ ("/api/backend/codex/auth", False),
],
)
-def test_remote_model_and_backend_reads_follow_execution_safety_policy(path, local_only):
+def test_temporary_org_model_and_backend_reads_are_runtime_routes(path, local_only):
assert ui_server._is_remote_local_execution_request("GET", path) is local_only
@@ -2299,6 +2323,44 @@ def test_remote_show_event_stream_redacts_local_screenshot_path() -> None:
assert data["transcript_text"] == "Annotation at med_1"
+def test_active_org_event_stream_keeps_runtime_details() -> None:
+ from vibe.authorization import AuthorizationContext
+
+ context = AuthorizationContext(
+ instance_role="viewer",
+ subject="member-1",
+ instance_access_source="organization_group",
+ organization_id="org-1",
+ organization_member_id="membership-1",
+ organization_role="member",
+ is_remote=True,
+ )
+ show_frame = _show_event_frame()
+ vault_frame = json.dumps(
+ {
+ "type": "vaults.updated",
+ "data": {"scope": "secret", "secret_name": "RUNTIME_KEY"},
+ }
+ )
+
+ assert (
+ ui_server._workbench_event_payload_for_context(
+ context,
+ "show.event",
+ show_frame,
+ )
+ == show_frame
+ )
+ assert (
+ ui_server._workbench_event_payload_for_context(
+ context,
+ "vaults.updated",
+ vault_frame,
+ )
+ == vault_frame
+ )
+
+
def test_remote_show_event_stream_drops_unprojectable_frame() -> None:
from vibe.authorization import AuthorizationContext
@@ -2344,49 +2406,49 @@ def _deny_show_page_acl(monkeypatch, *, allowed: bool) -> list[tuple[str, str]]:
return checks
-def test_remote_owner_show_event_requires_the_show_page_acl(monkeypatch) -> None:
- """An Instance owner does not override a Show Page's own resource policy.
-
- Direct reads of a private page whose policy names another subject already
- deny this owner, so the workbench SSE must not forward the same page's
- annotation text and attachment metadata either.
- """
+def test_active_org_show_event_bypasses_show_page_acl(monkeypatch) -> None:
+ """The temporary rollout opens every Show Page without changing its ACL."""
from vibe.authorization import AuthorizationContext
checks = _deny_show_page_acl(monkeypatch, allowed=False)
- remote_owner = AuthorizationContext(
- instance_role="owner",
- subject="[email protected]",
+ remote_member = AuthorizationContext(
+ instance_role="viewer",
+ subject="member-1",
+ instance_access_source="organization_group",
+ organization_id="org-1",
+ organization_member_id="membership-1",
+ organization_role="member",
is_remote=True,
)
assert (
ui_server._workbench_event_visible_to_context(
- remote_owner, "show.event", _show_event_frame()
+ remote_member, "show.event", _show_event_frame()
)
- is False
+ is True
)
- assert checks == [("show_page", "ses123")]
+ assert checks == []
-def test_remote_owner_show_event_passes_the_allowed_show_page(monkeypatch) -> None:
+def test_non_org_remote_show_event_does_not_reach_resource_acl(monkeypatch) -> None:
from vibe.authorization import AuthorizationContext
checks = _deny_show_page_acl(monkeypatch, allowed=True)
- remote_owner = AuthorizationContext(
+ non_member = AuthorizationContext(
instance_role="owner",
subject="[email protected]",
+ instance_access_source="owner",
is_remote=True,
)
assert (
ui_server._workbench_event_visible_to_context(
- remote_owner, "show.event", _show_event_frame()
+ non_member, "show.event", _show_event_frame()
)
- is True
+ is False
)
- assert checks == [("show_page", "ses123")]
+ assert checks == []
def test_show_event_without_a_session_is_dropped(monkeypatch) -> None:
@@ -2507,7 +2569,7 @@ def test_remote_skill_operations_are_blocked_before_api_calls(
assert response.get_json()["code"] == "remote_execution_disabled"
-def test_remote_project_scoped_skill_reads_require_project_access(
+def test_active_org_project_scoped_skill_reads_bypass_project_acl(
monkeypatch,
tmp_path,
):
@@ -2535,22 +2597,27 @@ def test_remote_project_scoped_skill_reads_require_project_access(
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-owner", role="editor"),
+ _org_session_cookie(config, "[email protected]", "user-member"),
domain="alex.avibe.bot",
)
- async def unexpected_list(*args, **kwargs):
- raise AssertionError("restricted remote skill read reached the Skills API")
+ calls = []
- monkeypatch.setattr(api, "list_skills", unexpected_list)
+ async def list_skills(*args, **kwargs):
+ calls.append((args, kwargs))
+ return {"ok": True, "skills": []}
+
+ monkeypatch.setattr(api, "list_skills", list_skills)
response = client.get(
f"/api/skills?scope=project&project_id={project['id']}",
base_url="https://alex.avibe.bot",
environ_base=_remote_peer(),
)
- assert response.status_code == 404
- assert response.get_json()["error"]["code"] == "project_not_found"
+ assert response.status_code == 200
+ assert response.get_json() == {"ok": True, "skills": []}
+ assert len(calls) == 1
+ assert calls[0][1]["user_context"].is_active_organization_member is True
@pytest.mark.parametrize(
@@ -2609,7 +2676,7 @@ def test_remote_vault_mutations_are_blocked_before_api_calls(
("DELETE", "/api/users/U1", None, "remove_user"),
],
)
-def test_remote_im_user_operations_are_blocked_before_api_calls(
+def test_active_org_member_can_manage_im_users(
monkeypatch,
tmp_path,
method,
@@ -2622,14 +2689,23 @@ def test_remote_im_user_operations_are_blocked_before_api_calls(
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-owner"),
+ _org_session_cookie(
+ config,
+ "user-owner",
+ role="owner",
+ organization_role="owner",
+ ),
domain="alex.avibe.bot",
)
- def unexpected_user_call(*args, **kwargs):
- raise AssertionError("remote IM user mutation reached the local user store")
+ calls = []
- monkeypatch.setattr(api, api_method, unexpected_user_call)
+ def user_call(*args, **kwargs):
+ calls.append((args, kwargs))
+ return {"ok": True}
+
+ monkeypatch.setattr(api, api_method, user_call)
response = client.request(
method,
path,
@@ -2639,8 +2715,8 @@ def test_remote_im_user_operations_are_blocked_before_api_calls(
environ_base=_remote_peer(),
)
- assert response.status_code == 403
- assert response.get_json()["code"] == "remote_execution_disabled"
+ assert response.status_code == 200
+ assert len(calls) == 1
@pytest.mark.parametrize(
@@ -2649,9 +2725,10 @@ def test_remote_im_user_operations_are_blocked_before_api_calls(
("GET", "/api/bind-codes", None, "get_bind_codes"),
("POST", "/api/bind-codes", {"type": "one_time"}, "create_bind_code"),
("DELETE", "/api/bind-codes/CODE1", None, "delete_bind_code"),
+ ("GET", "/api/setup/first-bind-code", None, "get_first_bind_code"),
],
)
-def test_remote_bind_code_operations_are_blocked_before_api_calls(
+def test_active_org_member_can_manage_bind_codes(
monkeypatch,
tmp_path,
method,
@@ -2664,14 +2741,23 @@ def test_remote_bind_code_operations_are_blocked_before_api_calls(
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-owner"),
+ _org_session_cookie(
+ config,
+ "user-owner",
+ role="owner",
+ organization_role="owner",
+ ),
domain="alex.avibe.bot",
)
- def unexpected_bind_code_call(*args, **kwargs):
- raise AssertionError("remote bind-code operation reached the local auth store")
+ calls = []
+
+ def bind_code_call(*args, **kwargs):
+ calls.append((args, kwargs))
+ return {"ok": True}
- monkeypatch.setattr(api, api_method, unexpected_bind_code_call)
+ monkeypatch.setattr(api, api_method, bind_code_call)
response = client.request(
method,
path,
@@ -2681,8 +2767,8 @@ def test_remote_bind_code_operations_are_blocked_before_api_calls(
environ_base=_remote_peer(),
)
- assert response.status_code == 403
- assert response.get_json()["code"] == "remote_execution_disabled"
+ assert response.status_code == 200
+ assert len(calls) == 1
def test_remote_project_archive_is_blocked_before_project_store(monkeypatch, tmp_path):
@@ -2790,16 +2876,11 @@ def test_remote_queue_deletion_is_blocked_before_store_access(
assert response.get_json()["code"] == "remote_execution_disabled"
-def test_remote_owner_instruction_reads_stay_local_while_queue_reads_do_not(
+def test_active_org_member_can_read_instructions_and_session_queue(
monkeypatch,
tmp_path,
):
- """Project and global instructions are local reads; the queue is not.
-
- A checked-out ``AGENTS.md`` / ``CLAUDE.md`` can be a symlink pointing
- outside the Project, and a remote caller holds no file capability to
- follow it, so the read stays trusted-local like the global prompts.
- """
+ """The temporary runtime policy opens instruction and queue reads."""
from storage.importer import ensure_sqlite_state
@@ -2814,7 +2895,7 @@ def test_remote_owner_instruction_reads_stay_local_while_queue_reads_do_not(
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-owner"),
+ _org_session_cookie(config, "[email protected]", "user-member"),
domain="alex.avibe.bot",
)
@@ -2834,29 +2915,18 @@ def test_remote_owner_instruction_reads_stay_local_while_queue_reads_do_not(
environ_base=_remote_peer(),
)
- assert project_response.status_code == 403
- assert project_response.get_json()["code"] == "remote_execution_disabled"
- assert global_response.status_code == 403
- assert global_response.get_json()["code"] == "remote_execution_disabled"
+ assert project_response.status_code == 200
+ assert global_response.status_code == 200
assert queue_response.status_code == 200
assert queue_response.get_json() == {"queued": []}
- assert ui_server._is_remote_local_execution_request("POST", "/api/skills/preview")
+ assert not ui_server._is_remote_local_execution_request("POST", "/api/skills/preview")
-def test_remote_owner_cannot_register_or_test_a_web_push_endpoint(
+def test_active_org_member_can_register_and_test_a_web_push_endpoint(
monkeypatch,
tmp_path,
):
- """Push registration is the SSRF surface; the status read is not.
-
- A subscription endpoint is caller-supplied and ``send_web_push()`` fetches
- it from this host, and nothing between the payload and that request keeps
- it pointed at a real push service - an HTTPS URL naming loopback, a private
- LAN host or a rebinding name is accepted. A remote caller could therefore
- register one and use ``/test`` to have the Avibe host issue the request
- from inside its own network, so both mutations stop at the boundary while
- the principal-scoped status read still crosses it.
- """
+ """Web Push follows the same temporary unrestricted runtime policy."""
from storage.importer import ensure_sqlite_state
@@ -2871,7 +2941,7 @@ def test_remote_owner_cannot_register_or_test_a_web_push_endpoint(
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-owner"),
+ _org_session_cookie(config, "[email protected]", "user-member"),
domain="alex.avibe.bot",
)
headers = csrf_headers(client, "https://alex.avibe.bot")
@@ -2908,11 +2978,11 @@ def test_remote_owner_cannot_register_or_test_a_web_push_endpoint(
)
for response in (subscribe, test_send, unsubscribe):
- assert response.status_code == 403
- assert response.get_json()["code"] == "remote_execution_disabled"
- assert sent == []
+ assert response.status_code == 200
+ assert len(sent) == 1
+ assert sent[0]["subscription"]["endpoint"] == internal_endpoint
assert status.status_code == 200
- # No endpoint was stored, so the status read reports nothing to send to.
+ # Unsubscribe disables the just-created endpoint before the final status read.
assert status.get_json()["subscription_count"] == 0
@@ -3118,10 +3188,10 @@ def test_remote_show_runtime_write_is_rejected_before_runtime_invocation(
)
assert response.status_code == 403
- assert response.get_json()["code"] == "remote_execution_disabled"
+ assert response.get_json()["error"] == "instance_access_forbidden"
-def test_remote_owner_can_still_read_authorized_session_history(
+def test_active_org_member_can_read_session_history_without_resource_acl(
monkeypatch,
tmp_path,
):
@@ -3161,7 +3231,7 @@ def test_remote_owner_can_still_read_authorized_session_history(
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-owner"),
+ _org_session_cookie(config, "[email protected]", "user-member"),
domain="alex.avibe.bot",
)
response = client.get(
@@ -3176,7 +3246,7 @@ def test_remote_owner_can_still_read_authorized_session_history(
]
-def test_signed_show_page_entitlement_does_not_bypass_session_history_acl(
+def test_show_page_email_session_cannot_read_session_history_api(
monkeypatch,
tmp_path,
):
@@ -3245,12 +3315,8 @@ def test_signed_show_page_entitlement_does_not_bypass_session_history_acl(
"guest-1",
session_claims={
"vibe_instance_id": "inst_123",
- "vibe_instance_role": "editor",
- "vibe_instance_access_source": "organization_group",
- "vibe_organization_id": "org-1",
- "vibe_organization_member_id": "member-guest-1",
- "vibe_organization_role": "member",
- "vibe_group_ids": ["group-sales"],
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "show_page_email",
"vibe_show_page_id": session["id"],
},
),
@@ -3262,11 +3328,11 @@ def test_signed_show_page_entitlement_does_not_bypass_session_history_acl(
environ_base=_remote_peer(),
)
- assert response.status_code == 404
- assert response.get_json() == {"ok": False, "error": "not_found"}
+ assert response.status_code == 403
+ assert response.get_json() == {"ok": False, "error": "show_page_access_forbidden"}
-def test_remote_viewer_can_read_but_cannot_use_management_api(monkeypatch, tmp_path):
+def test_non_org_remote_identity_cannot_use_runtime_apis(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
client = app.test_client()
@@ -3286,42 +3352,29 @@ def test_remote_viewer_can_read_but_cannot_use_management_api(monkeypatch, tmp_p
manage_response = client.get("/api/remote-access/status", base_url="https://alex.avibe.bot")
session_response = client.get("/api/session", base_url="https://alex.avibe.bot")
- assert read_response.status_code == 200
+ assert read_response.status_code == 403
assert manage_response.status_code == 403
assert manage_response.get_json()["error"] == "instance_access_forbidden"
+ assert session_response.status_code == 200
session_payload = session_response.get_json()
- assert session_payload["instance_role"] == "viewer"
- assert session_payload["capabilities"]["can_read_instance"] is True
- assert session_payload["capabilities"]["can_chat"] is False
- assert session_payload["capabilities"]["is_instance_owner"] is False
+ assert session_payload["temporary_unrestricted_org_access"] is False
+ assert session_payload["capabilities"]["can_read_instance"] is False
+ assert session_payload["capabilities"]["can_use_system"] is False
@pytest.mark.parametrize(
- (
- "role",
- "agents_status",
- "skills_status",
- "vault_status",
- "show_pages_status",
- "conversation_status",
- "project_status",
- ),
+ ("role", "organization_role"),
[
- ("viewer", 403, 403, 403, 200, 403, 403),
- ("editor", 200, 200, 200, 200, 400, 403),
- ("owner", 200, 200, 200, 200, 400, 400),
+ ("viewer", "member"),
+ ("editor", "member"),
+ ("owner", "owner"),
],
)
-def test_remote_instance_role_route_matrix(
+def test_active_org_instance_roles_share_temporary_runtime_access(
monkeypatch,
tmp_path,
role,
- agents_status,
- skills_status,
- vault_status,
- show_pages_status,
- conversation_status,
- project_status,
+ organization_role,
):
from storage.importer import ensure_sqlite_state
@@ -3338,7 +3391,13 @@ def test_remote_instance_role_route_matrix(
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, f"{role}@example.com", f"user-{role}", role=role),
+ _org_session_cookie(
+ config,
+ f"{role}@example.com",
+ f"user-{role}",
+ role=role,
+ organization_role=organization_role,
+ ),
domain="alex.avibe.bot",
)
headers = csrf_headers(client, "https://alex.avibe.bot")
@@ -3370,45 +3429,30 @@ def test_remote_instance_role_route_matrix(
)
assert read_response.status_code == 200
- assert agents_response.status_code == agents_status
- assert skills_response.status_code == skills_status
- assert vault_response.status_code == vault_status
- assert show_pages_response.status_code == show_pages_status
+ assert agents_response.status_code == 200
+ assert skills_response.status_code == 200
+ assert vault_response.status_code == 200
+ assert show_pages_response.status_code == 200
assert config_response.status_code == 200
assert prefs_read_response.status_code == 200
assert prefs_read_response.get_json()["background_work_banner_enabled"] is True
- # The prefs record is process-global rather than per-principal, so the read
- # crosses the tunnel for every role while the write stays trusted-local.
- assert prefs_write_response.status_code == 403
- # Role grants an authorized remote operation, not trusted-local visibility.
- # All remote callers receive the same explicit safe config projection.
+ assert prefs_write_response.status_code == 200
+ # Temporary admission keeps the remote identity but exposes the same
+ # runtime configuration fields as local access. Pairing/tunnel identity and
+ # the separately managed Memory block stay outside this generic response.
config_payload = config_response.get_json()
- assert set(config_payload) == {
- "ack_mode",
- "agent_progress_style",
- "capabilities",
- "include_time_info",
- "include_user_info",
- "language",
- "mode",
- "reply_enhancements",
- "setup_state",
- "show_duration",
- "ui",
- "version",
- }
+ assert "runtime" in config_payload
+ assert "agents" in config_payload
+ assert "memory" not in config_payload
+ assert "remote_access" not in config_payload
assert config_payload["ack_mode"] == "reaction"
assert config_payload["show_duration"] is False
assert config_payload["include_time_info"] is False
assert config_payload["include_user_info"] is True
assert config_payload["reply_enhancements"] is False
assert config_payload["agent_progress_style"] == "concise"
- assert conversation_response.status_code == conversation_status
- assert project_response.status_code == project_status
- if role == "viewer":
- assert conversation_response.get_json()["error"] == "instance_access_forbidden"
- if role != "owner":
- assert project_response.get_json()["error"] == "instance_access_forbidden"
+ assert conversation_response.status_code == 400
+ assert project_response.status_code == 400
def _forged_session_cookie(config: V2Config, exp: int, *, email: str = "[email protected]", subject: str = "user-1") -> str:
@@ -3797,7 +3841,13 @@ def test_remote_status_projects_a_remote_safe_payload(monkeypatch, tmp_path):
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-owner"),
+ _org_session_cookie(
+ config,
+ "user-owner",
+ role="owner",
+ organization_role="owner",
+ ),
domain="alex.avibe.bot",
)
@@ -4067,7 +4117,7 @@ def test_remote_config_post_accepts_public_origin_default_https_port(monkeypatch
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ _org_session_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
headers = csrf_headers(client, "https://alex.avibe.bot")
@@ -4090,12 +4140,7 @@ def test_custom_hostname_config_post_accepts_same_origin(monkeypatch, tmp_path):
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_access.make_session_cookie(
- config,
- "user-1",
- session_claims=_oauth_exchange_result(config, nonce="unused")["session_claims"],
- ),
+ _org_session_cookie(config, "[email protected]", "user-1"),
domain="max.fileguard.io",
)
headers = csrf_headers(client, "https://max.fileguard.io")
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index e6087a995..d4d9c3f06 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -41,6 +41,39 @@ from vibe.ui_server import app
from storage import message_deliveries
+def _active_org_cookie(config, email="[email protected]", subject="member-1"):
+ return remote_session_cookie(
+ config,
+ email,
+ subject,
+ role="viewer",
+ access_source="organization_group",
+ organization_id="org-1",
+ organization_member_id=f"membership-{subject}",
+ organization_role="member",
+ group_ids=[],
+ )
+
+
+def _show_page_email_cookie(
+ config,
+ session_id="ses123",
+ subject="viewer-1",
+):
+ return remote_session_cookie(
+ config,
+ email,
+ subject,
+ session_claims={
+ "vibe_instance_id": config.remote_access.vibe_cloud.instance_id,
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "show_page_email",
+ "vibe_show_page_id": session_id,
+ },
+ )
+
+
class _FakeShowRuntimeManager:
def __init__(
self,
@@ -660,7 +693,7 @@ def test_remote_show_page_icon_is_not_persistently_cached(monkeypatch, tmp_path)
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "owner-1"),
+ _active_org_cookie(config, "[email protected]", "owner-1"),
domain="alex.avibe.bot",
)
@@ -675,17 +708,13 @@ def test_remote_show_page_icon_is_not_persistently_cached(monkeypatch, tmp_path)
assert response.headers["Cache-Control"] == "private, no-store"
-def test_remote_show_page_ensure_redacts_local_path(monkeypatch, tmp_path):
+def test_remote_non_org_owner_cannot_ensure_show_page(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
+ calls = []
monkeypatch.setattr(
"vibe.api.ensure_show_page",
- lambda session_id, **_kwargs: {
- "ok": True,
- "existed": False,
- "session_id": session_id,
- "path": "/Users/alex/.avibe/show-pages/ses123",
- },
+ lambda session_id, **_kwargs: calls.append(session_id),
)
client = app.test_client()
client.set_cookie(
@@ -701,8 +730,9 @@ def test_remote_show_page_ensure_redacts_local_path(monkeypatch, tmp_path):
headers=csrf_headers(client, "https://alex.avibe.bot"),
)
- assert response.status_code == 200
- assert response.get_json() == {"ok": True, "existed": False, "session_id": "ses123"}
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "remote_execution_disabled"
+ assert calls == []
def test_show_page_icon_endpoint_enforces_token_without_selecting_the_file(monkeypatch, tmp_path):
@@ -1141,7 +1171,7 @@ def test_public_show_page_injects_auth_aware_annotation_config(monkeypatch, tmp_
if authenticated:
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ _active_org_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
try:
@@ -1784,9 +1814,7 @@ def _screenshot_event(local_path: str) -> dict:
}
-def test_remote_private_show_events_redact_the_local_screenshot_path(monkeypatch, tmp_path):
- # The private Show event surface is remote-readable, so it must project the
- # same way the workbench SSE does: attachment id yes, host path no.
+def test_remote_non_org_owner_cannot_read_private_show_events(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
_create_show_page("ses123", "private")
@@ -1808,11 +1836,8 @@ def test_remote_private_show_events_redact_the_local_screenshot_path(monkeypatch
environ_base=_remote_peer(),
)
- assert response.status_code == 200
- event = response.json()["events"][0]
- assert "path" not in event["payload"]["screenshot"]
- assert event["payload"]["screenshot"]["attachmentId"] == "med_1"
- assert local_path not in event["transcript_text"]
+ assert response.status_code == 401
+ assert response.get_json()["error"] == "remote_access_login_required"
def test_local_private_show_events_keep_the_local_screenshot_path(monkeypatch, tmp_path):
@@ -1850,7 +1875,7 @@ def test_remote_private_show_page_denies_at_fs_workspace_symlink_escape(monkeypa
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "owner-1"),
+ _active_org_cookie(config, "[email protected]", "owner-1"),
domain="alex.avibe.bot",
)
manager = _FakeShowRuntimeManager(body=b"TOPSECRET")
@@ -2128,7 +2153,7 @@ def test_private_show_me_is_always_available(monkeypatch, tmp_path):
assert response.headers["cache-control"] == "no-store, private"
-def test_private_show_page_treats_remote_viewer_as_read_only(monkeypatch, tmp_path):
+def test_private_show_page_treats_show_page_email_viewer_as_read_only(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
_create_agent_session("ses123")
@@ -2153,13 +2178,7 @@ def test_private_show_page_treats_remote_viewer_as_read_only(monkeypatch, tmp_pa
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(
- config,
- "user-viewer",
- role="viewer",
- access_source="email",
- ),
+ _show_page_email_cookie(config, email="[email protected]", subject="user-viewer"),
domain="alex.avibe.bot",
)
try:
@@ -2209,7 +2228,7 @@ def test_public_show_me_accepts_valid_workbench_session(monkeypatch, tmp_path):
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ _active_org_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
@@ -3086,7 +3105,7 @@ def test_private_show_page_records_remote_oauth_author(monkeypatch, tmp_path):
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ _active_org_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
@@ -3112,7 +3131,7 @@ def test_private_show_page_records_remote_oauth_author(monkeypatch, tmp_path):
assert event["message"]["metadata"]["author"] == expected_author
-def test_private_show_page_rejects_remote_dispatch_before_event_store(monkeypatch, tmp_path):
+def test_private_show_page_allows_active_org_dispatch(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
_create_agent_session("ses123")
@@ -3122,15 +3141,16 @@ def test_private_show_page_rejects_remote_dispatch_before_event_store(monkeypatc
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ _active_org_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
- monkeypatch.setattr(
- "vibe.ui_server._show_session_event_store",
- lambda: (_ for _ in ()).throw(
- AssertionError("remote Show dispatch reached the event store")
- ),
- )
+ dispatched = []
+
+ async def accept_dispatch(event):
+ dispatched.append(event)
+ return ui_server._ShowEventDispatchOutcome.ACCEPTED
+
+ monkeypatch.setattr("vibe.ui_server._run_show_event_dispatch", accept_dispatch)
response = client.post(
"/show/ses123/__show/events",
@@ -3147,8 +3167,9 @@ def test_private_show_page_rejects_remote_dispatch_before_event_store(monkeypatc
},
)
- assert response.status_code == 403
- assert response.get_json()["code"] == "remote_execution_disabled"
+ assert response.status_code == 201
+ assert response.get_json()["ok"] is True
+ assert len(dispatched) == 1
def test_private_show_page_accepts_mark_read_receipt_and_records_reader(monkeypatch, tmp_path):
@@ -3175,7 +3196,7 @@ def test_private_show_page_accepts_mark_read_receipt_and_records_reader(monkeypa
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ _active_org_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
response = client.post(
@@ -3254,6 +3275,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.ui_server import _show_events_stream
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
@@ -3279,7 +3301,10 @@ def test_show_events_stream_replays_all_persisted_pages_before_live(monkeypatch,
store.close()
async def _collect_replay() -> str:
- response = await _show_events_stream("ses123")
+ response = await _show_events_stream(
+ "ses123",
+ authorization_context=trusted_local_context(),
+ )
iterator = response.body_iterator.__aiter__()
chunks = []
try:
@@ -3302,6 +3327,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.ui_server import _show_events_stream
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
@@ -3310,7 +3336,10 @@ def test_show_events_stream_forwards_live_dispatch_events(monkeypatch, tmp_path)
_create_show_page("ses123", "private")
async def _collect_live_dispatch() -> str:
- response = await _show_events_stream("ses123")
+ response = await _show_events_stream(
+ "ses123",
+ authorization_context=trusted_local_context(),
+ )
iterator = response.body_iterator.__aiter__()
chunks = []
try:
@@ -3934,7 +3963,7 @@ def test_public_show_page_events_require_share_token(monkeypatch, tmp_path):
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ _active_org_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
@@ -3969,7 +3998,7 @@ def test_public_show_page_events_require_matching_share_referer(monkeypatch, tmp
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ _active_org_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
headers = _public_show_write_headers(share_id)
@@ -3998,7 +4027,7 @@ def test_public_show_page_events_reject_cross_share_token(monkeypatch, tmp_path)
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ _active_org_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
@@ -4022,7 +4051,7 @@ def test_public_show_page_events_reject_token_from_previous_share_owner(monkeypa
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ _active_org_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
@@ -4048,7 +4077,7 @@ def test_public_show_page_events_accept_oauth_user_and_record_author(monkeypatch
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-2"),
+ _active_org_cookie(config, "[email protected]", "user-2"),
domain="alex.avibe.bot",
)
@@ -4097,7 +4126,7 @@ def test_public_show_page_redacts_materialized_screenshot_path(monkeypatch, tmp_
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-2"),
+ _active_org_cookie(config, "[email protected]", "user-2"),
domain="alex.avibe.bot",
)
@@ -4201,7 +4230,7 @@ def test_public_show_page_accepts_mark_read_receipt_and_records_reader(monkeypat
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-2"),
+ _active_org_cookie(config, "[email protected]", "user-2"),
domain="alex.avibe.bot",
)
response = client.post(
@@ -4246,7 +4275,7 @@ def test_public_show_page_rejects_resolution_for_unknown_mark(monkeypatch, tmp_p
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-2"),
+ _active_org_cookie(config, "[email protected]", "user-2"),
domain="alex.avibe.bot",
)
@@ -4281,7 +4310,7 @@ def test_public_show_page_events_accept_injected_share_session_id(monkeypatch, t
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-2"),
+ _active_org_cookie(config, "[email protected]", "user-2"),
domain="alex.avibe.bot",
)
@@ -4310,7 +4339,7 @@ def test_public_show_page_intent_fallback_does_not_expose_author_email(monkeypat
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-2"),
+ _active_org_cookie(config, "[email protected]", "user-2"),
domain="alex.avibe.bot",
)
@@ -4342,7 +4371,7 @@ def test_public_show_page_events_ignore_client_event_id_and_dispatch(monkeypatch
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-2"),
+ _active_org_cookie(config, "[email protected]", "user-2"),
domain="alex.avibe.bot",
)
@@ -4375,7 +4404,7 @@ def test_public_show_page_events_reject_non_human_types(monkeypatch, tmp_path, e
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-2"),
+ _active_org_cookie(config, "[email protected]", "user-2"),
domain="alex.avibe.bot",
)
@@ -5815,7 +5844,7 @@ def test_private_show_page_hmr_websocket_accepts_remote_session(monkeypatch, tmp
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
- remote_session_cookie(config, "[email protected]", "user-1"),
+ _active_org_cookie(config, "[email protected]", "user-1"),
domain="alex.avibe.bot",
)
try:
@@ -5860,18 +5889,30 @@ def test_private_show_page_hmr_websocket_closes_at_authorization_refresh_deadlin
monkeypatch.setattr(
ui_server,
"_show_runtime_websocket_resource_context",
- lambda websocket: resource_access_service.ResourceUserContext(is_trusted_local=True),
+ lambda websocket: resource_access_service.ResourceUserContext(
+ instance_role="viewer",
+ subject="remote-member",
+ instance_access_source="organization_group",
+ organization_id="org-1",
+ organization_member_id="membership-1",
+ organization_role="member",
+ is_remote=True,
+ ),
)
monkeypatch.setattr(
ui_server,
"_remote_access_websocket_session_claims",
lambda websocket, config: {
- "sub": "remote-owner",
- "vibe_instance_role": "owner",
- "vibe_instance_access_source": "owner",
+ "sub": "remote-member",
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "organization_group",
+ "vibe_organization_id": "org-1",
+ "vibe_organization_member_id": "membership-1",
+ "vibe_organization_role": "member",
"claims_issued_at": 1,
},
)
+ monkeypatch.setattr(remote_access, "session_authorization_is_current", lambda *args: True)
monkeypatch.setattr(
remote_access,
"session_authorization_refresh_deadline",
diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsx
index 673b00c93..7a96fd6d6 100644
--- a/ui/src/components/AppShell.test.tsx
+++ b/ui/src/components/AppShell.test.tsx
@@ -31,6 +31,7 @@ const status = vi.hoisted(() => ({ state: 'ready' as const }));
const inbox = vi.hoisted(() => ({ totalUnread: 0 }));
const instanceAuth = vi.hoisted(() => ({
remote: true,
+ hasTemporaryUnrestrictedOrgAccess: true,
hasTemporaryUnrestrictedOrgAppAccess: true,
capabilities: {
can_manage_instance: true,
@@ -47,7 +48,11 @@ const instanceAuth = vi.hoisted(() => ({
vi.mock('../context/ApiContext', () => ({ useApi: () => api }));
vi.mock('../context/StatusContext', () => ({ useStatus: () => ({ status }) }));
vi.mock('../context/WorkbenchInboxContext', () => ({ useWorkbenchInbox: () => inbox }));
-vi.mock('../context/InstanceAuthorizationContext', () => ({ useInstanceAuthorization: () => instanceAuth }));
+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 }) => (
<div data-testid="dock-provider" data-enabled={String(enabled)}>{children}</div>
@@ -64,6 +69,9 @@ vi.mock('./apps/MobileDockDrawer', () => ({
MobileDockDrawer: () => <div data-testid="mobile-dock-drawer" />,
}));
vi.mock('./apps/WindowLayer', () => ({ WindowLayer: () => <div data-testid="window-layer" /> }));
+vi.mock('./workbench/NewSessionSheet', () => ({
+ NewSessionSheet: () => null,
+}));
vi.mock('./workbench/WorkbenchSidebar', () => ({ WorkbenchSidebar: () => <div /> }));
vi.mock('./workbench/search/SearchPalette', () => ({ SearchPalette: () => null }));
vi.mock('react-i18next', () => ({
@@ -72,6 +80,7 @@ vi.mock('react-i18next', () => ({
beforeEach(() => {
instanceAuth.capabilities.can_manage_instance = true;
+ instanceAuth.hasTemporaryUnrestrictedOrgAccess = true;
instanceAuth.hasTemporaryUnrestrictedOrgAppAccess = true;
api.getConfig.mockResolvedValue({ platforms: { enabled: [] } });
api.getMemorySettings.mockResolvedValue({
@@ -99,7 +108,7 @@ describe('AppShell setup recovery', () => {
expect(await screen.findByText('setup.remoteOwner.title')).toBeTruthy();
expect(screen.getByRole('link', { name: 'setup.remoteOwner.action' }).getAttribute('href')).toBe(
- '/admin/settings/messaging',
+ '/admin/dashboard',
);
expect(screen.queryByTestId('wizard')).toBeNull();
});
@@ -130,6 +139,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;
render(
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 7e3af106c..1ad41208b 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -11,7 +11,10 @@ import { memoryNavShouldBeVisible } from '../lib/memorySettings';
import { useApi } from '../context/ApiContext';
import { useStatus } from '../context/StatusContext';
import { useWorkbenchInbox } from '../context/WorkbenchInboxContext';
-import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';
+import {
+ canUseAppsSurface,
+ useInstanceAuthorization,
+} from '../context/InstanceAuthorizationContext';
import { AccountMenu } from './AccountMenu';
import { LanguageSwitcher } from './LanguageSwitcher';
import { ThemeToggle } from './ThemeToggle';
@@ -36,7 +39,7 @@ import { OrganizationShell } from '../features/organization/OrganizationShell';
import {
adminLandingPath,
isAdvancedSettingsPath,
- isLocalSystemPath,
+ isLocalSystemPathForAccess,
isMemorySettingsPath,
} from '../lib/adminNavigation';
@@ -235,7 +238,7 @@ export const AppShell: React.FC = () => {
const {
capabilities,
remote,
- hasTemporaryUnrestrictedOrgAppAccess,
+ hasTemporaryUnrestrictedOrgAccess,
} = useInstanceAuthorization();
const api = useApi();
const location = useLocation();
@@ -265,12 +268,12 @@ export const AppShell: React.FC = () => {
useViewportHeightVar();
useEffect(() => {
- if (!capabilities.can_manage_instance) return;
+ if (!capabilities.can_manage_instance && !hasTemporaryUnrestrictedOrgAccess) return;
api.getConfig().then((c: any) => {
setConfig(c);
setEnabledPlatforms(getEnabledPlatforms(c));
}).catch(() => {});
- }, [api, capabilities.can_manage_instance]);
+ }, [api, capabilities.can_manage_instance, hasTemporaryUnrestrictedOrgAccess]);
useEffect(() => {
const refreshMemoryNav = () => {
@@ -342,7 +345,11 @@ export const AppShell: React.FC = () => {
return <OrganizationShell />;
}
- if (location.pathname === '/setup' && remote && capabilities.can_manage_instance) {
+ if (
+ location.pathname === '/setup' &&
+ remote &&
+ (capabilities.can_manage_instance || hasTemporaryUnrestrictedOrgAccess)
+ ) {
return (
<main className="flex min-h-screen items-center justify-center bg-background p-4 text-foreground">
<Card className="w-full max-w-md">
@@ -353,7 +360,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)}>
+ <Link to={adminLandingPath(capabilities.can_use_system, hasTemporaryUnrestrictedOrgAccess === true)}>
{t('setup.remoteOwner.action')}
</Link>
</Button>
@@ -366,7 +373,8 @@ export const AppShell: React.FC = () => {
const hasChannelPlatforms = enabledPlatforms.some((platform) => platformSupportsChannels(config, platform));
const modelHubEnabled = modelHubEnabledFromConfig(config);
const isRunning = status.state === 'running';
- const canUseApps = !remote || hasTemporaryUnrestrictedOrgAppAccess === true;
+ const canUseApps = canUseAppsSurface(remote, hasTemporaryUnrestrictedOrgAccess);
+ const canUseRuntimeSurfaces = !remote || hasTemporaryUnrestrictedOrgAccess === true;
const ownerOnlyPath =
location.pathname === '/setup' ||
@@ -374,17 +382,19 @@ export const AppShell: React.FC = () => {
['/agents', '/harness'].some(
(path) => location.pathname === path || location.pathname.startsWith(`${path}/`),
);
- // Owner is not enough for these: `can_manage_instance` stays true for a remote
- // Instance owner, but every one of them runs on local-only routes. The list
- // and its rationale live in `isLocalSystemPath` so this redirect and the
- // navigation entries below cannot drift apart.
- const localSystemPath = isLocalSystemPath(location.pathname);
+ // 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 resourceUseDenied =
- (location.pathname.startsWith('/skills') && !capabilities.can_use_skills) ||
- (location.pathname.startsWith('/vaults') && !capabilities.can_use_vault_secrets);
+ (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;
if (
- (ownerOnlyPath && !capabilities.can_manage_instance) ||
+ (ownerOnlyPath && !capabilities.can_manage_instance && !canUseRuntimeSurfaces) ||
(localSystemPath && !capabilities.can_use_system) ||
resourceUseDenied ||
appAccessDenied
@@ -466,18 +476,18 @@ export const AppShell: React.FC = () => {
},
];
- // Second half of the trusted-local gate: a page the redirect above withholds
+ // 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. Recurses into groups (平台凭据 is a child) and drops a
// group left with nothing to open.
const withoutLocalSystemEntries = (navItems: ShellNavItem[]): ShellNavItem[] =>
navItems
- .filter((item) => !item.to || !isLocalSystemPath(item.to))
+ .filter((item) => !item.to || !isLocalSystemPathForAccess(item.to, canUseRuntimeSurfaces))
.map((item) =>
item.children ? { ...item, children: withoutLocalSystemEntries(item.children) } : item,
)
.filter((item) => item.to || item.onClick || (item.children?.length ?? 0) > 0);
- const visibleAdminItems = capabilities.can_use_system
+ const visibleAdminItems = canUseRuntimeSurfaces || capabilities.can_use_system
? adminItems
: withoutLocalSystemEntries(adminItems);
@@ -501,7 +511,7 @@ export const AppShell: React.FC = () => {
match: (pathname) => isAdvancedSettingsPath(pathname, memoryNavVisible),
},
];
- const adminMobileTabs = capabilities.can_use_system
+ const adminMobileTabs = canUseRuntimeSurfaces || capabilities.can_use_system
? adminMobileTabsAll
: withoutLocalSystemEntries(adminMobileTabsAll);
// The More sheet shows the overflow: admin sections not already on the bottom
@@ -522,8 +532,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 ? [{
- to: capabilities.can_manage_agents ? '/agents' : capabilities.can_use_skills ? '/skills' : '/vaults',
+ ...(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',
label: t('nav.capabilities'),
icon: LayoutGrid,
match: (p: string) => ['/agents', '/skills', '/harness', '/vaults'].some((x) => p.startsWith(x)),
@@ -639,9 +649,9 @@ export const AppShell: React.FC = () => {
<Building2 className="size-[18px] text-muted group-hover:text-foreground" />
</Link>
)}
- {shellMode === 'workbench' && capabilities.can_manage_instance && (
+ {shellMode === 'workbench' && (capabilities.can_manage_instance || canUseRuntimeSurfaces) && (
<Link
- to={adminLandingPath(capabilities.can_use_system)}
+ to={adminLandingPath(capabilities.can_use_system, canUseRuntimeSurfaces)}
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]"
@@ -694,7 +704,7 @@ export const AppShell: React.FC = () => {
/>
{isRunning ? t('common.running') : t('common.stopped')}
</span>
- {capabilities.can_manage_instance && <VersionBadge openUpward />}
+ {(capabilities.can_manage_instance || canUseRuntimeSurfaces) && <VersionBadge openUpward />}
</div>
</div>
</div>
@@ -768,7 +778,7 @@ export const AppShell: React.FC = () => {
) : (
<MobileTabBar
items={workbenchTabs}
- center={capabilities.can_chat
+ center={(capabilities.can_chat || canUseRuntimeSurfaces)
? { onClick: () => setNewSessionOpen(true), label: t('appShell.newSession'), icon: Plus }
: undefined}
/>
@@ -815,7 +825,7 @@ export const AppShell: React.FC = () => {
<MobileDockDrawer open={appsDrawerOpen} onClose={() => setAppsDrawerOpen(false)} />
)}
- {capabilities.can_chat && (
+ {(capabilities.can_chat || canUseRuntimeSurfaces) && (
<NewSessionSheet
open={newSessionOpen}
onClose={() => setNewSessionOpen(false)}
diff --git a/ui/src/components/Workbench.tsx b/ui/src/components/Workbench.tsx
index d25ace947..8f68d6b83 100644
--- a/ui/src/components/Workbench.tsx
+++ b/ui/src/components/Workbench.tsx
@@ -8,7 +8,10 @@ import { NewProjectDialog } from './workbench/NewProjectDialog';
import { Composer } from './workbench/Composer';
import { ProjectPicker } from './workbench/ProjectPicker';
import { AgentRoutePicker } from './workbench/AgentRoutePicker';
-import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';
+import {
+ canUseRuntimeSurfaces,
+ useInstanceAuthorization,
+} from '../context/InstanceAuthorizationContext';
import { canCreateLocalProject } from '../lib/sessionInfo';
// Mirrors design.pen DnkGJ "Workbench" canvas: a centered hero panel +
@@ -21,10 +24,15 @@ import { canCreateLocalProject } from '../lib/sessionInfo';
export const Workbench: React.FC = () => {
const { t } = useTranslation();
const navigate = useNavigate();
- const { capabilities } = useInstanceAuthorization();
- const canCreateProject = canCreateLocalProject(capabilities);
+ const {
+ capabilities,
+ remote,
+ hasTemporaryUnrestrictedOrgAccess,
+ } = useInstanceAuthorization();
+ const canUseRuntime = canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess);
+ const canCreateProject = canUseRuntime || canCreateLocalProject(capabilities);
const ns = useNewSession({
- active: capabilities.can_chat,
+ active: capabilities.can_chat || canUseRuntime,
loadErrorText: t('newSession.loadError'),
createFailedText: t('newSession.createFailed'),
});
@@ -50,15 +58,15 @@ export const Workbench: React.FC = () => {
...(canCreateProject
? [{ key: 'newProject', icon: FolderPlus, onClick: () => setNewProjectOpen(true) }]
: []),
- ...(capabilities.can_manage_agents
+ ...(capabilities.can_manage_agents || canUseRuntime
? [{ key: 'openAgents', icon: Bot, onClick: () => navigate('/agents') }]
: []),
- ...(capabilities.can_manage_instance
+ ...(capabilities.can_manage_instance || canUseRuntime
? [{ key: 'openHarness', icon: Activity, onClick: () => navigate('/harness') }]
: []),
];
- if (!capabilities.can_chat) return <Navigate to="/projects" replace />;
+ if (!capabilities.can_chat && !canUseRuntime) 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 710972055..3ae37e91b 100644
--- a/ui/src/components/settings/SettingsMemoryPage.test.tsx
+++ b/ui/src/components/settings/SettingsMemoryPage.test.tsx
@@ -259,8 +259,8 @@ describe('SettingsMemoryPage disabled recorder health', () => {
});
describe('SettingsMemoryPage remote administration gate', () => {
- // A remote Instance owner keeps `can_manage_instance`, so only the locality
- // half of the gate can keep the local-only administration routes off screen.
+ // A legacy remote Instance owner without active Organization membership is
+ // outside the temporary runtime rollout even when its owner capability is set.
const renderRemoteOwner = () =>
render(
<MemoryRouter>
@@ -276,7 +276,23 @@ describe('SettingsMemoryPage remote administration gate', () => {
</MemoryRouter>,
);
- it('hides the admin log, the settings tab and the engine restart from a remote owner', async () => {
+ const renderActiveOrgMember = () =>
+ render(
+ <MemoryRouter>
+ <InstanceAuthorizationContext.Provider
+ value={{
+ remote: true,
+ instanceRole: 'viewer',
+ hasTemporaryUnrestrictedOrgAccess: true,
+ capabilities: DENIED_INSTANCE_CAPABILITIES,
+ }}
+ >
+ <SettingsMemoryPage />
+ </InstanceAuthorizationContext.Provider>
+ </MemoryRouter>,
+ );
+
+ it('hides runtime administration from a remote non-member', async () => {
renderRemoteOwner();
expect(await screen.findByRole('radio', { name: 'memory.tabs.status' })).toBeTruthy();
@@ -286,6 +302,16 @@ describe('SettingsMemoryPage remote administration gate', () => {
expect(screen.queryByRole('button', { name: 'memory.status.restartEngine' })).toBeNull();
});
+ it('shows all Memory administration controls to an active Organization member', async () => {
+ api.getMemoryStatus.mockResolvedValue(readyStatus());
+
+ renderActiveOrgMember();
+
+ expect(await screen.findByRole('radio', { name: 'memory.tabs.log' })).toBeTruthy();
+ expect(screen.getByRole('radio', { name: 'memory.tabs.settings' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'memory.status.restartEngine' })).toBeTruthy();
+ });
+
it('replaces the remote setup flow with the unavailable notice', async () => {
api.getMemorySettings.mockResolvedValue({
status: 'ok',
@@ -299,7 +325,7 @@ describe('SettingsMemoryPage remote administration gate', () => {
expect(screen.queryByRole('radio', { name: 'memory.tabs.status' })).toBeNull();
});
- it('derives profile/search enablement from the permitted status read when settings stay local-only', async () => {
+ it('derives profile/search enablement from the permitted status read for a remote non-member', async () => {
api.getMemorySettings.mockResolvedValue({
status: 'failed',
error: 'remote_execution_disabled',
diff --git a/ui/src/components/settings/SettingsMemoryPage.tsx b/ui/src/components/settings/SettingsMemoryPage.tsx
index cd8ba37b5..502ec2192 100644
--- a/ui/src/components/settings/SettingsMemoryPage.tsx
+++ b/ui/src/components/settings/SettingsMemoryPage.tsx
@@ -43,10 +43,11 @@ export const SettingsMemoryPage: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
- const { remote } = useInstanceAuthorization();
- // The admin log, the settings save and clear / runtime-restart are local-only
- // in the remote HTTP policy; status, profile and search stay remote-permitted.
- const canAdminister = canAdministerMemory({ remote });
+ const { remote, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
+ const canAdminister = canAdministerMemory({
+ remote,
+ temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
+ });
const [tab, setTab] = useState<MemoryTab>('status');
const [clearOpen, setClearOpen] = useState(false);
@@ -75,12 +76,13 @@ export const SettingsMemoryPage: React.FC = () => {
const { reload: loadFailures, reloadIfIdle: pollFailures } = failuresRead;
const settings = settingsRead.data;
const status = statusRead.data;
- // Forbidden is the backend's "this is not a direct-loopback browser" verdict, and it is
- // sticky per resource, so the static state never flickers away on a later request.
+ // Forbidden means the current identity is outside the admitted runtime
+ // policy. It is sticky per resource, so the static state never flickers away
+ // on a later request.
const remoteUnavailable = settingsRead.forbidden || statusRead.forbidden || failuresRead.forbidden;
- // `settings` is local-only, so remote owners derive the broad enablement bit
- // from the permitted status read instead of letting profile/search stay
- // permanently "disabled" just because the settings payload is absent.
+ // A remote identity outside the temporary active-member rollout may still
+ // receive the permitted status read, so derive broad enablement from it when
+ // the settings payload is absent.
const memoryEnabled = settings?.enabled ?? (statusRead.loaded && status ? status.state !== 'disabled' : false);
// Dependency readiness comes from the authoritative Dependencies source (plan §5), NOT the
diff --git a/ui/src/components/settings/SettingsMessagingPage.test.tsx b/ui/src/components/settings/SettingsMessagingPage.test.tsx
index 0e89d4934..197d34d04 100644
--- a/ui/src/components/settings/SettingsMessagingPage.test.tsx
+++ b/ui/src/components/settings/SettingsMessagingPage.test.tsx
@@ -65,6 +65,12 @@ const remoteOwner: InstanceAuthorizationValue = {
},
};
+const activeOrgMember: InstanceAuthorizationValue = {
+ ...remoteOwner,
+ instanceRole: 'viewer',
+ hasTemporaryUnrestrictedOrgAccess: true,
+};
+
function renderPage(context: InstanceAuthorizationValue) {
return render(
<InstanceAuthorizationContext.Provider value={context}>
@@ -104,4 +110,12 @@ describe('SettingsMessagingPage locality gating', () => {
expect(screen.getByText('dashboard.opencodeActiveTurnTimeout')).toBeTruthy();
expect(screen.getByText('dashboard.showPagesPrompt')).toBeTruthy();
});
+
+ it('shows every runtime messaging control to an active Organization member', async () => {
+ renderPage(activeOrgMember);
+
+ expect(await screen.findByText('dashboard.errorRetryLimit')).toBeTruthy();
+ expect(screen.getByText('dashboard.opencodeActiveTurnTimeout')).toBeTruthy();
+ expect(screen.getByText('dashboard.showPagesPrompt')).toBeTruthy();
+ });
});
diff --git a/ui/src/components/settings/SettingsMessagingPage.tsx b/ui/src/components/settings/SettingsMessagingPage.tsx
index d6c669ff7..27ce8114c 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 } = useInstanceAuthorization();
- const canUseSystem = capabilities.can_use_system;
+ const { capabilities, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
+ const canUseSystem = capabilities.can_use_system || hasTemporaryUnrestrictedOrgAccess === true;
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/settings/memory/MemoryStatusPanel.tsx b/ui/src/components/settings/memory/MemoryStatusPanel.tsx
index 55be1a438..a06591635 100644
--- a/ui/src/components/settings/memory/MemoryStatusPanel.tsx
+++ b/ui/src/components/settings/memory/MemoryStatusPanel.tsx
@@ -49,8 +49,8 @@ export const MemoryStatusPanel: React.FC<{
loading: boolean;
error: string | null;
onRefresh: () => void;
- /** Absent when the viewer cannot administer Memory (remote), which hides the
- * credential fault's settings shortcut. */
+ /** Absent when the current runtime policy cannot administer Memory, which
+ * hides the credential fault's settings shortcut. */
onOpenSettings?: () => void;
}> = ({
status,
diff --git a/ui/src/components/ui/vault-approval-card.tsx b/ui/src/components/ui/vault-approval-card.tsx
index 8a343e16d..41f2f98aa 100644
--- a/ui/src/components/ui/vault-approval-card.tsx
+++ b/ui/src/components/ui/vault-approval-card.tsx
@@ -116,7 +116,7 @@ export const VaultApprovalCard: React.FC<{
const { t } = useTranslation();
const api = useApi();
const vault = useProtectedVault();
- const { remote } = useInstanceAuthorization();
+ const { remote, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
// The request is passed in already hydrated by the UI-audience inbox list
// (`getVaultRequests`, #708), so `card.secret_unlock_material` /
@@ -360,12 +360,10 @@ export const VaultApprovalCard: React.FC<{
);
}
- // Approve / deny / sign all drive local-only Vault routes, and
- // `can_manage_instance` stays true for a remote Instance owner, so a remote
- // approver would only reach `remote_execution_disabled`. Show the request
- // read-only there instead — this card also renders inside the chat transcript,
- // which a remote viewer can read.
- const canApprove = canManageVaultSecrets({ remote });
+ const canApprove = canManageVaultSecrets({
+ remote,
+ temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
+ });
const approveDisabled = busy || !canApprove || (!isSign && !option);
return (
diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsx
index c2cce4fa4..12c197a79 100644
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@ -33,7 +33,10 @@ import type {
VibeAgentOnboardingResult,
VibeAgentUpdatePayload,
} from '../../context/ApiContext';
-import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
+import {
+ canUseRuntimeSurfaces,
+ useInstanceAuthorization,
+} from '../../context/InstanceAuthorizationContext';
import { AgentGraphTab } from './AgentGraphTab';
import { useToast } from '../../context/ToastContext';
import { NewAgentDialog } from './NewAgentDialog';
@@ -79,7 +82,12 @@ export const AgentsPage: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
- const { capabilities, remote } = useInstanceAuthorization();
+ 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
@@ -118,15 +126,15 @@ 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 ? (['definitions'] as const) : AGENTS_TAB_ORDER;
- const activeTab = remote ? 'definitions' : agentsTab;
- // Every Agent editor control is local-only; remote instances get a read-only
- // catalog. Organization onboarding stays available — it is separately
- // permitted by the remote policy.
- const canEditAgents = canEditAgentDefinitions({ remote });
+ const visibleTabs = remote && !canUseRuntime ? (['definitions'] as const) : AGENTS_TAB_ORDER;
+ const activeTab = remote && !canUseRuntime ? 'definitions' : agentsTab;
+ const canEditAgents = canEditAgentDefinitions({
+ remote,
+ temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
+ });
const refreshOnboarding = useCallback(async () => {
- if (!capabilities.can_manage_agents) {
+ if (!capabilities.can_manage_agents && !canUseRuntime) {
setOnboardingInventory(null);
return;
}
@@ -136,7 +144,7 @@ export const AgentsPage: React.FC = () => {
} catch {
setOnboardingInventory(null);
}
- }, [api, capabilities.can_manage_agents]);
+ }, [api, capabilities.can_manage_agents, canUseRuntime]);
const refresh = useCallback(async () => {
setLoading(true);
@@ -184,7 +192,7 @@ export const AgentsPage: React.FC = () => {
}, [selected]);
const fetchRunningActiveCount = useCallback(async () => {
- if (remote) {
+ if (remote && !canUseRuntime) {
setRunningActiveCount(null);
return;
}
@@ -202,7 +210,7 @@ export const AgentsPage: React.FC = () => {
} catch {
setRunningActiveCount(null);
}
- }, [api, remote]);
+ }, [api, canUseRuntime, remote]);
// Keep the badge fresh on every tab (including 运行) so it never depends on
// the graph view's filters.
@@ -211,7 +219,7 @@ export const AgentsPage: React.FC = () => {
}, [fetchRunningActiveCount]);
useEffect(() => {
- if (remote) {
+ if (remote && !canUseRuntime) {
setEventBridgeConnected(false);
return;
}
@@ -233,10 +241,10 @@ export const AgentsPage: React.FC = () => {
onSessionStatus: () => fetchRunningActiveCount(),
onAuthorizationChanged: () => void refresh(),
});
- }, [api, fetchRunningActiveCount, refresh, remote]);
+ }, [api, canUseRuntime, fetchRunningActiveCount, refresh, remote]);
useEffect(() => {
- if (remote) return;
+ if (remote && !canUseRuntime) 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),
@@ -286,7 +294,7 @@ export const AgentsPage: React.FC = () => {
document.removeEventListener('visibilitychange', refreshNow);
window.removeEventListener('focus', refreshNow);
};
- }, [eventBridgeConnected, fetchRunningActiveCount, remote]);
+ }, [canUseRuntime, eventBridgeConnected, fetchRunningActiveCount, remote]);
const selectAgent = useCallback(
async (name: string, openDetail = false) => {
@@ -501,8 +509,8 @@ export const AgentsPage: React.FC = () => {
})}
</div>
- {/* The run graph is a trusted-local process diagnostic. */}
- {!remote && activeTab === 'running' && <AgentGraphTab />}
+ {/* The run graph follows the temporary Organization runtime policy. */}
+ {(!remote || canUseRuntime) && activeTab === 'running' && <AgentGraphTab />}
{activeTab === 'definitions' && onboardingInventory && (
<OrganizationAgentOnboarding
@@ -1155,9 +1163,9 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, on
</div>
</Field>
- {/* Model — Combobox with chevron + searchable + custom values. Remote
- instances get the same value as a locked chip (the Backend field's
- read-only treatment) because the update endpoint is local-only. */}
+ {/* Model — Combobox with chevron + searchable + custom values. Callers
+ outside the current runtime policy get the Backend field's locked
+ treatment. */}
<Field label={t('agents.detail.model')}>
{!canEdit ? (
<div className="flex items-center gap-2 rounded-lg border border-border bg-surface-3 px-3 py-2">
@@ -1252,8 +1260,7 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, on
</span>
</button>
{/* Expand into the full editor modal (large input + Markdown
- edit/preview) — the shared EditorDialog primitive. The editor
- saves, so it stays local-only. */}
+ edit/preview) — the shared EditorDialog primitive. */}
{canEdit && (
<Button
type="button"
diff --git a/ui/src/components/workbench/CapabilityTabs.test.tsx b/ui/src/components/workbench/CapabilityTabs.test.tsx
index 280e0f773..3276f5f63 100644
--- a/ui/src/components/workbench/CapabilityTabs.test.tsx
+++ b/ui/src/components/workbench/CapabilityTabs.test.tsx
@@ -31,16 +31,14 @@ describe('CapabilityTabs', () => {
expect(markup).toContain('workbench.modules.harness.title');
});
- it('hides the Harness tab from a remote owner even though can_manage_agents is true', () => {
- // A remote Instance owner keeps can_manage_agents, which is exactly why the
- // Harness tab needs the trusted-local canUseHarness predicate on top of it:
- // without it the tab navigates into the AppShell local-only redirect.
+ it('shows the Harness tab for an active Organization member', () => {
const remoteOwner: InstanceAuthorizationValue = {
...localOwner,
remote: true,
+ hasTemporaryUnrestrictedOrgAccess: true,
};
const markup = renderWith(remoteOwner);
expect(markup).toContain('workbench.modules.agents.title');
- expect(markup).not.toContain('workbench.modules.harness.title');
+ expect(markup).toContain('workbench.modules.harness.title');
});
});
diff --git a/ui/src/components/workbench/CapabilityTabs.tsx b/ui/src/components/workbench/CapabilityTabs.tsx
index a78532de1..48e300810 100644
--- a/ui/src/components/workbench/CapabilityTabs.tsx
+++ b/ui/src/components/workbench/CapabilityTabs.tsx
@@ -3,7 +3,10 @@ import { NavLink, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Activity, Bot, KeyRound, WandSparkles } from 'lucide-react';
import clsx from 'clsx';
-import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
+import {
+ canUseRuntimeSurfaces,
+ useInstanceAuthorization,
+} from '../../context/InstanceAuthorizationContext';
import { canUseHarness } from '../../lib/remoteAuth';
const TABS = [
@@ -21,17 +24,21 @@ export const CapabilityTabs: React.FC = () => {
const { t } = useTranslation();
const { pathname } = useLocation();
const activeTabRef = useRef<HTMLAnchorElement | null>(null);
- const { capabilities, remote } = useInstanceAuthorization();
+ const {
+ capabilities,
+ remote,
+ hasTemporaryUnrestrictedOrgAccess,
+ } = useInstanceAuthorization();
+ const canUseRuntime = canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess);
const tabs = TABS.filter(({ to }) => {
- // Harness is the exception to the owner check: its page opens entirely on
- // local-only routes (`/api/harness/bootstrap`), so `can_manage_agents`
- // (which stays true for a remote owner) would navigate a remote owner into
- // the AppShell local-only redirect. The trusted-local `canUseHarness`
- // predicate keeps the tab local-only, matching the desktop sidebar.
- if (to === '/harness') return capabilities.can_manage_agents && canUseHarness({ remote });
- if (to === '/agents') return capabilities.can_manage_agents;
- if (to === '/skills') return capabilities.can_use_skills;
- if (to === '/vaults') return capabilities.can_use_vault_secrets;
+ 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;
return false;
});
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 43311bed1..03d37f4f8 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -9,7 +9,11 @@ import { useApi } from '../../context/ApiContext';
import { selectApiErrorFields } from '../../context/apiErrorParse';
import { useToast } from '../../context/ToastContext';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
-import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
+import {
+ canUseAppsSurface,
+ canUseRuntimeSurfaces,
+ 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';
@@ -216,19 +220,24 @@ export const ChatPage: React.FC = () => {
// true })) — a general signal that this navigation must leave Show Page mode.
const showChatSignal = searchParams.get('view') === 'chat';
const api = useApi();
- const { capabilities } = useInstanceAuthorization();
+ const {
+ capabilities,
+ remote,
+ hasTemporaryUnrestrictedOrgAccess,
+ } = useInstanceAuthorization();
const [sessionCanChat, setSessionCanChat] = useState(false);
- const canChat = capabilities.can_chat && sessionCanChat;
- // Show Page resource ACLs are temporarily disabled for remote Organization
- // members (avibe#1313). The existing role-level Show Pages capability is
- // sufficient here; Apps availability must never depend on can_use_system.
- const canManageShowPageAsInstance = capabilities.can_use_show_pages;
+ 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 [showPageAccessResult, setShowPageAccessResult] = useState<{
sessionId: string;
probe: ShowPageAccessProbe;
} | null>(null);
const showPageAccessProbeGenerationRef = useRef(0);
- const currentShowPageAccessProbe = capabilities.can_use_show_pages
+ const currentShowPageAccessProbe = canManageShowPageAsInstance
&& showPageAccessResult?.sessionId === sessionId
? showPageAccessResult?.probe ?? null
: null;
@@ -382,12 +391,12 @@ export const ChatPage: React.FC = () => {
}
}, [api]);
useEffect(() => {
- if (!sessionId || !capabilities.can_use_show_pages) return undefined;
+ if (!sessionId || !canManageShowPageAsInstance) return undefined;
void probeShowPageAccess(sessionId);
return () => {
showPageAccessProbeGenerationRef.current += 1;
};
- }, [capabilities.can_use_show_pages, probeShowPageAccess, sessionId]);
+ }, [canManageShowPageAsInstance, probeShowPageAccess, sessionId]);
// The mounted Show Page frame, so parent-level chords can also be bound inside
// its document (see the ⌘⇧D effect). Stable callback + ref, never state: a ref
// callback that set state would re-create itself on every commit and re-attach
@@ -2683,7 +2692,7 @@ export const ChatPage: React.FC = () => {
showPageAccess={showPageAccess}
canOpenShowPage={canOpenShowPage}
canManageShowPage={canManageShowPage}
- canManageInstance={capabilities.can_manage_instance}
+ canManageInstance={capabilities.can_manage_instance || canUseRuntime}
sessionActions={sessionActions}
titleFieldRef={titleFieldRef}
/>
@@ -2770,7 +2779,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 ? (
+ sessionId && !readOnly && (capabilities.can_manage_instance || canUseRuntime) ? (
<VaultChatRequests
requests={transcriptTailVaultRequests}
onResolved={refreshVaultRequests}
@@ -2791,7 +2800,7 @@ export const ChatPage: React.FC = () => {
{writable && (
<QueueStrip queue={queue} onRemove={removeQueued} onRecall={recallQueued} onSendNow={sendQueueNow} />
)}
- {sessionId && !readOnly && capabilities.can_manage_instance && pendingApprovals.length > 0 ? (
+ {sessionId && !readOnly && (capabilities.can_manage_instance || canUseRuntime) && 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 efd79da93..79a53163c 100644
--- a/ui/src/components/workbench/InboxPage.tsx
+++ b/ui/src/components/workbench/InboxPage.tsx
@@ -22,7 +22,12 @@ import {
export const InboxPage: React.FC = () => {
const { t } = useTranslation();
const navigate = useNavigate();
- const { capabilities } = useInstanceAuthorization();
+ const {
+ capabilities,
+ remote,
+ hasTemporaryUnrestrictedOrgAccess,
+ } = useInstanceAuthorization();
+ const canUseRuntime = !remote || hasTemporaryUnrestrictedOrgAccess === true;
const {
inboxSessions,
unreadBySession,
@@ -189,8 +194,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 && <WebPushControl />}
- {capabilities.can_chat && (
+ {(capabilities.can_manage_instance || canUseRuntime) && <WebPushControl />}
+ {(capabilities.can_chat || canUseRuntime) && (
<button
type="button"
onClick={onMarkAllRead}
@@ -292,7 +297,7 @@ export const InboxPage: React.FC = () => {
{t('workbench.inbox.openSession')}
<ArrowRight className="size-3" />
</button>
- {capabilities.can_chat && unread > 0 && (
+ {(capabilities.can_chat || canUseRuntime) && 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 62b4c659a..d771cb8f7 100644
--- a/ui/src/components/workbench/ProjectPicker.tsx
+++ b/ui/src/components/workbench/ProjectPicker.tsx
@@ -4,7 +4,10 @@ import clsx from 'clsx';
import type { WorkbenchProject } from '../../context/ApiContext';
import { Button } from '../ui/button';
-import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
+import {
+ canUseRuntimeSurfaces,
+ useInstanceAuthorization,
+} from '../../context/InstanceAuthorizationContext';
import { canCreateLocalProject } from '../../lib/sessionInfo';
interface ProjectPickerProps {
@@ -22,8 +25,14 @@ interface ProjectPickerProps {
// reachable) plus a New Project chip; the active chip is the resolved target.
export const ProjectPicker: React.FC<ProjectPickerProps> = ({ projects, targetId, onSelect, onNewProject, disabled }) => {
const { t } = useTranslation();
- const { capabilities } = useInstanceAuthorization();
- const canCreateProject = canCreateLocalProject(capabilities);
+ const {
+ capabilities,
+ remote,
+ hasTemporaryUnrestrictedOrgAccess,
+ } = useInstanceAuthorization();
+ const canCreateProject =
+ canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess) ||
+ 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 5a0fedc3f..3b4b44fef 100644
--- a/ui/src/components/workbench/ProjectSettingsDialog.tsx
+++ b/ui/src/components/workbench/ProjectSettingsDialog.tsx
@@ -5,7 +5,10 @@ import { FileText } from 'lucide-react';
import { useApi } from '../../context/ApiContext';
import type { ProjectDefaultAgent, VibeAgentBrief, WorkbenchProject } from '../../context/ApiContext';
-import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
+import {
+ canUseRuntimeSurfaces,
+ useInstanceAuthorization,
+} from '../../context/InstanceAuthorizationContext';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
import { Button } from '../ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../ui/dialog';
@@ -31,14 +34,17 @@ export const ProjectSettingsDialog: React.FC<{
const { t } = useTranslation();
const api = useApi();
const { setProjectDefaultAgent } = useWorkbenchProjectsTree();
- const { capabilities, remote } = useInstanceAuthorization();
- // Reading and saving AGENTS.md are both local-only, so the shortcut is only
- // offered where the editor can actually load the file.
- const canEditAgentsMd = capabilities.can_manage_projects && canEditProjectInstructions({ remote });
- // The remote project PATCH filter keeps only `display_name`, so every pick the
- // route picker persists would dead-end in `remote_execution_disabled`; the
- // section is offered only where it can actually save.
- const canEditDefaultAgent = capabilities.can_manage_projects && canEditProjectDefaultAgent({ remote });
+ 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 [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 cfb5f0f3d..11a722f50 100644
--- a/ui/src/components/workbench/ProjectsPage.tsx
+++ b/ui/src/components/workbench/ProjectsPage.tsx
@@ -21,7 +21,10 @@ import clsx from 'clsx';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
-import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
+import {
+ canUseRuntimeSurfaces,
+ useInstanceAuthorization,
+} from '../../context/InstanceAuthorizationContext';
import type { ProjectSessionsState } from '../../context/WorkbenchProjectsContext';
import type { WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
import { formatRelativeTime } from '../../lib/relativeTime';
@@ -82,14 +85,17 @@ const MobileProjectRow: React.FC<{
}> = ({ project, open, state, onToggle }) => {
const { t } = useTranslation();
const navigate = useNavigate();
- const { capabilities, remote } = useInstanceAuthorization();
- // Rename and the Project settings are remote-permitted; archiving is not
- // (`DELETE /api/projects/{id}` is local-only) even though
- // `can_manage_projects` stays true for a remote Instance owner.
- const canArchive = capabilities.can_manage_projects && canArchiveProjects({ remote });
- // Reading a project's AGENTS.md is remote-permitted but saving it is not, and
- // this surface is an editor with no read-only mode, so it stays local.
- const canEditAgentsMd = capabilities.can_manage_projects && canEditProjectInstructions({ remote });
+ 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 { renameProject, archiveProject, createSessionForProject } = useWorkbenchProjectsTree();
const [menuOpen, setMenuOpen] = useState(false);
// Guards against a double-tap creating two sessions before navigation unmounts.
@@ -102,7 +108,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 && project.capabilities.can_chat;
+ const canChat = (capabilities.can_chat || canUseRuntime) && (canUseRuntime || project.capabilities.can_chat);
useEffect(() => {
if (renaming) inputRef.current?.focus();
@@ -167,7 +173,7 @@ const MobileProjectRow: React.FC<{
)}
{open ? <ChevronDown className="size-4 shrink-0 text-muted" /> : <ChevronRight className="size-4 shrink-0 text-muted" />}
</button>
- {(canChat || capabilities.can_manage_projects) && <Popover open={menuOpen} onOpenChange={setMenuOpen}>
+ {(canChat || canManageProjects) && <Popover open={menuOpen} onOpenChange={setMenuOpen}>
<PopoverTrigger asChild>
<Button
type="button"
@@ -199,7 +205,7 @@ const MobileProjectRow: React.FC<{
>
{t('newSession.title')}
</MenuItem>}
- {capabilities.can_manage_projects && <>
+ {canManageProjects && <>
<MenuItem
icon={Pencil}
onClick={() => {
@@ -247,7 +253,7 @@ const MobileProjectRow: React.FC<{
</PopoverContent>
</Popover>}
</div>
- {capabilities.can_manage_projects && (
+ {canManageProjects && (
<>
<ProjectSettingsDialog project={project} open={settingsOpen} onClose={() => setSettingsOpen(false)} />
<ProjectAgentsMdDialog project={project} open={agentsOpen} onClose={() => setAgentsOpen(false)} />
@@ -383,8 +389,13 @@ const MobileSessionRow: React.FC<{
export const ProjectsPage: React.FC = () => {
const { t } = useTranslation();
const navigate = useNavigate();
- const { capabilities } = useInstanceAuthorization();
- const canCreateProject = canCreateLocalProject(capabilities);
+ const {
+ capabilities,
+ remote,
+ hasTemporaryUnrestrictedOrgAccess,
+ } = useInstanceAuthorization();
+ const canUseRuntime = canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess);
+ const canCreateProject = canUseRuntime || canCreateLocalProject(capabilities);
const { unreadBySession } = useWorkbenchInbox();
const {
projects,
@@ -494,8 +505,8 @@ export const ProjectsPage: React.FC = () => {
projectId={project.id}
session={session}
unread={unreadBySession[session.id] ?? 0}
- canChat={capabilities.can_chat && project.capabilities.can_chat}
- canManageMetadata={project.capabilities.can_chat}
+ canChat={(capabilities.can_chat || canUseRuntime) && (canUseRuntime || project.capabilities.can_chat)}
+ canManageMetadata={canUseRuntime || 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 df3d254e2..8713c1b4d 100644
--- a/ui/src/components/workbench/SkillsPage.tsx
+++ b/ui/src/components/workbench/SkillsPage.tsx
@@ -20,7 +20,10 @@ import { BrowseRegistryDialog } from './skills/BrowseRegistryDialog';
import { errorMessage } from '@/lib/errorMessage';
import { Badge } from '../ui/badge';
import { canManageSkills } from '../../lib/remoteAuth';
-import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
+import {
+ canUseRuntimeSurfaces,
+ useInstanceAuthorization,
+} from '../../context/InstanceAuthorizationContext';
const skillKey = (s: SkillBrief) => `${s.scope}:${s.name}`;
@@ -28,12 +31,14 @@ export const SkillsPage: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
- const { capabilities, remote } = useInstanceAuthorization();
- // `can_manage_instance` stays true for a remote Instance owner, but every Skill
- // mutation (add / upload / registry search / dependency install / update /
- // remove) and the `askill` update check are local-only, so a remote viewer gets
- // the read-only catalog `GET /api/skills` already permits.
- const canManage = capabilities.can_manage_instance && canManageSkills({ remote });
+ const { capabilities, remote, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
+ const canUseRuntime = canUseRuntimeSurfaces(remote, hasTemporaryUnrestrictedOrgAccess);
+ const canManage =
+ (capabilities.can_manage_instance || canUseRuntime) &&
+ canManageSkills({
+ remote,
+ temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
+ });
const [scope, setScope] = useState<SkillScope>('global');
const [projects, setProjects] = useState<WorkbenchProject[]>([]);
@@ -301,7 +306,7 @@ export const SkillsPage: React.FC = () => {
{t('skills.addSkill')}
</Button>
</>
- ) : remote ? (
+ ) : remote && !canUseRuntime ? (
<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 75516cd28..0672cd2cd 100644
--- a/ui/src/components/workbench/VaultsPage.test.tsx
+++ b/ui/src/components/workbench/VaultsPage.test.tsx
@@ -27,6 +27,18 @@ const remoteOwner = {
},
};
+const activeOrgMember = {
+ remote: true,
+ instanceRole: 'viewer' as const,
+ hasTemporaryUnrestrictedOrgAccess: true,
+ capabilities: {
+ ...OWNER_INSTANCE_CAPABILITIES,
+ can_manage_instance: false,
+ can_use_vault_secrets: false,
+ can_use_system: false,
+ },
+};
+
vi.mock('../../context/ApiContext', async (loadOriginal) => {
const original = await loadOriginal<typeof import('../../context/ApiContext')>();
return { ...original, useApi: () => api };
@@ -38,6 +50,7 @@ vi.mock('../../context/ToastContext', () => ({
vi.mock('../../lib/useProtectedVault', () => ({
useProtectedVault: () => ({ revealProtectedValue }),
+ useVaultLock: () => ({ unlocked: false, remainingMs: 0, lockNow: vi.fn() }),
}));
vi.mock('react-i18next', () => ({
@@ -57,9 +70,9 @@ vi.mock('./WorkbenchPageHeader', () => ({
),
}));
-function renderPage() {
+function renderPage(context = remoteOwner) {
return render(
- <InstanceAuthorizationContext.Provider value={remoteOwner}>
+ <InstanceAuthorizationContext.Provider value={context}>
<MemoryRouter initialEntries={['/vaults']}>
<VaultsPage />
</MemoryRouter>
@@ -96,4 +109,11 @@ describe('VaultsPage remote audit history', () => {
expect(await screen.findByText('grant_created')).toBeTruthy();
expect(await screen.findByText('alpha')).toBeTruthy();
});
+
+ it('shows Vault management controls to an active Organization member', async () => {
+ renderPage(activeOrgMember);
+
+ expect(await screen.findByRole('button', { name: 'vaults.add' })).toBeTruthy();
+ expect(screen.queryByText('vaults.remoteReadOnly')).toBeNull();
+ });
});
diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsx
index 238747e50..24cfeb968 100644
--- a/ui/src/components/workbench/VaultsPage.tsx
+++ b/ui/src/components/workbench/VaultsPage.tsx
@@ -24,7 +24,10 @@ import { VaultSettingsDialog } from '../ui/vault-settings-dialog';
import { canManageVaultSecrets } from '../../lib/remoteAuth';
import { useProtectedVault } from '../../lib/useProtectedVault';
import { useVaultRequestRefresh } from '../../lib/useVaultRequestRefresh';
-import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
+import {
+ canUseRuntimeSurfaces,
+ useInstanceAuthorization,
+} from '../../context/InstanceAuthorizationContext';
const PENDING_REQUEST_EXPIRY_GRACE_MS = 100;
const MAX_BROWSER_TIMEOUT_MS = 2_147_483_647;
@@ -232,8 +235,8 @@ function describeGrant(g: VaultGrant, t: TFunction): { Icon: typeof KeyRound; la
* and an inline × to revoke. A grant is a fixed protected set keyed by grant_id — the chip
* summarizes its `source_selector`, never a group.
*/
-// ``onRevoke`` is omitted when revocation is unavailable (remote access: the
-// revoke route is local-only), which renders the chip read-only.
+// ``onRevoke`` is omitted when the current runtime policy withholds revocation,
+// which renders the chip read-only.
const GrantChip: React.FC<{ grant: VaultGrant; now: number; onRevoke?: (grant: VaultGrant) => void }> = ({
grant: g,
now,
@@ -489,15 +492,15 @@ export const VaultsPage: React.FC = () => {
const api = useApi();
const { showToast } = useToast();
const vault = useProtectedVault();
- const { capabilities, remote } = useInstanceAuthorization();
- // `can_manage_instance` stays true for a remote Instance owner, but every Vault
- // mutation (create / edit / delete / reveal, settings save, request fulfil or
- // deny, grant revoke, sign) and every key-material read the lock indicator
- // needs (`vmk`, `pubkey`, `sandbox/root-metadata`) is local-only. Remote owners
- // therefore keep the reads the policy permits — inventory, tags, settings,
- // grants, audit — and lose the controls that would dead-end.
- const canManage = capabilities.can_manage_instance && canManageVaultSecrets({ remote });
- const canReadVaultState = capabilities.can_manage_instance;
+ 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 [searchParams, setSearchParams] = useSearchParams();
const [secrets, setSecrets] = useState<VaultSecret[]>([]);
const [grants, setGrants] = useState<VaultGrant[]>([]);
@@ -778,7 +781,7 @@ export const VaultsPage: React.FC = () => {
<Plus className="size-4" />
{t('vaults.add')}
</Button>
- ) : remote ? (
+ ) : remote && !canUseRuntime ? (
<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 49ab695ac..728139c21 100644
--- a/ui/src/components/workbench/WebPushControl.tsx
+++ b/ui/src/components/workbench/WebPushControl.tsx
@@ -24,15 +24,16 @@ type Status = 'checking' | 'unsupported' | 'needs_install' | 'disabled' | 'enabl
export const WebPushControl: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
- const { remote } = useInstanceAuthorization();
+ const { remote, hasTemporaryUnrestrictedOrgAccess } = 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);
- // Subscribe / unsubscribe / test are local-only, so a remote instance can read
- // its push status but cannot register an endpoint for this host to call.
- const canRegister = canRegisterWebPush({ remote });
+ const canRegister = canRegisterWebPush({
+ remote,
+ temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
+ });
const refresh = async () => {
const nextSupport = getWebPushSupportState();
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index 2988e1c17..b9c62a98c 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -28,7 +28,11 @@ import type { LucideIcon } from 'lucide-react';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
-import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
+import {
+ canUseAppsSurface,
+ canUseRuntimeSurfaces,
+ useInstanceAuthorization,
+} from '../../context/InstanceAuthorizationContext';
import { useWindowManager } from '../../context/WindowManagerContext';
import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';
import type { InboxSession, WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
@@ -395,11 +399,11 @@ const ProjectRow: React.FC<{
canChat: boolean;
canManageMetadata: boolean;
canManageProjects: boolean;
- /** Archiving is local-only (`DELETE /api/projects/{id}`), unlike rename. */
+ /** Whether the current runtime policy admits Project archiving. */
canArchive: boolean;
- /** The Editor app is a trusted-local surface. */
+ /** Whether the current runtime policy admits opening the Project in Editor. */
canOpenInEditor: boolean;
- /** Saving a project's AGENTS.md is local-only; the dialog has no read-only mode. */
+ /** Whether the current runtime policy admits saving a Project's AGENTS.md. */
canEditAgentsMd: boolean;
unreadBySession: Record<string, number>;
onRename: (next: string) => Promise<void>;
@@ -660,16 +664,25 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
const { t } = useTranslation();
const navigate = useNavigate();
const authorizeRouteAction = useUnsavedChangesActionGuard();
- const { capabilities, remote } = useInstanceAuthorization();
- const canCreateProject = canCreateLocalProject(capabilities);
+ 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 capabilityNav = CAPABILITY_NAV.filter(({ to }) => {
- // Harness is trusted-local: the page opens on `/api/harness/bootstrap` and
- // every task/watch/run route it drives is local-only, while
- // `can_manage_agents` stays true for a remote Instance owner.
- if (to === '/harness') return capabilities.can_manage_agents && canUseHarness({ remote });
- if (to === '/agents') return capabilities.can_manage_agents;
- if (to === '/skills') return capabilities.can_use_skills;
- if (to === '/vaults') return capabilities.can_use_vault_secrets;
+ 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;
return false;
});
const { totalUnread, unreadSessions, inboxSessions, markRead, unreadBySession } = useWorkbenchInbox();
@@ -800,7 +813,7 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
unreadBySession={unreadBySession}
unreadSessions={unreadSessions}
totalUnread={totalUnread}
- canMarkRead={capabilities.can_chat}
+ canMarkRead={canChat}
onItemClick={onItemClick}
onMarkAllRead={onMarkAllRead}
onMouseEnter={openPopover}
@@ -858,7 +871,7 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
row above to reclaim that space for the Projects list; ⌘K still
works. Both are roomy 28px tap targets. */}
<div className="flex items-center gap-0.5">
- {capabilities.can_manage_projects && <Button
+ {canManageProjects && <Button
type="button"
variant="ghost"
size="icon"
@@ -924,12 +937,18 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
}
}}
creatingSession={creatingSession(project.id)}
- canChat={capabilities.can_chat && project.capabilities.can_chat}
- canManageMetadata={project.capabilities.can_chat}
- canManageProjects={capabilities.can_manage_projects}
- canArchive={capabilities.can_manage_projects && canArchiveProjects({ remote })}
- canOpenInEditor
- canEditAgentsMd={capabilities.can_manage_projects && canEditProjectInstructions({ remote })}
+ canChat={canChat && (canUseRuntime || project.capabilities.can_chat)}
+ canManageMetadata={canUseRuntime || project.capabilities.can_chat}
+ canManageProjects={canManageProjects}
+ canArchive={canManageProjects && canArchiveProjects({
+ remote,
+ temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
+ })}
+ canOpenInEditor={canUseApps}
+ canEditAgentsMd={canManageProjects && canEditProjectInstructions({
+ remote,
+ temporaryUnrestrictedOrgAccess: hasTemporaryUnrestrictedOrgAccess,
+ })}
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
new file mode 100644
index 000000000..add5c394d
--- /dev/null
+++ b/ui/src/context/InstanceAuthorizationContext.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from 'vitest';
+
+import { canUseAppsSurface } 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);
+ });
+});
diff --git a/ui/src/context/InstanceAuthorizationContext.ts b/ui/src/context/InstanceAuthorizationContext.ts
index ea15fdb42..9421699be 100644
--- a/ui/src/context/InstanceAuthorizationContext.ts
+++ b/ui/src/context/InstanceAuthorizationContext.ts
@@ -6,14 +6,32 @@ import { DENIED_INSTANCE_CAPABILITIES } from '../lib/sessionInfo';
export interface InstanceAuthorizationValue {
remote: boolean;
instanceRole: 'owner' | 'editor' | 'viewer' | null;
- /** Temporary rollout policy, derived from signed active-Organization-member claims. */
+ /** 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,
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 9f3e11e31..9affa74ce 100644
--- a/ui/src/context/InstanceAuthorizationProvider.tsx
+++ b/ui/src/context/InstanceAuthorizationProvider.tsx
@@ -22,6 +22,7 @@ export const InstanceAuthorizationProvider = ({
return {
remote: false,
instanceRole: session.instance_role ?? 'owner',
+ hasTemporaryUnrestrictedOrgAccess: false,
hasTemporaryUnrestrictedOrgAppAccess: false,
capabilities: session.capabilities ?? OWNER_INSTANCE_CAPABILITIES,
};
@@ -30,6 +31,7 @@ export const InstanceAuthorizationProvider = ({
return {
remote: true,
instanceRole: null,
+ hasTemporaryUnrestrictedOrgAccess: false,
hasTemporaryUnrestrictedOrgAppAccess: false,
capabilities: DENIED_INSTANCE_CAPABILITIES,
};
@@ -37,7 +39,11 @@ export const InstanceAuthorizationProvider = ({
return {
remote: true,
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,
};
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsx
index 68f873176..a2b457cc9 100644
--- a/ui/src/context/WorkbenchInboxProvider.tsx
+++ b/ui/src/context/WorkbenchInboxProvider.tsx
@@ -114,11 +114,9 @@ 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: `POST /api/sessions/{id}/mark-read` is local-only, and a remote
- // viewer reading a session it is allowed to read auto-clears unread on
- // view. The mark-read CONTROLS are already trusted-local (`can_chat`);
- // this keeps the automatic write from surfacing
- // `remote_execution_disabled` to a legitimate remote reader.
+ // 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.
const result = await api.markSessionRead(sessionId, untilMessageId, { handleError: false });
// The unread map is authoritative for badges; the card's unread styling
// derives from it, so clearing here clears the dot without touching the
diff --git a/ui/src/features/organization/OrganizationShell.tsx b/ui/src/features/organization/OrganizationShell.tsx
index 2eb01c42c..7319c1aea 100644
--- a/ui/src/features/organization/OrganizationShell.tsx
+++ b/ui/src/features/organization/OrganizationShell.tsx
@@ -37,12 +37,14 @@ const NAV = [
{ path: '/admin/organization/resources', key: 'resources', icon: Building2 },
] as const;
-// Organization is the surface a REMOTE Instance owner lives in, and the
-// Dashboard is trusted-local, so "back to control panel" has to resolve to an
-// admin page this caller can actually open instead of bouncing to the Workbench.
+// Resolve "back to control panel" against the temporary runtime admission.
+// Remote Access itself remains on the separate pairing/tunnel boundary below.
function useBackToControlPanelPath(): string {
- const { capabilities } = useInstanceAuthorization();
- return adminLandingPath(capabilities.can_use_system);
+ const { capabilities, hasTemporaryUnrestrictedOrgAccess } = useInstanceAuthorization();
+ return adminLandingPath(
+ capabilities.can_use_system,
+ hasTemporaryUnrestrictedOrgAccess === true,
+ );
}
function GateState() {
diff --git a/ui/src/lib/adminNavigation.test.ts b/ui/src/lib/adminNavigation.test.ts
index 60734acdf..a1f5a1582 100644
--- a/ui/src/lib/adminNavigation.test.ts
+++ b/ui/src/lib/adminNavigation.test.ts
@@ -5,6 +5,7 @@ import {
isAdvancedSettingsPath,
isLocalOnlyMessagingField,
isLocalSystemPath,
+ isLocalSystemPathForAccess,
isMemorySettingsPath,
} from './adminNavigation';
@@ -34,7 +35,7 @@ describe('isAdvancedSettingsPath', () => {
});
describe('isLocalSystemPath', () => {
- it('covers every destination whose page runs entirely on local-only routes', () => {
+ 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/users')).toBe(true);
@@ -82,10 +83,28 @@ describe('adminLandingPath', () => {
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);
+ });
+
+ 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);
+ });
});
describe('isLocalOnlyMessagingField', () => {
- it('marks only the protected messaging controls as trusted-local', () => {
+ it('marks the messaging controls governed by the runtime admission signal', () => {
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 120d37853..233d5423b 100644
--- a/ui/src/lib/adminNavigation.ts
+++ b/ui/src/lib/adminNavigation.ts
@@ -5,25 +5,17 @@ export const isMemorySettingsPath = (pathname: string): boolean =>
matchesRoute(pathname, '/admin/settings/memory');
/**
- * Destinations whose whole page runs on routes the remote HTTP policy classifies
- * local-only. `can_manage_instance` stays true for a remote Instance owner, so
- * the owner check alone still renders them: the Dashboard immediately requests
- * `/api/doctor`, `/api/logs`, `/api/settings`, `/api/users` and drives
- * `/api/control`; Remote Access drives pair / start / stop / optimize / settings
- * / diagnose (only its status read is remote-permitted); the service, platform,
- * backend, Model Hub, dependency, diagnostics, logs and users pages save or
- * reveal protected local state; and Harness opens on `/api/harness/bootstrap`.
- * They therefore need the trusted-local `can_use_system` capability on top,
- * otherwise a remote owner
- * gets partial or empty state and every mutation ends in
- * `remote_execution_disabled`.
+ * 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.
- * Messaging settings are deliberately absent: the payload filter restricts most
- * of that page to remotely-mutable preference fields, and the remaining
- * protected controls are gated by `isLocalOnlyMessagingField` below.
+ * 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 = [
'/admin/dashboard',
@@ -49,16 +41,34 @@ const LOCAL_ONLY_MESSAGING_FIELDS = new Set([
export const isLocalSystemPath = (pathname: string): boolean =>
LOCAL_SYSTEM_ROUTES.some((route) => matchesRoute(pathname, route));
+/**
+ * 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 isLocalOnlyMessagingField = (field: string): boolean =>
LOCAL_ONLY_MESSAGING_FIELDS.has(field);
/**
- * Where the "Control Panel" entry points. A remote owner cannot open the
- * Dashboard, so send them to the first admin page they can actually use rather
- * than through a redirect that bounces them back to the Workbench.
+ * 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.
*/
-export const adminLandingPath = (canUseSystem: boolean): string =>
- canUseSystem ? '/admin/dashboard' : '/admin/settings/messaging';
+export const adminLandingPath = (
+ canUseSystem: boolean,
+ temporaryUnrestrictedOrgAccess = false,
+): string =>
+ canUseSystem || temporaryUnrestrictedOrgAccess
+ ? '/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 c3596e39c..1aca4532e 100644
--- a/ui/src/lib/remoteAuth.test.ts
+++ b/ui/src/lib/remoteAuth.test.ts
@@ -30,16 +30,17 @@ describe('agent definition editing', () => {
expect(canEditAgentDefinitions({ remote: false })).toBe(true);
});
- it('renders a read-only catalog on a remote instance', () => {
+ 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);
});
});
-// Every Workbench control whose endpoint the remote HTTP policy classifies
-// local-only needs this locality check on top of its capability, because
-// `can_manage_instance` / `can_manage_agents` / `can_manage_projects` stay true
-// for a remote Instance owner.
-describe('local-only workbench controls', () => {
+// Runtime controls use the signed temporary Organization admission signal.
+describe('runtime-policy workbench controls', () => {
const predicates = {
canManageSkills,
canManageVaultSecrets,
@@ -55,7 +56,11 @@ describe('local-only workbench controls', () => {
expect(predicate({ remote: false })).toBe(true);
});
- it.each(Object.entries(predicates))('withholds %s on a remote instance', (_name, predicate) => {
+ 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);
});
});
@@ -134,8 +139,8 @@ describe('remote auth navigation', () => {
});
});
-describe('setup bypass for remote owners', () => {
- it('bypasses the setup wizard only for an authenticated remote owner', () => {
+describe('setup bypass for remote runtime access', () => {
+ it('bypasses setup for an authenticated owner or active Organization member', () => {
expect(
shouldBypassSetupForRemoteOwner({
remote: true,
@@ -143,6 +148,14 @@ describe('setup bypass for remote owners', () => {
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 1c42f7a02..e95b07e1c 100644
--- a/ui/src/lib/remoteAuth.ts
+++ b/ui/src/lib/remoteAuth.ts
@@ -28,127 +28,99 @@ export function isSetupCheckBypassed(path: string): boolean {
return SETUP_CHECK_BYPASS_PATHS.has(path);
}
-/**
- * Locality half of a Workbench control gate.
- *
- * `can_manage_instance` / `can_manage_agents` / `can_manage_projects` stay true
- * for a remote Instance owner, so a role check alone still renders controls whose
- * endpoints the remote HTTP policy classifies local-only — they dead-end in
- * `remote_execution_disabled`. Every predicate below is that missing locality
- * check; combine it with the capability that already guards the surface locally
- * (`canManageSkills({ remote }) && capabilities.can_manage_instance`), the same
- * shape as the trusted-local capabilities the backend derives
- * (`can_use_system` = not remote and owner).
- */
-type RemoteContext = { remote: boolean };
+/** 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 isTrustedLocal(context: RemoteContext): boolean {
- return !context.remote;
+function hasTemporaryUnrestrictedOrgAccess(context: RemoteContext): boolean {
+ return (
+ context.temporaryUnrestrictedOrgAccess === true ||
+ context.temporaryUnrestrictedOrgAppAccess === true
+ );
+}
+
+function canUseTemporaryOrgRuntime(context: RemoteContext): boolean {
+ return !context.remote || hasTemporaryUnrestrictedOrgAccess(context);
}
/**
- * Agent definition editing is local-only. The remote HTTP policy permits Agent
- * detail reads and organization onboarding, and `/api/global-prompts` is local
- * only, so create / import / edit / enable / set-default / run / delete would
- * all dead-end in `remote_execution_disabled`. Remote instances therefore get a
- * read-only Agent catalog; onboarding stays available because it is separately
- * permitted.
+ * Temporary policy: active Organization members may edit Agent definitions.
*/
export function canEditAgentDefinitions(context: RemoteContext): boolean {
- return isTrustedLocal(context);
+ return canUseTemporaryOrgRuntime(context);
}
/**
- * Skill management is local-only: `GET /api/skills` is the only remote-permitted
- * Skill route, while add / upload / preview / registry search / dependency
- * install / update / remove are all local. Remote instances therefore get a
- * read-only Skill catalog.
+ * Temporary policy: active Organization members may manage Skills.
*/
export function canManageSkills(context: RemoteContext): boolean {
- return isTrustedLocal(context);
+ return canUseTemporaryOrgRuntime(context);
}
/**
- * Vault management is local-only. The inventory, tags, settings, pending
- * requests, grants and audit reads are remote-permitted, but every mutation
- * (create / edit / delete a secret, reveal, settings save, request fulfil/deny,
- * grant revoke, sign) and every key-material read (`vmk`, `pubkey`,
- * `sandbox/root-metadata`, WebAuthn factor options) is local. Remote instances
- * therefore get a read-only Vault.
+ * Temporary policy: active Organization members may manage Vault resources.
*/
export function canManageVaultSecrets(context: RemoteContext): boolean {
- return isTrustedLocal(context);
+ return canUseTemporaryOrgRuntime(context);
}
/**
- * Harness is local-only: the page opens on `/api/harness/bootstrap` and every
- * task / watch / run route it drives is local, so the whole surface — route and
- * navigation entry — is unavailable remotely.
+ * Temporary policy: active Organization members may use Harness definitions and runs.
*/
export function canUseHarness(context: RemoteContext): boolean {
- return isTrustedLocal(context);
+ return canUseTemporaryOrgRuntime(context);
}
/**
- * Archiving a Project is local-only (`DELETE /api/projects/{id}`), unlike the
- * remote-permitted Project list, create and rename.
+ * Temporary policy: active Organization members may archive Projects.
*/
export function canArchiveProjects(context: RemoteContext): boolean {
- return isTrustedLocal(context);
+ return canUseTemporaryOrgRuntime(context);
}
/**
- * Project instructions are local-only in both directions: saving `AGENTS.md` is
- * local, and the read is too because a checked-in `AGENTS.md` / `CLAUDE.md`
- * symlink can point outside the Project workspace, which a remote caller has no
- * file capability to follow.
+ * Temporary policy: active Organization members may edit project instructions.
*/
export function canEditProjectInstructions(context: RemoteContext): boolean {
- return isTrustedLocal(context);
+ return canUseTemporaryOrgRuntime(context);
}
/**
- * A Project's default Agent is local-only. `PATCH /api/projects/{id}` is
- * payload-filtered remotely down to `display_name`, so the rename this dialog
- * shares stays permitted while every default-Agent field the picker persists
- * (`agent_id`, `agent_name`, `agent_variant`, `model`, `reasoning_effort`)
- * dead-ends in `remote_execution_disabled`.
+ * Temporary policy: active Organization members may edit project Agent defaults.
*/
export function canEditProjectDefaultAgent(context: RemoteContext): boolean {
- return isTrustedLocal(context);
+ return canUseTemporaryOrgRuntime(context);
}
/**
- * Memory administration is local-only: the admin log enumerates memcells for
- * every principal, a settings save repoints the shared provider endpoints, and
- * clear / runtime-restart act on the whole local sidecar. The principal-scoped
- * status, profile and search reads stay remote-permitted.
+ * Temporary policy: active Organization members may administer Memory.
*/
export function canAdministerMemory(context: RemoteContext): boolean {
- return isTrustedLocal(context);
+ return canUseTemporaryOrgRuntime(context);
}
-/**
- * Remote owners can skip the global setup wizard: the wizard is a local-only
- * flow, while the remote shell has its own recovery surface.
- */
+/** 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;
+ return !!session?.remote && session.authenticated === true && (
+ session.capabilities?.can_manage_instance === true ||
+ session.temporaryUnrestrictedOrgAccess === true ||
+ session.temporaryUnrestrictedOrgAppAccess === true
+ );
}
/**
- * Registering and testing a Web Push subscription is local-only: the endpoint is
- * caller-supplied and this host later fetches it, so a remote subscription would
- * be an outbound request to an address the caller picked. Reading push status
- * stays remote-permitted, which is why this gates the enable / disable / test
- * controls rather than the surface that shows them.
+ * Temporary policy: active Organization members may register and test Web Push.
*/
export function canRegisterWebPush(context: RemoteContext): boolean {
- return isTrustedLocal(context);
+ return canUseTemporaryOrgRuntime(context);
}
diff --git a/ui/src/lib/sessionInfo.test.ts b/ui/src/lib/sessionInfo.test.ts
index d3dac21ad..7136883f1 100644
--- a/ui/src/lib/sessionInfo.test.ts
+++ b/ui/src/lib/sessionInfo.test.ts
@@ -34,6 +34,7 @@ describe('normalizeSessionInfo', () => {
sub: 'owner-1',
instance_role: 'owner',
+ temporary_unrestricted_org_access: false,
temporary_unrestricted_org_app_access: false,
capabilities: OWNER_INSTANCE_CAPABILITIES,
});
@@ -45,6 +46,7 @@ describe('normalizeSessionInfo', () => {
authenticated: true,
instance_role: 'viewer',
+ temporary_unrestricted_org_access: false,
temporary_unrestricted_org_app_access: false,
capabilities: {
can_read_instance: true,
@@ -57,6 +59,7 @@ describe('normalizeSessionInfo', () => {
authenticated: true,
instance_role: 'viewer',
+ temporary_unrestricted_org_access: false,
temporary_unrestricted_org_app_access: false,
capabilities: {
...DENIED_INSTANCE_CAPABILITIES,
@@ -77,6 +80,7 @@ describe('normalizeSessionInfo', () => {
});
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);
});
diff --git a/ui/src/lib/sessionInfo.ts b/ui/src/lib/sessionInfo.ts
index 02a7ec4f5..5e4463147 100644
--- a/ui/src/lib/sessionInfo.ts
+++ b/ui/src/lib/sessionInfo.ts
@@ -24,6 +24,8 @@ export type SessionInfo =
email: string;
sub?: string;
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;
};
@@ -102,8 +104,12 @@ export const normalizeSessionInfo = (value: unknown): SessionInfo => {
email: typeof value.email === 'string' ? value.email : '',
...(typeof value.sub === 'string' ? { sub: value.sub } : {}),
instance_role: instanceRole,
- temporary_unrestricted_org_app_access:
+ 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 69fd170d5..b56ea9661 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1216,11 +1216,10 @@ def client_config_payload(config: V2Config) -> dict:
``config_to_payload`` has to emit ``memory`` because the UI save path uses
the same projection as its deep-merge base, and an omitted block resets the
stored one (the ``agents.avault`` comment above records the same hazard).
- A response is the opposite case: Memory settings — enablement, both
- processing endpoint URLs and model names, and API-key-presence flags — are
- reachable only through the direct-loopback-only ``/api/memory/*`` routes,
- so returning them from a generic endpoint would hand them to any
- authenticated remote caller over the tunnel.
+ A response is the opposite case: Memory settings have their own
+ ``/api/memory/*`` routes and lifecycle, so returning them from the generic
+ config endpoint would duplicate that contract and mix independently loaded
+ state into every settings response.
Every endpoint that returns the generic config must project through this
function, so a new one inherits the exclusion instead of having to repeat
@@ -1242,12 +1241,11 @@ _REMOTE_CONFIG_UI_FIELDS = (
def remote_config_payload(config: V2Config) -> dict:
- """Return the explicit remote-safe projection of generic configuration.
+ """Return the fallback projection for remote identities without rollout access.
- Instance role determines which remote routes a caller may use, but it does
- not make the caller trusted to inspect local filesystem layout, executable
- paths, or runtime configuration. Keep this as an allowlist so new local
- settings remain local by default.
+ 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.
"""
payload = client_config_payload(config)
@@ -1795,9 +1793,10 @@ def get_vibe_agents(
backend: Optional[str] = None,
include_disabled: bool = False,
include_archived: bool = False,
+ user_context: Any = None,
) -> dict:
_ensure_builtin_default_agents()
- user_context = resolve_resource_access_context()
+ user_context = resolve_resource_access_context(user_context)
store = VibeAgentStore()
try:
normalized_backend = validate_agent_backend(backend) if backend else None
@@ -1860,7 +1859,7 @@ def _agent_onboarding_resource_descriptors(
return descriptors
-def get_vibe_agent_onboarding() -> dict:
+def get_vibe_agent_onboarding(*, user_context: Any = None) -> dict:
"""Return the safe owner inventory for Organization Agent onboarding."""
config = V2Config.load()
@@ -1868,7 +1867,7 @@ def get_vibe_agent_onboarding() -> dict:
store = VibeAgentStore()
try:
result = store.organization_onboarding_inventory(
- user_context=resolve_resource_access_context(),
+ user_context=resolve_resource_access_context(user_context),
)
finally:
store.close()
@@ -1881,14 +1880,14 @@ def get_vibe_agent_onboarding() -> dict:
return result
-def onboard_vibe_agents() -> dict:
+def onboard_vibe_agents(*, user_context: Any = None) -> dict:
"""Register all existing Agents privately, then publish the safe index."""
from vibe import remote_access
config = V2Config.load()
_ensure_builtin_default_agents(config)
- context = resolve_resource_access_context()
+ context = resolve_resource_access_context(user_context)
store = VibeAgentStore()
try:
result = store.onboard_organization_agents(user_context=context)
@@ -1914,8 +1913,10 @@ def onboard_vibe_agents() -> dict:
return result
-def get_vibe_agent(name: str) -> dict:
- user_context = resolve_resource_access_context()
+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)
@@ -1927,14 +1928,20 @@ def get_vibe_agent(name: str) -> dict:
default_agent = None
return {
"ok": True,
- "agent": _vibe_agent_payload(agent, remote_safe=user_context.is_remote),
+ "agent": _vibe_agent_payload(
+ agent,
+ remote_safe=(
+ user_context.is_remote
+ and not has_temporary_unrestricted_runtime_access(user_context)
+ ),
+ ),
"default_agent_name": default_agent.name if default_agent else None,
}
finally:
store.close()
-def create_vibe_agent(payload: dict) -> dict:
+def create_vibe_agent(payload: dict, *, user_context: Any = None) -> dict:
if not isinstance(payload, dict):
raise ValueError("Agent payload must be an object")
metadata = payload.get("metadata") or payload.get("metadata_json") or {}
@@ -1952,7 +1959,7 @@ def create_vibe_agent(payload: dict) -> dict:
system_prompt=payload.get("system_prompt"),
metadata=metadata,
enabled=_parse_agent_enabled_field(payload, default=True),
- user_context=resolve_resource_access_context(),
+ user_context=resolve_resource_access_context(user_context),
)
except AgentNameValidationError as exc:
return _agent_name_validation_error(exc)
@@ -1961,7 +1968,7 @@ def create_vibe_agent(payload: dict) -> dict:
store.close()
-def update_vibe_agent(name: str, payload: dict) -> dict:
+def update_vibe_agent(name: str, payload: dict, *, user_context: Any = None) -> dict:
if not isinstance(payload, dict):
raise ValueError("Agent payload must be an object")
if "backend" in payload:
@@ -2007,7 +2014,7 @@ def update_vibe_agent(name: str, payload: dict) -> dict:
store = VibeAgentStore()
try:
- context = resolve_resource_access_context()
+ context = resolve_resource_access_context(user_context)
try:
agent = (
store.rename(name, new_name, user_context=context)
@@ -2067,10 +2074,10 @@ def _agent_reference_rewrite_error(exc: AgentReferenceRewriteError) -> dict:
}
-def remove_vibe_agent(name: str) -> dict:
+def remove_vibe_agent(name: str, *, user_context: Any = None) -> dict:
store = VibeAgentStore()
try:
- context = resolve_resource_access_context()
+ context = resolve_resource_access_context(user_context)
store.require_manageable(name, user_context=context)
try:
archived = store.archive(name, user_context=context)
@@ -2103,10 +2110,10 @@ def remove_vibe_agent(name: str) -> dict:
store.close()
-def set_default_vibe_agent(name: str) -> dict:
+def set_default_vibe_agent(name: str, *, user_context: Any = None) -> dict:
store = VibeAgentStore()
try:
- context = resolve_resource_access_context()
+ context = resolve_resource_access_context(user_context)
agent = store.require_manageable(name, user_context=context)
if not agent.enabled:
raise ValueError(f"agent '{agent.name}' is disabled")
@@ -4788,7 +4795,7 @@ def store_vault_pubkey_pin(payload: dict) -> dict:
return {"ok": True, "secret": meta}
-def import_vibe_agents(payload: dict) -> dict:
+def import_vibe_agents(payload: dict, *, user_context: Any = None) -> dict:
if not isinstance(payload, dict):
raise ValueError("Import payload must be an object")
candidates = []
@@ -4829,7 +4836,10 @@ def import_vibe_agents(payload: dict) -> dict:
store = VibeAgentStore()
try:
- result = store.import_candidates(candidates, user_context=resolve_resource_access_context())
+ result = store.import_candidates(
+ candidates,
+ user_context=resolve_resource_access_context(user_context),
+ )
return {
"ok": True,
"imported": [_vibe_agent_payload(agent, brief=True) for agent in result.imported],
@@ -4839,13 +4849,16 @@ def import_vibe_agents(payload: dict) -> dict:
store.close()
-def get_settings(platform: Optional[str] = None) -> dict:
+def get_settings(platform: Optional[str] = None, *, user_context: Any = None) -> dict:
store = SettingsStore.get_instance()
target_platform = platform or _current_platform()
if target_platform == "discord":
_migrate_discord_guild_scope_from_config(store)
payload = _settings_to_payload(store, platform=target_platform)
- payload["agent_catalog"] = get_vibe_agents(include_archived=True)
+ payload["agent_catalog"] = get_vibe_agents(
+ include_archived=True,
+ user_context=user_context,
+ )
return payload
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 7027cd7cf..7592d8e34 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -6,7 +6,11 @@ from dataclasses import dataclass
import re
from typing import Any, Mapping
-from core.inbox_events import RUNS_UPDATED_EVENT
+from core.inbox_events import (
+ DEFINITIONS_UPDATED_EVENT,
+ RUNS_UPDATED_EVENT,
+ VAULTS_UPDATED_EVENT,
+)
INSTANCE_ROLES = frozenset({"owner", "editor", "viewer"})
@@ -44,7 +48,13 @@ _VIEWER_WORKBENCH_EVENTS = frozenset(
}
)
_EDITOR_WORKBENCH_EVENTS = frozenset({"queue.updated", "show.event"})
-_REMOTE_LOCAL_ONLY_WORKBENCH_EVENTS = frozenset({RUNS_UPDATED_EVENT})
+_PRIVILEGED_RUNTIME_WORKBENCH_EVENTS = frozenset(
+ {
+ DEFINITIONS_UPDATED_EVENT,
+ RUNS_UPDATED_EVENT,
+ VAULTS_UPDATED_EVENT,
+ }
+)
REMOTE_HTTP_ALLOWED = "allowed"
REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER = "active_organization_member"
@@ -78,19 +88,41 @@ class AuthorizationContext:
@property
def is_instance_owner(self) -> bool:
- return self.is_trusted_local or self.instance_role == "owner"
+ if self.is_trusted_local:
+ return True
+ return self._has_admitted_remote_identity() and self.instance_role == "owner"
@property
def is_active_organization_member(self) -> bool:
return bool(
- self.organization_id
+ self.instance_role in INSTANCE_ROLES
+ and self.instance_access_source in INSTANCE_ACCESS_SOURCES
+ and self.organization_id
and self.organization_member_id
and self.organization_role in ORGANIZATION_ROLES
)
+ def _has_admitted_remote_identity(self) -> bool:
+ """Return whether this context carries an identity accepted for runtime use.
+
+ HTTP admission validates the signed session before a request reaches a
+ service. Services are also callable directly, so they must not infer
+ authority from a caller-constructed ``owner`` role alone. Show Page
+ email grants are the one non-Organization remote identity and 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)
+ return self.is_active_organization_member
+
def has_role(self, minimum_role: str) -> bool:
if self.is_trusted_local:
return True
+ if not self._has_admitted_remote_identity():
+ return False
return _ROLE_RANK.get(self.instance_role or "", 0) >= _ROLE_RANK[minimum_role]
@property
@@ -182,15 +214,16 @@ class AuthorizationContext:
}
-def has_temporary_unrestricted_org_app_access(
+def has_temporary_unrestricted_org_access(
context: AuthorizationContext | Mapping[str, Any] | None,
) -> bool:
- """Return whether the temporary Organization Apps policy applies.
+ """Return whether the temporary unrestricted Organization policy applies.
This is an HTTP/product rollout rule, not a projected capability. Until the
- per-App and Show Page authorization model tracked in avibe#1313 ships, every
- authenticated Organization member may use the remote Apps surfaces. Exact
- Show Page email grants remain confined to their signed page subtree.
+ 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 = (
@@ -208,6 +241,27 @@ def has_temporary_unrestricted_org_app_access(
)
+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
@@ -319,6 +373,15 @@ def require_instance_role(
if isinstance(context, AuthorizationContext)
else context_from_session_payload(context)
)
+ # The temporary rollout intentionally has no per-surface role split for an
+ # active Organization member, but it does not turn an arbitrary remote
+ # Instance owner into an Organization member. Keep exact Show Page email
+ # grants on their signed viewer role; the HTTP/page boundary scopes them to
+ # the one page separately.
+ if resolved.is_remote and resolved.instance_access_source != "show_page_email":
+ if not has_temporary_unrestricted_org_access(resolved):
+ raise InstanceAuthorizationError(minimum_role)
+ return resolved
if not resolved.has_role(minimum_role):
raise InstanceAuthorizationError(minimum_role)
return resolved
@@ -344,13 +407,33 @@ def can_receive_workbench_event(
) -> bool:
"""Return whether an SSE subscriber may receive a workbench event."""
- if event_type == "show.event" and has_temporary_unrestricted_org_app_access(context):
+ 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 (
+ event_type == "show.event"
+ and isinstance(context, AuthorizationContext)
+ and context.instance_access_source == "show_page_email"
+ 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 _REMOTE_LOCAL_ONLY_WORKBENCH_EVENTS:
+ if getattr(context, "is_remote", False) and event_type in _PRIVILEGED_RUNTIME_WORKBENCH_EVENTS:
return False
return True
@@ -442,10 +525,9 @@ _REMOTE_LOCAL_ONLY_HTTP_RULES = tuple(
("GET", r"^/api/harness/(?:runs|bootstrap|runs/[^/]+)$"),
("GET", r"^/api/vault/(?:pubkey|agent/pubkey|sandbox/root-metadata|vmk)$"),
("GET", r"^/api/global-prompts$"),
- # Model Hub source listing returns credential metadata
- # (credential_ref, masked_credential, account_label, custom base_url,
- # usage/billing) that must not cross the tunnel; the mutation surface
- # is already fail-closed local-only, so the read stays local-only too.
+ # Baseline for remote identities outside the temporary active-member
+ # rollout. The explicit matrix below admits the same Model Hub metadata
+ # and mutations for active Organization members.
("GET", r"^/api/models/sources$"),
("HEAD", r"^/api/models/sources$"),
("GET", r"^/api/skills/(?:check|find)$"),
@@ -467,35 +549,101 @@ _REMOTE_PAYLOAD_FILTERED_HTTP_RULES = tuple(
)
)
-# Temporary, exact remote App surface for authenticated Organization members.
-# Keep this list route-specific: unrelated control-plane and future unknown API
-# endpoints must continue to fall through to the local-only default. The
-# replacement capability/resource model is tracked in avibe#1313.
-_TEMPORARY_ORGANIZATION_APP_HTTP_RULES = tuple(
+# Temporary unrestricted runtime surface for authenticated active Organization
+# members. This is deliberately an explicit route matrix: Organization auth,
+# membership, tunnel pairing, cloud-management, and unknown future API routes
+# still use their existing policy. The per-surface authorization model is
+# tracked in avibe#1313.
+_UNRESTRICTED_ORG_METHODS = frozenset({"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"})
+_TEMPORARY_UNRESTRICTED_ORG_HTTP_RULES = tuple(
(methods, re.compile(pattern))
for methods, pattern in (
- (frozenset({"GET", "HEAD"}), r"^/api/dock$"),
- (frozenset({"POST"}), r"^/api/dock/pins$"),
- (frozenset({"DELETE"}), r"^/api/dock/pins/[^/]+$"),
- (frozenset({"PUT"}), r"^/api/dock/order$"),
+ # Settings, configuration, workbench preferences, and service control.
+ # Config responses use the local runtime projection with only the
+ # pairing/tunnel block removed.
+ (frozenset({"POST"}), r"^/api/config$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/(?:settings|settings/thread|workbench/prefs|ui/reload)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/(?:control|doctor|logs|upgrade)$"),
+ # The shell polls the process status and the setup pages use these
+ # local discovery/configuration helpers. They do not alter Organization
+ # identity, pairing, or tunnel state.
+ (_UNRESTRICTED_ORG_METHODS, r"^/status$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/(?:cli/detect|slack/manifest)$"),
+ # Harness, Agent definitions, global prompts, and runtime diagnostics.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/harness/(?:counts|tasks|tasks/[^/]+|watches|watches/[^/]+|runs|runs/[^/]+|bootstrap)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/agents(?:/(?:default|import|[^/]+))?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/(?:agent-backends|agents-graph|agent-onboarding|running-agents(?:/end)?)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/agent/[^/]+/install(?:/[^/]+)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/global-prompts$"),
+ # Skills and their installed runtime dependencies.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/skills(?:/(?:preview|find|check|update|upload|[^/]+))?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/dependencies(?:/[^/]+(?:/install(?:/[^/]+)?)?)?$"),
+ # Vault inventory, key material, secret CRUD, grants, approvals, and audit.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/vault/(?:secrets(?:/[^/]+(?:/reveal-context)?)?|tags|pubkey|agent/pubkey|sandbox/root-metadata|agent-bindings:batch|agent-binding|settings|vmk|authz/factors/webauthn(?:/options)?|signing-addresses|requests(?:/[^/]+(?:/(?:deny|fulfill-access))?)?|provision-requests(?:/(?:by-id/)?[^/]+)?|grants(?:/[^/]+)?|sign|pubkey-pin|audit)$"),
+ # Model Hub source/mapping/OAuth/runtime management.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/sources(?:/[^/]+(?:/(?:credential|reauth|refresh|models(?:/.*)?)?)?)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/(?:agents|events)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/agents/(?:opencode/menu|[^/]+/(?:sources|mode|mappings|chain|probe))$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/turns/[^/]+/provenance$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/oauth/(?:start|status/[^/]+|submit|cancel)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/migration/(?:scan|apply)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/runtime/(?:status|start)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/models/sources/[^/]+/models(?:/.*)?$"),
+ # Memory administration.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/memory/(?:settings|status|failures|profile|log|log/entry|search|runtime/restart|clear)$"),
+ # Projects, sessions, chat execution, and ASR.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/projects(?:/[^/]+(?:/agents-md)?)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/workbench/projects-bootstrap$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/sessions(?:/[^/]+(?:/(?:fork|bootstrap|archive-preview|messages|activity|cli-activity|cancel|mark-read|turn-state|queue(?:/[^/]+(?:/send-now)?)?|draft|attachments))?)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/(?:search/messages|events|inbox)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/asr/(?:transcribe|telemetry|status)$"),
+ # Apps: Dock, Files, browse favorites, Terminal teardown, and Show Pages.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/dock(?:/pins(?:/[^/]+)?|/order)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/files/(?:list|meta|content|write|upload|mkdir|rename|move|copy|delete|delete/undo|search|search_names|search/replace|search/undo)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/media/[^/]+(?:/meta)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/browse(?:/favorites|/mkdir)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/terminal/[^/]+$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/show-pages(?:/[^/]+(?:/(?:visibility|ensure|access|authorized-emails|rotate-share|share-id|icon))?)?$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/show/sessions/[^/]+/(?:events|prewarm)$"),
+ # Agent backends, provider setup, platform settings, and channel tools.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/backend/(?:codex|claude|opencode)/(?:runtime|restart)$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/backend/(?:codex|claude)/auth$"),
(
- frozenset({"GET", "HEAD"}),
- r"^/api/files/(?:list|meta|content|search|search_names)$",
+ _UNRESTRICTED_ORG_METHODS,
+ r"^/api/backend/(?:codex|claude|opencode)/auth/(?:oauth/(?:start|status/[^/]+|submit-code|cancel|remove)|api-key/remove|test)$",
),
(
- frozenset({"POST"}),
- r"^/api/files/(?:upload|mkdir|rename|move|copy|delete|delete/undo|search/replace|search/undo)$",
+ _UNRESTRICTED_ORG_METHODS,
+ r"^/api/backend/claude/auth/oauth/credentials/remove$",
),
- (frozenset({"PUT"}), r"^/api/files/write$"),
- (frozenset({"GET", "HEAD"}), r"^/api/browse/favorites$"),
- (frozenset({"DELETE"}), r"^/api/terminal/[^/]+$"),
- (frozenset({"POST"}), r"^/api/show-pages/[^/]+/icon$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/backend/opencode/(?:providers|custom-provider(?:/[^/]+)?|default-provider|provider/[^/]+/(?:auth(?:/.*)?|test|models(?:/.*)?))$"),
+ (
+ _UNRESTRICTED_ORG_METHODS,
+ r"^/api/(?:opencode/(?:options|permission-status|setup-permission)|claude/(?:agents|models)|codex/(?:agents|models))$",
+ ),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/(?:platforms|slack(?:/(?:auth_test|channels))?|discord/(?:auth_test|channels|guilds)|telegram/(?:auth_test|chats)|lark/(?:auth_test|chats|temp_ws/(?:start|stop))|wechat/qr_login/(?:start|poll)|channels/delete)$"),
+ # Push registration is a runtime notification surface.
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/web-push/(?:status|vapid-public-key|subscriptions|test)$"),
+ # Local IM users and bind codes are part of the temporarily unrestricted
+ # runtime administration surface. This does not include Organization
+ # membership, Cloud pairing, or tunnel control routes.
+ (frozenset({"GET", "HEAD", "POST"}), r"^/api/users$"),
+ (frozenset({"POST"}), r"^/api/users/[^/]+/admin$"),
+ (frozenset({"DELETE"}), r"^/api/users/[^/]+$"),
+ (frozenset({"GET", "HEAD", "POST"}), r"^/api/bind-codes$"),
+ (frozenset({"DELETE"}), r"^/api/bind-codes/[^/]+$"),
+ (frozenset({"GET", "HEAD"}), r"^/api/setup/first-bind-code$"),
+ (_UNRESTRICTED_ORG_METHODS, r"^/api/resource-policies(?:/[^/]+/[^/]+)?$"),
)
)
-# Positive allowlist for remote-safe owner surfaces. Any route that mutates
-# local Agent, IM, Vault, or other execution state must stay absent here and
-# therefore use the fail-closed local-only default below.
+# Compatibility name retained for callers/tests from the previous Apps-only
+# rollout. New code should use the unrestricted Organization matrix above.
+_TEMPORARY_ORGANIZATION_APP_HTTP_RULES = _TEMPORARY_UNRESTRICTED_ORG_HTTP_RULES
+
+# Compatibility allowlist for remote identities outside the temporary active
+# Organization rollout. The unrestricted active-member matrix is evaluated
+# first; unknown routes still use the fail-closed local-only default below.
_REMOTE_OWNER_ALLOWED_HTTP_RULES = tuple(
(methods, re.compile(pattern))
for methods, pattern in (
@@ -597,14 +745,25 @@ def _owner_http_rule_matches(method: str, path: str) -> bool:
)
-def _temporary_organization_app_rule_matches(method: str, path: str) -> bool:
+def _temporary_unrestricted_org_rule_matches(method: str, path: str) -> bool:
return any(
method in methods and pattern.fullmatch(path)
- for methods, pattern in _TEMPORARY_ORGANIZATION_APP_HTTP_RULES
+ for methods, pattern in _TEMPORARY_UNRESTRICTED_ORG_HTTP_RULES
)
-def http_authorization_policy(method: str, path: str) -> HttpAuthorizationPolicy:
+def _temporary_organization_app_rule_matches(method: str, path: str) -> bool:
+ """Compatibility alias for the previous Apps-only policy matcher."""
+
+ return _temporary_unrestricted_org_rule_matches(method, path)
+
+
+def http_authorization_policy(
+ method: str,
+ path: str,
+ *,
+ temporary_org_access: bool = False,
+) -> HttpAuthorizationPolicy:
"""Return role and remote-exposure policy for one HTTP request.
Explicit viewer/editor and owner-management routes keep their approved remote
@@ -634,14 +793,22 @@ def http_authorization_policy(method: str, path: str) -> HttpAuthorizationPolicy
)
return HttpAuthorizationPolicy(minimum_role, remote_access)
if path == "/status":
- return HttpAuthorizationPolicy(None, REMOTE_HTTP_LOCAL_ONLY)
+ return HttpAuthorizationPolicy(None, REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER)
if not path.startswith("/api/"):
return HttpAuthorizationPolicy(None)
- if _temporary_organization_app_rule_matches(normalized_method, path):
- return HttpAuthorizationPolicy(
- "viewer",
- REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER,
+ if _temporary_unrestricted_org_rule_matches(normalized_method, path):
+ # The matrix is an identity-independent route classification. The
+ # request boundary below admits it only after verifying the signed
+ # active-Organization claim; ordinary remote callers still receive
+ # ``remote_execution_disabled`` there. The optional keyword is retained
+ # for callers from the previous Apps-only rollout, but classification is
+ # deliberately context-independent.
+ minimum_role = (
+ "owner"
+ if re.fullmatch(r"^/api/projects/[^/]+/agents-md$", path)
+ else "viewer"
)
+ return HttpAuthorizationPolicy(minimum_role, REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER)
minimum_role = "owner"
if _http_rule_matches(normalized_method, path, _VIEWER_HTTP_MUTATION_RULES):
diff --git a/vibe/ui_memory_routes.py b/vibe/ui_memory_routes.py
index 0c8cb2487..6ef4c7982 100644
--- a/vibe/ui_memory_routes.py
+++ b/vibe/ui_memory_routes.py
@@ -1,6 +1,6 @@
"""The ``/api/memory/*`` UI surface.
-Every route here requires a trusted local or authenticated Avibe Cloud browser
+Every route here requires an authorized local or authenticated Avibe Cloud browser
and answers with the closed Memory result envelope (``{"status": "ok", ...}`` /
``{"status": "failed", "error":
<closed code>}``) plus ``Cache-Control: no-store``. Keeping them in one module
@@ -30,7 +30,7 @@ _MEMORY_LOG_ENTRY_ID_RE = re.compile(r"[A-Za-z0-9_.:-]{1,256}\Z")
def _memory_ui_user_key() -> str | None:
- """Ask ``ui_server`` for the trusted browser's Memory identity.
+ """Ask ``ui_server`` for the authorized browser's Memory identity.
Late-bound on purpose: the policy belongs with the other request-locality
helpers in ``ui_server``, and resolving it per call keeps it patchable there.
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 9f8384f55..6dc07fc49 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -19,7 +19,6 @@ import threading
import time
from collections import OrderedDict, deque
from contextlib import contextmanager
-from dataclasses import replace
from datetime import datetime, timezone
from enum import Enum
from pathlib import Path
@@ -2304,10 +2303,10 @@ 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_app_access
+ from vibe.authorization import has_temporary_unrestricted_org_access
resource_allowed = (
- has_temporary_unrestricted_org_app_access(context)
+ has_temporary_unrestricted_org_access(context)
or context.can_use_show_page(show_page_id)
or _show_page_resource_access_allowed(context, show_page_id)
)
@@ -2386,36 +2385,84 @@ def enforce_show_page_email_scope():
return jsonify({"ok": False, "error": "show_page_access_forbidden"}), 403
-def _temporary_org_app_resource_context(context: Any = None):
- """Return a request-scoped resource context for the temporary Org policy.
+def _temporary_org_runtime_resource_context(context: Any = None):
+ """Return the unchanged identity for the temporary runtime policy.
- The real authorization context remains on ``g`` for downstream identity,
- renewal, and audit behavior. Only resource-service calls receive this copy,
- which preserves the remote subject/Organization claims while bypassing the
- Show Page ACL until avibe#1313 replaces the temporary full-access 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.
"""
- from vibe.authorization import has_temporary_unrestricted_org_app_access
+ if context is not None:
+ return context
+ try:
+ resolved = getattr(g, "authorization_context", None)
+ except (LookupError, RuntimeError):
+ resolved = None
+ return resolved
+
+
+def _has_temporary_runtime_access(context: Any) -> bool:
+ from vibe.authorization import has_temporary_unrestricted_runtime_access
- resolved = context if context is not None else getattr(g, "authorization_context", None)
- if not has_temporary_unrestricted_org_app_access(resolved):
- return resolved
- return replace(resolved, is_trusted_local=True)
+ return bool(has_temporary_unrestricted_runtime_access(context))
+
+
+def _has_runtime_owner_access(context: Any) -> bool:
+ if context is None:
+ return False
+ if context.is_remote and not _has_temporary_runtime_access(context):
+ return False
+ return bool(context.is_instance_owner or _has_temporary_runtime_access(context))
@app.before_request
def enforce_instance_role_capabilities():
if _remote_auth_exempt_path():
return None
- from vibe.authorization import http_authorization_policy
+ from vibe.authorization import (
+ InstanceAuthorizationError,
+ REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER,
+ has_temporary_unrestricted_org_access,
+ http_authorization_policy,
+ require_instance_role,
+ )
- policy = http_authorization_policy(request.method, request.path)
+ policy = http_authorization_policy(
+ request.method,
+ request.path,
+ )
g.http_authorization_policy = policy
minimum_role = policy.minimum_role
if minimum_role is None:
return None
- context = getattr(g, "authorization_context", None)
- if context is None or not context.has_role(minimum_role):
+ try:
+ context = getattr(g, "authorization_context", None)
+ except (LookupError, RuntimeError):
+ # This helper is also exercised by pure policy tests outside a request.
+ context = None
+ if context is None:
+ return jsonify(
+ {
+ "ok": False,
+ "error": "instance_access_forbidden",
+ "required_role": minimum_role,
+ }
+ ), 403
+ # Known temporary runtime routes are admitted only for an active
+ # Organization member. Preserve the established remote-disabled response
+ # for other authenticated remote principals instead of leaking a role-only
+ # failure before the remote execution boundary can classify the request.
+ if (
+ context.is_remote
+ and policy.remote_access == REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER
+ and request.path.startswith("/api/")
+ and not has_temporary_unrestricted_org_access(context)
+ ):
+ return _remote_execution_disabled_response()
+ try:
+ require_instance_role(context, minimum_role)
+ except InstanceAuthorizationError:
return jsonify(
{
"ok": False,
@@ -2557,7 +2604,10 @@ def _is_remote_local_execution_request(method: str, path: str, payload: Any = No
http_authorization_policy,
)
- remote_access = http_authorization_policy(method, path).remote_access
+ remote_access = http_authorization_policy(
+ method,
+ path,
+ ).remote_access
if remote_access == REMOTE_HTTP_LOCAL_ONLY:
return True
if remote_access != REMOTE_HTTP_PAYLOAD_FILTERED:
@@ -2569,22 +2619,38 @@ def _is_remote_local_execution_request(method: str, path: str, payload: Any = No
async def enforce_remote_local_execution_boundary():
"""Keep unapproved local-machine capabilities on the trusted-local origin."""
- context = getattr(g, "authorization_context", None)
+ try:
+ context = getattr(g, "authorization_context", None)
+ except (LookupError, RuntimeError):
+ context = None
if context is None or not context.is_remote:
return None
from vibe.authorization import (
REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER,
REMOTE_HTTP_LOCAL_ONLY,
REMOTE_HTTP_PAYLOAD_FILTERED,
- has_temporary_unrestricted_org_app_access,
+ has_temporary_unrestricted_org_access,
http_authorization_policy,
)
policy = getattr(g, "http_authorization_policy", None)
if policy is None:
- policy = http_authorization_policy(request.method, request.path)
+ policy = http_authorization_policy(
+ request.method,
+ request.path,
+ )
if policy.remote_access == REMOTE_HTTP_ACTIVE_ORGANIZATION_MEMBER:
- if has_temporary_unrestricted_org_app_access(context):
+ if has_temporary_unrestricted_org_access(context):
+ if request.method == "POST" and request.path == "/api/config":
+ # Runtime configuration is temporarily writable for active
+ # Organization members, but remote access identity/tunnel
+ # settings remain control-plane owned. Drop that block before
+ # it reaches the generic config merge/save path.
+ payload = await request.load_json()
+ if isinstance(payload, dict):
+ payload = dict(payload)
+ payload.pop("remote_access", None)
+ g.remote_unrestricted_config_payload = payload
return None
return _remote_execution_disabled_response()
if policy.remote_access == REMOTE_HTTP_LOCAL_ONLY:
@@ -2622,14 +2688,23 @@ def enforce_project_role_capabilities():
if _remote_auth_exempt_path():
return None
context = getattr(g, "authorization_context", None)
- if context is None or context.is_instance_owner:
+ if context is None or _has_runtime_owner_access(context):
return None
from storage import project_access_service
from storage.db import create_sqlite_engine
from vibe.authorization import required_instance_role
- minimum_instance_role = required_instance_role(request.method, request.path)
+ minimum_instance_role = getattr(
+ g,
+ "http_authorization_policy",
+ None,
+ )
+ minimum_instance_role = (
+ minimum_instance_role.minimum_role
+ if minimum_instance_role is not None
+ else required_instance_role(request.method, request.path)
+ )
if minimum_instance_role not in {"viewer", "editor"}:
return None
resource = _project_access_resource(request.path)
@@ -2638,9 +2713,7 @@ def enforce_project_role_capabilities():
kind, resource_id = resource
if kind == "show_page":
- from vibe.authorization import has_temporary_unrestricted_org_app_access
-
- if has_temporary_unrestricted_org_app_access(context) or context.can_use_show_page(
+ if _has_temporary_runtime_access(context) or context.can_use_show_page(
resource_id
):
return None
@@ -3267,30 +3340,35 @@ def _show_runtime_websocket_authorized(
return False
from vibe.authorization import (
context_from_session_payload,
- has_temporary_unrestricted_org_app_access,
+ has_temporary_unrestricted_org_access,
)
context = context_from_session_payload(payload)
- if not context.has_role(minimum_role):
- return False
- if require_unrestricted_org_apps and not has_temporary_unrestricted_org_app_access(
- context
- ):
+ temporary_org_access = has_temporary_unrestricted_org_access(context)
+ 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
- if project_session_id is None or context.is_instance_owner:
+ if project_session_id is None or _has_runtime_owner_access(context):
return True
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_app_access
+ from vibe.authorization import has_temporary_unrestricted_org_access
- if (
- context is None
- or context.is_instance_owner
- or has_temporary_unrestricted_org_app_access(context)
- ):
+ if context is None:
+ return False
+ if context.is_remote and 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):
return False
@@ -3326,9 +3404,15 @@ async def _wait_for_project_session_access_loss(
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_app_access
+ from vibe.authorization import has_temporary_unrestricted_org_access
- if context is None or has_temporary_unrestricted_org_app_access(context):
+ if context is None:
+ return False
+ if context.is_remote and 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(
@@ -3361,7 +3445,7 @@ def _show_runtime_websocket_resource_context(websocket: Any):
payload = _remote_access_websocket_session_payload(websocket, config)
if payload is None:
return resource_access_service.ResourceUserContext()
- return _temporary_org_app_resource_context(
+ return _temporary_org_runtime_resource_context(
resource_access_service.current_resource_context(
payload,
is_remote=True,
@@ -3853,16 +3937,29 @@ def config_get():
# (``save_config``) already creates the file on the first real save.
config = settings_service.load_config_or_default()
authorization_context = getattr(g, "authorization_context", None)
- if authorization_context is None or not authorization_context.is_remote:
- payload = api.client_config_payload(config)
- payload["capabilities"] = {"model_hub": {"enabled": is_model_hub_enabled()}}
- return jsonify(payload)
-
- payload = api.remote_config_payload(config)
+ payload = _config_payload_for_context(config, authorization_context)
payload["capabilities"] = {"model_hub": {"enabled": is_model_hub_enabled()}}
return jsonify(payload)
+def _config_payload_for_context(config: Any, authorization_context: Any) -> dict[str, Any]:
+ """Project config without turning a remote member into a local identity."""
+
+ from vibe import api
+
+ if authorization_context is None or not authorization_context.is_remote:
+ 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
+
+
_MODEL_HUB_SERVICE = None
@@ -4311,6 +4408,7 @@ def vibe_agents_get():
from vibe import api
try:
+ user_context = getattr(g, "authorization_context", None)
include_disabled = str(request.args.get("include_disabled") or request.args.get("all") or "").lower() in {
"1",
"true",
@@ -4326,6 +4424,7 @@ def vibe_agents_get():
backend=request.args.get("backend") or None,
include_disabled=include_disabled,
include_archived=include_archived,
+ user_context=user_context,
)
)
except (ValueError, PermissionError) as exc:
@@ -4339,9 +4438,10 @@ def vibe_agent_onboarding():
from vibe import api
try:
+ user_context = getattr(g, "authorization_context", None)
if request.method == "POST":
- return jsonify(api.onboard_vibe_agents())
- return jsonify(api.get_vibe_agent_onboarding())
+ return jsonify(api.onboard_vibe_agents(user_context=user_context))
+ return jsonify(api.get_vibe_agent_onboarding(user_context=user_context))
except (ValueError, PermissionError) as exc:
return _vibe_agent_error_response(exc)
@@ -4436,7 +4536,7 @@ def vibe_agent_get(name):
from vibe import api
try:
- return jsonify(api.get_vibe_agent(name))
+ return jsonify(api.get_vibe_agent(name, user_context=getattr(g, "authorization_context", None)))
except (ValueError, PermissionError) as exc:
return _vibe_agent_error_response(exc)
@@ -4446,7 +4546,12 @@ def vibe_agents_post():
from vibe import api
try:
- return _vibe_agent_result_response(api.create_vibe_agent(request.json or {}))
+ return _vibe_agent_result_response(
+ api.create_vibe_agent(
+ request.json or {},
+ user_context=getattr(g, "authorization_context", None),
+ )
+ )
except (ValueError, PermissionError) as exc:
return _vibe_agent_error_response(exc)
@@ -4456,7 +4561,12 @@ def vibe_agents_import_post():
from vibe import api
try:
- return _vibe_agent_result_response(api.import_vibe_agents(request.json or {}))
+ return _vibe_agent_result_response(
+ api.import_vibe_agents(
+ request.json or {},
+ user_context=getattr(g, "authorization_context", None),
+ )
+ )
except (ValueError, PermissionError) as exc:
return _vibe_agent_error_response(exc)
@@ -4467,7 +4577,12 @@ def vibe_agents_default_post():
payload = request.json or {}
try:
- return jsonify(api.set_default_vibe_agent(payload.get("name") or ""))
+ return jsonify(
+ api.set_default_vibe_agent(
+ payload.get("name") or "",
+ user_context=getattr(g, "authorization_context", None),
+ )
+ )
except (ValueError, PermissionError) as exc:
return _vibe_agent_error_response(exc)
@@ -4477,7 +4592,13 @@ def vibe_agent_patch(name):
from vibe import api
try:
- return _vibe_agent_result_response(api.update_vibe_agent(name, request.json or {}))
+ return _vibe_agent_result_response(
+ api.update_vibe_agent(
+ name,
+ request.json or {},
+ user_context=getattr(g, "authorization_context", None),
+ )
+ )
except (ValueError, PermissionError) as exc:
return _vibe_agent_error_response(exc)
@@ -4487,7 +4608,12 @@ def vibe_agent_delete(name):
from vibe import api
try:
- return _vibe_agent_result_response(api.remove_vibe_agent(name))
+ return _vibe_agent_result_response(
+ api.remove_vibe_agent(
+ name,
+ user_context=getattr(g, "authorization_context", None),
+ )
+ )
except (ValueError, PermissionError) as exc:
return _vibe_agent_error_response(exc)
@@ -4496,7 +4622,12 @@ def vibe_agent_delete(name):
def settings_get():
from vibe import api
- return jsonify(api.get_settings(request.args.get("platform") or None))
+ return jsonify(
+ api.get_settings(
+ request.args.get("platform") or None,
+ user_context=getattr(g, "authorization_context", None),
+ )
+ )
def _vault_error_response(exc):
@@ -4949,7 +5080,8 @@ def _is_remote_show_page_request() -> bool:
def _show_page_payload_for_request(payload: dict) -> dict:
- if not _is_remote_show_page_request():
+ 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"}
@@ -4960,7 +5092,7 @@ def show_pages_list_get():
from vibe import api
context = getattr(g, "authorization_context", None)
- resource_context = _temporary_org_app_resource_context(context)
+ resource_context = _temporary_org_runtime_resource_context(context)
payload = api.list_show_pages(user_context=resource_context)
if _is_remote_show_page_request():
payload = {
@@ -4972,8 +5104,7 @@ def show_pages_list_get():
}
if (
context is not None
- and not context.is_instance_owner
- and not getattr(resource_context, "is_trusted_local", False)
+ and not _has_runtime_owner_access(context)
):
engine = _projects_engine()
with engine.connect() as conn:
@@ -5004,7 +5135,7 @@ def show_page_visibility_post(session_id):
api.set_show_page_visibility(
session_id,
str(payload.get("visibility") or ""),
- user_context=_temporary_org_app_resource_context(),
+ user_context=_temporary_org_runtime_resource_context(),
)
)
except ShowPageError as exc:
@@ -5021,7 +5152,7 @@ def show_page_ensure_post(session_id):
_show_page_payload_for_request(
api.ensure_show_page(
session_id,
- user_context=_temporary_org_app_resource_context(),
+ user_context=_temporary_org_runtime_resource_context(),
)
)
)
@@ -5038,7 +5169,7 @@ def show_page_access_get(session_id):
response = jsonify(
api.get_show_page_access(
session_id,
- user_context=_temporary_org_app_resource_context(),
+ user_context=_temporary_org_runtime_resource_context(),
)
)
response.headers["Cache-Control"] = "no-store, private"
@@ -5057,7 +5188,7 @@ def show_page_authorized_emails_get(session_id):
response = jsonify(
api.get_show_page_authorized_emails(
session_id,
- user_context=_temporary_org_app_resource_context(),
+ user_context=_temporary_org_runtime_resource_context(),
)
)
response.headers["Cache-Control"] = "no-store, private"
@@ -5087,7 +5218,7 @@ def show_page_authorized_emails_put(session_id):
api.replace_show_page_authorized_emails(
session_id,
emails,
- user_context=_temporary_org_app_resource_context(),
+ user_context=_temporary_org_runtime_resource_context(),
)
)
except ShowPageError as exc:
@@ -5103,7 +5234,7 @@ def show_page_rotate_share_post(session_id):
return jsonify(
api.rotate_show_page_share(
session_id,
- user_context=_temporary_org_app_resource_context(),
+ user_context=_temporary_org_runtime_resource_context(),
)
)
except ShowPageError as exc:
@@ -5121,7 +5252,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_app_resource_context(),
+ user_context=_temporary_org_runtime_resource_context(),
)
)
except ShowPageError as exc:
@@ -5164,7 +5295,7 @@ def show_page_icon_get(session_id):
try:
page = store.require_access(
session_id,
- user_context=_temporary_org_app_resource_context(),
+ user_context=_temporary_org_runtime_resource_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
@@ -5223,7 +5354,7 @@ def _dock_error_response(exc):
def dock_get():
from vibe import api
- return jsonify(api.get_dock(user_context=_temporary_org_app_resource_context()))
+ return jsonify(api.get_dock(user_context=_temporary_org_runtime_resource_context()))
@app.route("/api/dock/pins", methods=["POST"])
@@ -5237,7 +5368,7 @@ def dock_pin_post():
return jsonify(
api.pin_dock_show_page(
str(payload.get("session_id") or ""),
- user_context=_temporary_org_app_resource_context(),
+ user_context=_temporary_org_runtime_resource_context(),
)
)
except (DockError, ShowPageError) as exc:
@@ -5254,7 +5385,7 @@ def dock_unpin_delete(session_id):
return jsonify(
api.unpin_dock_show_page(
session_id,
- user_context=_temporary_org_app_resource_context(),
+ user_context=_temporary_org_runtime_resource_context(),
)
)
except (DockError, ShowPageError) as exc:
@@ -5277,7 +5408,7 @@ def dock_order_put():
api.set_dock_order(
payload.get("order"),
known=payload.get("known"),
- user_context=_temporary_org_app_resource_context(),
+ user_context=_temporary_org_runtime_resource_context(),
)
)
except (DockError, ShowPageError) as exc:
@@ -5712,8 +5843,11 @@ async def config_post():
from vibe import remote_access
remote_mutable_payload = getattr(g, "remote_mutable_config_payload", None)
+ unrestricted_payload = getattr(g, "remote_unrestricted_config_payload", None)
payload = (
- remote_mutable_payload
+ unrestricted_payload
+ if unrestricted_payload is not None
+ else remote_mutable_payload
if remote_mutable_payload is not None
else request.json or {}
)
@@ -5794,16 +5928,16 @@ async def config_post():
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)
- response_payload = (
- api.remote_config_payload(config)
- if is_remote
- else api.client_config_payload(config)
- )
- # Remote config writes are restricted to preferences. Runtime reconciliation
- # results belong to trusted-local configuration and can expose local state.
+ 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:
@@ -6559,7 +6693,7 @@ def api_session():
from vibe import remote_access
from vibe.authorization import (
context_from_session_payload,
- has_temporary_unrestricted_org_app_access,
+ has_temporary_unrestricted_org_access,
trusted_local_context,
)
@@ -6596,8 +6730,11 @@ def api_session():
"email": str(payload.get("email", "")),
"sub": str(payload.get("sub", "")),
"instance_role": context.instance_role,
+ "temporary_unrestricted_org_access": (
+ has_temporary_unrestricted_org_access(context)
+ ),
"temporary_unrestricted_org_app_access": (
- has_temporary_unrestricted_org_app_access(context)
+ has_temporary_unrestricted_org_access(context)
),
"capabilities": context.capability_projection(),
}
@@ -7823,7 +7960,7 @@ def _accessible_project_scope_ids_for_context(conn, context) -> list[str] | None
"""Return a principal's readable Project scopes; owners need no SQL filter."""
from storage import project_access_service
- if context is None or context.is_instance_owner:
+ if context is None or _has_runtime_owner_access(context):
return None
return sorted(
project_access_service.project_scope_id(project_id)
@@ -7994,12 +8131,12 @@ def _resolve_project_dir(project_id):
authorization_context = getattr(g, "authorization_context", None)
engine = _projects_engine()
with engine.connect() as conn:
- project = projects_service.get_project(
+ folder = projects_service.get_project_workdir(
conn,
project_id,
authorization_context=authorization_context,
)
- folder = (project.get("folder_path") or "").strip()
+ folder = folder.strip()
if not folder:
raise _ProjectNoFolder(project_id)
return folder
@@ -8116,6 +8253,7 @@ def global_prompts_save():
async def skills_list():
from vibe import api
+ user_context = getattr(g, "authorization_context", None)
scope = request.args.get("scope") or "all"
backends = [b for b in (request.args.get("backends") or "").split(",") if b]
project_id = request.args.get("project_id")
@@ -8129,6 +8267,7 @@ async def skills_list():
result = await api.list_skills(
scope="global",
backends=backends or None,
+ user_context=user_context,
**_skills_project_id_kwargs(None, project_id),
)
if isinstance(result, dict) and result.get("ok"):
@@ -8139,6 +8278,7 @@ async def skills_list():
scope=scope,
project_dir=project_dir,
backends=backends or None,
+ user_context=user_context,
**_skills_project_id_kwargs(project_dir, project_id),
)
)
@@ -8148,6 +8288,7 @@ async def skills_list():
async def skills_preview():
from vibe import api
+ user_context = getattr(g, "authorization_context", None)
payload = request.json or {}
project_id = payload.get("project_id")
try:
@@ -8160,6 +8301,7 @@ async def skills_preview():
await api.preview_skill_source(
str(payload.get("source") or ""),
project_dir=project_dir,
+ user_context=user_context,
**_skills_project_id_kwargs(project_dir, project_id),
)
)
@@ -8169,6 +8311,7 @@ async def skills_preview():
async def skills_add():
from vibe import api
+ user_context = getattr(g, "authorization_context", None)
payload = request.json or {}
project_id = payload.get("project_id")
try:
@@ -8187,6 +8330,7 @@ async def skills_add():
all_skills=bool(payload.get("all")),
skill=payload.get("skill") or None,
copy=bool(payload.get("copy")),
+ user_context=user_context,
)
)
@@ -8195,6 +8339,7 @@ async def skills_add():
async def skills_remove(name):
from vibe import api
+ user_context = getattr(g, "authorization_context", None)
backends = [b for b in (request.args.get("backends") or "").split(",") if b]
project_id = request.args.get("project_id")
try:
@@ -8210,6 +8355,7 @@ async def skills_remove(name):
project_dir=project_dir,
project_id=project_id,
backends=backends or None,
+ user_context=user_context,
)
)
@@ -8218,13 +8364,19 @@ async def skills_remove(name):
async def skills_find():
from vibe import api
- return jsonify(await api.find_skills(request.args.get("q") or ""))
+ return jsonify(
+ await api.find_skills(
+ request.args.get("q") or "",
+ user_context=getattr(g, "authorization_context", None),
+ )
+ )
@app.route("/api/skills/check", methods=["GET"])
async def skills_check():
from vibe import api
+ user_context = getattr(g, "authorization_context", None)
scope = request.args.get("scope") or "project"
project_id = request.args.get("project_id")
try:
@@ -8234,13 +8386,21 @@ async def skills_check():
except _ProjectNoFolder:
# Folderless project has no project-local skills, so nothing to check.
return jsonify({"ok": True, "skills": []})
- return jsonify(await api.check_skills(scope=scope, project_dir=project_dir, project_id=project_id))
+ return jsonify(
+ await api.check_skills(
+ scope=scope,
+ project_dir=project_dir,
+ project_id=project_id,
+ user_context=user_context,
+ )
+ )
@app.route("/api/skills/update", methods=["POST"])
async def skills_update():
from vibe import api
+ user_context = getattr(g, "authorization_context", None)
payload = request.json or {}
project_id = payload.get("project_id")
try:
@@ -8255,6 +8415,7 @@ async def skills_update():
scope=payload.get("scope") or "project",
project_dir=project_dir,
project_id=project_id,
+ user_context=user_context,
)
)
@@ -8263,6 +8424,7 @@ async def skills_update():
async def skills_upload():
from vibe import api
+ user_context = getattr(g, "authorization_context", None)
payload = request.json or {}
project_id = payload.get("project_id")
try:
@@ -8277,6 +8439,7 @@ async def skills_upload():
await api.upload_skill_zip(
payload,
project_dir=project_dir,
+ user_context=user_context,
**_skills_project_id_kwargs(project_dir, project_id),
)
)
@@ -8638,7 +8801,12 @@ def _session_runtime_projection(
if isinstance(raw_activities, list)
else []
)
- if getattr(authorization_context, "is_remote", False):
+ 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)
+ ):
activities = [
item
for item in activities
@@ -8709,8 +8877,12 @@ async def sessions_bootstrap(session_id: str):
if can_chat
else []
)
- can_access_draft = can_chat and not bool(
- authorization_context and authorization_context.is_remote
+ 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)
)
draft = message_deliveries.get_draft(conn, session_id) if can_access_draft else None
@@ -8726,11 +8898,7 @@ async def sessions_bootstrap(session_id: str):
try:
config = settings_service.load_config_or_default()
- config_payload = (
- vibe_api.remote_config_payload(config)
- if authorization_context and authorization_context.is_remote
- else vibe_api.client_config_payload(config)
- )
+ config_payload = _config_payload_for_context(config, authorization_context)
except Exception:
logger.exception("sessions_bootstrap: failed to load config")
config_payload = None
@@ -9653,7 +9821,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_app_resource_context(),
+ user_context=_temporary_org_runtime_resource_context(),
)
# Broadcast so EVERY already-mounted inventory (Dock, WindowLayer, mobile
# drawer, app search) reloads and picks up the new icon_version — the
@@ -9962,19 +10130,19 @@ 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_app_access
+ 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_app_access(
+ 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 context.is_instance_owner:
+ if context is None or _has_runtime_owner_access(context):
return True
session_ids = media_service.referenced_session_ids(conn, token)
if session_ids:
@@ -10002,6 +10170,7 @@ def _registered_media_response(
*,
expected_session_id: str | None = None,
expected_source: str | None = None,
+ public_show_page: bool = False,
):
from urllib.parse import quote
@@ -10010,8 +10179,6 @@ def _registered_media_response(
engine = _projects_engine()
with engine.connect() as conn:
row = media_service.get_by_token(conn, token)
- if row and not _request_can_read_media_row(conn, token, row):
- row = None
matches_expected_session = (
expected_session_id is None
or bool(row)
@@ -10020,11 +10187,29 @@ def _registered_media_response(
or media_service.is_referenced_by_session(conn, token, expected_session_id)
)
)
+ matches_expected_source = (
+ expected_source is None
+ or bool(row)
+ and row.get("source") == expected_source
+ )
+ public_show_page_validated = bool(
+ public_show_page
+ and expected_session_id
+ and expected_source == "show_annotation"
+ and matches_expected_session
+ and matches_expected_source
+ )
+ if row and not public_show_page_validated and not _request_can_read_media_row(
+ conn,
+ token,
+ row,
+ ):
+ row = None
if not row or row.get("revoked_at"):
return jsonify({"error": "not_found"}), 404
if not matches_expected_session:
return jsonify({"error": "not_found"}), 404
- if expected_source is not None and row.get("source") != expected_source:
+ if not matches_expected_source:
return jsonify({"error": "not_found"}), 404
stored = row["local_path"]
try:
@@ -11053,13 +11238,13 @@ 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_app_access
+ from vibe.authorization import has_temporary_unrestricted_org_access
- if has_temporary_unrestricted_org_app_access(context):
+ 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
- if context.is_instance_owner:
+ if _has_runtime_owner_access(context):
return True
if event_type in {"authorization.changed", "workbench.events.bridge.status"}:
return True
@@ -11093,7 +11278,12 @@ def _workbench_event_payload_for_context(context, event_type: str, payload: str)
Returns ``None`` when the event cannot be projected safely for this
recipient, in which case the caller drops the frame.
"""
- if event_type == "show.event" and context is not None and context.is_remote:
+ if (
+ event_type == "show.event"
+ and context is not None
+ and context.is_remote
+ and not _has_temporary_runtime_access(context)
+ ):
# A Show annotation event carries the absolute host path of its
# materialized screenshot. Remote subscribers read the image by
# attachment id, so drop the path rather than stream the host layout —
@@ -11110,7 +11300,12 @@ 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:
+ 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):
@@ -11255,7 +11450,7 @@ async def workbench_events():
if (
event_type == "authorization.changed"
and authorization_context is not None
- and not authorization_context.is_instance_owner
+ and not _has_runtime_owner_access(authorization_context)
):
payload = json.dumps(
{
@@ -12314,12 +12509,17 @@ def _sanitize_public_show_event_payload(payload: dict[str, Any]) -> dict[str, An
def _show_request_author(*, public: bool = False) -> dict[str, str] | None:
from vibe import remote_access
- from vibe.authorization import context_from_session_payload
+ from vibe.authorization import (
+ context_from_session_payload,
+ has_temporary_unrestricted_runtime_access,
+ )
if not public:
context = getattr(g, "authorization_context", None)
if context is not None:
- if not context.has_role("editor"):
+ if not context.has_role("editor") and not has_temporary_unrestricted_runtime_access(
+ context
+ ):
return None
if context.is_remote:
return {"kind": "user", "email": context.email} if context.email else None
@@ -12338,7 +12538,10 @@ 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"):
+ if email and (
+ context.has_role("editor")
+ or has_temporary_unrestricted_runtime_access(context)
+ ):
return {"kind": "user", "email": email}
return None
@@ -12373,7 +12576,11 @@ async def _show_event_response_from_payload(
):
context = getattr(g, "authorization_context", None)
is_remote_caller = context is not None and context.is_remote
- if is_remote_caller and show_event_request_requests_dispatch(payload):
+ if (
+ is_remote_caller
+ and show_event_request_requests_dispatch(payload)
+ and not _has_temporary_runtime_access(context)
+ ):
return _remote_execution_disabled_response()
if is_remote_caller or public:
# A remote caller — whether an authenticated editor on the HTML route or
@@ -12399,9 +12606,13 @@ async def _show_event_response_from_payload(
),
400,
)
- # The echo of the stored event goes back to whoever posted it, so a remote
- # author must not learn the local screenshot path from its own response.
- remote = not public and _is_remote_show_page_request()
+ # 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)
+ )
if show_event_payload_session_mismatch(session_id, payload):
return (
jsonify(
@@ -13050,10 +13261,13 @@ async def _show_events_response(
public: bool = False,
public_share_id: str | None = None,
):
- # A remote reader of the private Show surface must not receive local
- # screenshot paths either; resolve it here because the SSE generator runs
- # after the request context is gone.
- remote = not public and _is_remote_show_page_request()
+ # 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)
+ )
if request.method == "GET":
if request.args.get("stream") == "1":
return await _show_events_stream(
@@ -13065,9 +13279,7 @@ async def _show_events_response(
authorization_refresh_at=(
None if public else getattr(g, "remote_authorization_refresh_at", None)
),
- authorization_context=(
- None if public else getattr(g, "authorization_context", None)
- ),
+ authorization_context=authorization_context,
remote_session_payload=(
None if public else getattr(g, "remote_session_payload", None)
),
@@ -13822,7 +14034,7 @@ def redirect_private_show_page_to_canonical_path(session_id):
try:
page = store.require_access(
session_id,
- user_context=_temporary_org_app_resource_context(),
+ user_context=_temporary_org_runtime_resource_context(),
)
except ShowPageError as exc:
if exc.code == "resource_access_forbidden":
@@ -13856,7 +14068,7 @@ async def serve_private_show_page(session_id, asset_path):
try:
page = store.require_access(
session_id,
- user_context=_temporary_org_app_resource_context(),
+ user_context=_temporary_org_runtime_resource_context(),
)
except ShowPageError as exc:
if exc.code == "resource_access_forbidden":
@@ -13993,6 +14205,7 @@ async def serve_public_show_page(share_id, asset_path):
token,
expected_session_id=page.session_id,
expected_source="show_annotation",
+ public_show_page=True,
)
if asset_path.strip("/") in {"__show/events", "__events"}:
if request.method == "GET":