Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions dojo/product/api/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,7 @@ def get_findings_count(self, obj) -> int:

# TODO: maybe extend_schema_field is needed here?
def get_findings_list(self, obj) -> list[int]:
finding_ids = getattr(obj, "prefetched_active_finding_ids", None)
if finding_ids is not None:
return finding_ids
return obj.open_findings_list()
16 changes: 16 additions & 0 deletions dojo/product/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,22 @@ class ProductViewSet(
permissions.UserHasProductPermission,
)

def paginate_queryset(self, queryset):
page = super().paginate_queryset(queryset)
if self.action == "list" and page:
products = {product.pk: product for product in page}
for product in page:
product.prefetched_active_finding_ids = []
# Load only IDs for the authorized, filtered page, without materializing
# Finding objects. Keep the model's ordering, as open_findings_list() does.
findings = Finding.objects.filter(
test__engagement__product_id__in=products,
active=True,
).values_list("test__engagement__product_id", "id")
for product_id, finding_id in findings.iterator():
products[product_id].prefetched_active_finding_ids.append(finding_id)
return page

def get_queryset(self):
base_findings = Finding.objects.filter(
test__engagement__product_id=OuterRef("pk"),
Expand Down
101 changes: 91 additions & 10 deletions unittests/test_api_product_prefetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def setUp(self):
self.client.force_authenticate(user=self.user)
self.client.force_login(self.user)

def _create_product(self, suffix):
def _create_product(self, suffix, *, active=True):
"""Create a product with every relation the serializer renders."""
product = Product.objects.create(
name=f"ProdPrefetch Product {suffix}",
Expand Down Expand Up @@ -79,7 +79,7 @@ def _create_product(self, suffix):
test=test,
reporter=self.user,
severity="High",
active=True,
active=active,
)
return product

Expand All @@ -89,23 +89,19 @@ def _query_count(self, url):
self.assertEqual(response.status_code, 200, response.content[:2000])
return len(ctx.captured_queries)

def _assert_constant_query_count(self, url, expected_growth=4):
self._create_product("baseline")
def _assert_constant_query_count(self, url, expected_growth=0, *, active=True):
self._create_product("baseline", active=active)
# Warm-up request: fills ContentType cache and other one-time lookups.
self._query_count(url)
with_one = self._query_count(url)

extra_products = 4
for i in range(extra_products):
self._create_product(f"extra-{i}")
self._create_product(f"extra-{i}", active=active)
with_five = self._query_count(url)

per_product_growth = with_five - with_one
# Product.open_findings_list() fires one query per product — a known
# limitation (see the TODO comment on the method) that requires either
# a PostgreSQL-specific ArrayAgg or an API-breaking field removal to
# resolve. All other relations are bulk-loaded, so the per-product
# cost is exactly 1 query. Anything above that signals a new N+1.
# Include the active finding IDs in the constant-query guarantee.
self.assertEqual(
per_product_growth,
expected_growth,
Expand All @@ -116,6 +112,91 @@ def _assert_constant_query_count(self, url, expected_growth=4):
def test_product_list_query_count_constant(self):
self._assert_constant_query_count("/api/v2/products/")

def test_product_list_query_count_constant_for_member(self):
member = Dojo_User.objects.create(username="prodprefetch_member")
self.client.force_authenticate(user=member)
self.client.force_login(member)
self.prod_type.authorized_users.add(member)
self._assert_constant_query_count("/api/v2/products/")

def test_product_list_query_count_constant_without_active_findings(self):
self._assert_constant_query_count("/api/v2/products/", active=False)

def test_product_list_preserves_active_finding_ids_and_order(self):
product = self._create_product("findings")
test = Test.objects.get(engagement__product=product)
for title, severity, numerical_severity, active in (
("First", "Critical", "S0", True),
("Last", "Low", "S3", True),
("Inactive", "High", "S1", False),
):
Finding.objects.create(
test=test, reporter=self.user, title=title, severity=severity,
numerical_severity=numerical_severity, active=active,
)
other = self._create_product("other")
other_test = Test.objects.get(engagement__product=other)
Finding.objects.filter(test=other_test).update(active=False)
extra_engagement = Engagement.objects.create(
product=product, name="Another engagement", target_start=now(), target_end=now(),
)
extra_test = Test.objects.create(
engagement=extra_engagement, test_type=self.test_type, target_start=now(), target_end=now(),
)
Finding.objects.create(
test=extra_test, reporter=self.user, title="Active false positive", severity="Medium",
numerical_severity="S2", active=True, false_p=True,
)

response = self.client.get("/api/v2/products/", {"limit": 100})
self.assertEqual(200, response.status_code)
rows = {row["id"]: row for row in response.data["results"]}
expected = product.open_findings_list()
self.assertEqual(4, len(expected))
self.assertEqual(expected, rows[product.id]["findings_list"])
self.assertEqual(4, rows[product.id]["findings_count"])
self.assertEqual([], rows[other.id]["findings_list"])
self.assertEqual(0, rows[other.id]["findings_count"])

def test_product_list_respects_pagination_and_filtering(self):
products = [self._create_product(f"page-{idx}") for idx in range(3)]
for offset, product in enumerate(products):
response = self.client.get("/api/v2/products/", {"limit": 1, "offset": offset})
self.assertEqual(200, response.status_code)
self.assertEqual(3, response.data["count"])
self.assertEqual([product.id], [row["id"] for row in response.data["results"]])
self.assertEqual(product.open_findings_list(), response.data["results"][0]["findings_list"])

response = self.client.get("/api/v2/products/", {"id": products[1].id})
self.assertEqual(200, response.status_code)
self.assertEqual([products[1].id], [row["id"] for row in response.data["results"]])
self.assertEqual(products[1].open_findings_list(), response.data["results"][0]["findings_list"])

def test_product_list_does_not_include_unauthorized_products(self):
allowed = self._create_product("allowed")
self._create_product("forbidden")
member = Dojo_User.objects.create(username="prodprefetch_restricted")
allowed.authorized_users.add(member)
self.client.force_authenticate(user=member)
self.client.force_login(member)

response = self.client.get("/api/v2/products/")
self.assertEqual(200, response.status_code)
self.assertEqual([allowed.id], [row["id"] for row in response.data["results"]])
self.assertEqual(allowed.open_findings_list(), response.data["results"][0]["findings_list"])

def test_product_list_empty_page(self):
self._create_product("empty-page")
response = self.client.get("/api/v2/products/", {"offset": 10})
self.assertEqual(200, response.status_code)
self.assertEqual([], response.data["results"])

def test_product_retrieve_preserves_active_finding_ids(self):
product = self._create_product("retrieve")
response = self.client.get(f"/api/v2/products/{product.id}/")
self.assertEqual(200, response.status_code)
self.assertEqual(product.open_findings_list(), response.data["findings_list"])

@classmethod
def _v3_enabled(cls):
from django.conf import settings # noqa: PLC0415
Expand Down