: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(projects): match ?search= as a phrase, not as split terms (#79516)
Yasend02c6ae0aeb2
diff --git a/posthog/api/project.py b/posthog/api/project.pyindex 470fd9a3ce2a..fbd61fb1e536 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -13,7 +13,7 @@ from django.utils.dateparse import parse_datetimeimport structlogfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view-from rest_framework import exceptions, filters, request, response, serializers, viewsets+from rest_framework import exceptions, request, response, serializers, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.permissions import BasePermission, IsAuthenticated@@ -54,6 +54,7 @@ from posthog.constants import AvailableFeaturefrom posthog.decorators import disallow_if_impersonatedfrom posthog.event_usage import report_user_actionfrom posthog.exceptions import Conflict+from posthog.filters import PhraseSearchFilterfrom posthog.geoip import get_geoip_propertiesfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.models import User@@ -1328,7 +1329,7 @@ class ProjectViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsetsqueryset = Project.objects.all().select_related("organization").prefetch_related("teams")lookup_field = "id"ordering = "-created_by"- filter_backends = [filters.SearchFilter]+ filter_backends = [PhraseSearchFilter]search_fields = ["name"]def safely_get_queryset(self, queryset):diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.pyindex b1e0ab81820d..137b9cebb965 100644--- a/posthog/api/test/test_project.py+++ b/posthog/api/test/test_project.py@@ -667,7 +667,7 @@ class TestProjectAPI(team_api_test_factory()): # type: ignoreresponse = self.client.post(f"/api/projects/{self.project.id}/generate_conversations_public_token/")self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)- def test_project_name_search_filter(self):+ def _create_searchable_projects(self) -> None:self.organization.available_product_features = [{"key": AvailableFeature.ORGANIZATIONS_PROJECTS,@@ -679,39 +679,37 @@ class TestProjectAPI(team_api_test_factory()): # type: ignoreself.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()- Project.objects.create_with_team(- organization=self.organization,- name="Analytics Dashboard",- initiating_user=self.user,- )- Project.objects.create_with_team(- organization=self.organization,- name="Revenue Tracker",- initiating_user=self.user,- )- Project.objects.create_with_team(- organization=self.organization,- name="User Analytics",- initiating_user=self.user,- )+ for name in [+ "Analytics Dashboard",+ "Revenue Tracker",+ "User Analytics",+ "Acme Non-prod",+ "Acme NON PROD Portal",+ ]:+ Project.objects.create_with_team(+ organization=self.organization,+ name=name,+ initiating_user=self.user,+ )- response = self.client.get("/api/projects/?search=Analytics")- self.assertEqual(response.status_code, status.HTTP_200_OK)- results = response.json()["results"]- self.assertEqual(len(results), 2)- names = {r["name"] for r in results}- self.assertEqual(names, {"Analytics Dashboard", "User Analytics"})+ @parameterized.expand(+ [+ ("term_matching_several", "Analytics", {"Analytics Dashboard", "User Analytics"}),+ ("term_matching_one", "Revenue", {"Revenue Tracker"}),+ ("term_matching_none", "nonexistent", set()),+ # The space is part of the value, so "Acme Non-prod" must not come back+ ("phrase_keeps_its_space", "NON%20PROD", {"Acme NON PROD Portal"}),+ # Quotes carry no meaning, so they only match a name that contains them+ ("quotes_match_literally", "%22NON%20PROD%22", set()),+ ]+ )+ def test_project_name_search_filter(self, _name: str, query: str, expected_names: set[str]) -> None:+ self._create_searchable_projects()- response = self.client.get("/api/projects/?search=Revenue")- self.assertEqual(response.status_code, status.HTTP_200_OK)- results = response.json()["results"]- self.assertEqual(len(results), 1)- self.assertEqual(results[0]["name"], "Revenue Tracker")+ response = self.client.get(f"/api/projects/?search={query}")- response = self.client.get("/api/projects/?search=nonexistent")self.assertEqual(response.status_code, status.HTTP_200_OK)- results = response.json()["results"]- self.assertEqual(len(results), 0)+ self.assertEqual({result["name"] for result in response.json()["results"]}, expected_names)def test_read_only_api_key_cannot_update_project_config_fields(self):"""API keys with only project:read scope should not be able to modify config fields via /api/projects/."""diff --git a/posthog/filters.py b/posthog/filters.pyindex 432db2c3c453..c984d6382924 100644--- a/posthog/filters.py+++ b/posthog/filters.py@@ -11,6 +11,17 @@ from rest_framework.views import APIView_MT = TypeVar("_MT", bound=models.Model)+class PhraseSearchFilter(filters.SearchFilter):+ """Matches `?search=` as one literal substring instead of splitting it into independent terms.++ DRF's SearchFilter ANDs the whitespace-separated parts, so `NON PROD` also matches `Non-prod`.+ """++ def get_search_terms(self, request: Request) -> list[str]:+ term = request.query_params.get(self.search_param, "").replace("\x00", "").strip()+ return [term] if term else []++class TermSearchFilterBackend(filters.BaseFilterBackend):"""Allows fuzzy searching based on the pg_trgm extension.