diff --git a/gns3server/api/operation_ids.py b/gns3server/api/operation_ids.py index ae8c9a2ae..290026c35 100644 --- a/gns3server/api/operation_ids.py +++ b/gns3server/api/operation_ids.py @@ -20,7 +20,7 @@ Readable and unique OpenAPI operationIds. """ import re -from typing import Callable +from typing import Callable, Sequence from fastapi import APIRouter from fastapi.routing import APIRoute @@ -46,10 +46,13 @@ def generate_operation_id(route: APIRoute) -> str: return name -def add_stub_routes(router: APIRouter, endpoint: Callable, name: str) -> None: +def add_stub_routes(router: APIRouter, endpoint: Callable, name: str, paths: Sequence[str] = ("/{path:path}",)) -> None: """ - Registers a catch-all route per HTTP method so that every method gets its own operationId. + Registers a stub route per path and HTTP method so that every method gets its own operationId. + The default path is a catch-all for everything under the router prefix. """ - for method in STUB_METHODS: - router.add_api_route("/{path:path}", endpoint, methods=[method], name=f"{name}_{method.lower()}") + for index, path in enumerate(paths): + suffix = f"_{index}" if len(paths) > 1 else "" + for method in STUB_METHODS: + router.add_api_route(path, endpoint, methods=[method], name=f"{name}{suffix}_{method.lower()}") diff --git a/gns3server/api/routes/controller/__init__.py b/gns3server/api/routes/controller/__init__.py index 9ebf5a2df..0de9cdc2a 100644 --- a/gns3server/api/routes/controller/__init__.py +++ b/gns3server/api/routes/controller/__init__.py @@ -21,6 +21,37 @@ from gns3server.agent import AI_COPILOT_AVAILABLE from gns3server.api.operation_ids import add_stub_routes from gns3server.config import Config +# The LLM model configuration routes share the /access prefix with users, groups and API keys, +# so their stub must cover only their own paths: a catch-all under /access would answer 501 for +# every /access route included after it (e.g. creating an API key). +LLM_STUB_PATHS = ( + "/users/{user_id}/llm-model-configs{rest:path}", + "/groups/{group_id}/llm-model-configs{rest:path}", +) + + +async def ai_not_available(): + raise HTTPException( + status_code=status.HTTP_501_NOT_IMPLEMENTED, + detail="AI Copilot is not available. Install AI dependencies with: pip install gns3-server[ai-features]", + ) + + +def build_ai_stub_routers() -> tuple[APIRouter, APIRouter, APIRouter]: + """ + Stub routers (chat, copilot, LLM model configurations) that answer 501 + when the AI dependencies are not installed. + """ + + chat_router = APIRouter() + copilot_router = APIRouter() + llm_router = APIRouter() + add_stub_routes(chat_router, ai_not_available, "chat_not_available") + add_stub_routes(copilot_router, ai_not_available, "copilot_not_available") + add_stub_routes(llm_router, ai_not_available, "llm_not_available", paths=LLM_STUB_PATHS) + return chat_router, copilot_router, llm_router + + # Conditionally import AI-dependent routes if AI_COPILOT_AVAILABLE: from . import chat, copilot, llm_model_configs @@ -29,25 +60,7 @@ if AI_COPILOT_AVAILABLE: _copilot_router = copilot.router _llm_router = llm_model_configs.router else: - # Create stub routers that return 501 for all AI endpoints - _chat_router = APIRouter() - _copilot_router = APIRouter() - _llm_router = APIRouter() - - @_chat_router.api_route("/{path:path}", methods=["GET", "POST", "DELETE", "PATCH", "PUT"], include_in_schema=False) - @_copilot_router.api_route( - "/{path:path}", methods=["GET", "POST", "DELETE", "PATCH", "PUT"], include_in_schema=False - ) - @_llm_router.api_route("/{path:path}", methods=["GET", "POST", "DELETE", "PATCH", "PUT"], include_in_schema=False) - async def ai_not_available(path: str = ""): - raise HTTPException( - status_code=status.HTTP_501_NOT_IMPLEMENTED, - detail="AI Copilot is not available. Install AI dependencies with: pip install gns3-server[ai-features]", - ) - - add_stub_routes(_chat_router, ai_not_available, "chat_not_available") - add_stub_routes(_copilot_router, ai_not_available, "copilot_not_available") - add_stub_routes(_llm_router, ai_not_available, "llm_not_available") + _chat_router, _copilot_router, _llm_router = build_ai_stub_routers() from . import ( diff --git a/tests/api/routes/controller/test_ai_stub_routes.py b/tests/api/routes/controller/test_ai_stub_routes.py new file mode 100644 index 000000000..1292297c5 --- /dev/null +++ b/tests/api/routes/controller/test_ai_stub_routes.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# 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 pytest +from fastapi import APIRouter, FastAPI, status +from httpx import ASGITransport, AsyncClient + +from gns3server.api.routes.controller import build_ai_stub_routers + +pytestmark = pytest.mark.asyncio + + +@pytest.fixture +def stub_app() -> FastAPI: + """ + The /access layout of the controller API without the AI dependencies: + the LLM stub is included before a later /access router, as API keys are. + """ + + _, _, llm_router = build_ai_stub_routers() + later_router = APIRouter() + + @later_router.post("/access/api-keys") + async def create_api_key(): + return {"created": True} + + application = FastAPI() + application.include_router(llm_router, prefix="/v3/access") + application.include_router(later_router, prefix="/v3") + return application + + +async def test_llm_stub_does_not_shadow_later_access_routes(stub_app: FastAPI) -> None: + + async with AsyncClient(transport=ASGITransport(app=stub_app), base_url="http://test") as client: + response = await client.post("/v3/access/api-keys") + assert response.status_code == status.HTTP_200_OK + assert response.json() == {"created": True} + + +@pytest.mark.parametrize( + "method, path", + [ + ("GET", "/v3/access/users/1/llm-model-configs"), + ("GET", "/v3/access/users/1/llm-model-configs/own"), + ("POST", "/v3/access/users/1/llm-model-configs"), + ("PUT", "/v3/access/users/1/llm-model-configs/default/2"), + ("DELETE", "/v3/access/groups/1/llm-model-configs/2"), + ], +) +async def test_llm_stub_answers_llm_paths(stub_app: FastAPI, method: str, path: str) -> None: + + async with AsyncClient(transport=ASGITransport(app=stub_app), base_url="http://test") as client: + response = await client.request(method, path) + assert response.status_code == status.HTTP_501_NOT_IMPLEMENTED + assert "AI Copilot is not available" in response.json()["detail"] + + +async def test_create_api_key(app: FastAPI, client: AsyncClient) -> None: + + response = await client.post(app.url_path_for("create_api_key"), json={"name": "stub-check"}) + assert response.status_code == status.HTTP_201_CREATED + assert response.json()["api_key"].startswith("gns3_")