From 6d6b5351fabc2b4843bdd5a200f87cb301fffdc9 Mon Sep 17 00:00:00 2001 From: YueGuobin Date: Sat, 29 Aug 2026 01:00:12 +0800 Subject: [PATCH] fix: issue short-lived console tickets instead of JWTs in node_console MCP tool LLM clients transcribing the console WebSocket URL into shell commands reliably corrupted the ~200-char JWT embedded in it (dropped header segment -> "MissingAlgorithmError: Missing 'alg' value in header" on every connection attempt). The node_console tool now mints a short random ticket ("gns3t_" + 16 urlsafe chars, 10 min TTL, multi-use) stored server-side and bound to the node's console endpoints: - new ConsoleTicketService (gns3server/services/console_tickets.py), in-memory store with lazy expiry sweeps - get_current_active_user_from_websocket redeems tickets through the existing "token" query parameter, gated on websocket.path_params so a ticket only authenticates the console/ws and console/vnc routes of the node it was minted for; the JWT path is unchanged - redemption reuses the existing user lookup, token_version revocation and is_active checks, so logging out invalidates outstanding tickets - vnc_url no longer embeds the full session JWT - the tool docstring now tells clients to run the returned command verbatim instead of reconstructing the URL --- docs/features/mcp-service.md | 6 +- docs/features/vnc-websocket-console.md | 4 +- .../gns3_copilot/gns3_client/api_handlers.py | 31 ++- gns3server/agent/mcp/__init__.py | 24 +- .../controller/dependencies/authentication.py | 24 +- gns3server/services/__init__.py | 2 + gns3server/services/console_tickets.py | 115 +++++++++ tests/agent/mcp/test_handlers.py | 28 +++ .../routes/controller/test_console_tickets.py | 227 ++++++++++++++++++ 9 files changed, 431 insertions(+), 30 deletions(-) create mode 100644 gns3server/services/console_tickets.py create mode 100644 tests/api/routes/controller/test_console_tickets.py diff --git a/docs/features/mcp-service.md b/docs/features/mcp-service.md index 3dbfdbbd4..c3381343c 100644 --- a/docs/features/mcp-service.md +++ b/docs/features/mcp-service.md @@ -439,7 +439,7 @@ sequenceDiagram ### Console WebSocket -The `node_console` tool returns a WebSocket URL for connecting to a node's console. The URL includes a short-lived JWT (10 min) — reconnect if it expires. This endpoint is protocol-agnostic — it works for **telnet**, **ssh**, and **vnc** console types alike. The WebSocket simply proxies raw byte streams between the client and the compute node; protocol negotiation (e.g. SSH key exchange) happens on the compute side. +The `node_console` tool returns a WebSocket URL for connecting to a node's console. The URL includes a short-lived **console ticket** (10 min) — a short random string (`gns3t_…`, 22 chars) minted server-side and bound to that node's console endpoints. Tickets replaced the long JWT previously embedded here: LLM clients retyping the URL into shell commands reliably corrupted a ~200-char JWT, while a short ticket survives copying. Re-request the URL when the ticket expires (logging out also invalidates outstanding tickets). This endpoint is protocol-agnostic — it works for **telnet**, **ssh**, and **vnc** console types alike. The WebSocket simply proxies raw byte streams between the client and the compute node; protocol negotiation (e.g. SSH key exchange) happens on the compute side. The WebSocket URL is constructed using the server's `_server_url()`, which resolves the host as follows: @@ -454,11 +454,11 @@ When `Server.host` is `0.0.0.0` (listen on all interfaces), the MCP server disco If the configured host is already a specific IP or hostname (not `0.0.0.0`), it is used directly in the URL without modification. -Use `websocat` to connect from the command line: +Use `websocat` to connect from the command line (use the `command` returned by `node_console` verbatim — never reconstruct the URL by hand): ```bash # The host in the URL is automatically resolved to a reachable address -websocat ws://192.168.1.3:3080/v3/projects/{project_id}/nodes/{node_id}/console/ws?token= +websocat ws://192.168.1.3:3080/v3/projects/{project_id}/nodes/{node_id}/console/ws?token= ``` ### Source Files diff --git a/docs/features/vnc-websocket-console.md b/docs/features/vnc-websocket-console.md index 41b2a2ec2..b117ad152 100644 --- a/docs/features/vnc-websocket-console.md +++ b/docs/features/vnc-websocket-console.md @@ -58,7 +58,7 @@ graph LR **URL**: `ws://{controller_host}:{port}/v3/projects/{project_id}/nodes/{node_id}/console/vnc?token={jwt_token}` **Authentication**: -- JWT token via query parameter +- JWT token via query parameter, **or** a short-lived console ticket (`gns3t_…`, minted per node by the `node_console` MCP tool, valid 10 min, bound to this node's console endpoints) - User must have `Node.Console` privilege **WebSocket Subprotocols**: @@ -179,7 +179,7 @@ sequenceDiagram 1. **Authentication**: - JWT token validation via `has_privilege_on_websocket("Node.Console")` dependency - - Token passed as query parameter: `?token={jwt}` + - Token passed as query parameter: `?token={jwt}`, or a console ticket (`gns3t_…`) redeemable only on the node it was minted for 2. **Authorization**: - RBAC privilege check: `Node.Console` diff --git a/gns3server/agent/gns3_copilot/gns3_client/api_handlers.py b/gns3server/agent/gns3_copilot/gns3_client/api_handlers.py index 2dcec5afa..e8acdfc06 100644 --- a/gns3server/agent/gns3_copilot/gns3_client/api_handlers.py +++ b/gns3server/agent/gns3_copilot/gns3_client/api_handlers.py @@ -53,7 +53,8 @@ from concurrent.futures import ThreadPoolExecutor import hashlib import logging -from gns3server.services import auth_service +from gns3server.services import auth_service, console_ticket_service +from gns3server.services.console_tickets import DEFAULT_TICKET_TTL from gns3server.agent.gns3_copilot.gns3_client.connector import Gns3Connector @@ -416,12 +417,21 @@ def get_node_console_info_handler(params: dict[str, Any], gns3_ctx: dict[str, An node = conn.http_call("get", f"{conn.base_url}/projects/{project_id}/nodes/{node_id}").json() console_type = node.get("console_type", "unknown") - # Short-lived JWT for the WebSocket URL (10 min) + # Short-lived console ticket (10 min, multi-use, bound to this node's + # console endpoints). Deliberately a short random string instead of a JWT: + # LLM clients retype this URL into shell commands and reliably corrupted + # the ~200-char JWT previously embedded here (dropped header segment → + # "Missing 'alg' value in header" on the server). username = gns3_ctx.get("jwt_username") - ws_token = auth_service.create_access_token(username, token_version=gns3_ctx.get("jwt_token_version", 0), expires_in=10) if username else None + ticket = console_ticket_service.mint( + username, + token_version=gns3_ctx.get("jwt_token_version", 0), + project_id=project_id, + node_id=node_id, + ) if username else None raw_url = f"{gns3_ctx['server_url']}/v3/projects/{project_id}/nodes/{node_id}/console/ws" - if ws_token: - raw_url += f"?token={ws_token}" + if ticket: + raw_url += f"?token={ticket}" # Convert http scheme to ws for direct websocat usage ws_url = raw_url.replace("https://", "wss://").replace("http://", "ws://") @@ -432,14 +442,15 @@ def get_node_console_info_handler(params: dict[str, Any], gns3_ctx: dict[str, An "ws_url": ws_url, "command": f"websocat -t --no-close {ws_url}", } - if ws_token: + if ticket: # Fingerprint of the minted token: compare it against what actually reached the # server (logged on WebSocket auth rejection) to detect copy corruption, and # re-request the URL once token_ttl_seconds has elapsed. - result["token_sha256_prefix"] = hashlib.sha256(ws_token.encode()).hexdigest()[:8] - result["token_ttl_seconds"] = 600 - if console_type in ("vnc",): - result["vnc_url"] = f"/v3/projects/{project_id}/nodes/{node_id}/console/vnc?token={gns3_ctx['jwt_token']}" + result["token_sha256_prefix"] = hashlib.sha256(ticket.encode()).hexdigest()[:8] + result["token_ttl_seconds"] = DEFAULT_TICKET_TTL + if console_type in ("vnc",) and ticket: + # Same node binding covers the vnc endpoint (identical path params) + result["vnc_url"] = f"/v3/projects/{project_id}/nodes/{node_id}/console/vnc?token={ticket}" return result diff --git a/gns3server/agent/mcp/__init__.py b/gns3server/agent/mcp/__init__.py index a74031f5d..1caaa85fe 100644 --- a/gns3server/agent/mcp/__init__.py +++ b/gns3server/agent/mcp/__init__.py @@ -557,21 +557,19 @@ async def node_console( ) -> list[dict[str, Any]]: """Get WebSocket console connection info for a node. - Returns the WebSocket URL, console type (telnet/ssh/vnc), and other - connection details needed to interact with a node's console via WebSocket. - The URL includes a short-lived JWT (10 min) — reconnect if it expires. + Returns the console type (telnet/ssh/vnc) and a ready-to-run websocat + command with a short-lived access token (10 min) already embedded. - Complete workflow: - 1. Call this tool with project_id and node_id to get the WebSocket URL - 2. Connect to the returned URL using websocat in text mode (-t): - > websocat -t --no-close "ws://:3080/v3/projects/{project_id}/nodes/{node_id}/console/ws?token={jwt_token}" - 3. Send device commands with \\r\\n line endings via heredoc: - > websocat -t --no-close "ws://..." <<< $'\\r\\nenable\\r\\nshow version\\r\\nexit\\r\\n' - 4. Receive response: websocat receives and displays device output - Use 'timeout' to avoid connection hanging: - > timeout 10 websocat -t --no-close "ws://..." <<< $'commands\\r\\n' + IMPORTANT — copy the returned values EXACTLY: + - Run the returned "command" string verbatim; it already contains the + full URL with token. NEVER construct or edit the URL yourself, and + NEVER copy the token by hand — a mistyped token is rejected. + - The token expires after token_ttl_seconds (10 min): call this tool + again to get a fresh one; do not reuse an old URL. + + Sending device commands after connecting: + > timeout 10 websocat -t --no-close "ws://..." <<< $'\\r\\nenable\\r\\nshow version\\r\\nexit\\r\\n' - Key points: - Use \\r\\n (not \\n) to match console protocol line endings - Use $'...' format for escape sequences in bash - --no-close keeps the WebSocket open after stdin (heredoc) hits EOF, so diff --git a/gns3server/api/routes/controller/dependencies/authentication.py b/gns3server/api/routes/controller/dependencies/authentication.py index 1712155cd..7ff79cb4f 100644 --- a/gns3server/api/routes/controller/dependencies/authentication.py +++ b/gns3server/api/routes/controller/dependencies/authentication.py @@ -29,7 +29,9 @@ import gns3server.db.models as models from gns3server.db.repositories.api_keys import ApiKeysRepository from gns3server.db.repositories.users import UsersRepository from gns3server.db.repositories.rbac import RbacRepository -from gns3server.services import auth_service +from gns3server.schemas.controller.tokens import TokenData +from gns3server.services import auth_service, console_ticket_service +from gns3server.services.console_tickets import TICKET_PREFIX from .database import get_repository log = logging.getLogger(__name__) @@ -149,7 +151,25 @@ async def get_current_active_user_from_websocket( await websocket.accept(subprotocol=subprotocol) try: - token_data = auth_service.get_token_data(token) + if token.startswith(TICKET_PREFIX): + # Console tickets ("gns3t_…"): short-lived credentials bound to one + # node's console endpoints, minted by the node_console MCP tool. + # redeem() confines them to the route matching their binding, so + # they cannot authenticate the notification/wireshark sockets that + # share this dependency. + ticket = console_ticket_service.redeem(token, websocket.path_params) + if ticket is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid or expired console ticket", + ) + token_data = TokenData( + username=ticket.username, + token_version=ticket.token_version, + token_use="access", + ) + else: + token_data = auth_service.get_token_data(token) _reject_refresh_token(token_data) user = await user_repo.get_user_by_username(token_data.username) diff --git a/gns3server/services/__init__.py b/gns3server/services/__init__.py index f9be542e2..f44e732a2 100644 --- a/gns3server/services/__init__.py +++ b/gns3server/services/__init__.py @@ -15,5 +15,7 @@ # along with this program. If not, see . from .authentication import AuthService +from .console_tickets import ConsoleTicketService auth_service = AuthService() +console_ticket_service = ConsoleTicketService() diff --git a/gns3server/services/console_tickets.py b/gns3server/services/console_tickets.py new file mode 100644 index 000000000..6f238ac28 --- /dev/null +++ b/gns3server/services/console_tickets.py @@ -0,0 +1,115 @@ +# +# Copyright (C) 2026 GNS3 Technologies Inc. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Short-lived console tickets. + +A console ticket is a short random string ("gns3t_" + 16 urlsafe chars) that +replaces the long JWT previously embedded in console WebSocket URLs returned +to LLM clients, which reliably corrupted the ~200-char JWT when retyping it +into a shell command. The ticket carries no information itself — the server +remembers what it maps to, which is what makes a 96-bit random string a +sufficient credential. + +Tickets are bound to a single node's console endpoints (console/ws and +console/vnc share the same binding) and are multi-use within their TTL, so +console clients that reconnect after a drop keep working. Redeeming also +re-checks the minting user's token_version, so logging out invalidates +outstanding tickets just like it invalidates JWTs. +""" + +import logging +import secrets +import time +from dataclasses import dataclass +from typing import Optional + +log = logging.getLogger(__name__) + +# Distinguishes tickets from JWTs (which contain dots) and API keys ("gns3_") +TICKET_PREFIX = "gns3t_" +DEFAULT_TICKET_TTL = 600 # seconds + + +@dataclass +class ConsoleTicket: + username: str + token_version: int + project_id: str + node_id: str + expires_at: float # time.monotonic() based + + +class ConsoleTicketService: + """ + In-memory store for console tickets. + + Single-process asyncio app: minting (MCP tool handlers, via worker + threads) and redemption (WS auth dependency, event loop) share one dict. + dict get/set/del are atomic under the GIL and keys are random, so no + locking is needed. Tickets vanish on restart — clients just request a + new one. + """ + + def __init__(self) -> None: + self._tickets: dict[str, ConsoleTicket] = {} + + def mint( + self, + username: str, + token_version: int, + project_id: str, + node_id: str, + ttl: int = DEFAULT_TICKET_TTL, + ) -> str: + # 12 random bytes → 16 urlsafe chars (~96 bits); comfortably + # unguessable within the 10-minute window and short enough that + # LLM clients copy it without corruption. + ticket = TICKET_PREFIX + secrets.token_urlsafe(12) + self._sweep_expired() + self._tickets[ticket] = ConsoleTicket( + username=username, + token_version=token_version, + project_id=project_id, + node_id=node_id, + expires_at=time.monotonic() + ttl, + ) + return ticket + + def redeem(self, ticket: str, path_params: dict) -> Optional[ConsoleTicket]: + """ + Validate a ticket against the route it is being used on. + + Returns the ticket record if valid, None otherwise. The route's path + parameters must match the ticket's binding, which confines a ticket + to the node's console endpoints — routes without a node_id path + parameter (notifications, web wireshark, …) always fail the binding. + """ + + record = self._tickets.get(ticket) + if record is None: + return None + if time.monotonic() >= record.expires_at: + self._tickets.pop(ticket, None) + return None + if path_params.get("project_id") != record.project_id or path_params.get("node_id") != record.node_id: + return None + return record + + def _sweep_expired(self) -> None: + now = time.monotonic() + for ticket in [t for t, record in self._tickets.items() if now >= record.expires_at]: + del self._tickets[ticket] diff --git a/tests/agent/mcp/test_handlers.py b/tests/agent/mcp/test_handlers.py index b71b33ee0..2588e98c3 100644 --- a/tests/agent/mcp/test_handlers.py +++ b/tests/agent/mcp/test_handlers.py @@ -280,10 +280,38 @@ class TestNode: def test_console(self, ctx): from gns3server.agent.gns3_copilot.gns3_client.api_handlers import get_node_console_info_handler + from gns3server.services import console_ticket_service with patch(f"{AH}._get_connector") as m: m.return_value = _mock_conn({"console_url": "ws://host/console"}) result = get_node_console_info_handler({"project_id": "p1", "node_id": "n1"}, ctx) assert "command" in result + # the URL embeds a short console ticket (not a JWT) redeemable for this node + assert "?token=gns3t_" in result["ws_url"] + ticket = result["ws_url"].split("token=")[1] + assert ticket in result["command"] + assert result["token_ttl_seconds"] == 600 + assert len(result["token_sha256_prefix"]) == 8 + redeemed = console_ticket_service.redeem(ticket, {"project_id": "p1", "node_id": "n1"}) + assert redeemed is not None and redeemed.username == "admin" + assert "vnc_url" not in result # console_type is not vnc + + def test_console_vnc_uses_same_ticket(self, ctx): + from gns3server.agent.gns3_copilot.gns3_client.api_handlers import get_node_console_info_handler + with patch(f"{AH}._get_connector") as m: + m.return_value = _mock_conn({"console_type": "vnc"}) + result = get_node_console_info_handler({"project_id": "p1", "node_id": "n1"}, ctx) + ticket = result["ws_url"].split("token=")[1] + # one node-bound ticket covers both console endpoints (identical path params) + assert result["vnc_url"] == f"/v3/projects/p1/nodes/n1/console/vnc?token={ticket}" + + def test_console_without_username_omits_token(self, ctx): + from gns3server.agent.gns3_copilot.gns3_client.api_handlers import get_node_console_info_handler + unauthenticated_ctx = {k: v for k, v in ctx.items() if k != "jwt_username"} + with patch(f"{AH}._get_connector") as m: + m.return_value = _mock_conn({"console_url": "ws://host/console"}) + result = get_node_console_info_handler({"project_id": "p1", "node_id": "n1"}, unauthenticated_ctx) + assert "token=" not in result["ws_url"] + assert "token_sha256_prefix" not in result @staticmethod def _file_conn(text): diff --git a/tests/api/routes/controller/test_console_tickets.py b/tests/api/routes/controller/test_console_tickets.py new file mode 100644 index 000000000..4518d26d8 --- /dev/null +++ b/tests/api/routes/controller/test_console_tickets.py @@ -0,0 +1,227 @@ +# +# Copyright (C) 2026 GNS3 Technologies Inc. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +import hashlib +from types import SimpleNamespace +from typing import List + +import aiohttp +import pytest +from fastapi import FastAPI +from httpx import AsyncClient +from httpx_ws import aconnect_ws +from httpx_ws.transport import ASGIWebSocketTransport +from pydantic import SecretStr + +from gns3server.config import Config +from gns3server.controller import Controller +from gns3server.controller.compute import Compute +from gns3server.controller.node import Node +from gns3server.controller.project import Project +from gns3server.services.console_tickets import ( + ConsoleTicketService, + DEFAULT_TICKET_TTL, + TICKET_PREFIX, +) +from gns3server.services import console_ticket_service +from gns3server.utils.http_client import HTTPClient +from tests.api.routes.controller.test_nodes import FakeComputeConsoleWebSocket + + +class TestConsoleTicketService: + """Unit tests for the in-memory ticket store (fresh instances, no app).""" + + def test_mint_format(self) -> None: + + service = ConsoleTicketService() + ticket = service.mint("admin", 1, "p1", "n1") + assert ticket.startswith(TICKET_PREFIX) + # 12 random bytes -> 16 urlsafe chars; shell-safe alphabet (no quoting hazards) + assert len(ticket) == len(TICKET_PREFIX) + 16 + assert "." not in ticket # never confusable with a JWT + assert service.mint("admin", 1, "p1", "n1") != ticket + + def test_redeem_valid_ticket_is_multi_use(self) -> None: + + service = ConsoleTicketService() + ticket = service.mint("admin", 7, "p1", "n1") + path_params = {"project_id": "p1", "node_id": "n1"} + first = service.redeem(ticket, path_params) + second = service.redeem(ticket, path_params) # console clients reconnect, tickets stay usable + assert first is not None and second is not None + assert first.username == "admin" + assert first.token_version == 7 + + def test_redeem_rejects_wrong_binding(self) -> None: + + service = ConsoleTicketService() + ticket = service.mint("admin", 0, "p1", "n1") + assert service.redeem(ticket, {"project_id": "p1", "node_id": "n2"}) is None + assert service.redeem(ticket, {"project_id": "p2", "node_id": "n1"}) is None + # routes without a node_id path parameter (notifications, wireshark…) never accept a ticket + assert service.redeem(ticket, {"project_id": "p1"}) is None + assert service.redeem(ticket, {}) is None + + def test_redeem_rejects_unknown_ticket(self) -> None: + + service = ConsoleTicketService() + assert service.redeem(TICKET_PREFIX + "doesnotexist", {"project_id": "p1", "node_id": "n1"}) is None + + def test_expired_ticket_is_rejected_and_removed(self) -> None: + + service = ConsoleTicketService() + ticket = service.mint("admin", 0, "p1", "n1", ttl=0) + assert service.redeem(ticket, {"project_id": "p1", "node_id": "n1"}) is None + assert ticket not in service._tickets + + def test_mint_sweeps_expired_entries(self) -> None: + + service = ConsoleTicketService() + stale = service.mint("admin", 0, "p1", "n1", ttl=0) + fresh = service.mint("admin", 0, "p1", "n2", ttl=DEFAULT_TICKET_TTL) + assert stale not in service._tickets + assert fresh in service._tickets + + +class TestConsoleTicketWebSocketAuth: + """ + Drive the console WebSocket auth dependency end-to-end through the real + routes (the shared service singleton is the one the dependency consults). + """ + + pytestmark = pytest.mark.asyncio + + @pytest.fixture(autouse=True) + def _reset_controller_singleton(self, controller): + # The project/compute fixtures register state on the shared Controller + # singleton; reset it after each test so files running later (e.g. the + # controller statistics endpoint) see a pristine controller regardless + # of test order — same reset the controller fixture applies at setup. + yield + Controller._instance = None + + @pytest.fixture + def node(self, project: Project, compute: Compute) -> Node: + + compute.host = "127.0.0.1" + compute.port = 3080 + node = Node(project, compute, "test", node_type="vpcs") + project._nodes[node.id] = node + return node + + @pytest.fixture + def compute_credentials(self) -> None: + + server_config = Config.instance().settings.Server + server_config.compute_username = "admin" + server_config.compute_password = SecretStr("password") + + @staticmethod + def _ws_client(app: FastAPI, base_client: AsyncClient) -> AsyncClient: + # base_client must be requested so the app gets the test-DB dependency + # override, but the WebSocket connection itself needs a function-local + # client: closing the WS transport from the class-scoped base_client + # teardown exits anyio cancel scopes in the wrong task. + return AsyncClient(base_url="http://test-api", transport=ASGIWebSocketTransport(app=app)) + + @staticmethod + def _forward_compute_ws(monkeypatch, messages: List[aiohttp.WSMessage]) -> FakeComputeConsoleWebSocket: + + compute_ws = FakeComputeConsoleWebSocket(messages) + monkeypatch.setattr( + HTTPClient, + "get_client", + classmethod(lambda cls: SimpleNamespace(ws_connect=lambda *args, **kwargs: compute_ws)) + ) + return compute_ws + + async def test_console_ws_accepts_valid_ticket( + self, + app: FastAPI, + base_client: AsyncClient, + compute_credentials, + project: Project, + node: Node, + monkeypatch + ) -> None: + # admin is the seeded superadmin, so the RBAC privilege check is skipped + ticket = console_ticket_service.mint("admin", 0, project.id, node.id) + self._forward_compute_ws(monkeypatch, [ + aiohttp.WSMessage(aiohttp.WSMsgType.TEXT, "device output", None), + ]) + + async with self._ws_client(app, base_client) as client: + async with aconnect_ws( + f"/v3/projects/{project.id}/nodes/{node.id}/console/ws", + client, + params={"token": ticket} + ) as ws: + # reaching the compute forwarding loop means ticket auth succeeded + assert await ws.receive_text() == "device output" + + async def test_console_ws_rejects_ticket_bound_to_other_node( + self, + app: FastAPI, + base_client: AsyncClient, + project: Project, + node: Node + ) -> None: + + other_node = "00000000-0000-0000-0000-000000000000" + ticket = console_ticket_service.mint("admin", 0, project.id, other_node) + async with self._ws_client(app, base_client) as client: + async with aconnect_ws( + f"/v3/projects/{project.id}/nodes/{node.id}/console/ws", + client, + params={"token": ticket} + ) as ws: + notification = await ws.receive_json() + assert notification["event"]["message"] == ( + "Could not authenticate while connecting to controller WebSocket: " + "Invalid or expired console ticket " + f"(received token sha256 prefix: {hashlib.sha256(ticket.encode()).hexdigest()[:8]})" + ) + + async def test_console_ws_rejects_ticket_with_stale_token_version( + self, + app: FastAPI, + base_client: AsyncClient, + project: Project, + node: Node + ) -> None: + # logging out bumps the user's token_version: outstanding tickets must die with it + ticket = console_ticket_service.mint("admin", 999, project.id, node.id) + async with self._ws_client(app, base_client) as client: + async with aconnect_ws( + f"/v3/projects/{project.id}/nodes/{node.id}/console/ws", + client, + params={"token": ticket} + ) as ws: + notification = await ws.receive_json() + assert "Token has been revoked for 'admin'" in notification["event"]["message"] + + async def test_ticket_rejected_on_non_console_websocket( + self, + app: FastAPI, + base_client: AsyncClient + ) -> None: + # the controller notification stream shares the WS auth dependency but has + # no node binding: a console ticket must not authenticate it + ticket = console_ticket_service.mint("admin", 0, "p1", "n1") + async with self._ws_client(app, base_client) as client: + async with aconnect_ws("/v3/notifications/ws", client, params={"token": ticket}) as ws: + notification = await ws.receive_json() + assert "Invalid or expired console ticket" in notification["event"]["message"]