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): block reserved async functions in user-authored hog (#89177)

Daniel Marchuk5de6dc6a6e06
diff --git a/posthog/cdp/test/test_validation.py b/posthog/cdp/test/test_validation.py
index 192e7a5c67d1..94f9aff635df 100644
--- a/posthog/cdp/test/test_validation.py
+++ b/posthog/cdp/test/test_validation.py
@@ -17,6 +17,7 @@ from posthog.cdp.validation import (
RecordAliasRewriter,
compile_hog,
generate_template_bytecode,
+ reserved_functions_used,
)
from posthog.models.integration import Integration
@@ -1219,3 +1220,25 @@ class TestTaskInputTypeValidation(SimpleTestCase):
else:
with pytest.raises(ValidationError):
validate_inputs(schema, inputs)
+
+
+class TestReservedFunctionsUsed(SimpleTestCase):
+ # The worker's async function registry is global, so the save-time check is the only thing
+ # that stops user-authored hog from reaching a handler only PostHog's machinery should call.
+ @parameterized.expand(
+ [
+ ("direct_call", "let res := sendEmail(inputs.email)", {"sendEmail"}),
+ ("bare_reference", "let f := sendEmail", {"sendEmail"}),
+ ("inside_block", "if (true) { sendEmail(inputs.email) }", {"sendEmail"}),
+ ("inside_lambda", "let f := (to) -> sendEmail(to)", {"sendEmail"}),
+ ("as_argument", "print(sendEmail)", {"sendEmail"}),
+ ("two_names", "sendEmail(1)\nsendPushNotification(2)", {"sendEmail", "sendPushNotification"}),
+ ("supported_function", "let res := fetch('https://example.com', {})", set()),
+ ("similar_name", "let res := sendEmails(inputs.email)", set()),
+ ("property_of_same_name", "return inputs.sendEmail", set()),
+ ("string_only", "return f'sendEmail is not called here'", set()),
+ ("does_not_parse", "let res := sendEmail(", set()),
+ ]
+ )
+ def test_reserved_functions_used(self, _name: str, hog: str, expected: set[str]) -> None:
+ assert reserved_functions_used(hog) == expected
diff --git a/posthog/cdp/validation.py b/posthog/cdp/validation.py
index 16d9a289b822..73369e5eac7a 100644
--- a/posthog/cdp/validation.py
+++ b/posthog/cdp/validation.py
@@ -201,6 +201,29 @@ register_supported_function("postHogUpdateAccount")
register_supported_function("postHogSetAccountProperties")
+# Async functions that put the invocation on a queue the running consumer cannot serve.
+#
+# The worker's async function registry is global and is not scoped by function type, so any hog
+# program that names one of these reaches the real handler. These two handlers set
+# `queueParameters` to a bespoke type ('email', 'sendPushNotification') instead of the ordinary
+# 'fetch'. Only the messaging consumers process those queues. When a plain destination stages one,
+# the cyclotron worker produces to a Kafka topic its cluster does not have. The produce error
+# terminates the worker process, and the partition it owned stops draining.
+#
+# Membership is decided by that failure mode, NOT by "the worker registers it". Most registered
+# async functions stage an ordinary 'fetch' (postHogCreateAccount, postHogCreateTask and the
+# postHogGet*/postHogUpdate* family), which is the same mechanism CORE_SUPPORTED_FUNCTIONS already
+# gives user code, so they are safe here and are deliberately absent. produceToWarehouseWebhooks is
+# also absent: it only appends to an in-memory list, and its callers are all
+# `warehouse_source_webhook` functions, which HogFunctionSerializer.validate_type refuses anyway.
+#
+# Before adding a name, check what its handler in nodejs/src/cdp/async-functions/ stages.
+RESERVED_ASYNC_FUNCTIONS = {
+ "sendEmail",
+ "sendPushNotification",
+}
+
+
# Globals that the realtime transformer actually populates at runtime.
# Keep in sync with HogTransformerService.createInvocationGlobals
# (nodejs/src/cdp/hog-transformations/hog-transformer.service.ts).
@@ -343,6 +366,42 @@ class HyphenatedPropertyDetector(TraversingVisitor):
return True
+class ReservedFunctionDetector(TraversingVisitor):
+ names: set[str]
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.names = set()
+
+ def visit_call(self, node: ast.Call) -> None:
+ super().visit_call(node)
+ if node.name in RESERVED_ASYNC_FUNCTIONS:
+ self.names.add(node.name)
+
+ def visit_field(self, node: ast.Field) -> None:
+ # A bare reference is caught as well as a direct call. `let f := sendEmail` followed by
+ # `f()` compiles to the same global dispatch, so the name alone is refused.
+ super().visit_field(node)
+ if len(node.chain) == 1 and str(node.chain[0]) in RESERVED_ASYNC_FUNCTIONS:
+ self.names.add(str(node.chain[0]))
+
+
+def reserved_functions_used(hog: str) -> set[str]:
+ """The reserved async functions that the given hog source names.
+
+ Source that does not parse gives an empty set. compile_hog reports the parse error with a
+ better message, so this must not raise before it runs.
+ """
+ try:
+ program = parse_program(hog)
+ except Exception:
+ return set()
+
+ detector = ReservedFunctionDetector()
+ detector.visit(program)
+ return detector.names
+
+
class RecordAliasRewriter(TraversingVisitor):
"""Rewrite `{record.x}` template references to `{event.properties.x}` for data-warehouse-table
sources. The synced row is delivered under `event.properties` at runtime, so `record` is a
diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.py
index 20efcc870bb4..db59eacf7684 100644
--- a/products/cdp/backend/api/hog_function.py
+++ b/products/cdp/backend/api/hog_function.py
@@ -38,6 +38,7 @@ from posthog.cdp.validation import (
compile_hog,
generate_template_bytecode,
masked_secret_input_keys,
+ reserved_functions_used,
)
from posthog.event_usage import AGENT_EVENT_SOURCES, get_event_source
from posthog.exceptions_capture import capture_exception
@@ -463,6 +464,32 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):
}
)
+ def _validate_no_reserved_functions(self, attrs: dict) -> None:
+ # The worker's async function registry is global, so `sendEmail` and its peers run from any
+ # function that names them, and a call from user-authored code kills the worker process.
+ # These functions are reached legitimately through a hidden template, so a template's own
+ # calls stay allowed. That keeps a function built from one editable, disableable and
+ # deletable, which is how such a function gets cleaned up.
+ used = reserved_functions_used(attrs["hog"])
+ if not used:
+ return
+
+ template_id = attrs.get("template_id") or (
+ self.instance.template_id if isinstance(self.instance, HogFunction) else None
+ )
+ template = HogFunctionTemplate.get_template(template_id) if template_id else None
+ allowed = reserved_functions_used(template.code) if template and template.code else set()
+
+ unexpected = used - allowed
+ if unexpected:
+ names = ", ".join(sorted(unexpected))
+ raise serializers.ValidationError(
+ {
+ "hog": f"Reserved for PostHog's own use and not callable from a function's code: {names}. "
+ "Use the matching workflow step or destination template instead."
+ }
+ )
+
# NOTE: All pre-validation should be done here such as loading the template info etc.
def to_internal_value(self, data):
# Copy before filling in defaults below: `data` is `request.data` itself, and injecting
@@ -669,6 +696,7 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):
raise serializers.ValidationError({"hog": "Error in TypeScript code"})
attrs["bytecode"] = None
else:
+ self._validate_no_reserved_functions(attrs)
attrs["bytecode"] = compile_hog(attrs["hog"], hog_type)
attrs["transpiled"] = None
diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.py
index 8b941b4a8aab..689a08fd8d77 100644
--- a/products/cdp/backend/api/test/test_hog_function.py
+++ b/products/cdp/backend/api/test/test_hog_function.py
@@ -377,6 +377,125 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
assert response.status_code == expected, response.json()
+ def _create_email_template(self) -> None:
+ # Mirrors the real `template-email`: a hidden template whose code calls the reserved
+ # `sendEmail` async function.
+ HogFunctionTemplate.objects.create(
+ template_id="template-email-test",
+ sha="1.0.0",
+ name="Email",
+ description="Internal building block",
+ code="let res := sendEmail(inputs.email)\nif (not res.success) { throw Error('failed') }",
+ code_language="hog",
+ inputs_schema=[],
+ type="destination",
+ status="hidden",
+ category=["Other"],
+ free=True,
+ )
+
+ @parameterized.expand(
+ [
+ # These two handlers stage a queue only the messaging consumers serve, so a call from a
+ # plain destination makes the worker produce to a topic its cluster lacks and the
+ # process dies. Both a direct call and a bare reference are refused, because the bare
+ # name compiles to the same global dispatch once it is called.
+ ("send_email_call", "let res := sendEmail(inputs.email)\nreturn res"),
+ ("send_email_reference", "let f := sendEmail\nreturn f(inputs.email)"),
+ ("send_email_nested", "if (true) { for (let i := 0; i < 1; i := i + 1) { sendEmail(inputs.email) } }"),
+ ("send_push_notification", "return sendPushNotification(inputs.message)"),
+ ]
+ )
+ def test_create_calling_reserved_function_is_blocked(self, _name: str, hog: str) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_functions/",
+ data={"type": "destination", "name": "Sneaky", "hog": hog, "inputs": {}},
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "hog"
+ assert "Reserved for PostHog's own use" in response.json()["detail"]
+ assert not HogFunction.objects.filter(team=self.team, name="Sneaky").exists()
+
+ @parameterized.expand(
+ [
+ # Only the two messaging functions are refused. Async functions that stage an ordinary
+ # 'fetch' carry no such risk, so the reserved set must not creep out to swallow the
+ # customer analytics family that destinations are meant to call.
+ ("fetch", "let res := fetch('https://example.com', {})\nreturn res"),
+ ("post_hog_update_account", "return postHogUpdateAccount({'external_id': '1', 'updates': {}})"),
+ ]
+ )
+ def test_create_with_supported_function_is_allowed(self, _name: str, hog: str) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_functions/",
+ data={"type": "destination", "name": f"Fine {_name}", "hog": hog, "inputs": {}},
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+
+ @parameterized.expand(
+ [
+ # A function built from the template that legitimately calls the reserved function keeps
+ # the template's own calls, so it can still be disabled and deleted. Adding a call the
+ # template does not make is refused even on that function.
+ ("resave_template_code_allowed", "let res := sendEmail(inputs.email)", status.HTTP_200_OK),
+ (
+ "added_reserved_call_blocked",
+ "let res := sendEmail(inputs.email)\nsendPushNotification(inputs.message)",
+ status.HTTP_400_BAD_REQUEST,
+ ),
+ ]
+ )
+ def test_function_from_template_may_only_keep_the_templates_reserved_calls(
+ self, _name: str, hog: str, expected: int
+ ) -> None:
+ self._create_email_template()
+ fn = HogFunction.objects.create(
+ team=self.team,
+ name="Workflow email step",
+ type="destination",
+ template_id="template-email-test",
+ enabled=False,
+ inputs_schema=[],
+ inputs={},
+ hog="let res := sendEmail(inputs.email)",
+ )
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_functions/{fn.id}/",
+ data={"hog": hog},
+ )
+ assert response.status_code == expected, response.json()
+
+ @parameterized.expand(
+ [
+ # The template carve-out keeps the reserved call a hidden template makes, so a function
+ # built from one stays disableable and deletable. It must never yield a function that
+ # RUNS, because only a running one can wedge a worker. Two independent rules close that:
+ # the hidden-template rule refuses any save leaving it enabled, and an existing
+ # function's type is immutable, so it cannot be re-typed into a plain destination while
+ # keeping the call.
+ ("enable_blocked", {"enabled": True}, "enabled"),
+ ("retype_blocked", {"type": "transformation"}, "type"),
+ ]
+ )
+ def test_template_carve_out_cannot_yield_a_runnable_function(self, _name: str, patch: dict, attr: str) -> None:
+ self._create_email_template()
+ fn = HogFunction.objects.create(
+ team=self.team,
+ name="Workflow email step",
+ type="destination",
+ template_id="template-email-test",
+ enabled=False,
+ inputs_schema=[],
+ inputs={},
+ hog="let res := sendEmail(inputs.email)",
+ )
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_functions/{fn.id}/",
+ data={**patch, "hog": "let res := sendEmail(inputs.email)"},
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == attr
+
@parameterized.expand(
[
# Filters that no longer compile (e.g. the team's test account filters gained a static