From 04a8ba06a86ad03e07149d8ce40182ab57d14a11 Mon Sep 17 00:00:00 2001 From: YueGuobin Date: Fri, 6 Nov 2026 15:42:51 +0800 Subject: [PATCH] fix: start pull events when the pull begins and reject unsafe image names The pull started event was emitted by the route before the pull took its per compute lock, so a request queued behind another pull claimed to be running while it was still waiting. The pull now reports the started state itself, once it owns the lock. Deleting an image interpolates the name into the daemon API path. The pattern on the path parameter limits it to the characters of an image reference and validate_docker_image_name also rejects "..", so a name cannot escape that path. Applied on both the controller and compute routes. --- gns3server/api/routes/compute/images.py | 18 +++++++++++---- gns3server/api/routes/controller/computes.py | 10 ++++++-- gns3server/compute/docker/__init__.py | 24 +++++++++++++------- gns3server/utils/images.py | 18 +++++++++++++++ tests/api/routes/compute/test_images.py | 22 ++++++++++++++++-- tests/api/routes/controller/test_computes.py | 15 ++++++++++++ tests/compute/docker/test_docker.py | 10 ++++++-- 7 files changed, 99 insertions(+), 18 deletions(-) diff --git a/gns3server/api/routes/compute/images.py b/gns3server/api/routes/compute/images.py index 4a34bf794..87b2fea43 100644 --- a/gns3server/api/routes/compute/images.py +++ b/gns3server/api/routes/compute/images.py @@ -23,7 +23,7 @@ import time import urllib.parse from typing import List, Optional -from fastapi import APIRouter, Body, HTTPException, Query, Request, status +from fastapi import APIRouter, Body, HTTPException, Path, Query, Request, status from fastapi.responses import FileResponse from gns3server.compute.docker import Docker @@ -32,6 +32,7 @@ from gns3server.compute.dynamips import Dynamips from gns3server.compute.iou import IOU from gns3server.compute.notification_manager import NotificationManager from gns3server.compute.qemu import Qemu +from gns3server.utils.images import DOCKER_IMAGE_NAME_PATTERN, validate_docker_image_name # Daemon progress lines arrive dozens of times per second per layer: emit at # most one downloading event per second per pull. @@ -83,13 +84,17 @@ async def pull_docker_image( def progress_callback(progress: dict) -> None: nonlocal last_emit + # the started event comes from the pull itself, once it owns the lock, + # and is never throttled + if progress.get("state") == "started": + emit("started", progress["message"]) + return now = time.monotonic() if now - last_emit < PULL_PROGRESS_INTERVAL: return last_emit = now emit("downloading", progress["message"], progress) - emit("started", f"Pulling '{image}' from Docker repository") try: await docker_manager.pull_image(image, progress_callback=progress_callback, force=True) except DockerError as e: @@ -120,7 +125,7 @@ async def load_docker_image( @router.delete("/docker/images/{image:path}", status_code=status.HTTP_204_NO_CONTENT) async def delete_docker_image( - image: str, + image: str = Path(..., pattern=DOCKER_IMAGE_NAME_PATTERN), force: bool = Query(False, description="Remove the image even if a container uses it"), ) -> None: """ @@ -130,8 +135,13 @@ async def delete_docker_image( one) and answers a conflict, unless force is set. """ + image = urllib.parse.unquote(image) + try: + validate_docker_image_name(image) + except ValueError as e: + raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(e)) from e docker_manager = Docker.instance() - await docker_manager.delete_image(urllib.parse.unquote(image), force=force) + await docker_manager.delete_image(image, force=force) @router.get("/dynamips/images") diff --git a/gns3server/api/routes/controller/computes.py b/gns3server/api/routes/controller/computes.py index 51c6f51d2..33ac14b1c 100644 --- a/gns3server/api/routes/controller/computes.py +++ b/gns3server/api/routes/controller/computes.py @@ -21,7 +21,7 @@ API routes for computes. from typing import Any, List, Optional, Union from uuid import UUID -from fastapi import APIRouter, Body, Depends, Query, Request, status +from fastapi import APIRouter, Body, Depends, HTTPException, Path, Query, Request, status import gns3server.db.models as models from gns3server import schemas @@ -30,6 +30,7 @@ from gns3server.controller.controller_error import ControllerBadRequestError, Co from gns3server.db.repositories.computes import ComputesRepository from gns3server.db.repositories.rbac import RbacRepository from gns3server.services.computes import ComputesService +from gns3server.utils.images import DOCKER_IMAGE_NAME_PATTERN, validate_docker_image_name from .dependencies.database import get_repository from .dependencies.rbac import has_privilege @@ -264,7 +265,7 @@ async def docker_load_image(compute_id: Union[str, UUID], request: Request) -> N ) async def docker_delete_image( compute_id: Union[str, UUID], - image: str, + image: str = Path(..., pattern=DOCKER_IMAGE_NAME_PATTERN), force: bool = Query(False, description="Remove the image even if a container uses it"), ) -> None: """ @@ -276,6 +277,11 @@ async def docker_delete_image( Required privilege: Compute.Modify """ + try: + validate_docker_image_name(image) + except ValueError as e: + raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(e)) from e + compute = Controller.instance().get_compute(str(compute_id)) await compute.http_query("DELETE", f"/docker/images/{image}", params={"force": str(force).lower()}) diff --git a/gns3server/compute/docker/__init__.py b/gns3server/compute/docker/__init__.py index bbe589626..44c2d3a01 100644 --- a/gns3server/compute/docker/__init__.py +++ b/gns3server/compute/docker/__init__.py @@ -368,10 +368,25 @@ class Docker(BaseManager): :params image: Image name :params progress_callback: A function that receives a dict with the - overall progress of the pull: layer counts and the latest daemon message + overall progress of the pull: layer counts and the latest daemon + message. The first call carries state="started" and happens once + the pull owns the compute pull lock, so a caller queued behind + another pull only sees it when the pull really begins. :params force: Pull the image even if it is already available locally """ + layers_total = 0 + layers_done = 0 + + def report(message, state=None): + if progress_callback: + progress = {"layers_total": layers_total, "layers_done": layers_done, "message": message} + if state is not None: + progress["state"] = state + progress_callback(progress) + + report(f"Pulling '{image}' from Docker repository", state="started") + if not force: try: await self.query("GET", f"images/{image}/json") @@ -379,13 +394,6 @@ class Docker(BaseManager): except DockerHttp404Error: pass - layers_total = 0 - layers_done = 0 - - def report(message): - if progress_callback: - progress_callback({"layers_total": layers_total, "layers_done": layers_done, "message": message}) - try: # The daemon streams progress lines for the whole pull: an idle # socket read for a minute means the registry is unreachable and diff --git a/gns3server/utils/images.py b/gns3server/utils/images.py index f61b80b61..327f28e81 100644 --- a/gns3server/utils/images.py +++ b/gns3server/utils/images.py @@ -53,6 +53,24 @@ log = logging.getLogger(__name__) # Include the first ISO 9660 volume descriptor in image type detection. IMAGE_HEADER_SIZE = 16 * 2048 + 7 +# A Docker image reference: name, optional registry, tag and digest. Callers +# must also reject ".." (not expressible here, the pydantic regex engine has no +# lookaround) so a name cannot escape the daemon API path it is interpolated +# into: see validate_docker_image_name. +DOCKER_IMAGE_NAME_PATTERN = r"^[a-zA-Z0-9][a-zA-Z0-9._/:@-]*$" + + +def validate_docker_image_name(image: str) -> None: + """ + Reject Docker image names that could escape the daemon API path they are + interpolated into. + + :raises ValueError: when the name is not safe + """ + + if ".." in image: + raise ValueError(f"Invalid Docker image name: {image}") + async def list_images(image_type): """ diff --git a/tests/api/routes/compute/test_images.py b/tests/api/routes/compute/test_images.py index ae3a22e4b..a104b9474 100644 --- a/tests/api/routes/compute/test_images.py +++ b/tests/api/routes/compute/test_images.py @@ -27,7 +27,12 @@ pytestmark = pytest.mark.asyncio class TestImagesRoutes: async def test_pull_docker_image(self, app: FastAPI, compute_client: AsyncClient) -> None: - with asyncio_patch("gns3server.compute.docker.Docker.pull_image") as mock: + async def fake_pull(image, progress_callback=None, force=False): + progress_callback( + {"layers_total": 0, "layers_done": 0, "message": "Pulling 'nginx:latest'", "state": "started"} + ) + + with asyncio_patch("gns3server.compute.docker.Docker.pull_image", side_effect=fake_pull) as mock: with asyncio_patch("gns3server.compute.notification_manager.NotificationManager.emit") as emit_mock: response = await compute_client.post( app.url_path_for("compute:pull_docker_image"), json={"image": "nginx:latest"} @@ -44,7 +49,11 @@ class TestImagesRoutes: async def test_pull_docker_image_progress_id(self, app: FastAPI, compute_client: AsyncClient) -> None: - with asyncio_patch("gns3server.compute.docker.Docker.pull_image"): + async def fake_pull(image, progress_callback=None, force=False): + progress_callback({"layers_total": 1, "layers_done": 0, "message": "Pulling", "state": "started"}) + progress_callback({"layers_total": 1, "layers_done": 0, "message": "[==> ] 10/100"}) + + with asyncio_patch("gns3server.compute.docker.Docker.pull_image", side_effect=fake_pull): with asyncio_patch("gns3server.compute.notification_manager.NotificationManager.emit") as emit_mock: response = await compute_client.post( app.url_path_for("compute:pull_docker_image"), @@ -57,6 +66,7 @@ class TestImagesRoutes: async def test_pull_docker_image_reports_downloading(self, app: FastAPI, compute_client: AsyncClient) -> None: async def fake_pull(image, progress_callback=None, force=False): + progress_callback({"layers_total": 2, "layers_done": 0, "message": "Pulling", "state": "started"}) progress_callback({"layers_total": 2, "layers_done": 1, "message": "[==> ] 40/100"}) with asyncio_patch("gns3server.compute.docker.Docker.pull_image", side_effect=fake_pull): @@ -118,6 +128,14 @@ class TestImagesRoutes: mock.assert_called_once_with("ios-xr/xrd-control-plane:24.4.1", force=False) assert response.status_code == status.HTTP_204_NO_CONTENT + async def test_delete_docker_image_rejects_path_traversal(self, app: FastAPI, compute_client: AsyncClient) -> None: + # percent encoded so the client does not normalize the ".." segments + # away before the request reaches the server + with asyncio_patch("gns3server.compute.docker.Docker.delete_image") as mock: + response = await compute_client.delete("/v3/compute/docker/images/a%2F..%2F..%2Fversion") + mock.assert_not_called() + assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT + async def test_delete_docker_image_force(self, app: FastAPI, compute_client: AsyncClient) -> None: with asyncio_patch("gns3server.compute.docker.Docker.delete_image") as mock: diff --git a/tests/api/routes/controller/test_computes.py b/tests/api/routes/controller/test_computes.py index c38b70592..976bad4f3 100644 --- a/tests/api/routes/controller/test_computes.py +++ b/tests/api/routes/controller/test_computes.py @@ -245,6 +245,21 @@ class TestComputeFeatures: ) assert response.status_code == status.HTTP_204_NO_CONTENT + async def test_compute_delete_docker_image_rejects_path_traversal( + self, app: FastAPI, client: AsyncClient, test_compute: Compute + ) -> None: + # percent encoded so the client does not normalize the ".." segments + # away before the request reaches the server + compute = MagicMock() + compute.http_query = AsyncioMagicMock(return_value={}) + with patch("gns3server.api.routes.controller.computes.Controller.instance") as controller: + controller.return_value.get_compute.return_value = compute + response = await client.delete( + f"/v3/computes/{test_compute.compute_id}/docker/images/a%2F..%2F..%2Fversion" + ) + compute.http_query.assert_not_called() + assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT + async def test_compute_load_docker_image(self, app: FastAPI, client: AsyncClient, test_compute: Compute) -> None: compute = MagicMock() diff --git a/tests/compute/docker/test_docker.py b/tests/compute/docker/test_docker.py index 721c06dee..92647e156 100644 --- a/tests/compute/docker/test_docker.py +++ b/tests/compute/docker/test_docker.py @@ -207,8 +207,14 @@ async def test_pull_image_reports_aggregated_progress(): with asyncio_patch("gns3server.compute.docker.Docker.http_query", return_value=response): await Docker.instance().pull_image("ubuntu", progress_callback=progress.append) # the callback sees the running totals of layers, not raw daemon lines - assert progress[0] == {"layers_total": 1, "layers_done": 0, "message": "Pulling fs layer"} - assert progress[1] == {"layers_total": 2, "layers_done": 0, "message": "Pulling fs layer"} + assert progress[0] == { + "layers_total": 0, + "layers_done": 0, + "message": "Pulling 'ubuntu' from Docker repository", + "state": "started", + } + assert progress[1] == {"layers_total": 1, "layers_done": 0, "message": "Pulling fs layer"} + assert progress[2] == {"layers_total": 2, "layers_done": 0, "message": "Pulling fs layer"} assert {"layers_total": 2, "layers_done": 0, "message": "[==> ] 40/100"} in progress assert progress[-1] == {"layers_total": 2, "layers_done": 2, "message": "Pull complete"}