Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(devex): declare path parameter types once per view (#126420)

Julian Bezd054ef9a796f
diff --git a/.agents/skills/isolating-product-facade-contracts/SKILL.md b/.agents/skills/isolating-product-facade-contracts/SKILL.md
index c06f41df66f4..8ae23079286d 100644
--- a/.agents/skills/isolating-product-facade-contracts/SKILL.md
+++ b/.agents/skills/isolating-product-facade-contracts/SKILL.md
@@ -271,6 +271,7 @@ records the decrease. See `products/architecture.md` § Wiring couplings.
- Keep facades thin; put business rules behind the facade, in `logic/` by default. Other internal packages (`services/`, `reviewer/`, …) are fine as long as they stay behind the facade.
- Transaction boundaries belong in the facade (or logic), not in views.
- A view that serves a contract checks object RBAC through an `ObjectAccessRef`: return one from `safely_get_object()`, or pass one to `self.check_object_permissions(request, ref)`. Never check by hand or in the facade. See `products/architecture.md` § Who owns RBAC?
+- A view without a `queryset` declares its URL kwarg types with `path_parameters = {"pk": UUID}`, and does not parse path ids by hand. See `products/architecture.md` § Path ids.
- Never return ORM models across product boundaries.
- A list view pages through the facade: the facade takes a `PageRequest` and returns a `Page`, and the view uses `FacadeLimitOffsetPagination` or `FacadeCursorPagination`. Never set paginator state by hand. See `products/architecture.md` § How do lists page?
- `hogli product:lint` reads the facade signatures, in the kinds `facade-returns`,
diff --git a/posthog/api/documentation.py b/posthog/api/documentation.py
index 867adf146cd4..1437b4945fcc 100644
--- a/posthog/api/documentation.py
+++ b/posthog/api/documentation.py
@@ -1,7 +1,8 @@
import os
import re
import copy
-from typing import Any, get_args
+from typing import TYPE_CHECKING, Any, get_args
+from uuid import UUID
from django.core.exceptions import ImproperlyConfigured
from django.db import models
@@ -32,6 +33,9 @@ from posthog.products import is_product_module
from products.feature_flags.backend.types import PropertyFilterType
+if TYPE_CHECKING:
+ from posthog.api.routing import PathParameter
+
# Path parameters that are resolved at runtime by TeamAndOrgViewSetMixin and
# therefore cannot be derived from any model field. We pre-supply their
# OpenAPI types so drf-spectacular never falls through to the warning path.
@@ -42,6 +46,13 @@ _KNOWN_PATH_PARAMS: dict[str, dict[str, Any]] = {
"plugin_config_id": {"schema": build_basic_type(OpenApiTypes.INT), "description": ""},
}
+# OpenAPI schemas for the types a view can declare in TeamAndOrgViewSetMixin.path_parameters.
+_DECLARED_PATH_PARAM_SCHEMAS: dict[type, dict[str, str]] = {
+ UUID: {"type": "string", "format": "uuid"},
+ int: {"type": "integer"},
+ str: {"type": "string"},
+}
+
# Canonical parameter component definitions for the highest-frequency path params. drf-spectacular
# inlines these into every operation that uses them — ``project_id`` alone shows up ~1100 times in
@@ -112,6 +123,18 @@ class PostHogAutoSchema(AutoSchema):
operation["x-request-dependent-scopes"] = True
return operation
+ def _declared_path_parameter(self, variable: str) -> "PathParameter | None":
+ # routing imports this module through posthog.api.utils, so a module-level import is circular.
+ from posthog.api.routing import as_path_parameter # noqa: PLC0415
+
+ declared = getattr(self.view, "path_parameters", {})
+ if variable in declared:
+ return as_path_parameter(declared[variable])
+ # The router names the detail kwarg `pk`, and drf-spectacular renames `{pk}` to `{id}` in the path.
+ if variable == "id" and "pk" in declared:
+ return as_path_parameter(declared["pk"])
+ return None
+
def _resolve_path_parameters(self, variables):
from drf_spectacular.plumbing import get_view_model, resolve_django_path_parameter, resolve_regex_path_parameter
@@ -119,6 +142,7 @@ class PostHogAutoSchema(AutoSchema):
parameters = []
for variable in variables:
+ declared = self._declared_path_parameter(variable)
if variable in _KNOWN_PATH_PARAMS:
# Params handled by TeamAndOrgViewSetMixin — not derivable from any model.
parameters.append(
@@ -129,6 +153,16 @@ class PostHogAutoSchema(AutoSchema):
schema=_KNOWN_PATH_PARAMS[variable]["schema"],
)
)
+ elif declared is not None:
+ # TeamAndOrgViewSetMixin parses the kwarg to this type, so the schema states the same type.
+ parameters.append(
+ build_parameter_type(
+ name=variable,
+ location=OpenApiParameter.PATH,
+ description=declared.description,
+ schema=_DECLARED_PATH_PARAM_SCHEMAS[declared.type],
+ )
+ )
elif model is None:
# No queryset — try to resolve from the URL pattern (e.g. <int:id>),
# otherwise default to string without warning. Method-level
diff --git a/posthog/api/routing.py b/posthog/api/routing.py
index c1b3bbc761ae..7925d5aa4e92 100644
--- a/posthog/api/routing.py
+++ b/posthog/api/routing.py
@@ -1,9 +1,11 @@
+import re
import sys
from collections.abc import Sequence
from functools import cached_property, lru_cache
from typing import TYPE_CHECKING, Any, Literal, Optional, cast
from uuid import UUID
+from django.core.exceptions import ImproperlyConfigured
from django.db.models.query import QuerySet
from opentelemetry import trace
@@ -26,6 +28,7 @@ from posthog.auth import (
SharingPasswordProtectedAuthentication,
)
from posthog.clickhouse.query_tagging import get_team_query_tags, tag_queries
+from posthog.dataclasses import frozen
from posthog.models.organization import Organization
from posthog.models.project import Project
from posthog.models.scoping import reset_current_team_id, set_current_team_id
@@ -58,6 +61,40 @@ else:
# Adapted from drf-extensions 0.8.0 (MIT, Copyright (c) 2013 Gennady Chibisov, github.com/chibisov/drf-extensions).
PARENT_LOOKUP_KWARG_PREFIX = "parent_lookup_"
+PathParameterType = type[UUID] | type[int] | type[str]
+PATH_PARAMETER_TYPES: tuple[PathParameterType, ...] = (UUID, int, str)
+# parents_query_dict resolves these with token overrides and `@current`, so path_parameters must not parse them.
+_PARENT_PATH_PARAMETERS = frozenset({"team_id", "project_id", "organization_id"})
+_ASCII_DIGITS = re.compile(r"[0-9]+")
+# Postgres bigint maximum. A larger id makes the database lookup fail with a 500.
+_MAX_BIGINT = 2**63 - 1
+
+
+@frozen
+class PathParameter:
+ """A URL kwarg type in TeamAndOrgViewSetMixin.path_parameters, with a description for the API docs."""
+
+ type: PathParameterType
+ description: str = ""
+
+
+def as_path_parameter(declared: PathParameterType | PathParameter) -> PathParameter:
+ if isinstance(declared, PathParameter):
+ return declared
+ return PathParameter(type=declared)
+
+
+def _parse_path_parameter(raw_value: str, parameter_type: PathParameterType) -> UUID | int | str:
+ if parameter_type is not int:
+ return parameter_type(raw_value)
+ # int() also accepts "1_000", " 7" and non-ASCII digits, which are not ids.
+ if not _ASCII_DIGITS.fullmatch(raw_value):
+ raise ValueError(f"{raw_value!r} is not a decimal id")
+ value = int(raw_value)
+ if value > _MAX_BIGINT:
+ raise ValueError(f"{raw_value!r} is out of the bigint range")
+ return value
+
class NestedRegistryItem:
def __init__(
@@ -199,6 +236,28 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):
required_scopes: Optional[list[str]] = None
sharing_enabled_actions: list[str] = []
+ # Types of the URL kwargs, for views without a queryset model, e.g. {"pk": UUID}, or
+ # {"pk": PathParameter(type=UUID, description="...")} to describe the id in the API docs.
+ # A nested parent lookup is declared by its bare name: "pipeline_id" types `parent_lookup_pipeline_id`.
+ # initial() parses each kwarg and answers 404 for a malformed value, so a handler gets `pk: UUID`.
+ # PostHogAutoSchema reads the same mapping to type the OpenAPI path parameters.
+ path_parameters: dict[str, PathParameterType | PathParameter] = {}
+
+ @classmethod
+ def _check_path_parameters(cls) -> None:
+ for name, declared in cls.path_parameters.items():
+ if name.startswith(PARENT_LOOKUP_KWARG_PREFIX) or name in _PARENT_PATH_PARAMETERS:
+ raise ImproperlyConfigured(
+ f"{cls.__name__}.path_parameters declares {name!r}. parents_query_dict resolves team_id, "
+ "project_id and organization_id. Declare any other parent lookup by its bare name, "
+ f"e.g. 'pipeline_id' for '{PARENT_LOOKUP_KWARG_PREFIX}pipeline_id'."
+ )
+ parameter_type = as_path_parameter(declared).type
+ if parameter_type not in PATH_PARAMETER_TYPES:
+ raise ImproperlyConfigured(
+ f"{cls.__name__}.path_parameters declares {name!r} as {parameter_type!r}. Use UUID, int or str."
+ )
+
def __init_subclass__(cls, **kwargs):
"""
This class plays a crucial role in ensuring common permissions, authentication and filtering.
@@ -216,6 +275,23 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):
if method in cls.__dict__:
raise Exception(f"Method {method} is protected and should not be overridden. {message}")
+ cls._check_path_parameters()
+
+ def _parse_path_parameters(self) -> None:
+ # Change self.kwargs in place, because APIView.dispatch passes this same dict to the handler.
+ # A parsed parent lookup is not written back to parents_query_dict, which can keep the raw string.
+ for name, declared in self.path_parameters.items():
+ kwarg_name = name if name in self.kwargs else f"{PARENT_LOOKUP_KWARG_PREFIX}{name}"
+ raw_value = self.kwargs.get(kwarg_name)
+ parameter_type = as_path_parameter(declared).type
+ if raw_value is None or isinstance(raw_value, parameter_type):
+ continue
+ try:
+ self.kwargs[kwarg_name] = _parse_path_parameter(raw_value, parameter_type)
+ except ValueError:
+ # A malformed id names no object, so the answer is 404, the same as from a queryset view.
+ raise NotFound()
+
def dispatch(self, request, *args, **kwargs):
"""
Outermost wrapper for the request lifecycle. The try/finally below
@@ -261,8 +337,12 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):
simply never set — scoped queries raise TeamScopeError, which is the
correct fail-closed behavior. dispatch() above guarantees cleanup
regardless.
+
+ Path parameters are parsed after super().initial(), so an
+ authentication or permission error wins over a 404 for a malformed id.
"""
super().initial(request, *args, **kwargs)
+ self._parse_path_parameters()
self._team_scope_token = None
if self._is_team_view or self._is_project_view:
try:
diff --git a/posthog/api/test/test_api_docs.py b/posthog/api/test/test_api_docs.py
index bf719b66d9d0..459d84982b56 100644
--- a/posthog/api/test/test_api_docs.py
+++ b/posthog/api/test/test_api_docs.py
@@ -1,10 +1,12 @@
import os
import re
+from typing import Any
+from uuid import UUID
from posthog.test.base import APIBaseTest
from unittest import mock
-from django.urls import URLPattern, path
+from django.urls import URLPattern, path, re_path
from drf_spectacular.generators import SchemaGenerator
from parameterized import parameterized
@@ -14,6 +16,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.documentation import extend_schema
+from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
class _XInternalMarkerSerializer(serializers.Serializer):
@@ -66,6 +69,31 @@ class _RequestDependentScopesViewSet(viewsets.ViewSet):
return Response({"ok": True})
+_UUID_SCHEMA = {"type": "string", "format": "uuid"}
+
+
+class _TypedPathViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "project"
+ path_parameters = {
+ "pk": PathParameter(type=UUID, description="A UUID string identifying this thing."),
+ "number": int,
+ "parent_id": UUID,
+ }
+
+ @extend_schema(responses={200: _XInternalMarkerSerializer})
+ def list(self, request: Request, **kwargs: Any) -> Response:
+ return Response({"ok": True})
+
+ @extend_schema(responses={200: _XInternalMarkerSerializer})
+ def retrieve(self, request: Request, pk: UUID, **kwargs: Any) -> Response:
+ return Response({"ok": True})
+
+ @extend_schema(responses={200: _XInternalMarkerSerializer})
+ @action(detail=True, methods=["GET"], url_path=r"numbers/(?P<number>[^/]+)")
+ def numbers(self, request: Request, pk: UUID, number: int, **kwargs: Any) -> Response:
+ return Response({"ok": True})
+
+
class TestAPIDocsSchema(APIBaseTest):
@parameterized.expand([("duplicate", False, True), ("not_a_duplicate", True, False)])
def test_org_path_sharing_a_project_suffix(self, _name: str, opted_out: bool, deprecated: bool) -> None:
@@ -137,6 +165,40 @@ class TestAPIDocsSchema(APIBaseTest):
assert "x-request-dependent-scopes" not in schema["paths"]["/api/request_dependent/"]["get"]
assert schema["paths"]["/api/request_dependent/{id}/"]["get"]["x-request-dependent-scopes"] is True
+ @parameterized.expand(
+ [
+ ("collection_has_none", "/api/typed/", {}),
+ ("described_id", "/api/typed/{id}/", {"id": (_UUID_SCHEMA, "A UUID string identifying this thing.")}),
+ (
+ "second_capture",
+ "/api/typed/{id}/numbers/{number}/",
+ {"id": (_UUID_SCHEMA, "A UUID string identifying this thing."), "number": ({"type": "integer"}, None)},
+ ),
+ ("parent_lookup", "/api/parents/{parent_id}/typed/", {"parent_id": (_UUID_SCHEMA, None)}),
+ ]
+ )
+ def test_path_parameters_type_the_path_parameters(
+ self, _name: str, path: str, expected: dict[str, tuple[dict, str | None]]
+ ) -> None:
+ patterns = [
+ re_path(r"^api/typed/$", _TypedPathViewSet.as_view({"get": "list"})),
+ re_path(r"^api/typed/(?P<pk>[^/.]+)/$", _TypedPathViewSet.as_view({"get": "retrieve"})),
+ re_path(
+ r"^api/typed/(?P<pk>[^/.]+)/numbers/(?P<number>[^/]+)/$",
+ _TypedPathViewSet.as_view({"get": "numbers"}),
+ ),
+ re_path(
+ r"^api/parents/(?P<parent_lookup_parent_id>[^/.]+)/typed/$", _TypedPathViewSet.as_view({"get": "list"})
+ ),
+ ]
+
+ schema = SchemaGenerator(patterns=patterns).get_schema(request=None, public=True)
+
+ parameters = schema["paths"][path]["get"].get("parameters", [])
+ assert {
+ param["name"]: (param["schema"], param.get("description")) for param in parameters if param["in"] == "path"
+ } == expected
+
def test_can_generate_api_docs_schema(self) -> None:
self.client.logout()
diff --git a/posthog/api/test/test_routing.py b/posthog/api/test/test_routing.py
index 0516d488ce62..05d50b304b3e 100644
--- a/posthog/api/test/test_routing.py
+++ b/posthog/api/test/test_routing.py
@@ -3,10 +3,13 @@ import pathlib
import importlib
import importlib.util
from datetime import timedelta
+from typing import Any
+from uuid import UUID
import pytest
from posthog.test.base import APIBaseTest
+from django.core.exceptions import ImproperlyConfigured
from django.db.models import Count
from django.db.models.functions import Lower
from django.test import override_settings
@@ -16,11 +19,13 @@ from django.utils import timezone
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
+from parameterized import parameterized
from rest_framework import viewsets
from rest_framework.decorators import action
+from rest_framework.request import Request
from rest_framework.response import Response
-from posthog.api.routing import DefaultRouterPlusPlus, RouterRegistry, TeamAndOrgViewSetMixin
+from posthog.api.routing import DefaultRouterPlusPlus, PathParameter, RouterRegistry, TeamAndOrgViewSetMixin
from posthog.auth import ProjectSecretAPIKeyAuthentication
from posthog.models.file_system.file_system import FileSystem
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
@@ -60,6 +65,41 @@ class OrderedFooViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
serializer_class = AnnotationSerializer
+class TypedPathFooViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "INTERNAL"
+ path_parameters = {
+ "pk": PathParameter(type=UUID, description="A UUID string identifying this foo."),
+ "number": int,
+ "foo_id": UUID,
+ }
+
+ def list(self, request: Request, **kwargs: Any) -> Response:
+ return Response({"kwargs": {name: type(value).__name__ for name, value in kwargs.items()}})
+
+ def retrieve(self, request: Request, pk: UUID, **kwargs: Any) -> Response:
+ return Response({"pk_type": type(pk).__name__})
+
+ @action(detail=True, methods=["get"], url_path=r"numbers/(?P<number>[^/]+)")
+ def numbers(self, request: Request, pk: UUID, number: int, **kwargs: Any) -> Response:
+ return Response({"pk_type": type(pk).__name__, "number": number})
+
+
+ "path_parameters",
+ [
+ {"parent_lookup_team_id": int},
+ {"parent_lookup_foo_id": UUID},
+ {"project_id": int},
+ {"organization_id": UUID},
+ {"pk": float},
+ {"pk": PathParameter(type=float)}, # type: ignore[arg-type]
+ ],
+)
+def test_path_parameters_reject_parent_lookups_and_unsupported_types(path_parameters: dict[str, Any]) -> None:
+ with pytest.raises(ImproperlyConfigured):
+ type("BadPathViewSet", (TeamAndOrgViewSetMixin, viewsets.GenericViewSet), {"path_parameters": path_parameters})
+
+
def test_stable_queryset_ordering_adds_a_primary_key_tiebreaker() -> None:
queryset = stable_queryset_ordering(Annotation.objects.order_by("date_marker"))
@@ -97,6 +137,10 @@ test_ordered_router.register(r"foos", OrderedFooViewSet, "team_ordered_foos", ["
test_projects_router = test_router.register(r"projects", FooViewSet, "projects")
test_projects_router.register(r"foos", FooViewSet, "project_foos", ["project_id"])
+test_typed_foos_router = test_projects_router.register(
+ r"typed_foos", TypedPathFooViewSet, "project_typed_foos", ["project_id"]
+)
+test_typed_foos_router.register(r"bars", TypedPathFooViewSet, "project_typed_foo_bars", ["project_id", "foo_id"])
test_organizations_router = test_router.register(r"organizations", FooViewSet, "organizations")
test_organizations_router.register(r"foos", FooViewSet, "organization_foos", ["organization_id"])
@@ -225,6 +269,46 @@ class TestTeamAndOrgViewSetMixin(APIBaseTest):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["team_id"], self.team.id)
+ @parameterized.expand(
+ [
+ ("uuid", "{id}/", 200, {"pk_type": "UUID"}),
+ ("second_capture", "{id}/numbers/7/", 200, {"pk_type": "UUID", "number": 7}),
+ ("list_route_has_no_pk", "", 200, {"kwargs": {"parent_lookup_project_id": "str"}}),
+ (
+ "parent_lookup",
+ "{id}/bars/",
+ 200,
+ {"kwargs": {"parent_lookup_project_id": "str", "parent_lookup_foo_id": "UUID"}},
+ ),
+ ("malformed_parent_lookup", "not-a-uuid/bars/", 404, None),
+ ("malformed_uuid", "not-a-uuid/", 404, None),
+ ("malformed_second_capture", "{id}/numbers/seven/", 404, None),
+ ("max_bigint", "{id}/numbers/9223372036854775807/", 200, {"pk_type": "UUID", "number": 2**63 - 1}),
+ ("above_bigint", "{id}/numbers/9223372036854775808/", 404, None),
+ ("underscore_separator", "{id}/numbers/1_000/", 404, None),
+ ("leading_space", "{id}/numbers/%207/", 404, None),
+ ("negative", "{id}/numbers/-7/", 404, None),
+ ("non_ascii_digit", "{id}/numbers/%D9%A7/", 404, None),
+ ]
+ )
+ def test_path_parameters_reach_the_handler_parsed(
+ self, _name: str, suffix: str, expected_status: int, expected_body: dict | None
+ ) -> None:
+ url = f"/api/projects/{self.team.id}/typed_foos/{suffix.format(id='3f1c9f0e-2b7a-4a5f-9c1d-8e6b2a4f7d31')}"
+
+ response = self.client.get(url)
+
+ self.assertEqual(response.status_code, expected_status)
+ if expected_body is not None:
+ self.assertEqual(response.json(), expected_body)
+
+ def test_path_parameters_parse_after_authentication(self) -> None:
+ self.client.logout()
+
+ response = self.client.get(f"/api/projects/{self.team.id}/typed_foos/not-a-uuid/")
+
+ self.assertEqual(response.status_code, 401)
+
def test_cannot_override_special_methods(self):
with pytest.raises(Exception) as e:
diff --git a/products/architecture.md b/products/architecture.md
index ca1258db3f25..449fe6e12e4c 100644
--- a/products/architecture.md
+++ b/products/architecture.md
@@ -463,6 +463,18 @@ A resource that inherits access from a parent object (`RESOURCE_FALLBACK_MAP`) n
The facade owns **tenant scoping** (`team_id` enforced via `for_team(team_id)` / a `ProductTeamModel` fail-closed manager) and **domain invariants** (state machines, idempotency) — these must hold for every caller, so they live below the HTTP boundary; user RBAC must not. Keeping RBAC in the shared DRF stack also lets cross-cutting permission tests enforce it consistently across products.
+### Path ids
+
+A view that reads through the facade has no `queryset`, so nothing can read the type of a URL kwarg from a model.
+Declare the types on the view: `path_parameters = {"pk": UUID}`.
+`TeamAndOrgViewSetMixin` parses each declared kwarg before the handler runs, and answers 404 for a malformed value, the same as a queryset view.
+The handler gets `pk: UUID`, and the OpenAPI schema shows `format: uuid`.
+A named capture in an action's `url_path` goes in the same mapping.
+A nested parent lookup goes in by its bare name: `"pipeline_id": UUID` types the `parent_lookup_pipeline_id` kwarg.
+`team_id`, `project_id` and `organization_id` do not, because `parents_query_dict` resolves them.
+To describe an id in the API docs, declare `PathParameter(type=UUID, description="...")` instead of the bare type.
+Do not parse path ids by hand. See `products/visual_review/backend/presentation/views.py`.
+
### How do lists page?
A facade returns contracts, not a queryset, so a view cannot hand its rows to a DRF paginator.
diff --git a/products/autoresearch/backend/presentation/views/views.py b/products/autoresearch/backend/presentation/views/views.py
index 36b35d5b8efe..516067d50c31 100644
--- a/products/autoresearch/backend/presentation/views/views.py
+++ b/products/autoresearch/backend/presentation/views/views.py
@@ -11,6 +11,7 @@ No business logic here — that lives behind ``facade/api.py``.
from dataclasses import fields
from typing import Any, cast
+from uuid import UUID
import structlog
from drf_spectacular.utils import OpenApiResponse, extend_schema
@@ -27,10 +28,9 @@ from rest_framework.response import Response
from rest_framework.throttling import BaseThrottle
from rest_framework.views import APIView
-from posthog.api.documentation import PostHogAutoSchema
from posthog.api.mixins import validated_request
from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
-from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
from posthog.models.user import User
from posthog.oauth_provenance import get_oauth_access_token, is_sandbox_origin_request
from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle
@@ -90,39 +90,6 @@ from .serializers import (
logger = structlog.get_logger(__name__)
-class FacadePathParamSchema(PostHogAutoSchema):
- """Types a facade-backed viewset's UUID path parameters.
-
- drf-spectacular reads a path parameter's type off the viewset's ``queryset`` model. These
- viewsets reach their data through the facade and declare no queryset, so each id is spelled
- out here instead. Declaring them through ``@extend_schema`` would not work: that appends the
- parameter to every operation in the viewset, including the collection routes whose path has
- no id in it. This hook only ever sees variables the path actually contains.
- """
-
- def _resolve_path_parameters(self, variables: Any) -> Any:
- declared = getattr(self.view, "uuid_path_parameters", {})
- resolved = []
- for parameter in super()._resolve_path_parameters(variables):
- description = declared.get(parameter["name"])
- if parameter["name"] not in declared:
- resolved.append(parameter)
- continue
- # Rebuilt rather than mutated, so the keys keep the order drf-spectacular emits.
- rebuilt: dict[str, Any] = {}
- for key, value in parameter.items():
- if key == "schema":
- rebuilt["schema"] = {"type": "string", "format": "uuid"}
- if description:
- rebuilt["description"] = description
- elif key == "description" and description:
- continue
- else:
- rebuilt[key] = value
- resolved.append(rebuilt)
- return resolved
-
-
class AutoresearchAccessPermission(BasePermission):
"""Gate the autoresearch product behind the `autoresearch` feature flag."""
@@ -139,13 +106,12 @@ class ArtifactStorageUnavailableError(APIException):
default_code = "artifact_storage_unavailable"
-def _parent_pipeline_id(view: Any) -> str | None:
+def _parent_pipeline_id(view: Any) -> UUID | None:
"""The pipeline this nested route is scoped to, or None on the unscoped collection route."""
- pipeline_id = view.kwargs.get("parent_lookup_pipeline_id")
- return str(pipeline_id) if pipeline_id else None
+ return view.kwargs.get("parent_lookup_pipeline_id")
-def _require_parent_pipeline_id(view: Any) -> str:
+def _require_parent_pipeline_id(view: Any) -> UUID:
"""The pipeline id for a route that cannot act without one."""
pipeline_id = _parent_pipeline_id(view)
if pipeline_id is None:
@@ -194,8 +160,9 @@ class AutoresearchPipelineViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet)
users daily and emits autoresearch_prediction events.
"""
- schema = FacadePathParamSchema()
- uuid_path_parameters = {"id": "A UUID string identifying this autoresearch pipeline."}
+ path_parameters = {
+ "pk": PathParameter(type=UUID, description="A UUID string identifying this autoresearch pipeline.")
+ }
scope_object = "autoresearch"
# The HogQL actions also carry their own `required_scopes`, so a scoped token needs `query:read` too.
scope_object_read_actions = [
@@ -724,8 +691,10 @@ class AutoresearchModelViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelVie
the daily inference workflow compiles to score users.
"""
- schema = FacadePathParamSchema()
- uuid_path_parameters = {"id": "A UUID string identifying this autoresearch model.", "pipeline_id": None}
+ path_parameters = {
+ "pk": PathParameter(type=UUID, description="A UUID string identifying this autoresearch model."),
+ "pipeline_id": UUID,
+ }
scope_object = "autoresearch"
scope_object_read_actions = ["list", "retrieve"]
scope_object_write_actions: list[str] = []
@@ -757,8 +726,10 @@ class AutoresearchRunViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelViewS
List and retrieve inference and validation runs for a pipeline.
"""
- schema = FacadePathParamSchema()
- uuid_path_parameters = {"id": "A UUID string identifying this autoresearch run.", "pipeline_id": None}
+ path_parameters = {
+ "pk": PathParameter(type=UUID, description="A UUID string identifying this autoresearch run."),
+ "pipeline_id": UUID,
+ }
scope_object = "autoresearch"
scope_object_read_actions = ["list", "retrieve"]
scope_object_write_actions: list[str] = []
@@ -793,8 +764,10 @@ class AutoresearchTrainingRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewS
score, and the summary of the run once it completes.
"""
- schema = FacadePathParamSchema()
- uuid_path_parameters = {"id": "A UUID string identifying this autoresearch training run.", "pipeline_id": None}
+ path_parameters = {
+ "pk": PathParameter(type=UUID, description="A UUID string identifying this autoresearch training run."),
+ "pipeline_id": UUID,
+ }
scope_object = "autoresearch"
scope_object_read_actions = ["list", "retrieve", "list_artifacts", "get_artifact", "history"]
scope_object_write_actions = [
@@ -1169,8 +1142,10 @@ class AutoresearchSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericView
search constraint, or dismiss it with rationale.
"""
- schema = FacadePathParamSchema()
- uuid_path_parameters = {"id": "A UUID string identifying this autoresearch suggestion.", "pipeline_id": None}
+ path_parameters = {
+ "pk": PathParameter(type=UUID, description="A UUID string identifying this autoresearch suggestion."),
+ "pipeline_id": UUID,
+ }
scope_object = "autoresearch"
scope_object_read_actions = ["list", "retrieve"]
scope_object_write_actions = ["create", "respond"]
diff --git a/products/review_hog/backend/presentation/views/project_settings.py b/products/review_hog/backend/presentation/views/project_settings.py
index 4bddfc2fb4b2..d9d3d3eddbf7 100644
--- a/products/review_hog/backend/presentation/views/project_settings.py
+++ b/products/review_hog/backend/presentation/views/project_settings.py
@@ -1,12 +1,13 @@
from typing import Any
from uuid import UUID
-from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
+from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.api.routing import PathParameter
from posthog.permissions import PostHogFeatureFlagPermission
from products.review_hog.backend.facade.api import (
@@ -225,6 +226,7 @@ class ReviewProjectSettingsViewSet(ReviewHogProjectViewSetMixin, viewsets.Generi
permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamStrictManagementPermission]
posthog_feature_flag = "review-hog"
serializer_class = ReviewProjectSettingsSerializer
+ path_parameters = {"person_id": PathParameter(type=UUID, description="Id of the list entry.")}
def _settings_response(self, response_status: int = status.HTTP_200_OK) -> Response:
settings = get_review_project_settings(self.effective_team_id, self.acting_user_id)
@@ -295,7 +297,6 @@ class ReviewProjectSettingsViewSet(ReviewHogProjectViewSetMixin, viewsets.Generi
return self._settings_response(status.HTTP_201_CREATED if created else status.HTTP_200_OK)
@extend_schema(
- parameters=[OpenApiParameter("person_id", str, OpenApiParameter.PATH, description="Id of the list entry.")],
responses={
200: OpenApiResponse(response=ReviewProjectSettingsSerializer, description="The person was removed."),
404: OpenApiResponse(response=ReviewHogSettingsErrorSerializer, description="No such list entry."),
@@ -309,8 +310,8 @@ class ReviewProjectSettingsViewSet(ReviewHogProjectViewSetMixin, viewsets.Generi
url_path=rf"project_settings/people/(?P<person_id>{UUID_PATH_PATTERN})",
required_scopes=["review_hog:write"],
)
- def remove_project_person(self, request: Request, person_id: str, **kwargs: Any) -> Response:
- if not remove_review_repository_person(self.effective_team_id, self.acting_user_id, None, UUID(person_id)):
+ def remove_project_person(self, request: Request, person_id: UUID, **kwargs: Any) -> Response:
+ if not remove_review_repository_person(self.effective_team_id, self.acting_user_id, None, person_id):
return no_such_list_entry_response()
return self._settings_response()
diff --git a/products/review_hog/backend/presentation/views/repositories.py b/products/review_hog/backend/presentation/views/repositories.py
index 060f85b605ef..e30e612894f4 100644
--- a/products/review_hog/backend/presentation/views/repositories.py
+++ b/products/review_hog/backend/presentation/views/repositories.py
@@ -2,14 +2,7 @@ import re
from typing import Any, cast
from uuid import UUID
-from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import (
- OpenApiParameter,
- OpenApiResponse,
- extend_schema,
- extend_schema_field,
- extend_schema_view,
-)
+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field, extend_schema_view
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound, ValidationError
@@ -17,7 +10,7 @@ from rest_framework.permissions import SAFE_METHODS, BasePermission
from rest_framework.request import Request
from rest_framework.response import Response
-from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.models.organization import OrganizationMembership
from posthog.models.scoping.manager import resolve_effective_team_id
@@ -97,23 +90,6 @@ def no_such_list_entry_response() -> Response:
return Response({"error": "No such list entry.", "conflicting_project": None}, status=status.HTTP_404_NOT_FOUND)
-def path_uuid(value: str) -> UUID:
- """The UUID of a detail URL. Any other value names no object, so the answer is 404."""
- try:
- return UUID(value)
- except ValueError:
- raise NotFound()
-
-
-def uuid_path_parameter(object_name: str) -> OpenApiParameter:
- return OpenApiParameter(
- "id",
- OpenApiTypes.UUID,
- OpenApiParameter.PATH,
- description=f"A UUID string identifying this {object_name}.",
- )
-
-
def decision_data(decision: AutomaticReviewDecision) -> dict[str, Any]:
return {"flash": decision.flash, "reason": decision.reason.value}
@@ -399,7 +375,6 @@ class EffectiveTeamStrictManagementPermission(EffectiveTeamMemberPermission):
summary="Remove a repository's settings",
description="Remove the repository from this project and clear its exception and lists. With an 'all "
"repositories' claim the repository stays in the project and follows the project rule.",
- parameters=[uuid_path_parameter("review repository")],
),
)
class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericViewSet):
@@ -413,11 +388,14 @@ class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericView
permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamStrictManagementPermission]
posthog_feature_flag = "review-hog"
serializer_class = ReviewRepositorySerializer
+ path_parameters = {
+ "pk": PathParameter(type=UUID, description="A UUID string identifying this review repository."),
+ "person_id": PathParameter(type=UUID, description="Id of the list entry."),
+ }
pagination_class = None
def _repository_or_404(self) -> ReviewRepositorySettings:
- repository_id = path_uuid(self.kwargs["pk"])
- repository = get_review_repository(self.effective_team_id, self.acting_user_id, repository_id)
+ repository = get_review_repository(self.effective_team_id, self.acting_user_id, self.kwargs["pk"])
if repository is None:
raise NotFound()
return repository
@@ -431,8 +409,7 @@ class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericView
return Response(ReviewRepositorySerializer(repositories, many=True).data)
def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- repository_id = path_uuid(self.kwargs["pk"])
- if not delete_review_repository(self.effective_team_id, self.acting_user_id, repository_id):
+ if not delete_review_repository(self.effective_team_id, self.acting_user_id, self.kwargs["pk"]):
raise NotFound()
return Response(status=status.HTTP_204_NO_CONTENT)
@@ -478,7 +455,6 @@ class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericView
return Response(response.data)
@extend_schema(
- parameters=[uuid_path_parameter("review repository")],
request=ReviewRepositoryPersonRequestSerializer,
responses={
200: OpenApiResponse(response=ReviewRepositorySerializer, description="The person was already on it."),
@@ -508,10 +484,6 @@ class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericView
return self._repository_response(repository.id, status.HTTP_201_CREATED if created else status.HTTP_200_OK)
@extend_schema(
- parameters=[
- uuid_path_parameter("review repository"),
- OpenApiParameter("person_id", str, OpenApiParameter.PATH, description="Id of the list entry."),
- ],
responses={
200: OpenApiResponse(response=ReviewRepositorySerializer, description="The person was removed."),
404: OpenApiResponse(response=ReviewHogSettingsErrorSerializer, description="No such list entry."),
@@ -525,11 +497,9 @@ class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericView
url_path=rf"people/(?P<person_id>{UUID_PATH_PATTERN})",
required_scopes=["review_hog:write"],
)
- def remove_person(self, request: Request, person_id: str, **kwargs: Any) -> Response:
+ def remove_person(self, request: Request, person_id: UUID, **kwargs: Any) -> Response:
repository = self._repository_or_404()
- if not remove_review_repository_person(
- self.effective_team_id, self.acting_user_id, repository.id, UUID(person_id)
- ):
+ if not remove_review_repository_person(self.effective_team_id, self.acting_user_id, repository.id, person_id):
return no_such_list_entry_response()
return self._repository_response(repository.id)
@@ -546,10 +516,13 @@ class ReviewInstallationClaimViewSet(ReviewHogProjectViewSetMixin, viewsets.Gene
permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamStrictManagementPermission]
posthog_feature_flag = "review-hog"
serializer_class = ReviewInstallationClaimSerializer
+ path_parameters = {
+ "pk": PathParameter(type=UUID, description="A UUID string identifying this review installation claim.")
+ }
pagination_class = None
def _claim_id_or_404(self) -> UUID:
- claim_id = path_uuid(self.kwargs["pk"])
+ claim_id = self.kwargs["pk"]
if get_review_installation_claim(self.effective_team_id, self.acting_user_id, claim_id) is None:
raise NotFound()
return claim_id
@@ -588,7 +561,6 @@ class ReviewInstallationClaimViewSet(ReviewHogProjectViewSetMixin, viewsets.Gene
return Response(ReviewInstallationClaimSerializer(claim).data, status=status.HTTP_201_CREATED)
@extend_schema(
- parameters=[uuid_path_parameter("review installation claim")],
request=ReviewInstallationClaimUpdateSerializer,
responses={
200: OpenApiResponse(response=ReviewInstallationClaimSerializer, description="The claim was changed."),
@@ -619,7 +591,6 @@ class ReviewInstallationClaimViewSet(ReviewHogProjectViewSetMixin, viewsets.Gene
return Response(ReviewInstallationClaimSerializer(claim).data)
@extend_schema(
- parameters=[uuid_path_parameter("review installation claim")],
responses={
204: OpenApiResponse(description="The claim and this project's repository settings there are gone.")
},
@@ -628,8 +599,7 @@ class ReviewInstallationClaimViewSet(ReviewHogProjectViewSetMixin, viewsets.Gene
"repositories and exceptions there are removed too. Personal choices stay.",
)
def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- claim_id = path_uuid(self.kwargs["pk"])
- if not delete_review_installation_claim(self.effective_team_id, self.acting_user_id, claim_id):
+ if not delete_review_installation_claim(self.effective_team_id, self.acting_user_id, self.kwargs["pk"]):
raise NotFound()
return Response(status=status.HTTP_204_NO_CONTENT)
@@ -638,7 +608,6 @@ class ReviewInstallationClaimViewSet(ReviewHogProjectViewSetMixin, viewsets.Gene
destroy=extend_schema(
summary="Clear my choice for a repository",
description="Clear the requesting user's own choice for one repository, so their default applies again.",
- parameters=[uuid_path_parameter("review user repository choice")],
),
)
class ReviewRepositoryChoiceViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericViewSet):
@@ -652,6 +621,9 @@ class ReviewRepositoryChoiceViewSet(ReviewHogProjectViewSetMixin, viewsets.Gener
permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamMemberPermission]
posthog_feature_flag = "review-hog"
serializer_class = ReviewRepositoryChoiceSerializer
+ path_parameters = {
+ "pk": PathParameter(type=UUID, description="A UUID string identifying this review user repository choice.")
+ }
pagination_class = None
def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
@@ -659,8 +631,7 @@ class ReviewRepositoryChoiceViewSet(ReviewHogProjectViewSetMixin, viewsets.Gener
return Response(ReviewRepositoryChoiceSerializer(choices, many=True).data)
def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- choice_id = path_uuid(self.kwargs["pk"])
- if not delete_review_repository_choice(self.effective_team_id, self.acting_user_id, choice_id):
+ if not delete_review_repository_choice(self.effective_team_id, self.acting_user_id, self.kwargs["pk"]):
raise NotFound()
return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/products/review_hog/backend/presentation/views/reviews.py b/products/review_hog/backend/presentation/views/reviews.py
index 0678739e0a8d..892f76570a6d 100644
--- a/products/review_hog/backend/presentation/views/reviews.py
+++ b/products/review_hog/backend/presentation/views/reviews.py
@@ -1,6 +1,6 @@
-import uuid
import dataclasses
from typing import Any, cast, get_args
+from uuid import UUID
from django.db import models
from django.utils import timezone
@@ -854,6 +854,7 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
serializer_class = ReviewRecentReviewSerializer
pagination_class = None
schema = _PageEnvelopeSchema()
+ path_parameters = {"pk": UUID}
def _root_team_id(self) -> int:
return resolve_effective_team_id(self.team_id)
@@ -1064,7 +1065,7 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
@extend_schema(
parameters=[
- # The viewset has no queryset, so the path parameter does not get its type from the model.
+ # _PageEnvelopeSchema does not extend PostHogAutoSchema, so path_parameters does not type the id here.
OpenApiParameter(
"id",
OpenApiTypes.UUID,
@@ -1087,15 +1088,11 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
"the resolution fields describe the report now, whatever the turn. Project-wide, so reviews listed "
"under `scope=everyone` can be opened too.",
)
- def retrieve(self, request: Request, pk: str | None = None, **kwargs) -> Response:
- try:
- report_uuid = uuid.UUID(str(pk))
- except ValueError:
- raise NotFound("Review not found.")
+ def retrieve(self, request: Request, pk: UUID, **kwargs) -> Response:
params = ReviewDetailParamsSerializer(data=request.query_params)
params.is_valid(raise_exception=True)
try:
- detail = get_review_detail(self._root_team_id(), report_uuid, params.validated_data.get("run_index"))
+ detail = get_review_detail(self._root_team_id(), pk, params.validated_data.get("run_index"))
except ReviewTurnNotFoundError:
raise NotFound("No completed review turn with that run_index.")
except ReviewNotFoundError:
diff --git a/products/stamphog/backend/presentation/views.py b/products/stamphog/backend/presentation/views.py
index df59bc0de45f..8b909d35ab9e 100644
--- a/products/stamphog/backend/presentation/views.py
+++ b/products/stamphog/backend/presentation/views.py
@@ -8,6 +8,7 @@ return serialized responses. No business logic here.
from functools import cached_property
from typing import Any, Literal, cast
from urllib.parse import quote
+from uuid import UUID
from django.conf import settings
from django.core import signing
@@ -150,6 +151,7 @@ class _StamphogTeamScopedViewSet(TeamAndOrgViewSetMixin):
# Appended onto the default team/scope permission stack by get_permissions.
permission_classes = [StamphogCanonicalTeamAccessPermission]
+ path_parameters = {"pk": UUID}
@cached_property
def canonical_team_id(self) -> int:
@@ -212,7 +214,7 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView
scope_object = "stamphog"
serializer_class = StamphogRepoConfigSerializer
- def _get_or_404(self, pk: str | None) -> contracts.RepoConfigDTO:
+ def _get_or_404(self, pk: UUID) -> contracts.RepoConfigDTO:
# A keyed lookup, not a scan: an installation can surface hundreds of repositories.
config = facade_api.get_repo_config_by_id(self.canonical_team_id, str(pk))
if config is None:
@@ -256,7 +258,7 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView
page = self.paginate_queryset(configs)
return self.get_paginated_response(self.get_serializer(page, many=True).data)
- def retrieve(self, request: Request, pk: str | None = None, **kwargs) -> Response:
+ def retrieve(self, request: Request, pk: UUID, **kwargs) -> Response:
return Response(self.get_serializer(self._get_or_404(pk)).data)
@extend_schema(request=StamphogRepoConfigWriteSerializer, responses={201: StamphogRepoConfigSerializer})
@@ -278,7 +280,7 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView
return Response(self.get_serializer(config).data, status=201)
@extend_schema(request=StamphogRepoConfigWriteSerializer, responses={200: StamphogRepoConfigSerializer})
- def update(self, request: Request, pk: str | None = None, **kwargs) -> Response:
+ def update(self, request: Request, pk: UUID, **kwargs) -> Response:
current = self._get_or_404(pk)
serializer = StamphogRepoConfigWriteSerializer(
data=request.data,
@@ -295,10 +297,10 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView
return Response(self.get_serializer(config).data)
@extend_schema(request=StamphogRepoConfigWriteSerializer, responses={200: StamphogRepoConfigSerializer})
- def partial_update(self, request: Request, pk: str | None = None, **kwargs) -> Response:
+ def partial_update(self, request: Request, pk: UUID, **kwargs) -> Response:
return self.update(request, pk=pk, partial=True, **kwargs)
- def destroy(self, request: Request, pk: str | None = None, **kwargs) -> Response:
+ def destroy(self, request: Request, pk: UUID, **kwargs) -> Response:
self._get_or_404(pk)
# A soft delete turns reviews off, so it takes manager like a PATCH to enabled=False.
self._require_review_level(request, "manager")
@@ -585,7 +587,7 @@ class ReviewRunViewSet(_StamphogTeamScopedViewSet, viewsets.GenericViewSet):
trigger=self.request.query_params.get("trigger"),
)
- def retrieve(self, request: Request, pk: str | None = None, **kwargs) -> Response:
+ def retrieve(self, request: Request, pk: UUID, **kwargs) -> Response:
run = facade_api.get_review_run(self.canonical_team_id, str(pk))
if run is None:
raise NotFound()
@@ -679,7 +681,7 @@ class PullRequestViewSet(_StamphogTeamScopedViewSet, viewsets.GenericViewSet):
merged=None if merged is None else merged.lower() in ("true", "1"),
)
- def retrieve(self, request: Request, pk: str | None = None, **kwargs) -> Response:
+ def retrieve(self, request: Request, pk: UUID, **kwargs) -> Response:
pull_request = facade_api.get_pull_request(self.canonical_team_id, str(pk))
if pull_request is None:
raise NotFound()
@@ -716,7 +718,7 @@ class DigestRunViewSet(_StamphogTeamScopedViewSet, viewsets.GenericViewSet):
scope_object = "stamphog"
serializer_class = DigestRunSerializer
- def retrieve(self, request: Request, pk: str | None = None, **kwargs) -> Response:
+ def retrieve(self, request: Request, pk: UUID, **kwargs) -> Response:
digest_run = facade_api.get_digest_run(self.canonical_team_id, str(pk))
if digest_run is None:
raise NotFound()
diff --git a/products/stamphog/backend/tests/test_api.py b/products/stamphog/backend/tests/test_api.py
index afad7416c766..b7e3f817f095 100644
--- a/products/stamphog/backend/tests/test_api.py
+++ b/products/stamphog/backend/tests/test_api.py
@@ -385,9 +385,10 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):
response = self.client.get(f"{self.url}{theirs.id}/")
assert response.status_code == status.HTTP_404_NOT_FOUND
- def test_malformed_config_id_is_a_404(self) -> None:
+ @parameterized.expand([("repo_configs",), ("review_runs",), ("pull_requests",), ("digest_runs",)])
+ def test_malformed_id_is_a_404(self, resource: str) -> None:
# An id that is not a UUID has to read as a miss, or a bad URL becomes a 500.
- response = self.client.get(f"{self.url}not-a-uuid/")
+ response = self.client.get(f"/api/projects/{self.team.id}/stamphog/{resource}/not-a-uuid/")
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_cannot_delete_other_teams_config(self) -> None:
diff --git a/products/visual_review/backend/presentation/views.py b/products/visual_review/backend/presentation/views.py
index d95b5e0395a2..9680693780c7 100644
--- a/products/visual_review/backend/presentation/views.py
+++ b/products/visual_review/backend/presentation/views.py
@@ -87,10 +87,11 @@ def _actor(request: Request) -> ActorType:
return ActorType.AGENT if is_mcp_request(request) else ActorType.HUMAN
-def _parse_uuid(value: str, field: str = "id") -> UUID:
- """Parse a path UUID, returning a 400 instead of letting a malformed value raise a 500.
+def _parse_uuid(value: str, field: str) -> UUID:
+ """Parse a parent lookup UUID, returning a 400 instead of letting a malformed value raise a 500.
- Path segments reach the viewset as raw strings, so a malformed run/repo id (truncated,
+ `path_parameters` parses only the view's own URL kwargs, so a parent segment such as the repo
+ id in `repos/<repo_id>/runs/` reaches the viewset as a raw string. A malformed one (truncated,
hallucinated by an MCP client, hand-typed) would otherwise crash `UUID(...)` with an
uncaught `ValueError`. Convert that into a clean DRF validation error."""
try:
@@ -190,6 +191,8 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""
scope_object = "visual_review"
+ path_parameters = {"pk": UUID}
+
pagination_class = FacadeLimitOffsetPagination
scope_object_write_actions = ["create", "partial_update", "quarantine", "unquarantine"]
scope_object_read_actions = [
@@ -225,29 +228,24 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
return Response(RepoSerializer(instance=repo).data, status=status.HTTP_201_CREATED)
- @extend_schema(
- parameters=[OpenApiParameter("id", OpenApiTypes.STR, OpenApiParameter.PATH)],
- responses={200: RepoSerializer},
- )
- def retrieve(self, request: Request, pk: str, **kwargs) -> Response:
+ @extend_schema(responses={200: RepoSerializer})
+ def retrieve(self, request: Request, pk: UUID, **kwargs) -> Response:
"""Get a repo by ID."""
- repo_id = _parse_uuid(pk)
try:
- repo = api.get_repo(repo_id, team_id=self.team_id)
+ repo = api.get_repo(pk, team_id=self.team_id)
except api.RepoNotFoundError:
return Response({"detail": "Repo not found"}, status=status.HTTP_404_NOT_FOUND)
return Response(RepoSerializer(instance=repo).data)
- @extend_schema(parameters=[OpenApiParameter("id", OpenApiTypes.STR, OpenApiParameter.PATH)])
@validated_request(
request_serializer=UpdateRepoInputSerializer,
responses={200: OpenApiResponse(response=RepoSerializer)},
)
- def partial_update(self, request: TypedRequest[UpdateRepoRequestInput], pk: str, **kwargs) -> Response:
+ def partial_update(self, request: TypedRequest[UpdateRepoRequestInput], pk: UUID, **kwargs) -> Response:
"""Update a repo's settings."""
body = request.validated_data
input_dto = UpdateRepoInput(
- repo_id=_parse_uuid(pk),
+ repo_id=pk,
baseline_file_paths=body.baseline_file_paths,
enable_pr_comments=body.enable_pr_comments,
debt_digest_enabled=body.debt_digest_enabled,
@@ -261,7 +259,6 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@extend_schema(
parameters=[
- OpenApiParameter("id", OpenApiTypes.STR, OpenApiParameter.PATH),
OpenApiParameter("identifier", OpenApiTypes.STR, OpenApiParameter.PATH),
OpenApiParameter(
"run_type",
@@ -277,9 +274,9 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
responses={200: OpenApiResponse(description="WebP thumbnail image")},
)
@action(detail=True, methods=["get"], url_path=r"thumbnails/(?P<identifier>.+[^/])")
- def thumbnail(self, request: Request, pk: str, identifier: str, **kwargs) -> HttpResponse:
+ def thumbnail(self, request: Request, pk: UUID, identifier: str, **kwargs) -> HttpResponse:
"""Serve a snapshot thumbnail by identifier. Returns WebP with ETag caching."""
- repo_id = _parse_uuid(pk)
+ repo_id = pk
try:
api.get_repo(repo_id, team_id=self.team_id)
except api.RepoNotFoundError:
@@ -326,15 +323,14 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
responses={200: QuarantinedIdentifierEntrySerializer(many=True)},
)
@action(detail=True, methods=["get"], url_path="quarantine")
- def list_quarantined(self, request: Request, pk: str, **kwargs) -> Response:
+ def list_quarantined(self, request: Request, pk: UUID, **kwargs) -> Response:
"""List quarantined identifiers. Without filter: active only. With identifier: full history."""
identifier = request.query_params.get("identifier")
run_type = request.query_params.get("run_type")
- repo_id = _parse_uuid(pk)
return facade_page_response(
self,
lambda page: api.list_quarantined(
- repo_id, team_id=self.team_id, identifier=identifier, run_type=run_type, page=page
+ pk, team_id=self.team_id, identifier=identifier, run_type=run_type, page=page
),
serializer_class=QuarantinedIdentifierEntrySerializer,
)
@@ -344,11 +340,11 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
responses={201: OpenApiResponse(response=QuarantinedIdentifierEntrySerializer)},
)
@action(detail=True, methods=["post"], url_path=r"quarantine/(?P<run_type>[^/]+)")
- def quarantine(self, request: TypedRequest[QuarantineInput], pk: str, run_type: str, **kwargs) -> Response:
+ def quarantine(self, request: TypedRequest[QuarantineInput], pk: UUID, run_type: str, **kwargs) -> Response:
"""Quarantine a snapshot identifier for a specific run type."""
try:
entry = api.quarantine_identifier(
- repo_id=_parse_uuid(pk),
+ repo_id=pk,
run_type=run_type,
input=request.validated_data,
user_id=cast(int, request.user.id),
@@ -372,11 +368,11 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
},
)
@action(detail=True, methods=["post"], url_path=r"quarantine/(?P<run_type>[^/]+)/expire")
- def unquarantine(self, request: TypedRequest, pk: str, run_type: str, **kwargs) -> Response:
+ def unquarantine(self, request: TypedRequest, pk: UUID, run_type: str, **kwargs) -> Response:
"""Expire all active quarantine entries for an identifier."""
try:
api.unquarantine_identifier(
- repo_id=_parse_uuid(pk),
+ repo_id=pk,
identifier=request.validated_data["identifier"],
run_type=run_type,
team_id=self.team_id,
@@ -403,7 +399,6 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response(status=status.HTTP_204_NO_CONTENT)
@extend_schema(
- parameters=[OpenApiParameter("id", OpenApiTypes.STR, OpenApiParameter.PATH)],
responses={200: BaselineOverviewSerializer},
description=(
"Snapshots overview for a repo: every identifier with a current baseline (latest "
@@ -415,8 +410,8 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
),
)
@action(detail=True, methods=["get"], url_path="baselines")
- def baselines(self, request: Request, pk: str, **kwargs) -> Response:
- repo_id = _parse_uuid(pk)
+ def baselines(self, request: Request, pk: UUID, **kwargs) -> Response:
+ repo_id = pk
try:
api.get_repo(repo_id, team_id=self.team_id)
except api.RepoNotFoundError:
@@ -425,7 +420,6 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response(BaselineOverviewSerializer(instance=result).data)
@extend_schema(
- parameters=[OpenApiParameter("id", OpenApiTypes.STR, OpenApiParameter.PATH)],
responses={200: FlakinessOverviewSerializer},
description=(
"Snapshots in a repo whose rendering cannot be trusted: those that failed the gate on a "
@@ -442,8 +436,8 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
),
)
@action(detail=True, methods=["get"], url_path="flakiness")
- def flakiness(self, request: Request, pk: str, **kwargs) -> Response:
- repo_id = _parse_uuid(pk)
+ def flakiness(self, request: Request, pk: UUID, **kwargs) -> Response:
+ repo_id = pk
try:
api.get_repo(repo_id, team_id=self.team_id)
except api.RepoNotFoundError:
@@ -452,7 +446,6 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response(FlakinessOverviewSerializer(instance=result).data)
@extend_schema(
- parameters=[OpenApiParameter("id", OpenApiTypes.STR, OpenApiParameter.PATH)],
description=(
"Snapshots that keep getting tolerated, counted across baselines, most manual tolerations "
"first. A toleration accepts one exact rendering, so a snapshot that keeps needing them "
@@ -470,8 +463,8 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
# nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients
@action(detail=True, methods=["get"], url_path="toleration-pileups", pagination_class=None)
- def toleration_pileups(self, request: TypedRequest, pk: str, **kwargs) -> Response:
- repo_id = _parse_uuid(pk)
+ def toleration_pileups(self, request: TypedRequest, pk: UUID, **kwargs) -> Response:
+ repo_id = pk
try:
api.get_repo(repo_id, team_id=self.team_id)
except api.RepoNotFoundError:
@@ -593,6 +586,8 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""
scope_object = "visual_review"
+ path_parameters = {"pk": UUID, "request_id": UUID}
+
pagination_class = FacadeLimitOffsetPagination
scope_object_write_actions = [
"create",
@@ -675,14 +670,11 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
result = api.create_run(request.validated_data, team_id=self.team_id)
return Response(CreateRunResultSerializer(instance=result).data, status=status.HTTP_201_CREATED)
- @extend_schema(
- parameters=[OpenApiParameter("id", OpenApiTypes.STR, OpenApiParameter.PATH)],
- responses={200: RunSerializer},
- )
- def retrieve(self, request: Request, pk: str, **kwargs) -> Response:
+ @extend_schema(responses={200: RunSerializer})
+ def retrieve(self, request: Request, pk: UUID, **kwargs) -> Response:
"""Get run status and summary."""
try:
- run = api.get_run(_parse_uuid(pk), team_id=self.team_id)
+ run = api.get_run(pk, team_id=self.team_id)
except api.RunNotFoundError:
return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
return Response(RunSerializer(instance=run).data)
@@ -692,13 +684,13 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
responses={200: SnapshotSerializer(many=True)},
)
@action(detail=True, methods=["get"], pagination_class=SnapshotsPagination)
- def snapshots(self, request: TypedRequest, pk: str, **kwargs) -> Response:
+ def snapshots(self, request: TypedRequest, pk: UUID, **kwargs) -> Response:
"""Get a run's snapshots with diff results, excluding quarantined ones by default."""
query = request.validated_query_data
paginator = cast(SnapshotsPagination, self.paginator)
try:
result = api.get_run_snapshots(
- _parse_uuid(pk),
+ pk,
team_id=self.team_id,
include_quarantined=query["include_quarantined"],
exclude_unchanged=query["exclude_unchanged"],
@@ -722,11 +714,11 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
responses={200: OpenApiResponse(response=SnapshotSerializer)},
)
@action(detail=True, methods=["post"], url_path="tolerate")
- def mark_tolerated(self, request: TypedRequest, pk: str, **kwargs) -> Response:
+ def mark_tolerated(self, request: TypedRequest, pk: UUID, **kwargs) -> Response:
"""Mark a changed snapshot as a known tolerated alternate."""
try:
snapshot = api.mark_snapshot_as_tolerated(
- run_id=_parse_uuid(pk),
+ run_id=pk,
snapshot_id=request.validated_data["snapshot_id"],
user_id=cast(int, request.user.id),
team_id=self.team_id,
@@ -747,13 +739,13 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
# nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients
@action(detail=True, methods=["get"], url_path="tolerated-hashes")
- def tolerated_hashes(self, request: Request, pk: str, **kwargs) -> Response:
+ def tolerated_hashes(self, request: Request, pk: UUID, **kwargs) -> Response:
"""List known tolerated hashes for a snapshot identifier."""
identifier = request.query_params.get("identifier")
if not identifier:
return Response({"detail": _MISSING_IDENTIFIER_DETAIL}, status=status.HTTP_400_BAD_REQUEST)
try:
- scope = api.get_run_scope(_parse_uuid(pk), team_id=self.team_id)
+ scope = api.get_run_scope(pk, team_id=self.team_id)
except api.RunNotFoundError:
return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
entries = api.get_tolerated_hashes(scope.repo_id, identifier)
@@ -766,12 +758,12 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients
@action(detail=True, methods=["post"], url_path="add-snapshots")
@validated_request(AddSnapshotsInputSerializer)
- def add_snapshots(self, request: TypedRequest[AddSnapshotsInput], pk: str, **kwargs) -> Response:
+ def add_snapshots(self, request: TypedRequest[AddSnapshotsInput], pk: UUID, **kwargs) -> Response:
"""Add a batch of snapshots to a pending run (shard-based flow)."""
try:
result = api.add_snapshots(
input=request.validated_data,
- run_id=_parse_uuid(pk),
+ run_id=pk,
team_id=self.team_id,
)
except api.RunNotFoundError:
@@ -789,14 +781,14 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
# nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients
@action(detail=True, methods=["get"], url_path="snapshot-history")
- def snapshot_history(self, request: Request, pk: str, **kwargs) -> Response:
+ def snapshot_history(self, request: Request, pk: UUID, **kwargs) -> Response:
"""Recent change history for a snapshot identifier across runs."""
identifier = request.query_params.get("identifier")
if not identifier:
return Response({"detail": _MISSING_IDENTIFIER_DETAIL}, status=status.HTTP_400_BAD_REQUEST)
try:
- scope = api.get_run_scope(_parse_uuid(pk), team_id=self.team_id)
+ scope = api.get_run_scope(pk, team_id=self.team_id)
except api.RunNotFoundError:
return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
@@ -811,11 +803,11 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
responses={200: OpenApiResponse(response=RunSerializer)},
)
@action(detail=True, methods=["post"])
- def complete(self, request: TypedRequest, pk: str, **kwargs) -> Response:
+ def complete(self, request: TypedRequest, pk: UUID, **kwargs) -> Response:
"""Complete a run: detect removals, verify uploads, trigger diff processing."""
try:
run = api.complete_run(
- _parse_uuid(pk),
+ pk,
team_id=self.team_id,
check_run_id=request.validated_data.get("check_run_id"),
)
@@ -836,7 +828,7 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
responses={200: OpenApiResponse(response=RunSerializer)},
)
@action(detail=True, methods=["post"])
- def approve(self, request: TypedRequest[ApproveRunRequestInput], pk: str, **kwargs) -> Response:
+ def approve(self, request: TypedRequest[ApproveRunRequestInput], pk: UUID, **kwargs) -> Response:
"""Mark snapshots reviewed (DB only).
Records the per-snapshot "Accept change" decision. Does not commit the baseline
@@ -845,11 +837,10 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
updates a quarantined story's baseline entry without lifting the quarantine.
"""
body = request.validated_data
- run_id = _parse_uuid(pk)
user_id = cast(int, request.user.id)
try:
- input_dto = ApproveRunInput(run_id=run_id, user_id=user_id, snapshots=body.snapshots)
+ input_dto = ApproveRunInput(run_id=pk, user_id=user_id, snapshots=body.snapshots)
run = api.approve_snapshots(input_dto, team_id=self.team_id)
return Response(RunSerializer(instance=run).data)
except api.RunNotFoundError:
@@ -866,7 +857,7 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
responses={200: OpenApiResponse(response=FinalizeResultSerializer)},
)
@action(detail=True, methods=["post"])
- def finalize(self, request: TypedRequest[FinalizeRunRequestInput], pk: str, **kwargs) -> Response:
+ def finalize(self, request: TypedRequest[FinalizeRunRequestInput], pk: UUID, **kwargs) -> Response:
"""Finalize a fully-reviewed run: commit the approved baseline and green the gate.
Commits exactly the snapshots approved in the DB (tolerated ones keep their baseline)
@@ -877,12 +868,11 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
committing it.
"""
body = request.validated_data
- run_id = _parse_uuid(pk)
user_id = cast(int, request.user.id)
try:
result = api.finalize_run(
- run_id=run_id,
+ run_id=pk,
user_id=user_id,
team_id=self.team_id,
approve_all=body.approve_all,
@@ -924,9 +914,9 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
description="Re-evaluate quarantine and counts, update commit status, and optionally rerun the CI job.",
)
@action(detail=True, methods=["post"], url_path="recompute")
- def recompute(self, request: Request, pk: str, **kwargs) -> Response:
+ def recompute(self, request: Request, pk: UUID, **kwargs) -> Response:
try:
- result = api.recompute_run(_parse_uuid(pk), team_id=self.team_id)
+ result = api.recompute_run(pk, team_id=self.team_id)
except api.RunNotFoundError:
return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
except ValueError:
@@ -947,10 +937,10 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
),
)
@action(detail=True, methods=["post"], url_path="lift_on_merge")
- def lift_on_merge(self, request: TypedRequest[LiftOnMergeInput], pk: str, **kwargs) -> Response:
+ def lift_on_merge(self, request: TypedRequest[LiftOnMergeInput], pk: UUID, **kwargs) -> Response:
try:
entry = api.request_quarantine_lift_on_merge(
- run_id=_parse_uuid(pk),
+ run_id=pk,
input=request.validated_data,
user_id=cast(int, request.user.id),
team_id=self.team_id,
@@ -965,7 +955,6 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response(QuarantineLiftEntrySerializer(instance=entry).data, status=status.HTTP_201_CREATED)
@extend_schema(
- parameters=[OpenApiParameter("id", OpenApiTypes.UUID, OpenApiParameter.PATH)],
responses={200: QuarantineLiftEntrySerializer(many=True)},
description=(
"Every request to lift a quarantine when this run's pull request merges, newest first, in any "
@@ -973,16 +962,15 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
),
)
@action(detail=True, methods=["get"], url_path="quarantine_lifts", pagination_class=None)
- def quarantine_lifts(self, request: Request, pk: str, **kwargs) -> Response:
+ def quarantine_lifts(self, request: Request, pk: UUID, **kwargs) -> Response:
try:
- entries = api.list_quarantine_lifts_for_run(_parse_uuid(pk), team_id=self.team_id)
+ entries = api.list_quarantine_lifts_for_run(pk, team_id=self.team_id)
except api.RunNotFoundError:
return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
return Response(QuarantineLiftEntrySerializer(instance=entries, many=True).data)
@extend_schema(
parameters=[
- OpenApiParameter("id", OpenApiTypes.UUID, OpenApiParameter.PATH),
OpenApiParameter(
"request_id",
OpenApiTypes.UUID,
@@ -995,11 +983,11 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
description="Withdraw a pending request to lift a quarantine when this run's pull request merges.",
)
@action(detail=True, methods=["post"], url_path=r"quarantine_lifts/(?P<request_id>[^/]+)/cancel")
- def cancel_quarantine_lift(self, request: Request, pk: str, request_id: str, **kwargs) -> Response:
+ def cancel_quarantine_lift(self, request: Request, pk: UUID, request_id: UUID, **kwargs) -> Response:
try:
api.cancel_quarantine_lift(
- run_id=_parse_uuid(pk),
- request_id=_parse_uuid(request_id, field="request_id"),
+ run_id=pk,
+ request_id=request_id,
team_id=self.team_id,
)
except (api.RunNotFoundError, api.QuarantineLiftRequestNotFoundError):
diff --git a/products/visual_review/backend/tests/test_presentation.py b/products/visual_review/backend/tests/test_presentation.py
index 9d98dbf02593..64d0da75ef3a 100644
--- a/products/visual_review/backend/tests/test_presentation.py
+++ b/products/visual_review/backend/tests/test_presentation.py
@@ -1049,26 +1049,29 @@ class TestRepoRunsSearch(VisualReviewTeamScopedTestMixin, APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
-class TestMalformedUuidReturns400(VisualReviewTeamScopedTestMixin, APIBaseTest):
+class TestMalformedUuid(VisualReviewTeamScopedTestMixin, APIBaseTest):
databases = PRODUCT_DATABASES
# 13 hex chars in the final group — the shape that reached us from an MCP client.
BAD_UUID = "4c4e61e7-192b-44cd-a0bf-c9ee996998625"
+ RUN_ID = "3f1c9f0e-2b7a-4a5f-9c1d-8e6b2a4f7d31"
@parameterized.expand(
[
- ("run_retrieve", "runs/{bad}/"),
- ("run_snapshots", "runs/{bad}/snapshots/"),
- ("repo_retrieve", "repos/{bad}/"),
- # Parent path segment (parents_query_dict) rather than pk.
- ("repo_nested_runs", "repos/{bad}/runs/"),
+ ("run_retrieve", "get", "runs/{bad}/", status.HTTP_404_NOT_FOUND),
+ ("run_snapshots", "get", "runs/{bad}/snapshots/", status.HTTP_404_NOT_FOUND),
+ ("repo_retrieve", "get", "repos/{bad}/", status.HTTP_404_NOT_FOUND),
+ # A second path capture, declared in path_parameters next to pk.
+ ("cancel_lift", "post", "runs/{run}/quarantine_lifts/{bad}/cancel/", status.HTTP_404_NOT_FOUND),
+ # Parent path segment (parents_query_dict), which path_parameters does not parse.
+ ("repo_nested_runs", "get", "repos/{bad}/runs/", status.HTTP_400_BAD_REQUEST),
]
)
- def test_malformed_uuid_returns_400_not_500(self, _name: str, path: str) -> None:
- suffix = path.format(bad=self.BAD_UUID)
- response = self.client.get(f"/api/projects/{self.team.id}/visual_review/{suffix}")
+ def test_malformed_uuid_is_not_a_500(self, _name: str, method: str, path: str, expected_status: int) -> None:
+ suffix = path.format(bad=self.BAD_UUID, run=self.RUN_ID)
+ response = getattr(self.client, method)(f"/api/projects/{self.team.id}/visual_review/{suffix}")
- assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.status_code == expected_status, response.json()
class TestSnapshotLookupRequiresIdentifier(VisualReviewTeamScopedTestMixin, APIBaseTest):