1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-01 08:26:03 +00:00

fix(api): an error's status says what it is, and its body is always {"detail"}

- libvirt errors all answered 400. A VM, pool or volume the host does not
  have now answers 404, a volume in use 409 (vrtManager.util.InUse) and a
  host that cannot be reached 503, which a client may retry.
- A template's power on or cycle and a stopped pool answered
  {"status": ...} with 409; they answer {"detail": ...}, as every other
  refusal. The schema documents these 409s (ErrorSerializer).
- The volume list and a volume of a stopped pool answered 200 with an
  empty list or a made-up volume; they answer 409.
- An API URL that names nothing answered the HTML error page; it answers
  a JSON 404 after the API's authentication.
- A session that must change its password was redirected to the HTML
  form; an API request of it gets the JSON 403 a token gets.
This commit is contained in:
catborise 2026-11-07 00:19:13 +03:00
parent 9d22d48a85
commit 0610c23a34
14 changed files with 145 additions and 36 deletions

View file

@ -6,11 +6,13 @@ from django.http import JsonResponse
from django.shortcuts import redirect, render
from django.utils.http import url_has_allowed_host_and_scheme
from django.utils.translation import gettext_lazy as _
import libvirt
from libvirt import libvirtError
from logs.audit import request_ip, write
from operations import claims, jobs
from operations.utils import busy_message, public_error_text, said, summary, words
from vrtManager.util import ConnectionFailed, InUse
from webvirtcloud.log_context import current_request
API_PREFIX = "/api/"
@ -46,6 +48,29 @@ def error_text(request, exception):
return public_error_text(exception)
# libvirt's "no such object" errors
NOT_FOUND_CODES = {
libvirt.VIR_ERR_NO_DOMAIN, libvirt.VIR_ERR_NO_DOMAIN_SNAPSHOT, libvirt.VIR_ERR_NO_STORAGE_POOL,
libvirt.VIR_ERR_NO_STORAGE_VOL, libvirt.VIR_ERR_NO_NETWORK, libvirt.VIR_ERR_NO_INTERFACE,
libvirt.VIR_ERR_NO_NWFILTER, libvirt.VIR_ERR_NO_SECRET, libvirt.VIR_ERR_NO_NODE_DEVICE,
}
def api_status(request, exception):
"""An API client's status for a libvirt error: 404 for an object the host
does not have, 409 for one in use, 503 for a host that cannot be reached
(a client may try again), else 400. Only a read or a delete names the
object not found: an action (POST) may miss another one it needs, as a
VM's removed network, and the VM is there."""
if isinstance(exception, InUse):
return 409
if isinstance(exception, ConnectionFailed):
return 503
if request.method in ("GET", "HEAD", "DELETE") and exception.get_error_code() in NOT_FOUND_CODES:
return 404
return 400
class RequestIdMiddleware:
"""Names the request for its log lines (see log_context) and sends the ID back in X-Request-ID."""
@ -106,7 +131,7 @@ class ExceptionMiddleware:
# API clients get JSON with a failure status, not the HTML error page.
if request.path_info.startswith(API_PREFIX):
if isinstance(exception, libvirtError):
return JsonResponse({"detail": error_text(request, exception)}, status=400)
return JsonResponse({"detail": error_text(request, exception)}, status=api_status(request, exception))
if isinstance(exception, claims.Busy):
return JsonResponse({"detail": busy_message(exception, request.user),
"operation": summary(exception.blocker, request.user) if exception.blocker else None},

View file

@ -7,6 +7,12 @@ class StatusSerializer(serializers.Serializer):
status = serializers.CharField()
class ErrorSerializer(serializers.Serializer):
"""Response body of a refused request: why, as DRF's own errors."""
detail = serializers.CharField()
class ActionStatusSerializer(StatusSerializer):
"""A VM action's status and what the web page would have shown after it,
such as a disk that was kept or a template that was not started."""

View file

@ -3,6 +3,7 @@ import os
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.test import TestCase
from drf_spectacular.generators import SchemaGenerator
from rest_framework.response import Response
from rest_framework.test import APIClient, APIRequestFactory
from rest_framework.views import APIView
@ -21,6 +22,26 @@ class APISchemaTestCase(TestCase):
self.assertEqual(client.get("/api/v1/computes/abc/instances/").status_code, 404)
self.assertEqual(client.get("/api/v1/instances/abc/").status_code, 404)
def test_an_api_url_that_names_nothing_is_a_json_404_after_authentication(self):
# it was the HTML error page
client = APIClient()
self.assertEqual(client.get("/api/v1/nothere/").status_code, 401)
client.force_login(get_user_model().objects.create_user("schema_user", password="pw"))
for url in ("/api/v1/nothere/", "/api/v1/nothere", "/api/v1/instances/1/x/", "/api/", "/api/v1/", "/api/nope/"):
with self.subTest(url):
response = client.get(url, follow=True)
self.assertEqual((response.status_code, response.json()), (404, {"detail": "Not found."}))
for method in ("head", "options"):
with self.subTest(method):
self.assertEqual(getattr(client, method)("/api/v1/nothere/").status_code, 404)
self.assertEqual(client.get("/api/schema/").status_code, 200)
def test_a_refusal_s_body_is_documented_with_its_409(self):
schema = SchemaGenerator().get_schema(request=None, public=True)
poweron = schema["paths"]["/api/v1/computes/{compute_pk}/instances/{id}/poweron/"]["post"]
self.assertEqual(poweron["responses"]["409"]["content"]["application/json"]["schema"]["$ref"],
"#/components/schemas/Error")
class SchemaPermissionTestCase(TestCase):
def test_schema_requires_login(self):

View file

@ -206,10 +206,14 @@ class AuthorizationMatrixTestCase(TestCase):
data["sshkeyid"] = key.pk
response = self.client.post(url, data, HTTP_REFERER=f"/instances/{self.instance.pk}/")
if response.status_code >= 500:
# Only the fixture's explicit libvirt failure is an acceptable
# authorization outcome. Unexpected failures must fail the test.
self.assertEqual(response.status_code, 500)
self.assertTrue(response.context and response.context.get("libvirt_error"))
# Only the fixture's explicit libvirt failure (its host is not
# reached) is an acceptable authorization outcome: the page's error
# page, the API's 503. Unexpected failures must fail the test.
if url.startswith("/api/"):
self.assertEqual(response.status_code, 503)
else:
self.assertEqual(response.status_code, 500)
self.assertTrue(response.context and response.context.get("libvirt_error"))
return response
def _url(self, name, params):

View file

@ -11,7 +11,7 @@ from django.contrib.messages import get_messages
from django.contrib.messages.storage.fallback import FallbackStorage
from django.contrib.sessions.middleware import SessionMiddleware
from django.test import RequestFactory, TestCase
from vrtManager.util import ConnectionFailed
from vrtManager.util import ConnectionFailed, InUse, OperationError
from webvirtcloud.middleware import ExceptionMiddleware, error_text
HOST_DETAIL = "ssh: connect to host 10.0.0.9 port 22: No route to host"
@ -90,11 +90,25 @@ class ConnectionErrorPageTests(TestCase):
def test_api_answers_the_same_way(self):
response, _ = self.handle(self.owner, ConnectionFailed(f"Connection Failed: {HOST_DETAIL}"), path="/api/v1/instances/1/")
self.assertEqual(response.status_code, 400)
self.assertEqual(response.status_code, 503) # a client may try again
self.assertNotIn(b"10.0.0.9", response.content)
response, _ = self.handle(self.admin, ConnectionFailed(f"Connection Failed: {HOST_DETAIL}"), path="/api/v1/instances/1/")
self.assertIn(b"10.0.0.9", response.content)
def test_the_api_s_status_says_what_kind_of_error_it_is(self):
for error, expected, method in (
(libvirt_error(libvirt.VIR_FROM_STORAGE, "Storage pool not found", libvirt.VIR_ERR_NO_STORAGE_POOL), 404, "get"),
(libvirt_error(libvirt.VIR_FROM_QEMU, "Domain not found", libvirt.VIR_ERR_NO_DOMAIN), 404, "delete"),
# starting a VM whose network was removed: the VM is there
(libvirt_error(libvirt.VIR_FROM_NETWORK, "Network not found", libvirt.VIR_ERR_NO_NETWORK), 400, "post"),
(InUse("Volume %(name)s is in use", name="a.qcow2"), 409, "delete"),
(libvirt_error(libvirt.VIR_FROM_QEMU, "Requested operation is not valid", libvirt.VIR_ERR_OPERATION_INVALID), 400, "post"),
(OperationError("Invalid cache mode"), 400, "post"),
):
with self.subTest(str(error)):
response, _ = self.handle(self.admin, error, path="/api/v1/instances/1/", method=method)
self.assertEqual(response.status_code, expected)
def test_views_that_report_the_error_themselves(self):
request = RequestFactory().post("/")
request.user = self.owner

View file

@ -5,10 +5,24 @@ from drf_spectacular.views import (
SpectacularRedocView,
SpectacularSwaggerSplitView,
)
from drf_spectacular.utils import extend_schema
from rest_framework.decorators import api_view
from rest_framework.exceptions import NotFound
from appsettings.views import appsettings
from console.views import console
from instances.views import index
@extend_schema(exclude=True)
@api_view(["GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE"])
def api_not_found(request):
"""An API URL that names nothing: JSON, after the API's authentication, as
every other API answer. Only one with a trailing slash: one without is
redirected to it first."""
raise NotFound
urlpatterns = [
path("", index, name="index"),
path("admin/", include(("admin.urls", "admin"), namespace="admin")),
@ -26,6 +40,7 @@ urlpatterns = [
re_path(r"^swagger\.(?P<format>json|yaml)$", SpectacularAPIView.as_view(), name="schema-json"),
path("swagger/", SpectacularSwaggerSplitView.as_view(url_name="schema"), name="schema-swagger-ui"),
path("redoc/", SpectacularRedocView.as_view(url_name="schema"), name="schema-redoc"),
re_path(r"^api/(?:.*/)?$", api_not_found),
]
if settings.DEBUG: