fix(webui): enforce workspace authority across queued inputs

Keep workspace changes at the authenticated owner boundary. Queue follow-up inputs separately when their tool scope differs from the active run.

Co-authored-by: Tenable Research <152317477+tenbbughunters@users.noreply.github.com>
This commit is contained in:
Xubin RenandTenable Research committed 2026-11-04 23:33:49 +08:00
1 parent 4dd3fbecb6
commit 219dd13fd8
12 files changed
+381 -36

No files matched your search

+9 -2
View File
@@ -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:
+2 -6
View File
@@ -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)
@@ -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"):
@@ -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(
{
@@ -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)
@pytest.mark.parametrize("entrypoint", ["new_chat", "set_workspace_scope", "message"])
@pytest.mark.parametrize("audience", ["client", "webui"])
@pytest.mark.parametrize("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")
@pytest.mark.parametrize("stored", ["draft", "persisted"])
@pytest.mark.parametrize("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"
@pytest.mark.parametrize("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)
+32 -1
View File
@@ -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,
+20 -7
View File
@@ -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,
+1 -16
View File
@@ -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(