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(cdp): keep plaintext destination secrets out of the site apps bundle (#109384)

Daniel Marchuk82537f9bdf7f
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.md
index e45d8615c611..bbcd6cd5a8d1 100644
--- a/docs/internal/activity-logging.md
+++ b/docs/internal/activity-logging.md
@@ -135,6 +135,10 @@ The activity log API, the advanced activity logs API and its exports, the notifi
The `system.activity_logs` SQL table and the search filter read the stored `detail`, so old rows need rewriting to stay masked there.
These protections do not revoke exposed credentials.
+New browser configuration builds leave out a site function while one of its secret values would reach the browser.
+That covers a secret still stored in plaintext inputs, and a mapping secret or its default.
+Regenerate existing browser configurations after deployment to replace cached JavaScript.
+
## Writes the signal cannot see
The mixin hooks `save()` and `delete()`.
diff --git a/posthog/cdp/site_functions.py b/posthog/cdp/site_functions.py
index 77f179fde531..03cf975027d9 100644
--- a/posthog/cdp/site_functions.py
+++ b/posthog/cdp/site_functions.py
@@ -1,4 +1,5 @@
import json
+from typing import Any
from posthog.hogql.compiler.javascript import JavaScriptCompiler
@@ -9,6 +10,38 @@ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cdp.backend.models.plugin import transpile
+def exposed_secret_input_keys(hog_function: HogFunction) -> set[str]:
+ """Secret input keys whose value the transpiled JavaScript would carry into a browser.
+
+ The transpiler reads the plaintext `inputs` columns, so a secret is only exposed while its value
+ is still stored in one. `move_secret_inputs` moves a top-level secret into `encrypted_inputs` on
+ every save and never touches a mapping, which is why a mapping secret and a row saved before
+ that split are the ones that reach the browser.
+ """
+ exposed: set[str] = set()
+ configs: list[tuple[Any, bool]] = [
+ ({"inputs_schema": hog_function.inputs_schema, "inputs": hog_function.inputs}, False),
+ # The transpiler skips disabled mappings, so their values never reach the browser.
+ *((mapping, True) for mapping in hog_function.mappings or [] if not (mapping or {}).get("disabled")),
+ ]
+ for config, is_mapping in configs:
+ if not isinstance(config, dict):
+ continue
+ inputs = config.get("inputs") or {}
+ for schema in config.get("inputs_schema") or []:
+ if not isinstance(schema, dict) or not schema.get("secret") or "key" not in schema:
+ continue
+ value = inputs.get(schema["key"])
+ if isinstance(value, dict) and value.get("value") is not None:
+ exposed.add(str(schema["key"]))
+ # The transpiler falls back to a mapping input's own schema default when the input is missing
+ # or null. It builds the top-level inputs from stored values alone, so a top-level default never
+ # reaches the browser.
+ elif is_mapping and inputs.get(schema["key"]) is None and schema.get("default") is not None:
+ exposed.add(str(schema["key"]))
+ return exposed
+
+
def get_transpiled_function(hog_function: HogFunction) -> str:
response = ""
@@ -86,12 +119,13 @@ def get_transpiled_function(hog_function: HogFunction) -> str:
mapping_code += "(function (){" # IIFE so that the code below has different globals than the filters above
mapping_code += "const newInputs = structuredClone(inputs); const __getGlobal = (key) => key === 'inputs' ? newInputs : globals[key];\n"
- for schema in mapping_inputs_schema:
- if "key" in schema and schema["key"] not in mapping_inputs:
- mapping_inputs[schema["key"]] = {"value": schema.get("default", None)}
+ mapping_defaults = {schema["key"]: schema.get("default") for schema in mapping_inputs_schema if "key" in schema}
+ for key, default in mapping_defaults.items():
+ if key not in mapping_inputs:
+ mapping_inputs[key] = {"value": default}
for key, input in mapping_inputs.items():
- value = input.get("value") if input is not None else schema.get("default", None)
+ value = input.get("value") if input is not None else mapping_defaults.get(key)
key_string = json.dumps(str(key) or "<empty>")
if (isinstance(value, str) and "{" in value) or isinstance(value, dict) or isinstance(value, list):
base_code = transpile_template_code(value, compiler)
diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.py
index e63889bea66e..0e684b8d735a 100644
--- a/posthog/models/remote_config.py
+++ b/posthog/models/remote_config.py
@@ -357,7 +357,7 @@ class RemoteConfig(UUIDTModel):
def _build_site_apps_js(self):
# NOTE: This is the web focused config for the frontend that includes site apps
- from posthog.cdp.site_functions import get_transpiled_function
+ from posthog.cdp.site_functions import exposed_secret_input_keys, get_transpiled_function
from posthog.plugins.site import get_site_apps_for_team, get_site_config_from_schema
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
@@ -382,10 +382,12 @@ class RemoteConfig(UUIDTModel):
deleted=False,
type__in=("site_destination", "site_app"),
)
- .only("id", "team_id", "inputs", "hog", "filters", "mappings")
+ .only("id", "team_id", "inputs", "inputs_schema", "hog", "filters", "mappings")
)
for site_function in site_functions:
+ if exposed_secret_input_keys(site_function):
+ continue
try:
source = get_transpiled_function(site_function)
# NOTE: It is an object as we can later add other properties such as a consent ID
diff --git a/posthog/models/test/test_remote_config.py b/posthog/models/test/test_remote_config.py
index 41b159dbdc14..a1c0b480442c 100644
--- a/posthog/models/test/test_remote_config.py
+++ b/posthog/models/test/test_remote_config.py
@@ -11,15 +11,18 @@ from django.utils import timezone
from parameterized import parameterized
+from posthog.cdp.templates.helpers import mock_transpile
from posthog.models.integration import Integration
from posthog.models.project import Project
from posthog.models.remote_config import REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET, RemoteConfig
from products.actions.backend.models.action import Action
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.surveys.backend.models import Survey
CONFIG_REFRESH_QUERY_COUNT = 6
+SITE_HOG = "export function onEvent({ inputs }) { console.log(inputs) }"
@pytest.mark.usefixtures("unittest_snapshot")
@@ -403,6 +406,112 @@ class TestRemoteConfig(_RemoteConfigBase):
assert result == []
+ @parameterized.expand([("no_default", {}), ("top_level_default", {"default": "abc"})])
+ def test_site_functions_keep_publishing_when_the_secret_is_encrypted(
+ self, _name: str, default: dict[str, str]
+ ) -> None:
+ # `move_secret_inputs` leaves the value in `encrypted_inputs`, which the transpiler never
+ # reads, so the function has to stay published.
+ function = HogFunction.objects.create(
+ team=self.team,
+ type="site_destination",
+ enabled=True,
+ hog=SITE_HOG,
+ inputs_schema=[{"key": "token", "type": "string", "secret": True, **default}],
+ inputs={"token": {"value": "example-private-browser-value"}},
+ )
+ assert (function.inputs or {}) == {}
+ assert (function.encrypted_inputs or {})["token"]["value"] == "example-private-browser-value"
+
+ with patch("posthog.cdp.site_functions.transpile", side_effect=mock_transpile):
+ result = "".join(self.remote_config._build_site_apps_js())
+
+ assert str(function.id) in result
+ assert "example-private-browser-value" not in result
+
+ @parameterized.expand(
+ [
+ ("mapping", True, {"inputs": {"token": {"value": "example-private-browser-value"}}}),
+ ("mapping_default", True, {"inputs": {}, "default": "example-private-browser-value"}),
+ ("mapping_null_input", True, {"inputs": {"token": None}, "default": "example-private-browser-value"}),
+ ("legacy_plaintext_inputs", False, {"inputs": {"token": {"value": "example-private-browser-value"}}}),
+ ]
+ )
+ def test_site_functions_are_not_published_while_a_secret_sits_in_plaintext(
+ self, _name: str, in_mapping: bool, stored: dict
+ ) -> None:
+ schema = {"key": "token", "type": "string", "secret": True}
+ if "default" in stored:
+ schema["default"] = stored["default"]
+ config = {"inputs_schema": [schema], "inputs": stored["inputs"]}
+ unsafe = HogFunction.objects.create(
+ team=self.team,
+ type="site_destination",
+ enabled=True,
+ hog=SITE_HOG,
+ **({"mappings": [config]} if in_mapping else config),
+ )
+ if not in_mapping:
+ # A row saved before secret inputs were encrypted keeps the value in `inputs`, which
+ # `save()` would otherwise move out of the way.
+ HogFunction.objects.filter(id=unsafe.id).update(inputs=config["inputs"], encrypted_inputs=None)
+ unsafe.refresh_from_db()
+ safe = HogFunction.objects.create(team=self.team, type="site_destination", enabled=True, hog=SITE_HOG)
+
+ with patch("posthog.cdp.site_functions.transpile", side_effect=mock_transpile):
+ result = "".join(self.remote_config._build_site_apps_js())
+
+ assert str(unsafe.id) not in result
+ assert str(safe.id) in result
+ assert "example-private-browser-value" not in result
+
+ @parameterized.expand(
+ [
+ (
+ "disabled_mapping",
+ {
+ "disabled": True,
+ "inputs_schema": [{"key": "token", "type": "string", "secret": True}],
+ "inputs": {"token": {"value": "example-private-browser-value"}},
+ },
+ ),
+ (
+ "null_input_with_a_non_secret_last_schema",
+ {
+ "inputs_schema": [
+ {"key": "token", "type": "string", "secret": True, "default": "example-private-browser-value"},
+ {"key": "label", "type": "string", "default": "shown"},
+ ],
+ "inputs": {"token": {"value": None}, "label": None},
+ },
+ ),
+ (
+ "null_input_after_a_mapping_with_a_secret_default",
+ {
+ "inputs_schema": [
+ {"key": "token", "type": "string", "secret": True, "default": "example-private-browser-value"}
+ ],
+ "inputs": {"token": {"value": None}},
+ },
+ {"inputs_schema": [], "inputs": {"label": None}},
+ ),
+ ]
+ )
+ def test_site_functions_publish_when_no_secret_reaches_the_browser(self, _name: str, *mappings: dict) -> None:
+ function = HogFunction.objects.create(
+ team=self.team,
+ type="site_destination",
+ enabled=True,
+ hog=SITE_HOG,
+ mappings=list(mappings),
+ )
+
+ with patch("posthog.cdp.site_functions.transpile", side_effect=mock_transpile):
+ result = "".join(self.remote_config._build_site_apps_js())
+
+ assert str(function.id) in result
+ assert "example-private-browser-value" not in result
+
class TestRemoteConfigSurveys(_RemoteConfigBase):
# Largely copied from TestSurveysAPIList