diff --git a/gns3server/api/routes/compute/virtualbox_nodes.py b/gns3server/api/routes/compute/virtualbox_nodes.py index 49e7f7316..b8fd10408 100644 --- a/gns3server/api/routes/compute/virtualbox_nodes.py +++ b/gns3server/api/routes/compute/virtualbox_nodes.py @@ -329,7 +329,8 @@ async def console_ws( Console WebSocket. """ - await node.start_websocket_console(websocket) + if websocket: + await node.start_websocket_console(websocket) @router.post( diff --git a/gns3server/api/routes/compute/vpcs_nodes.py b/gns3server/api/routes/compute/vpcs_nodes.py index 9d0fc86be..7eda1e95b 100644 --- a/gns3server/api/routes/compute/vpcs_nodes.py +++ b/gns3server/api/routes/compute/vpcs_nodes.py @@ -301,7 +301,8 @@ async def console_ws( Console WebSocket. """ - await node.start_websocket_console(websocket) + if websocket: + await node.start_websocket_console(websocket) @router.post( diff --git a/gns3server/api/routes/controller/nodes.py b/gns3server/api/routes/controller/nodes.py index e16442f3b..b83b0fd6e 100644 --- a/gns3server/api/routes/controller/nodes.py +++ b/gns3server/api/routes/controller/nodes.py @@ -33,7 +33,6 @@ from fastapi.routing import APIRoute from gns3server import schemas from gns3server.api.openapi import binary_request_body, binary_response -from gns3server.config import Config from gns3server.controller import Controller from gns3server.controller.controller_error import ( ControllerBadRequestError, @@ -859,19 +858,14 @@ async def ws_console( try: # forward WebSocket data in both directions between the client and the compute console WebSocket log.info(f"Forwarding console WebSocket to '{ws_console_compute_url}'") - server_config = Config.instance().settings.Server - user = server_config.compute_username - password = server_config.compute_password - if not user: - raise ControllerForbiddenError("Compute username is not set") - user = user.strip() - if user and password: - auth_header = aiohttp.encode_basic_auth(user, password.get_secret_value(), encoding="utf-8") - else: - auth_header = aiohttp.encode_basic_auth(user, "", encoding="utf-8") + # authenticate with the credentials of this compute, not with the local server + # credentials: they only match for the local compute + headers = {} + if compute.auth_header: + headers["Authorization"] = compute.auth_header ssl_context = Controller.instance().ssl_context() async with HTTPClient.get_client().ws_connect( - ws_console_compute_url, headers={"Authorization": auth_header}, ssl_context=ssl_context + ws_console_compute_url, headers=headers, ssl_context=ssl_context ) as ws: tasks = [ asyncio.ensure_future(ws_receive(ws)), @@ -959,19 +953,14 @@ async def vnc_console( try: # forward WebSocket data in both directions between the client and the compute VNC console WebSocket log.info(f"Forwarding VNC console WebSocket to '{vnc_console_compute_url}'") - server_config = Config.instance().settings.Server - user = server_config.compute_username - password = server_config.compute_password - if not user: - raise ControllerForbiddenError("Compute username is not set") - user = user.strip() - if user and password: - auth_header = aiohttp.encode_basic_auth(user, password.get_secret_value(), encoding="utf-8") - else: - auth_header = aiohttp.encode_basic_auth(user, "", encoding="utf-8") + # authenticate with the credentials of this compute, not with the local server + # credentials: they only match for the local compute + headers = {} + if compute.auth_header: + headers["Authorization"] = compute.auth_header ssl_context = Controller.instance().ssl_context() async with HTTPClient.get_client().ws_connect( - vnc_console_compute_url, headers={"Authorization": auth_header}, ssl_context=ssl_context + vnc_console_compute_url, headers=headers, ssl_context=ssl_context ) as ws: tasks = [ asyncio.ensure_future(vnc_receive(ws)), diff --git a/gns3server/controller/compute.py b/gns3server/controller/compute.py index be1e0fdba..347e0f7fa 100644 --- a/gns3server/controller/compute.py +++ b/gns3server/controller/compute.py @@ -23,6 +23,7 @@ import logging import socket import sys from asyncio import timeout as asynctimeout +from typing import Optional import aiohttp from fastapi import HTTPException @@ -295,6 +296,15 @@ class Compute: def password(self, value): self._set_auth(self._user, value) + @property + def auth_header(self) -> Optional[str]: + """ + Value for the Authorization header when sending requests to this compute, + or None when the compute has no user configured. + """ + + return self._auth + @property def cpu_usage_percent(self): return self._cpu_usage_percent diff --git a/tests/api/routes/compute/test_vpcs_nodes.py b/tests/api/routes/compute/test_vpcs_nodes.py index 3fd03cfe6..1c8de171d 100644 --- a/tests/api/routes/compute/test_vpcs_nodes.py +++ b/tests/api/routes/compute/test_vpcs_nodes.py @@ -14,12 +14,14 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -from unittest.mock import patch +from unittest.mock import AsyncMock, patch import pytest import pytest_asyncio from fastapi import FastAPI, status from httpx import AsyncClient +from httpx_ws import aconnect_ws +from httpx_ws.transport import ASGIWebSocketTransport from gns3server.compute.project import Project from tests.utils import asyncio_patch @@ -269,6 +271,23 @@ class TestVPCSNodesRoutes: assert response.status_code == status.HTTP_204_NO_CONTENT assert mock.called + async def test_vpcs_console_ws_rejects_invalid_credentials( + self, app: FastAPI, compute_client: AsyncClient, vm: dict + ) -> None: + # regression test: the console handler must not run after compute WebSocket + # authentication failed (it used to crash with "AttributeError: 'NoneType' + # object has no attribute 'client'", see issue #3076) + ws_path = f"/v3/compute/projects/{vm['project_id']}/vpcs/nodes/{vm['node_id']}/console/ws" + + with patch("gns3server.compute.vpcs.vpcs_vm.VPCSVM.start_websocket_console", new_callable=AsyncMock) as mock: + async with AsyncClient(base_url="http://test-api", transport=ASGIWebSocketTransport(app=app)) as ws_client: + async with aconnect_ws(ws_path, ws_client, auth=("wrong_user", "wrong_password")) as ws: + json_error = await ws.receive_json() + assert json_error["event"]["message"] == ( + "Could not authenticate while connecting to compute WebSocket: Could not validate credentials" + ) + assert not mock.called + # @pytest.mark.asyncio # async def test_vpcs_pcap(self, app: FastAPI, compute_client: AsyncClient, vm, compute_project: Project): # diff --git a/tests/api/routes/controller/test_nodes.py b/tests/api/routes/controller/test_nodes.py index facbf5e6e..ab3582379 100644 --- a/tests/api/routes/controller/test_nodes.py +++ b/tests/api/routes/controller/test_nodes.py @@ -996,6 +996,81 @@ class TestNodeConsoleWebSocketRoutes: assert websocket.sent == [] assert compute_ws.closed + @staticmethod + def _capturing_ws_connect(monkeypatch, messages: List[aiohttp.WSMessage], captured: dict) -> None: + """ + Same as _forward_compute_ws but records the URL and headers passed to + the compute ws_connect() call. + """ + + compute_ws = FakeComputeConsoleWebSocket(messages) + + def ws_connect(url, **kwargs): + captured["url"] = url + captured["headers"] = kwargs.get("headers") + return compute_ws + + monkeypatch.setattr( + HTTPClient, + "get_client", + classmethod(lambda cls: SimpleNamespace(ws_connect=ws_connect)), + ) + + async def test_console_ws_authenticates_with_compute_credentials( + self, compute_credentials, project: Project, controller, monkeypatch + ) -> None: + """ + The console WebSocket must authenticate with the credentials stored on the + compute, not with the local server credentials: a remote compute has its own + credentials and would always reject the local ones (issue #3076). + """ + + remote_compute = Compute( + "remote.example.com", + controller, + host="127.0.0.1", + port=3080, + user="remote-user", + password=SecretStr("remote-password"), + ) + node = Node(project, remote_compute, "test", node_type="vpcs") + project._nodes[node.id] = node + + captured: dict = {} + self._capturing_ws_connect( + monkeypatch, [aiohttp.WSMessage(aiohttp.WSMsgType.TEXT, "device output", None)], captured + ) + websocket = FakeClientWebSocket() + + await ws_console(websocket, current_user=MagicMock(), node=node) + + # the local server credentials ("admin"/"password", set by compute_credentials) must not be used + assert captured["headers"]["Authorization"] == aiohttp.encode_basic_auth( + "remote-user", "remote-password", encoding="utf-8" + ) + + async def test_console_ws_without_compute_user_sends_no_auth_header( + self, compute_credentials, project: Project, controller, monkeypatch + ) -> None: + """ + A compute without a user connects without an Authorization header, like any + other controller to compute request. + """ + + remote_compute = Compute("remote.example.com", controller, host="127.0.0.1", port=3080) + node = Node(project, remote_compute, "test", node_type="vpcs") + project._nodes[node.id] = node + + captured: dict = {} + self._capturing_ws_connect( + monkeypatch, [aiohttp.WSMessage(aiohttp.WSMsgType.TEXT, "device output", None)], captured + ) + websocket = FakeClientWebSocket() + + await ws_console(websocket, current_user=MagicMock(), node=node) + + assert "Authorization" not in captured["headers"] + class _FakeComputeWebSocket: """