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.

fix(visual_review): return 400 for malformed run UUID instead of 500 (#73406)

posthog[bot]9d80cc95d026
diff --git a/products/visual_review/backend/presentation/views.py b/products/visual_review/backend/presentation/views.py
index 23b1999df837..a2ac919d9e34 100644
--- a/products/visual_review/backend/presentation/views.py
+++ b/products/visual_review/backend/presentation/views.py
@@ -20,6 +20,7 @@ from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
from rest_framework import status, viewsets
from rest_framework.decorators import action
+from rest_framework.exceptions import ValidationError
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.request import Request
from rest_framework.response import Response
@@ -64,6 +65,18 @@ from .serializers import (
)
+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.
+
+ Path segments reach the viewset as raw strings, so a malformed run/repo id (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:
+ return UUID(value)
+ except ValueError:
+ raise ValidationError({field: "Must be a valid UUID."})
+
+
class SnapshotsPagination(LimitOffsetPagination):
"""Adds quarantined_count to the paginated snapshots envelope so a client can
show "N quarantined hidden" without a second request. The action sets
@@ -137,8 +150,9 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
def retrieve(self, request: Request, pk: str, **kwargs) -> Response:
"""Get a repo by ID."""
+ repo_id = _parse_uuid(pk)
try:
- repo = api.get_repo(UUID(pk), team_id=self.team_id)
+ repo = api.get_repo(repo_id, 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)
@@ -152,7 +166,7 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""Update a repo's settings."""
body = request.validated_data
input_dto = UpdateRepoInput(
- repo_id=UUID(pk),
+ repo_id=_parse_uuid(pk),
baseline_file_paths=body.baseline_file_paths,
enable_pr_comments=body.enable_pr_comments,
)
@@ -173,14 +187,15 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@action(detail=True, methods=["get"], url_path=r"thumbnails/(?P<identifier>.+[^/])")
def thumbnail(self, request: Request, pk: str, identifier: str, **kwargs) -> HttpResponse:
"""Serve a snapshot thumbnail by identifier. Returns WebP with ETag caching."""
+ repo_id = _parse_uuid(pk)
try:
- api.get_repo(UUID(pk), team_id=self.team_id)
+ api.get_repo(repo_id, team_id=self.team_id)
except api.RepoNotFoundError:
resp = HttpResponse(status=404)
patch_cache_control(resp, no_store=True)
return resp
- thumb_hash = api.get_thumbnail_hash_for_identifier(UUID(pk), identifier)
+ thumb_hash = api.get_thumbnail_hash_for_identifier(repo_id, identifier)
if thumb_hash is None:
resp = HttpResponse(status=404)
patch_cache_control(resp, no_store=True)
@@ -193,7 +208,7 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
patch_vary_headers(not_modified, ["Authorization", "Cookie"])
return not_modified
- thumb_bytes = api.read_thumbnail_bytes(UUID(pk), thumb_hash)
+ thumb_bytes = api.read_thumbnail_bytes(repo_id, thumb_hash)
if thumb_bytes is None:
resp = HttpResponse(status=404)
patch_cache_control(resp, no_store=True)
@@ -221,7 +236,7 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""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")
- entries = api.list_quarantined(UUID(pk), team_id=self.team_id, identifier=identifier, run_type=run_type)
+ entries = api.list_quarantined(_parse_uuid(pk), team_id=self.team_id, identifier=identifier, run_type=run_type)
page = self.paginate_queryset(entries)
if page is not None:
serializer = QuarantinedIdentifierEntrySerializer(instance=page, many=True)
@@ -237,7 +252,7 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""Quarantine a snapshot identifier for a specific run type."""
try:
entry = api.quarantine_identifier(
- repo_id=UUID(pk),
+ repo_id=_parse_uuid(pk),
run_type=run_type,
input=request.validated_data,
user_id=cast(int, request.user.id),
@@ -256,7 +271,7 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""Expire all active quarantine entries for an identifier."""
try:
api.unquarantine_identifier(
- repo_id=UUID(pk),
+ repo_id=_parse_uuid(pk),
identifier=request.validated_data.identifier,
run_type=run_type,
team_id=self.team_id,
@@ -279,11 +294,12 @@ 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)
try:
- api.get_repo(UUID(pk), team_id=self.team_id)
+ api.get_repo(repo_id, team_id=self.team_id)
except api.RepoNotFoundError:
return Response({"detail": "Repo not found"}, status=status.HTTP_404_NOT_FOUND)
- result = api.get_baselines_overview(UUID(pk))
+ result = api.get_baselines_overview(repo_id)
return Response(BaselineOverviewSerializer(instance=result).data)
@@ -320,7 +336,7 @@ class SnapshotViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
def timeline(self, request: Request, run_type: str, identifier: str, **kwargs) -> Response:
"""Deduped baseline timeline for a snapshot identity. Newest first."""
- repo_id = UUID(self.parents_query_dict["repo_id"])
+ repo_id = _parse_uuid(self.parents_query_dict["repo_id"], field="repo_id")
try:
api.get_repo(repo_id, team_id=self.team_id)
except api.RepoNotFoundError:
@@ -365,7 +381,7 @@ class RepoRunsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
{"detail": f"search must be at most {MAX_SEARCH_LENGTH} characters"},
status=status.HTTP_400_BAD_REQUEST,
)
- repo_id = UUID(self.parents_query_dict["repo_id"])
+ repo_id = _parse_uuid(self.parents_query_dict["repo_id"], field="repo_id")
runs = api.list_runs(self.team_id, review_state=review_state, repo_id=repo_id, search=search)
page = self.paginate_queryset(runs)
if page is not None:
@@ -377,7 +393,7 @@ class RepoRunsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@action(detail=False, methods=["get"])
def counts(self, request: Request, **kwargs) -> Response:
"""Review state counts for runs in this repo."""
- repo_id = UUID(self.parents_query_dict["repo_id"])
+ repo_id = _parse_uuid(self.parents_query_dict["repo_id"], field="repo_id")
return Response(api.get_review_state_counts(self.team_id, repo_id=repo_id))
@@ -466,7 +482,7 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def retrieve(self, request: Request, pk: str, **kwargs) -> Response:
"""Get run status and summary."""
try:
- run = api.get_run(UUID(pk), team_id=self.team_id)
+ run = api.get_run(_parse_uuid(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)
@@ -490,7 +506,9 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""Get a run's snapshots with diff results, excluding quarantined ones by default."""
include_quarantined = request.query_params.get("include_quarantined", "").lower() in ("1", "true")
try:
- result = api.get_run_snapshots(UUID(pk), team_id=self.team_id, include_quarantined=include_quarantined)
+ result = api.get_run_snapshots(
+ _parse_uuid(pk), team_id=self.team_id, include_quarantined=include_quarantined
+ )
except api.RunNotFoundError:
return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
page = self.paginate_queryset(result.snapshots)
@@ -509,7 +527,7 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""Mark a changed snapshot as a known tolerated alternate."""
try:
snapshot = api.mark_snapshot_as_tolerated(
- run_id=UUID(pk),
+ run_id=_parse_uuid(pk),
snapshot_id=request.validated_data["snapshot_id"],
user_id=cast(int, request.user.id),
team_id=self.team_id,
@@ -531,7 +549,7 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
if not identifier:
return Response({"detail": "identifier query param required"}, status=status.HTTP_400_BAD_REQUEST)
try:
- run = api.get_run(UUID(pk), team_id=self.team_id)
+ run = api.get_run(_parse_uuid(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(run.repo_id, identifier)
@@ -548,7 +566,7 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
try:
result = api.add_snapshots(
input=request.validated_data,
- run_id=UUID(pk),
+ run_id=_parse_uuid(pk),
team_id=self.team_id,
)
except api.RunNotFoundError:
@@ -569,7 +587,7 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response({"detail": "identifier query param required"}, status=status.HTTP_400_BAD_REQUEST)
try:
- run = api.get_run(UUID(pk), team_id=self.team_id)
+ run = api.get_run(_parse_uuid(pk), team_id=self.team_id)
except api.RunNotFoundError:
return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
@@ -584,7 +602,7 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def complete(self, request: Request, pk: str, **kwargs) -> Response:
"""Complete a run: detect removals, verify uploads, trigger diff processing."""
try:
- run = api.complete_run(UUID(pk), team_id=self.team_id)
+ run = api.complete_run(_parse_uuid(pk), team_id=self.team_id)
except api.RunNotFoundError:
return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
except api.GitHubRateLimitError as e:
@@ -609,7 +627,7 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
or change the GitHub gate — call finalize to ship the run.
"""
body = request.validated_data
- run_id = UUID(pk)
+ run_id = _parse_uuid(pk)
user_id = cast(int, request.user.id)
try:
@@ -639,7 +657,7 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
the server returns the signed baseline YAML instead of committing it.
"""
body = request.validated_data
- run_id = UUID(pk)
+ run_id = _parse_uuid(pk)
user_id = cast(int, request.user.id)
try:
@@ -688,7 +706,7 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@action(detail=True, methods=["post"], url_path="recompute")
def recompute(self, request: Request, pk: str, **kwargs) -> Response:
try:
- result = api.recompute_run(UUID(pk), team_id=self.team_id)
+ result = api.recompute_run(_parse_uuid(pk), team_id=self.team_id)
except api.RunNotFoundError:
return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
except ValueError:
diff --git a/products/visual_review/backend/tests/test_presentation.py b/products/visual_review/backend/tests/test_presentation.py
index a79bfd58a9d5..b0ff53afbca4 100644
--- a/products/visual_review/backend/tests/test_presentation.py
+++ b/products/visual_review/backend/tests/test_presentation.py
@@ -624,6 +624,28 @@ class TestRepoRunsSearch(VisualReviewTeamScopedTestMixin, APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+class TestMalformedUuidReturns400(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"
+
+ @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/"),
+ ]
+ )
+ 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}")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+
+
class TestRunFinalizePersonalAPIKeyScopes(VisualReviewTeamScopedTestMixin, APIBaseTest):
databases = PRODUCT_DATABASES
CONFIG_AUTO_LOGIN = False