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.

chore(merge): integrate latest master and close release gate

Max7d1ca1ffccc3
diff --cc core/controller.py
index 3a2051792,e4d9ab2a3..e693937d1
--- a/core/controller.py
+++ b/core/controller.py
@@@ -1962,56 -1868,12 +2037,54 @@@ class Controller
pass
self.cleanup_task = None
+ async def _cancel_internal_server_task() -> None:
+ task = getattr(self, "_internal_server_task", None)
+ if task is not None and not task.done():
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ self._internal_server_task = None
+
+ async def _cancel_memory_reconcile_task() -> None:
+ task = getattr(self, "_memory_reconcile_task", None)
+ try:
+ if task is not None:
+ if not task.done():
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ except Exception as error:
+ logger.debug("Memory startup reconciliation already failed: %s", error)
+ finally:
+ self._memory_reconcile_task = None
+
+ # Without this the task is never settled, so the done callback that
+ # records "stopped" never runs and internal-server.json keeps saying
+ # "ready" after the service exits.
+ _stop_loop_coroutine(_cancel_internal_server_task(), "Internal dispatch server")
+ try:
+ from core import internal_server as _internal_server
+
+ _internal_server.note_stopped()
+ except Exception as e:
+ logger.debug(f"Internal dispatch server status write skipped: {e}")
+
_stop_loop_coroutine(_cancel_cleanup_task(), "Idle cleanup task")
- _stop_loop_coroutine(self.scheduled_task_service.stop(), "Scheduled task service")
- supervisor = getattr(self, "runtime_work_supervisor", None)
- stop_supervisor = getattr(supervisor, "stop", None)
- if callable(stop_supervisor):
- _stop_loop_coroutine(stop_supervisor(), "Runtime work supervisor")
- _stop_loop_coroutine(self.watch_service.stop(), "Watch service")
+ _stop_loop_coroutine(
+ self._join_runtime_work_stack_shutdown(),
+ "Runtime work stack",
+ )
_stop_loop_coroutine(self.runtime_command_watcher.stop(), "Runtime command watcher")
+ # Reconciliation can start the sidecar, so settle it before closing the
+ # runtime or it could race shutdown and leave a process behind.
+ _stop_loop_coroutine(_cancel_memory_reconcile_task(), "Memory startup reconciliation")
+ memory_runtime = getattr(self, "memory_runtime", None)
+ if memory_runtime is not None:
+ _stop_loop_coroutine(memory_runtime.close(), "Memory runtime")
model_hub_turn_gateway = getattr(self, "model_hub_turn_gateway", None)
if model_hub_turn_gateway is not None:
_stop_loop_coroutine(model_hub_turn_gateway.close(), "Model Hub turn gateway")
diff --cc docs/plans/2026-08-04-org-master-conservative-harness-gate.md
index 0c20c2115,000000000..4617f9ed2
mode 100644,000000..100644
--- a/docs/plans/2026-08-04-org-master-conservative-harness-gate.md
+++ b/docs/plans/2026-08-04-org-master-conservative-harness-gate.md
@@@ -1,78 -1,0 +1,80 @@@
+# Organization-to-Master Conservative Execution Gate
+
+Status: Approved for the `org` to `master` integration release on 2026-08-04.
+
+## Background
+
+PR #1162 carries Organization principals into the local Workbench and Resource
+ACL model. The Agent runtimes are intentionally shell-capable and can mutate
+their own environment, so Agent environment variables cannot authenticate a
+remote caller or turn persisted identity into durable execution authority.
+
+The existing Organization-aware Harness plan already defines stored principal
+data as provenance, not bearer authority, and requires an authoritative local
+entitlement mirror before remote recurring execution can be enabled.
+
+## Approved Release Boundary
+
+- Keep Organization management, Project and Resource ACL management, and
+ authorized Project, Session, message, and history reads.
+- Keep trusted-local Workbench, CLI, Task, Watch, Agent, terminal, and file
+ behavior unchanged.
+- Keep IM-triggered Agent behavior unchanged.
+- Make every remote Workbench capability read-only with respect to local Agent,
+ terminal, file, and Harness execution.
+- Reject remote Task and Watch creation or update at the definition service
+ boundary when an explicit remote `AuthorizationContext` is present.
+- Suspend previously persisted remote-origin Tasks and Watches before any Agent,
+ command, or waiter process starts.
+- Retire previously queued remote Workbench Deliveries before they can be
+ claimed by a durable Agent turn.
+- Treat persisted `resource_user_context` only as provenance indicating remote
+ origin. It is never sufficient authority for autonomous execution.
+
+## Enforcement Points
+
+1. The signed HTTP session projects remote `can_chat`, terminal, file, and
+ system execution capabilities as false.
+2. The UI server rejects remote message dispatch, Show-event Agent dispatch,
- Agent-definition and instruction mutations, service control, local
- installers, terminal sockets, file operations, and Harness definition
++ Agent-definition and instruction mutations, model/backend mutations and
++ runtime operations, service control, local installers, terminal sockets,
++ file operations including Show Page icon uploads, and Harness definition
+ mutations before invoking their underlying services.
+3. The durable Delivery owner retires remote-origin queue entries before the
+ FIFO claim that starts an Agent turn.
+4. Task and Watch stores reject explicit remote definition writes.
+5. Task and Watch executors detect persisted remote provenance and atomically
+ disable the definition with `remote_autonomous_harness_disabled` before any
+ process spawn or Agent dispatch.
+
+## Deferred Phase 2
+
+Remote Agent and autonomous Harness execution stay disabled until both are
+available:
+
+- server-mediated Agent tools whose caller identity cannot be removed or forged
+ by the Agent process; and
+- an authoritative local entitlement mirror that revalidates current Instance
+ revision, membership, role, groups, Project access, and Resource ACLs at every
+ launch and resume boundary.
+
+No opaque token passed through the current Agent environment is considered a
+substitute for either dependency.
+
+## Validation
+
+- Remote Workbench message and Show dispatch do not reserve or start a turn.
+- Remote terminal and file requests fail closed; trusted-local requests retain
+ existing behavior.
- - Remote service control, installers, and Agent-definition mutations fail before
- reaching their local runtime services.
++- Remote service control, installers, Agent-definition mutations, model/backend
++ mutations and probes, and Show Page icon writes fail before reaching their
++ local runtime or filesystem services.
+- Paired Project synchronization never forwards the device secret through an
+ HTTP redirect.
+- Remote Task and Watch add/update calls produce no definition write.
+- Existing remote-origin Tasks and Watches are disabled before command, waiter,
+ or Agent dispatch.
+- Existing queued remote Workbench Deliveries are retired before FIFO claim;
+ later local queue entries remain runnable.
+- Focused backend tests, frontend build, Ruff, lock validation, and diff checks
+ pass before the PR is pushed for a new current-head review.
diff --cc storage/vault_service.py
index b9b803032,77dbce147..9240e7cc3
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@@ -25,7 -25,7 +25,7 @@@ from datetime import datetime, timedelt
from typing import Any
from urllib.parse import urlsplit
- from sqlalchemy import and_, func, or_, select
-from sqlalchemy import func, or_, select, tuple_
++from sqlalchemy import and_, func, or_, select, tuple_
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.engine import Connection
from sqlalchemy.exc import IntegrityError
diff --cc tests/test_resource_acl_agents.py
index 08c68bdfd,000000000..16561d44b
mode 100644,000000..100644
--- a/tests/test_resource_acl_agents.py
+++ b/tests/test_resource_acl_agents.py
@@@ -1,633 -1,0 +1,631 @@@
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+from sqlalchemy import select
+
+from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore, TaskExecutionStore
+from core.vibe_agents import AgentImportCandidate, VibeAgent, VibeAgentAccessError, VibeAgentStore
+from core.watches import ManagedWatchStore
+from storage import resource_access_service, workbench_sessions_service
+from storage.db import get_cached_sqlite_engine
+from storage.models import resource_access_groups, resource_access_policies
+from storage.settings_service import upsert_scope
+from tests.test_ui_remote_access_auth import _remote_peer, _save_config
+from tests.ui_server_test_helpers import csrf_headers
+from vibe import remote_access
+from vibe.ui_server import app
+
+
+def _organization_context(
+ subject: str,
+ *,
+ group_ids: frozenset[str] | None = frozenset({"group-engineering"}),
+ instance_role: str = "editor",
+) -> resource_access_service.ResourceUserContext:
+ return resource_access_service.ResourceUserContext(
+ subject=subject,
+ email=f"{subject}@example.com",
+ organization_id="org-1",
+ organization_member_id=f"member-{subject}",
+ organization_role="member",
+ group_ids=group_ids,
+ instance_role=instance_role,
+ instance_access_source="organization_group",
+ is_remote=True,
+ )
+
+
+def _organization_cookie(
+ config,
+ *,
+ subject: str,
+ groups: list[str] | None = None,
+ instance_role: str = "viewer",
+) -> str:
+ claims = {
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": instance_role,
+ "vibe_instance_access_source": "organization_group",
+ "vibe_organization_id": "org-1",
+ "vibe_organization_member_id": f"member-{subject}",
+ "vibe_organization_role": "member",
+ "vibe_membership_version": "membership-v2",
+ }
+ if groups is not None:
+ claims["vibe_group_ids"] = groups
+ return remote_access.make_session_cookie(
+ config,
+ f"{subject}@example.com",
+ subject,
+ session_claims=claims,
+ )
+
+
+def _seed_agents_with_policies() -> tuple[VibeAgentStore, dict[str, VibeAgent]]:
+ store = VibeAgentStore()
+ agents = {
+ "private": store.create(name="private-agent", backend="codex"),
+ "public": store.create(name="public-agent", backend="codex"),
+ "scope": store.create(name="scope-agent", backend="codex"),
+ }
+ with store.engine.begin() as connection:
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind="agent",
+ resource_id=agents["private"].id,
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="private",
+ )
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind="agent",
+ resource_id=agents["public"].id,
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="public",
+ )
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind="agent",
+ resource_id=agents["scope"].id,
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="scope",
+ group_ids=["group-engineering"],
+ )
+ return store, agents
+
+
+def test_agent_catalog_filters_private_public_scope_and_missing_group_context(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store, _agents = _seed_agents_with_policies()
+ try:
+ owner_names = {agent.name for agent in store.list_agents(user_context=_organization_context("owner-1"))}
+ member_names = {agent.name for agent in store.list_agents(user_context=_organization_context("member-1"))}
+ no_group_names = {
+ agent.name
+ for agent in store.list_agents(user_context=_organization_context("member-2", group_ids=None))
+ }
+ finally:
+ store.close()
+
+ assert owner_names == {"private-agent", "public-agent", "scope-agent"}
+ assert member_names == {"public-agent", "scope-agent"}
+ assert no_group_names == {"public-agent"}
+
+
+def test_agent_removal_deletes_resource_policy_and_groups(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = VibeAgentStore()
+ try:
+ agent = store.create(name="removed-agent", backend="codex")
+ with store.engine.begin() as connection:
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind="agent",
+ resource_id=agent.id,
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="scope",
+ group_ids=["group-engineering"],
+ )
+
+ assert store.remove(agent.name) is True
+ with store.engine.connect() as connection:
+ policies = connection.execute(
+ select(resource_access_policies).where(
+ resource_access_policies.c.resource_kind == "agent",
+ resource_access_policies.c.resource_id == agent.id,
+ )
+ ).all()
+ groups = connection.execute(
+ select(resource_access_groups).where(
+ resource_access_groups.c.resource_kind == "agent",
+ resource_access_groups.c.resource_id == agent.id,
+ )
+ ).all()
+ finally:
+ store.close()
+
+ assert policies == []
+ assert groups == []
+
+
- def test_remote_agent_creation_defaults_to_private_organization_policy(monkeypatch, tmp_path) -> None:
++def test_remote_agent_creation_is_blocked_by_conservative_execution_gate(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ _organization_cookie(
+ config,
+ subject="member-1",
+ groups=["group-engineering"],
+ instance_role="owner",
+ ),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.post(
+ "/api/agents",
+ json={"name": "remote-private", "backend": "codex"},
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
- assert response.status_code == 200
- agent_id = response.get_json()["agent"]["id"]
- engine = get_cached_sqlite_engine()
- with engine.connect() as connection:
- policy = resource_access_service.get_resource_policy("agent", agent_id, connection=connection)
- assert policy is not None
- assert policy["organization_id"] == "org-1"
- assert policy["owner_user_id"] == "member-1"
- assert policy["access_level"] == "private"
++ assert response.status_code == 403
++ assert response.get_json()["code"] == "remote_execution_disabled"
++ store = VibeAgentStore()
++ try:
++ assert store.get("remote-private") is None
++ finally:
++ store.close()
+
+
+def test_agent_management_is_enforced_inside_the_store(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store, agents = _seed_agents_with_policies()
+ editor = _organization_context("member-1")
+ owner = _organization_context("owner-1", instance_role="owner")
+ try:
+ with pytest.raises(VibeAgentAccessError):
+ store.update(agents["public"].name, description="denied", user_context=editor)
+ with pytest.raises(VibeAgentAccessError):
+ store.remove(agents["public"].name, user_context=editor)
+ with pytest.raises(VibeAgentAccessError):
+ store.set_default_agent_name(agents["public"].name, user_context=editor)
+
+ updated = store.update(
+ agents["private"].name,
+ description="owner update",
+ user_context=owner,
+ )
+ assert updated.description == "owner update"
+ finally:
+ store.close()
+
+
+def test_remote_partial_agent_updates_persist_canonical_selector_pair(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store, agents = _seed_agents_with_policies()
+ store.close()
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as connection:
+ scope_id = upsert_scope(
+ connection,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_partial_agent",
+ now="2026-07-20T00:00:00Z",
+ )
+ session = workbench_sessions_service.create_session(
+ connection,
+ scope_id=scope_id,
+ agent_backend="",
+ agent_id=agents["public"].id,
+ user_context=_organization_context("member-1"),
+ )
+ by_name = workbench_sessions_service.update_session(
+ connection,
+ session["id"],
+ agent_name=agents["scope"].name,
+ user_context=_organization_context("member-1"),
+ )
+ by_id = workbench_sessions_service.update_session(
+ connection,
+ session["id"],
+ agent_id=agents["public"].id,
+ user_context=_organization_context("member-1"),
+ )
+
+ assert (session["agent_id"], session["agent_name"], session["agent_backend"]) == (
+ agents["public"].id,
+ agents["public"].name,
+ agents["public"].backend,
+ )
+ assert (by_name["agent_id"], by_name["agent_name"]) == (
+ agents["scope"].id,
+ agents["scope"].name,
+ )
+ assert (by_id["agent_id"], by_id["agent_name"]) == (
+ agents["public"].id,
+ agents["public"].name,
+ )
+
+
+def test_remote_agent_request_and_selection_reject_inaccessible_agent(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ store, agents = _seed_agents_with_policies()
+ private_agent = agents["private"]
+ public_agent = agents["public"]
+ store.set_default_agent_name(private_agent.name)
+ store.close()
+ context = _organization_context("member-1")
+
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ _organization_cookie(
+ config,
+ subject="member-1",
+ groups=["group-engineering"],
+ instance_role="editor",
+ ),
+ domain="alex.avibe.bot",
+ )
+ response = client.get(
+ "/api/agents/private-agent",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["error"] == "instance_access_forbidden"
+ catalog = client.get(
+ "/api/agents",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ public_mutation = client.patch(
+ "/api/agents/public-agent",
+ json={"description": "not allowed"},
+ 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"
+ default_mutation = client.post(
+ "/api/agents/default",
+ json={"name": public_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()
+
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as connection:
+ scope_id = upsert_scope(
+ connection,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_acl_agents",
+ now="2026-07-20T00:00:00Z",
+ )
+ with pytest.raises(VibeAgentAccessError):
+ workbench_sessions_service.create_session(
+ connection,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name=private_agent.name,
+ agent_id=private_agent.id,
+ user_context=context,
+ )
+ with pytest.raises(VibeAgentAccessError):
+ 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(
+ connection,
+ scope_id=scope_id,
+ agent_backend="codex",
+ user_context=resource_access_service.ResourceUserContext(is_trusted_local=True),
+ )
+ 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"] == "remote_execution_disabled"
+ assert dispatch_calls == []
+
+ with engine.begin() as connection:
+ resource_access_service.apply_control_plane_intent(
+ connection,
+ organization_id="org-1",
+ resource_kind="agent",
+ resource_id=public_agent.id,
+ revision=1,
+ access_level="private",
+ group_ids=[],
+ )
+ 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"] == "remote_execution_disabled"
+ assert dispatch_calls == []
+
+ with pytest.raises(
+ resource_access_service.ResourceAccessError,
+ match="remote_autonomous_harness_disabled",
+ ):
+ ScheduledTaskStore(tmp_path / "tasks.json").add_task(
+ session_key="avibe::project::proj_acl_agents",
+ prompt="run",
+ schedule_type="cron",
+ agent_name=private_agent.name,
+ cron="0 * * * *",
+ timezone_name="UTC",
+ user_context=context,
+ )
+ with pytest.raises(
+ resource_access_service.ResourceAccessError,
+ match="remote_autonomous_harness_disabled",
+ ):
+ ManagedWatchStore(tmp_path / "watches.json").add_watch(
+ name="acl watch",
+ session_key="avibe::project::proj_acl_agents",
+ command=["true"],
+ shell_command=None,
+ prefix=None,
+ cwd=str(tmp_path),
+ mode="once",
+ timeout_seconds=1,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=1,
+ post_to=None,
+ deliver_key=None,
+ agent_name=private_agent.name,
+ user_context=context,
+ )
+
+
+def test_remote_external_guest_cannot_create_agent(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"),
+ )
+ with pytest.raises(VibeAgentAccessError):
+ store.create(
+ name="guest-agent",
+ backend="codex",
+ user_context=resource_access_service.ResourceUserContext(
+ subject="guest-1",
+ instance_role="viewer",
+ instance_access_source="email",
+ is_remote=True,
+ ),
+ )
+ with pytest.raises(VibeAgentAccessError):
+ store.import_candidates(
+ [AgentImportCandidate(name="guest-import", backend="codex")],
+ user_context=resource_access_service.ResourceUserContext(
+ subject="guest-1",
+ instance_role="viewer",
+ instance_access_source="email",
+ is_remote=True,
+ ),
+ )
+ finally:
+ store.close()
+
+
+def test_remote_background_definitions_are_rejected_and_legacy_rows_fail_before_dispatch(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ agent_store, agents = _seed_agents_with_policies()
+ context = _organization_context("member-1")
+ task_store = ScheduledTaskStore(tmp_path / "tasks.json")
+ 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",
+ shell_command="touch should-not-run",
+ )
+ task.metadata = {
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "legacy-remote-user"
+ }
+ }
+ task_store.upsert_task(task)
+ 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,
+ )
+ watch.metadata = {
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "legacy-remote-user"
+ }
+ }
+ watch_store.upsert_watch(watch)
+
+ service = ScheduledTaskService(
+ controller=SimpleNamespace(),
+ store=task_store,
+ request_store=request_store,
+ )
+ task_result = asyncio.run(
+ service._execute_task(task, execution_id="task-run", disable_one_shot=False)
+ )
+ assert task_result.error == "remote_autonomous_harness_disabled"
+ stored_task = task_store.get_task(task.id)
+ assert stored_task is not None
+ assert stored_task.enabled is False
+ assert stored_task.last_error == "remote_autonomous_harness_disabled"
+ assert not (tmp_path / "should-not-run").exists()
+
+ request = request_store.enqueue_hook_send(
+ session_key=watch.session_key,
+ prompt="run watch",
+ agent_name=watch.agent_name,
+ session_policy=watch.session_policy,
+ run_type="watch",
+ definition_id=watch.id,
+ source_kind="watch",
+ metadata=watch.metadata,
+ )
+ claimed = request_store.claim(request.id)
+ assert claimed is not None
+ asyncio.run(service._execute_claimed_request(claimed))
+ completed = request_store.get_run(request.id)
+ assert completed is not None
+ assert completed["status"] == "failed"
+ assert completed["error"] == "remote_autonomous_harness_disabled"
+ finally:
+ agent_store.close()
diff --cc tests/test_ui_remote_access_auth.py
index adfdabce2,521fbed1a..c5a8d738f
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@@ -739,573 -599,10 +739,656 @@@ def test_loopback_origin_proxy_with_loo
follow_redirects=False,
)
- assert response.status_code != 503
+ assert response.status_code != 503
+
+
+def test_remote_host_allows_valid_remote_session(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"), domain="alex.avibe.bot")
+
+ response = client.get("/dashboard", base_url="https://alex.avibe.bot", follow_redirects=False)
+
+ assert response.status_code != 302
+
+
+def test_remote_generic_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"
+ config.memory.processing.llm.model = "private-model"
+ config.save()
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(config, "[email protected]", "user-1"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.get(
+ "/api/config",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 200
+ assert "memory" not in response.get_json()
+
+
+def test_remote_session_info_includes_authenticated_subject(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"),
+ 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",
+ "capabilities": {
+ "is_instance_owner": True,
+ "can_read_instance": True,
+ "can_chat": False,
+ "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,
+ },
+ }
+
+
+def test_remote_file_api_is_blocked_while_local_file_browsing_still_works(
+ 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"),
+ domain="alex.avibe.bot",
+ )
+
+ remote_response = client.get(
+ "/api/files/list",
+ params={"path": str(tmp_path)},
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ local_response = app.test_client().get(
+ "/api/files/list",
+ params={"path": str(tmp_path)},
+ base_url="http://localhost",
+ environ_base={"REMOTE_ADDR": "127.0.0.1"},
+ )
+
+ assert remote_response.status_code == 403
+ assert remote_response.get_json()["code"] == "remote_execution_disabled"
+ assert local_response.status_code == 200
+ assert local_response.get_json()["path"] == str(tmp_path.resolve())
+
+
+ ("method", "path", "json_body"),
+ [
+ ("PATCH", "/api/harness/tasks/task-1", {"enabled": False}),
+ ("DELETE", "/api/harness/tasks/task-1", None),
+ ("PATCH", "/api/harness/watches/watch-1", {"enabled": False}),
+ ("DELETE", "/api/harness/watches/watch-1", None),
+ ],
+)
+def test_remote_harness_mutations_are_blocked_before_store_access(
+ monkeypatch,
+ tmp_path,
+ method,
+ path,
+ json_body,
+):
+ 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"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.request(
+ method,
+ path,
+ json=json_body,
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "remote_execution_disabled"
+
+
+ ("path", "json_body", "controller_method"),
+ [
+ ("/api/sessions/ses-local/cancel", {}, "cancel_dispatch"),
+ (
+ "/api/running-agents/end",
+ {"backend": "codex", "base_session_id": "local-run"},
+ "end_running_agent",
+ ),
+ ],
+)
+def test_remote_agent_termination_is_blocked_before_controller_access(
+ monkeypatch,
+ tmp_path,
+ path,
+ json_body,
+ controller_method,
+):
+ 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"),
+ domain="alex.avibe.bot",
+ )
+
+ async def unexpected_controller_call(*args, **kwargs):
+ raise AssertionError("remote termination reached the local controller")
+
+ monkeypatch.setattr(
+ f"vibe.internal_client.{controller_method}",
+ unexpected_controller_call,
+ )
+ response = client.post(
+ path,
+ json=json_body,
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "remote_execution_disabled"
+
+
+def test_remote_session_archive_is_blocked_before_store_access(
+ 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"),
+ domain="alex.avibe.bot",
+ )
+
+ def unexpected_archive(*args, **kwargs):
+ raise AssertionError("remote archive reached the local session store")
+
+ monkeypatch.setattr(
+ "core.services.sessions.archive_session",
+ unexpected_archive,
+ )
+ response = client.delete(
+ "/api/sessions/ses-local",
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "remote_execution_disabled"
+
+
+ ("path", "json_body", "call_target"),
+ [
+ ("/api/control", {"action": "restart"}, "vibe.runtime.read_status"),
+ ("/api/upgrade", {}, "vibe.api.do_upgrade"),
+ ("/api/agent/codex/install", {}, "vibe.api.start_agent_install_job"),
+ (
+ "/api/dependencies/askill/install",
+ {},
+ "vibe.api.start_dependency_install_job",
+ ),
+ ],
+)
+def test_remote_system_operations_are_blocked_before_runtime_calls(
+ monkeypatch,
+ tmp_path,
+ path,
+ json_body,
+ call_target,
+):
+ 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"),
+ domain="alex.avibe.bot",
+ )
+
+ def unexpected_runtime_call(*args, **kwargs):
+ raise AssertionError("remote system operation reached the local runtime")
+
+ monkeypatch.setattr(call_target, unexpected_runtime_call)
+ response = client.post(
+ path,
+ json=json_body,
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "remote_execution_disabled"
+
+
++ ("path", "call_target"),
++ [
++ ("/api/models/runtime/start", "vibe.ui_server._model_hub_service"),
++ ("/api/models/agents/codex/probe", "vibe.ui_server._model_hub_service"),
++ ("/api/backend/codex/restart", "vibe.api.restart_backend"),
++ ("/api/backend/codex/auth/test", "vibe.api.test_backend_auth_async"),
++ ],
++)
++def test_remote_model_and_backend_operations_are_blocked_before_runtime_calls(
++ monkeypatch,
++ tmp_path,
++ path,
++ call_target,
++):
++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
++ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
++ 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"),
++ domain="alex.avibe.bot",
++ )
++
++ def unexpected_runtime_call(*args, **kwargs):
++ raise AssertionError("remote backend operation reached the local runtime")
++
++ monkeypatch.setattr(call_target, unexpected_runtime_call)
++ response = client.post(
++ path,
++ json={},
++ headers=csrf_headers(client, "https://alex.avibe.bot"),
++ base_url="https://alex.avibe.bot",
++ environ_base=_remote_peer(),
++ )
++
++ assert response.status_code == 403
++ assert response.get_json()["code"] == "remote_execution_disabled"
++
++
++def test_remote_show_page_icon_upload_is_blocked_before_filesystem_access(
++ 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"),
++ domain="alex.avibe.bot",
++ )
++
++ def unexpected_icon_write(*args, **kwargs):
++ raise AssertionError("remote icon upload reached the local filesystem")
++
++ monkeypatch.setattr(api, "upload_show_page_icon", unexpected_icon_write)
++ response = client.post(
++ "/api/show-pages/ses-local/icon",
++ files={"file": ("icon.svg", b"<svg/>", "image/svg+xml")},
++ headers=csrf_headers(client, "https://alex.avibe.bot"),
++ base_url="https://alex.avibe.bot",
++ environ_base=_remote_peer(),
++ )
++
++ assert response.status_code == 403
++ assert response.get_json()["code"] == "remote_execution_disabled"
++
++
++ "path",
++ [
++ "/api/models/runtime/status",
++ "/api/models/agents",
++ "/api/backend/codex/runtime",
++ "/api/backend/codex/auth",
++ ],
++)
++def test_remote_model_and_backend_reads_remain_available(path):
++ assert not ui_server._is_remote_local_execution_request("GET", path)
++
++
+ ("method", "path", "json_body", "api_method"),
+ [
+ ("POST", "/api/agents", {"name": "remote"}, "create_vibe_agent"),
+ ("POST", "/api/agents/import", {}, "import_vibe_agents"),
+ ("POST", "/api/agents/default", {"name": "remote"}, "set_default_vibe_agent"),
+ ("PATCH", "/api/agents/remote", {"enabled": False}, "update_vibe_agent"),
+ ("DELETE", "/api/agents/remote", None, "remove_vibe_agent"),
+ ],
+)
+def test_remote_agent_definition_mutations_are_blocked_before_api_calls(
+ monkeypatch,
+ tmp_path,
+ method,
+ path,
+ json_body,
+ api_method,
+):
+ 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"),
+ domain="alex.avibe.bot",
+ )
+
+ def unexpected_agent_call(*args, **kwargs):
+ raise AssertionError("remote Agent mutation reached the local Agent API")
+
+ monkeypatch.setattr(api, api_method, unexpected_agent_call)
+ response = client.request(
+ method,
+ path,
+ json=json_body,
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "remote_execution_disabled"
+
+
+ ("method", "path", "json_body", "api_method"),
+ [
+ ("POST", "/api/skills", {"source": "gh:owner/repo"}, "add_skill"),
+ ("POST", "/api/skills/update", {"name": "demo"}, "update_skill"),
+ ("POST", "/api/skills/upload", {"content_base64": ""}, "upload_skill_zip"),
+ ("DELETE", "/api/skills/demo", None, "remove_skill"),
+ ],
+)
+def test_remote_skill_mutations_are_blocked_before_api_calls(
+ monkeypatch,
+ tmp_path,
+ method,
+ path,
+ json_body,
+ api_method,
+):
+ 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"),
+ domain="alex.avibe.bot",
+ )
+
+ async def unexpected_skill_call(*args, **kwargs):
+ raise AssertionError("remote skill mutation reached the local Skills API")
+
+ monkeypatch.setattr(api, api_method, unexpected_skill_call)
+ response = client.request(
+ method,
+ path,
+ json=json_body,
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "remote_execution_disabled"
+
+
+ ("path", "json_body", "write_target"),
+ [
+ (
+ "/api/projects/proj-local/agents-md",
+ {"content": "remote instructions"},
+ "vibe.project_agents_md.save_agents_md",
+ ),
+ (
+ "/api/global-prompts",
+ {"content": "remote instructions", "backends": ["codex"]},
+ "vibe.global_agents_md.write_many_global_agents_md",
+ ),
+ ],
+)
+def test_remote_agent_instruction_writes_are_blocked_before_filesystem_access(
+ monkeypatch,
+ tmp_path,
+ path,
+ json_body,
+ write_target,
+):
+ 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"),
+ domain="alex.avibe.bot",
+ )
+
+ def unexpected_instruction_write(*args, **kwargs):
+ raise AssertionError("remote instruction mutation reached the local filesystem")
+
+ monkeypatch.setattr(write_target, unexpected_instruction_write)
+ response = client.put(
+ path,
+ json=json_body,
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "remote_execution_disabled"
+
+
+def test_remote_queue_deletion_is_blocked_before_store_access(
+ 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"),
+ domain="alex.avibe.bot",
+ )
+
+ def unexpected_queue_retirement(*args, **kwargs):
+ raise AssertionError("remote queue deletion reached the local delivery store")
+
+ monkeypatch.setattr(
+ "storage.message_deliveries.retire_queued_with_run",
+ unexpected_queue_retirement,
+ )
+ response = client.delete(
+ "/api/sessions/ses-local/queue/del-local",
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "remote_execution_disabled"
+
+
+def test_remote_owner_can_still_read_agent_instructions_and_queue(
+ monkeypatch,
+ tmp_path,
+):
+ from storage.importer import ensure_sqlite_state
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ ensure_sqlite_state()
+ monkeypatch.setattr(ui_server, "_resolve_project_dir", lambda project_id: str(tmp_path))
+ monkeypatch.setattr(
+ "vibe.global_agents_md.read_all_global_agents_md",
+ lambda: [],
+ )
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(config, "[email protected]", "user-owner"),
+ domain="alex.avibe.bot",
+ )
+
+ project_response = client.get(
+ "/api/projects/proj-local/agents-md",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ global_response = client.get(
+ "/api/global-prompts",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ queue_response = client.get(
+ "/api/sessions/ses-local/queue",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert project_response.status_code == 200
+ assert project_response.get_json()["source"] == "none"
+ assert global_response.status_code == 200
+ assert global_response.get_json() == {"backends": []}
+ assert queue_response.status_code == 200
+ assert queue_response.get_json() == {"queued": []}
+ assert not ui_server._is_remote_local_execution_request("POST", "/api/skills/preview")
+
+
+def test_remote_show_dispatch_is_rejected_before_event_reservation(
+ 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"),
+ domain="alex.avibe.bot",
+ )
+ monkeypatch.setattr(ui_server, "_is_cli_show_event_request", lambda: True)
+
+ def unexpected_store():
+ raise AssertionError("remote Show dispatch must not reserve an event")
+
+ monkeypatch.setattr(ui_server, "_show_session_event_store", unexpected_store)
+ response = client.post(
+ "/api/show/sessions/ses-remote/events",
+ json={
+ "type": "human.intent.submitted",
+ "actor": "human",
+ "payload": {"intent": "choose", "dispatch": True},
+ },
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "remote_execution_disabled"
+
+
+def test_remote_owner_can_still_read_authorized_session_history(
+ monkeypatch,
+ tmp_path,
+):
+ from storage import messages_service, workbench_sessions_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.settings_service import upsert_scope
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_remote_history",
+ now="2026-08-04T00:00:00Z",
+ )
+ session = workbench_sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="worker",
+ )
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ platform="avibe",
+ author="user",
+ message_type="user",
+ text="readable history",
+ )
+
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(config, "[email protected]", "user-owner"),
+ domain="alex.avibe.bot",
+ )
+ response = client.get(
+ f"/api/sessions/{session['id']}/messages",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 200
+ assert [row["text"] for row in response.get_json()["messages"]] == [
+ "readable history"
+ ]
-def test_remote_host_allows_valid_remote_session(monkeypatch, tmp_path):
+def test_remote_viewer_can_read_but_cannot_use_management_api(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
client = app.test_client()
diff --cc vibe/ui_server.py
index 5e9227d4f,60bb9fc95..a2de75355
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@@ -2212,144 -2127,6 +2212,143 @@@ def enforce_remote_access_cookie()
return jsonify({"ok": False, "error": "remote_access_login_required"}), 401
+def enforce_instance_role_capabilities():
+ if _remote_auth_exempt_path():
+ return None
+ from vibe.authorization import required_instance_role
+
+ minimum_role = required_instance_role(request.method, request.path)
+ if minimum_role is None:
+ return None
+ context = getattr(g, "authorization_context", None)
+ if context is None or not context.has_role(minimum_role):
+ return jsonify(
+ {
+ "ok": False,
+ "error": "instance_access_forbidden",
+ "required_role": minimum_role,
+ }
+ ), 403
+ return None
+
+
+def _is_remote_local_execution_request(method: str, path: str) -> bool:
+ normalized_method = method.upper()
++ is_mutation = normalized_method not in {"GET", "HEAD", "OPTIONS"}
+ if path.startswith(("/api/files/", "/api/browse")):
+ return True
+ if path.startswith("/api/terminal/"):
+ return True
- if path.startswith("/api/harness/") and normalized_method not in {
- "GET",
- "HEAD",
- "OPTIONS",
- }:
++ if is_mutation and path.startswith(("/api/harness/", "/api/models/", "/api/backend/")):
++ return True
++ if normalized_method == "POST" and re.fullmatch(r"/api/show-pages/[^/]+/icon", path):
+ return True
+ if normalized_method == "POST" and path == "/api/running-agents/end":
+ return True
+ if normalized_method == "POST" and path in {
+ "/api/agents",
+ "/api/agents/default",
+ "/api/agents/import",
+ "/api/control",
+ "/api/skills",
+ "/api/skills/update",
+ "/api/skills/upload",
+ "/api/upgrade",
+ }:
+ return True
+ if normalized_method == "POST" and re.fullmatch(
+ r"/api/(?:agent/[^/]+|dependencies/[^/]+)/install",
+ path,
+ ):
+ return True
+ if normalized_method in {"PATCH", "DELETE"} and re.fullmatch(
+ r"/api/agents/[^/]+",
+ path,
+ ):
+ return True
+ if normalized_method == "PUT" and (
+ path == "/api/global-prompts"
+ or re.fullmatch(r"/api/projects/[^/]+/agents-md", path)
+ ):
+ return True
+ if normalized_method == "DELETE" and (
+ re.fullmatch(r"/api/skills/[^/]+", path)
+ or re.fullmatch(r"/api/sessions/[^/]+(?:/queue/[^/]+)?", path)
+ ):
+ return True
+ return normalized_method == "POST" and bool(
+ re.fullmatch(
+ r"/api/sessions/[^/]+/(?:messages|attachments|cancel|queue/[^/]+/send-now)",
+ path,
+ )
+ )
+
+
+def enforce_remote_local_execution_boundary():
+ """Keep shell-capable Workbench surfaces on the trusted-local origin."""
+
+ context = getattr(g, "authorization_context", None)
+ if (
+ context is None
+ or not context.is_remote
+ or not _is_remote_local_execution_request(request.method, request.path)
+ ):
+ return None
+ return _remote_execution_disabled_response()
+
+
+_PROJECT_RESOURCE_PATHS = (
+ ("project", re.compile(r"^/api/projects/([^/]+)(?:/agents-md)?$")),
+ ("session", re.compile(r"^/api/sessions/([^/]+)(?:/.*)?$")),
+ ("session", re.compile(r"^/api/show-pages/([^/]+)(?:/.*)?$")),
+ ("session", re.compile(r"^/api/show/sessions/([^/]+)(?:/.*)?$")),
+ ("session", re.compile(r"^/show/([^/]+)(?:/.*)?$")),
+)
+
+
+def _project_access_resource(path: str) -> tuple[str, str] | None:
+ for kind, pattern in _PROJECT_RESOURCE_PATHS:
+ match = pattern.fullmatch(path)
+ if match is not None:
+ return kind, unquote(match.group(1))
+ return None
+
+
+def enforce_project_role_capabilities():
+ """Narrow remote non-owner Project/session routes through applied Project ACLs."""
+ if _remote_auth_exempt_path():
+ return None
+ context = getattr(g, "authorization_context", None)
+ if context is None or context.is_instance_owner:
+ 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)
+ if minimum_instance_role not in {"viewer", "editor"}:
+ return None
+ resource = _project_access_resource(request.path)
+ if resource is None:
+ return None
+
+ kind, resource_id = resource
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ role = (
+ project_access_service.get_effective_project_role(conn, context, resource_id)
+ if kind == "project"
+ else project_access_service.get_effective_session_role(conn, context, resource_id)
+ )
+ if not project_access_service.role_allows(role, minimum_instance_role):
+ return jsonify({"ok": False, "error": "not_found"}), 404
+ return None
+
+
@app.before_request
def protect_mutating_ui_requests():
if request.method not in MUTATING_METHODS: