fix: replace Bearer JWTs with path-bound access tickets in MCP download tools

link_capture_download and get_symbol embedded a 10-min JWT in the
Authorization header of the curl command they return; LLM clients
retyping that command corrupted the long token — the same failure
class as the console WebSocket URLs fixed in the previous commit.

Generalize the ticket store (console_tickets.py -> access_tickets.py,
ConsoleTicketService -> AccessTicketService): a ticket now binds to
either a node's console endpoints (WebSocket, matched against route
path params) or one exact REST resource path (capture file, symbol
image). The two binding modes are isolated — a node-bound ticket
cannot authenticate a REST resource and vice versa.

get_user_from_token redeems path-bound tickets through the existing
token parameter / Bearer header, matched exactly against
request.url.path, then reuses the shared user lookup and token_version
revocation checks. Download URLs embed ?token=<ticket> and the curl
commands no longer carry a Bearer header.
This commit is contained in:
YueGuobin committed 2026-08-29 01:10:19 +08:00
1 parent 6d6b5351fa
commit d1edfbe5e8
8 files changed
+293 -88

No files matched your search

@@ -53,8 +53,8 @@ from concurrent.futures import ThreadPoolExecutor
import hashlib
import logging
from gns3server.services import auth_service, console_ticket_service
from gns3server.services.console_tickets import DEFAULT_TICKET_TTL
from gns3server.services import access_ticket_service
from gns3server.services.access_tickets import DEFAULT_TICKET_TTL
from gns3server.agent.gns3_copilot.gns3_client.connector import Gns3Connector
@@ -423,7 +423,7 @@ def get_node_console_info_handler(params: dict[str, Any], gns3_ctx: dict[str, An
# 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 = console_ticket_service.mint(
ticket = access_ticket_service.mint(
username,
token_version=gns3_ctx.get("jwt_token_version", 0),
project_id=project_id,
@@ -859,34 +859,36 @@ def download_capture_file_handler(params: dict[str, Any], gns3_ctx: dict[str, An
if not project_id:
return {"error": "project_id is required"}
username = gns3_ctx.get("jwt_username")
download_token = auth_service.create_access_token(username, token_version=gns3_ctx.get("jwt_token_version", 0), expires_in=10) if username else None
token_version = gns3_ctx.get("jwt_token_version", 0)
def _download(link_id: str) -> dict[str, Any]:
# short-lived ticket bound to this exact download path — LLM clients
# retyping curl commands corrupted the long Bearer JWT this used to embed
path = f"/v3/projects/{project_id}/links/{link_id}/capture/file"
url = f"{gns3_ctx['server_url']}{path}"
ticket = access_ticket_service.mint(username, token_version=token_version, path=path) if username else None
if ticket:
url += f"?token={ticket}"
entry = {"link_id": link_id, "download_url": url}
if ticket:
entry["curl_command"] = f"curl -L -o capture_{link_id}.pcap '{url}'"
return entry
link_ids = params.get("link_ids")
if link_ids:
if not isinstance(link_ids, list):
return {"error": "link_ids must be a list"}
results = []
for lid in link_ids:
url = f"{gns3_ctx['server_url']}/v3/projects/{project_id}/links/{lid}/capture/file"
entry = {"link_id": lid, "download_url": url}
if download_token:
cmd = f"curl -L -o capture_{lid}.pcap -H 'Authorization: Bearer {download_token}' '{url}'"
entry["curl_command"] = cmd
results.append(entry)
return {"downloads": results, "count": len(results), "note": "Files are in pcap format. Links include a 10-minute token."}
results = [_download(lid) for lid in link_ids]
return {"downloads": results, "count": len(results), "note": "Files are in pcap format. URLs include a 10-minute ticket."}
link_id = params.get("link_id")
if not link_id:
return {"error": "link_id or link_ids is required"}
download_url = f"{gns3_ctx['server_url']}/v3/projects/{project_id}/links/{link_id}/capture/file"
result = {
"link_id": link_id,
"download_url": download_url,
"note": "The file is in pcap format and can be analyzed with Wireshark or tcpdump.",
}
if download_token:
result["curl_command"] = f"curl -L -o capture.pcap -H 'Authorization: Bearer {download_token}' '{download_url}'"
result["note"] += " The download link includes a 10-minute token."
result = _download(link_id)
result["note"] = "The file is in pcap format and can be analyzed with Wireshark or tcpdump."
if "curl_command" in result:
result["curl_command"] = f"curl -L -o capture.pcap '{result['download_url']}'"
result["note"] += " The download URL includes a 10-minute ticket."
return result
+13 -6
View File
@@ -23,7 +23,7 @@ from typing import Any
import logging
from gns3server.services import auth_service
from gns3server.services import access_ticket_service
log = logging.getLogger(__name__)
@@ -52,18 +52,25 @@ def get_symbol_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> dict
symbol_id = params.get("symbol_id")
if not symbol_id:
return {"error": "symbol_id is required"}
download_url = f"{gns3_ctx['server_url']}/v3/symbols/{symbol_id}/raw"
path = f"/v3/symbols/{symbol_id}/raw"
download_url = f"{gns3_ctx['server_url']}{path}"
username = gns3_ctx.get("jwt_username")
download_token = auth_service.create_access_token(username, token_version=gns3_ctx.get("jwt_token_version", 0), expires_in=10) if username else None
# short-lived ticket bound to this exact path — LLM clients retyping curl
# commands corrupted the long Bearer JWT this used to embed
ticket = access_ticket_service.mint(
username, token_version=gns3_ctx.get("jwt_token_version", 0), path=path
) if username else None
if ticket:
download_url += f"?token={ticket}"
result = {
"symbol_id": symbol_id,
"download_url": download_url,
"note": "Symbol files are SVG images.",
}
if download_token:
if ticket:
safe_name = symbol_id.replace(':', '').replace('/', '_')
result["curl_command"] = f"curl -L -o '{safe_name}.svg' -H 'Authorization: Bearer {download_token}' '{download_url}'"
result["note"] += " Download link includes a 10-minute token."
result["curl_command"] = f"curl -L -o '{safe_name}.svg' '{download_url}'"
result["note"] += " The download URL includes a 10-minute ticket."
return result
@@ -30,8 +30,8 @@ from gns3server.db.repositories.api_keys import ApiKeysRepository
from gns3server.db.repositories.users import UsersRepository
from gns3server.db.repositories.rbac import RbacRepository
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 gns3server.services import auth_service, access_ticket_service
from gns3server.services.access_tickets import TICKET_PREFIX
from .database import get_repository
log = logging.getLogger(__name__)
@@ -50,6 +50,7 @@ def _reject_refresh_token(token_data) -> None:
async def get_user_from_token(
request: Request,
bearer_token: str = Depends(oauth2_scheme),
user_repo: UsersRepository = Depends(get_repository(UsersRepository)),
api_keys_repo: ApiKeysRepository = Depends(get_repository(ApiKeysRepository)),
@@ -68,6 +69,38 @@ async def get_user_from_token(
headers={"WWW-Authenticate": "Bearer"},
)
if token.startswith(TICKET_PREFIX):
# Access tickets ("gns3t_…"): short-lived credentials bound to one
# exact resource path, minted by the MCP download tools (capture
# files, symbols). redeem_for_path() confines the ticket to that
# path, so it cannot be replayed against any other resource.
ticket = access_ticket_service.redeem_for_path(token, request.url.path)
if ticket is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired access ticket",
headers={"WWW-Authenticate": "Bearer"},
)
token_data = TokenData(
username=ticket.username,
token_version=ticket.token_version,
token_use="access",
)
user = await user_repo.get_user_by_username(token_data.username)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
if token_data.token_version != user.token_version:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Token has been revoked for '{token_data.username}'",
headers={"WWW-Authenticate": "Bearer"},
)
return user
# API Key authentication — format: gns3_<api_key_id>_<random_secret>
# Direct lookup by UUID avoids O(n) scan of all keys.
if token.startswith("gns3_"):
@@ -152,12 +185,12 @@ async def get_current_active_user_from_websocket(
try:
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)
# 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.
ticket = access_ticket_service.redeem(token, websocket.path_params)
if ticket is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
+2 -2
View File
@@ -15,7 +15,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .authentication import AuthService
from .console_tickets import ConsoleTicketService
from .access_tickets import AccessTicketService
auth_service = AuthService()
console_ticket_service = ConsoleTicketService()
access_ticket_service = AccessTicketService()
@@ -15,20 +15,27 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Short-lived console tickets.
Short-lived access 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
An access ticket is a short random string ("gns3t_" + 16 urlsafe chars) that
replaces the long JWTs previously embedded in URLs and curl commands 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.
A ticket is bound to exactly one target, in one of two modes:
- node binding (project_id + node_id): redeemable on that node's console
WebSocket endpoints (console/ws and console/vnc share the binding),
validated against the route's path parameters.
- path binding (exact resource path): redeemable on one REST resource path
(e.g. a capture file download or a symbol image), validated against
request.url.path.
Tickets are multi-use within their TTL, so clients that reconnect keep
working. Redemption re-checks the minting user's token_version, so logging
out invalidates outstanding tickets just like it invalidates JWTs.
"""
import logging
@@ -45,34 +52,36 @@ DEFAULT_TICKET_TTL = 600 # seconds
@dataclass
class ConsoleTicket:
class AccessTicket:
username: str
token_version: int
project_id: str
node_id: str
expires_at: float # time.monotonic() based
project_id: Optional[str] = None # node binding: console WebSocket endpoints
node_id: Optional[str] = None
path: Optional[str] = None # path binding: one exact REST resource path
expires_at: float = 0.0 # time.monotonic() based
class ConsoleTicketService:
class AccessTicketService:
"""
In-memory store for console tickets.
In-memory store for access tickets.
Single-process asyncio app: minting (MCP tool handlers, via worker
threads) and redemption (WS auth dependency, event loop) share one dict.
threads) and redemption (auth dependencies, 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] = {}
self._tickets: dict[str, AccessTicket] = {}
def mint(
self,
username: str,
token_version: int,
project_id: str,
node_id: str,
project_id: Optional[str] = None,
node_id: Optional[str] = None,
path: Optional[str] = None,
ttl: int = DEFAULT_TICKET_TTL,
) -> str:
# 12 random bytes → 16 urlsafe chars (~96 bits); comfortably
@@ -80,33 +89,58 @@ class ConsoleTicketService:
# LLM clients copy it without corruption.
ticket = TICKET_PREFIX + secrets.token_urlsafe(12)
self._sweep_expired()
self._tickets[ticket] = ConsoleTicket(
self._tickets[ticket] = AccessTicket(
username=username,
token_version=token_version,
project_id=project_id,
node_id=node_id,
path=path,
expires_at=time.monotonic() + ttl,
)
return ticket
def redeem(self, ticket: str, path_params: dict) -> Optional[ConsoleTicket]:
def redeem(self, ticket: str, path_params: dict) -> Optional[AccessTicket]:
"""
Validate a ticket against the route it is being used on.
Validate a node-bound ticket against a WebSocket route.
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.
parameter (notifications, web wireshark, …) always fail the binding,
and so do path-bound (REST) tickets.
"""
record = self._get_valid(ticket)
if record is None:
return None
if record.node_id is None or record.path is not 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 redeem_for_path(self, ticket: str, path: str) -> Optional[AccessTicket]:
"""
Validate a path-bound ticket against a REST resource path.
The path must match exactly — a ticket minted for one capture file
download cannot be replayed against any other resource.
"""
record = self._get_valid(ticket)
if record is None:
return None
if record.path is None or record.path != path:
return None
return record
def _get_valid(self, ticket: str) -> Optional[AccessTicket]:
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: