Skip to content

Your lightweight open-source personal agent.

fix(webui): enforce workspace authority across queued inputs

Xubin Ren219dd13fd87e
diff --git a/docs/webui.md b/docs/webui.md
index b4d3bf240..ee2ad8eca 100644
--- a/docs/webui.md
+++ b/docs/webui.md
@@ -161,6 +161,10 @@ Temporary does not mean consequence-free. Requests still go to the configured mo
## Workspace and Access
+Project selection and Full Access controls require an owner-authenticated WebUI connection. Ordinary WebSocket clients stay within the workspace and access mode configured by the operator; an owner's saved topic scope or WebUI preference does not grant a client additional access. Existing topics remain available to the owner, while clients attempting to resume a topic outside their configured authority receive an error instead of silently changing its scope. Legacy plain-text clients use the same permission boundary. Keep the configured `tokenIssueSecret` (or fallback `token`) private: it can issue owner credentials. Share short-lived client connection tokens, not that owner secret.
+
+With unified sessions, inputs with different workspace permissions wait for the active turn to finish, then run with their own permissions. Inputs with the same scope can still join the active turn.
+
Use the workspace picker to browse folders on the connected nanobot host, enter an absolute path, or return to recent and starred projects; favorites persist across gateway restarts. The host name appears above saved locations. Project paths refer to that machine, not the browser's filesystem.
Choose the project when starting a new topic. Saved topics, including forks, keep their project directory fixed. Start a new topic for another project. You can still change access mode within the same project while the topic is idle.
diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py
index 183ef59b3..d1d8ae232 100644
--- a/nanobot/agent/loop.py
+++ b/nanobot/agent/loop.py
@@ -1125,7 +1125,7 @@ class AgentLoop:
except asyncio.QueueEmpty:
break
- async def _to_user_message(pending_msg: InboundMessage) -> dict[str, Any]:
+ async def _to_user_message(pending_msg: InboundMessage) -> dict[str, Any] | None:
content = pending_msg.content
image_paths = pending_msg.media if pending_msg.media else None
if image_paths:
@@ -1157,6 +1157,10 @@ class AgentLoop:
message_metadata=_prompt_scope_metadata(metadata),
session_metadata=_prompt_scope_metadata(session.metadata) if session is not None else None,
)
+ # A follow-up cannot inherit another input's tool authority.
+ # Leave it for the FIFO worker to run with its own scope.
+ if scope != effective_scope:
+ return None
pending_request = RequestContext(
channel=pending_msg.channel,
chat_id=pending_msg.chat_id,
@@ -1209,7 +1213,10 @@ class AgentLoop:
# owns completion, command dispatch, and control metadata.
if not self._can_inject_message(pending_msg):
break
- converted.append(await _to_user_message(pending_msg))
+ row = await _to_user_message(pending_msg)
+ if row is None:
+ break
+ converted.append(row)
consumed_inputs.append(pending_msg)
if execution_scope is not None:
try:
diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py
index be80fae6c..40dd98044 100644
--- a/nanobot/channels/websocket/runtime.py
+++ b/nanobot/channels/websocket/runtime.py
@@ -853,12 +853,8 @@ class WebSocketChannel(BaseChannel):
# WebSocket already authenticates at handshake time (token),
# so pairing is not applicable. Treat as non-DM to avoid
# sending pairing codes to an already-authenticated client.
- await self._handle_message(
- sender_id=client_id,
- chat_id=default_chat_id,
- content=content,
- metadata={"remote": getattr(connection, "remote_address", None)},
- is_dm=False,
+ await self._commands.dispatch_legacy_message(
+ connection, client_id, default_chat_id, content,
)
except Exception as e:
self.logger.debug("connection ended: {}", e)
diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py
index 5cf02730a..911387c4a 100644
--- a/nanobot/channels/websocket/tests/test_websocket_channel.py
+++ b/nanobot/channels/websocket/tests/test_websocket_channel.py
@@ -1782,6 +1782,7 @@ async def test_webui_message_scope_inherits_persisted_session_scope(
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=default_workspace),
)
conn = AsyncMock()
+ channel._webui_connections.add(conn)
conn.remote_address = ("127.0.0.1", 50123)
conn.request = SimpleNamespace(headers=Headers({"Host": "localhost:8765"}))
@@ -1847,6 +1848,7 @@ async def test_persisted_project_rejects_scope_changes_but_keeps_access_controls
await controller.persist_scope(chat_id, scope)
conn = AsyncMock()
+ channel._webui_connections.add(conn)
conn.remote_address = ("203.0.113.8", 50123)
await channel._dispatch_envelope(conn, "remote-client", {
"type": command, "chat_id": chat_id, "turn_id": "scope-change",
@@ -2018,6 +2020,7 @@ async def test_webui_scope_expands_home_project_path(
gateway=_basic_handler(bus, session_manager=SessionManager(tmp_path / "sessions"), workspace_path=default_workspace),
)
conn = AsyncMock()
+ channel._webui_connections.add(conn)
conn.remote_address = ("127.0.0.1", 50123)
await channel._dispatch_envelope(
@@ -2055,6 +2058,7 @@ async def test_webui_scope_rejects_missing_project_path(bus: MagicMock, tmp_path
gateway=_basic_handler(bus, session_manager=SessionManager(tmp_path / "sessions"), workspace_path=default_workspace),
)
conn = AsyncMock()
+ channel._webui_connections.add(conn)
conn.remote_address = ("127.0.0.1", 50123)
await channel._dispatch_envelope(
@@ -2092,6 +2096,7 @@ async def test_webui_scope_rejects_running_scope_change(bus: MagicMock, tmp_path
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=default_workspace),
)
conn = AsyncMock()
+ channel._webui_connections.add(conn)
conn.remote_address = ("127.0.0.1", 50123)
conn.request = SimpleNamespace(headers=Headers({"Host": "localhost:8765"}))
@@ -2151,6 +2156,7 @@ async def test_webui_set_workspace_scope_rejects_running_chat(bus: MagicMock, tm
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=default_workspace),
)
conn = AsyncMock()
+ channel._webui_connections.add(conn)
conn.remote_address = ("127.0.0.1", 50123)
await channel._dispatch_envelope(
@@ -2331,6 +2337,7 @@ async def test_remote_webui_scope_allows_full_access_for_custom_scope(
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=default_workspace),
)
conn = AsyncMock()
+ channel._webui_connections.add(conn)
conn.remote_address = ("203.0.113.8", 50123)
await channel._dispatch_envelope(
@@ -2375,6 +2382,7 @@ async def test_native_webui_scope_allows_custom_scope_without_loopback(
),
)
conn = AsyncMock()
+ channel._webui_connections.add(conn)
conn.remote_address = None
await channel._dispatch_envelope(
@@ -6862,6 +6870,7 @@ async def test_webui_access_mode_can_toggle_back_to_full(bus, tmp_path, headers)
default_restrict_to_workspace=True),
)
conn = AsyncMock()
+ channel._webui_connections.add(conn)
conn.remote_address = ("127.0.0.1", 50123)
conn.request = SimpleNamespace(headers=headers)
for mode in ("full", "restricted", "full"):
diff --git a/nanobot/channels/websocket/tests/test_websocket_http_routes.py b/nanobot/channels/websocket/tests/test_websocket_http_routes.py
index 71f589d52..75f8b8f76 100644
--- a/nanobot/channels/websocket/tests/test_websocket_http_routes.py
+++ b/nanobot/channels/websocket/tests/test_websocket_http_routes.py
@@ -2566,6 +2566,7 @@ async def test_session_delete_removes_unpersisted_new_chat(
project.mkdir()
channel = _ch(bus, session_manager=sm, workspace_path=tmp_path, port=_free_port())
connection = AsyncMock()
+ channel._webui_connections.add(connection)
connection.remote_address = ("127.0.0.1", 50123)
connection.request.headers = {"Host": "localhost"}
@@ -2716,6 +2717,7 @@ async def test_remote_new_chat_accepts_server_project_path_and_full_access(
other_project.mkdir()
channel = _ch(bus, workspace_path=tmp_path, port=_free_port())
connection = AsyncMock()
+ channel._webui_connections.add(connection)
connection.remote_address = ("192.168.1.5", 50123)
connection.request = _FakeReq(
{
diff --git a/nanobot/channels/websocket/tests/test_workspace_authority.py b/nanobot/channels/websocket/tests/test_workspace_authority.py
new file mode 100644
index 000000000..b4cb59b5f
--- /dev/null
+++ b/nanobot/channels/websocket/tests/test_workspace_authority.py
@@ -0,0 +1,216 @@
+"""Exercise credential authority from real loopback handshakes through file tools."""
+
+import asyncio
+from contextlib import asynccontextmanager
+
+import pytest
+
+from nanobot.agent.tools.filesystem import EditFileTool, ReadFileTool, WriteFileTool
+from nanobot.bus.queue import MessageBus
+from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
+from nanobot.security.workspace_access import (
+ WorkspaceScopeResolver,
+ bind_workspace_scope,
+ reset_workspace_scope,
+)
+from nanobot.session.manager import SessionManager
+from nanobot.webui.gateway_services import build_gateway_services
+from nanobot.webui.workspaces import write_webui_default_access_mode
+
+from .ws_test_client import WsTestClient
+
+
+@asynccontextmanager
+async def _running_gateway(tmp_path, *, restricted=True, surface="browser"):
+ workspace = tmp_path / "workspace"
+ project = tmp_path / "project"
+ workspace.mkdir()
+ project.mkdir()
+ (workspace / "canary.txt").write_text("ordinary-workspace")
+ (project / "canary.txt").write_text("owner-project")
+ bus = MessageBus()
+ cfg = WebSocketConfig.model_validate({
+ "enabled": True, "allowFrom": ["*"], "host": "127.0.0.1", "port": 0,
+ "path": "/ws", "websocketRequiresToken": True,
+ })
+ gateway = build_gateway_services(
+ config=cfg, bus=bus, config_path=tmp_path / "config.json",
+ session_manager=SessionManager(tmp_path / "sessions"),
+ static_dist_path=None, workspace_path=workspace, default_restrict_to_workspace=restricted,
+ runtime_model_name=None, runtime_surface=surface, runtime_capabilities_overrides=None,
+ )
+ channel = WebSocketChannel(cfg.model_dump(by_alias=True), bus, gateway=gateway)
+ task = asyncio.create_task(channel.start())
+ try:
+ async with asyncio.timeout(5):
+ while channel._server is None:
+ if task.done():
+ await task
+ await asyncio.sleep(0.01)
+ port = channel._server.sockets[0].getsockname()[1]
+ yield channel, f"ws://127.0.0.1:{port}/ws", workspace, project, bus
+ finally:
+ await channel.stop()
+ await task
+
+
+async def _result(client, event):
+ """Ignore hydration/broadcast events, but never ignore a command rejection."""
+ async with asyncio.timeout(5):
+ while True:
+ result = await client.recv_raw()
+ if result["event"] in (event, "error"):
+ return result
+
+
+async def _check_file_authority(msg, workspace, project, *, allowed, restricted=True):
+ scope = WorkspaceScopeResolver(workspace, default_restrict_to_workspace=restricted).for_turn(
+ channel="websocket", message_metadata=msg.metadata, session_metadata=None,
+ )
+ bound = bind_workspace_scope(scope)
+ try:
+ read = ReadFileTool(workspace=workspace, restrict_to_workspace=restricted)
+ write = WriteFileTool(workspace=workspace, restrict_to_workspace=restricted)
+ edit = EditFileTool(workspace=workspace, restrict_to_workspace=restricted)
+ outside = project / "canary.txt"
+ results = [
+ await read.execute(path=str(outside)),
+ await write.execute(path=str(project / "written.txt"), content="owner-write"),
+ await edit.execute(path=str(outside), old_text="owner-project", new_text="owner-edited"),
+ ]
+ if allowed:
+ assert "owner-project" in results[0]
+ assert (project / "written.txt").read_text() == "owner-write"
+ assert outside.read_text() == "owner-edited"
+ else:
+ assert all("outside allowed directory" in result for result in results)
+ assert "owner-project" not in results[0]
+ assert not (project / "written.txt").exists()
+ assert outside.read_text() == "owner-project"
+ assert "ordinary-workspace" in await read.execute(path="canary.txt")
+ await write.execute(path="local.txt", content="ordinary-write")
+ await edit.execute(path="local.txt", old_text="ordinary-write", new_text="ordinary-edit")
+ assert (workspace / "local.txt").read_text() == "ordinary-edit"
+ finally:
+ reset_workspace_scope(bound)
+
+
[email protected]("entrypoint", ["new_chat", "set_workspace_scope", "message"])
[email protected]("audience", ["client", "webui"])
[email protected]("selection", ["project", "full"])
+async def test_workspace_selection_requires_owner_on_wire(tmp_path, entrypoint, audience, selection):
+ async with _running_gateway(tmp_path) as (channel, uri, workspace, project, bus):
+ gateway = channel.gateway
+ token = gateway.tokens.issue_token(60, audience=audience)
+ async with WsTestClient(uri, token=token) as client:
+ await client.recv_ready()
+ chat_id = f"selected-{tmp_path.name}"
+ await client.send_json({
+ "type": entrypoint, "chat_id": chat_id, "content": "read canary", "webui": True,
+ "workspace_scope": {
+ "project_path": str(project if selection == "project" else workspace),
+ "access_mode": "restricted" if selection == "project" else "full",
+ },
+ })
+ if audience == "client":
+ result = await _result(client, {
+ "new_chat": "attached", "set_workspace_scope": "session_updated", "message": "error",
+ }[entrypoint])
+ assert result["event"] == "error", result
+ assert result["detail"] == "workspace_scope_rejected"
+ assert result["reason"] == "project selection is unavailable for this connection"
+ # Rejection precedes staging as well as persistence/agent dispatch.
+ assert not gateway.workspaces._draft_scopes
+ assert gateway.session_manager.list_sessions() == []
+ chat_id = "ordinary-topic"
+ elif entrypoint != "message":
+ result = await _result(client, "attached" if entrypoint == "new_chat" else "session_updated")
+ assert result["event"] != "error"
+ chat_id = result["chat_id"]
+ if audience == "client" or entrypoint != "message":
+ # No explicit scope: exercise the selected owner's draft or the
+ # ordinary client's operator-configured default, respectively.
+ await client.send_json({"type": "message", "chat_id": chat_id, "content": "read canary"})
+ msg = await asyncio.wait_for(bus.consume_inbound(), timeout=5)
+ assert msg.chat_id == chat_id # No rejected message preceded the safe one.
+ await _check_file_authority(msg, workspace, project, allowed=audience == "webui")
+
+
[email protected]("stored", ["draft", "persisted"])
[email protected]("selection", ["project", "full"])
+async def test_client_cannot_resume_owner_scope(tmp_path, stored, selection):
+ async with _running_gateway(tmp_path) as (channel, uri, workspace, project, bus):
+ gateway = channel.gateway
+ token = gateway.tokens.issue_token(60, audience="webui")
+ async with WsTestClient(uri, token=token) as owner:
+ await owner.recv_ready()
+ await owner.send_json({
+ "type": "new_chat", "workspace_scope": {
+ "project_path": str(project if selection == "project" else workspace),
+ "access_mode": "restricted" if selection == "project" else "full",
+ },
+ })
+ attached = await _result(owner, "attached")
+ assert attached["event"] == "attached"
+ chat_id = attached["chat_id"]
+ if stored == "persisted":
+ await owner.send_json({"type": "message", "chat_id": chat_id, "content": "hello"})
+ assert (await asyncio.wait_for(bus.consume_inbound(), timeout=5)).chat_id == chat_id
+ saved = gateway.workspaces.scope_for_session_key(f"websocket:{chat_id}")
+ token = gateway.tokens.issue_token(60)
+ async with WsTestClient(uri, token=token) as client:
+ await client.recv_ready()
+ for entrypoint in ("set_workspace_scope", "message"):
+ await client.send_json({"type": entrypoint, "chat_id": chat_id, "content": "read canary"})
+ assert (await _result(client, "error"))["detail"] == "workspace_scope_rejected"
+ assert gateway.workspaces.scope_for_session_key(f"websocket:{chat_id}") == saved
+ await client.send_json({"type": "message", "chat_id": "safe", "content": "hello"})
+ msg = await asyncio.wait_for(bus.consume_inbound(), timeout=5)
+ assert msg.chat_id == "safe"
+ await _check_file_authority(msg, workspace, project, allowed=False)
+
+
+async def test_legacy_frames_cannot_inherit_owner_scope(tmp_path):
+ async with _running_gateway(tmp_path) as (channel, uri, workspace, project, bus):
+ gateway = channel.gateway
+ token = gateway.tokens.issue_token(60)
+ async with WsTestClient(uri, token=token) as client:
+ ready = await client.recv_ready()
+ chat_id = ready.chat_id
+ await client.send_text("ordinary legacy message")
+ msg = await asyncio.wait_for(bus.consume_inbound(), timeout=5)
+ assert msg.metadata["workspace_scope"]["project_path"] == str(workspace.resolve())
+ # An owner may update a still-connected client's default chat.
+ owner_token = gateway.tokens.issue_token(60, audience="webui")
+ async with WsTestClient(uri, token=owner_token) as owner:
+ await owner.recv_ready()
+ await owner.send_json({
+ "type": "set_workspace_scope", "chat_id": chat_id,
+ "workspace_scope": {"project_path": str(workspace), "access_mode": "full"},
+ })
+ assert (await _result(owner, "session_updated"))["event"] == "session_updated"
+ for frame in ("read canary", '{"content":"read canary"}'):
+ await client.ws.send(frame)
+ assert (await _result(client, "error"))["detail"] == "workspace_scope_rejected"
+ await client.send_json({"type": "message", "chat_id": "safe", "content": "hello"})
+ msg = await asyncio.wait_for(bus.consume_inbound(), timeout=5)
+ assert msg.chat_id == "safe"
+
+
[email protected]("restricted", [True, False])
+async def test_client_uses_operator_config_not_owner_full_default(tmp_path, restricted):
+ # A native host permits owner Full Access; that capability is not client authority.
+ async with _running_gateway(tmp_path, restricted=restricted, surface="native") as (
+ channel, uri, workspace, project, bus,
+ ):
+ write_webui_default_access_mode("full")
+ token = channel.gateway.tokens.issue_token(60)
+ async with WsTestClient(uri, token=token) as client:
+ await client.recv_ready()
+ await client.send_json({"type": "new_chat"})
+ result = await _result(client, "attached")
+ assert result["event"] == "attached"
+ await client.send_json({"type": "message", "chat_id": result["chat_id"], "content": "hello"})
+ msg = await asyncio.wait_for(bus.consume_inbound(), timeout=5)
+ assert msg.metadata["workspace_scope"]["access_mode"] == ("restricted" if restricted else "full")
+ await _check_file_authority(msg, workspace, project, allowed=not restricted, restricted=restricted)
diff --git a/nanobot/webui/inbound_commands.py b/nanobot/webui/inbound_commands.py
index 13260705a..5ab8d71f6 100644
--- a/nanobot/webui/inbound_commands.py
+++ b/nanobot/webui/inbound_commands.py
@@ -164,7 +164,7 @@ class WebUICommandRouter:
self._message_locks: dict[tuple[str, str], tuple[asyncio.Lock, int]] = {}
def workspace_project_selection_available(self, connection: ServerConnection) -> bool:
- return self._http_router.workspace_project_selection_available(connection)
+ return connection in self._webui_connections
async def send_webui_protocol_error(
self,
@@ -286,6 +286,37 @@ class WebUICommandRouter:
)
return None
+ async def dispatch_legacy_message(
+ self,
+ connection: ServerConnection,
+ client_id: str,
+ chat_id: str,
+ content: str,
+ ) -> None:
+ """Authorize legacy text frames through the same workspace boundary."""
+ scope = await self.workspace_scope_or_error(
+ connection,
+ lambda: self._workspaces.scope_for_message(
+ {}, chat_id=chat_id, chat_running=False,
+ can_change_project=self.workspace_project_selection_available(connection),
+ ),
+ chat_id=chat_id,
+ )
+ if scope is None:
+ return
+ await self._transport.webui_dispatch_message(
+ sender_id=client_id, chat_id=chat_id, content=content,
+ media=None,
+ metadata={
+ "remote": getattr(connection, "remote_address", None),
+ WORKSPACE_SCOPE_METADATA_KEY: scope.metadata(),
+ },
+ is_dm=False,
+ session_key=None,
+ require_existing_session=False,
+ session_generation=None,
+ )
+
async def dispatch(
self,
connection: ServerConnection,
diff --git a/nanobot/webui/workspaces.py b/nanobot/webui/workspaces.py
index 2410b13cf..f239a6562 100644
--- a/nanobot/webui/workspaces.py
+++ b/nanobot/webui/workspaces.py
@@ -314,15 +314,20 @@ class WebUIWorkspaceController:
data = await self._sessions.state.read_metadata(session_key)
return self._scope_from_snapshot(data)
- def _scope_from_snapshot(self, data: dict[str, Any] | None) -> WorkspaceScope:
+ def _scope_from_snapshot(
+ self, data: dict[str, Any] | None, *, default_scope: WorkspaceScope | None = None,
+ ) -> WorkspaceScope:
+ if default_scope is None:
+ default_scope = self.default_scope()
if not isinstance(data, dict):
- return self.default_scope()
+ return default_scope
metadata = data.get("metadata", {})
if not isinstance(metadata, dict) or WORKSPACE_SCOPE_METADATA_KEY not in metadata:
- return self.default_scope()
+ return default_scope
metadata_data = cast(dict[str, Any], metadata)
return self._scope_from_metadata_value(
- cast(object, metadata_data.get(WORKSPACE_SCOPE_METADATA_KEY))
+ cast(object, metadata_data.get(WORKSPACE_SCOPE_METADATA_KEY)),
+ default_scope=default_scope,
)
def _validate_existing_project(self, metadata: Mapping[str, Any], scope: WorkspaceScope) -> None:
@@ -393,17 +398,23 @@ class WebUIWorkspaceController:
session_key: str | None,
can_change_project: bool,
) -> WorkspaceScope:
+ baseline = default_workspace_scope(
+ self._default_workspace,
+ self._default_restrict_to_workspace,
+ source_channel=_WEBUI_SCOPE_CHANNEL,
+ )
+ default = self.default_scope() if can_change_project else baseline
data = (
await self._sessions.state.read_metadata(session_key)
if self._sessions is not None and session_key else None
)
if data is not None:
- current = self._scope_from_snapshot(data)
+ current = self._scope_from_snapshot(data, default_scope=default)
elif session_key and (draft := self._draft_scopes.get(session_key)) is not None:
self._draft_scopes.move_to_end(session_key)
current = draft
else:
- current = self.default_scope()
+ current = default
raw = envelope.get(WORKSPACE_SCOPE_METADATA_KEY)
if raw is None:
scope = current
@@ -416,7 +427,9 @@ class WebUIWorkspaceController:
)
if data is not None:
self._validate_existing_project(data["metadata"], scope)
- if not can_change_project and not _scope_change_is_non_escalating(current, scope):
+ # An owner's draft, saved scope or UI preference cannot authorize a client.
+ # Its ceiling is operator config, including deliberately unrestricted use.
+ if not can_change_project and not _scope_change_is_non_escalating(baseline, scope):
raise WorkspaceScopeError(
"project selection is unavailable for this connection",
status=403,
diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py
index 3431d0295..516d5c1f1 100644
--- a/nanobot/webui/ws_http.py
+++ b/nanobot/webui/ws_http.py
@@ -448,15 +448,6 @@ class GatewayHTTPHandler:
mcp_oauth_redirect_uri=self._mcp_oauth_redirect_uri,
)
- 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 check_api_token(self, request: WsRequest) -> bool:
if getattr(request, "_nanobot_trusted_proxy_authenticated", False):
@@ -1726,15 +1717,13 @@ class GatewayHTTPHandler:
return _http_error(401, "Unauthorized")
return _http_json_response(
self.workspaces.payload(
- can_change_project=self.workspace_project_selection_available(connection),
+ can_change_project=True, # This HTTP route requires owner API authentication.
)
)
def _handle_workspace_favorite(self, connection: Any, request: WsRequest) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
- if not self.workspace_project_selection_available(connection):
- return _http_error(403, "project selection is unavailable for this connection")
payload = _mutation_payload(request) or {}
try:
favorites = self.workspaces.set_favorite_project(payload.get("path"), payload.get("pinned"))
@@ -1747,8 +1736,6 @@ class GatewayHTTPHandler:
async def _handle_workspace_resolve_project(self, connection: Any, request: WsRequest) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
- if not self.workspace_project_selection_available(connection):
- return _http_error(403, "project selection is unavailable for this connection")
payload = _mutation_payload(request) or {}
try:
project = self.workspaces.resolve_project(payload.get("path"))
@@ -1759,8 +1746,6 @@ class GatewayHTTPHandler:
async def _handle_workspace_directories(self, connection: Any, request: WsRequest) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
- if not self.workspace_project_selection_available(connection):
- return _http_error(403, "project selection is unavailable for this connection")
query = _parse_query(request.path)
try:
payload = await asyncio.to_thread(
diff --git a/tests/agent/test_session_inbox_controls.py b/tests/agent/test_session_inbox_controls.py
index 10646701a..8409fac93 100644
--- a/tests/agent/test_session_inbox_controls.py
+++ b/tests/agent/test_session_inbox_controls.py
@@ -17,6 +17,7 @@ from nanobot.cron.session_turns import CRON_DEFER_UNTIL_IDLE_META, CRON_TRIGGER_
from nanobot.goal.assembly import install_goal
from nanobot.providers.base import GenerationSettings, LLMResponse, LLMUsage, ToolCallRequest
from nanobot.runtime_context import public_history_messages
+from nanobot.security.workspace_access import current_workspace_scope
from nanobot.session.automation_turns import AUTOMATION_HISTORY_META
from nanobot.session.goal_state import GOAL_STATE_KEY
from nanobot.session.history_visibility import is_hidden_history_message
@@ -48,6 +49,49 @@ async def loop(tmp_path):
await agent.aclose()
[email protected]("followup_scope", ["same", "restricted", "other-project"])
+async def test_unified_followup_keeps_its_workspace_authority(loop, tmp_path, followup_scope):
+ loop._unified_session = True
+ project = tmp_path / "other-project"
+ project.mkdir()
+ initial_scope = {"project_path": str(tmp_path), "access_mode": "full"}
+ next_scope = {
+ "project_path": str(project if followup_scope == "other-project" else tmp_path),
+ "access_mode": "restricted" if followup_scope == "restricted" else "full",
+ }
+ observed = []
+
+ async def chat(**kwargs):
+ scope = current_workspace_scope()
+ observed.append(scope.metadata())
+ if len(observed) == 1:
+ await loop.bus.publish_inbound(InboundMessage(
+ channel="websocket", sender_id="client", chat_id="followup", content="second",
+ metadata={"workspace_scope": next_scope},
+ ))
+ async with asyncio.timeout(3):
+ while loop._pending_queues["unified:default"].empty():
+ await asyncio.sleep(0)
+ return LLMResponse(content="done")
+
+ loop.provider.chat_stream_with_retry = chat
+ loop.runner.run = AsyncMock(wraps=loop.runner.run)
+ worker = asyncio.create_task(loop.run())
+ try:
+ await loop.bus.publish_inbound(InboundMessage(
+ channel="websocket", sender_id="owner", chat_id="initial", content="first",
+ metadata={"workspace_scope": initial_scope},
+ ))
+ async with asyncio.timeout(5):
+ while not observed or "unified:default" in loop._pending_queues:
+ await asyncio.sleep(0.01)
+ assert observed == [initial_scope, next_scope]
+ assert loop.runner.run.await_count == (1 if followup_scope == "same" else 2)
+ finally:
+ loop.stop()
+ await asyncio.wait_for(worker, timeout=3)
+
+
@pytest.mark.parametrize("rejection", ["stop", "followup", "replaced-followup", "idle"])
async def test_rejected_input_does_not_stop_other_sessions(loop, monkeypatch, rejection):
state = loop.sessions.state
diff --git a/tests/agent/tools/test_runtime_control.py b/tests/agent/tools/test_runtime_control.py
index 1313d8487..06debf52c 100644
--- a/tests/agent/tools/test_runtime_control.py
+++ b/tests/agent/tools/test_runtime_control.py
@@ -500,7 +500,8 @@ async def test_access_changes_refresh_only_new_message_and_preserve_prefix(tmp_p
@pytest.mark.asyncio
-async def test_injected_channel_input_reports_active_tool_scope(tmp_path: Path) -> None:
[email protected]("same_scope", [True, False])
+async def test_followup_only_joins_matching_tool_scope(tmp_path: Path, same_scope: bool) -> None:
project = tmp_path / "project"
project.mkdir()
(project / "marker.txt").write_text("active project", encoding="utf-8")
@@ -517,7 +518,8 @@ async def test_injected_channel_input_reports_active_tool_scope(tmp_path: Path)
session.add_message("user", "Start")
await loop.sessions.state.prepare_input(session)
pending = asyncio.Queue()
- await pending.put(InboundMessage("telegram", "user", "chat", "Read marker.txt"))
+ followup = InboundMessage("websocket" if same_scope else "telegram", "user", "chat", "Read marker.txt")
+ await pending.put(followup)
await loop._run_agent_loop(
TranscriptInput(history=session.get_history(), current_message=None),
runtime=loop.llm_runtime(), session=session, pending_queue=pending,
@@ -525,8 +527,14 @@ async def test_injected_channel_input_reports_active_tool_scope(tmp_path: Path)
)
calls = loop.provider.chat_stream_with_retry.await_args_list
context = calls[0].kwargs["messages"][-1]["content"]
- assert json.dumps(str(project.resolve())) in context
- assert "File access: project and tool-specific allowed paths only." in context
+ if same_scope:
+ assert json.dumps(str(project.resolve())) in context
+ assert "File access: project and tool-specific allowed paths only." in context
+ assert pending.empty()
+ else:
+ assert context == "Start"
+ assert pending.get_nowait() is followup
+ assert pending.empty()
assert any(message.get("role") == "tool" and "active project" in message["content"]
for message in calls[1].kwargs["messages"])
diff --git a/tests/utils/test_webui_workspaces.py b/tests/utils/test_webui_workspaces.py
index 251d7ac19..faa37df99 100644
--- a/tests/utils/test_webui_workspaces.py
+++ b/tests/utils/test_webui_workspaces.py
@@ -112,6 +112,36 @@ async def test_webui_default_access_applies_to_unscoped_old_sessions(tmp_path, m
assert new_scope.access_mode == "full"
[email protected]("scope_present", [False, True])
+async def test_old_session_scope_defaults_respect_connection_authority(
+ tmp_path, monkeypatch, scope_present: bool,
+) -> None:
+ monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
+ default = tmp_path / "default"
+ default.mkdir()
+ sessions = SessionManager(tmp_path / "sessions")
+ session = sessions.get_or_create("websocket:legacy")
+ if scope_present:
+ session.metadata[WORKSPACE_SCOPE_METADATA_KEY] = None
+ sessions.save(session)
+ write_webui_default_access_mode("full")
+ controller = WebUIWorkspaceController(
+ session_manager=sessions, default_workspace=default, default_restrict_to_workspace=True,
+ )
+
+ client_scope = await controller.scope_for_message(
+ {}, chat_id="legacy", chat_running=False, can_change_project=False,
+ )
+ owner_scope = await controller.scope_for_message(
+ {}, chat_id="legacy", chat_running=False, can_change_project=True,
+ )
+
+ assert client_scope.project_path == default.resolve()
+ assert client_scope.access_mode == "restricted"
+ assert owner_scope.access_mode == ("restricted" if scope_present else "full")
+ assert sessions.read_session_metadata("websocket:legacy")["metadata"] == session.metadata
+
+
def test_indexed_scope_preserves_missing_and_explicit_null_semantics(tmp_path, monkeypatch) -> None:
monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
default = tmp_path / "default"