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: add scoping checks (#61901)

Tom Piccirello69683686efb5
diff --git a/ee/api/billing.py b/ee/api/billing.py
index 265eb9472b7d..16805675ba5e 100644
--- a/ee/api/billing.py
+++ b/ee/api/billing.py
@@ -396,7 +396,11 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
res = billing_manager.authorize_status(organization, request.data)
return Response(res, status=status.HTTP_200_OK)
- @action(methods=["PATCH"], detail=False)
+ @action(
+ methods=["PATCH"],
+ detail=False,
+ permission_classes=[permissions.IsAuthenticated, IsOrganizationAdmin],
+ )
def license(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:
license = get_cached_instance_license()
diff --git a/ee/api/dashboard_collaborator.py b/ee/api/dashboard_collaborator.py
index c8b87ef2ada8..678c7068aa90 100644
--- a/ee/api/dashboard_collaborator.py
+++ b/ee/api/dashboard_collaborator.py
@@ -23,8 +23,9 @@ class CanEditDashboardCollaborator(BasePermission):
if request.method in SAFE_METHODS:
return True
try:
- # nosemgrep: idor-lookup-without-team (dashboard access validated by parent viewset)
- dashboard: Dashboard = Dashboard.objects.get(id=view.parents_query_dict["dashboard_id"])
+ dashboard: Dashboard = Dashboard.objects.get(
+ id=view.parents_query_dict["dashboard_id"], team__project_id=view.team.project_id
+ )
except Dashboard.DoesNotExist:
raise exceptions.NotFound("Dashboard not found.")
@@ -104,8 +105,9 @@ class DashboardCollaboratorViewSet(
def get_serializer_context(self) -> dict[str, Any]:
context = super().get_serializer_context()
try:
- # nosemgrep: idor-lookup-without-team (dashboard access validated by parent viewset)
- context["dashboard"] = Dashboard.objects.get(id=context["dashboard_id"])
+ context["dashboard"] = Dashboard.objects.get(
+ id=context["dashboard_id"], team__project_id=self.team.project_id
+ )
except Dashboard.DoesNotExist:
raise exceptions.NotFound("Dashboard not found.")
return context
diff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.py
index 74b3b504e52c..392c3ebc9c01 100644
--- a/ee/api/test/test_billing.py
+++ b/ee/api/test/test_billing.py
@@ -271,6 +271,16 @@ class TestUnlicensedBillingAPI(APIBaseTest):
"products": create_default_products_response()["products"],
}
+ def test_license_patch_denied_for_members(self):
+ # Unlicensed instance, so the permission layer (not the "license already exists"
+ # guard) decides the outcome. Setting the instance-wide license key is an
+ # admin-only action.
+ TEST_clear_instance_license_cache()
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ response = self.client.patch("/api/billing/license", {}, content_type="application/json")
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
class TestBillingAPI(APILicensedTest):
def test_billing_fails_for_old_license_type(self):
diff --git a/ee/api/test/test_dashboard_collaborators.py b/ee/api/test/test_dashboard_collaborators.py
index 261798c6b6f6..23e2941fdf7b 100644
--- a/ee/api/test/test_dashboard_collaborators.py
+++ b/ee/api/test/test_dashboard_collaborators.py
@@ -286,3 +286,52 @@ class TestDashboardCollaboratorsAPI(APILicensedTest):
response_data,
self.permission_denied_response("You don't have edit permissions for this dashboard."),
)
+
+ def test_cannot_add_collaborator_to_dashboard_in_another_project(self):
+ # Admin of their own project must not be able to manage collaborators on a dashboard
+ # that belongs to a different organization, by passing their own project_id in the URL.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ org_a_collaborator = User.objects.create_and_join(self.organization, "[email protected]", None)
+
+ _, victim_team, _ = User.objects.bootstrap("VictimOrg", "[email protected]", None)
+ victim_dashboard = Dashboard.objects.create(
+ team=victim_team,
+ name="Victim Dashboard",
+ restriction_level=Dashboard.RestrictionLevel.ONLY_COLLABORATORS_CAN_EDIT,
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/{victim_dashboard.id}/collaborators/",
+ {
+ "user_uuid": str(org_a_collaborator.uuid),
+ "level": Dashboard.PrivilegeLevel.CAN_EDIT,
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertFalse(DashboardPrivilege.objects.filter(dashboard=victim_dashboard).exists())
+
+ def test_cannot_remove_collaborator_from_dashboard_in_another_project(self):
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ _, victim_team, _ = User.objects.bootstrap("VictimOrg", "[email protected]", None)
+ victim_dashboard = Dashboard.objects.create(
+ team=victim_team,
+ name="Victim Dashboard",
+ restriction_level=Dashboard.RestrictionLevel.ONLY_COLLABORATORS_CAN_EDIT,
+ )
+ collaborator = User.objects.create_and_join(victim_team.organization, "[email protected]", None)
+ privilege = DashboardPrivilege.objects.create(
+ user=collaborator,
+ dashboard=victim_dashboard,
+ level=Dashboard.PrivilegeLevel.CAN_EDIT,
+ )
+
+ response = self.client.delete(
+ f"/api/projects/{self.team.id}/dashboards/{victim_dashboard.id}/collaborators/{collaborator.uuid}"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertTrue(DashboardPrivilege.objects.filter(id=privilege.id).exists())
diff --git a/ee/api/vercel/test/test_vercel_installation.py b/ee/api/vercel/test/test_vercel_installation.py
index 87f0a8333970..6eb92140e869 100644
--- a/ee/api/vercel/test/test_vercel_installation.py
+++ b/ee/api/vercel/test/test_vercel_installation.py
@@ -103,6 +103,9 @@ class TestVercelInstallationAPI(VercelTestBase):
assert response.json() == {"finalized": True}
def test_invalid_installation_id_format(self):
+ # The token is bound to a different installation than the URL targets, so the
+ # per-installation authorization check rejects the request before the URL format
+ # is ever validated.
url = "/api/vercel/v1/installations/invalid-id/"
response = self._request("get", url=url, auth_type="system")
- assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.status_code == status.HTTP_403_FORBIDDEN
diff --git a/ee/api/vercel/test/test_vercel_permission.py b/ee/api/vercel/test/test_vercel_permission.py
index 3314ddf4322a..a25af95b2063 100644
--- a/ee/api/vercel/test/test_vercel_permission.py
+++ b/ee/api/vercel/test/test_vercel_permission.py
@@ -259,15 +259,17 @@ class TestVercelPermissionIntegration(VercelTestBase):
@parameterized.expand(
[
+ # A token issued for one installation must not be able to act on another
+ # installation by changing the id in the URL.
(
"patch",
VercelTestBase.OTHER_INSTALLATION_ID,
None,
"user",
{"billingPlanId": "pro200"},
- status.HTTP_204_NO_CONTENT,
+ status.HTTP_403_FORBIDDEN,
),
- ("delete", VercelTestBase.OTHER_INSTALLATION_ID, None, "user", None, status.HTTP_200_OK),
+ ("delete", VercelTestBase.OTHER_INSTALLATION_ID, None, "user", None, status.HTTP_403_FORBIDDEN),
("patch", None, None, "system", {"billingPlanId": "pro200"}, status.HTTP_403_FORBIDDEN),
("get", None, None, "user", None, status.HTTP_403_FORBIDDEN),
]
@@ -278,6 +280,18 @@ class TestVercelPermissionIntegration(VercelTestBase):
)
assert response.status_code == expected_status
+ @parameterized.expand([("patch", {"billingPlanId": "pro200"}), ("delete", None)])
+ def test_cross_installation_access_denied(self, method, data):
+ # Token bound to self.installation_id, request targets OTHER_INSTALLATION_ID.
+ response = self._make_request(
+ method,
+ jwt_installation_id=self.installation_id,
+ url_installation_id=VercelTestBase.OTHER_INSTALLATION_ID,
+ auth_type="user",
+ data=data,
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
@parameterized.expand(
[
("patch", "ADMIN", {"billingPlanId": "pro200"}, status.HTTP_204_NO_CONTENT),
diff --git a/ee/api/vercel/vercel_permission.py b/ee/api/vercel/vercel_permission.py
index ae491b95068a..3423345f42ae 100644
--- a/ee/api/vercel/vercel_permission.py
+++ b/ee/api/vercel/vercel_permission.py
@@ -25,6 +25,11 @@ class VercelPermission(BasePermission):
auth_type = request.headers.get("X-Vercel-Auth", "").lower()
if auth_type == "user":
self._validate_user_role(request, view)
+ # Bind the token to its own installation. These viewsets resolve their target by
+ # the URL installation_id without calling check_object_permissions, so the match
+ # must be enforced here for every installation-scoped endpoint.
+ if "installation_id" in view.kwargs or "parent_lookup_installation_id" in view.kwargs:
+ self._validate_installation_id_match(request, view)
return True
def has_object_permission(self, request: Request, view, obj) -> bool:
diff --git a/posthog/async_migrations/migrations/0010_move_old_partitions.py b/posthog/async_migrations/migrations/0010_move_old_partitions.py
index 99b97ddbdf20..f3ed76faca94 100644
--- a/posthog/async_migrations/migrations/0010_move_old_partitions.py
+++ b/posthog/async_migrations/migrations/0010_move_old_partitions.py
@@ -46,18 +46,23 @@ class Migration(AsyncMigrationDefinition):
return is_cloud()
def _get_partitions_to_move(self):
- # nosemgrep: clickhouse-injection-taint - migration params, not user input
+ # Partition bounds come from the request body (AsyncMigration.parameters), so they are
+ # bound as query parameters rather than interpolated into the SQL text.
result = sync_execute(
- f"""
+ """
SELECT DISTINCT partition_id FROM system.parts
WHERE
table = 'sharded_events'
AND (
- partition < '{self.get_parameter("OLDEST_PARTITION_TO_KEEP")}'
- OR partition > '{self.get_parameter("NEWEST_PARTITION_TO_KEEP")}'
+ partition < %(oldest_partition)s
+ OR partition > %(newest_partition)s
)
ORDER BY partition_id
- """
+ """,
+ {
+ "oldest_partition": self.get_parameter("OLDEST_PARTITION_TO_KEEP"),
+ "newest_partition": self.get_parameter("NEWEST_PARTITION_TO_KEEP"),
+ },
)
return [row[0] for row in result]
diff --git a/posthog/async_migrations/test/test_0010_move_old_partitions.py b/posthog/async_migrations/test/test_0010_move_old_partitions.py
new file mode 100644
index 000000000000..771014a84f1d
--- /dev/null
+++ b/posthog/async_migrations/test/test_0010_move_old_partitions.py
@@ -0,0 +1,40 @@
+import importlib
+
+import pytest
+from unittest.mock import patch
+
+from posthog.async_migrations.setup import get_async_migration_definition
+from posthog.async_migrations.test.util import AsyncMigrationBaseTest
+
+pytestmark = pytest.mark.async_migrations
+
+MIGRATION_NAME = "0010_move_old_partitions"
+migration_module = importlib.import_module(f"posthog.async_migrations.migrations.{MIGRATION_NAME}")
+
+
+class Test0010MoveOldPartitions(AsyncMigrationBaseTest):
+ def test_partition_parameters_are_bound_not_interpolated(self):
+ migration = get_async_migration_definition(MIGRATION_NAME)
+ malicious = "200001' OR '1'='1"
+
+ with (
+ patch.object(migration_module, "sync_execute", return_value=[]) as mock_sync_execute,
+ patch.object(
+ migration,
+ "get_parameter",
+ side_effect=lambda name: {
+ "OLDEST_PARTITION_TO_KEEP": malicious,
+ "NEWEST_PARTITION_TO_KEEP": "202308",
+ }[name],
+ ),
+ ):
+ migration._get_partitions_to_move()
+
+ mock_sync_execute.assert_called_once()
+ call = mock_sync_execute.call_args
+ sql = call.args[0]
+ params = call.args[1] if len(call.args) > 1 else call.kwargs.get("args")
+
+ assert malicious not in sql
+ assert params is not None
+ assert malicious in params.values()
diff --git a/products/cdp/backend/api/hog_function_template.py b/products/cdp/backend/api/hog_function_template.py
index 0f170163f8f7..5cceaa2ed50b 100644
--- a/products/cdp/backend/api/hog_function_template.py
+++ b/products/cdp/backend/api/hog_function_template.py
@@ -84,11 +84,18 @@ class PublicHogFunctionTemplateViewSet(
viewsets.GenericViewSet,
):
scope_object = "hog_function"
- permission_classes = [permissions.AllowAny]
serializer_class = HogFunctionTemplateSerializer
queryset = HogFunctionTemplate.objects.all()
lookup_field = "template_id"
+ def get_permissions(self):
+ # The dedicated public catalog endpoint is intentionally anonymous. The project-nested
+ # mount is part of the authenticated app and must not expose templates (including hidden
+ # ones) to anonymous callers.
+ if self.request.path.startswith("/api/public_hog_function_templates"):
+ return [permissions.AllowAny()]
+ return [permissions.IsAuthenticated()]
+
def filter_queryset(self, queryset: QuerySet) -> QuerySet:
if self.action == "list":
types = ["destination"]
@@ -102,11 +109,8 @@ class PublicHogFunctionTemplateViewSet(
if self.request.GET.get("template_id"):
queryset = queryset.filter(template_id=self.request.GET["template_id"])
- # Don't include deprecated templates when listing
- queryset = queryset.exclude(status="deprecated")
-
- if self.request.path.startswith("/api/public_hog_function_templates"):
- queryset = queryset.exclude(status="hidden")
+ # Don't include deprecated or hidden templates when listing, regardless of mount
+ queryset = queryset.exclude(status="deprecated").exclude(status="hidden")
return queryset
diff --git a/products/cdp/backend/api/plugin.py b/products/cdp/backend/api/plugin.py
index e868b2f28c70..fccf7ef45330 100644
--- a/products/cdp/backend/api/plugin.py
+++ b/products/cdp/backend/api/plugin.py
@@ -406,9 +406,16 @@ class PluginViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
@action(methods=["GET"], detail=False)
def unused(self, request: request.Request, **kwargs):
- ids = Plugin.objects.exclude(
- id__in=PluginConfig.objects.filter(enabled=True).values_list("plugin_id", flat=True)
- ).values_list("id", flat=True)
+ ids = (
+ self.get_queryset()
+ .exclude(
+ id__in=PluginConfig.objects.filter(
+ enabled=True, team__organization_id=self.organization_id
+ ).values_list("plugin_id", flat=True)
+ )
+ .order_by("id")
+ .values_list("id", flat=True)
+ )
return Response(ids)
@action(methods=["GET"], detail=False)
diff --git a/products/cdp/backend/api/test/test_hog_function_templates.py b/products/cdp/backend/api/test/test_hog_function_templates.py
index b6b4afdecd5a..bfef53ac6bc6 100644
--- a/products/cdp/backend/api/test/test_hog_function_templates.py
+++ b/products/cdp/backend/api/test/test_hog_function_templates.py
@@ -271,8 +271,53 @@ class TestHogFunctionTemplates(ClickhouseTestMixin, APIBaseTest, QueryMatchingTe
data=payload,
)
- assert response.status_code in {status.HTTP_405_METHOD_NOT_ALLOWED}, response.json()
+ assert response.status_code in {
+ status.HTTP_401_UNAUTHORIZED,
+ status.HTTP_403_FORBIDDEN,
+ status.HTTP_405_METHOD_NOT_ALLOWED,
+ }, response.json()
unchanged_template = self.client.get("/api/projects/@current/hog_function_templates/template-slack")
assert unchanged_template.json()["code"] != 'return "scary_code"'
+
+ def test_hidden_template_not_exposed_to_anonymous_on_project_route(self):
+ HogFunctionTemplate.objects.create(
+ template_id="template-hidden",
+ sha="1.0.0",
+ name="Hidden Template",
+ description="A hidden template",
+ code="return event",
+ code_language="hog",
+ inputs_schema={},
+ type="destination",
+ status="hidden",
+ category=["Other"],
+ free=True,
+ )
+ self.client.logout()
+
+ list_response = self.client.get(f"/api/projects/{self.team.id}/hog_function_templates/")
+ assert list_response.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)
+
+ retrieve_response = self.client.get(f"/api/projects/{self.team.id}/hog_function_templates/template-hidden")
+ assert retrieve_response.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)
+
+ def test_hidden_templates_excluded_from_project_list(self):
+ HogFunctionTemplate.objects.create(
+ template_id="template-hidden",
+ sha="1.0.0",
+ name="Hidden Template",
+ description="A hidden template",
+ code="return event",
+ code_language="hog",
+ inputs_schema={},
+ type="destination",
+ status="hidden",
+ category=["Other"],
+ free=True,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_function_templates/")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert "template-hidden" not in [template["id"] for template in response.json()["results"]]
diff --git a/products/cdp/backend/api/test/test_plugin.py b/products/cdp/backend/api/test/test_plugin.py
index 29bd3d5ae16c..47b34a3997d7 100644
--- a/products/cdp/backend/api/test/test_plugin.py
+++ b/products/cdp/backend/api/test/test_plugin.py
@@ -875,6 +875,17 @@ class TestPluginAPI(APIBaseTest, QueryMatchingTest):
[plugin_no_configs.id, plugin_only_disabled.id],
)
+ def test_plugin_unused_does_not_leak_other_orgs(self, mock_get, mock_reload):
+ own_unused = Plugin.objects.create(organization=self.organization)
+ other_org = Organization.objects.create(name="Other Org")
+ other_org_unused = Plugin.objects.create(organization=other_org)
+
+ response = self.client.get("/api/organizations/@current/plugins/unused/")
+
+ self.assertEqual(response.status_code, 200)
+ self.assertIn(own_unused.id, response.json())
+ self.assertNotIn(other_org_unused.id, response.json())
+
def test_install_plugin_on_multiple_orgs(self, mock_get, mock_reload):
# Expectation: since plugins are url-unique, installing the same plugin on a second orgs should
# return a 400 response, as the plugin is already installed on the first org