diff --git a/docs/webui.md b/docs/webui.md index 745396949..a4a55d5c8 100644 --- a/docs/webui.md +++ b/docs/webui.md @@ -178,7 +178,8 @@ or a result you must retain. Use the workspace picker before starting project-specific work. This gives the agent the right project context for file paths, shell commands, and topic metadata. A locally hosted WebUI opens the operating system's folder chooser -when one is available; remote deployments keep the manual absolute path entry. +when one is available; remote deployments use a manual absolute path on the +nanobot host. The browser's local filesystem is never used for project selection. Selecting a project does not replace the configured agent workspace. The two paths have different responsibilities: @@ -207,9 +208,10 @@ neighboring memory or profile files, and it does not allow writes outside the selected project. These tool exceptions do not broaden the browser's file preview boundary. -Remote WebUI connections may reduce access for the current workspace. Selecting a -different workspace or enabling Full Access remains limited to local and native -clients. +Remote WebUI connections may reduce access for the current workspace and may +select a different workspace by entering its server-side path. A remote project +change must use Restricted mode; enabling Full Access remains limited to local +and native clients. ## Composer diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py index d85cc4615..37a4b16be 100644 --- a/nanobot/channels/websocket/tests/test_websocket_channel.py +++ b/nanobot/channels/websocket/tests/test_websocket_channel.py @@ -2066,7 +2066,10 @@ async def test_remote_access_reduction_rejects_stale_in_flight_message_scope( @pytest.mark.asyncio -async def test_webui_scope_rejects_non_loopback_custom_scope(bus: MagicMock, tmp_path) -> None: +async def test_remote_webui_scope_rejects_full_access_for_custom_scope( + bus: MagicMock, + tmp_path, +) -> None: default_workspace = tmp_path / "default" project = tmp_path / "project" default_workspace.mkdir() @@ -2096,7 +2099,7 @@ async def test_webui_scope_rejects_non_loopback_custom_scope(bus: MagicMock, tmp payload = json.loads(conn.send.await_args.args[0]) assert payload["event"] == "error" assert payload["detail"] == "workspace_scope_rejected" - assert payload["reason"] == "workspace controls are localhost-only" + assert payload["reason"] == "full workspace access is unavailable for this connection" assert payload["chat_id"] == "chat-remote" assert sessions.read_session_file("websocket:chat-remote") is None diff --git a/nanobot/channels/websocket/tests/test_websocket_http_routes.py b/nanobot/channels/websocket/tests/test_websocket_http_routes.py index ade609824..450f7b527 100644 --- a/nanobot/channels/websocket/tests/test_websocket_http_routes.py +++ b/nanobot/channels/websocket/tests/test_websocket_http_routes.py @@ -2468,6 +2468,76 @@ async def test_webui_automation_result_is_authenticated_and_returns_only_selecte await server_task +@pytest.mark.asyncio +async def test_remote_new_chat_accepts_server_project_path_but_rejects_remote_full_access( + bus: MagicMock, tmp_path: Path +) -> None: + project = tmp_path / "remote-project" + other_project = tmp_path / "other-project" + project.mkdir() + other_project.mkdir() + channel = _ch(bus, workspace_path=tmp_path, port=_free_port()) + connection = AsyncMock() + connection.remote_address = ("192.168.1.5", 50123) + connection.request = _FakeReq( + { + "Host": "nas.example", + "X-Forwarded-For": "203.0.113.42", + } + ) + + await channel._dispatch_envelope( + connection, + "remote-webui", + { + "type": "new_chat", + "workspace_scope": { + "project_path": str(project), + "access_mode": "restricted", + }, + }, + ) + + attached = next( + payload + for payload in ( + json.loads(call.args[0]) for call in connection.send.await_args_list + ) + if payload.get("event") == "attached" + ) + key = f"websocket:{attached['chat_id']}" + scope = channel.gateway.workspaces.scope_for_session_key(key) + assert scope.project_path == project.resolve() + assert scope.access_mode == "restricted" + + connection.send.reset_mock() + await channel._dispatch_envelope( + connection, + "remote-webui", + { + "type": "new_chat", + "workspace_scope": { + "project_path": str(other_project), + "access_mode": "full", + }, + }, + ) + + rejected = [ + json.loads(call.args[0]) + for call in connection.send.await_args_list + if json.loads(call.args[0]).get("event") == "error" + ] + assert rejected == [ + { + "event": "error", + "detail": "workspace_scope_rejected", + "reason": "full workspace access is unavailable for this connection", + } + ] + + +@pytest.mark.asyncio async def test_webui_automations_route_lists_all_jobs_and_allows_user_actions( bus: MagicMock, tmp_path: Path ) -> None: @@ -3535,6 +3605,54 @@ async def test_workspace_folder_picker_is_local_authenticated_mutation( pick_folder.assert_awaited_once_with() +@pytest.mark.parametrize( + ("connection", "headers", "can_use_full_access", "can_pick_folder"), + [ + ( + _REMOTE, + {"Host": "nas.example", "X-Forwarded-For": "203.0.113.42"}, + False, + False, + ), + ( + _LOCAL, + {"Host": "nas.example", "X-Forwarded-For": "203.0.113.42"}, + False, + False, + ), + (_LOCAL, {"Host": "127.0.0.1:8765"}, True, True), + ], +) +@pytest.mark.parametrize("native_picker_available", [True, False]) +def test_workspace_payload_separates_remote_project_selection_from_full_access( + bus: MagicMock, + monkeypatch: pytest.MonkeyPatch, + native_picker_available: bool, + connection: _FakeConn, + headers: dict[str, str], + can_use_full_access: bool, + can_pick_folder: bool, +) -> None: + monkeypatch.setattr( + "nanobot.webui.ws_http.native_folder_picker_available", + lambda: native_picker_available, + ) + channel = _ch(bus) + token = channel.gateway.tokens.issue_api_token(300) + request = _FakeReq( + {"Authorization": f"Bearer {token}", **headers}, + path="/api/workspaces", + ) + + response = channel.gateway.http._handle_workspaces(connection, request) + + assert response.status_code == 200 + controls = json.loads(response.body.decode())["controls"] + assert controls["can_change_project"] is True + assert controls["can_use_full_access"] is can_use_full_access + assert controls["can_pick_folder"] is (can_pick_folder and native_picker_available) + + @pytest.mark.asyncio async def test_workspace_folder_picker_rejects_direct_http( bus: MagicMock, diff --git a/nanobot/webui/inbound_commands.py b/nanobot/webui/inbound_commands.py index 145329e35..4e17136a8 100644 --- a/nanobot/webui/inbound_commands.py +++ b/nanobot/webui/inbound_commands.py @@ -151,8 +151,11 @@ class WebUICommandRouter: self.request_operations: dict[str, WebUIRequestOperation] = {} self.request_locks: dict[ServerConnection, asyncio.Lock] = {} - def workspace_controls_available(self, connection: ServerConnection) -> bool: - return self._http_router.workspace_controls_available(connection) + def workspace_project_selection_available(self, connection: ServerConnection) -> bool: + return self._http_router.workspace_project_selection_available(connection) + + def workspace_full_access_available(self, connection: ServerConnection) -> bool: + return self._http_router.workspace_full_access_available(connection) async def send_webui_protocol_error( self, @@ -296,7 +299,8 @@ class WebUICommandRouter: connection, lambda: self._workspaces.scope_for_new_chat( envelope, - controls_available=self.workspace_controls_available(connection), + can_change_project=self.workspace_project_selection_available(connection), + can_use_full_access=self.workspace_full_access_available(connection), ), ) if scope is None: @@ -436,7 +440,8 @@ class WebUICommandRouter: envelope, chat_id=chat_id, chat_running=websocket_turn_wall_started_at(chat_id) is not None, - controls_available=self.workspace_controls_available(connection), + can_change_project=self.workspace_project_selection_available(connection), + can_use_full_access=self.workspace_full_access_available(connection), ), chat_id=chat_id, ) @@ -580,7 +585,8 @@ class WebUICommandRouter: envelope, chat_id=chat_id, chat_running=websocket_turn_wall_started_at(chat_id) is not None, - controls_available=self.workspace_controls_available(connection), + can_change_project=self.workspace_project_selection_available(connection), + can_use_full_access=self.workspace_full_access_available(connection), ) ), chat_id=chat_id, diff --git a/nanobot/webui/workspaces.py b/nanobot/webui/workspaces.py index 15b9ea88d..27902d13c 100644 --- a/nanobot/webui/workspaces.py +++ b/nanobot/webui/workspaces.py @@ -151,7 +151,8 @@ def workspaces_payload( *, default_workspace: Path, default_restrict_to_workspace: bool, - controls_available: bool, + can_change_project: bool, + can_use_full_access: bool, folder_picker_available: bool = False, ) -> dict[str, Any]: default_access_mode = read_webui_default_access_mode() @@ -169,8 +170,8 @@ def workspaces_payload( "default_access_mode": default_access_mode, "default_scope": default_scope.payload(), "controls": { - "can_change_project": controls_available, - "can_use_full_access": controls_available, + "can_change_project": can_change_project, + "can_use_full_access": can_use_full_access, "can_pick_folder": folder_picker_available, }, } @@ -254,13 +255,15 @@ class WebUIWorkspaceController: def payload( self, *, - controls_available: bool, + can_change_project: bool, + can_use_full_access: bool, folder_picker_available: bool = False, ) -> dict[str, Any]: return workspaces_payload( default_workspace=self._default_workspace, default_restrict_to_workspace=self._default_restrict_to_workspace, - controls_available=controls_available, + can_change_project=can_change_project, + can_use_full_access=can_use_full_access, folder_picker_available=folder_picker_available, ) @@ -269,7 +272,8 @@ class WebUIWorkspaceController: envelope: dict[str, Any], *, session_key: str | None, - controls_available: bool, + can_change_project: bool, + can_use_full_access: bool, ) -> WorkspaceScope: current = self.scope_for_session_key(session_key) if session_key else self.default_scope() raw = envelope.get(WORKSPACE_SCOPE_METADATA_KEY) @@ -282,20 +286,37 @@ class WebUIWorkspaceController: default_restrict_to_workspace=self._default_restrict_to_workspace, source_channel=_WEBUI_SCOPE_CHANNEL, ) - if not controls_available and not _scope_change_is_non_escalating(current, scope): - raise WorkspaceScopeError("workspace controls are localhost-only", status=403) + if not can_change_project and not _scope_change_is_non_escalating(current, scope): + raise WorkspaceScopeError( + "project selection is unavailable for this connection", + status=403, + ) + if ( + not can_use_full_access + and scope.access_mode == "full" + and ( + current.access_mode != "full" + or scope.project_path != current.project_path + ) + ): + raise WorkspaceScopeError( + "full workspace access is unavailable for this connection", + status=403, + ) return scope def scope_for_new_chat( self, envelope: dict[str, Any], *, - controls_available: bool, + can_change_project: bool, + can_use_full_access: bool, ) -> WorkspaceScope: return self.scope_from_envelope( envelope, session_key=None, - controls_available=controls_available, + can_change_project=can_change_project, + can_use_full_access=can_use_full_access, ) def scope_for_set_request( @@ -304,14 +325,16 @@ class WebUIWorkspaceController: *, chat_id: str, chat_running: bool, - controls_available: bool, + can_change_project: bool, + can_use_full_access: bool, ) -> WorkspaceScope: if chat_running: raise WorkspaceScopeError("chat_running", status=409) return self.scope_from_envelope( envelope, session_key=webui_session_key(chat_id), - controls_available=controls_available, + can_change_project=can_change_project, + can_use_full_access=can_use_full_access, ) def scope_for_message( @@ -320,12 +343,14 @@ class WebUIWorkspaceController: *, chat_id: str, chat_running: bool, - controls_available: bool, + can_change_project: bool, + can_use_full_access: bool, ) -> WorkspaceScope: scope = self.scope_from_envelope( envelope, session_key=webui_session_key(chat_id), - controls_available=controls_available, + can_change_project=can_change_project, + can_use_full_access=can_use_full_access, ) if ( WORKSPACE_SCOPE_METADATA_KEY in envelope diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index 998f58cf5..51ccdea78 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -407,8 +407,36 @@ class GatewayHTTPHandler: mcp_oauth_redirect_uri=self._mcp_oauth_redirect_uri, ) - def workspace_controls_available(self, connection: Any) -> bool: - return self._runtime_surface == "native" or _is_localhost(connection) + def workspace_project_selection_available(self, connection: Any) -> bool: + """Return whether an authenticated WebUI may submit a server path. + + Project paths are interpreted by the gateway, not by the browser. The + WebUI route and WebSocket handshake already authenticate the caller, + so remote clients can use the manual server-path picker as well. + """ + return True + + def workspace_full_access_available( + self, + connection: Any, + headers: Any | None = None, + ) -> bool: + """Return whether this request may opt into Full Access. + + A reverse proxy can make a remote browser look like a localhost TCP + peer. Inspect the original browser headers before granting this + capability so proxy-local requests keep the remote restriction. + """ + if self._runtime_surface == "native": + return True + if headers is None: + request = getattr(connection, "request", None) + headers = getattr(request, "headers", None) + if not isinstance(headers, Mapping): + # Lightweight in-process test connections do not carry a + # handshake request. Real WebSocket connections do. + return _is_localhost(connection) + return _is_local_browser_request(connection, headers) def workspace_folder_picker_available( self, @@ -1439,7 +1467,11 @@ class GatewayHTTPHandler: return _http_error(401, "Unauthorized") return _http_json_response( self.workspaces.payload( - controls_available=self.workspace_controls_available(connection), + can_change_project=self.workspace_project_selection_available(connection), + can_use_full_access=self.workspace_full_access_available( + connection, + request.headers, + ), folder_picker_available=self.workspace_folder_picker_available( connection, request, diff --git a/tests/utils/test_webui_workspaces.py b/tests/utils/test_webui_workspaces.py index 04d340421..0648bb6ec 100644 --- a/tests/utils/test_webui_workspaces.py +++ b/tests/utils/test_webui_workspaces.py @@ -35,7 +35,8 @@ def test_workspace_payload_is_config_data_dir_scoped(tmp_path, monkeypatch) -> N payload = workspaces_payload( default_workspace=default, default_restrict_to_workspace=False, - controls_available=True, + can_change_project=True, + can_use_full_access=True, ) assert payload["default_scope"]["project_path"] == str(default.resolve()) @@ -45,7 +46,7 @@ def test_workspace_payload_is_config_data_dir_scoped(tmp_path, monkeypatch) -> N assert payload["controls"]["can_pick_folder"] is False -def test_workspace_payload_hides_mutable_state_when_controls_unavailable( +def test_workspace_payload_allows_remote_project_selection_without_full_access( tmp_path, monkeypatch, ) -> None: @@ -56,15 +57,35 @@ def test_workspace_payload_hides_mutable_state_when_controls_unavailable( payload = workspaces_payload( default_workspace=default, default_restrict_to_workspace=False, - controls_available=False, + can_change_project=True, + can_use_full_access=False, ) assert payload["default_scope"]["project_path"] == str(default.resolve()) - assert payload["controls"]["can_change_project"] is False + assert payload["controls"]["can_change_project"] is True assert payload["controls"]["can_use_full_access"] is False assert payload["controls"]["can_pick_folder"] is False +def test_workspace_payload_hides_project_selection_when_unavailable( + tmp_path, + monkeypatch, +) -> None: + monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui") + default = tmp_path / "default" + default.mkdir() + + payload = workspaces_payload( + default_workspace=default, + default_restrict_to_workspace=False, + can_change_project=False, + can_use_full_access=False, + ) + + assert payload["controls"]["can_change_project"] is False + assert payload["controls"]["can_use_full_access"] is False + + def test_workspace_payload_advertises_native_folder_picker(tmp_path, monkeypatch) -> None: monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui") default = tmp_path / "default" @@ -73,7 +94,8 @@ def test_workspace_payload_advertises_native_folder_picker(tmp_path, monkeypatch payload = workspaces_payload( default_workspace=default, default_restrict_to_workspace=False, - controls_available=True, + can_change_project=True, + can_use_full_access=True, folder_picker_available=True, ) @@ -91,7 +113,8 @@ def test_workspace_payload_uses_webui_default_access_mode(tmp_path, monkeypatch) payload = workspaces_payload( default_workspace=default, default_restrict_to_workspace=True, - controls_available=True, + can_change_project=True, + can_use_full_access=True, ) assert payload["default_access_mode"] == "full" @@ -120,7 +143,11 @@ def test_webui_default_access_applies_to_unscoped_old_sessions(tmp_path, monkeyp ) scope = controller.scope_for_session_key("websocket:old-chat") - new_scope = controller.scope_for_new_chat({}, controls_available=True) + new_scope = controller.scope_for_new_chat( + {}, + can_change_project=True, + can_use_full_access=True, + ) assert scope.project_path == default.resolve() assert scope.access_mode == "full" @@ -301,7 +328,8 @@ def test_remote_existing_chat_can_reduce_its_workspace_access(tmp_path, monkeypa }, chat_id="remote-chat", chat_running=False, - controls_available=False, + can_change_project=True, + can_use_full_access=False, ) assert scope.project_path == project.resolve() @@ -313,10 +341,11 @@ def test_remote_existing_chat_can_reduce_its_workspace_access(tmp_path, monkeypa [ (False, "default", "restricted", True), (True, "default", "full", False), - (False, "other", "restricted", False), + (False, "other", "restricted", True), + (False, "other", "full", False), ], ) -def test_remote_new_chat_only_allows_non_escalating_scope_change( +def test_remote_new_chat_allows_project_selection_only_in_restricted_mode( tmp_path, monkeypatch, default_restricted: bool, @@ -344,7 +373,8 @@ def test_remote_new_chat_only_allows_non_escalating_scope_change( "access_mode": access_mode, } }, - controls_available=False, + can_change_project=True, + can_use_full_access=False, ) if allowed: @@ -352,5 +382,39 @@ def test_remote_new_chat_only_allows_non_escalating_scope_change( assert scope.project_path == requested_path.resolve() assert scope.access_mode == access_mode else: - with pytest.raises(WorkspaceScopeError, match="workspace controls are localhost-only"): + with pytest.raises( + WorkspaceScopeError, + match="full workspace access is unavailable for this connection", + ): resolve() + + +def test_project_selection_can_remain_disabled_for_untrusted_connections( + tmp_path, + monkeypatch, +) -> None: + monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui") + default = tmp_path / "default" + other = tmp_path / "other" + default.mkdir() + other.mkdir() + controller = WebUIWorkspaceController( + session_manager=None, + default_workspace=default, + default_restrict_to_workspace=True, + ) + + with pytest.raises( + WorkspaceScopeError, + match="project selection is unavailable for this connection", + ): + controller.scope_for_new_chat( + { + "workspace_scope": { + "project_path": str(other), + "access_mode": "restricted", + } + }, + can_change_project=False, + can_use_full_access=False, + ) diff --git a/webui/src/components/thread/WorkspaceControls.tsx b/webui/src/components/thread/WorkspaceControls.tsx index 23cfc6944..a98ee6e53 100644 --- a/webui/src/components/thread/WorkspaceControls.tsx +++ b/webui/src/components/thread/WorkspaceControls.tsx @@ -29,6 +29,7 @@ import { cn } from "@/lib/utils"; import { isAbsoluteWorkspacePath, projectNameFromPath, + sameWorkspacePath, scopeWithAccessMode, selectedProjectScope, shortWorkspacePath, @@ -81,7 +82,9 @@ export function WorkspaceProjectPicker({ && !!defaultScope && !!onChange && controls?.can_change_project !== false; - const pickFolder = getRuntimeHost().pickFolder ?? onPickFolder; + const pickFolder = controls?.can_pick_folder + ? getRuntimeHost().pickFolder ?? onPickFolder + : undefined; const nativeProjectPicker = !!pickFolder; useEffect(() => { @@ -115,16 +118,22 @@ export function WorkspaceProjectPicker({ setPathError(t("workspace.dialog.absolutePathRequired")); return; } + const accessMode = + controls?.can_use_full_access === false + && !sameWorkspacePath(trimmed, base.project_path) + ? "restricted" + : base.access_mode; onChange({ ...base, project_path: trimmed, project_name: projectName || projectNameFromPath(trimmed), - restrict_to_workspace: base.access_mode === "restricted", + access_mode: accessMode, + restrict_to_workspace: accessMode === "restricted", }); setPathError(null); setOpen(false); }, - [defaultScope, onChange, scope, t], + [controls?.can_use_full_access, defaultScope, onChange, scope, t], ); const pickNativeFolder = useCallback(async () => { diff --git a/webui/src/tests/thread-composer.test.tsx b/webui/src/tests/thread-composer.test.tsx index 7deb72144..4584577c5 100644 --- a/webui/src/tests/thread-composer.test.tsx +++ b/webui/src/tests/thread-composer.test.tsx @@ -1477,7 +1477,11 @@ describe("ThreadComposer", () => { variant="hero" workspaceScope={defaultScope} workspaceDefaultScope={defaultScope} - workspaceControls={{ can_change_project: true, can_use_full_access: true }} + workspaceControls={{ + can_change_project: true, + can_use_full_access: true, + can_pick_folder: true, + }} onWorkspaceScopeChange={onWorkspaceScopeChange} />, ); @@ -1494,6 +1498,57 @@ describe("ThreadComposer", () => { })); }); + it("does not use a native host picker when the gateway disallows folder picking", async () => { + const user = userEvent.setup(); + const onWorkspaceScopeChange = vi.fn(); + const pickFolder = vi.fn().mockResolvedValue("/Users/test/native-project"); + const onPickWorkspaceFolder = vi.fn().mockResolvedValue("/srv/nas-project"); + const defaultScope = { + project_path: "/srv/nanobot/workspace", + project_name: "workspace", + access_mode: "full" as const, + restrict_to_workspace: false, + }; + Object.defineProperty(window, "nanobotHost", { + configurable: true, + value: { pickFolder }, + }); + + render( + , + ); + + await user.click(screen.getByRole("button", { name: "Choose project" })); + + expect(await screen.findByLabelText("Paste path")).toBeInTheDocument(); + expect(pickFolder).not.toHaveBeenCalled(); + expect(onPickWorkspaceFolder).not.toHaveBeenCalled(); + + fireEvent.change(screen.getByLabelText("Paste path"), { + target: { value: "/srv/nas-project" }, + }); + fireEvent.click(screen.getByRole("button", { name: "Use Path" })); + + expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ + project_path: "/srv/nas-project", + access_mode: "restricted", + restrict_to_workspace: true, + })); + }); + it("uses the gateway folder picker for a locally hosted WebUI", async () => { const onWorkspaceScopeChange = vi.fn(); const pickFolder = vi.fn().mockResolvedValue("/Users/test/gateway-project");