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.

chore(storage): restrict auth token cache deserialization (#73372)

Tom Piccirello1920144a3ee0
diff --git a/.agents/security.md b/.agents/security.md
index 4f6708c33384..d926e27a1eec 100644
--- a/.agents/security.md
+++ b/.agents/security.md
@@ -95,6 +95,43 @@ queryset.filter(name__icontains=value) # SAFE
> **JSONField note:** If the first path segment is a JSONField (e.g. `detail__`), Django routes all subsequent `__` as JSON key lookups rather than FK traversals, which mitigates the risk. An allowlist is still recommended as defense in depth.
+## Deserialization (pickle)
+
+**Do not add new `pickle` usage.**
+Unpickling bytes that any other process could influence is arbitrary code execution — the pickle stream can name any importable callable and pass it arguments.
+This applies to the equivalents too: `cPickle`, `cloudpickle`, `dill`, `marshal`, `shelve`, `joblib`, `pandas.read_pickle`, and `numpy.load(..., allow_pickle=True)`.
+CI already fails on new pickle: the `avoid-pickle` rule from the `p/security-audit` Semgrep pack runs with `--error` (see `.github/workflows/ci-security.yaml`), so introducing one is a hard stop, not a warning.
+Pickle can also appear without the word `pickle`: Django's default cache backend (`cache.set` / `cache.get`) pickles values transparently, so treat the cache as a pickle boundary and only store JSON-serializable values in it.
+
+**Use JSON instead.**
+For plain data, use `json`.
+For typed objects, use a schema-validated (de)serializer that constructs only declared types — Pydantic `model.model_dump_json()` / `Model.model_validate_json(...)` is the house default (the AI conversation stream in `ee/hogai/stream/redis_stream.py` uses exactly this).
+Anything that crosses a process, cache, queue, or the wire must be JSON-shaped, not pickle-shaped.
+
+**If pickle is genuinely unavoidable** — almost always an existing cross-language or cross-version format contract you can't change unilaterally (e.g. Django's cache backend and the Rust services both wrap JSON in pickle) — it must satisfy all of:
+
+1. **Internal, self-generated data only.** Never unpickle anything a user, tenant, or untrusted service could write. "Internal Redis" is not a trust boundary — anyone with write access to the datastore controls the bytes.
+2. **A restricted `pickle.Unpickler`.** Override `find_class` to a strict allowlist of the exact classes you expect, or — when the payload is JSON-shaped (str/dict/list/number/bool/None) — a deny-all `find_class` that raises for everything. JSON-shaped values deserialize through dedicated opcodes that never call `find_class`, so denying it blocks every code-execution path while still loading your data.
+3. **A justified `# nosemgrep`** on the line immediately before the call (per the repo nosemgrep convention), stating why it's safe.
+
+Reference implementations:
+
+```python
+# Deny-all: the payload is only ever a JSON string / dict, so no class is ever legitimate.
+# posthog/storage/auth_token_cache_verifier.py -> _JsonOnlyUnpickler
+class _JsonOnlyUnpickler(pickle.Unpickler):
+ def find_class(self, module: str, name: str) -> Any:
+ raise pickle.UnpicklingError(f"refusing to unpickle disallowed global {module}.{name}")
+
+# Allowlist: reconstruct only our own catalog classes.
+# posthog/hogql/database/database.py -> _CatalogUnpickler
+class _CatalogUnpickler(pickle.Unpickler):
+ def find_class(self, module: str, name: str) -> Any:
+ if module.startswith(_ALLOWED_PREFIXES) or module in _ALLOWED_MODULES:
+ return super().find_class(module, name)
+ raise pickle.UnpicklingError(f"refusing to unpickle disallowed global {module}.{name}")
+```
+
## Semgrep Rules
Run `semgrep --config .semgrep/rules/security/ .` to check for injection issues.
diff --git a/posthog/storage/auth_token_cache_verifier.py b/posthog/storage/auth_token_cache_verifier.py
index 53b8d302c244..626bd4de190d 100644
--- a/posthog/storage/auth_token_cache_verifier.py
+++ b/posthog/storage/auth_token_cache_verifier.py
@@ -12,9 +12,11 @@ is keyed by token hash, not by team ID.
from __future__ import annotations
+import io
import json
import pickle
from dataclasses import dataclass, field
+from typing import Any
import redis as redis_lib
import structlog
@@ -135,11 +137,30 @@ def _deserialize_cache_value(raw_value: bytes | str) -> dict | None:
return None
+class _JsonOnlyUnpickler(pickle.Unpickler):
+ """Unpickler that refuses to construct any class or callable.
+
+ The auth-token cache only ever holds ``pickle(json_string)`` or ``pickle(dict)``
+ (Django's cache and the Rust service both wrap a JSON payload). JSON-shaped values —
+ str, dict, list, int, float, bool, None — deserialize through dedicated pickle opcodes
+ that never call ``find_class``. Every code-execution path (GLOBAL/REDUCE/NEWOBJ) routes
+ a class or callable through ``find_class``, so denying it blocks arbitrary-code execution
+ while still loading exactly the data we expect from this internal cache.
+ """
+
+ def find_class(self, module: str, name: str) -> Any:
+ # nosemgrep: python.lang.security.deserialization.pickle.avoid-pickle (deny-all guard: rejects every class/callable, never deserializes one)
+ raise pickle.UnpicklingError(f"refusing to unpickle disallowed global {module}.{name}")
+
+
def _unpickle_json(raw_bytes: bytes) -> dict | None:
- """Unpickle bytes and parse the inner JSON string into a dict."""
+ """Unpickle bytes and parse the inner JSON string into a dict.
+
+ Uses ``_JsonOnlyUnpickler`` so a hostile payload written into Redis can't execute
+ code — the cache only ever holds a JSON string or a plain dict.
+ """
try:
- # nosemgrep: python.lang.security.deserialization.pickle.avoid-pickle (internal Redis cache, data is self-generated by our Rust service)
- unpickled = pickle.loads(raw_bytes) # noqa: S301
+ unpickled = _JsonOnlyUnpickler(io.BytesIO(raw_bytes)).load()
if isinstance(unpickled, str):
data = json.loads(unpickled)
if isinstance(data, dict):
diff --git a/posthog/storage/test/test_auth_token_cache_verifier.py b/posthog/storage/test/test_auth_token_cache_verifier.py
index 1f294f45005c..52747a97fad9 100644
--- a/posthog/storage/test/test_auth_token_cache_verifier.py
+++ b/posthog/storage/test/test_auth_token_cache_verifier.py
@@ -3,7 +3,7 @@ import pickle
from unittest.mock import patch
-from django.test import TestCase
+from django.test import SimpleTestCase, TestCase
import redis as redis_lib
import zstandard as zstd
@@ -14,9 +14,23 @@ from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
from posthog.models.project_secret_api_key import ProjectSecretAPIKey
from posthog.models.team.team import Team
from posthog.models.user import User
-from posthog.storage.auth_token_cache_verifier import verify_and_fix_auth_token_cache
+from posthog.storage.auth_token_cache_verifier import _deserialize_cache_value, verify_and_fix_auth_token_cache
from posthog.storage.team_access_cache import TOKEN_CACHE_PREFIX
+# Module-level so the malicious payload can be pickled by qualified name (local objects aren't picklable).
+_pickle_execution_marker: list[bool] = []
+
+
+def _record_pickle_execution() -> str:
+ _pickle_execution_marker.append(True)
+ return "executed"
+
+
+class _MaliciousPayload:
+ def __reduce__(self):
+ # A stock unpickler runs this callable during load — the classic pickle RCE vector.
+ return (_record_pickle_execution, ())
+
class TestAuthTokenCacheVerifier(TestCase):
def setUp(self):
@@ -892,3 +906,19 @@ class TestAuthTokenCacheVerifier(TestCase):
assert self.redis.exists(key)
assert result.valid >= 1
assert result.parse_errors == 0
+
+
+class TestAuthTokenCacheDeserializationHardening(SimpleTestCase):
+ def test_malicious_pickle_is_rejected_without_executing_code(self):
+ payload = pickle.dumps(_MaliciousPayload())
+
+ # Guard: this payload really is a live execution vector under a stock unpickler.
+ _pickle_execution_marker.clear()
+ # nosemgrep: python.lang.security.deserialization.pickle.avoid-pickle (test asserting the exploit is live, so we can prove the deserializer blocks it)
+ pickle.loads(payload) # noqa: S301
+ assert _pickle_execution_marker == [True]
+
+ # The cache deserializer must reject the payload and run none of its code.
+ _pickle_execution_marker.clear()
+ assert _deserialize_cache_value(payload) is None
+ assert _pickle_execution_marker == []