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(file-system): validate path and meta inputs (#74439)

Tom Piccirello85af9311ac8d
diff --git a/posthog/api/file_system/file_system.py b/posthog/api/file_system/file_system.py
index bcc17a1a9854..5fe278c33a8d 100644
--- a/posthog/api/file_system/file_system.py
+++ b/posthog/api/file_system/file_system.py
@@ -1,4 +1,5 @@
import re
+import json
import shlex
import logging
import builtins
@@ -57,11 +58,33 @@ DELETE_PREVIEW_ENTRY_LIMIT = 200
# endpoint can't be used to learn which refs exist.
UNDO_DELETE_REFUSED = "Couldn't restore this. It may already be restored, or you may not have access to it."
+# Paths the product itself builds are at most three segments deep ("Unfiled/Insights/<name>"), so
+# these leave ample headroom for hand-made trees while keeping the per-segment folder creation in
+# `_assure_parent_folders` (one existence check plus one insert each) bounded.
+MAX_PATH_LENGTH = 4000
+MAX_PATH_SEGMENTS = 50
+
+# `meta` is a free-form client blob, so it only needs a ceiling that keeps a single row from
+# dominating a page of list results.
+MAX_META_BYTES = 1_000_000
+
# Search-within-Recents scans this many of the user's most-recent views, then the text filter trims
# them to a page. Bounds the hydration key set so the query stays cheap on heavy view-log histories.
RECENTS_SEARCH_SCAN_LIMIT = 200
+def validate_file_system_path(path: Any) -> str:
+ """Bound a caller-supplied path before it reaches the per-segment folder creation loop, which
+ costs one existence check plus one insert per segment and autocommits each one."""
+ if not isinstance(path, str):
+ raise serializers.ValidationError("Path must be a string.")
+ if len(path) > MAX_PATH_LENGTH:
+ raise serializers.ValidationError(f"Path must be {MAX_PATH_LENGTH} characters or fewer.")
+ if len(split_path(path)) > MAX_PATH_SEGMENTS:
+ raise serializers.ValidationError(f"Path can be at most {MAX_PATH_SEGMENTS} levels deep.")
+ return path
+
+
class FileSystemSerializer(FileSystemAccessLevelSerializerMixin, serializers.ModelSerializer):
last_viewed_at = serializers.DateTimeField(read_only=True, allow_null=True)
created_by = UserBasicSerializer(read_only=True, allow_null=True)
@@ -91,6 +114,18 @@ class FileSystemSerializer(FileSystemAccessLevelSerializerMixin, serializers.Mod
"user_access_level",
]
+ def validate_path(self, path: str) -> str:
+ return validate_file_system_path(path)
+
+ def validate_meta(self, meta: Any) -> dict[str, Any]:
+ # Readers treat `meta` as an object, so anything else stored here breaks every listing that
+ # includes the row, not just the writer's own request.
+ if not isinstance(meta, dict):
+ raise serializers.ValidationError("Meta must be an object.")
+ if len(json.dumps(meta, default=str).encode()) > MAX_META_BYTES:
+ raise serializers.ValidationError(f"Meta must be smaller than {MAX_META_BYTES / 1_000_000:g} MB.")
+ return meta
+
def update(self, instance: FileSystem, validated_data: dict[str, Any]) -> FileSystem:
if "path" in validated_data:
instance.depth = len(split_path(validated_data["path"]))
@@ -157,6 +192,10 @@ class UndoDeleteItemSerializer(serializers.Serializer):
ref = serializers.CharField()
path = serializers.CharField(required=False, allow_blank=True)
+ def validate_path(self, value: str) -> str:
+ # Restoring re-creates parent folders through the same per-segment loop as create/move/link.
+ return validate_file_system_path(value)
+
class UndoDeleteRequestSerializer(serializers.Serializer):
items = UndoDeleteItemSerializer(many=True)
@@ -495,12 +534,16 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
def _created_by_users(self, results: builtins.list[dict[str, Any]]) -> builtins.list[dict[str, Any]]:
# Collect user IDs from the "created_by" meta field so the client can render avatars
- # without a second round-trip.
- user_ids = {
- created_by
- for item in results
- if isinstance((created_by := item.get("meta", {}).get("created_by")), int) and created_by
- }
+ # without a second round-trip. Rows written before `meta` was validated can hold a
+ # non-object value, and one of those must not take down the whole listing.
+ user_ids = set()
+ for item in results:
+ meta = item.get("meta")
+ if not isinstance(meta, dict):
+ continue
+ created_by = meta.get("created_by")
+ if isinstance(created_by, int) and created_by:
+ user_ids.add(created_by)
if not user_ids:
return []
users_qs = User.objects.filter(organization=self.organization, id__in=user_ids).distinct()
@@ -815,6 +858,7 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
new_path = request.data.get("new_path")
if not new_path:
return Response({"detail": "new_path is required"}, status=status.HTTP_400_BAD_REQUEST)
+ new_path = validate_file_system_path(new_path)
self._assure_parent_folders(new_path, cast(User, request.user))
@@ -864,6 +908,7 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
new_path = request.data.get("new_path")
if not new_path:
return Response({"detail": "new_path is required"}, status=status.HTTP_400_BAD_REQUEST)
+ new_path = validate_file_system_path(new_path)
self._assure_parent_folders(new_path, cast(User, request.user))
diff --git a/posthog/api/file_system/test/test_file_system.py b/posthog/api/file_system/test/test_file_system.py
index 122ac9d271f3..5893bf604a81 100644
--- a/posthog/api/file_system/test/test_file_system.py
+++ b/posthog/api/file_system/test/test_file_system.py
@@ -9,6 +9,7 @@ from unittest.mock import patch
from django.core.cache import cache
from django.db import connection
+from django.test import SimpleTestCase
from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
@@ -16,7 +17,14 @@ from rest_framework import status
from rest_framework.test import APIRequestFactory
from posthog.api.file_system.deletion import undo_delete
-from posthog.api.file_system.file_system import DELETE_PREVIEW_ENTRY_LIMIT
+from posthog.api.file_system.file_system import (
+ DELETE_PREVIEW_ENTRY_LIMIT,
+ MAX_META_BYTES,
+ MAX_PATH_LENGTH,
+ MAX_PATH_SEGMENTS,
+ FileSystemSerializer,
+ UndoDeleteItemSerializer,
+)
from posthog.models import OrganizationMembership, Project, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.file_system.file_system import FileSystem
@@ -2357,3 +2365,80 @@ class TestDestroyRepairsLeftoverHogFunctions(APIBaseTest):
"ref": str(feature.id),
"path": fs_entry.path,
}
+
+
+class TestFileSystemSerializerInputValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("meta_null", {"path": "a", "type": "doc", "meta": None}, "meta"),
+ ("meta_list", {"path": "a", "type": "doc", "meta": [1, 2, 3]}, "meta"),
+ ("meta_number", {"path": "a", "type": "doc", "meta": 5}, "meta"),
+ ("meta_string", {"path": "a", "type": "doc", "meta": "nope"}, "meta"),
+ ("meta_too_large", {"path": "a", "type": "doc", "meta": {"k": "x" * (MAX_META_BYTES + 1)}}, "meta"),
+ ("path_too_long", {"path": "x" * (MAX_PATH_LENGTH + 1), "type": "doc"}, "path"),
+ ("path_too_many_segments", {"path": "/".join(["s"] * (MAX_PATH_SEGMENTS + 1)), "type": "doc"}, "path"),
+ ]
+ )
+ def test_rejects_out_of_bounds_input(self, _name: str, payload: dict[str, Any], field: str) -> None:
+ serializer = FileSystemSerializer(data=payload)
+
+ self.assertFalse(serializer.is_valid())
+ self.assertIn(field, serializer.errors)
+
+ @parameterized.expand(
+ [
+ ("meta_dict", {"path": "a/b", "type": "doc", "meta": {"created_by": 1}}),
+ ("meta_absent", {"path": "a/b", "type": "doc"}),
+ ("meta_empty", {"path": "a/b", "type": "doc", "meta": {}}),
+ ("path_at_segment_limit", {"path": "/".join(["s"] * MAX_PATH_SEGMENTS), "type": "doc"}),
+ ]
+ )
+ def test_accepts_in_bounds_input(self, _name: str, payload: dict[str, Any]) -> None:
+ serializer = FileSystemSerializer(data=payload)
+
+ self.assertTrue(serializer.is_valid(), serializer.errors)
+
+
+class TestFileSystemInputValidationAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.user.is_staff = True
+ self.user.save()
+ self.url = f"/api/projects/{self.team.id}/file_system/"
+
+ def test_create_with_too_many_path_segments_is_rejected_and_writes_nothing(self):
+ response = self.client.post(self.url, {"path": "/".join(["s"] * (MAX_PATH_SEGMENTS + 1)), "type": "doc"})
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())
+ self.assertEqual(FileSystem.objects.filter(team=self.team).count(), 0)
+
+ @parameterized.expand(["move", "link"])
+ def test_action_with_too_many_path_segments_is_rejected_and_writes_nothing(self, action_name: str):
+ item_id = self.client.post(self.url, {"path": "Start", "type": "doc"}).json()["id"]
+
+ response = self.client.post(
+ f"{self.url}{item_id}/{action_name}/",
+ {"new_path": "/".join(["s"] * (MAX_PATH_SEGMENTS + 1))},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())
+ self.assertEqual(FileSystem.objects.filter(team=self.team).count(), 1)
+
+ @parameterized.expand([("too_many_segments", "s/" * (MAX_PATH_SEGMENTS + 1)), ("too_long", "x" * 4001)])
+ def test_undo_delete_rejects_an_unbounded_restore_path(self, _name: str, path: str):
+ # undo_delete re-creates parent folders through the same per-segment loop as create/move,
+ # so its restore path needs the same bound. Asserted on the serializer rather than the
+ # endpoint because an unresolvable ref would 400 on its own and mask the bound.
+ serializer = UndoDeleteItemSerializer(data={"type": "doc", "ref": "1", "path": path})
+
+ self.assertFalse(serializer.is_valid())
+ self.assertIn("path", serializer.errors)
+
+ @parameterized.expand([("null", None), ("list", ["poison"]), ("string", "poison")])
+ def test_list_survives_a_row_with_non_object_meta(self, _name: str, meta: Any):
+ FileSystem.objects.create(team=self.team, path="!", type="doc", created_by=self.user, meta=meta)
+
+ response = self.client.get(self.url)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual([row["path"] for row in response.json()["results"]], ["!"])