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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(ci): remove obsolete remote execution gate tests
Maxd7444e259297
diff --git a/scripts/ci_unit_test_timings.json b/scripts/ci_unit_test_timings.jsonindex f2cf8eb74..424e6b3e3 100644--- a/scripts/ci_unit_test_timings.json+++ b/scripts/ci_unit_test_timings.json@@ -242,7 +242,6 @@"tests/test_tunnel_quality.py": 2,"tests/test_tunnel_recovery.py": 4,"tests/test_ui_api.py": 24,- "tests/test_ui_remote_access_auth.py": 9,"tests/test_ui_server_fastapi.py": 15,"tests/test_ui_server_install.py": 3,"tests/test_ui_server_logs.py": 3,diff --git a/tests/scenarios/tunnel_quality/catalog.yaml b/tests/scenarios/tunnel_quality/catalog.yamlindex 754538042..31374c507 100644--- a/tests/scenarios/tunnel_quality/catalog.yaml+++ b/tests/scenarios/tunnel_quality/catalog.yaml@@ -169,7 +169,7 @@ scenarios:status: coveredkind: network_policylayer: contract- test: tests/test_ui_remote_access_auth.py::test_ra_tq_026_remote_status_uses_cf_ray_on_paired_public_host+ test: tests/test_remote_access_vibe_cloud.py::test_ra_tq_026_remote_status_uses_cf_ray_on_paired_public_host- id: RA-TQ-027name: User optimization policies change recovery sensitivity without changing path measurementsstatus: covereddiff --git a/tests/test_agent_organization_onboarding.py b/tests/test_agent_organization_onboarding.pyindex 23895ab36..3f96d155a 100644--- a/tests/test_agent_organization_onboarding.py+++ b/tests/test_agent_organization_onboarding.py@@ -7,8 +7,7 @@ import pytestfrom core.vibe_agents import VibeAgentAccessError, VibeAgentStorefrom storage import resource_access_service-from tests.test_ui_remote_access_auth import _remote_peer, _save_config-from tests.ui_server_test_helpers import csrf_headers+from tests.ui_server_test_helpers import csrf_headers, remote_peer, save_configfrom vibe import remote_accessfrom vibe.ui_server import app@@ -209,7 +208,7 @@ def test_onboarding_preserves_existing_acl_revision(monkeypatch, tmp_path) -> Nodef test_onboarding_publication_redacts_prompt_credentials_paths_and_config(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)+ config = save_config(tmp_path)config.remote_access.vibe_cloud.enabled = Trueconfig.remote_access.vibe_cloud.instance_id = "inst_123"config.remote_access.vibe_cloud.instance_secret = "paired-device-secret"@@ -294,7 +293,7 @@ def test_agent_rename_and_delete_converge_in_full_resource_index(monkeypatch, tmdef test_owner_http_workflow_lists_and_onboards_agents_and_editor_is_admitted(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)+ config = save_config(tmp_path)store = VibeAgentStore()try:store.create(name="legacy-http", backend="codex", system_prompt="must-not-appear")@@ -317,14 +316,14 @@ def test_owner_http_workflow_lists_and_onboards_agents_and_editor_is_admitted(moinventory = client.get("/api/agent-onboarding",base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)onboarded = client.post("/api/agent-onboarding",json={},headers=csrf_headers(client, "https://alex.avibe.bot"),base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)assert inventory.status_code == 200@@ -376,7 +375,7 @@ def test_owner_http_workflow_lists_and_onboards_agents_and_editor_is_admitted(modenied = client.get("/api/agent-onboarding",base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)# Temporary full-access rollout (#1343): an active Organization editor is# admitted to the onboarding surface too.diff --git a/tests/test_dock_api.py b/tests/test_dock_api.pyindex 23a72a9b0..1db25900b 100644--- a/tests/test_dock_api.py+++ b/tests/test_dock_api.py@@ -10,7 +10,7 @@ import pytestfrom core.dock_store import BUILTIN_DOCK_IDS, DockErrorfrom core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir-from tests.test_ui_remote_access_auth import _remote_peer, _save_config+from tests.ui_server_test_helpers import remote_peer, save_configfrom vibe import api, ui_serverfrom vibe.ui_server import app@@ -64,7 +64,7 @@ def _show(session_id: str) -> str:def test_dock_default_is_builtins_only(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)result = api.get_dock()@@ -76,7 +76,7 @@ def test_dock_default_is_builtins_only(monkeypatch, tmp_path):def test_pin_appends_and_captures_title(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_pin", title="Sales Dashboard")_make_show_page("ses_pin")@@ -95,7 +95,7 @@ def test_pin_appends_and_captures_title(monkeypatch, tmp_path):def test_pin_without_session_title_stores_empty_snapshot(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_plain") # IM-dispatch sessions persist title=None_make_show_page("ses_plain")@@ -106,7 +106,7 @@ def test_pin_without_session_title_stores_empty_snapshot(monkeypatch, tmp_path):def test_pin_is_idempotent(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_dup", title="Once")_make_show_page("ses_dup")@@ -123,7 +123,7 @@ def test_pin_multiple_sessions_all_survive(monkeypatch, tmp_path):# earlier one (the read-modify-write is serialized under a lock so concurrent# pins can't lost-update).monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)for sid in ("ses_a", "ses_b", "ses_c"):_seed_session(sid, title=sid.upper())_make_show_page(sid)@@ -139,7 +139,7 @@ def test_pin_rejects_when_install_budget_is_full(monkeypatch, tmp_path):# pins, else a pin can grow ``pins`` past what a read would keep and the# just-added page is silently dropped on the next load.monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)monkeypatch.setattr("core.dock_store.MAX_PINNED_PAGES", 1) # room for exactly one pinfor sid in ("ses_full1", "ses_full2"):_seed_session(sid)@@ -159,7 +159,7 @@ def test_load_dock_clamps_oversized_corrupt_pins(monkeypatch, tmp_path):from core.dock_store import DOCK_STATE_KEYmonkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)monkeypatch.setattr("core.dock_store.MAX_PINNED_PAGES", 1) # room for exactly one pinset_state_meta(DOCK_STATE_KEY,@@ -190,7 +190,7 @@ def test_reconcile_does_not_readd_undocked_builtin(monkeypatch, tmp_path):from core.dock_store import DOCK_STATE_KEYmonkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)set_state_meta(DOCK_STATE_KEY,{@@ -213,7 +213,7 @@ def test_legacy_full_order_doc_still_valid(monkeypatch, tmp_path):from core.dock_store import DOCK_STATE_KEYmonkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)order = ["files", "terminal", "editor", "library", _show("ses_keep")]set_state_meta(DOCK_STATE_KEY,@@ -229,7 +229,7 @@ def test_legacy_full_order_doc_still_valid(monkeypatch, tmp_path):def test_pin_unknown_show_page_is_404(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_nopage") # session exists but has no Show Pagewith pytest.raises(DockError) as excinfo:@@ -239,7 +239,7 @@ def test_pin_unknown_show_page_is_404(monkeypatch, tmp_path):def test_pin_malformed_session_id_raises_show_page_error(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)with pytest.raises(ShowPageError) as excinfo:api.pin_dock_show_page("bad id!")@@ -248,7 +248,7 @@ def test_pin_malformed_session_id_raises_show_page_error(monkeypatch, tmp_path):def test_unpin_removes_and_is_idempotent(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_u", title="Bye")_make_show_page("ses_u")api.pin_dock_show_page("ses_u")@@ -267,7 +267,7 @@ def test_unpin_removes_and_is_idempotent(monkeypatch, tmp_path):def test_set_order_persists_valid_permutation(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_o", title="Ordered")_make_show_page("ses_o")api.pin_dock_show_page("ses_o")@@ -284,7 +284,7 @@ def test_set_order_accepts_library_builtin(monkeypatch, tmp_path):# includes it is accepted and persists — the same reorder path #892 shipped,# now covering the 4th built-in.monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_lib", title="Ordered")_make_show_page("ses_lib")api.pin_dock_show_page("ses_lib")@@ -300,7 +300,7 @@ def test_set_order_rejects_unknown_id(monkeypatch, tmp_path):# Subset validation (§7.1c) still rejects an id that is not a real dock item,# so a stale client can't resurrect a pin removed by another tab.monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)with pytest.raises(DockError) as excinfo:api.set_dock_order(["files", "terminal", "editor", "show:ghost"])@@ -312,7 +312,7 @@ def test_set_order_accepts_proper_subset(monkeypatch, tmp_path):# built-in (undocking it) is accepted and persists — no longer rejected as a# non-set-equal order.monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)dock = api.set_dock_order(["files", "terminal"])["dock"] # editor + library undockedassert dock["order"] == ["files", "terminal"]@@ -323,7 +323,7 @@ def test_set_order_accepts_empty_dock(monkeypatch, tmp_path):# Undocking everything (including all built-ins) is legal — the empty Dock is# a valid saved state (the popover shows the App Library hint client-side).monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)dock = api.set_dock_order([])["dock"]assert dock["order"] == []@@ -336,7 +336,7 @@ def test_set_order_rejects_stale_known(monkeypatch, tmp_path):# silently undock that newer pin (which install docked by default). Subset# validation alone would have accepted the omission.monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_new", title="New")_make_show_page("ses_new")api.pin_dock_show_page("ses_new") # server now has show:ses_new installed + docked@@ -354,7 +354,7 @@ def test_set_order_with_matching_known_allows_intentional_undock(monkeypatch, tm# INTENTIONAL undock (distinct from a stale omission) and is accepted — the# page stays installed.monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_k", title="K")_make_show_page("ses_k")api.pin_dock_show_page("ses_k")@@ -369,7 +369,7 @@ def test_undocked_builtin_persists_across_reload(monkeypatch, tmp_path):# An undocked built-in stays undocked across a reload — reconcile never# re-adds it (the whole point of built-ins being undockable now).monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)api.set_dock_order(["files", "terminal", "editor"]) # library undockedassert "library" not in api.get_dock()["dock"]["order"]@@ -380,7 +380,7 @@ def test_installed_page_can_be_undocked_but_stays_installed(monkeypatch, tmp_pat# ``order``) while REMAINING installed (kept in ``pins``) — install and dock# are separate. Its ``show:`` id is absent from the order but the pin persists.monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_keep", title="Keep")_make_show_page("ses_keep")api.pin_dock_show_page("ses_keep") # installs + docks@@ -397,7 +397,7 @@ def test_delete_pin_cascades_out_of_order(monkeypatch, tmp_path):# DELETE pins (uninstall) removes the page from BOTH pins and order, leaving# the other docked tiles intact.monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_del", title="Del")_make_show_page("ses_del")api.pin_dock_show_page("ses_del")@@ -411,7 +411,7 @@ def test_delete_pin_cascades_out_of_order(monkeypatch, tmp_path):def test_set_order_rejects_duplicates(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)with pytest.raises(DockError) as excinfo:api.set_dock_order(["files", "files", "terminal", "editor"])@@ -420,7 +420,7 @@ def test_set_order_rejects_duplicates(monkeypatch, tmp_path):def test_set_order_rejects_non_list(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)with pytest.raises(DockError) as excinfo:api.set_dock_order("files,terminal,editor")@@ -429,7 +429,7 @@ def test_set_order_rejects_non_list(monkeypatch, tmp_path):def test_dock_route_round_trip_via_client(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)response = app.test_client().get("/api/dock", base_url="http://127.0.0.1:5123")@@ -444,12 +444,12 @@ def test_dock_route_blocked_for_remote_without_session(monkeypatch, tmp_path):remote request without a session gets the login-required API contract, neveran OAuth side effect or an unauthenticated native response."""monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)get_resp = app.test_client().get("/api/dock",base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),follow_redirects=False,)assert get_resp.status_code == 401@@ -461,7 +461,7 @@ def test_dock_route_blocked_for_remote_without_session(monkeypatch, tmp_path):post_resp = app.test_client().post("/api/dock/pins",base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),json={"session_id": "ses_x"},follow_redirects=False,)diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 93b11a4fe..7cf91444b 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -39,8 +39,7 @@ from core.handlers.model_hub.service import (ModelHubService,create_default_service,)-from tests.test_ui_remote_access_auth import _remote_peer, _save_config-from tests.ui_server_test_helpers import csrf_headers+from tests.ui_server_test_helpers import csrf_headers, remote_peer, save_configfrom vibe import ui_serverfrom vibe.model_hub_client import ModelHubRemoteService, _decodefrom vibe.ui_server import app@@ -3381,12 +3380,12 @@ def test_runtime_start_route_requires_csrf_before_starting_engine(monkeypatch, tdef test_runtime_start_route_requires_remote_session(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)response = app.test_client().post("/api/models/runtime/start",base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)assert response.status_code == 401diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.pyindex 2bc7e25c5..ebfd722fc 100644--- a/tests/test_remote_access_vibe_cloud.py+++ b/tests/test_remote_access_vibe_cloud.py@@ -16,7 +16,7 @@ from config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig,from storage.db import create_sqlite_enginefrom storage.models import remote_access_authorizationsfrom tests.ui_server_test_helpers import remote_session_cookie-from vibe import remote_access+from vibe import remote_access, ui_serverfrom vibe import runtime@@ -94,6 +94,64 @@ def _session_cookie()+def test_ra_tq_026_remote_status_uses_cf_ray_on_paired_public_host(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _config()+ config.save()+ observed = []++ def status(+ loaded_config=None,+ *,+ client_colo=None,+ client_access="local",+ include_network_path=False,+ ):+ observed.append((loaded_config, client_colo, client_access, include_network_path))+ return {"ok": True, "client_colo": client_colo}++ monkeypatch.setattr(remote_access, "status", status)+ with ui_server.app.test_request_context(+ "/api/remote-access/status",+ base_url="https://alex.avibe.bot",+ headers={"CF-Ray": "9f1234567890abcd-SIN"},+ ):+ response = ui_server.remote_access_status()++ assert response.status_code == 200+ assert observed[0][0].remote_access.vibe_cloud.public_url == config.remote_access.vibe_cloud.public_url+ assert observed[0][1:] == ("SIN", "remote", True)+++def test_ra_tq_026_remote_status_ignores_spoofed_cf_ray(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _config()+ config.save()+ observed = []++ def status(+ loaded_config=None,+ *,+ client_colo=None,+ client_access="local",+ include_network_path=False,+ ):+ observed.append((loaded_config, client_colo, client_access, include_network_path))+ return {"ok": True, "client_colo": client_colo}++ monkeypatch.setattr(remote_access, "status", status)+ with ui_server.app.test_request_context(+ "/api/remote-access/status",+ base_url="http://127.0.0.1:5123",+ headers={"CF-Ray": "9f1234567890abcd-NRT"},+ ):+ response = ui_server.remote_access_status()++ assert response.status_code == 200+ assert observed[0][1:] == (None, "local", True)+ assert config.remote_access.vibe_cloud.public_url == "https://alex.avibe.bot"++def test_session_cookie_roundtrip() -> None:config = _config()diff --git a/tests/test_resource_acl_agents.py b/tests/test_resource_acl_agents.pyindex 2a9cfc473..7b2713860 100644--- a/tests/test_resource_acl_agents.py+++ b/tests/test_resource_acl_agents.py@@ -13,8 +13,7 @@ from storage import resource_access_service, workbench_sessions_servicefrom storage.db import get_cached_sqlite_enginefrom storage.models import resource_access_groups, resource_access_policiesfrom 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 tests.ui_server_test_helpers import csrf_headers, remote_peer, save_configfrom vibe import remote_accessfrom vibe.ui_server import app@@ -159,7 +158,7 @@ def test_agent_removal_deletes_resource_policy_and_groups(monkeypatch, tmp_path)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)+ config = save_config(tmp_path)client = app.test_client()client.set_cookie(remote_access.SESSION_COOKIE_NAME,@@ -177,7 +176,7 @@ def test_active_org_agent_creation_is_allowed_without_trusted_local_identity(monjson={"name": "remote-private", "backend": "codex"},headers=csrf_headers(client, "https://alex.avibe.bot"),base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)assert response.status_code in {200, 201}@@ -277,7 +276,7 @@ def test_remote_partial_agent_updates_persist_canonical_selector_pair(monkeypatcdef test_active_org_agent_detail_uses_full_runtime_projection(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)+ config = save_config(tmp_path)store = VibeAgentStore()try:agent = store.create(@@ -309,7 +308,7 @@ def test_active_org_agent_detail_uses_full_runtime_projection(monkeypatch, tmp_premote_response = remote.get("/api/agents/imported-agent",base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)local_response = app.test_client().get("/api/agents/imported-agent")@@ -325,7 +324,7 @@ def test_active_org_agent_detail_uses_full_runtime_projection(monkeypatch, tmp_pdef 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)+ config = save_config(tmp_path)store, agents = _seed_agents_with_policies()private_agent = agents["private"]store.set_default_agent_name(private_agent.name)@@ -344,10 +343,10 @@ def test_active_org_agent_selection_and_harness_bindings_are_allowed(monkeypatchresponse = client.get("/api/agents/private-agent",base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)assert response.status_code == 200- catalog = client.get("/api/agents", base_url="https://alex.avibe.bot", environ_base=_remote_peer())+ catalog = client.get("/api/agents", base_url="https://alex.avibe.bot", environ_base=remote_peer())assert catalog.status_code == 200assert {"private-agent", "public-agent", "scope-agent"}.issubset({agent["name"] for agent in catalog.get_json()["agents"]}@@ -359,7 +358,7 @@ def test_active_org_agent_selection_and_harness_bindings_are_allowed(monkeypatchjson={"description": "member update"},headers=csrf_headers(client, "https://alex.avibe.bot"),base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)assert denied_mutation.status_code == 403# An active Organization admin/owner can manage.@@ -379,7 +378,7 @@ def test_active_org_agent_selection_and_harness_bindings_are_allowed(monkeypatchjson={"description": "admin update"},headers=csrf_headers(client, "https://alex.avibe.bot"),base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)assert mutation.status_code == 200default_mutation = client.post(@@ -387,7 +386,7 @@ def test_active_org_agent_selection_and_harness_bindings_are_allowed(monkeypatchjson={"name": private_agent.name},headers=csrf_headers(client, "https://alex.avibe.bot"),base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)assert default_mutation.status_code == 200diff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.pyindex 94d3bc312..f02e2e115 100644--- a/tests/test_resource_acl_show_pages.py+++ b/tests/test_resource_acl_show_pages.py@@ -11,8 +11,7 @@ from storage import workbench_sessions_service as sessions_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_statefrom storage.models import agent_sessions, show_pages-from tests.test_ui_remote_access_auth import _remote_peer, _save_config-from tests.ui_server_test_helpers import csrf_headers+from tests.ui_server_test_helpers import csrf_headers, remote_peer, save_configfrom vibe import api, remote_access, ui_serverfrom vibe.ui_server import app@@ -200,7 +199,7 @@ def test_remote_org_members_can_open_all_show_pages_temporarily(organization_role,) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)+ config = save_config(tmp_path)store = _seed_show_pages_with_policies()store.close()@@ -224,19 +223,19 @@ def test_remote_org_members_can_open_all_show_pages_temporarily(catalog = client.get("/api/show-pages",base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)mutation = client.post("/api/show-pages/ses-public/visibility",json={"visibility": "offline"},headers=csrf_headers(client, "https://alex.avibe.bot"),base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)page = client.get("/show/ses-private/",base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),headers={"Accept": "text/html"},follow_redirects=False,)@@ -353,7 +352,7 @@ def test_active_organization_admin_can_manage_all_pages_temporarily(monkeypatch,def test_access_only_manager_visibility_response_does_not_expose_page_payload(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)store = _seed_show_pages_with_policies()admin = _organization_context("admin-1",@@ -384,7 +383,7 @@ def test_access_only_manager_visibility_response_does_not_expose_page_payload(modef test_excluded_scoped_owner_share_mutations_do_not_expose_page_payload(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)store = _seed_show_pages_with_policies()excluded_owner = _organization_context("owner-1",@@ -438,7 +437,7 @@ def test_remote_show_page_owner_can_control_sharing_without_instance_owner_role(def test_remote_show_page_owner_mutations_reach_resource_acl_as_viewer(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)+ config = save_config(tmp_path)store = ShowPageStore()project_path = tmp_path / "project"project_path.mkdir()@@ -470,7 +469,7 @@ def test_remote_show_page_owner_mutations_reach_resource_acl_as_viewer(monkeypatrequest_options = {"headers": csrf_headers(client, "https://alex.avibe.bot"),"base_url": "https://alex.avibe.bot",- "environ_base": _remote_peer(),+ "environ_base": remote_peer(),}ensured = client.post(@@ -504,7 +503,7 @@ def test_remote_show_page_owner_mutations_reach_resource_acl_as_viewer(monkeypatdef test_organization_admin_can_read_show_page_access_metadata_without_use_access(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)store = _seed_show_pages_with_policies()store.close()admin = _organization_context(@@ -569,7 +568,7 @@ def test_show_page_access_api_distinguishes_personal_and_organization_modes(monk"public_link_enabled": False,}- config = _save_config(tmp_path)+ config = save_config(tmp_path)store = ShowPageStore()try:store.ensure("ses-organization")@@ -603,7 +602,7 @@ def test_show_page_access_api_distinguishes_personal_and_organization_modes(monkorganization = client.get("/api/show-pages/ses-organization/access",base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)assert organization.status_code == 200assert organization.get_json() == {@@ -691,7 +690,7 @@ def test_show_page_email_grants_reject_non_owner_without_contacting_backend(instance_role: str,) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)store = _seed_show_pages_with_policies()store.close()monkeypatch.setattr(@@ -723,7 +722,7 @@ def test_show_page_email_grants_report_unavailable_without_cloud_pairing(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)store = ShowPageStore()try:store.ensure("ses-email-access")@@ -742,7 +741,7 @@ def test_show_page_email_grants_report_transient_device_failures_as_retryable(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)store = ShowPageStore()try:store.ensure("ses-email-access-transient")@@ -766,7 +765,7 @@ def test_show_page_email_grants_report_transient_device_failures_as_retryable(def test_show_page_email_grant_device_requests_freeze_the_target(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)+ config = save_config(tmp_path)calls: list[tuple] = []monkeypatch.setattr(remote_access, "_resource_acl_sync_configured", lambda _config: True)monkeypatch.setattr(@@ -815,7 +814,7 @@ def test_show_page_email_grant_device_requests_freeze_the_target(monkeypatch, tmdef test_show_page_email_grant_change_requires_authorization_revision(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)+ config = save_config(tmp_path)monkeypatch.setattr(remote_access, "_resource_acl_sync_configured", lambda _config: True)monkeypatch.setattr(remote_access,@@ -836,7 +835,7 @@ def test_show_page_email_grant_change_requires_authorization_revision(monkeypatcdef test_remote_org_dock_requires_admin_owner_role(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)+ config = save_config(tmp_path)store = _seed_show_pages_with_policies()store.close()owner = _organization_context("owner-1", instance_role="owner")@@ -883,7 +882,7 @@ def test_remote_org_dock_requires_admin_owner_role(monkeypatch, tmp_path) -> Non"/api/dock/pins/ses-public",headers=csrf_headers(client, "https://alex.avibe.bot"),base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)# A plain active Organization member is denied dock mutations under the# Resource ACL boundary (see #1343).@@ -892,7 +891,7 @@ def test_remote_org_dock_requires_admin_owner_role(monkeypatch, tmp_path) -> Nondef test_remote_admin_dock_order_preserves_hidden_private_pins(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)store = _seed_show_pages_with_policies()store.close()owner = _organization_context("owner-1", instance_role="owner")@@ -919,7 +918,7 @@ def test_remote_admin_dock_order_preserves_hidden_private_pins(monkeypatch, tmp_def test_untrusted_dock_context_fails_closed(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)store = _seed_show_pages_with_policies()store.close()owner = _organization_context("owner-1", instance_role="owner")@@ -943,7 +942,7 @@ def test_remote_member_archive_is_denied_under_resource_acl(monkeypatch, tmp_patfrom unittest.mock import AsyncMockmonkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)+ config = save_config(tmp_path)project_dir = tmp_path / "project"project_dir.mkdir()ensure_sqlite_state()@@ -996,7 +995,7 @@ def test_remote_member_archive_is_denied_under_resource_acl(monkeypatch, tmp_patf"/api/sessions/{session_id}",headers=csrf_headers(client, "https://alex.avibe.bot"),base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)assert response.status_code in {403, 404}@@ -1015,7 +1014,7 @@ def test_remote_org_show_annotation_media_temporarily_follows_open_page_policy() -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)+ config = save_config(tmp_path)project_dir = tmp_path / "project"project_dir.mkdir()ensure_sqlite_state()@@ -1100,7 +1099,7 @@ def test_remote_org_show_annotation_media_temporarily_follows_open_page_policy(return client.get(f"/api/media/{token}",base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),+ environ_base=remote_peer(),)# Show annotation screenshots are part of the temporarily open page.diff --git a/tests/test_show_pages_admin_api.py b/tests/test_show_pages_admin_api.pyindex 3c1bece3b..6b7e8c2b4 100644--- a/tests/test_show_pages_admin_api.py+++ b/tests/test_show_pages_admin_api.py@@ -3,7 +3,7 @@import pytestfrom core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir-from tests.test_ui_remote_access_auth import _save_config+from tests.ui_server_test_helpers import save_configfrom vibe import apifrom vibe.ui_server import app@@ -60,7 +60,7 @@ def _set_visibility(session_id: str, visibility: str) -> None:def test_list_show_pages_orders_newest_first_and_joins_title(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_titled", title="Q2 funnel dashboard")_seed_session("ses_plain")_set_visibility("ses_titled", "public")@@ -89,7 +89,7 @@ def test_list_show_pages_preserves_archived_agent_display_name(monkeypatch, tmp_from storage.models import agent_sessionsmonkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)store = VibeAgentStore()try:original = store.create(name="pm", backend="claude")@@ -120,7 +120,7 @@ def test_list_show_pages_preserves_archived_agent_display_name(monkeypatch, tmp_def test_set_show_page_visibility_public_then_offline(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_x")_set_visibility("ses_x", "private")@@ -137,7 +137,7 @@ def test_set_show_page_visibility_public_then_offline(monkeypatch, tmp_path):def test_set_show_page_visibility_rejects_invalid(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_x")with pytest.raises(ShowPageError) as excinfo:@@ -147,7 +147,7 @@ def test_set_show_page_visibility_rejects_invalid(monkeypatch, tmp_path):def test_rotate_share_requires_public_and_revokes_previous(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_x")_set_visibility("ses_x", "private")@@ -165,7 +165,7 @@ def test_rotate_share_requires_public_and_revokes_previous(monkeypatch, tmp_pathdef test_show_pages_list_route_returns_payload(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)_seed_session("ses_route", title="Release notes preview")_set_visibility("ses_route", "public")diff --git a/tests/test_ui_project_access.py b/tests/test_ui_project_access.pyindex 31d1a8b71..a8e010fb6 100644--- a/tests/test_ui_project_access.py+++ b/tests/test_ui_project_access.py@@ -277,26 +277,6 @@ def test_active_org_member_can_use_every_project_runtime_surface(monkeypatch, tm)assert mark_read.status_code == 200- allowed_action = client.post(- f"/api/sessions/{ids['session_a']}/attachments",- base_url=REMOTE_ORIGIN,- environ_base=REMOTE_PEER,- headers=headers,- json={},- )- hidden_action = client.post(- f"/api/sessions/{ids['session_b']}/attachments",- base_url=REMOTE_ORIGIN,- environ_base=REMOTE_PEER,- headers=headers,- json={},- )- # Empty JSON is rejected by the upload parser, but the request must reach- # the endpoint rather than being stopped by the remote execution gate.- assert allowed_action.status_code != 403 or allowed_action.get_json().get("code") != "remote_execution_disabled"- assert hidden_action.status_code != 403 or hidden_action.get_json().get("code") != "remote_execution_disabled"--def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config, ids = _setup_state(tmp_path)@@ -455,16 +435,6 @@ def test_archived_project_invalidates_retained_remote_urls(monkeypatch, tmp_path{"session_id": ids["session_a"]}]- response = client.post(- f"/api/sessions/{ids['session_a']}/attachments",- base_url=REMOTE_ORIGIN,- environ_base=REMOTE_PEER,- headers=csrf_headers(client, REMOTE_ORIGIN),- json={},- )- assert response.status_code != 403 or response.get_json().get("code") != "remote_execution_disabled"--def test_legacy_media_token_uses_all_migrated_session_references(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config, ids = _setup_state(tmp_path)@@ -639,9 +609,9 @@ def test_viewer_no_match_owner_and_local_matrix(monkeypatch, tmp_path) -> None:email="[email protected]",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+ assert _get(no_match, "/api/projects").status_code == 200+ assert _get(no_match, "/api/sessions").status_code == 200+ assert _get(no_match, f"/api/sessions/{ids['session_a']}").status_code == 404no_match_headers = csrf_headers(no_match, REMOTE_ORIGIN)denied = no_match.post("/api/sessions",@@ -651,7 +621,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()["code"] == "remote_execution_disabled"+ assert denied.get_json()["code"] == "project_access_denied"organization_member = app.test_client()organization_member.set_cookie(diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.pydeleted file mode 100644index 2e9cfbc64..000000000--- a/tests/test_ui_remote_access_auth.py+++ /dev/null@@ -1,6371 +0,0 @@-from __future__ import annotations--import ipaddress-import json-import logging-import socket-import asyncio-from collections import namedtuple-from urllib.parse import urlencode--import httpx-import pytest--from config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, UiConfig, V2Config-from config.v2_config import CONFIG_LOCK-from storage.importer import ensure_sqlite_state-from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie-from vibe import api-from vibe import remote_access-from vibe import ui_server-from vibe.ui_compat import g-from vibe.ui_server import app-from starlette.websockets import WebSocketDisconnect---_FakeSnicaddr = namedtuple("snicaddr", ["family", "address", "netmask", "broadcast", "ptp"])---def _mock_interface(monkeypatch, ip: str, prefix: int, name: str = "en0") -> None:- """Make ``psutil.net_if_addrs()`` report ``ip`` with the given prefix- length so ``_local_interface_network`` returns the expected subnet.- Tests that exercise the RFC1918/ULA trust path need this because the- real test runner does not have the synthetic addresses (192.168.2.3- etc.) configured on any interface."""- address = ipaddress.ip_address(ip)- if address.version == 4:- family = socket.AF_INET- netmask = str(ipaddress.IPv4Network(f"0.0.0.0/{prefix}").netmask)- else:- family = socket.AF_INET6- netmask = str(ipaddress.IPv6Network(f"::/{prefix}").netmask)- snic = _FakeSnicaddr(family=family, address=ip, netmask=netmask, broadcast=None, ptp=None)- monkeypatch.setattr("vibe.ui_server.psutil.net_if_addrs", lambda: {name: [snic]})---def _mock_no_interfaces(monkeypatch) -> None:- monkeypatch.setattr("vibe.ui_server.psutil.net_if_addrs", lambda: {})---def _mock_tailscale_whois(- monkeypatch,- peer: str,- *,- addresses: list[str] | None = None,- allowed_ips: list[str] | None = None,- payload_key: str = "Node",-) -> None:- """Stub ``_tailscale_whois`` with the modern ``Node`` payload shape by- default (host-CIDR address strings, as emitted by current ``tailscale- whois --json``); pass ``payload_key="Machine"`` for the legacy shape."""- peer_address = ipaddress.ip_address(peer)- prefix = peer_address.max_prefixlen- monkeypatch.setattr(ui_server, "_TAILSCALE_PEER_CACHE", {})- monkeypatch.setattr(- ui_server,- "_tailscale_whois",- lambda address: {- payload_key: {- "Addresses": addresses or [f"{peer_address}/{prefix}"],- "AllowedIPs": allowed_ips or [f"{peer_address}/{prefix}"],- }- }- if address == peer_address- else None,- )---def _save_config(tmp_path) -> V2Config:- config = V2Config(- mode="self_host",- version="v2",- platform="slack",- platforms=PlatformsConfig(enabled=["slack"], primary="slack"),- slack=SlackConfig(bot_token=""),- runtime=RuntimeConfig(default_cwd="."),- agents=AgentsConfig(),- ui=UiConfig(),- remote_access=RemoteAccessConfig(),- )- cloud = config.remote_access.vibe_cloud- cloud.enabled = True- cloud.public_url = "https://alex.avibe.bot"- cloud.client_id = "vr_client_123"- cloud.instance_id = "inst_123"- cloud.session_secret = "session-secret"- cloud.authorization_endpoint = "https://backend.test/oauth/authorize"- cloud.redirect_uri = "https://alex.avibe.bot/auth/callback"- config.save()- return config---def _oauth_exchange_result(config: V2Config, *, nonce: str) -> dict:- return {- "claims": {- "email": "[email protected]",- "sub": "user-1",- "nonce": nonce,- },- "session_claims": {- "vibe_instance_id": config.remote_access.vibe_cloud.instance_id,- "vibe_instance_role": "owner",- "vibe_instance_access_source": "owner",- },- }---def _remote_peer() -> dict[str, str]:- return {"REMOTE_ADDR": "203.0.113.10"}---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()- (ui_dist / "index.html").write_text("<html><body>Avibe shell</body></html>", encoding="utf-8")- monkeypatch.setattr(ui_server, "get_ui_dist_path", lambda: ui_dist)- return ui_dist--[email protected]("path", ["/", "/dashboard", "/chat/session-1"])-def test_remote_spa_document_serves_shell_without_starting_login(monkeypatch, tmp_path, path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- _mock_ui_dist(monkeypatch, tmp_path)-- response = app.test_client().get(- path,- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 200- assert response.headers.get("Location") is None- assert response.text == "<html><body>Avibe shell</body></html>"---def test_remote_login_endpoint_redirects_to_vibe_cloud_login(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)-- response = app.test_client().get(- "/auth/login?next=/dashboard",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 302- assert response.headers["Location"].startswith("https://backend.test/oauth/authorize?")- state = httpx.URL(response.headers["Location"]).params["state"]- state_payload = ui_server._read_oauth_state(config.remote_access.vibe_cloud.session_secret, state)- assert state_payload is not None- assert state_payload["next"] == "/dashboard"- assert state_payload["retry"] is False---def test_private_show_page_login_freezes_target_in_authorize_and_handshake(- monkeypatch, tmp_path-):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()-- navigation = client.get(- "/show/session-one/",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- headers={"Accept": "text/html"},- follow_redirects=False,- )-- assert navigation.status_code == 302- assert navigation.headers["Location"] == "/auth/login?next=%2Fshow%2Fsession-one%2F"-- login = client.get(- navigation.headers["Location"],- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert login.status_code == 302- authorize_params = httpx.URL(login.headers["Location"]).params- assert authorize_params["show_page_id"] == "session-one"- state_payload = ui_server._read_oauth_state(- config.remote_access.vibe_cloud.session_secret,- authorize_params["state"],- )- assert state_payload is not None- stored = remote_access._oauth_handshakes[state_payload["r"]]- assert stored["show_page_id"] == "session-one"-- asset = client.get(- "/show/session-one/asset.js",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )- assert asset.status_code == 401- assert asset.get_json()["error"] == "remote_access_login_required"---def test_private_show_page_asset_xhr_gets_401_instead_of_show_page_oauth(- monkeypatch, tmp_path-):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- ensure_sqlite_state()- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- remote_session_cookie(- config,- "[email protected]",- "guest-1",- role="viewer",- access_source="email",- ),- domain="alex.avibe.bot",- )-- response = client.get(- "/show/session-one/asset.js",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- headers={"Accept": "application/javascript"},- follow_redirects=False,- )-- assert response.status_code == 401- assert response.get_json()["error"] == "remote_access_login_required"---def test_existing_broader_session_reauthorization_stops_when_grant_is_missing(- monkeypatch,- tmp_path,-):- from core.show_pages import ShowPageStore-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- store = ShowPageStore()- try:- store.ensure("session-one")- finally:- store.close()- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- remote_session_cookie(- config,- "[email protected]",- "guest-1",- role="editor",- access_source="email",- ),- domain="alex.avibe.bot",- )-- start = client.get(- "/show/session-one/__show/me",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- headers={"Accept": "text/html"},- follow_redirects=False,- )- authorize_params = httpx.URL(start.headers["Location"]).params- state = authorize_params["state"]- state_payload = ui_server._read_oauth_state(- config.remote_access.vibe_cloud.session_secret,- state,- )- assert state_payload is not None- nonce = remote_access._oauth_handshakes[state_payload["r"]]["nonce"]- monkeypatch.setattr(- remote_access,- "exchange_oauth_code",- lambda *args, **kwargs: {- "claims": {- "email": "[email protected]",- "sub": "guest-1",- "nonce": nonce,- },- "session_claims": {- "vibe_instance_id": "inst_123",- "vibe_instance_role": "editor",- "vibe_instance_access_source": "email",- },- },- )-- callback = client.get(- f"/auth/callback?code=test-code&state={state}",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )- assert callback.status_code == 302- assert ui_server.REMOTE_SHOW_PAGE_REAUTH_PARAM in callback.headers["Location"]-- denied = client.get(- callback.headers["Location"],- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )- assert denied.status_code == 401- assert denied.get_json()["error"] == "remote_access_login_required"- assert "Location" not in denied.headers---def test_show_page_email_session_is_confined_to_its_signed_route(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- cookie = remote_access.make_session_cookie(- config,- "[email protected]",- "guest-1",- session_claims={- "vibe_instance_id": "inst_123",- "vibe_instance_role": "viewer",- "vibe_instance_access_source": "show_page_email",- "vibe_show_page_id": "session-one",- },- )- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- cookie,- domain="alex.avibe.bot",- )-- exact = client.get(- "/show/session-one/missing.js",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )- other = client.get(- "/show/session-two/",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )- workbench = client.get(- "/api/show-pages",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )- session_api = client.get(- "/api/session",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )-- assert exact.status_code != 403- assert other.status_code == 403- assert other.get_json()["error"] == "show_page_access_forbidden"- assert workbench.status_code == 403- assert session_api.status_code == 403---def test_show_page_oidc_claim_shape_fails_closed(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- base = {- "vibe_instance_id": "inst_123",- "vibe_instance_role": "viewer",- "vibe_instance_access_source": "show_page_email",- }-- with pytest.raises(remote_access.OAuthCodeExchangeError, match="invalid_show_page_id"):- remote_access.session_claims_from_oidc(config, base)- broader = remote_access.session_claims_from_oidc(- config,- {- **base,- "vibe_instance_role": "editor",- "vibe_instance_access_source": "email",- "vibe_show_page_id": "session-one",- },- )- assert broader["vibe_instance_access_source"] == "email"- assert broader["vibe_instance_role"] == "editor"- assert broader["vibe_show_page_id"] == "session-one"---def test_remote_login_endpoint_sanitizes_external_next_target(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)-- response = app.test_client().get(- "/auth/login?next=https://evil.example/path",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- state = httpx.URL(response.headers["Location"]).params["state"]- state_payload = ui_server._read_oauth_state(config.remote_access.vibe_cloud.session_secret, state)- assert state_payload is not None- assert state_payload["next"] == "/"---def test_remote_login_endpoint_returns_authenticated_session_to_target(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(- "/auth/login?next=/chat/session-1",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 302- assert response.headers["Location"] == "/chat/session-1"---def test_custom_hostname_uses_remote_auth_until_heartbeat_removes_it(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- config.remote_access.vibe_cloud.instance_secret = "instance-secret"- responses = iter(- [- {"ok": True, "active_hostnames": ["max.fileguard.io"]},- {"ok": True, "active_hostnames": []},- ]- )- monkeypatch.setattr(remote_access, "runtime_status_payload", lambda *args, **kwargs: {"event": "heartbeat"})- monkeypatch.setattr(remote_access, "_json_request", lambda *args, **kwargs: next(responses))- client = app.test_client()-- assert remote_access.report_runtime_status(config)["ok"] is True- allowed = client.get(- "/auth/login?next=/dashboard",- base_url="https://max.fileguard.io",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert allowed.status_code == 302- assert httpx.URL(allowed.headers["Location"]).params["redirect_uri"] == (- "https://max.fileguard.io/auth/callback"- )-- assert remote_access.report_runtime_status(config)["ok"] is True- removed = client.get(- "/auth/login?next=/dashboard",- base_url="https://max.fileguard.io",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert removed.status_code == 503- assert removed.get_json()["error"] == "remote_access_host_mismatch"---def test_persisted_custom_hostname_is_allowed_before_process_cache_warms(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- remote_access._replace_active_hostnames(config, ["max.fileguard.io"])- remote_access._clear_active_hostnames_cache()-- response = app.test_client().get(- "/auth/login?next=/dashboard",- base_url="https://max.fileguard.io",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 302- assert remote_access.active_hostnames(config) == frozenset({"max.fileguard.io"})---def test_custom_hostname_oauth_flow_reuses_redirect_uri_for_exchange(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- remote_access._replace_active_hostnames(config, ["max.fileguard.io"])- client = app.test_client()-- login = client.get(- "/auth/login?next=/dashboard",- base_url="https://max.fileguard.io",- environ_base=_remote_peer(),- follow_redirects=False,- )- authorize_params = httpx.URL(login.headers["Location"]).params- oauth_cookie_header = next(- header- for header in login.headers.getlist("Set-Cookie")- if header.startswith(f"{ui_server.REMOTE_OAUTH_COOKIE_NAME}=")- )- oauth_cookie = oauth_cookie_header.split(";", 1)[0].split("=", 1)[1]- handshake = ui_server._read_oauth_cookie(config.remote_access.vibe_cloud.session_secret, oauth_cookie)- assert handshake is not None- state_payload = ui_server._read_oauth_state(- config.remote_access.vibe_cloud.session_secret,- authorize_params["state"],- )- assert state_payload is not None- stored = remote_access._oauth_handshakes[state_payload["r"]]-- assert authorize_params["redirect_uri"] == "https://max.fileguard.io/auth/callback"- assert handshake["redirect_uri"] == "https://max.fileguard.io/auth/callback"- assert stored["redirect_uri"] == "https://max.fileguard.io/auth/callback"-- exchanged = {}-- def exchange(cfg, code, verifier, redirect_uri=None):- exchanged.update({"code": code, "verifier": verifier, "redirect_uri": redirect_uri})- return _oauth_exchange_result(cfg, nonce=handshake["nonce"])-- monkeypatch.setattr(remote_access, "exchange_oauth_code", exchange)- client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="max.fileguard.io")-- callback = client.get(- f"/auth/callback?code=test-code&state={authorize_params['state']}",- base_url="https://max.fileguard.io",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert callback.status_code == 302- assert callback.headers["Location"] == "/dashboard"- assert exchanged == {- "code": "test-code",- "verifier": handshake["code_verifier"],- "redirect_uri": "https://max.fileguard.io/auth/callback",- }---def test_oauth_redirect_uri_falls_back_for_unlisted_request_host(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)-- with app.test_request_context("/dashboard", base_url="https://unlisted.example"):- response = ui_server._redirect_to_vibe_cloud_login(config)-- params = httpx.URL(response.headers["Location"]).params- assert params["redirect_uri"] == config.remote_access.vibe_cloud.redirect_uri---def test_login_redirect_sets_persistent_handshake_cookie(monkeypatch, tmp_path):- # iOS standalone PWAs drop session-scoped cookies (no Max-Age) across the- # cross-origin authorize excursion, so the callback can't read the handshake- # back and deterministically fails with invalid_oauth_state. The handshake- # cookie must be persistent. Regression guard for the PWA login dead-end.- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)-- with app.test_request_context("/dashboard", base_url="https://alex.avibe.bot"):- response = ui_server._redirect_to_vibe_cloud_login(config)-- set_cookie = response.headers["Set-Cookie"]- assert set_cookie.startswith(f"{ui_server.REMOTE_OAUTH_COOKIE_NAME}=")- assert f"Max-Age={ui_server.REMOTE_OAUTH_HANDSHAKE_TTL_SECONDS}" in set_cookie---def test_login_redirect_sets_stable_device_binding_cookie(monkeypatch, tmp_path):- # The store-fallback recovery is bound to this persistent per-browser device- # cookie, which (unlike the per-flow handshake state) survives the iOS authorize- # excursion. The login redirect must seed it, long-lived.- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)-- with app.test_request_context("/dashboard", base_url="https://alex.avibe.bot"):- response = ui_server._redirect_to_vibe_cloud_login(config)-- device_cookies = [- c for c in response.headers.getlist("Set-Cookie")- if c.startswith(f"{ui_server.REMOTE_OAUTH_DEVICE_COOKIE_NAME}=")- ]- assert len(device_cookies) == 1- assert f"Max-Age={ui_server.REMOTE_OAUTH_DEVICE_TTL_SECONDS}" in device_cookies[0]- assert "HttpOnly" in device_cookies[0]- assert "Secure" in device_cookies[0]---def test_remote_setup_route_serves_shell_before_login(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- _mock_ui_dist(monkeypatch, tmp_path)-- response = app.test_client().get(- "/setup",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 200- assert response.headers.get("Location") is None- assert "Avibe shell" in response.text--[email protected]("path", ["/api/config", "/status", "/api/events"])-def test_remote_background_get_without_session_returns_login_required(monkeypatch, tmp_path, path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)-- response = app.test_client().get(- path,- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 401- assert response.get_json()["error"] == "remote_access_login_required"- assert response.headers.get("Location") is None- assert ui_server.REMOTE_OAUTH_COOKIE_NAME not in response.headers.get("Set-Cookie", "")---def test_api_config_blocked_host_returns_machine_readable_error(monkeypatch, tmp_path):- """Contract the SPA AuthGuard depends on: a blocked GET /api/config returns- 503 with a machine-readable ``error`` code (not a redirect, not an opaque- body). The guard reads this to show an explicit "access blocked" screen- instead of bouncing the visitor to the setup wizard."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)-- response = app.test_client().get(- "/api/config",- base_url="https://old-alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_remote_private_document_routes_through_dedicated_login_endpoint(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)-- response = app.test_client().get(- "/show/ses123/?foo=bar",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- headers={"Accept": "text/html"},- follow_redirects=False,- )-- assert response.status_code == 302- assert response.headers["Location"] == "/auth/login?next=%2Fshow%2Fses123%2F%3Ffoo%3Dbar"- assert ui_server.REMOTE_OAUTH_COOKIE_NAME not in response.headers.get("Set-Cookie", "")---def test_remote_login_preserves_callback_retry_budget(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- _mock_ui_dist(monkeypatch, tmp_path)- client = app.test_client()- state = ui_server._make_oauth_state(- config.remote_access.vibe_cloud.session_secret,- next_target="/show/ses123/?tab=flow",- )-- callback = client.get(- f"/auth/callback?code=test-code&state={state}",- base_url="https://alex.avibe.bot",- follow_redirects=False,- )- retry_target = callback.headers["Location"]- login_entry = client.get(- retry_target,- base_url="https://alex.avibe.bot",- headers={"Accept": "text/html"},- follow_redirects=False,- )- login = client.get(- login_entry.headers["Location"],- base_url="https://alex.avibe.bot",- follow_redirects=False,- )-- assert login_entry.status_code == 302- assert login_entry.headers["Location"] == f"/auth/login?{urlencode({'next': retry_target})}"- assert login.status_code == 302- oauth_state = httpx.URL(login.headers["Location"]).params["state"]- state_payload = ui_server._read_oauth_state(config.remote_access.vibe_cloud.session_secret, oauth_state)- assert state_payload is not None- assert state_payload["next"] == "/show/ses123/?tab=flow"- assert state_payload["retry"] is True---def test_remote_spa_document_with_explicit_port_still_serves_shell(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- _mock_ui_dist(monkeypatch, tmp_path)-- response = app.test_client().get("/dashboard", base_url="https://alex.avibe.bot:443", follow_redirects=False)-- assert response.status_code == 200- assert response.headers.get("Location") is None---def test_remote_spa_document_with_trailing_dot_still_serves_shell(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- _mock_ui_dist(monkeypatch, tmp_path)-- response = app.test_client().get("/dashboard", base_url="https://alex.avibe.bot.", follow_redirects=False)-- assert response.status_code == 200- assert response.headers.get("Location") is None---def test_remote_health_does_not_require_remote_access_cookie(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)-- response = app.test_client().get(- "/health",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 200- assert response.get_json()["status"] == "ok"---def test_localhost_does_not_require_remote_access_cookie(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)-- response = app.test_client().get("/health", base_url="http://127.0.0.1:5123")-- assert response.status_code == 200---def test_live_request_cannot_spoof_test_remote_addr_header(monkeypatch, tmp_path):- """The compatibility test-client shim accepts an environ_base REMOTE_ADDR,- but the transport header it uses must not be honored on live ASGI traffic."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)-- async def _exercise():- transport = httpx.ASGITransport(app=app, client=("203.0.113.10", 50000))- async with httpx.AsyncClient(transport=transport, base_url="http://127.0.0.1:5123") as client:- return await client.get(- "/dashboard",- headers={"X-Vibe-Test-Remote-Addr": "127.0.0.1"},- follow_redirects=False,- )-- response = asyncio.run(_exercise())-- assert response.status_code == 503- assert response.json()["error"] == "remote_access_host_mismatch"---def test_docker_loopback_host_requires_explicit_trust(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.delenv("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS", raising=False)- _save_config(tmp_path)-- response = app.test_client().get(- "/health",- base_url="http://127.0.0.1:15130",- environ_base={"REMOTE_ADDR": "172.17.0.1"},- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_docker_loopback_health_probe_is_allowed_when_explicitly_trusted(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS", "1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST", "127.0.0.1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_PEER_IPS", "172.17.0.1")- _save_config(tmp_path)-- response = app.test_client().get(- "/health",- base_url="http://127.0.0.1:15130",- environ_base={"REMOTE_ADDR": "172.17.0.1"},- )-- assert response.status_code == 200---def test_docker_loopback_status_probe_is_allowed_when_explicitly_trusted(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS", "1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST", "127.0.0.1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_PEER_IPS", "172.17.0.1")- _save_config(tmp_path)-- response = app.test_client().get(- "/status",- base_url="http://127.0.0.1:15130",- environ_base={"REMOTE_ADDR": "172.17.0.1"},- )-- assert response.status_code == 200---def test_authenticated_remote_status_probe_is_blocked_before_runtime_access(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- monkeypatch.setattr(- "vibe.runtime.render_status",- lambda **kwargs: (_ for _ in ()).throw(AssertionError("runtime status must stay local")),- )- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- remote_session_cookie(config, "[email protected]", "viewer-1", role="viewer"),- domain="alex.avibe.bot",- )-- response = client.get(- "/status",- 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_docker_loopback_probe_accepts_ipv4_mapped_peer(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS", "1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST", "127.0.0.1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_PEER_IPS", "172.17.0.1")- _save_config(tmp_path)-- response = app.test_client().get(- "/health",- base_url="http://127.0.0.1:15130",- environ_base={"REMOTE_ADDR": "::ffff:172.17.0.1"},- )-- assert response.status_code == 200---def test_docker_loopback_trust_does_not_bypass_ui_auth(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS", "1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST", "127.0.0.1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_PEER_IPS", "172.17.0.1")- _save_config(tmp_path)-- response = app.test_client().get(- "/dashboard",- base_url="http://127.0.0.1:15130",- environ_base={"REMOTE_ADDR": "172.17.0.1"},- )-- assert response.status_code == 200- assert "<!doctype html>" in response.text---def test_docker_loopback_trust_requires_loopback_port_binding(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS", "1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST", "0.0.0.0")- _save_config(tmp_path)-- response = app.test_client().get(- "/health",- base_url="http://127.0.0.1:15130",- environ_base={"REMOTE_ADDR": "172.17.0.1"},- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_docker_loopback_ui_requires_loopback_port_binding(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS", "1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST", "0.0.0.0")- _save_config(tmp_path)-- response = app.test_client().get(- "/dashboard",- base_url="http://127.0.0.1:15130",- environ_base={"REMOTE_ADDR": "172.17.0.1"},- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_docker_loopback_trust_still_rejects_non_local_host(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS", "1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST", "127.0.0.1")- _save_config(tmp_path)-- response = app.test_client().get(- "/health",- base_url="https://old-alex.avibe.bot",- environ_base={"REMOTE_ADDR": "172.17.0.1"},- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_docker_loopback_trust_rejects_untrusted_peer(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS", "1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST", "127.0.0.1")- _save_config(tmp_path)-- response = app.test_client().get(- "/health",- base_url="http://127.0.0.1:15130",- environ_base={"REMOTE_ADDR": "8.8.8.8"},- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_docker_loopback_trust_requires_configured_peer_ip(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS", "1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST", "127.0.0.1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_PEER_IPS", "172.17.0.1")- _save_config(tmp_path)-- response = app.test_client().get(- "/health",- base_url="http://127.0.0.1:15130",- environ_base={"REMOTE_ADDR": "172.17.0.1"},- )-- assert response.status_code == 200---def test_docker_loopback_trust_accepts_runtime_default_gateway(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS", "1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST", "127.0.0.1")- monkeypatch.delenv("VIBE_REMOTE_DOCKER_LOOPBACK_PEER_IPS", raising=False)- monkeypatch.setattr(- ui_server,- "_docker_route_table_lines",- lambda: [- "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT",- "eth0\t00000000\t010013AC\t0003\t0\t0\t0\t00000000\t0\t0\t0",- ],- )- _save_config(tmp_path)-- response = app.test_client().get(- "/dashboard",- base_url="http://127.0.0.1:15130",- environ_base={"REMOTE_ADDR": "172.19.0.1"},- )-- assert response.status_code == 200- assert "<!doctype html>" in response.text---def test_docker_loopback_trust_rejects_same_network_container_peer(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS", "1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST", "127.0.0.1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_PEER_IPS", "172.17.0.1")- _save_config(tmp_path)-- response = app.test_client().get(- "/dashboard",- base_url="http://127.0.0.1:15130",- environ_base={"REMOTE_ADDR": "172.17.0.2"},- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_docker_loopback_trust_rejects_non_gateway_peer_on_dynamic_bridge(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS", "1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST", "127.0.0.1")- monkeypatch.delenv("VIBE_REMOTE_DOCKER_LOOPBACK_PEER_IPS", raising=False)- monkeypatch.setattr(- ui_server,- "_docker_route_table_lines",- lambda: [- "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT",- "eth0\t00000000\t010013AC\t0003\t0\t0\t0\t00000000\t0\t0\t0",- ],- )- _save_config(tmp_path)-- response = app.test_client().get(- "/dashboard",- base_url="http://127.0.0.1:15130",- environ_base={"REMOTE_ADDR": "172.19.0.2"},- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_docker_loopback_trust_accepts_ipv4_mapped_configured_peer(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS", "1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST", "127.0.0.1")- monkeypatch.setenv("VIBE_REMOTE_DOCKER_LOOPBACK_PEER_IPS", "172.17.0.1")- _save_config(tmp_path)-- response = app.test_client().get(- "/health",- base_url="http://127.0.0.1:15130",- environ_base={"REMOTE_ADDR": "::ffff:172.17.0.1"},- )-- assert response.status_code == 200---def test_unmatched_non_local_host_fails_closed_when_remote_access_enabled(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)-- response = app.test_client().get(- "/dashboard",- base_url="https://old-alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_loopback_proxy_with_public_host_mismatch_fails_closed(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)-- response = app.test_client().get(- "/dashboard",- base_url="https://old-alex.avibe.bot",- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_loopback_proxy_with_partial_forwarded_metadata_fails_closed(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)-- response = app.test_client().get(- "/dashboard",- base_url="https://old-alex.avibe.bot",- environ_base={"REMOTE_ADDR": "127.0.0.1"},- headers={"X-Real-IP": "203.0.113.10"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_loopback_origin_proxy_with_loopback_host_is_allowed(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)-- response = app.test_client().get(- "/dashboard",- base_url="http://127.0.0.1:15131",- environ_base={"REMOTE_ADDR": "127.0.0.1"},- headers={- "X-Forwarded-Proto": "https",- "X-Forwarded-Host": "vibe.example",- },- follow_redirects=False,- )-- 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_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"- config.memory.processing.llm.model = "private-model"- config.save()- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- _org_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_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"- config.agents.codex.cli_path = "/opt/avibe/bin/codex"- config.save()- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- _org_session_cookie(config, "[email protected]", "user-owner", role="owner", organization_role="owner"),- domain="alex.avibe.bot",- )-- response = client.get(- "/api/config",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )-- assert response.status_code == 200- payload = response.get_json()- assert payload["mode"] == "self_host"- assert payload["ui"]["instance_name"] == config.ui.instance_name- 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_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"- config.agents.codex.cli_path = "/opt/avibe/bin/codex"- config.ack_mode = "reaction"- config.show_duration = False- config.include_time_info = False- config.include_user_info = True- config.reply_enhancements = False- config.agent_progress_style = "concise"- config.save()- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- _org_session_cookie(config, "[email protected]", "user-owner", role="owner", organization_role="owner"),- domain="alex.avibe.bot",- )-- response = client.post(- "/api/config",- json={"ui": {"instance_name": "Remote Workbench"}},- headers=csrf_headers(client, "https://alex.avibe.bot"),- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )-- assert response.status_code == 200- payload = response.get_json()- assert payload["ui"]["instance_name"] == "Remote Workbench"- 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 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--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,- _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- 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 grants runtime management without fabricating owner- # identity or trusted-local machine capability bits.- assert payload["capabilities"]["is_instance_owner"] is False- assert payload["capabilities"]["can_manage_instance"] is True- assert payload["capabilities"]["can_use_system"] is False---def test_non_org_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())--- ("instance_role", "organization_role"),- [("owner", "owner"), ("viewer", "member")],-)-def test_remote_org_members_can_use_files_editor_and_builtin_apps(- monkeypatch,- tmp_path,- instance_role,- organization_role,-):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- workspace = tmp_path / "workspace"- workspace.mkdir()- write_path = workspace / f"{organization_role}.txt"- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- remote_session_cookie(- config,- f"{organization_role}@example.com",- f"user-{organization_role}",- role=instance_role,- access_source="organization_group",- organization_id="org-1",- organization_member_id=f"member-{organization_role}",- organization_role=organization_role,- group_ids=[],- ),- domain="alex.avibe.bot",- )-- list_response = client.get(- "/api/files/list",- params={"path": str(workspace)},- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )- write_response = client.put(- "/api/files/write",- json={"path": str(write_path), "content": "remote editor write"},- headers=csrf_headers(client, "https://alex.avibe.bot"),- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )- dock_response = client.get(- "/api/dock",- 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())- assert write_response.status_code == 200- assert write_path.read_text(encoding="utf-8") == "remote editor write"- assert dock_response.status_code == 200- assert dock_response.get_json()["dock"]["order"] == [- "files",- "terminal",- "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",- environ_base=_remote_peer(),- )- assert session_response.get_json()["temporary_unrestricted_org_app_access"] is True--- ("method", "path", "json_body"),- [- ("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_active_org_access_preserves_identity_control_plane_boundary(- 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",- role="owner",- access_source="organization_group",- organization_id="org-1",- organization_member_id="member-owner",- organization_role="owner",- group_ids=[],- ),- domain="alex.avibe.bot",- )-- response = client.request(- method,- path,- json=json_body,- headers=csrf_headers(client, "https://alex.avibe.bot") if method != "GET" else None,- 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"),- [- ("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"--[email protected]("path", ("/api/running-agents", "/api/agents-graph"))-def test_remote_runtime_snapshots_are_blocked_before_controller_access(monkeypatch, tmp_path, 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", role="owner"),- domain="alex.avibe.bot",- )-- async def unexpected_snapshot(*args, **kwargs):- raise AssertionError("remote runtime snapshot reached the local controller")-- monkeypatch.setattr("vibe.internal_client.list_running_agents", unexpected_snapshot)- response = client.get(- path,- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )-- assert response.status_code == 403- assert response.get_json()["code"] == "remote_execution_disabled"--- "json_body",- [- {"agent_name": "codex"},- {"model": "gpt-5"},- {"reasoning_effort": "high"},- {"scope_id": "scope-local"},- {"visibility": "background"},- {"pinned": True},- ],-)-def test_remote_session_execution_settings_are_blocked_before_store_access(- monkeypatch,- tmp_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",- )-- def unexpected_session_update(*args, **kwargs):- raise AssertionError("remote session routing reached the local session store")-- monkeypatch.setattr(- "core.services.sessions.update_session",- unexpected_session_update,- )- response = client.patch(- "/api/sessions/ses-local",- 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"),- [- ("POST", "/api/projects", {"folder_path": "/tmp/remote-project"}),- ("PATCH", "/api/projects/proj-local", {"folder_path": "/tmp/remote-project"}),- ("PATCH", "/api/projects/proj-local", {"agent_name": "codex"}),- ("PATCH", "/api/projects/proj-local", {"model": "gpt-5"}),- ],-)-def test_remote_project_execution_settings_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",- )-- monkeypatch.setattr(- "storage.projects_service.create_project",- lambda *args, **kwargs: (_ for _ in ()).throw(- AssertionError("remote project creation reached the local project store")- ),- )- monkeypatch.setattr(- "storage.projects_service.update_project",- lambda *args, **kwargs: (_ for _ in ()).throw(- AssertionError("remote project routing reached the local project store")- ),- )- 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"---def test_remote_im_settings_are_rejected_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",- )-- monkeypatch.setattr(- api,- "save_settings",- lambda payload: (_ for _ in ()).throw(- AssertionError("remote IM configuration reached the local settings store")- ),- )- response = client.post(- "/api/settings",- json={"platform": "slack", "channels": {"C1": {"enabled": False}}},- 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_im_settings_read_is_rejected_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",- )- monkeypatch.setattr(- api,- "get_settings",- lambda *args, **kwargs: (_ for _ in ()).throw(- AssertionError("remote IM settings read reached the local settings store")- ),- )-- response = client.get(- "/api/settings?platform=slack",- 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_thread_scope_settings_are_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",- )- monkeypatch.setattr(- api,- "save_thread_settings",- lambda payload: (_ for _ in ()).throw(- AssertionError("remote thread routing reached the local settings store")- ),- )-- response = client.post(- "/api/settings/thread",- json={- "platform": "telegram",- "channel_id": "channel-1",- "thread_id": "thread-1",- "settings": {"enabled": 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_session_fork_is_rejected_before_fork_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",- )-- async def unexpected_turn_state(session_id):- raise AssertionError(f"remote fork reached turn-state lookup for {session_id}")-- monkeypatch.setattr(ui_server, "_session_turn_state_for_fork", unexpected_turn_state)- monkeypatch.setattr(- ui_server,- "_reserve_forked_session_for_ui",- lambda *args, **kwargs: (_ for _ in ()).throw(- AssertionError("remote fork reached the local session store")- ),- )-- response = client.post(- "/api/sessions/ses-local/fork",- 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"--- "json_body",- [- {"agents": {"codex": {"cli_path": "/tmp/remote-codex"}}},- {"platforms": {"enabled": ["telegram"], "primary": "telegram"}},- {"remote_access": {"provider": "none"}},- {"ui": {"setup_host": "0.0.0.0"}},- {"update": {"auto_update": False}},- {"show_pages_prompt": "follow remote instructions"},- {"future_runtime": {"enabled": True}},- ],-)-def test_remote_execution_config_changes_are_blocked_before_runtime_reconcile(- monkeypatch,- tmp_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",- )- monkeypatch.setattr(- ui_server,- "_save_config_and_runtime_decisions",- lambda *args, **kwargs: (_ for _ in ()).throw(- AssertionError("remote execution config reached persistence/reconcile")- ),- )-- response = client.post(- "/api/config",- 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_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 not ui_server._is_remote_local_execution_request(- "PATCH", "/api/sessions/ses-local", {"visibility": "background"}- )- 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_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,- _org_session_cookie(config, "[email protected]", "user-member"),- domain="alex.avibe.bot",- )-- async def projected(_session_id):- return {- "status_code": 200,- "body": {- "in_flight": False,- "foreground": "idle",- "background_activities": [- {- "id": "backend-1",- "item_kind": "backend_activity",- "label": "Waiting for turn",- "status": "running",- },- {- "id": "task-1",- "item_kind": "task",- "label": "private prompt head",- "status": "scheduled",- },- ],- "pending_activity_output_count": 1,- "connection": "connected",- },- }-- monkeypatch.setattr("vibe.internal_client.turn_state", projected)- response = client.get(- "/api/sessions/ses-local/turn-state",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )-- assert response.status_code == 200- body = response.get_json()- 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"--- ("method", "path", "payload"),- [- ("POST", "/api/sessions", None),- ("POST", "/api/sessions", {"project_id": "proj-1", "future_route": "codex"}),- ("PATCH", "/api/sessions/ses-1", {"title": "renamed", "future_route": "codex"}),- ("POST", "/api/projects", {"display_name": "Project", "future_workdir": "/tmp"}),- ("PATCH", "/api/projects/proj-1", {"display_name": "Project", "future_route": "codex"}),- (- "POST",- "/api/settings",- {"platform": "slack", "channels": {"C1": {"enabled": True, "future_route": "codex"}}},- ),- (- "POST",- "/api/settings/thread",- {- "platform": "telegram",- "channel_id": "C1",- "thread_id": "T1",- "settings": {"enabled": True, "future_route": "codex"},- },- ),- ],-)-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_temporary_org_config_policy_accepts_runtime_fields_but_not_identity_routes(- monkeypatch,- tmp_path,-):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)-- assert not ui_server._is_remote_local_execution_request(- "POST",- "/api/config",- {- **json.loads(json.dumps(api.config_to_payload(config))),- "future_runtime": {"enabled": True},- },- )- assert ui_server._is_remote_local_execution_request(- "POST", "/api/remote-access/settings", {"enabled": True}- )---def test_active_org_config_preserves_runtime_fields_but_strips_remote_access_identity(- 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,- _org_session_cookie(config, "[email protected]", "user-member"),- domain="alex.avibe.bot",- )- payload = json.loads(json.dumps(api.config_to_payload(config)))- payload["language"] = "zh"- payload["agent_progress_style"] = "concise"- observed = []-- def save_config(remote_payload):- observed.append(remote_payload)- return config, False, False, []-- monkeypatch.setattr(ui_server, "_save_config_and_runtime_decisions", save_config)- monkeypatch.setattr(ui_server, "_ensure_remote_access_monitoring", lambda _config: None)- response = client.post(- "/api/config",- json=payload,- headers=csrf_headers(client, "https://alex.avibe.bot"),- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )-- assert response.status_code == 200- assert len(observed) == 1- assert observed[0]["language"] == "zh"- assert observed[0]["agent_progress_style"] == "concise"- 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]---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"--- ("method", "path", "json_body", "call_target"),- [- ("GET", "/api/doctor", None, "vibe.ui_server.paths.get_runtime_doctor_path"),- ("POST", "/api/doctor", {}, "vibe.cli._doctor"),- ("POST", "/api/logs", {}, "vibe.ui_server._resolve_log_sources"),- ("POST", "/api/ui/reload", {"host": "127.0.0.1", "port": 5123}, "vibe.runtime.read_status"),- ("POST", "/api/opencode/options", {"cwd": "/tmp/remote"}, "vibe.api.opencode_options_async"),- ("POST", "/api/opencode/setup-permission", {}, "vibe.api.setup_opencode_permission"),- ],-)-def test_remote_diagnostics_and_legacy_system_helpers_are_blocked_before_local_access(- monkeypatch,- tmp_path,- method,- 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_local_access(*args, **kwargs):- raise AssertionError(f"remote request reached local capability: {path}")-- monkeypatch.setattr(call_target, unexpected_local_access)- request_kwargs = {- "headers": csrf_headers(client, "https://alex.avibe.bot"),- "base_url": "https://alex.avibe.bot",- "environ_base": _remote_peer(),- }- if json_body is not None:- request_kwargs["json"] = json_body- response = client.request(method, path, **request_kwargs)-- 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/models/sources", "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"--- ("instance_role", "organization_role"),- [("owner", "owner"), ("viewer", "member")],-)-def test_remote_org_members_can_reach_show_page_icon_upload(- monkeypatch,- tmp_path,- instance_role,- organization_role,-):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- calls = []-- def upload_icon(*args, **kwargs):- calls.append((args, kwargs))- return {"ok": True, "session_id": "ses-remote", "icon_version": "v1"}-- monkeypatch.setattr(api, "upload_show_page_icon", upload_icon)- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- remote_session_cookie(- config,- f"{organization_role}@example.com",- f"user-{organization_role}",- role=instance_role,- access_source="organization_group",- organization_id="org-1",- organization_member_id=f"member-{organization_role}",- organization_role=organization_role,- group_ids=[],- ),- domain="alex.avibe.bot",- )-- response = client.post(- "/api/show-pages/ses-remote/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 == 200- assert len(calls) == 1- assert calls[0][0] == ("ses-remote", b"<svg/>")- 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--- ("path", "json_body", "api_method", "expected_args"),- [- (- "/api/show-pages/ses-local/rotate-share",- {},- "rotate_show_page_share",- ("ses-local",),- ),- (- "/api/show-pages/ses-local/share-id",- {"share_id": "remote-link"},- "set_show_page_share_id",- ("ses-local", "remote-link"),- ),- ],-)-def test_remote_show_page_public_link_mutations_reach_resource_authorization(- monkeypatch,- tmp_path,- path,- json_body,- api_method,- expected_args,-):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- _org_session_cookie(config, "[email protected]", "user-member"),- domain="alex.avibe.bot",- )-- calls = []-- def authorized_show_page_write(*args, **kwargs):- calls.append((args, kwargs))- return {"session_id": "ses-local", "share_id": "remote-link"}-- monkeypatch.setattr(api, api_method, authorized_show_page_write)- 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 == 200- assert len(calls) == 1- args, kwargs = calls[0]- assert args == expected_args- assert kwargs["user_context"].is_remote is True- assert kwargs["user_context"].is_trusted_local is False--- ("path", "local_only"),- [- ("/api/models/runtime/status", False),- ("/api/models/agents", False),- ("/api/models/sources", False),- ("/api/backend/codex/runtime", False),- ("/api/backend/codex/auth", False),- ],-)-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---def _show_event_frame() -> str:- return json.dumps(- {- "type": "show.event",- "data": {- "id": "evt-1",- "session_id": "ses123",- "transcript_text": "Annotation at /Users/alex/.avibe/state/media/shot.png",- "payload": {- "author": {"kind": "user", "email": "[email protected]"},- "screenshot": {- "attachmentId": "med_1",- "path": "/Users/alex/.avibe/state/media/shot.png",- "mimeType": "image/png",- "width": 10,- "height": 10,- },- },- },- }- )---def test_remote_show_event_stream_redacts_local_screenshot_path() -> None:- from vibe.authorization import AuthorizationContext-- projected = ui_server._workbench_event_payload_for_context(- AuthorizationContext(instance_role="owner", is_remote=True),- "show.event",- _show_event_frame(),- )-- assert projected is not None- assert "/Users/alex/.avibe" not in projected- data = json.loads(projected)["data"]- screenshot = data["payload"]["screenshot"]- assert "path" not in screenshot- # Everything the remote workbench needs to render the annotation survives.- assert screenshot["attachmentId"] == "med_1"- assert data["session_id"] == "ses123"- 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"},- }- )-- # Vaults.updated keeps the runtime data; only the host path on- # show.event frames is redacted (display-layer redaction is preserved- # under the temporary full-access rollout — see #1343).- assert (- ui_server._workbench_event_payload_for_context(- context,- "vaults.updated",- vault_frame,- )- == vault_frame- )- show_projection = ui_server._workbench_event_payload_for_context(- context,- "show.event",- show_frame,- )- assert show_projection is not None- show_data = json.loads(show_projection)["data"]- assert show_data["payload"]["screenshot"].get("path") is None- assert "med_1" in show_data["transcript_text"]---def test_remote_show_event_stream_drops_unprojectable_frame() -> None:- from vibe.authorization import AuthorizationContext-- remote_owner = AuthorizationContext(instance_role="owner", is_remote=True)-- assert (- ui_server._workbench_event_payload_for_context(remote_owner, "show.event", "not json")- is None- )- assert (- ui_server._workbench_event_payload_for_context(- remote_owner, "show.event", json.dumps({"type": "show.event", "data": "opaque"})- )- is None- )---def test_local_show_event_stream_keeps_the_screenshot_path() -> None:- from vibe.authorization import trusted_local_context-- frame = _show_event_frame()-- assert (- ui_server._workbench_event_payload_for_context(- trusted_local_context(), "show.event", frame- )- == frame- )---def _deny_show_page_acl(monkeypatch, *, allowed: bool) -> list[tuple[str, str]]:- """Record the Show Page ACL checks the workbench stream makes."""-- from storage import resource_access_service-- checks: list[tuple[str, str]] = []-- def _can_use_resource(context, resource_kind, resource_id, **kwargs):- checks.append((resource_kind, resource_id))- return allowed-- monkeypatch.setattr(resource_access_service, "can_use_resource", _can_use_resource)- return checks---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_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_member, "show.event", _show_event_frame()- )- is True- )- assert checks == []---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)- non_member = AuthorizationContext(- instance_role="owner",- subject="[email protected]",- instance_access_source="owner",- is_remote=True,- )-- assert (- ui_server._workbench_event_visible_to_context(- non_member, "show.event", _show_event_frame()- )- is False- )- assert checks == []---def test_show_event_without_a_session_is_dropped(monkeypatch) -> None:- from vibe.authorization import AuthorizationContext-- _deny_show_page_acl(monkeypatch, allowed=True)- remote_owner = AuthorizationContext(instance_role="owner", is_remote=True)-- assert (- ui_server._workbench_event_visible_to_context(- remote_owner,- "show.event",- json.dumps({"type": "show.event", "data": {"id": "evt-1"}}),- )- is False- )---def test_local_show_event_skips_the_remote_acl(monkeypatch) -> None:- """A trusted-local subscriber has no authorization context to evaluate."""-- checks = _deny_show_page_acl(monkeypatch, allowed=False)-- assert (- ui_server._workbench_event_visible_to_context(None, "show.event", _show_event_frame())- is True- )- assert checks == []--- ("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"),- [- ("GET", "/api/skills/check", None, "check_skills"),- ("GET", "/api/skills/find?q=memory", None, "find_skills"),- ("POST", "/api/skills/preview", {"source": "./local-skill"}, "preview_skill_source"),- ("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_operations_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"---def test_active_org_project_scoped_skill_reads_bypass_project_acl(- monkeypatch,- tmp_path,-):- from storage import project_access_service, projects_service- from storage.db import create_sqlite_engine- from storage.importer import ensure_sqlite_state-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- ensure_sqlite_state()- engine = create_sqlite_engine()- folder = tmp_path / "project"- folder.mkdir()- with engine.begin() as conn:- project = projects_service.create_project(conn, str(folder), display_name="Restricted")- project_access_service.apply_project_access_intent(- conn,- {- "project_id": project["id"],- "revision": 1,- "mode": "restricted",- "bindings": [],- },- )- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- _org_session_cookie(config, "[email protected]", "user-member"),- domain="alex.avibe.bot",- )-- calls = []-- 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 == 200- assert response.get_json() == {"ok": True, "skills": []}- assert len(calls) == 1- assert calls[0][1]["user_context"].is_active_organization_member is True--- ("method", "path", "json_body", "api_method"),- [- ("POST", "/api/vault/requests/access", {"secret_name": "REMOTE_SECRET"}, "request_vault_access"),- ("POST", "/api/vault/requests/sign", {"secret_name": "REMOTE_SECRET"}, "request_vault_sign"),- ("POST", "/api/vault/secrets", {"name": "REMOTE_SECRET"}, "create_vault_secret"),- ("PATCH", "/api/vault/secrets/REMOTE_SECRET", {"description": "changed"}, "update_vault_secret"),- ("DELETE", "/api/vault/secrets/REMOTE_SECRET", None, "delete_vault_secret"),- ("POST", "/api/vault/grants", {"secret_name": "REMOTE_SECRET"}, "create_vault_grant"),- ("DELETE", "/api/vault/grants/grant-1", None, "revoke_vault_grant"),- ("POST", "/api/vault/sign", {"secret_name": "REMOTE_SECRET"}, "vault_sign"),- ],-)-def test_remote_vault_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_vault_call(*args, **kwargs):- raise AssertionError("remote Vault mutation reached the local Vault API")-- monkeypatch.setattr(api, api_method, unexpected_vault_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"),- [- ("GET", "/api/users", None, "get_users"),- ("POST", "/api/users", {"platform": "slack", "users": {"U1": {"enabled": True}}}, "save_users"),- ("POST", "/api/users/U1/admin", {"platform": "slack", "is_admin": True}, "toggle_admin"),- ("DELETE", "/api/users/U1", None, "remove_user"),- ],-)-def test_active_org_member_can_manage_im_users(- 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,- _org_session_cookie(- config,- "[email protected]",- "user-owner",- role="owner",- organization_role="owner",- ),- domain="alex.avibe.bot",- )-- calls = []-- def user_call(*args, **kwargs):- calls.append((args, kwargs))- return {"ok": True}-- monkeypatch.setattr(api, api_method, user_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 == 200- assert len(calls) == 1--- ("method", "path", "json_body", "api_method"),- [- ("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_active_org_member_can_manage_bind_codes(- 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,- _org_session_cookie(- config,- "[email protected]",- "user-owner",- role="owner",- organization_role="owner",- ),- domain="alex.avibe.bot",- )-- calls = []-- def bind_code_call(*args, **kwargs):- calls.append((args, kwargs))- return {"ok": True}-- monkeypatch.setattr(api, api_method, bind_code_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 == 200- assert len(calls) == 1---def test_remote_project_archive_is_blocked_before_project_store(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", role="owner"),- domain="alex.avibe.bot",- )- monkeypatch.setattr(- "storage.projects_service.archive_project",- lambda *args, **kwargs: (_ for _ in ()).throw(- AssertionError("remote project archive reached the local project store")- ),- )-- response = client.delete(- "/api/projects/proj-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", "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_active_org_member_can_read_instructions_and_session_queue(- monkeypatch,- tmp_path,-):- """The temporary runtime policy opens instruction and queue reads."""-- 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,- _org_session_cookie(config, "[email protected]", "user-member"),- 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 global_response.status_code == 200- 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_active_org_member_can_register_and_test_a_web_push_endpoint(- monkeypatch,- tmp_path,-):- """Web Push follows the same temporary unrestricted runtime policy."""-- from storage.importer import ensure_sqlite_state-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- ensure_sqlite_state()- sent: list[dict] = []- monkeypatch.setattr(- "core.web_push.send_web_push",- lambda **kwargs: sent.append(kwargs),- )- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- _org_session_cookie(config, "[email protected]", "user-member"),- domain="alex.avibe.bot",- )- headers = csrf_headers(client, "https://alex.avibe.bot")-- def _post(path: str, payload: dict):- return client.post(- path,- json=payload,- headers=headers,- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )-- internal_endpoint = "https://127.0.0.1:8443/push"- subscribe = _post(- "/api/web-push/subscriptions",- {- "endpoint": internal_endpoint,- "keys": {"p256dh": "public-key", "auth": "auth-secret"},- },- )- test_send = _post("/api/web-push/test", {"endpoint": internal_endpoint})- unsubscribe = client.delete(- "/api/web-push/subscriptions",- json={"endpoint": internal_endpoint},- headers=headers,- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )- status = client.get(- "/api/web-push/status",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )-- for response in (subscribe, test_send, unsubscribe):- assert response.status_code == 200- assert len(sent) == 1- assert sent[0]["subscription"]["endpoint"] == internal_endpoint- assert status.status_code == 200- # Unsubscribe disables the just-created endpoint before the final status read.- assert status.get_json()["subscription_count"] == 0---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 _show_event_response_json(response_tuple) -> dict:- """Read the JSON body of a `_show_event_response_from_payload` return value.-- The compat `jsonify()` yields a Starlette `JSONResponse` inside a test- request context, so read its raw body rather than the Flask `get_json()`.- """-- response = response_tuple[0]- if hasattr(response, "get_json"):- return response.get_json()- return json.loads(response.body)---async def test_remote_show_write_rejects_agent_provenance_event_types(- monkeypatch,- tmp_path,-):- """A remote editor may only author human Show events, not Agent/system ones.-- The shared `_show_event_response_from_payload` already blocks events that- request Agent dispatch, but a non-dispatching event such as- `assistant.mark.created` or `system.runtime.status` still reaches- `ShowSessionEventStore.append()`, which derives the actor from the type and- would persist it as `author="agent"`. A collaborator could therefore forge- Agent or system activity in the shared transcript, so the remote path is- restricted to the same human-event / mark-resolution allowlist the public- route enforces. This is exercised through the HTML route- (`POST /show/<id>/__show/events`, remote-allowed for editors), the surface a- remote collaborator with page access actually reaches; the store is stubbed- so reaching it would raise, proving rejection happens at the boundary.- """-- from vibe.authorization import AuthorizationContext-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- remote_context = AuthorizationContext(instance_role="editor", is_remote=True)-- def unexpected_store():- raise AssertionError("an unsupported remote event must not be stored")-- monkeypatch.setattr(ui_server, "_show_session_event_store", unexpected_store)-- async def unexpected_dispatch(event_payload):- raise AssertionError("an unsupported remote event must not dispatch")-- monkeypatch.setattr(ui_server, "_run_show_event_dispatch", unexpected_dispatch)-- for event_type in ("assistant.mark.created", "system.runtime.status"):- with app.test_request_context(- "/show/ses-remote/__show/events",- method="POST",- base_url="https://alex.avibe.bot",- ):- g.authorization_context = remote_context- response = await ui_server._show_event_response_from_payload(- "ses-remote",- {"type": event_type, "actor": "agent", "payload": {}},- )- assert response[1] == 400, event_type- assert _show_event_response_json(response)["code"] == "unsupported_event_type"---async def test_remote_show_write_accepts_human_event_and_mark_resolution(- monkeypatch,- tmp_path,-):- """A remote editor may still post the human events and resolve a mark.-- The human-event / mark-resolution allowlist is the surface a collaborator- actually needs: typing an intent, annotating, and resolving an Agent-drawn- mark. These must still be accepted across the tunnel. A trusted-local caller- keeps the full supported set, so `assistant.mark.created` (Agent- provenance) is allowed locally.- """-- from vibe.authorization import AuthorizationContext, trusted_local_context-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- remote_context = AuthorizationContext(instance_role="editor", is_remote=True)-- accepted: list[tuple[str, str]] = []-- class _StubStore:- def __init__(self):- self.closed = False-- def append(self, session_id, payload, *, author=None, reserve_dispatch=True):- accepted.append(("append", payload["type"]))- return {- "id": "evt-1",- "sessionId": session_id,- "type": payload["type"],- "actor": "human",- "payload": payload.get("payload", {}),- "ts": "2026-08-10T10:00:00Z",- }-- def close(self):- accepted.append(("close", "store"))-- monkeypatch.setattr(ui_server, "_show_session_event_store", _StubStore)- monkeypatch.setattr(- ui_server, "_publish_show_session_event", lambda event_payload: None- )-- # Remote: human intent and mark resolution are accepted.- for event_type in ("human.intent.submitted", "assistant.mark.resolved"):- with app.test_request_context(- "/show/ses-remote/__show/events",- method="POST",- base_url="https://alex.avibe.bot",- ):- g.authorization_context = remote_context- response = await ui_server._show_event_response_from_payload(- "ses-remote",- {"type": event_type, "actor": "human", "payload": {}},- )- assert response[1] == 201, event_type- assert _show_event_response_json(response)["ok"] is True-- # Local: Agent provenance is allowed, so the store sees it.- with app.test_request_context(- "/show/ses-local/__show/events",- method="POST",- base_url="http://127.0.0.1:5123",- ):- g.authorization_context = trusted_local_context()- response = await ui_server._show_event_response_from_payload(- "ses-local",- {"type": "assistant.mark.created", "actor": "agent", "payload": {}},- )- assert response[1] == 201- appended_types = [t for op, t in accepted if op == "append"]- assert appended_types == [- "human.intent.submitted",- "assistant.mark.resolved",- "assistant.mark.created",- ]---def test_remote_show_runtime_write_is_rejected_before_runtime_invocation(- 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",- )-- async def unexpected_runtime(*args, **kwargs):- raise AssertionError("remote Show write reached the local Show Runtime")-- monkeypatch.setattr(ui_server, "_show_page_runtime_response", unexpected_runtime)- response = client.post(- "/show/ses-remote/api/example",- json={"input": "remote"},- headers=csrf_headers(client, "https://alex.avibe.bot"),- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )-- assert response.status_code == 403- payload = response.get_json()- assert payload["code"] == "remote_execution_disabled"- assert payload["error"]["code"] == "remote_execution_disabled"---def test_active_org_member_can_read_session_history_without_resource_acl(- 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,- _org_session_cookie(config, "[email protected]", "user-member"),- 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_show_page_email_session_cannot_read_session_history_api(- monkeypatch,- tmp_path,-):- from core.show_pages import ShowPageStore- from storage import (- messages_service,- project_access_service,- projects_service,- workbench_sessions_service,- )- from storage.db import create_sqlite_engine- from storage.importer import ensure_sqlite_state-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- ensure_sqlite_state()- engine = create_sqlite_engine()- project_dir = tmp_path / "page-entitlement-project"- project_dir.mkdir()- with engine.begin() as conn:- project = projects_service.create_project(conn, str(project_dir))- applied = project_access_service.apply_project_access_intent(- conn,- {- "project_id": project["id"],- "organization_id": "org-1",- "revision": 1,- "mode": "restricted",- "bindings": [- {- "principal_kind": "organization_group",- "principal_value": "group-engineering",- "access_role": "viewer",- }- ],- },- )- assert applied.outcome == "applied"- session = workbench_sessions_service.create_session(- conn,- scope_id=project["scope_id"],- agent_backend="codex",- agent_name="owner-worker",- )- messages_service.append(- conn,- scope_id=project["scope_id"],- session_id=session["id"],- platform="avibe",- author="user",- message_type="user",- text="owner-only transcript",- )- show_pages = ShowPageStore()- try:- show_pages.ensure(session["id"])- finally:- show_pages.close()-- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- remote_session_cookie(- config,- "[email protected]",- "guest-1",- session_claims={- "vibe_instance_id": "inst_123",- "vibe_instance_role": "viewer",- "vibe_instance_access_source": "show_page_email",- "vibe_show_page_id": session["id"],- },- ),- 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 == 403- assert response.get_json() == {"ok": False, "error": "show_page_access_forbidden"}---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()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- remote_session_cookie(- config,- "[email protected]",- "user-viewer",- role="viewer",- access_source="owner",- ),- domain="alex.avibe.bot",- )-- read_response = client.get("/api/version", base_url="https://alex.avibe.bot")- 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")-- # /api/version is a baseline read (origin/org viewer-allowed) and stays- # available to a signed non-Organization viewer; runtime management- # endpoints (/api/remote-access/status) are denied under the active-Org- # admission gate.- assert read_response.status_code == 200- 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["temporary_unrestricted_org_access"] is False- assert session_payload["capabilities"]["can_read_instance"] is True- assert session_payload["capabilities"]["can_chat"] is False- assert session_payload["capabilities"]["can_use_system"] is False--- ("role", "organization_role"),- [- ("viewer", "member"),- ("editor", "member"),- ("owner", "owner"),- ],-)-def test_active_org_instance_roles_share_temporary_runtime_access(- monkeypatch,- tmp_path,- role,- organization_role,-):- from storage.importer import ensure_sqlite_state-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- config.ack_mode = "reaction"- config.show_duration = False- config.include_time_info = False- config.include_user_info = True- config.reply_enhancements = False- config.agent_progress_style = "concise"- config.save()- ensure_sqlite_state()- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- _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")-- read_response = client.get("/api/projects", base_url="https://alex.avibe.bot")- agents_response = client.get("/api/agents", base_url="https://alex.avibe.bot")- skills_response = client.get("/api/skills", base_url="https://alex.avibe.bot")- vault_response = client.get("/api/vault/secrets", base_url="https://alex.avibe.bot")- show_pages_response = client.get("/api/show-pages", base_url="https://alex.avibe.bot")- config_response = client.get("/api/config", base_url="https://alex.avibe.bot")- prefs_read_response = client.get("/api/workbench/prefs", base_url="https://alex.avibe.bot")- prefs_write_response = client.put(- "/api/workbench/prefs",- base_url="https://alex.avibe.bot",- headers=headers,- json={"background_work_banner_enabled": False},- )- conversation_response = client.post(- "/api/sessions",- base_url="https://alex.avibe.bot",- headers=headers,- json={},- )- project_response = client.post(- "/api/projects",- base_url="https://alex.avibe.bot",- headers=headers,- json={},- )-- assert read_response.status_code == 200- 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- 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 "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 == 400- assert project_response.status_code == 400---def _forged_session_cookie(config: V2Config, exp: int, *, email: str = "[email protected]", subject: str = "user-1") -> str:- import json- import urllib.parse-- cloud = config.remote_access.vibe_cloud- payload = {- "email": email,- "sub": subject,- "instance_id": cloud.instance_id,- "vibe_instance_id": cloud.instance_id,- "vibe_instance_role": "owner",- "vibe_instance_access_source": "owner",- "iat": exp - remote_access.SESSION_TTL_SECONDS,- "exp": exp,- "claims_issued_at": exp - remote_access.SESSION_TTL_SECONDS,- }- payload_text = urllib.parse.quote(json.dumps(payload, separators=(",", ":")), safe="")- signature = remote_access._session_signature(cloud.session_secret, payload_text)- return f"{payload_text}.{signature}"---def test_remote_api_get_with_expired_session_returns_login_required(monkeypatch, tmp_path):- import time as _time-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- _forged_session_cookie(config, int(_time.time()) - 60),- domain="alex.avibe.bot",- )-- response = client.get(- "/api/config",- base_url="https://alex.avibe.bot",- follow_redirects=False,- )-- assert response.status_code == 401- assert response.get_json()["error"] == "remote_access_login_required"- assert response.headers.get("Location") is None---def test_remote_session_probe_reports_unauthenticated_when_authorization_refresh_required(monkeypatch, tmp_path):- import time as _time-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- near_exp = int(_time.time()) + (remote_access.SESSION_TTL_SECONDS // 2) - 60- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- _forged_session_cookie(config, near_exp),- 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": False,- "authorization_refresh_required": True,- }---def test_cloud_token_requires_authorization_refresh_before_mint(monkeypatch, tmp_path):- import time as _time-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- near_exp = int(_time.time()) + (remote_access.SESSION_TTL_SECONDS // 2) - 60- mint_called = False-- def fake_mint(*args, **kwargs):- nonlocal mint_called- mint_called = True- return {"access_token": "must-not-mint", "expires_in": 60}-- monkeypatch.setattr(remote_access, "mint_cloud_token", fake_mint)- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- _forged_session_cookie(config, near_exp),- domain="alex.avibe.bot",- )-- response = client.get("/api/cloud/token", base_url="https://alex.avibe.bot")-- assert response.status_code == 401- assert response.get_json()["error"] == "remote_access_authorization_refresh_required"- assert mint_called is False---def test_remote_host_does_not_renew_fresh_cookie(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- _mock_ui_dist(monkeypatch, 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)-- set_cookie_headers = response.headers.getlist("Set-Cookie")- assert not any(h.startswith(f"{remote_access.SESSION_COOKIE_NAME}=") for h in set_cookie_headers)---def test_remote_page_refreshes_authorization_past_half_ttl(monkeypatch, tmp_path):- import time as _time-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- _mock_ui_dist(monkeypatch, tmp_path)- near_exp = int(_time.time()) + (remote_access.SESSION_TTL_SECONDS // 2) - 60- cookie = _forged_session_cookie(config, near_exp)- client = app.test_client()- client.set_cookie(remote_access.SESSION_COOKIE_NAME, cookie, domain="alex.avibe.bot")-- response = client.get("/dashboard", base_url="https://alex.avibe.bot", follow_redirects=False)-- assert response.status_code == 302- assert response.headers["Location"].startswith(config.remote_access.vibe_cloud.authorization_endpoint)- assert not any(- header.startswith(f"{remote_access.SESSION_COOKIE_NAME}=")- for header in response.headers.getlist("Set-Cookie")- )---def test_remote_api_requests_signal_authorization_refresh(monkeypatch, tmp_path):- import time as _time-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- near_exp = int(_time.time()) + (remote_access.SESSION_TTL_SECONDS // 2) - 60- cookie = _forged_session_cookie(config, near_exp)- client = app.test_client()- client.set_cookie(remote_access.SESSION_COOKIE_NAME, cookie, domain="alex.avibe.bot")-- response = client.post(- "/api/config",- json={"remote_access": {"vibe_cloud": {"enabled": False}}},- base_url="https://alex.avibe.bot",- )-- assert response.status_code == 401- assert response.get_json()["error"] == "remote_access_authorization_refresh_required"- refreshed = next(- (h for h in response.headers.getlist("Set-Cookie") if h.startswith(f"{remote_access.SESSION_COOKIE_NAME}=")),- None,- )- assert refreshed is None---def test_remote_api_get_requires_top_level_authorization_refresh(monkeypatch, tmp_path):- import time as _time-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- near_exp = int(_time.time()) + (remote_access.SESSION_TTL_SECONDS // 2) - 60- cookie = _forged_session_cookie(config, near_exp)- client = app.test_client()- client.set_cookie(remote_access.SESSION_COOKIE_NAME, cookie, domain="alex.avibe.bot")-- response = client.get(- "/api/config",- base_url="https://alex.avibe.bot",- follow_redirects=False,- )-- assert response.status_code == 401- assert response.get_json()["error"] == "remote_access_authorization_refresh_required"- assert response.headers.get("Location") is None---def test_remote_host_fails_closed_when_config_load_fails(monkeypatch):- def fail_load():- raise ValueError("corrupt config")-- monkeypatch.setattr(ui_server.V2Config, "load", fail_load)-- response = app.test_client().get(- "/dashboard",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_config_unavailable"---def test_host_starting_with_127_but_not_ip_is_not_local_when_config_load_fails(monkeypatch):- def fail_load():- raise ValueError("corrupt config")-- monkeypatch.setattr(ui_server.V2Config, "load", fail_load)-- response = app.test_client().get(- "/dashboard",- base_url="https://127.attacker.example",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_config_unavailable"---def test_loopback_peer_with_arbitrary_host_is_not_local_when_config_load_fails(monkeypatch):- def fail_load():- raise ValueError("corrupt config")-- monkeypatch.setattr(ui_server.V2Config, "load", fail_load)-- response = app.test_client().get(- "/dashboard",- base_url="https://attacker.example",- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_config_unavailable"---def test_spoofed_loopback_host_is_not_local_when_peer_is_remote(monkeypatch):- def fail_load():- raise ValueError("corrupt config")-- monkeypatch.setattr(ui_server.V2Config, "load", fail_load)-- response = app.test_client().get(- "/dashboard",- base_url="https://127.0.0.1",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_config_unavailable"---def test_cloudflare_forwarded_request_with_loopback_host_fails_closed(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)-- response = app.test_client().get(- "/dashboard",- base_url="https://127.0.0.1",- headers=_cloudflare_headers(),- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_trusted_proxy_forwarded_host_routes_remote_access(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")- _save_config(tmp_path)- _mock_ui_dist(monkeypatch, tmp_path)-- response = app.test_client().get(- "/dashboard",- base_url="http://127.0.0.1:5123",- headers={- "X-Forwarded-Proto": "https",- "X-Forwarded-Host": "alex.avibe.bot",- "X-Forwarded-For": "203.0.113.10",- },- environ_base={"REMOTE_ADDR": "127.0.0.1"},- follow_redirects=False,- )-- assert response.status_code == 200- assert response.headers.get("Location") is None---def test_ra_tq_026_remote_status_uses_cf_ray_on_paired_public_host(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- observed = []-- def status(- loaded_config=None,- *,- client_colo=None,- client_access="local",- include_network_path=False,- ):- observed.append((loaded_config, client_colo, client_access, include_network_path))- return {"ok": True, "client_colo": client_colo}-- monkeypatch.setattr(remote_access, "status", status)- with app.test_request_context(- "/api/remote-access/status",- base_url="https://alex.avibe.bot",- headers={"CF-Ray": "9f1234567890abcd-SIN"},- ):- response = ui_server.remote_access_status()-- assert response.status_code == 200- assert observed[0][0].remote_access.vibe_cloud.public_url == config.remote_access.vibe_cloud.public_url- assert observed[0][1] == "SIN"- assert observed[0][2] == "remote"- assert observed[0][3] is True---def test_ra_tq_026_remote_status_ignores_spoofed_cf_ray(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- observed = []-- def status(- loaded_config=None,- *,- client_colo=None,- client_access="local",- include_network_path=False,- ):- observed.append((loaded_config, client_colo, client_access, include_network_path))- return {"ok": True, "client_colo": client_colo}-- monkeypatch.setattr(remote_access, "status", status)- with app.test_request_context(- "/api/remote-access/status",- base_url="http://127.0.0.1:5123",- headers={"CF-Ray": "9f1234567890abcd-NRT"},- ):- response = ui_server.remote_access_status()-- assert response.status_code == 200- assert observed[0][1] is None- assert observed[0][2] == "local"- assert observed[0][3] is True- assert config.remote_access.vibe_cloud.public_url == "https://alex.avibe.bot"---def test_remote_status_projects_a_remote_safe_payload(monkeypatch, tmp_path):- """A remote caller gets only the connector state the UI shows, not host internals.-- The raw ``remote_access.status()`` payload includes the cloudflared PID, the- absolute binary path/version, the edge bind-address settings and the- network-path diagnostics. None of that is needed across the tunnel and the- host-internal fields fingerprint the machine, so the allowlisted status- endpoint projects only the public URL, paired/running state, transport- protocol and tunnel quality when the request is remote. A local caller still- receives the full payload.- """-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)-- full_payload = {- "ok": True,- "provider": "vibe_cloud",- "enabled": True,- "public_url": "https://alex.avibe.bot",- "paired": True,- "running": True,- "pid": 4711,- "pid_state": "cloudflared",- "binary_found": True,- "binary_path": "/usr/local/bin/cloudflared",- "binary_version": "2024.1.0",- "transport_protocol": "http2",- "settings": {- "transport_protocol": "http2",- "auto_recovery": True,- "optimization_profile": "balanced",- "edge_ip_version": "4",- "edge_bind_address": "192.168.1.5",- },- "tunnel_quality": {"sampled_at": "2026-08-10T10:00:00Z", "grade": "good"},- "network_path": {"provider": "Cloudflare", "asn": 13335},- }- monkeypatch.setattr(remote_access, "status", lambda *a, **k: dict(full_payload))-- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- _org_session_cookie(- config,- "[email protected]",- "user-owner",- role="owner",- organization_role="owner",- ),- domain="alex.avibe.bot",- )-- def _status(base_url, environ):- return client.get(- "/api/remote-access/status",- base_url=base_url,- environ_base=environ,- )-- remote_response = _status("https://alex.avibe.bot", _remote_peer())- local_response = _status("http://127.0.0.1:5123", {"REMOTE_ADDR": "127.0.0.1"})-- assert remote_response.status_code == 200- remote_body = remote_response.get_json()- assert set(remote_body) == {- "ok",- "provider",- "enabled",- "public_url",- "paired",- "running",- "transport_protocol",- "tunnel_quality",- }- # The host-internal and diagnostic fields never cross the tunnel.- for sensitive in (- "pid",- "pid_state",- "binary_found",- "binary_path",- "binary_version",- "settings",- "network_path",- ):- assert sensitive not in remote_body- assert remote_body["public_url"] == config.remote_access.vibe_cloud.public_url- assert remote_body["running"] is True-- # A local caller keeps the full payload, including the host internals.- assert local_response.status_code == 200- assert local_response.get_json() == full_payload---def test_trusted_proxy_missing_forwarded_host_fails_closed(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")- _save_config(tmp_path)-- response = app.test_client().get(- "/dashboard",- base_url="http://127.0.0.1:5123",- headers={- "X-Forwarded-Proto": "https",- "X-Forwarded-For": "8.8.8.8",- },- environ_base={"REMOTE_ADDR": "127.0.0.1"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_trusted_proxy_unmatched_forwarded_host_fails_closed(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")- _save_config(tmp_path)-- response = app.test_client().get(- "/dashboard",- base_url="http://127.0.0.1:5123",- headers={- "X-Forwarded-Proto": "https",- "X-Forwarded-Host": "evil.example",- "X-Forwarded-For": "8.8.8.8",- },- environ_base={"REMOTE_ADDR": "127.0.0.1"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_trusted_proxy_malformed_forwarded_host_fails_closed(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")- _save_config(tmp_path)-- response = app.test_client().get(- "/dashboard",- base_url="http://127.0.0.1:5123",- headers={- "X-Forwarded-Proto": "https",- "X-Forwarded-Host": "[bad",- "X-Forwarded-For": "8.8.8.8",- },- environ_base={"REMOTE_ADDR": "127.0.0.1"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_remote_host_fails_closed_when_disabled_but_hostname_still_matches(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- config.remote_access.vibe_cloud.enabled = False- config.save()-- response = app.test_client().get(- "/dashboard",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_disabled"---def test_unmatched_non_local_host_fails_closed_when_remote_access_disabled(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- config.remote_access.vibe_cloud.enabled = False- config.save()-- response = app.test_client().get(- "/dashboard",- base_url="https://old-alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_remote_host_fails_closed_when_public_url_is_invalid(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- config.remote_access.vibe_cloud.public_url = "alex.avibe.bot"- config.save()-- response = app.test_client().get(- "/dashboard",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_public_url_invalid"---def test_remote_host_fails_closed_when_public_url_is_http(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- config.remote_access.vibe_cloud.public_url = "http://alex.avibe.bot"- config.save()-- response = app.test_client().get(- "/dashboard",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_public_url_invalid"---def test_remote_host_fails_closed_when_public_url_contains_userinfo(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- config.remote_access.vibe_cloud.public_url = "https://user:[email protected]"- config.save()-- response = app.test_client().get(- "/dashboard",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_public_url_invalid"---def test_remote_host_fails_closed_when_public_url_is_empty(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- config.remote_access.vibe_cloud.public_url = ""- config.save()-- response = app.test_client().get(- "/dashboard",- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_public_url_invalid"---def test_remote_host_fails_closed_when_session_secret_is_empty(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- config.remote_access.vibe_cloud.session_secret = ""- config.save()-- response = app.test_client().get("/dashboard", base_url="https://alex.avibe.bot", follow_redirects=False)-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_session_secret_missing"---def test_config_post_rotates_session_secret_when_remote_access_is_disabled(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- old_secret = config.remote_access.vibe_cloud.session_secret- client = app.test_client()-- monkeypatch.setattr(remote_access, "reconcile", lambda: {"ok": True, "stopped": True})-- response = client.post(- "/api/config",- json={"remote_access": {"vibe_cloud": {"enabled": False}}},- headers=csrf_headers(client, "http://127.0.0.1:5123"),- base_url="http://127.0.0.1:5123",- )- saved = V2Config.load()-- assert response.status_code == 200- assert saved.remote_access.vibe_cloud.enabled is False- assert saved.remote_access.vibe_cloud.session_secret- assert saved.remote_access.vibe_cloud.session_secret != old_secret---def test_config_post_skips_reconcile_when_remote_access_is_unchanged(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()- reconcile_calls = []-- monkeypatch.setattr(remote_access, "reconcile", lambda: reconcile_calls.append(True) or {"ok": True})-- response = client.post(- "/api/config",- json=api.config_to_payload(config),- headers=csrf_headers(client, "http://127.0.0.1:5123"),- base_url="http://127.0.0.1:5123",- )-- assert response.status_code == 200- assert reconcile_calls == []---def test_remote_config_post_accepts_public_origin_default_https_port(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- config.remote_access.vibe_cloud.public_url = "https://alex.avibe.bot:443"- config.save()- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- _org_session_cookie(config, "[email protected]", "user-1"),- domain="alex.avibe.bot",- )- headers = csrf_headers(client, "https://alex.avibe.bot")-- response = client.post(- "/api/config",- json=api.config_to_payload(config),- headers=headers,- base_url="https://alex.avibe.bot",- environ_base=_remote_peer(),- )-- assert response.status_code == 200---def test_custom_hostname_config_post_accepts_same_origin(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- remote_access._replace_active_hostnames(config, ["max.fileguard.io"])- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- _org_session_cookie(config, "[email protected]", "user-1"),- domain="max.fileguard.io",- )- headers = csrf_headers(client, "https://max.fileguard.io")-- response = client.post(- "/api/config",- json=api.config_to_payload(config),- headers=headers,- base_url="https://max.fileguard.io",- environ_base=_remote_peer(),- )-- assert response.status_code == 200---def test_config_post_returns_saved_config_when_remote_reconcile_fails(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- old_secret = config.remote_access.vibe_cloud.session_secret- client = app.test_client()-- monkeypatch.setattr(remote_access, "reconcile", lambda: {"ok": False, "error": "cloudflared_stop_failed"})-- response = client.post(- "/api/config",- json={"remote_access": {"vibe_cloud": {"enabled": False}}},- headers=csrf_headers(client, "http://127.0.0.1:5123"),- base_url="http://127.0.0.1:5123",- )- saved = V2Config.load()- body = response.get_json()-- assert response.status_code == 200- assert body["remote_access_runtime"]["ok"] is False- assert body["remote_access_runtime"]["error"] == "cloudflared_stop_failed"- assert saved.remote_access.vibe_cloud.enabled is False- assert saved.remote_access.vibe_cloud.session_secret != old_secret---def test_config_post_reconciles_after_releasing_config_lock(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- client = app.test_client()- lock_states = []-- def reconcile():- lock_states.append(CONFIG_LOCK._is_owned())- return {"ok": True, "stopped": True}-- monkeypatch.setattr(remote_access, "reconcile", reconcile)-- response = client.post(- "/api/config",- json={"remote_access": {"vibe_cloud": {"enabled": False}}},- headers=csrf_headers(client, "http://127.0.0.1:5123"),- base_url="http://127.0.0.1:5123",- )-- assert response.status_code == 200- assert lock_states == [False]---def test_config_post_reconciles_from_fresh_config(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- client = app.test_client()- reconcile_args = []-- def reconcile(*args):- reconcile_args.append(args)- return {"ok": True, "stopped": True}-- monkeypatch.setattr(remote_access, "reconcile", reconcile)-- response = client.post(- "/api/config",- json={"remote_access": {"vibe_cloud": {"enabled": False}}},- headers=csrf_headers(client, "http://127.0.0.1:5123"),- base_url="http://127.0.0.1:5123",- )-- assert response.status_code == 200- assert reconcile_args == [()]---def test_remote_callback_rejects_nonce_mismatch(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()-- with app.test_request_context("/dashboard", base_url="https://alex.avibe.bot"):- redirect = ui_server._redirect_to_vibe_cloud_login(config)- oauth_cookie = redirect.headers["Set-Cookie"].split(";", 1)[0].split("=", 1)[1]- client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="alex.avibe.bot")-- monkeypatch.setattr(- remote_access,- "exchange_oauth_code",- lambda cfg, code, verifier, redirect_uri=None: _oauth_exchange_result(- cfg,- nonce="wrong-nonce",- ),- )-- state = ui_server._read_oauth_cookie(config.remote_access.vibe_cloud.session_secret, oauth_cookie)["state"]- response = client.get(f"/auth/callback?code=test-code&state={state}", base_url="https://alex.avibe.bot")-- assert response.status_code == 400- assert "text/html" in response.headers["Content-Type"]- assert "invalid_oauth_nonce" in response.text- assert "Sign in again" in response.text- # Re-login button points back at the original destination from the handshake.- assert 'href="/dashboard"' in response.text--- ("access_source", "instance_role"),- [("show_page_email", "viewer"), ("email", "editor")],-)-def test_remote_callback_rejects_signed_entitlement_for_a_different_page(- monkeypatch, tmp_path, access_source, instance_role-):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()-- with app.test_request_context(- "/show/session-one/",- base_url="https://alex.avibe.bot",- ):- redirect = ui_server._redirect_to_vibe_cloud_login(config)- oauth_cookie = redirect.headers["Set-Cookie"].split(";", 1)[0].split("=", 1)[1]- client.set_cookie(- ui_server.REMOTE_OAUTH_COOKIE_NAME,- oauth_cookie,- domain="alex.avibe.bot",- )- oauth_state = ui_server._read_oauth_cookie(- config.remote_access.vibe_cloud.session_secret,- oauth_cookie,- )-- monkeypatch.setattr(- remote_access,- "exchange_oauth_code",- lambda cfg, code, verifier, redirect_uri=None: {- "claims": {- "email": "[email protected]",- "sub": "guest-1",- "nonce": oauth_state["nonce"],- },- "session_claims": {- "vibe_instance_id": "inst_123",- "vibe_instance_role": instance_role,- "vibe_instance_access_source": access_source,- "vibe_show_page_id": "session-two",- },- },- )-- response = client.get(- f"/auth/callback?code=test-code&state={oauth_state['state']}",- base_url="https://alex.avibe.bot",- )-- assert response.status_code == 400- assert "invalid_show_page_id" in response.text- assert 'href="/show/session-one/"' in response.text- assert not any(- header.startswith(f"{remote_access.SESSION_COOKIE_NAME}=")- for header in response.headers.getlist("Set-Cookie")- )---def test_remote_callback_externalizes_large_organization_claims(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()-- with app.test_request_context("/dashboard", base_url="https://alex.avibe.bot"):- redirect = ui_server._redirect_to_vibe_cloud_login(config)- oauth_cookie = redirect.headers["Set-Cookie"].split(";", 1)[0].split("=", 1)[1]- client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="alex.avibe.bot")- oauth_state = ui_server._read_oauth_cookie(config.remote_access.vibe_cloud.session_secret, oauth_cookie)- group_ids = [f"00000000-0000-4000-8000-{index:012d}" for index in range(100)]-- monkeypatch.setattr(- remote_access,- "exchange_oauth_code",- lambda cfg, code, verifier, redirect_uri=None: {- "claims": {- "email": "[email protected]",- "sub": "user-1",- "nonce": oauth_state["nonce"],- },- "session_claims": {- "vibe_instance_id": "inst_123",- "vibe_instance_role": "viewer",- "vibe_instance_access_source": "organization_group",- "vibe_organization_id": "org-1",- "vibe_organization_member_id": "member-1",- "vibe_organization_role": "member",- "vibe_group_ids": group_ids,- },- },- )-- response = client.get(- f"/auth/callback?code=test-code&state={oauth_state['state']}",- base_url="https://alex.avibe.bot",- )-- assert response.status_code == 302- assert response.headers["Location"] == "/dashboard"- session_header = next(- header- for header in response.headers.getlist("Set-Cookie")- if header.startswith(f"{remote_access.SESSION_COOKIE_NAME}=")- )- session_cookie = session_header.split(";", 1)[0].split("=", 1)[1]- assert len(session_cookie.encode("ascii")) <= remote_access.SESSION_COOKIE_MAX_VALUE_BYTES- payload = remote_access.parse_session_cookie(config, session_cookie)- assert payload is not None- assert payload["vibe_group_ids"] == group_ids---def test_remote_callback_explains_pairing_mismatch(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()-- with app.test_request_context("/dashboard", base_url="https://alex.avibe.bot"):- redirect = ui_server._redirect_to_vibe_cloud_login(config)- oauth_cookie = redirect.headers["Set-Cookie"].split(";", 1)[0].split("=", 1)[1]- client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="alex.avibe.bot")-- def exchange(cfg, code, verifier, redirect_uri=None):- raise remote_access.OAuthCodeExchangeError("invalid_instance_id")-- monkeypatch.setattr(remote_access, "exchange_oauth_code", exchange)-- state = ui_server._read_oauth_cookie(config.remote_access.vibe_cloud.session_secret, oauth_cookie)["state"]- response = client.get(f"/auth/callback?code=test-code&state={state}", base_url="https://alex.avibe.bot")-- assert response.status_code == 400- assert "text/html" in response.headers["Content-Type"]- assert "remote_pairing_mismatch" in response.text- assert "Reconnect this Avibe" in response.text- assert "pair Remote Access again" in response.text- assert "Technical details" in response.text- assert "reason: invalid_instance_id" in response.text- assert "error: remote_pairing_mismatch" in response.text---def test_remote_callback_explains_clock_mismatch(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()-- with app.test_request_context("/dashboard", base_url="https://alex.avibe.bot"):- redirect = ui_server._redirect_to_vibe_cloud_login(config)- oauth_cookie = redirect.headers["Set-Cookie"].split(";", 1)[0].split("=", 1)[1]- client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="alex.avibe.bot")-- def exchange(cfg, code, verifier, redirect_uri=None):- raise remote_access.OAuthCodeExchangeError("expired_id_token")-- monkeypatch.setattr(remote_access, "exchange_oauth_code", exchange)-- state = ui_server._read_oauth_cookie(config.remote_access.vibe_cloud.session_secret, oauth_cookie)["state"]- response = client.get(f"/auth/callback?code=test-code&state={state}", base_url="https://alex.avibe.bot")-- assert response.status_code == 400- assert "oauth_time_mismatch" in response.text- assert "Check this machine's clock" in response.text- assert "reason: expired_id_token" in response.text---def test_remote_callback_redacts_quoted_oauth_details(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()-- with app.test_request_context("/dashboard", base_url="https://alex.avibe.bot"):- redirect = ui_server._redirect_to_vibe_cloud_login(config)- oauth_cookie = redirect.headers["Set-Cookie"].split(";", 1)[0].split("=", 1)[1]- client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="alex.avibe.bot")-- def exchange(cfg, code, verifier, redirect_uri=None):- raise remote_access.OAuthCodeExchangeError(- "token_endpoint_rejected",- '{"code":"secret-code","code_verifier":"secret-verifier","detail":"bad code"}',- )-- monkeypatch.setattr(remote_access, "exchange_oauth_code", exchange)-- state = ui_server._read_oauth_cookie(config.remote_access.vibe_cloud.session_secret, oauth_cookie)["state"]- response = client.get(f"/auth/callback?code=test-code&state={state}", base_url="https://alex.avibe.bot")-- assert response.status_code == 400- assert "detail:" in response.text- assert "code=<redacted>" in response.text- assert "code_verifier=<redacted>" in response.text- assert "secret-code" not in response.text- assert "secret-verifier" not in response.text- assert "test-code" not in response.text---def test_remote_callback_log_omits_raw_oauth_rejection_detail(monkeypatch, tmp_path, caplog):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()-- with app.test_request_context("/dashboard", base_url="https://alex.avibe.bot"):- redirect = ui_server._redirect_to_vibe_cloud_login(config)- oauth_cookie = redirect.headers["Set-Cookie"].split(";", 1)[0].split("=", 1)[1]- client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="alex.avibe.bot")-- def exchange(cfg, code, verifier, redirect_uri=None):- raise remote_access.OAuthCodeExchangeError("token_endpoint_rejected", '{"code":"secret-code"}')-- monkeypatch.setattr(remote_access, "exchange_oauth_code", exchange)- with ui_server._oauth_diag_log_lock:- ui_server._oauth_diag_log_state.pop("exchange_failed", None)- caplog.set_level(logging.WARNING, logger="vibe.ui_server")-- state = ui_server._read_oauth_cookie(config.remote_access.vibe_cloud.session_secret, oauth_cookie)["state"]- response = client.get(f"/auth/callback?code=test-code&state={state}", base_url="https://alex.avibe.bot")-- assert response.status_code == 400- messages = "\n".join(record.getMessage() for record in caplog.records)- assert "reason=token_endpoint_rejected" in messages- assert "secret-code" not in messages- assert "test-code" not in messages---def test_remote_callback_rejects_when_remote_access_is_disabled(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()- oauth_cookie = ui_server._make_oauth_cookie(- config.remote_access.vibe_cloud.session_secret,- {- "state": "state-1",- "nonce": "nonce-1",- "code_verifier": "verifier-1",- "next": "/dashboard",- "exp": int(ui_server.datetime.now().timestamp()) + 300,- },- )- config.remote_access.vibe_cloud.enabled = False- config.save()- exchange_calls = []- client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="alex.avibe.bot")-- monkeypatch.setattr(- remote_access,- "exchange_oauth_code",- lambda *args, **kwargs: exchange_calls.append(args) or {"claims": {"nonce": "nonce-1"}},- )-- response = client.get("/auth/callback?code=test-code&state=state-1", base_url="https://alex.avibe.bot")-- assert response.status_code == 400- assert response.get_json()["error"] == "remote_access_disabled"- assert exchange_calls == []---def test_remote_callback_restarts_oauth_when_state_cookie_was_lost(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()- state = ui_server._make_oauth_state(- config.remote_access.vibe_cloud.session_secret,- next_target="/show/ses123/?tab=flow",- )- exchange_calls = []- monkeypatch.setattr(remote_access, "exchange_oauth_code", lambda *args, **kwargs: exchange_calls.append(args))-- response = client.get(- f"/auth/callback?code=test-code&state={state}",- base_url="https://alex.avibe.bot",- follow_redirects=False,- )-- assert response.status_code == 302- assert response.headers["Location"] == f"/show/ses123/?tab=flow&{ui_server.REMOTE_OAUTH_RETRY_PARAM}=1"- assert ui_server.REMOTE_OAUTH_COOKIE_NAME in response.headers["Set-Cookie"]- assert exchange_calls == []---def test_remote_callback_does_not_restart_oauth_twice(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()- state = ui_server._make_oauth_state(- config.remote_access.vibe_cloud.session_secret,- next_target="/show/ses123/",- retry=True,- )-- response = client.get(f"/auth/callback?code=test-code&state={state}", base_url="https://alex.avibe.bot")-- # Auto-retry already spent: render the friendly re-login page, not raw JSON.- assert response.status_code == 400- assert "text/html" in response.headers["Content-Type"]- assert "invalid_oauth_state" in response.text- assert "Sign in again" in response.text- # Retry recovers the original destination from the signed state param.- assert 'href="/show/ses123/"' in response.text---def test_remote_callback_renders_relogin_page_for_legacy_state(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- client = app.test_client()-- response = client.get("/auth/callback?code=test-code&state=state-1", base_url="https://alex.avibe.bot")-- # Undecodable state has no recoverable destination, so the retry button- # falls back to the home page.- assert response.status_code == 400- assert "text/html" in response.headers["Content-Type"]- assert "invalid_oauth_state" in response.text- assert "Sign in again" in response.text- assert 'href="/"' in response.text---def test_remote_callback_diagnostics_do_not_expose_oauth_parameters(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- client = app.test_client()-- response = client.get(- "/auth/callback?code=secret-code&state=secret-state",- base_url="https://alex.avibe.bot",- )-- assert response.status_code == 400- assert "invalid_oauth_state" in response.text- assert "Technical details" in response.text- assert "error: invalid_oauth_state" in response.text- assert "host: alex.avibe.bot" in response.text- assert "secret-code" not in response.text- assert "secret-state" not in response.text---def test_remote_callback_recovers_via_store_when_cookie_state_desyncs(monkeypatch, tmp_path):- # iOS standalone PWA: the handshake cookie carries a *different* (but valid)- # state than the one the user approved, because the cross-origin authorize step- # runs in a separate in-app-browser context. The callback must still complete by- # recovering the PKCE secrets from the server-side store, keyed by the signed URL- # state. Regression guard for the deterministic PWA invalid_oauth_state dead-end.- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- secret = config.remote_access.vibe_cloud.session_secret- client = app.test_client()-- # The flow the user actually approved: a signed state plus its server-side record,- # bound to this browser's stable device id.- rid = "approvedrid000"- device_id = "device-abc-123"- state_url = ui_server._make_oauth_state(secret, next_target="/dashboard", rid=rid)- remote_access.store_oauth_handshake(- rid,- nonce="nonce-approved",- code_verifier="verifier-approved",- next_target="/dashboard",- device_hash=ui_server._oauth_device_hash(secret, device_id),- redirect_uri="https://alex.avibe.bot/auth/callback",- )-- # A stale-but-valid cookie from a *different* GET / generation (different state).- stale_cookie = ui_server._make_oauth_cookie(- secret,- {- "state": ui_server._make_oauth_state(secret, next_target="/", rid="stalerid0000"),- "nonce": "nonce-stale",- "code_verifier": "verifier-stale",- "next": "/",- "exp": int(ui_server.datetime.now().timestamp()) + 300,- },- )- client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, stale_cookie, domain="alex.avibe.bot")- # The device cookie is stable across the excursion and matches the record's bind.- client.set_cookie(ui_server.REMOTE_OAUTH_DEVICE_COOKIE_NAME, device_id, domain="alex.avibe.bot")-- captured = {}-- def exchange(cfg, code, verifier, redirect_uri=None):- captured["verifier"] = verifier- captured["redirect_uri"] = redirect_uri- return _oauth_exchange_result(cfg, nonce="nonce-approved")-- monkeypatch.setattr(remote_access, "exchange_oauth_code", exchange)-- response = client.get(- f"/auth/callback?code=test-code&state={state_url}",- base_url="https://alex.avibe.bot",- follow_redirects=False,- )-- assert response.status_code == 302- assert response.headers["Location"] == "/dashboard"- # Used the server-side record's verifier, not the stale cookie's.- assert captured["verifier"] == "verifier-approved"- assert captured["redirect_uri"] == "https://alex.avibe.bot/auth/callback"- # Handshake is single-use: consumed by the callback.- assert remote_access.pop_oauth_handshake(rid) is None---def test_oauth_handshake_store_is_single_use_and_expires(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)-- remote_access.store_oauth_handshake("rid-abc", nonce="n", code_verifier="v", next_target="/x")- first = remote_access.pop_oauth_handshake("rid-abc")- assert first is not None- assert first["code_verifier"] == "v"- assert first["next"] == "/x"- # Single-use: a second pop finds nothing.- assert remote_access.pop_oauth_handshake("rid-abc") is None-- # An expired record is treated as absent.- remote_access.store_oauth_handshake("rid-exp", nonce="n", code_verifier="v", next_target="/x")- remote_access._oauth_handshakes["rid-exp"]["exp"] = 0- assert remote_access.pop_oauth_handshake("rid-exp") is None-- # Invalid ids are rejected, never touching the filesystem.- assert remote_access.pop_oauth_handshake("bad/rid") is None- assert remote_access.pop_oauth_handshake(None) is None---def test_oauth_handshake_store_caps_entries(monkeypatch, tmp_path):- # The store is written on every unauthenticated redirect; a hard cap prevents- # unbounded inode growth under a burst. At capacity, new writes are shed and- # existing in-flight entries are preserved.- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- monkeypatch.setattr(remote_access, "OAUTH_HANDSHAKE_MAX_ENTRIES", 3)-- for i in range(3):- remote_access.store_oauth_handshake(f"rid-{i}", nonce="n", code_verifier="v", next_target="/")- remote_access.store_oauth_handshake("rid-overflow", nonce="n", code_verifier="v", next_target="/")-- assert remote_access.pop_oauth_handshake("rid-overflow") is None- assert remote_access.pop_oauth_handshake("rid-0") is not None---def test_oauth_handshake_cap_holds_under_concurrency(monkeypatch, tmp_path):- # Atomic admission: a concurrent burst must not blow past the cap. Without the- # lock, many threads could pass the count check before any writes.- import threading-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- monkeypatch.setattr(remote_access, "OAUTH_HANDSHAKE_MAX_ENTRIES", 5)-- barrier = threading.Barrier(20)-- def worker(i):- try:- barrier.wait(timeout=5)- except threading.BrokenBarrierError:- pass- remote_access.store_oauth_handshake(f"rid-{i:03d}", nonce="n", code_verifier="v", next_target="/")-- threads = [threading.Thread(target=worker, args=(i,)) for i in range(20)]- for t in threads:- t.start()- for t in threads:- t.join()-- assert len(remote_access._oauth_handshakes) <= 5---def test_unauthenticated_auth_requests_are_rate_limited(monkeypatch, tmp_path):- # A flood of explicit login-start requests from one client is 429'd, instead- # of each one doing handshake/cookie/log work.- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- monkeypatch.setattr(ui_server, "_AUTH_RATELIMIT_MAX_PER_WINDOW", 3)- client = app.test_client()-- statuses = [- client.get(- "/auth/login?next=/dashboard",- base_url="https://alex.avibe.bot",- environ_base={"REMOTE_ADDR": "203.0.113.77"},- follow_redirects=False,- ).status_code- for _ in range(5)- ]- assert statuses[:3] == [302, 302, 302] # within budget -> redirect to OAuth- assert statuses[3:] == [429, 429] # over budget -> throttled---def test_auth_rate_limit_ignores_untrusted_forwarded_ip(monkeypatch, tmp_path):- # A direct (non-loopback) peer can't dodge the limit by rotating CF-Connecting-IP:- # the forwarded IP is trusted only from the loopback tunnel peer, so such a peer- # is keyed by its real address and the rotating header is ignored.- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- monkeypatch.setattr(ui_server, "_AUTH_RATELIMIT_MAX_PER_WINDOW", 3)- client = app.test_client()-- statuses = [- client.get(- "/auth/login?next=/dashboard",- base_url="https://alex.avibe.bot",- environ_base={"REMOTE_ADDR": "203.0.113.90"},- headers={"CF-Connecting-IP": f"9.9.9.{i}"}, # rotated each request- follow_redirects=False,- ).status_code- for i in range(5)- ]- assert statuses[:3] == [302, 302, 302]- assert statuses[3:] == [429, 429] # still limited despite the rotating header---def test_auth_rate_limit_keys_trusted_proxy_by_forwarded_client(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")- _save_config(tmp_path)- monkeypatch.setattr(ui_server, "_AUTH_RATELIMIT_MAX_PER_WINDOW", 3)- with ui_server._auth_ratelimit_lock:- ui_server._auth_ratelimit.clear()- client = app.test_client()-- def get_status(client_ip: str) -> int:- return client.get(- "/auth/login?next=/dashboard",- base_url="http://127.0.0.1:5123",- environ_base={"REMOTE_ADDR": "127.0.0.1"},- headers={- "X-Forwarded-Proto": "https",- "X-Forwarded-Host": "alex.avibe.bot",- "X-Forwarded-For": client_ip,- },- follow_redirects=False,- ).status_code-- first_client = [get_status("203.0.113.10") for _ in range(3)]- second_client = [get_status("203.0.113.11") for _ in range(3)]- first_client_over_budget = get_status("203.0.113.10")-- assert first_client == [302, 302, 302]- assert second_client == [302, 302, 302]- assert first_client_over_budget == 429---def test_auth_rate_limit_table_is_bounded(monkeypatch, tmp_path):- # The limiter's own table is hard-capped (LRU eviction), so a burst of distinct- # clients can't drive unbounded in-process memory growth.- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- monkeypatch.setattr(ui_server, "_AUTH_RATELIMIT_MAX_TRACKED_CLIENTS", 3)- client = app.test_client()-- for i in range(10): # 10 distinct peers- client.get(- "/auth/login?next=/dashboard",- base_url="https://alex.avibe.bot",- environ_base={"REMOTE_ADDR": f"198.51.100.{i}"},- follow_redirects=False,- )- assert len(ui_server._auth_ratelimit) <= 3---def test_oauth_diag_log_is_rate_limited(monkeypatch):- # The unauthenticated callback failure path must not grow the log without bound:- # repeated hits within the window emit once, with the suppressed count folded in.- clock = {"t": 1000.0}- monkeypatch.setattr(ui_server.time, "monotonic", lambda: clock["t"])- ui_server._oauth_diag_log_state.pop("test_key", None)-- emitted = []- monkeypatch.setattr(ui_server.logger, "warning", lambda msg, *a: emitted.append(msg % a if a else msg))-- for _ in range(5):- ui_server._log_oauth_diag("test_key", "boom x=%s", 1)- assert len(emitted) == 1 # only the first hit in the window is logged-- clock["t"] += ui_server._OAUTH_DIAG_LOG_INTERVAL_SECONDS + 1- ui_server._log_oauth_diag("test_key", "boom x=%s", 1)- assert len(emitted) == 2- assert "suppressed" in emitted[1] # the 4 suppressed hits are reported---def test_oauth_error_page_localizes_from_accept_language(monkeypatch, tmp_path):- # The re-login page copy must come from vibe/i18n and honor the browser's- # Accept-Language (the only server-readable locale signal pre-auth).- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- client = app.test_client()-- response = client.get(- "/auth/callback?code=test-code&state=state-1",- base_url="https://alex.avibe.bot",- headers={"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8"},- )-- assert response.status_code == 400- body = response.text- assert '<html lang="zh"' in body- assert "登录会话已过期" in body # invalid_oauth_state_title (zh)- assert "重新登录" in body # sign_in_again (zh)- assert "Your sign-in session expired" not in body # not the English copy---def test_remote_callback_refuses_store_fallback_without_device_binding(monkeypatch, tmp_path):- # Login-CSRF block: a code+state callback URL must not complete in a browser that- # isn't the one that started the flow. The store record is bound to the attacker's- # device id; the victim's browser presents its own (different) device cookie plus a- # stale handshake cookie, so the store-fallback must refuse — no token exchange.- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- secret = config.remote_access.vibe_cloud.session_secret- client = app.test_client()-- rid = "victimrid0001"- state_url = ui_server._make_oauth_state(secret, next_target="/dashboard", rid=rid)- remote_access.store_oauth_handshake(- rid,- nonce="n",- code_verifier="v",- next_target="/dashboard",- device_hash=ui_server._oauth_device_hash(secret, "attacker-device"),- )-- # Victim browser: a valid-but-stale handshake cookie and its OWN device cookie.- stale_cookie = ui_server._make_oauth_cookie(- secret,- {- "state": ui_server._make_oauth_state(secret, next_target="/", rid="victimst0000"),- "nonce": "x",- "code_verifier": "x",- "next": "/",- "exp": int(ui_server.datetime.now().timestamp()) + 300,- },- )- client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, stale_cookie, domain="alex.avibe.bot")- client.set_cookie(ui_server.REMOTE_OAUTH_DEVICE_COOKIE_NAME, "victim-device", domain="alex.avibe.bot")-- exchanged = []- monkeypatch.setattr(- remote_access, "exchange_oauth_code", lambda *a, **k: exchanged.append(a) or {"claims": {}}- )-- response = client.get(- f"/auth/callback?code=test-code&state={state_url}",- base_url="https://alex.avibe.bot",- follow_redirects=False,- )-- # Never exchanged the code, and never redirected the browser to the target.- assert exchanged == []- assert response.headers.get("Location") != "/dashboard"---def test_oauth_handshake_pop_is_atomic_single_use_under_concurrency(monkeypatch, tmp_path):- import threading- from unittest import mock-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- remote_access.store_oauth_handshake("race-rid000", nonce="n", code_verifier="v", next_target="/")-- barrier = threading.Barrier(2)- orig_replace = remote_access.os.replace-- def delayed_replace(src, dst):- try:- barrier.wait(timeout=5)- except threading.BrokenBarrierError:- pass- return orig_replace(src, dst)-- results = []-- def worker():- results.append(remote_access.pop_oauth_handshake("race-rid000"))-- with mock.patch.object(remote_access.os, "replace", delayed_replace):- threads = [threading.Thread(target=worker) for _ in range(2)]- for t in threads:- t.start()- for t in threads:- t.join()-- # The atomic claim guarantees exactly one racer gets the record.- assert sum(1 for r in results if r is not None) == 1---def test_remote_callback_accepts_html_escaped_state_separator(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()- oauth_cookie = ui_server._make_oauth_cookie(- config.remote_access.vibe_cloud.session_secret,- {- "state": "state-1",- "nonce": "nonce-1",- "code_verifier": "verifier-1",- "next": "/dashboard",- "exp": int(ui_server.datetime.now().timestamp()) + 300,- },- )- exchange_calls = []- client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="alex.avibe.bot")-- def exchange(cfg, code, verifier, redirect_uri=None):- exchange_calls.append((code, verifier))- return _oauth_exchange_result(cfg, nonce="nonce-1")-- monkeypatch.setattr(remote_access, "exchange_oauth_code", exchange)-- response = client.get("/auth/callback?code=test-code&state=state-1", base_url="https://alex.avibe.bot")-- assert response.status_code == 302- assert response.headers["Location"] == "/dashboard"- assert exchange_calls == [("test-code", "verifier-1")]---def test_remote_callback_sanitizes_protocol_relative_next(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- client = app.test_client()- oauth_cookie = ui_server._make_oauth_cookie(- config.remote_access.vibe_cloud.session_secret,- {- "state": "state-1",- "nonce": "nonce-1",- "code_verifier": "verifier-1",- "next": "//attacker.example",- "exp": int(ui_server.datetime.now().timestamp()) + 300,- },- )- client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="alex.avibe.bot")-- monkeypatch.setattr(- remote_access,- "exchange_oauth_code",- lambda cfg, code, verifier, redirect_uri=None: _oauth_exchange_result(- cfg,- nonce="nonce-1",- ),- )-- response = client.get("/auth/callback?code=test-code&state=state-1", base_url="https://alex.avibe.bot")-- assert response.status_code == 302- assert response.headers["Location"] == "/"---def _save_config_with_setup_host(tmp_path, host: str) -> V2Config:- config = _save_config(tmp_path)- config.ui.setup_host = host- config.save()- return config---def test_setup_host_lan_request_is_treated_as_local(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "192.168.2.3")- _mock_interface(monkeypatch, "192.168.2.3", 24)-- response = app.test_client().get(- "/health",- base_url="http://192.168.2.3:5123",- environ_base={"REMOTE_ADDR": "192.168.2.5"},- )-- assert response.status_code == 200---def test_setup_host_request_from_self_is_treated_as_local(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "192.168.2.3")- _mock_interface(monkeypatch, "192.168.2.3", 24)-- response = app.test_client().get(- "/health",- base_url="http://192.168.2.3:5123",- environ_base={"REMOTE_ADDR": "192.168.2.3"},- )-- assert response.status_code == 200--[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")-def test_terminal_websocket_rejects_setup_host_origin_from_different_port(monkeypatch, tmp_path):- # A private setup-host request is treated as local (accepted without a session- # cookie), so the terminal Origin check must still pin it to the exact scheme+port —- # otherwise a same-host page served on another port could open a cross-origin- # terminal socket. Regression guard for the setup-host CSWSH gap: before passing the- # config into _websocket_is_local_request, this request fell through to the remote- # host-only relaxation and the mismatched port was accepted.- monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "192.168.2.3")- _mock_interface(monkeypatch, "192.168.2.3", 24)-- with pytest.raises(WebSocketDisconnect) as exc:- with app.test_client().websocket_connect(- "/api/terminal/test",- headers={- "host": "192.168.2.3:5123",- "origin": "http://192.168.2.3:3000",- "x-vibe-test-remote-addr": "192.168.2.5",- },- ):- pass-- assert exc.value.code == 1008--[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")-def test_terminal_websocket_accepts_setup_host_origin_from_same_port(monkeypatch, tmp_path):- # The exact-origin counterpart: a setup-host terminal request whose Origin matches the- # request scheme+port must still be accepted (the fix must not over-reject LAN setup).- monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "192.168.2.3")- _mock_interface(monkeypatch, "192.168.2.3", 24)-- accepted = False-- async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):- nonlocal accepted- accepted = True-- monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)-- with app.test_client().websocket_connect(- "/api/terminal/test",- headers={- "host": "192.168.2.3:5123",- "origin": "http://192.168.2.3:5123",- "x-vibe-test-remote-addr": "192.168.2.5",- },- ):- pass-- assert accepted is True--[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")-def test_terminal_websocket_accepts_setup_host_from_trusted_proxy(monkeypatch, tmp_path):- monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")- _save_config_with_setup_host(tmp_path, "192.168.2.3")- _mock_interface(monkeypatch, "192.168.2.3", 24)-- accepted = False-- async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):- nonlocal accepted- accepted = True-- monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)-- with app.test_client().websocket_connect(- "/api/terminal/test",- headers={- "host": "127.0.0.1:5123",- "origin": "http://192.168.2.3:5123",- "x-forwarded-proto": "http",- "x-forwarded-host": "192.168.2.3:5123",- "x-forwarded-for": "192.168.2.5",- "x-vibe-test-remote-addr": "127.0.0.1",- },- ):- pass-- assert accepted is True--[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")-def test_terminal_websocket_accepts_trusted_public_origin_from_proxy_when_remote_access_disabled(- monkeypatch,- tmp_path,-):- monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")- monkeypatch.setenv(ui_server.TRUSTED_PUBLIC_ORIGINS_ENV, "https://avibe.example.com")- config = _save_config(tmp_path)- config.remote_access.vibe_cloud.enabled = False- config.save()-- accepted = False-- async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):- nonlocal accepted- accepted = True-- monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)-- with app.test_client().websocket_connect(- "/api/terminal/test",- headers={- "host": "127.0.0.1:5123",- "origin": "https://avibe.example.com",- "x-forwarded-proto": "https",- "x-forwarded-host": "avibe.example.com",- "x-forwarded-for": "203.0.113.10",- "x-vibe-test-remote-addr": "127.0.0.1",- },- ):- pass-- assert accepted is True--[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")-def test_terminal_websocket_rejects_unlisted_public_origin_from_trusted_proxy(monkeypatch, tmp_path):- monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")- config = _save_config(tmp_path)- config.remote_access.vibe_cloud.enabled = False- config.save()-- with pytest.raises(WebSocketDisconnect) as exc:- with app.test_client().websocket_connect(- "/api/terminal/test",- headers={- "host": "127.0.0.1:5123",- "origin": "https://avibe.example.com",- "x-forwarded-proto": "https",- "x-forwarded-host": "avibe.example.com",- "x-forwarded-for": "203.0.113.10",- "x-vibe-test-remote-addr": "127.0.0.1",- },- ):- pass-- assert exc.value.code == 1008--[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")-def test_terminal_websocket_rejects_loopback_trusted_public_origin_when_remote_access_enabled(- monkeypatch,- tmp_path,-):- monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")- monkeypatch.setenv(ui_server.TRUSTED_PUBLIC_ORIGINS_ENV, "https://alex.avibe.bot")- config = _save_config(tmp_path)- config.remote_access.vibe_cloud.public_url = "https://alex.avibe.bot"- config.remote_access.vibe_cloud.enabled = True- config.save()-- with pytest.raises(WebSocketDisconnect) as exc:- with app.test_client().websocket_connect(- "/api/terminal/test",- headers={- "host": "127.0.0.1:5123",- "origin": "https://alex.avibe.bot",- "x-forwarded-proto": "https",- "x-forwarded-host": "alex.avibe.bot",- "x-forwarded-for": "203.0.113.10",- "x-vibe-test-remote-addr": "127.0.0.1",- },- ):- pass-- assert exc.value.code == 1008--[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")-def test_terminal_websocket_rejects_remote_same_host_different_origin(monkeypatch, tmp_path):- monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")- 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",- )-- with pytest.raises(WebSocketDisconnect) as exc:- with client.websocket_connect(- "wss://alex.avibe.bot/api/terminal/test",- headers={- "host": "alex.avibe.bot",- "origin": "https://alex.avibe.bot:8443",- "x-forwarded-for": "203.0.113.10",- },- ):- pass-- assert exc.value.code == 1008--[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")[email protected]("origin", ["https://alex.avibe.bot", "https://alex.avibe.bot:443"])-def test_terminal_websocket_rejects_non_org_remote_exact_trusted_origin(monkeypatch, tmp_path, origin):- monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- accepted = False-- async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):- nonlocal accepted- accepted = True-- monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- remote_session_cookie(config, "[email protected]", "user-1"),- domain="alex.avibe.bot",- )-- with pytest.raises(WebSocketDisconnect) as exc:- with client.websocket_connect(- "wss://alex.avibe.bot/api/terminal/test",- headers={- "host": "alex.avibe.bot",- "origin": origin,- "x-forwarded-for": "203.0.113.10",- },- ):- pass-- assert exc.value.code == 1008- assert accepted is False--[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")- ("instance_role", "organization_role"),- [("owner", "owner"), ("viewer", "member")],-)-def test_terminal_websocket_accepts_remote_org_owner_and_member(- monkeypatch,- tmp_path,- instance_role,- organization_role,-):- monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- handled_session_ids: list[str] = []-- async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):- handled_session_ids.append(session_id)-- monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)- subject = f"user-{organization_role}"- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- remote_session_cookie(- config,- f"{organization_role}@example.com",- subject,- role=instance_role,- access_source="organization_group",- organization_id="org-1",- organization_member_id=f"member-{organization_role}",- organization_role=organization_role,- group_ids=[],- ),- domain="alex.avibe.bot",- )-- with client.websocket_connect(- "wss://alex.avibe.bot/api/terminal/shared-session",- headers={- "host": "alex.avibe.bot",- "origin": "https://alex.avibe.bot",- "x-forwarded-for": "203.0.113.10",- },- ):- pass-- assert handled_session_ids == [- ui_server._terminal_effective_session_id("shared-session", subject)- ]--[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")-def test_terminal_websocket_rejects_remote_viewer(monkeypatch, tmp_path):- monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")- 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-viewer",- role="viewer",- access_source="email",- ),- domain="alex.avibe.bot",- )-- with pytest.raises(WebSocketDisconnect) as exc:- with client.websocket_connect(- "wss://alex.avibe.bot/api/terminal/test",- headers={- "host": "alex.avibe.bot",- "origin": "https://alex.avibe.bot",- "x-forwarded-for": "203.0.113.10",- },- ):- pass-- assert exc.value.code == 1008--[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")-def test_terminal_websocket_rejects_remote_active_custom_hostname(monkeypatch, tmp_path):- monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- remote_access._replace_active_hostnames(config, ["max.fileguard.io"])- accepted = False-- async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):- nonlocal accepted- accepted = True-- monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- remote_access.make_session_cookie(- config,- "[email protected]",- "user-1",- session_claims=_oauth_exchange_result(config, nonce="unused")["session_claims"],- ),- domain="max.fileguard.io",- )-- with pytest.raises(WebSocketDisconnect) as exc:- with client.websocket_connect(- "wss://max.fileguard.io/api/terminal/test",- headers={- "host": "max.fileguard.io",- "origin": "https://max.fileguard.io",- "x-forwarded-for": "203.0.113.10",- },- ):- pass-- assert exc.value.code == 1008- assert accepted is False---def test_terminal_effective_session_id_scopes_remote_subjects():- client_id = "shared-session"-- user_one_first = ui_server._terminal_effective_session_id(client_id, "user-1")- user_one_second = ui_server._terminal_effective_session_id(client_id, "user-1")- user_two = ui_server._terminal_effective_session_id(client_id, "user-2")-- assert user_one_first == user_one_second- assert user_one_first != user_two- assert user_one_first.endswith("-shared-session")- assert ui_server._terminal_effective_session_id(client_id, None) == client_id--[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")-def test_terminal_websocket_never_starts_a_remote_subject_session(monkeypatch, tmp_path):- monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)- handled_session_ids: list[str] = []-- async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):- handled_session_ids.append(session_id)-- monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)-- def connect_as(subject: str) -> None:- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- remote_session_cookie(config, f"{subject}@example.com", subject),- domain="alex.avibe.bot",- )- with pytest.raises(WebSocketDisconnect) as exc:- with client.websocket_connect(- "wss://alex.avibe.bot/api/terminal/shared-session",- headers={- "host": "alex.avibe.bot",- "origin": "https://alex.avibe.bot",- "x-forwarded-for": "203.0.113.10",- },- ):- pass- assert exc.value.code == 1008-- connect_as("user-1")- connect_as("user-1")- connect_as("user-2")-- assert handled_session_ids == []--[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")-def test_terminal_websocket_keeps_local_session_id_unscoped(monkeypatch, tmp_path):- monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "192.168.2.3")- _mock_interface(monkeypatch, "192.168.2.3", 24)- handled_session_ids: list[str] = []-- async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):- handled_session_ids.append(session_id)-- monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)-- with app.test_client().websocket_connect(- "/api/terminal/local-session",- headers={- "host": "192.168.2.3:5123",- "origin": "http://192.168.2.3:5123",- "x-vibe-test-remote-addr": "192.168.2.5",- },- ):- pass-- assert handled_session_ids == ["local-session"]---def test_setup_host_with_public_peer_is_not_local(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "192.168.2.3")-- response = app.test_client().get(- "/dashboard",- base_url="http://192.168.2.3:5123",- environ_base={"REMOTE_ADDR": "8.8.8.8"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_lan_peer_with_tailscale_setup_is_not_local(monkeypatch, tmp_path):- """Wildcard-bind regression guard: a LAN peer cannot inherit setup-host- trust by spoofing the Host header to a Tailscale setup_host that lives- in a different private block."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "100.97.103.112")-- response = app.test_client().get(- "/dashboard",- base_url="http://100.97.103.112:5123",- environ_base={"REMOTE_ADDR": "192.168.1.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_tailscale_peer_with_lan_setup_is_not_local(monkeypatch, tmp_path):- """Inverse of the LAN-vs-Tailscale check: a Tailscale peer cannot inherit- setup-host trust by spoofing the Host header to a LAN setup_host."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "192.168.2.3")-- response = app.test_client().get(- "/dashboard",- base_url="http://192.168.2.3:5123",- environ_base={"REMOTE_ADDR": "100.97.103.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_tailscale_peer_with_tailscale_setup_is_local(monkeypatch, tmp_path):- """Same-block trust still works: a Tailscale peer can inherit setup-host- trust when setup_host is also in 100.64/10."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "100.97.103.112")-- response = app.test_client().get(- "/health",- base_url="http://100.97.103.112:5123",- environ_base={"REMOTE_ADDR": "100.97.103.5"},- )-- assert response.status_code == 200---def test_setup_host_rfc1918_peer_outside_interface_subnet_is_not_local(monkeypatch, tmp_path):- """RFC1918 trust must not span the entire /8: a 10.50/16 peer cannot- inherit setup-host trust from a 10.1.2.3 setup_host configured with a- /24 mask. Pre-wildcard, the kernel only let in peers on the same- interface subnet — _local_interface_network restores that scoping- using the actual netmask."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "10.1.2.3")- _mock_interface(monkeypatch, "10.1.2.3", 24)-- response = app.test_client().get(- "/dashboard",- base_url="http://10.1.2.3:5123",- environ_base={"REMOTE_ADDR": "10.50.0.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_rfc1918_peer_in_same_interface_subnet_is_local(monkeypatch, tmp_path):- """Same-subnet RFC1918 peer still inherits trust (typical home/office LAN)."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "10.1.2.3")- _mock_interface(monkeypatch, "10.1.2.3", 24)-- response = app.test_client().get(- "/health",- base_url="http://10.1.2.3:5123",- environ_base={"REMOTE_ADDR": "10.1.2.50"},- )-- assert response.status_code == 200---def test_setup_host_192168_peer_outside_interface_subnet_is_not_local(monkeypatch, tmp_path):- """A peer on 192.168.2/24 cannot spoof Host=192.168.1.5 when the- interface mask is /24."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "192.168.1.5")- _mock_interface(monkeypatch, "192.168.1.5", 24)-- response = app.test_client().get(- "/dashboard",- base_url="http://192.168.1.5:5123",- environ_base={"REMOTE_ADDR": "192.168.2.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_with_16_prefix_includes_peer_in_same_16(monkeypatch, tmp_path):- """When the interface mask is /16, a peer on a different /24 within- the same /16 still inherits trust — fixed-/24 estimates were too- narrow for /16 LANs."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "192.168.1.5")- _mock_interface(monkeypatch, "192.168.1.5", 16)-- response = app.test_client().get(- "/health",- base_url="http://192.168.1.5:5123",- environ_base={"REMOTE_ADDR": "192.168.7.20"},- )-- assert response.status_code == 200---def test_setup_host_with_20_prefix_includes_peer_in_same_20(monkeypatch, tmp_path):- """/20 corporate networks (4096 addresses) are honored without- artificially narrowing to /24."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "10.1.16.5")- _mock_interface(monkeypatch, "10.1.16.5", 20)-- response = app.test_client().get(- "/health",- base_url="http://10.1.16.5:5123",- environ_base={"REMOTE_ADDR": "10.1.31.250"},- )-- assert response.status_code == 200---def test_setup_host_with_20_prefix_excludes_peer_outside_20(monkeypatch, tmp_path):- """/20 still excludes peers outside the /20 (peer in next /20 is not- on the same routed subnet)."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "10.1.16.5")- _mock_interface(monkeypatch, "10.1.16.5", 20)-- response = app.test_client().get(- "/dashboard",- base_url="http://10.1.16.5:5123",- environ_base={"REMOTE_ADDR": "10.1.32.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_unknown_to_local_interfaces_is_not_local(monkeypatch, tmp_path):- """If setup_host is not configured on any local interface, deny trust- rather than guess a subnet — this preserves the kernel's pre-wildcard- "no matching interface, no traffic" semantics."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "192.168.99.99")- _mock_no_interfaces(monkeypatch)-- response = app.test_client().get(- "/dashboard",- base_url="http://192.168.99.99:5123",- environ_base={"REMOTE_ADDR": "192.168.99.50"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_ipv6_with_56_prefix_includes_peer_in_same_56(monkeypatch, tmp_path):- """A non-/64 IPv6 LAN (e.g. /56 prefix delegated to the home network)- is honored without artificially narrowing to /64."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "fd00:0:0:1::5")- _mock_interface(monkeypatch, "fd00:0:0:1::5", 56)-- response = app.test_client().get(- "/health",- base_url="http://[fd00:0:0:1::5]:5123",- environ_base={"REMOTE_ADDR": "fd00:0:0:7::20"},- )-- assert response.status_code == 200---def test_setup_host_ipv6_with_64_prefix_excludes_peer_outside_64(monkeypatch, tmp_path):- """Default IPv6 LAN /64 still scopes peers correctly."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "fd00::5")- _mock_interface(monkeypatch, "fd00::5", 64)-- response = app.test_client().get(- "/dashboard",- base_url="http://[fd00::5]:5123",- environ_base={"REMOTE_ADDR": "fd00:0:0:1::20"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def _save_config_tunnel_off_with_setup_host(tmp_path, host: str) -> V2Config:- config = _save_config(tmp_path)- config.remote_access.vibe_cloud.enabled = False- config.ui.setup_host = host- config.save()- return config---def test_setup_host_tunnel_off_allows_routed_peer_outside_interface_subnet(monkeypatch, tmp_path):- """When the tunnel is off, the UI binds directly to setup_host and the- kernel already enforces interface filtering — a routed peer reaching- setup_host across a /16 corporate or campus net must have been routed- legitimately, so the application layer should not add a second-pass- subnet gate (regression noted in Codex review of #252)."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_tunnel_off_with_setup_host(tmp_path, "10.1.2.3")- _mock_interface(monkeypatch, "10.1.2.3", 24)-- response = app.test_client().get(- "/health",- base_url="http://10.1.2.3:5123",- environ_base={"REMOTE_ADDR": "10.50.0.5"},- )-- assert response.status_code == 200---def test_setup_host_tunnel_off_still_rejects_public_peer(monkeypatch, tmp_path):- """Tunnel-off relaxation of the subnet gate must not relax the- private-peer requirement: a public peer is still untrusted."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_tunnel_off_with_setup_host(tmp_path, "10.1.2.3")-- response = app.test_client().get(- "/dashboard",- base_url="http://10.1.2.3:5123",- environ_base={"REMOTE_ADDR": "8.8.8.8"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_tunnel_on_still_enforces_subnet_gate(monkeypatch, tmp_path):- """Mirror of the tunnel-off test above: with the tunnel on, the- wildcard bind requires the application-layer subnet gate, so the same- cross-subnet peer that is allowed when the tunnel is off must be- rejected when the tunnel is on."""- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "10.1.2.3")- _mock_interface(monkeypatch, "10.1.2.3", 24)-- response = app.test_client().get(- "/dashboard",- base_url="http://10.1.2.3:5123",- environ_base={"REMOTE_ADDR": "10.50.0.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_mismatched_host_header_is_not_local(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "192.168.2.3")-- response = app.test_client().get(- "/dashboard",- base_url="http://10.0.0.5:5123",- environ_base={"REMOTE_ADDR": "192.168.2.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_wildcard_allows_actual_lan_interface_host(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setattr(ui_server, "_is_containerized_runtime", lambda: False)- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_interface(monkeypatch, "192.168.2.3", 24)-- response = app.test_client().get(- "/health",- base_url="http://192.168.2.3:5123",- environ_base={"REMOTE_ADDR": "192.168.2.5"},- )-- assert response.status_code == 200---def test_setup_host_wildcard_allows_bare_metal_eth_lan_interface(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setattr(ui_server, "_is_containerized_runtime", lambda: False)- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_interface(monkeypatch, "192.168.2.3", 24, name="eth0")-- response = app.test_client().get(- "/health",- base_url="http://192.168.2.3:5123",- environ_base={"REMOTE_ADDR": "192.168.2.5"},- )-- assert response.status_code == 200---def test_setup_host_wildcard_does_not_trust_container_eth_interface(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setattr(ui_server, "_is_containerized_runtime", lambda: True)- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_interface(monkeypatch, "192.168.2.3", 24, name="eth0")-- response = app.test_client().get(- "/dashboard",- base_url="http://192.168.2.3:5123",- environ_base={"REMOTE_ADDR": "192.168.2.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_wildcard_does_not_trust_unconfigured_lan_host(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_no_interfaces(monkeypatch)-- response = app.test_client().get(- "/dashboard",- base_url="http://192.168.2.3:5123",- environ_base={"REMOTE_ADDR": "192.168.2.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_wildcard_does_not_trust_docker_bridge_interface(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_interface(monkeypatch, "172.17.0.1", 16, name="docker0")-- response = app.test_client().get(- "/dashboard",- base_url="http://172.17.0.1:5123",- environ_base={"REMOTE_ADDR": "172.17.0.2"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_wildcard_does_not_trust_cni_bridge_interface(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_interface(monkeypatch, "192.168.2.3", 24, name="cni0")-- response = app.test_client().get(- "/dashboard",- base_url="http://192.168.2.3:5123",- environ_base={"REMOTE_ADDR": "192.168.2.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_wildcard_does_not_trust_flannel_interface(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_interface(monkeypatch, "10.244.0.1", 24, name="flannel.1")-- response = app.test_client().get(- "/dashboard",- base_url="http://10.244.0.1:5123",- environ_base={"REMOTE_ADDR": "10.244.0.2"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_wildcard_does_not_trust_bridge_interface_in_cgnat_range(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_interface(monkeypatch, "100.97.103.112", 32, name="docker0")-- response = app.test_client().get(- "/dashboard",- base_url="http://100.97.103.112:5123",- environ_base={"REMOTE_ADDR": "100.97.103.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_wildcard_rejects_peer_outside_interface_subnet(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_interface(monkeypatch, "192.168.1.5", 24)-- response = app.test_client().get(- "/dashboard",- base_url="http://192.168.1.5:5123",- environ_base={"REMOTE_ADDR": "192.168.2.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_wildcard_rejects_public_peer(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_interface(monkeypatch, "192.168.2.3", 24)-- response = app.test_client().get(- "/dashboard",- base_url="http://192.168.2.3:5123",- environ_base={"REMOTE_ADDR": "8.8.8.8"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_wildcard_with_reverse_proxy_header_is_not_local(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_interface(monkeypatch, "192.168.2.3", 24)-- response = app.test_client().get(- "/dashboard",- base_url="http://192.168.2.3:5123",- environ_base={"REMOTE_ADDR": "192.168.2.5"},- headers={"X-Forwarded-For": "203.0.113.10"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_wildcard_with_reverse_proxy_header_skips_interface_probe(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- monkeypatch.setattr(- ui_server,- "_local_interface_network",- lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("interface probe should be skipped")),- )-- response = app.test_client().get(- "/dashboard",- base_url="http://100.97.103.112:5123",- environ_base={"REMOTE_ADDR": "100.97.103.5"},- headers={"X-Forwarded-For": "203.0.113.10"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_wildcard_allows_actual_tailscale_interface_host(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_interface(monkeypatch, "100.97.103.112", 32, name="tailscale0")- _mock_tailscale_whois(monkeypatch, "100.97.103.5")-- response = app.test_client().get(- "/health",- base_url="http://100.97.103.112:5123",- environ_base={"REMOTE_ADDR": "100.97.103.5"},- )-- assert response.status_code == 200---def test_setup_host_wildcard_rejects_tailscale_peer_without_whois(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_interface(monkeypatch, "100.97.103.112", 32, name="tailscale0")- monkeypatch.setattr(ui_server, "_TAILSCALE_PEER_CACHE", {})- monkeypatch.setattr(ui_server, "_tailscale_whois", lambda address: None)-- response = app.test_client().get(- "/dashboard",- base_url="http://100.97.103.112:5123",- environ_base={"REMOTE_ADDR": "100.97.103.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_wildcard_rejects_tailscale_subnet_router_peer(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_interface(monkeypatch, "100.97.103.112", 32, name="tailscale0")- _mock_tailscale_whois(monkeypatch, "100.97.103.5", allowed_ips=["100.97.103.5/32", "192.168.50.0/24"])-- response = app.test_client().get(- "/dashboard",- base_url="http://100.97.103.112:5123",- environ_base={"REMOTE_ADDR": "100.97.103.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_trusted_tailscale_peer_accepts_modern_node_whois_payload(monkeypatch):- """Current ``tailscale whois --json`` nests the peer under ``Node`` with- host-CIDR address strings; the top-level ``Machine`` object is gone."""- peer = ipaddress.ip_address("100.97.103.5")- monkeypatch.setattr(ui_server, "_TAILSCALE_PEER_CACHE", {})- monkeypatch.setattr(- ui_server,- "_tailscale_whois",- lambda address: {- "Node": {- "Name": "iphone.example.ts.net.",- "Machine": "mkey:0123456789abcdef",- "Addresses": ["100.97.103.5/32", "fd7a:115c:a1e0::5/128"],- "AllowedIPs": ["100.97.103.5/32", "fd7a:115c:a1e0::5/128"],- },- "UserProfile": {"LoginName": "[email protected]"},- "CapMap": {},- },- )-- assert ui_server._is_trusted_tailscale_peer(peer) is True---def test_trusted_tailscale_peer_accepts_legacy_machine_whois_payload(monkeypatch):- peer = ipaddress.ip_address("100.97.103.5")- _mock_tailscale_whois(- monkeypatch,- "100.97.103.5",- addresses=["100.97.103.5"],- payload_key="Machine",- )-- assert ui_server._is_trusted_tailscale_peer(peer) is True---def test_trusted_tailscale_peer_rejects_node_payload_with_subnet_route(monkeypatch):- peer = ipaddress.ip_address("100.97.103.5")- _mock_tailscale_whois(- monkeypatch,- "100.97.103.5",- allowed_ips=["100.97.103.5/32", "192.168.50.0/24"],- )-- assert ui_server._is_trusted_tailscale_peer(peer) is False---def test_trusted_tailscale_peer_ignores_non_host_address_entries(monkeypatch):- """Address entries that are not host CIDRs must not satisfy the peer- match, so a payload claiming a whole range cannot vouch for the peer."""- peer = ipaddress.ip_address("100.97.103.5")- _mock_tailscale_whois(- monkeypatch,- "100.97.103.5",- addresses=["100.97.103.0/24"],- )-- assert ui_server._is_trusted_tailscale_peer(peer) is False---def test_setup_host_wildcard_does_not_trust_unconfigured_tailscale_host(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_no_interfaces(monkeypatch)-- response = app.test_client().get(- "/dashboard",- base_url="http://100.97.103.112:5123",- environ_base={"REMOTE_ADDR": "100.97.103.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_ipv6_wildcard_allows_actual_private_interface_host(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setattr(ui_server, "_is_containerized_runtime", lambda: False)- _save_config_with_setup_host(tmp_path, "::")- _mock_interface(monkeypatch, "fd00::5", 64)-- response = app.test_client().get(- "/health",- base_url="http://[fd00::5]:5123",- environ_base={"REMOTE_ADDR": "fd00::20"},- )-- assert response.status_code == 200---def test_setup_host_ipv6_wildcard_allows_tailscale_ula_interface_host(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "::")- _mock_interface(monkeypatch, "fd7a:115c:a1e0::5", 128, name="tailscale0")- _mock_tailscale_whois(monkeypatch, "fd7a:115c:a1e0::20")-- response = app.test_client().get(- "/health",- base_url="http://[fd7a:115c:a1e0::5]:5123",- environ_base={"REMOTE_ADDR": "fd7a:115c:a1e0::20"},- )-- assert response.status_code == 200---def test_setup_host_ipv6_wildcard_does_not_trust_bridge_in_tailscale_ula_range(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "::")- _mock_interface(monkeypatch, "fd7a:115c:a1e0::5", 64, name="docker0")-- response = app.test_client().get(- "/dashboard",- base_url="http://[fd7a:115c:a1e0::5]:5123",- environ_base={"REMOTE_ADDR": "fd7a:115c:a1e0::20"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_wildcard_does_not_trust_generic_utun_tunnel(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- _mock_interface(monkeypatch, "100.97.103.112", 32, name="utun4")- monkeypatch.setattr(ui_server, "_tailscale_local_addresses", lambda: frozenset())-- response = app.test_client().get(- "/dashboard",- base_url="http://100.97.103.112:5123",- environ_base={"REMOTE_ADDR": "100.97.103.5"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_wildcard_trusts_utun_when_tailscale_reports_local_ip(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "0.0.0.0")- address = ipaddress.ip_address("100.97.103.112")- _mock_interface(monkeypatch, str(address), 32, name="utun4")- monkeypatch.setattr(ui_server, "_tailscale_local_addresses", lambda: frozenset({address}))- _mock_tailscale_whois(monkeypatch, "100.97.103.5")-- response = app.test_client().get(- "/health",- base_url="http://100.97.103.112:5123",- environ_base={"REMOTE_ADDR": "100.97.103.5"},- )-- assert response.status_code == 200---def test_setup_host_ipv6_wildcard_does_not_trust_generic_utun_tunnel(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "::")- _mock_interface(monkeypatch, "fd7a:115c:a1e0::5", 128, name="utun4")- monkeypatch.setattr(ui_server, "_tailscale_local_addresses", lambda: frozenset())-- response = app.test_client().get(- "/dashboard",- base_url="http://[fd7a:115c:a1e0::5]:5123",- environ_base={"REMOTE_ADDR": "fd7a:115c:a1e0::20"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_ipv6_wildcard_trusts_utun_when_tailscale_reports_local_ip(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "::")- address = ipaddress.ip_address("fd7a:115c:a1e0::5")- _mock_interface(monkeypatch, str(address), 128, name="utun4")- monkeypatch.setattr(ui_server, "_tailscale_local_addresses", lambda: frozenset({address}))- _mock_tailscale_whois(monkeypatch, "fd7a:115c:a1e0::20")-- response = app.test_client().get(- "/health",- base_url="http://[fd7a:115c:a1e0::5]:5123",- environ_base={"REMOTE_ADDR": "fd7a:115c:a1e0::20"},- )-- assert response.status_code == 200---def test_setup_host_with_cloudflare_metadata_is_not_local(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "192.168.2.3")-- response = app.test_client().get(- "/dashboard",- base_url="http://192.168.2.3:5123",- environ_base={"REMOTE_ADDR": "192.168.2.5"},- headers=_cloudflare_headers(),- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_with_reverse_proxy_header_is_not_local(monkeypatch, tmp_path):- """A non-Cloudflare reverse proxy on the same host (nginx, Caddy, ...)- fronts vibe and an attacker spoofs Host=setup_host. The app sees a private- peer (the proxy) and the Host matches setup_host, so the host+peer pair- looks "local" — but X-Forwarded-For (or any other forwarded header) tells- us the actual client is unknown, so the request must not be trusted.- """- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config_with_setup_host(tmp_path, "192.168.2.3")-- response = app.test_client().get(- "/dashboard",- base_url="http://192.168.2.3:5123",- environ_base={"REMOTE_ADDR": "127.0.0.1"},- headers={"X-Forwarded-For": "203.0.113.10"},- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_setup_host_trusts_forwarded_host_from_explicit_trusted_proxy(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")- config = _save_config_with_setup_host(tmp_path, "192.168.2.3")- config.remote_access.vibe_cloud.enabled = False- config.save()-- response = app.test_client().get(- "/health",- base_url="http://127.0.0.1:5123",- environ_base={"REMOTE_ADDR": "127.0.0.1"},- headers={- "X-Forwarded-Proto": "http",- "X-Forwarded-Host": "192.168.2.3",- "X-Forwarded-For": "192.168.2.5",- },- follow_redirects=False,- )-- assert response.status_code == 200---def test_trusted_public_origin_can_come_from_config(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")- config = _save_config(tmp_path)- config.remote_access.vibe_cloud.enabled = False- config.ui.trusted_public_origins = ["https://avibe.example.com"]- config.save()-- response = app.test_client().get(- "/health",- base_url="http://127.0.0.1:5123",- environ_base={"REMOTE_ADDR": "127.0.0.1"},- headers={- "X-Forwarded-Proto": "https",- "X-Forwarded-Host": "avibe.example.com",- "X-Forwarded-For": "203.0.113.10",- },- follow_redirects=False,- )-- assert response.status_code == 200---def test_setup_host_rejects_public_forwarded_client_from_trusted_proxy(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")- config = _save_config_with_setup_host(tmp_path, "192.168.2.3")- config.remote_access.vibe_cloud.enabled = False- config.save()-- response = app.test_client().get(- "/health",- base_url="http://127.0.0.1:5123",- environ_base={"REMOTE_ADDR": "127.0.0.1"},- headers={- "X-Forwarded-Proto": "http",- "X-Forwarded-Host": "192.168.2.3",- "X-Forwarded-For": "8.8.8.8",- },- follow_redirects=False,- )-- assert response.status_code == 503- assert response.get_json()["error"] == "remote_access_host_mismatch"---def test_settings_get_serves_json_even_for_browser_accept(monkeypatch, tmp_path):- """After the /api/* migration the settings JSON API lives at /api/settings- and no longer content-negotiates a redirect. Even a browser-style- Accept: text/html request receives the JSON payload; SPA routing for the- user-facing /settings URL is handled by the static catch-all instead, so- the API path itself never collides with a UI route anymore.- """- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)-- response = app.test_client().get(- "/api/settings",- base_url="http://127.0.0.1:5123",- headers={"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},- follow_redirects=False,- )-- assert response.status_code == 200- assert response.is_json---def test_settings_get_returns_json_for_fetch_callers(monkeypatch, tmp_path):- """fetch() from the SPA hits /settings without an explicit text/html in- Accept; the handler must keep returning JSON so getSettings() works.- """- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)-- response = app.test_client().get(- "/api/settings",- base_url="http://127.0.0.1:5123",- headers={"Accept": "*/*"},- )-- assert response.status_code == 200- assert response.is_jsondiff --git a/tests/test_ui_resource_access_api.py b/tests/test_ui_resource_access_api.pyindex b62700f69..95d8c7268 100644--- a/tests/test_ui_resource_access_api.py+++ b/tests/test_ui_resource_access_api.py@@ -4,8 +4,7 @@ from config import pathsfrom storage import resource_access_servicefrom storage.db import get_cached_sqlite_enginefrom storage.migrations import run_migrations-from tests.test_ui_remote_access_auth import _save_config-from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie+from tests.ui_server_test_helpers import csrf_headers, remote_session_cookie, save_configfrom vibe import remote_accessfrom vibe.ui_server import app@@ -61,7 +60,7 @@ def _seed_organization_policy() -> None:def test_organization_context_and_policy_routes_use_signed_cookie_claims(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)+ config = save_config(tmp_path)_seed_organization_policy()client = app.test_client()client.set_cookie(@@ -103,7 +102,7 @@ def test_organization_context_and_policy_routes_use_signed_cookie_claims(monkeypdef test_organization_policy_put_does_not_create_local_revision(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)+ config = save_config(tmp_path)_seed_organization_policy()client = app.test_client()client.set_cookie(@@ -136,7 +135,7 @@ def test_organization_policy_put_does_not_create_local_revision(monkeypatch, tmpdef test_external_guest_cannot_update_an_organization_policy(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _save_config(tmp_path)+ config = save_config(tmp_path)_seed_organization_policy()client = app.test_client()client.set_cookie(diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex 82ee6128f..8703d8e8e 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -2,6 +2,7 @@ import asyncioimport base64import hashlibimport io+import ipaddressimport jsonimport osimport socket@@ -18,6 +19,15 @@ from unittest.mock import patchimport pytestfrom config import paths+from config.v2_config import (+ AgentsConfig,+ PlatformsConfig,+ RemoteAccessConfig,+ RuntimeConfig,+ SlackConfig,+ UiConfig,+ V2Config,+)from core.show_pages import (SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS,ShowPageStore,@@ -34,13 +44,56 @@ from core.show_runtime import (set_show_runtime_manager_for_tests,)from storage import resource_access_service-from tests.test_ui_remote_access_auth import _mock_interface, _remote_peer, _save_configfrom tests.ui_server_test_helpers import csrf_headers, remote_session_cookiefrom vibe import remote_access, ui_serverfrom vibe.ui_server import appfrom storage import message_deliveries+def _mock_interface(monkeypatch, ip: str, prefix: int, name: str = "en0") -> None:+ address = ipaddress.ip_address(ip)+ family = socket.AF_INET if address.version == 4 else socket.AF_INET6+ netmask = str(+ ipaddress.ip_network(f"{'0.0.0.0' if address.version == 4 else '::'}/{prefix}").netmask+ )+ snic = SimpleNamespace(+ family=family,+ address=ip,+ netmask=netmask,+ broadcast=None,+ ptp=None,+ )+ monkeypatch.setattr("vibe.ui_server.psutil.net_if_addrs", lambda: {name: [snic]})+++def _remote_peer() -> dict[str, str]:+ return {"REMOTE_ADDR": "203.0.113.10"}+++def _save_config(tmp_path):+ config = V2Config(+ mode="self_host",+ version="v2",+ platform="slack",+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ ui=UiConfig(),+ remote_access=RemoteAccessConfig(),+ )+ cloud = config.remote_access.vibe_cloud+ cloud.enabled = True+ cloud.public_url = "https://alex.avibe.bot"+ cloud.client_id = "vr_client_123"+ cloud.instance_id = "inst_123"+ cloud.session_secret = "session-secret"+ cloud.authorization_endpoint = "https://backend.test/oauth/authorize"+ cloud.redirect_uri = "https://alex.avibe.bot/auth/callback"+ config.save()+ return config++def _active_org_cookie(config, email="[email protected]", subject="member-1"):return remote_session_cookie(config,@@ -708,13 +761,16 @@ def test_remote_show_page_icon_is_not_persistently_cached(monkeypatch, tmp_path)assert response.headers["Cache-Control"] == "private, no-store"-def test_remote_non_org_owner_cannot_ensure_show_page(monkeypatch, tmp_path):+def test_remote_personal_owner_can_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: calls.append(session_id),+ lambda session_id, **_kwargs: (+ calls.append(session_id)+ or {"session_id": session_id, "visibility": "private"}+ ),)client = app.test_client()client.set_cookie(@@ -730,9 +786,12 @@ def test_remote_non_org_owner_cannot_ensure_show_page(monkeypatch, tmp_path):headers=csrf_headers(client, "https://alex.avibe.bot"),)- assert response.status_code == 403- assert response.get_json()["code"] == "remote_execution_disabled"- assert calls == []+ assert response.status_code == 200+ assert response.get_json() == {+ "session_id": "ses123",+ "visibility": "private",+ }+ assert calls == ["ses123"]def test_show_page_icon_endpoint_enforces_token_without_selecting_the_file(monkeypatch, tmp_path):diff --git a/tests/test_workbench_prefs_api.py b/tests/test_workbench_prefs_api.pyindex 5b0c181ce..17b13abaf 100644--- a/tests/test_workbench_prefs_api.py+++ b/tests/test_workbench_prefs_api.py@@ -7,7 +7,7 @@ Mutations run at the ``vibe.api`` layer (like the Dock tests); the GET routes anthe session filter are exercised through the Flask-compat test client."""-from tests.test_ui_remote_access_auth import _save_config+from tests.ui_server_test_helpers import save_configfrom vibe import apifrom vibe.ui_server import app@@ -17,7 +17,7 @@ _NOW = "2026-07-16T00:00:00Z"def test_banner_pref_api_round_trip(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)from storage.importer import ensure_sqlite_stateensure_sqlite_state()@@ -36,7 +36,7 @@ def test_banner_pref_api_round_trip(monkeypatch, tmp_path):def test_banner_pref_get_route_defaults_on(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)from storage.importer import ensure_sqlite_stateensure_sqlite_state()@@ -67,7 +67,7 @@ def _seed_watch(engine, watch_id: str, session_id: str) -> None:def test_harness_bootstrap_scopes_watches_by_session(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)+ save_config(tmp_path)from storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_statediff --git a/tests/ui_server_test_helpers.py b/tests/ui_server_test_helpers.pyindex 4e9420a80..78917c4b4 100644--- a/tests/ui_server_test_helpers.py+++ b/tests/ui_server_test_helpers.py@@ -2,9 +2,46 @@ from __future__ import annotationsfrom urllib.parse import urlparse+from config.v2_config import (+ AgentsConfig,+ PlatformsConfig,+ RemoteAccessConfig,+ RuntimeConfig,+ SlackConfig,+ UiConfig,+ V2Config,+)from vibe import remote_access+def save_config(tmp_path) -> V2Config:+ config = V2Config(+ mode="self_host",+ version="v2",+ platform="slack",+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ ui=UiConfig(),+ remote_access=RemoteAccessConfig(),+ )+ cloud = config.remote_access.vibe_cloud+ cloud.enabled = True+ cloud.public_url = "https://alex.avibe.bot"+ cloud.client_id = "vr_client_123"+ cloud.instance_id = "inst_123"+ cloud.session_secret = "session-secret"+ cloud.authorization_endpoint = "https://backend.test/oauth/authorize"+ cloud.redirect_uri = "https://alex.avibe.bot/auth/callback"+ config.save()+ return config+++def remote_peer() -> dict[str, str]:+ return {"REMOTE_ADDR": "203.0.113.10"}++def remote_session_cookie(config,email: str,diff --git a/vibe/authorization.py b/vibe/authorization.pyindex 7e2bddc95..277d39744 100644--- a/vibe/authorization.py+++ b/vibe/authorization.py@@ -494,238 +494,6 @@ _EDITOR_HTTP_RULES = tuple())-'''_REMOTE_LOCAL_ONLY_HTTP_RULES = tuple(- (method, re.compile(pattern))- for method, pattern in (- ("DELETE", r"^/api/sessions/[^/]+(?:/queue/[^/]+)?$"),- ("POST", r"^/api/sessions/[^/]+/fork$"),- ("GET", r"^/api/sessions/[^/]+/draft$"),- ("PUT", r"^/api/sessions/[^/]+/draft$"),- ("POST", r"^/api/sessions/[^/]+/mark-read$"),- (- "POST",- r"^/api/sessions/[^/]+/(?:attachments|cancel|queue/[^/]+/send-now)$",- ),- ("POST", r"^/api/projects$"),- ("POST", r"^/api/asr/transcribe$"),- ("POST", r"^/api/show/sessions/[^/]+/(?:events|prewarm)$"),- ("GET", r"^/api/settings$"),- ("HEAD", r"^/api/settings$"),- ("POST", r"^/api/settings$"),- ("POST", r"^/api/settings/thread$"),- ("DELETE", r"^/api/settings/thread$"),- ("GET", r"^/api/bind-codes$"),- ("DELETE", r"^/api/projects/[^/]+$"),- ("GET", r"^/api/harness/(?:runs|bootstrap|runs/[^/]+)$"),- ("GET", r"^/api/vault/(?:pubkey|agent/pubkey|sandbox/root-metadata|vmk)$"),- ("GET", r"^/api/global-prompts$"),- # 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)$"),- ("HEAD", r"^/api/skills/(?:check|find)$"),- ("POST", r"^/api/vault/requests/(?:access|sign)$"),- ("GET", r"^/api/users$"),- ("HEAD", r"^/api/users$"),- )-)--_REMOTE_PAYLOAD_FILTERED_HTTP_RULES = tuple(- (method, re.compile(pattern))- for method, pattern in (- ("POST", r"^/api/(?:config|sessions)$"),- ("PATCH", r"^/api/(?:projects|sessions)/[^/]+$"),- )-)--# 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 (- # 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 mutations (read endpoints are viewer-allowed on origin/org).- (frozenset({"POST"}), r"^/api/skills$"),- (frozenset({"POST"}), r"^/api/skills/preview$"),- (frozenset({"POST", "DELETE"}), r"^/api/skills/(?: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|processing-record|failures|maintenance|profile|log|log/entry|search|runtime/(?:restart|rebuild|factory-reset|repair)|clear(?:/(?:resume|abort))?)$",- ),- # 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|cli-activity|cancel|mark-read|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$"),- (- _UNRESTRICTED_ORG_METHODS,- r"^/api/backend/(?:codex|claude|opencode)/auth/(?:oauth/(?:start|status/[^/]+|submit-code|cancel|remove)|api-key/remove|test)$",- ),- (- _UNRESTRICTED_ORG_METHODS,- r"^/api/backend/claude/auth/oauth/credentials/remove$",- ),- (_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(?:/[^/]+/[^/]+)?$"),- )-)--# 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 (- (frozenset({"GET", "HEAD", "POST"}), r"^/api/agent-onboarding$"),- (- frozenset({"GET", "HEAD"}),- r"^/api/agents/[^/]+$",- ),- (- frozenset({"GET", "HEAD"}),- r"^/api/vault/(?:settings|requests|requests/[^/]+|provision-requests/[^/]+|provision-requests/by-id/[^/]+|grants|audit)$",- ),- (- frozenset({"POST"}),- r"^/api/show-pages/[^/]+/ensure$",- ),- (- frozenset({"GET", "HEAD", "PUT"}),- r"^/api/show-pages/[^/]+/authorized-emails$",- ),- # Dock reads and writes are admitted only by the temporary Organization- # Apps matrix above; Workbench preference writes remain local-only.- # Reading push status stays remote, and so does the `POST` form of it:- # it reports this principal's own subscription count and can only- # re-attach a device id to an endpoint that is already stored and- # enabled for that same principal, so it can neither introduce an- # endpoint nor send to one.- #- # Registering and testing a subscription are different: the endpoint is- # caller-supplied data that `send_web_push()` later fetches from the- # Avibe host, and nothing between the payload and the request restricts- # it to a real push service. A remote caller could register an HTTPS- # endpoint aimed at loopback, a private LAN host or a rebinding name and- # then have this host issue the request from inside the network, so the- # write and the test stay local until the endpoint is checked against- # its resolved addresses.- (- frozenset({"GET", "HEAD"}),- r"^/api/web-push/(?:status|vapid-public-key)$",- ),- (frozenset({"POST"}), r"^/api/web-push/status$"),- (- frozenset({"PUT"}),- r"^/api/resource-policies/[^/]+/[^/]+$",- ),- (- frozenset({"GET", "HEAD"}),- r"^/api/models/(?:agents|events)$",- ),- (- frozenset({"GET", "HEAD"}),- r"^/api/models/agents/[^/]+/(?:sources|chain)$",- ),- (- frozenset({"GET", "HEAD"}),- r"^/api/models/turns/[^/]+/provenance$",- ),- # OAuth polling follows its flow: `oauth/start` and the Settings- # `auth/oauth/start` are local-only, so only the local owner can open a- # flow, while a status poll returns that flow's authorization URL and- # device code and - once the Model Hub flow succeeds - the same- # credential and account payload `/api/models/sources` deliberately- # keeps local. A remote caller holding a flow id would read the local- # owner's in-flight login, so both status routes stay local too.- (- frozenset({"GET", "HEAD"}),- r"^/api/remote-access/status$",- ),- (- frozenset({"GET", "HEAD"}),- r"^/api/harness/counts$",- ),- # Memory reads that describe this principal's own view stay remote, and- # search is scoped to the caller. Shared provider settings and the- # process-global failure log do not: both expose data across principals,- # so they stay trusted-local with the admin log and other sidecar-wide- # operations. Memory administration is absent for the same reason: a- # settings PATCH repoints the shared provider endpoints, and- # `runtime/restart` / `clear` act on the whole local sidecar rather than- # one principal.- (frozenset({"GET", "HEAD"}), r"^/api/memory/(?:status|profile)$"),- (frozenset({"POST"}), r"^/api/memory/search$"),- )-)'''--def _http_rule_matches(method: str,path: str,diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 9a4d756ff..899f220aa 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -1566,21 +1566,6 @@ def _is_ui_static_request() -> bool:return getattr(endpoint, "__name__", "") == "serve_static_compat_endpoint"-_PROJECT_RESOURCE_POLICY_WRITE = re.compile(r"^/api/resource-policies/[^/]+/[^/]+$")---def _project_resource_policy_write_path(path: str) -> bool:- """Resource policy write endpoints surface not_found for non-members.-- These routes stay classified ``local_only`` so the boundary still refuses- trusted-local writes from arbitrary remote callers, but active members and- owners pass through to the handler, which returns 404 to non-members so the- existence of an unrelated Organization's policy is not leaked.- """-- return bool(_PROJECT_RESOURCE_POLICY_WRITE.match(path))--def _oauth_cookie_signature(secret: str, payload: str) -> str:return hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()@@ -2484,128 +2469,6 @@ def enforce_instance_role_capabilities():return None-_REMOTE_CONFIG_MUTABLE_FIELDS = frozenset(- {- "ack_mode",- # Remote owners may choose how progress is presented, but the heartbeat- # cadence stays trusted-local because it directly controls edit timing.- "agent_progress_style",- "agent_status_no_output_ms",- "include_time_info",- "include_user_info",- "language",- "reply_enhancements",- "show_duration",- }-)-_REMOTE_UI_CONFIG_MUTABLE_FIELDS = frozenset(- {- "chat_message_font_size",- "instance_name",- "show_agent_activity",- "show_tool_calls",- }-)---def _payload_has_only_fields(payload: Any, fields: frozenset[str] | set[str]) -> bool:- return isinstance(payload, dict) and set(payload).issubset(fields)---def _payload_changes_values(payload: Any, current: Any) -> bool:- """Return whether supplied values differ from the persisted projection.-- Config saves accept both complete UI round-trips and partial updates. Comparing- only supplied leaves lets an unchanged complete payload pass while still- rejecting a remote caller that changes any protected value.- """-- if isinstance(payload, dict):- if not isinstance(current, dict):- return True- return any(- key not in current or _payload_changes_values(value, current[key])- for key, value in payload.items()- )- return payload != current---def _remote_config_payload_is_allowed(payload: Any) -> bool:- """Allow explicit UI/message preferences and unchanged config round-trips.-- Every other current or future config field is protected. A full payload from- GET /api/config remains valid only while all protected values are unchanged.- """-- if not isinstance(payload, dict):- return False- from vibe import api-- current = _load_remote_access_config()- if current is None:- return False- # Compare the request with the same JSON representation the browser received;- # catalog tuples become arrays on the wire and must not look like mutations.- current_payload = json.loads(json.dumps(api.config_to_payload(current)))- for field, value in payload.items():- if field in _REMOTE_CONFIG_MUTABLE_FIELDS:- continue- if field == "ui":- if not isinstance(value, dict):- return False- current_ui = current_payload.get("ui")- if not isinstance(current_ui, dict):- return False- if any(- ui_field not in _REMOTE_UI_CONFIG_MUTABLE_FIELDS- and (- ui_field not in current_ui- or _payload_changes_values(ui_value, current_ui[ui_field])- )- for ui_field, ui_value in value.items()- ):- return False- continue- if field not in current_payload or _payload_changes_values(- value,- current_payload[field],- ):- return False- return True---def _remote_mutable_config_payload(payload: dict[str, Any]) -> dict[str, Any]:- """Strip unchanged protected config fields before the persistence boundary."""-- mutable = {- field: value- for field, value in payload.items()- if field in _REMOTE_CONFIG_MUTABLE_FIELDS- }- ui = payload.get("ui")- if isinstance(ui, dict):- mutable_ui = {- field: value- for field, value in ui.items()- if field in _REMOTE_UI_CONFIG_MUTABLE_FIELDS- }- if mutable_ui:- mutable["ui"] = mutable_ui- return mutable---def _remote_payload_is_allowed(method: str, path: str, payload: Any) -> bool:- """Compatibility helper retained for callers; remote payloads are unrestricted."""-- return True---def _is_remote_local_execution_request(method: str, path: str, payload: Any = None) -> bool:- """Compatibility helper; the transitional local-only boundary is removed."""-- return False--_PROJECT_RESOURCE_PATHS = (("project", re.compile(r"^/api/projects/([^/]+)(?:/agents-md)?$")),("session", re.compile(r"^/api/sessions/([^/]+)(?:/.*)?$")),@@ -8978,9 +8841,6 @@ RESERVED_SESSION_PROTECTED_I18N_KEY = "harness.notice.workspaceSessionProtected"#: is not an answer to "why did my message not send", and the composer's own inert-state#: notice has to say the same thing this body says.RESERVED_SESSION_READ_ONLY_I18N_KEY = "harness.notice.workspaceSessionReadOnly"-REMOTE_EXECUTION_DISABLED_I18N_KEY = "harness.notice.remoteExecutionDisabled"--def _reserved_session_response(i18n_key: str, *, code: str = "reserved_session"):"""Shared 403 payload for a write refused because the RUNTIME reserves the session.@@ -9000,18 +8860,6 @@ def _reserved_session_response(i18n_key: str, *, code: str = "reserved_session")lang = settings_service.load_config_or_default().languagereturn _coded_error_response(code, t(i18n_key, lang), 403)--def _remote_execution_disabled_response():- from core.services import settings as settings_service-- lang = settings_service.load_config_or_default().language- return _coded_error_response(- "remote_execution_disabled",- t(REMOTE_EXECUTION_DISABLED_I18N_KEY, lang),- 403,- )--def _backend_locked_response(err):"""Shared 409 payload for a rejected cross-backend session change.@@ -12760,12 +12608,6 @@ 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)- 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# a public share visitor — may only author human input: a typed intent or