From 7bf18ac2e8e9e0e83d0f5dcaf78a0e9fc8dbe57d Mon Sep 17 00:00:00 2001 From: YueGuobin Date: Mon, 2 Nov 2026 22:52:46 +0800 Subject: [PATCH] =?UTF-8?q?feat(mcp):=20node=5Fconsole=5Fexec=20=E2=80=94?= =?UTF-8?q?=20one-shot=20console=20session=20via=20the=20host's=20websocat?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replaces node_console (which handed a URL + ticket to the client for a bash websocat chain) with a tool that runs the whole session server-side: spawn `timeout N websocat -t --no-close `, feed the command lines through stdin (paced, CRLF), read stdout until the timeout kills websocat, return the collected output as plain text. - plain text replies: "output: ..." or bare error text — no JSON envelope, no status field (the server cannot judge command success) - raw output: UTF-8 decode with replacement only, no telnet/ANSI stripping; control keys are real characters (description teaches \u0003, no \x03 translation) - output funnel: grep= filter; <=50 lines return as-is; beyond that a 10-line sample plus hints — regrep=true re-filters the node's cached capture (no re-run), full=true returns the last 400 lines / 64 KiB, and the full capture is written to the node's files (console-capture.txt) with a ticketed curl download URL - get_node_console_info_handler removed with its hashlib/TTL imports; the node-bound console ticket redemption path stays (comment updated, no current producer) --- docs/features/mcp-service.md | 34 +- docs/features/vnc-websocket-console.md | 4 +- .../gns3_copilot/gns3_client/api_handlers.py | 52 -- gns3server/agent/mcp/__init__.py | 109 +++- gns3server/agent/mcp/console_exec.py | 405 +++++++++++++ .../controller/dependencies/authentication.py | 11 +- tests/agent/mcp/test_console_exec.py | 569 ++++++++++++++++++ tests/agent/mcp/test_handlers.py | 38 -- tests/agent/mcp/test_tool_params.py | 1 - 9 files changed, 1083 insertions(+), 140 deletions(-) create mode 100644 gns3server/agent/mcp/console_exec.py create mode 100644 tests/agent/mcp/test_console_exec.py diff --git a/docs/features/mcp-service.md b/docs/features/mcp-service.md index 8cbd60bf6..ff4a77a09 100644 --- a/docs/features/mcp-service.md +++ b/docs/features/mcp-service.md @@ -135,7 +135,7 @@ from the API key automatically — long-lived sessions keep working | `node_start` | Start node(s) — `node_id` or `node_ids` array | | `node_stop` | Stop node(s) — `node_id` or `node_ids` array | | `node_suspend` | Suspend node(s) — `node_id` or `node_ids` array | -| `node_console` | Get WebSocket console URL | +| `node_console_exec` | Run commands on a node's console (one call = one complete session) | | `node_file_list` | List files in node directory | | `node_file_get` | Read a file (with offset/limit) | | `node_file_write` | Write a file | @@ -252,7 +252,7 @@ they require a vision-capable model to be genuinely useful. Revisit later. | Network OS console, any interaction | `device_config_send` / `device_show_run` (batch drivers manage config mode themselves) | | Unfamiliar device: read its quirks before driving the console | `device_skill_get` (list first, then fetch by key) | | Practise troubleshooting: inject a realistic fault | `injection_skill_get` (list with the topology's protocols, then one fault) + `device_config_send` | -| VNC console | `node_console` (returns a websocat URL) | +| Any console interaction outside those drivers (incl. Docker/Linux nodes) | `node_console_exec` (one call = one session, plain-text output) | The tool connects to each device's console via telnet/SSH. Nodes must be in the `started` state (use `node_start` or `node_start_all`). Device type is auto-detected from the node's `device_type:` tag in GNS3. @@ -516,11 +516,24 @@ sequenceDiagram - Tool handlers use `Gns3Connector` (from `gns3_copilot.gns3_client.connector`) via the shared handler layer (`gns3_copilot.gns3_client.api_handlers`), keeping the MCP layer decoupled - The JWT token is stored in a `contextvars.ContextVar` so it is available within tool handler threads (Python ≥ 3.9 propagates contextvars through `asyncio.to_thread`). In stateful Streamable HTTP the session task inherits the context of the opening request, so handlers see the token presented at `initialize` -### Console WebSocket +### Node Console Execution -The `node_console` tool returns a WebSocket URL for connecting to a node's console. The URL includes a short-lived **access ticket** (10 min) — a short random string (`gns3t_…`, 22 chars) minted server-side and bound to that node's console endpoints. `link_capture_download` uses the same kind of ticket bound to one exact resource path instead of embedding a Bearer JWT in the returned curl command. Tickets replaced the long JWTs previously embedded in these URLs/commands: LLM clients retyping them 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 `node_console_exec` tool runs commands on a node's text console server-side. One tool call is one complete console session: the server spawns `timeout N websocat -t --no-close ''`, feeds the command lines through stdin (one line per turn, ~0.3 s pacing, `\r\n` line endings), keeps reading stdout until the timeout kills websocat, and returns the collected output as plain text (`output: …`, or bare error text — no JSON envelope, no status field: the server cannot judge whether the command itself succeeded). Works for **telnet** and **ssh** console types on all computes (the controller proxies the WebSocket); **vnc** consoles have no text channel and fail with a plain message. The client never sees a URL or token — the whole websocat chain is an implementation detail. -The WebSocket URL is constructed using the server's `_server_url()`, which resolves the host as follows: +Prerequisites: the node must be started, and the host running gns3server must have the `websocat` binary on its PATH (a missing binary returns a plain install hint). + +Output handling (the funnel): + +- Raw console bytes are decoded as UTF-8 with replacement — telnet negotiation and ANSI escapes are **not** stripped; stray bytes in the output are expected. +- `grep=` filters the captured lines (Python `re`, a superset of `grep -E`). +- Up to 50 lines return as-is; beyond that a 10-line sample returns with retrieval hints. +- `regrep=true` re-uses the node's last captured output — re-filter (`grep=`) or dump its tail (`full=true`) without re-running the command (no side effects). +- `full=true` returns the last 400 lines / 64 KiB. +- When output exceeds 50 lines, the full capture is also written to the node's files (`console-capture.txt`, overwritten per session) and the hint includes a `curl` URL with a short-lived **access ticket** (10 min) bound to that exact download path — the same mechanism `link_capture_download` uses. Tickets are short random strings (`gns3t_…`); they replaced long Bearer JWTs in returned URLs because LLM clients reliably corrupted those when retyping them (logging out invalidates outstanding tickets). + +Node-side state persists between calls (config mode, running pings, pager position) — a new session lands where the previous one ended. Control keys are sent as real characters: an interrupt is `"\u0003"` as its own line in the `command` string; the 4-character spelling `"\x03"` is not translated. `command=""` sends a single Enter (wake an idle console / read the prompt). The session stays open the full `timeout` window (default 15 s, max 300 s) — set it just above the expected output time. + +The console WebSocket URL is built from the server's `_server_url()`, which resolves the host as follows: | `Server.host` value | Resolved host in URL | |:---|:---| @@ -529,16 +542,7 @@ The WebSocket URL is constructed using the server's `_server_url()`, which resol | `::` (IPv6 any) | Detected via default route interface IP | | Detection failure | Fallback to `127.0.0.1` | -When `Server.host` is `0.0.0.0` (listen on all interfaces), the MCP server discovers the default route interface IP using a UDP socket connect to `8.8.8.8:80` — no network data is sent, the operating system simply selects the interface that would be used for the default route. This ensures the returned WebSocket URL uses a reachable address (e.g. `192.168.1.3` instead of `127.0.0.1`). - -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 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= -``` +When `Server.host` is `0.0.0.0` (listen on all interfaces), the MCP server discovers the default route interface IP using a UDP socket connect to `8.8.8.8:80` — no network data is sent, the operating system simply selects the interface that would be used for the default route. This ensures the console URL uses a reachable address (e.g. `192.168.1.3` instead of `127.0.0.1`). If the configured host is already a specific IP or hostname (not `0.0.0.0`), it is used directly without modification. ### Source Files diff --git a/docs/features/vnc-websocket-console.md b/docs/features/vnc-websocket-console.md index b117ad152..8b5682e21 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, **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) +- JWT token via query parameter, **or** a short-lived console ticket (`gns3t_…`, valid 10 min, bound to this node's console endpoints — no MCP tool currently mints these; the redemption path is reserved for handing node console access to external clients) - 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}`, or a console ticket (`gns3t_…`) redeemable only on the node it was minted for + - Token passed as query parameter: `?token={jwt}` (the server also redeems node-bound console tickets, `gns3t_…`, on these routes) 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 44e03688b..f14cd7794 100644 --- a/gns3server/agent/gns3_copilot/gns3_client/api_handlers.py +++ b/gns3server/agent/gns3_copilot/gns3_client/api_handlers.py @@ -47,14 +47,12 @@ Copilot-side callers build the context with :func:`build_gns3_ctx`, which pulls the request-scoped user JWT from the context variables. """ -import hashlib import logging from concurrent.futures import ThreadPoolExecutor from typing import Any from gns3server.agent.gns3_copilot.gns3_client.connector import Gns3Connector from gns3server.services import access_ticket_service -from gns3server.services.access_tickets import DEFAULT_TICKET_TTL from gns3server.utils.drawings import build_ellipse_svg, build_rectangle_svg, build_text_svg log = logging.getLogger(__name__) @@ -448,56 +446,6 @@ def update_node_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> dic return conn.http_call("put", url, json_data=update_data).json() -def get_node_console_info_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> dict[str, Any]: - project_id = params.get("project_id") - node_id = params.get("node_id") - if not project_id or not node_id: - return {"error": "project_id and node_id are required"} - conn = _get_connector(gns3_ctx) - 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 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") - ticket = ( - access_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 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://") - - result = { - "node_id": node_id, - "node_name": node.get("name"), - "console_type": console_type, - "ws_url": ws_url, - "command": f"websocat -t --no-close {ws_url}", - } - 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(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 - - # ── Node file handlers ──────────────────────────────────────────────────── diff --git a/gns3server/agent/mcp/__init__.py b/gns3server/agent/mcp/__init__.py index d5b8df636..b4bca26e5 100644 --- a/gns3server/agent/mcp/__init__.py +++ b/gns3server/agent/mcp/__init__.py @@ -60,7 +60,6 @@ from gns3server.agent.gns3_copilot.gns3_client.api_handlers import ( duplicate_node_handler, get_link_handler, get_links_handler, - get_node_console_info_handler, get_node_file_handler, get_node_handler, get_node_links_handler, @@ -109,6 +108,7 @@ from .computes import ( get_compute_images_handler, list_computes_handler, ) +from .console_exec import DEFAULT_TIMEOUT_S, DIRECT_LINES, FULL_LINES, MAX_TIMEOUT_S, console_exec from .device_config import ( device_config_send_handler, device_show_run_handler, @@ -754,38 +754,91 @@ async def node_update( @mcp.tool() -async def node_console( +async def node_console_exec( project_id: Annotated[str, Field(description="Project name or UUID containing the node")], - node_id: Annotated[str, Field(description="Node name or UUID to get console info for")], -) -> list[dict[str, Any]]: - """Get WebSocket console connection info for a node. + node_id: Annotated[str, Field(description="Node name or UUID to run commands on")], + command: Annotated[ + str, + Field( + description="Commands, one per line (\\n-separated). Empty = a single Enter (wake the console / read the prompt)." + ), + ] = "", + timeout: Annotated[ # noqa: ASYNC109 - timeout is the session length, not an async deadline + float, + Field( + description=f"Session length in seconds, 1-{int(MAX_TIMEOUT_S)} (default {int(DEFAULT_TIMEOUT_S)}). " + "The session stays open the FULL window — set it just above the expected output time." + ), + ] = DEFAULT_TIMEOUT_S, + grep: Annotated[ + str | None, + Field( + description="Optional Python regex (superset of grep -E). Only matching lines of the output are returned, " + "e.g. 'ospf|bgp', '^R1#'." + ), + ] = None, + regrep: Annotated[ + bool, + Field( + description="Re-use this node's last captured output instead of running a new session " + "(no re-run, no side effects). Combine with grep= or full=true." + ), + ] = False, + full: Annotated[ + bool, + Field( + description=f"Return the last {FULL_LINES} lines / 64 KiB of output instead of the {DIRECT_LINES}-line summary." + ), + ] = False, +) -> str: + """Run commands on a node's text console and return the output (one call = one complete session). - Returns the console type (telnet/ssh/vnc) and a ready-to-run websocat - command with a short-lived access token (10 min) already embedded. + The server connects to the node's console WebSocket, sends your command + lines, keeps collecting output until the timeout expires, disconnects, + and returns everything that came back as plain text. Works for telnet and + ssh console types on all computes (the controller proxies the WebSocket). + Node-side state persists between calls (config mode, running pings, + pager position) — a new session lands where the previous one ended. - 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. + Console input: + - command: one command per line (\\n-separated). Each line is sent with a + console line ending, lines are paced ~0.3 s apart so none is dropped. + - A line containing only a control character is a keypress, not a + command: interrupt a running command with a real Ctrl-C character — in + JSON tool arguments that is "\\u0003" as its own line. The 4-character + spelling "\\x03" is NOT translated and would arrive as text. + - command="" sends a single Enter — wakes an idle console and shows the + prompt. - Sending device commands after connecting: - > timeout 10 websocat -t --no-close "ws://..." <<< $'\\r\\nenable\\r\\nshow version\\r\\nexit\\r\\n' + Timeout: the session stays open for the FULL window (like + `timeout N websocat`). Output keeps arriving the whole time; there is no + early return. ~15 s fits a few show commands; big config blocks or + `show tech-support` need 30 s or more. - - 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 - device output is not cut off before it arrives - - Set a timeout to prevent hanging connections + Output is raw console bytes decoded as UTF-8 with replacement — telnet + negotiation and ANSI escape sequences may show up as stray bytes; that + is expected. When more than 50 lines would come back, only a 10-line + sample returns, with instructions to narrow (grep=), re-filter the cached + capture without re-running (regrep=true), dump its tail (full=true), or + download the whole capture with curl. + + Failures (node not started, VNC console, websocat missing on the server + host, silent console) return plain text describing the problem — there + is no status field, read the text itself. + + Example — two checks on one router, 20 s window: + node_console_exec(project_id="ospf-lab", node_id="R1", + command="show ip ospf neighbor\\nshow ip route summary", timeout=20) """ - return await asyncio.to_thread( - _run_handler_sync, - get_node_console_info_handler, - { - "project_id": project_id, - "node_id": node_id, - }, + return await console_exec( + project_id, + node_id, + command, + timeout, + grep=grep, + regrep=regrep, + full=full, + gns3_ctx=_gns3_ctx(), ) @@ -2146,7 +2199,7 @@ async def device_show_run( - Each node must have a device_type: tag set in GNS3 (e.g. device_type:cisco_ios_telnet, device_type:gns3_huawei_telnet_ce). Nodes without this tag will fail with "device_type tag not found". - Docker/Linux nodes are not supported (use node_console instead). + Docker/Linux nodes are not supported (use node_console_exec instead). Error contract: every failure is reported in-band as an entry with status "failed" and an "error" message (per-device entries also carry diff --git a/gns3server/agent/mcp/console_exec.py b/gns3server/agent/mcp/console_exec.py new file mode 100644 index 000000000..f8a84eaaa --- /dev/null +++ b/gns3server/agent/mcp/console_exec.py @@ -0,0 +1,405 @@ +# +# Copyright (C) 2026 GNS3 Technologies Inc. +# Author: Yue Guobin +# +# 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 . +# + +""" +node_console_exec: one-shot node console executor. + +Server-side equivalent of the client-side chain this workflow used to need: + + node_console (mint URL+ticket) -> bash: { sleep ..; printf 'cmd\r\n'; .. } + | timeout N websocat -t --no-close '' + +One tool call is one complete console session: the server spawns +``timeout N websocat -t --no-close ``, feeds the command lines through +stdin, keeps reading stdout until the timeout kills websocat, and returns the +collected output as plain text. No session state survives the call; node-side +state (config mode, running pings) persists across calls by nature of the +console itself. + +The transport is deliberately the host's websocat binary instead of a +self-built WebSocket client — the same wire behavior as the field-proven +bash template, including its quirks (raw byte stream, no early return). + +Output funnel: up to DIRECT_LINES lines are returned as-is. Beyond that a +SAMPLE_LINES excerpt comes back with retrieval hints — re-filter the cached +capture (regrep), dump its tail (full), or download the whole capture written +to the node's files. The raw capture is cached per node so a second look at a +command's output never re-runs it (and never repeats its side effects). +""" + +import asyncio +import contextlib +import logging +import math +import os +import re +import signal +from typing import Any + +from gns3server.services import access_ticket_service + +log = logging.getLogger(__name__) + +# Wall clock of the whole session (connect + send + receive), matching +# `timeout N websocat`. Field-tested sizing: 2-3 verification commands fit +# in 15 s; 46-50 config lines (~15 s of paced input) need 30 s or more. +DEFAULT_TIMEOUT_S = 15.0 +MAX_TIMEOUT_S = 300.0 +# Pacing between command lines. Consoles ingest lines much slower than a +# local shell (IOL polls its console ~50 ms per key; remote pty echo lags), +# and dumping 50 lines at once can drop input. +LINE_INTERVAL_S = 0.3 +# Output funnel thresholds. +DIRECT_LINES = 50 +SAMPLE_LINES = 10 +FULL_LINES = 400 +MAX_OUTPUT_BYTES = 64 * 1024 +# Flood guard for one session: stop collecting after this much raw output. +MAX_CAPTURE_BYTES = 8 * 1024 * 1024 +CAPTURE_FILE = "console-capture.txt" + +# Newest raw output per node (resolved UUIDs) — the regrep/full target. +_OUTPUT_CACHE: dict[tuple[str, str], str] = {} + + +def prepare_payloads(command: str) -> list[str]: + """Split a command string into console-ready stdin payloads. + + Each line becomes one write: + + - a plain line gets ``\\r\\n`` appended (consoles need the carriage + return; a bare ``\\n`` does not execute on most NOS), + - a line already ending in ``\\r`` only gets the ``\\n``, + - a line containing control characters (``\\x03`` and friends) is sent + verbatim with no line ending — it is a keypress, not a command. + """ + + payloads = [] + for line in command.split("\n"): + if line.endswith("\r"): + payloads.append(line + "\n") + elif any(ord(ch) < 0x20 and ch != "\t" for ch in line): + payloads.append(line) + else: + payloads.append(line + "\r\n") + return payloads + + +def _ws_url(server_url: str, project_id: str, node_id: str, token: str) -> str: + """Console WS URL on the controller (it proxies to the node's compute).""" + + url = f"{server_url}/v3/projects/{project_id}/nodes/{node_id}/console/ws" + url = url.replace("https://", "wss://").replace("http://", "ws://") + # JWTs are base64url + dots, safe in a query string as-is. + return f"{url}?token={token}" + + +async def _resolve_console_node( + project_id: str, + node_id: str, + gns3_ctx: dict[str, Any], + validate_console: bool = True, +) -> tuple[dict[str, Any] | None, str | None]: + """Fetch the node (resolving names to UUIDs) and validate its console. + + Returns (node dict, None) or (None, plain error text). Name resolution + goes through the same ``resolve_locators`` choke point as every other + tool (known-names fast failure included). With ``validate_console`` off, + only existence is required (the regrep path reads a capture from a node + that may since have been stopped). + """ + + from gns3server.agent.gns3_copilot.gns3_client.api_handlers import _get_connector + from gns3server.agent.mcp.locators import resolve_locators + + def resolve_and_fetch() -> dict[str, Any]: + resolved, resolution_error = resolve_locators( + {"project_id": project_id, "node_id": node_id}, + lambda handler, params: handler(params, gns3_ctx), + ) + if resolved is None: + assert resolution_error is not None # resolve_locators' None-error contract + return resolution_error + conn = _get_connector(gns3_ctx) + url = f"{conn.base_url}/projects/{resolved['project_id']}/nodes/{resolved['node_id']}" + return conn.http_call("get", url).json() + + try: + node = await asyncio.to_thread(resolve_and_fetch) + except Exception as e: + return None, f"could not resolve project '{project_id}' / node '{node_id}': {e}" + + if "error" in node: # resolution failure dict from resolve_locators + return None, str(node["error"]) + + if not validate_console: + return node, None + + name = node.get("name", node_id) + if (node.get("console_type") or "telnet") == "vnc": + return None, f"node '{name}' has a VNC console (pixel stream) — there is no text command channel" + if not node.get("console"): + return None, f"node '{name}' has no console" + if node.get("status") != "started": + return None, f"node '{name}' is {node.get('status')} — start it before using the console" + return node, None + + +async def _spawn(url: str, seconds: int) -> asyncio.subprocess.Process: + """Start ``timeout websocat -t --no-close ``. + + The subprocess gets its own process group: websocat is a child of + ``timeout``, and a cancelled call must take down the whole tree (an + externally killed ``timeout`` alone could orphan websocat). + """ + + return await asyncio.create_subprocess_exec( + "timeout", + str(seconds), + "websocat", + "-t", + "--no-close", + url, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + start_new_session=True, + ) + + +async def _feed_lines(stdin: asyncio.StreamWriter, payloads: list[str]) -> None: + """Write one payload per turn with pacing, then half-close stdin.""" + + try: + for payload in payloads: + stdin.write(payload.encode("utf-8", errors="replace")) + await stdin.drain() + await asyncio.sleep(LINE_INTERVAL_S) + finally: + stdin.close() + + +async def _drain_stream(stream: asyncio.StreamReader | None, cap: int) -> bytes: + """Read a subprocess stream to EOF, stopping at ``cap`` bytes.""" + + if stream is None: + return b"" + chunks: list[bytes] = [] + total = 0 + while total < cap: + block = await stream.read(65536) + if not block: + break + chunks.append(block) + total += len(block) + return b"".join(chunks) + + +async def _run_session(url: str, payloads: list[str], seconds: int) -> tuple[bytes, bytes, int | None]: + """Run one websocat session: feed the payloads, collect stdout until EOF. + + Returns (stdout, stderr, returncode). Exit code 124 (the ``timeout`` + kill) is the normal end of a session; websocat exiting on its own means + the console side dropped the connection. + """ + + try: + proc = await _spawn(url, seconds) + except FileNotFoundError: + return b"", b"timeout binary not found", -1 + + # stdin/stdout/stderr were requested as PIPE, so the Optional is static only + assert proc.stdin is not None and proc.stdout is not None and proc.stderr is not None + feed_task = asyncio.create_task(_feed_lines(proc.stdin, payloads)) + stderr_task = asyncio.create_task(_drain_stream(proc.stderr, 64 * 1024)) + try: + stdout = await _drain_stream(proc.stdout, MAX_CAPTURE_BYTES) + returncode = await proc.wait() + return stdout, await stderr_task, returncode + except asyncio.CancelledError: + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(proc.pid, signal.SIGTERM) + raise + finally: + feed_task.cancel() + stderr_task.cancel() + with contextlib.suppress(asyncio.CancelledError, BrokenPipeError, ConnectionResetError): + await feed_task + with contextlib.suppress(asyncio.CancelledError): + await stderr_task + if proc.returncode is None: + with contextlib.suppress(ProcessLookupError): + proc.kill() + with contextlib.suppress(asyncio.CancelledError): + await proc.wait() + + +def _session_error(stderr: bytes, returncode: int | None, seconds: int) -> str: + """Classify an output-less session into plain error text.""" + + err = stderr.decode("utf-8", errors="replace").strip() + # coreutils timeout exits 125 when it cannot run the command; the + # message text is the reliable marker for a missing websocat. + if "failed to run command" in err or returncode in (125, 127): + return ( + "websocat is not installed on the server host — install it " + "(https://github.com/vi/websocat/releases or `cargo install websocat`) and retry" + ) + if returncode == 124: + return ( + f"no console output within {seconds}s — the console may still be booting or silent; " + "retry with a larger timeout" + ) + detail = f": {err[-400:]}" if err else "" + return f"websocat exited with code {returncode}{detail}" + + +def _tail_bytes(text: str, cap: int) -> tuple[str, bool]: + """Byte-cap a string from the end; returns (text, was_capped).""" + + encoded = text.encode("utf-8", errors="replace") + if len(encoded) <= cap: + return text, False + return encoded[-cap:].decode("utf-8", errors="replace"), True + + +def shape_view(text: str, grep: str | None, full: bool) -> tuple[str, dict[str, Any] | None]: + """Filter and size the captured text for return. + + Returns (reply_body, None) for a final reply — including the plain-error + cases (invalid pattern, grep miss) — or (header, metadata) when the + output exceeded DIRECT_LINES: the caller appends retrieval hints to the + metadata-carrying header (it knows the download URL). + """ + + shown = text.splitlines() + if grep is not None: + try: + pattern = re.compile(grep) + except re.error as e: + return f"invalid grep pattern {grep!r}: {e}", None + shown = [line for line in shown if pattern.search(line)] + if not shown: + return ( + f"grep {grep!r} matched nothing — {len(text.splitlines())} lines captured. " + "Retry with a wider pattern and regrep=true (re-filters the capture, no re-run), " + f"or regrep=true + full=true to dump its last {FULL_LINES} lines.", + None, + ) + + if full: + tail = shown[-FULL_LINES:] + body, capped = _tail_bytes("\n".join(tail), MAX_OUTPUT_BYTES) + header = f"output: last {len(tail)} of {len(shown)} lines" + if len(shown) > FULL_LINES: + header += f" (line cap {FULL_LINES})" + if capped: + header += f" (byte cap {MAX_OUTPUT_BYTES // 1024} KiB)" + return f"{header}\n{body}", None + + if len(shown) > DIRECT_LINES: + sample = "\n".join(shown[:SAMPLE_LINES]) + header = f"output: {len(shown)} lines total — first {SAMPLE_LINES} shown:\n{sample}\n---" + return header, {"lines": len(shown), "grep": grep} + + body = "\n".join(shown) if grep is not None else text + return f"output:\n{body}", None + + +def _write_capture_and_url(text: str, project_id: str, node_id: str, gns3_ctx: dict[str, Any]) -> str | None: + """Persist the raw capture into the node's files; return a ticketed download URL. + + The file route and the path-bound access ticket are the same mechanism + the capture-download tool uses. Any failure here only costs the hint, + not the reply — return None and let the caller fall back. + """ + + from gns3server.agent.gns3_copilot.gns3_client.api_handlers import _get_connector + + username = gns3_ctx.get("jwt_username") + if not username: + return None + try: + conn = _get_connector(gns3_ctx) + conn.http_call( + "post", + f"{conn.base_url}/projects/{project_id}/nodes/{node_id}/files/{CAPTURE_FILE}", + data=text, + headers={"Content-Type": "text/plain"}, + ) + except Exception as e: + log.warning("Could not write the console capture file for node %s: %s", node_id, e) + return None + path = f"/v3/projects/{project_id}/nodes/{node_id}/files/{CAPTURE_FILE}" + ticket = access_ticket_service.mint(username, token_version=gns3_ctx.get("jwt_token_version", 0), path=path) + return f"{gns3_ctx['server_url']}{path}?token={ticket}" + + +async def console_exec( + project_id: str, + node_id: str, + command: str, + timeout: float, # noqa: ASYNC109 - operation-specific timeout is intentional + grep: str | None = None, + regrep: bool = False, + full: bool = False, + gns3_ctx: dict[str, Any] | None = None, +) -> str: + """Run one one-shot console session (or re-view its capture) as plain text.""" + + assert gns3_ctx is not None + node, error = await _resolve_console_node(project_id, node_id, gns3_ctx, validate_console=not regrep) + if error is not None: + return error + assert node is not None + key = (str(node["project_id"]), str(node["node_id"])) + + if regrep: + text = _OUTPUT_CACHE.get(key) + if text is None: + return ( + f"no captured output for node '{node.get('name', node_id)}' yet — " + "run a command first, then re-filter it with regrep=true" + ) + else: + url = _ws_url(gns3_ctx["server_url"], key[0], key[1], gns3_ctx.get("jwt_token") or "") + payloads = prepare_payloads(command) or ["\r\n"] + seconds = max(1, math.ceil(min(max(float(timeout), 1.0), MAX_TIMEOUT_S))) + stdout, stderr, returncode = await _run_session(url, payloads, seconds) + if not stdout: + return _session_error(stderr, returncode, seconds) + # Raw console bytes decoded with replacement only — telnet/ANSI noise + # is left in on purpose (no stripping layer between AI and console). + text = stdout.decode("utf-8", errors="replace") + _OUTPUT_CACHE[key] = text + + body, too_long = shape_view(text, grep, full) + if too_long is None: + return body + + download_url = await asyncio.to_thread(_write_capture_and_url, text, key[0], key[1], gns3_ctx) + hints = [ + f"{too_long['lines']} lines is too long to return whole. Without re-running the command:", + "- regrep=true + grep= re-filters the captured output", + f"- regrep=true + full=true returns its last {FULL_LINES} lines", + ] + if too_long["grep"] is None: + hints.append("- grep= re-runs the command with the filter applied") + if download_url: + hints.append(f"- download the full capture: curl -o {CAPTURE_FILE} '{download_url}'") + return "\n".join([body, *hints]) diff --git a/gns3server/api/routes/controller/dependencies/authentication.py b/gns3server/api/routes/controller/dependencies/authentication.py index 9fa30672e..eefbd1d89 100644 --- a/gns3server/api/routes/controller/dependencies/authentication.py +++ b/gns3server/api/routes/controller/dependencies/authentication.py @@ -191,10 +191,13 @@ async def get_current_active_user_from_websocket( try: if token.startswith(TICKET_PREFIX): # Node-bound access tickets ("gns3t_…"): short-lived credentials - # for 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. + # for one node's console endpoints. No MCP tool currently mints + # them (node_console_exec connects server-side with the session + # JWT), but the redemption path is kept as the designated + # mechanism for handing node console access to external clients. + # redeem() confines them to the route matching their binding, so + # they cannot authenticate the notification/wireshark sockets + # that share this dependency. ticket = access_ticket_service.redeem(token, websocket.path_params) if ticket is None: raise HTTPException( diff --git a/tests/agent/mcp/test_console_exec.py b/tests/agent/mcp/test_console_exec.py new file mode 100644 index 000000000..749b066e2 --- /dev/null +++ b/tests/agent/mcp/test_console_exec.py @@ -0,0 +1,569 @@ +""" +node_console_exec tests. + +The transport is the host's websocat binary behind `timeout`, so the session +tests run against a fake subprocess (a recorder with the asyncio Process +shape) — no binary, no network. One integration test exercises the real +websocat against a local WebSocket server and is skipped when websocat is +not installed. Node resolution is mocked at the connector layer, matching +the other handler tests. +""" + +import contextlib +import importlib +import shutil +import time +from unittest.mock import patch + +import pytest + +from gns3server.agent.mcp.console_exec import ( + _ws_url, + console_exec, + prepare_payloads, + shape_view, +) + +# the package __init__ rebinds the name "console_exec" to the tool function, +# so import paths hand back the function — the module (monkeypatch target for +# module-level constants) must come from sys.modules +ce_module = importlib.import_module("gns3server.agent.mcp.console_exec") + +AH = "gns3server.agent.gns3_copilot.gns3_client.api_handlers" +# list_projects_handler lives in the MCP projects module with its own +# _get_connector binding — both must be patched for locator-chain tests +PROJECTS = "gns3server.agent.mcp.projects" +CE = "gns3server.agent.mcp.console_exec" + + +def _node_payload(**overrides): + node = { + "node_id": "n-uuid-1", + "project_id": "p-uuid-1", + "name": "R1", + "status": "started", + "console": 5000, + "console_type": "telnet", + } + node.update(overrides) + return node + + +class _MockResponse: + def __init__(self, payload): + self._payload = payload + + def json(self): + return self._payload + + +class _MockConnector: + def __init__(self, payload): + self.base_url = "http://127.0.0.1:3080/v3" + self._payload = payload + self.calls = [] + + def http_call(self, method, url, **kwargs): + self.calls.append((method, url, kwargs)) + return _MockResponse(self._payload) + + +class _RoutingConnector: + """Serves the calls the locator chain makes: project list (name lookup), + node list (name lookup) and node detail — in URL-shape order.""" + + def __init__(self, projects, nodes, node): + self.base_url = "http://127.0.0.1:3080/v3" + self._projects = projects + self._nodes = nodes + self._node = node + self.calls = [] + + def http_call(self, method, url, **kwargs): + self.calls.append((method, url, kwargs)) + if url.endswith("/nodes"): + return _MockResponse(self._nodes) + if url.endswith("/projects"): + return _MockResponse(self._projects) + return _MockResponse(self._node) + + +class _FakeReader: + """StreamReader shape: hands out the given chunks, then EOF forever.""" + + def __init__(self, chunks): + self._chunks = list(chunks) + + async def read(self, n=-1): + if not self._chunks: + return b"" + return self._chunks.pop(0) + + +class _FakeWriter: + """StreamWriter shape: records writes, never blocks.""" + + def __init__(self): + self.received = [] + self.closed = False + + def write(self, data): + self.received.append(data) + + async def drain(self): + return None + + def close(self): + self.closed = True + + +class _FakeProc: + """asyncio Process shape for a websocat-under-timeout session.""" + + def __init__(self, stdout_chunks, stderr_chunks=(), returncode=124): + self.stdin = _FakeWriter() + self.stdout = _FakeReader(stdout_chunks) + self.stderr = _FakeReader(stderr_chunks) + self.returncode = returncode + self.pid = 4242 + + async def wait(self): + return self.returncode + + def kill(self): + pass + + +class _SpawnRecorder: + """Stands in for console_exec._spawn, handing out prepared processes.""" + + def __init__(self, *procs): + self.procs = list(procs) + self.calls = [] + + async def __call__(self, url, seconds): + self.calls.append((url, seconds)) + return self.procs.pop(0) + + +def _ctx(server_url="http://127.0.0.1:3080"): + return {"server_url": server_url, "jwt_token": "jwt-abc", "jwt_username": "admin", "jwt_token_version": 1} + + +@pytest.fixture(autouse=True) +def _fast_pacing_and_clean_cache(monkeypatch): + monkeypatch.setattr(ce_module, "LINE_INTERVAL_S", 0.01) + monkeypatch.setattr(ce_module, "_OUTPUT_CACHE", {}) + + +# ── pure helpers ──────────────────────────────────────────────────────── + + +def test_plain_lines_get_crlf(): + assert prepare_payloads("show version\nshow ip route") == ["show version\r\n", "show ip route\r\n"] + + +def test_line_already_ending_with_cr_gets_bare_lf(): + assert prepare_payloads("vtysh\r") == ["vtysh\r\n"] + + +def test_control_character_line_sent_verbatim(): + # Ctrl-C is a keypress, not a command: no line ending is appended + assert prepare_payloads("\x03") == ["\x03"] + assert prepare_payloads("conf t\n\x03") == ["conf t\r\n", "\x03"] + + +def test_no_control_spelling_translation(): + # the 4-character spelling "\x03" is text and must arrive as text + assert prepare_payloads("\\x03") == ["\\x03\r\n"] + + +def test_ws_url_scheme_and_token(): + assert _ws_url("https://h:3080", "p", "n", "t") == "wss://h:3080/v3/projects/p/nodes/n/console/ws?token=t" + assert _ws_url("http://h:3080", "p", "n", "t") == "ws://h:3080/v3/projects/p/nodes/n/console/ws?token=t" + + +def test_short_output_returns_raw_text(): + text = "Welcome to the console\r\nPC1> \r\n" + body, too_long = shape_view(text, grep=None, full=False) + assert too_long is None + assert body == "output:\n" + text # byte-faithful, \r\n untouched + + +def test_grep_filters_matching_lines(): + body, too_long = shape_view("R1# a\nR1# b\nX c\n", grep="^R1#", full=False) + assert too_long is None + assert body == "output:\nR1# a\nR1# b" + + +def test_grep_python_syntax_works(): + # \d is valid Python re (a grep -E would treat it as literal 'd') + body, _ = shape_view("ip 10.0.0.1\nip foo\n", grep=r"ip 10\.\d+", full=False) + assert "10.0.0.1" in body and "foo" not in body + + +def test_grep_miss_points_at_regrep(): + body, too_long = shape_view("aaa\nbbb\n", grep="zzz", full=False) + assert too_long is None + assert "matched nothing" in body and "2 lines captured" in body + assert "regrep=true" in body + + +def test_invalid_grep_is_a_plain_error(): + body, too_long = shape_view("aaa\n", grep="([unclosed", full=False) + assert too_long is None + assert body.startswith("invalid grep pattern") + + +def test_long_output_trips_the_funnel(): + text = "\n".join(f"line {i}" for i in range(60)) + body, too_long = shape_view(text, grep=None, full=False) + assert too_long == {"lines": 60, "grep": None} + assert body.startswith("output: 60 lines total — first 10 shown:\nline 0\n") + assert body.endswith("line 9\n---") + + +def test_full_returns_the_tail_with_header(): + text = "\n".join(f"line {i}" for i in range(500)) + body, too_long = shape_view(text, grep=None, full=True) + assert too_long is None + assert body.startswith("output: last 400 of 500 lines (line cap 400)\nline 100\n") + + +# ── sessions against a fake subprocess ────────────────────────────────── + + +@pytest.mark.asyncio +async def test_one_shot_session_collects_output_and_feeds_lines(): + proc = _FakeProc([b"Welcome\r\n", b"R1# show version\r\n", b"uptime 5m\r\n"]) + recorder = _SpawnRecorder(proc) + with ( + patch(f"{AH}._get_connector", return_value=_MockConnector(_node_payload())), + patch(f"{CE}._spawn", recorder), + ): + result = await console_exec( + "11111111-1111-1111-1111-111111111111", + "22222222-2222-2222-2222-222222222222", + "show version", + 5, + gns3_ctx=_ctx(), + ) + + assert result.startswith("output:\n") + assert "uptime 5m" in result + assert proc.stdin.received == [b"show version\r\n"] + assert proc.stdin.closed # stdin half-closed after feeding (--no-close keeps the session) + url, seconds = recorder.calls[0] + assert url == "ws://127.0.0.1:3080/v3/projects/p-uuid-1/nodes/n-uuid-1/console/ws?token=jwt-abc" + assert seconds == 5 + + +@pytest.mark.asyncio +async def test_empty_command_sends_a_single_enter(): + proc = _FakeProc([b"PC1> \r\n"]) + with ( + patch(f"{AH}._get_connector", return_value=_MockConnector(_node_payload())), + patch(f"{CE}._spawn", _SpawnRecorder(proc)), + ): + result = await console_exec( + "11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222", "", 3, gns3_ctx=_ctx() + ) + assert proc.stdin.received == [b"\r\n"] + assert "PC1>" in result + + +@pytest.mark.asyncio +async def test_timeout_is_clamped_to_the_allowed_range(): + proc = _FakeProc([b"PC1> \r\n"]) + recorder = _SpawnRecorder(proc) + with ( + patch(f"{AH}._get_connector", return_value=_MockConnector(_node_payload())), + patch(f"{CE}._spawn", recorder), + ): + await console_exec( + "11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222", "", 9999, gns3_ctx=_ctx() + ) + assert recorder.calls[0][1] == 300 + + +@pytest.mark.asyncio +async def test_missing_websocat_is_a_plain_install_hint(): + proc = _FakeProc([], stderr_chunks=[b"timeout: failed to run command 'websocat': No such file"], returncode=125) + with ( + patch(f"{AH}._get_connector", return_value=_MockConnector(_node_payload())), + patch(f"{CE}._spawn", _SpawnRecorder(proc)), + ): + result = await console_exec( + "11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222", "x", 3, gns3_ctx=_ctx() + ) + assert "websocat is not installed" in result + assert "install" in result + + +@pytest.mark.asyncio +async def test_silent_console_reports_the_window(): + proc = _FakeProc([], returncode=124) + with ( + patch(f"{AH}._get_connector", return_value=_MockConnector(_node_payload())), + patch(f"{CE}._spawn", _SpawnRecorder(proc)), + ): + result = await console_exec( + "11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222", "x", 8, gns3_ctx=_ctx() + ) + assert "no console output within 8s" in result + assert "larger timeout" in result + + +@pytest.mark.asyncio +async def test_node_not_started_is_rejected_before_spawning(): + recorder = _SpawnRecorder() + with ( + patch(f"{AH}._get_connector", return_value=_MockConnector(_node_payload(status="stopped"))), + patch(f"{CE}._spawn", recorder), + ): + result = await console_exec( + "11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222", "x", 3, gns3_ctx=_ctx() + ) + assert "stopped" in result + assert recorder.calls == [] + + +@pytest.mark.asyncio +async def test_vnc_console_has_no_text_channel(): + with ( + patch(f"{AH}._get_connector", return_value=_MockConnector(_node_payload(console_type="vnc"))), + patch(f"{CE}._spawn", _SpawnRecorder()), + ): + result = await console_exec( + "11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222", "x", 3, gns3_ctx=_ctx() + ) + assert "VNC" in result + + +@pytest.mark.asyncio +async def test_project_and_node_names_resolve_to_uuids(): + projects = [{"project_id": "p-uuid-1", "name": "ospf-lab"}] + nodes = [{"node_id": "n-uuid-1", "name": "R1"}] + connector = _RoutingConnector(projects, nodes, _node_payload()) + proc = _FakeProc([b"R1# \r\n"]) + with ( + patch(f"{AH}._get_connector", return_value=connector), + patch(f"{PROJECTS}._get_connector", return_value=connector), + patch(f"{CE}._spawn", _SpawnRecorder(proc)), + ): + result = await console_exec("ospf-lab", "R1", "show version", 3, gns3_ctx=_ctx()) + assert "R1#" in result + + +@pytest.mark.asyncio +async def test_unknown_node_name_lists_known_names(): + projects = [{"project_id": "p-uuid-1", "name": "ospf-lab"}] + nodes = [{"node_id": "n-uuid-1", "name": "R1"}] + connector = _RoutingConnector(projects, nodes, _node_payload()) + with ( + patch(f"{AH}._get_connector", return_value=connector), + patch(f"{PROJECTS}._get_connector", return_value=connector), + patch(f"{CE}._spawn", _SpawnRecorder()), + ): + result = await console_exec("ospf-lab", "ghost", "x", 3, gns3_ctx=_ctx()) + assert "Node 'ghost' not found" in result + assert "R1" in result # known names come back with the failure + + +@pytest.mark.asyncio +async def test_regrep_filters_the_cache_without_a_new_session(): + lines = [f"R1# line {i}" for i in range(6)] + proc = _FakeProc(["\n".join(lines).encode()]) + recorder = _SpawnRecorder(proc) + with ( + patch(f"{AH}._get_connector", return_value=_MockConnector(_node_payload())), + patch(f"{CE}._spawn", recorder), + ): + first = await console_exec( + "11111111-1111-1111-1111-111111111111", + "22222222-2222-2222-2222-222222222222", + "show thing", + 3, + gns3_ctx=_ctx(), + ) + assert "line 3" in first + # second look: no re-run, no second spawn + second = await console_exec( + "11111111-1111-1111-1111-111111111111", + "22222222-2222-2222-2222-222222222222", + "", + 3, + grep="line [3-4]$", + regrep=True, + gns3_ctx=_ctx(), + ) + assert "line 3" in second and "line 4" in second + assert "line 0" not in second + assert len(recorder.calls) == 1 + + +@pytest.mark.asyncio +async def test_regrep_without_cache_says_so(): + with ( + patch(f"{AH}._get_connector", return_value=_MockConnector(_node_payload())), + patch(f"{CE}._spawn", _SpawnRecorder()), + ): + result = await console_exec( + "11111111-1111-1111-1111-111111111111", + "22222222-2222-2222-2222-222222222222", + "", + 3, + grep="x", + regrep=True, + gns3_ctx=_ctx(), + ) + assert "no captured output" in result + + +@pytest.mark.asyncio +async def test_long_output_writes_capture_file_and_mints_path_ticket(): + text = "\n".join(f"line {i}" for i in range(60)) + "\n" + proc = _FakeProc([text.encode()]) + connector = _MockConnector(_node_payload()) + with ( + patch(f"{AH}._get_connector", return_value=connector), + patch(f"{CE}._spawn", _SpawnRecorder(proc)), + ): + result = await console_exec( + "11111111-1111-1111-1111-111111111111", + "22222222-2222-2222-2222-222222222222", + "show tech", + 5, + gns3_ctx=_ctx(), + ) + + assert "60 lines total" in result + assert "regrep=true" in result and "full=true" in result + assert ( + "curl -o console-capture.txt " + "'http://127.0.0.1:3080/v3/projects/p-uuid-1/nodes/n-uuid-1/files/console-capture.txt?token=gns3t_" in result + ) + # the full raw capture was pushed through the node files API + posts = [(m, u) for m, u, _ in connector.calls if m == "post"] + assert posts == [("post", "http://127.0.0.1:3080/v3/projects/p-uuid-1/nodes/n-uuid-1/files/console-capture.txt")] + # the embedded ticket redeems for exactly that path + from gns3server.services import access_ticket_service + + url = result.split("curl -o console-capture.txt '")[1].split("'")[0] + ticket = url.split("token=")[1] + redeemed = access_ticket_service.redeem_for_path( + ticket, "/v3/projects/p-uuid-1/nodes/n-uuid-1/files/console-capture.txt" + ) + assert redeemed is not None and redeemed.username == "admin" + # the ticket is path-bound: it must not open anything else + assert ( + access_ticket_service.redeem_for_path(ticket, "/v3/projects/p-uuid-1/nodes/other/files/console-capture.txt") + is None + ) + + +@pytest.mark.asyncio +async def test_short_output_does_not_write_a_capture_file(): + proc = _FakeProc([b"R1# ok\r\n"]) + connector = _MockConnector(_node_payload()) + with ( + patch(f"{AH}._get_connector", return_value=connector), + patch(f"{CE}._spawn", _SpawnRecorder(proc)), + ): + await console_exec( + "11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222", "x", 3, gns3_ctx=_ctx() + ) + assert [m for m, _, _ in connector.calls if m == "post"] == [] + + +@pytest.mark.asyncio +async def test_grep_hit_on_long_output_returns_only_matches(): + # filtered view fits the direct budget: no funnel, no capture file write + text = "\n".join(f"row {i} keep" if i % 10 == 0 else f"row {i}" for i in range(200)) + "\n" + proc = _FakeProc([text.encode()]) + connector = _MockConnector(_node_payload()) + with ( + patch(f"{AH}._get_connector", return_value=connector), + patch(f"{CE}._spawn", _SpawnRecorder(proc)), + ): + result = await console_exec( + "11111111-1111-1111-1111-111111111111", + "22222222-2222-2222-2222-222222222222", + "show big", + 5, + grep=" keep$", + gns3_ctx=_ctx(), + ) + assert result.count("keep") == 20 # exactly the matching lines, none of the noise + assert [m for m, _, _ in connector.calls if m == "post"] == [] + + +# ── integration: the real websocat binary ─────────────────────────────── + + +@contextlib.asynccontextmanager +async def _serve_console(received, replies): + """aiohttp WS server behaving like a console: banner on connect (BINARY, + the way the compute side ships it), reply per received line.""" + + from aiohttp import WSMsgType, web + + async def handler(request): + ws = web.WebSocketResponse() + await ws.prepare(request) + await ws.send_bytes(b"Welcome to the console\r\n") + async for msg in ws: + if msg.type == WSMsgType.TEXT: + received.append(msg.data) + await ws.send_bytes(replies.encode()) + return ws + + app = web.Application() + app.router.add_get("/v3/projects/{project_id}/nodes/{node_id}/console/ws", handler) + runner = web.AppRunner(app) + await runner.setup() + site = web.TCPSite(runner, "127.0.0.1", 0) + await site.start() + port = site._server.sockets[0].getsockname()[1] + try: + yield f"http://127.0.0.1:{port}" + finally: + await runner.cleanup() + + +@pytest.mark.asyncio +@pytest.mark.skipif(shutil.which("websocat") is None, reason="websocat is not installed") +async def test_real_websocat_session_end_to_end(): + received = [] + async with _serve_console(received, replies="R1# show version\r\nuptime 5m\r\n") as base: + with patch(f"{AH}._get_connector", return_value=_MockConnector(_node_payload())): + result = await console_exec( + "11111111-1111-1111-1111-111111111111", + "22222222-2222-2222-2222-222222222222", + "show version", + 2, + gns3_ctx=_ctx(base), + ) + + assert "uptime 5m" in result + assert received == ["show version\r\n"] + + +@pytest.mark.asyncio +@pytest.mark.skipif(shutil.which("websocat") is None, reason="websocat is not installed") +async def test_real_websocat_stays_open_the_full_window(): + # --no-close: after stdin EOF the session keeps receiving until timeout + received = [] + async with _serve_console(received, replies="ok\r\n") as base: + with patch(f"{AH}._get_connector", return_value=_MockConnector(_node_payload())): + started = time.monotonic() + await console_exec( + "11111111-1111-1111-1111-111111111111", + "22222222-2222-2222-2222-222222222222", + "x", + 2, + gns3_ctx=_ctx(base), + ) + elapsed = time.monotonic() - started + + assert elapsed >= 1.8 # it did not bail out after the echo ack diff --git a/tests/agent/mcp/test_handlers.py b/tests/agent/mcp/test_handlers.py index cad7b89c0..5b40b0d38 100644 --- a/tests/agent/mcp/test_handlers.py +++ b/tests/agent/mcp/test_handlers.py @@ -327,44 +327,6 @@ class TestNode: result = suspend_node_handler({"project_id": "p1", "node_ids": ["n1"]}, ctx) assert result[0]["status"] == "success" - def test_console(self, ctx): - from gns3server.agent.gns3_copilot.gns3_client.api_handlers import get_node_console_info_handler - from gns3server.services import access_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 = access_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): conn = _mock_conn() diff --git a/tests/agent/mcp/test_tool_params.py b/tests/agent/mcp/test_tool_params.py index 40cf964c3..c56ba252c 100644 --- a/tests/agent/mcp/test_tool_params.py +++ b/tests/agent/mcp/test_tool_params.py @@ -43,7 +43,6 @@ HANDLER_FILES = { "create_node_handler": API_HANDLERS_FILE, "delete_node_handler": API_HANDLERS_FILE, "update_node_handler": API_HANDLERS_FILE, - "get_node_console_info_handler": API_HANDLERS_FILE, "list_node_files_handler": API_HANDLERS_FILE, "get_node_file_handler": API_HANDLERS_FILE, "write_node_file_handler": API_HANDLERS_FILE,