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): reject Salesforce object paths with empty values (#81705)

Harley Alexander3f7cd529716c
diff --git a/frontend/src/mocks/fixtures/_hogFunctionTemplatesDestinations.json b/frontend/src/mocks/fixtures/_hogFunctionTemplatesDestinations.json
index 55b551c142f8..142f4abcffea 100644
--- a/frontend/src/mocks/fixtures/_hogFunctionTemplatesDestinations.json
+++ b/frontend/src/mocks/fixtures/_hogFunctionTemplatesDestinations.json
@@ -33407,7 +33407,7 @@
"type": "destination",
"id": "template-salesforce-create",
"name": "Salesforce",
- "hog": "let getPayload := () -> {\n let properties := {}\n if (inputs.include_all_event_properties) {\n if (not empty(event.elements_chain)) {\n properties['$elements_chain'] := event.elements_chain\n }\n for (let key, value in event.properties) {\n properties[key] := value\n }\n }\n if (inputs.include_all_person_properties) {\n for (let key, value in person.properties) {\n properties[key] := value\n }\n }\n for (let key, value in inputs.properties) {\n properties[key] := value\n }\n return properties\n}\n\nlet res := fetch(f'{inputs.oauth.instance_url}/services/data/v61.0/sobjects/{inputs.path}', {\n 'body': getPayload(),\n 'method': 'POST',\n 'headers': {\n 'Authorization': f'Bearer {inputs.oauth.access_token}',\n 'Content-Type': 'application/json'\n }\n});\n\nif (res.status >= 400) {\n throw Error(f'Salesforce request failed with status {res.status}: {res.body}');\n} else {\n print(res.status, res.body)\n}",
+ "hog": "let getPayload := () -> {\n let properties := {}\n if (inputs.include_all_event_properties) {\n if (not empty(event.elements_chain)) {\n properties['$elements_chain'] := event.elements_chain\n }\n for (let key, value in event.properties) {\n properties[key] := value\n }\n }\n if (inputs.include_all_person_properties) {\n for (let key, value in person.properties) {\n properties[key] := value\n }\n }\n for (let key, value in inputs.properties) {\n properties[key] := value\n }\n return properties\n}\n\nlet path := trim(inputs.path)\n\n// Values templated into the path resolve to an empty string when the property is unset, which\n// silently produces a URL Salesforce rejects. Fail here so the message names the real cause.\nfor (let segment in splitByString('/', path)) {\n if (empty(trim(segment))) {\n throw Error(f'Salesforce object path \\'{path}\\' is missing a value. A property mapped into the path was empty when this ran. Check that it is set before this step.')\n }\n}\n\nlet res := fetch(f'{inputs.oauth.instance_url}/services/data/v61.0/sobjects/{path}', {\n 'body': getPayload(),\n 'method': 'POST',\n 'headers': {\n 'Authorization': f'Bearer {inputs.oauth.access_token}',\n 'Content-Type': 'application/json'\n }\n});\n\nif (res.status >= 400) {\n throw Error(f'Salesforce request to \\'{path}\\' failed with status {res.status}: {res.body}');\n}\n\nprint(res.status, res.body)\nreturn res.body",
"inputs_schema": [
{
"key": "oauth",
@@ -33483,7 +33483,7 @@
"type": "destination",
"id": "template-salesforce-update",
"name": "Salesforce",
- "hog": "let getPayload := () -> {\n let properties := {}\n if (inputs.include_all_event_properties) {\n for (let key, value in event.properties) {\n properties[key] := value\n }\n }\n if (inputs.include_all_person_properties) {\n for (let key, value in person.properties) {\n properties[key] := value\n }\n }\n for (let key, value in inputs.properties) {\n properties[key] := value\n }\n return properties\n}\n\nlet res := fetch(f'{inputs.oauth.instance_url}/services/data/v61.0/sobjects/{inputs.path}', {\n 'body': getPayload(),\n 'method': 'PATCH',\n 'headers': {\n 'Authorization': f'Bearer {inputs.oauth.access_token}',\n 'Content-Type': 'application/json'\n }\n});\n\nif (res.status >= 400) {\n throw Error(f'Salesforce request failed with status {res.status}: {res.body}');\n} else {\n print(res.status, res.body)\n}",
+ "hog": "let getPayload := () -> {\n let properties := {}\n if (inputs.include_all_event_properties) {\n for (let key, value in event.properties) {\n properties[key] := value\n }\n }\n if (inputs.include_all_person_properties) {\n for (let key, value in person.properties) {\n properties[key] := value\n }\n }\n for (let key, value in inputs.properties) {\n properties[key] := value\n }\n return properties\n}\n\nlet path := trim(inputs.path)\nlet segments := splitByString('/', path)\n\n// Values templated into the path resolve to an empty string when the property is unset. That\n// truncates the URL to the object collection, which only accepts GET, HEAD, and POST, so\n// Salesforce answers the PATCH with a 405 that says nothing about the missing value.\nfor (let segment in segments) {\n if (empty(trim(segment))) {\n throw Error(f'Salesforce object path \\'{path}\\' is missing a value. A property mapped into the path was empty when this ran. Check that it is set before this step.')\n }\n}\n\nif (length(segments) < 2) {\n throw Error(f'Salesforce object path \\'{path}\\' has no record identifier. Use \\'Object/RecordId\\' to update by record ID, or \\'Object/ExternalIdField/Value\\' to update by external ID.')\n}\n\nlet res := fetch(f'{inputs.oauth.instance_url}/services/data/v61.0/sobjects/{path}', {\n 'body': getPayload(),\n 'method': 'PATCH',\n 'headers': {\n 'Authorization': f'Bearer {inputs.oauth.access_token}',\n 'Content-Type': 'application/json'\n }\n});\n\nif (res.status >= 400) {\n throw Error(f'Salesforce request to \\'{path}\\' failed with status {res.status}: {res.body}');\n}\n\nprint(res.status, res.body)\nreturn res.body",
"inputs_schema": [
{
"key": "oauth",
@@ -33499,9 +33499,9 @@
"type": "string",
"label": "Object path",
"secret": false,
- "default": "Leads/Email/{person.properties.email}",
+ "default": "Lead/Email/{person.properties.email}",
"required": true,
- "description": "The path to the object you want to create or update. This can be a standard object like 'Contact' for creating records or `Lead/Email/{person.properties.email}` for updating a lead by email. See https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_upsert.htm for more information."
+ "description": "The object and record to update. Use `Lead/{recordId}` to update by record ID, or `Lead/Email/{person.properties.email}` to update by an external ID field, which must be flagged as an External ID in Salesforce. A bare object name like `Lead` is not valid for updates. Updating by external ID creates the record when nothing matches. See https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_upsert.htm for more information."
},
{
"key": "include_all_event_properties",
diff --git a/posthog/cdp/templates/salesforce/template_salesforce.py b/posthog/cdp/templates/salesforce/template_salesforce.py
index e534a1dbc5c2..00f962f2a93b 100644
--- a/posthog/cdp/templates/salesforce/template_salesforce.py
+++ b/posthog/cdp/templates/salesforce/template_salesforce.py
@@ -53,7 +53,17 @@ let getPayload := () -> {
return properties
}
-let res := fetch(f'{inputs.oauth.instance_url}/services/data/v61.0/sobjects/{inputs.path}', {
+let path := trim(inputs.path)
+
+// Values templated into the path resolve to an empty string when the property is unset, which
+// silently produces a URL Salesforce rejects. Fail here so the message names the real cause.
+for (let segment in splitByString('/', path)) {
+ if (empty(trim(segment))) {
+ throw Error(f'Salesforce object path \\'{path}\\' is missing a value. A property mapped into the path was empty when this ran. Check that it is set before this step.')
+ }
+}
+
+let res := fetch(f'{inputs.oauth.instance_url}/services/data/v61.0/sobjects/{path}', {
'body': getPayload(),
'method': 'POST',
'headers': {
@@ -63,10 +73,11 @@ let res := fetch(f'{inputs.oauth.instance_url}/services/data/v61.0/sobjects/{inp
});
if (res.status >= 400) {
- throw Error(f'Salesforce request failed with status {res.status}: {res.body}');
-} else {
- print(res.status, res.body)
+ throw Error(f'Salesforce request to \\'{path}\\' failed with status {res.status}: {res.body}');
}
+
+print(res.status, res.body)
+return res.body
""".strip(),
inputs_schema=[
common_inputs["oauth"],
@@ -141,7 +152,23 @@ let getPayload := () -> {
return properties
}
-let res := fetch(f'{inputs.oauth.instance_url}/services/data/v61.0/sobjects/{inputs.path}', {
+let path := trim(inputs.path)
+let segments := splitByString('/', path)
+
+// Values templated into the path resolve to an empty string when the property is unset. That
+// truncates the URL to the object collection, which only accepts GET, HEAD, and POST, so
+// Salesforce answers the PATCH with a 405 that says nothing about the missing value.
+for (let segment in segments) {
+ if (empty(trim(segment))) {
+ throw Error(f'Salesforce object path \\'{path}\\' is missing a value. A property mapped into the path was empty when this ran. Check that it is set before this step.')
+ }
+}
+
+if (length(segments) < 2) {
+ throw Error(f'Salesforce object path \\'{path}\\' has no record identifier. Use \\'Object/RecordId\\' to update by record ID, or \\'Object/ExternalIdField/Value\\' to update by external ID.')
+}
+
+let res := fetch(f'{inputs.oauth.instance_url}/services/data/v61.0/sobjects/{path}', {
'body': getPayload(),
'method': 'PATCH',
'headers': {
@@ -151,10 +178,14 @@ let res := fetch(f'{inputs.oauth.instance_url}/services/data/v61.0/sobjects/{inp
});
if (res.status >= 400) {
- throw Error(f'Salesforce request failed with status {res.status}: {res.body}');
-} else {
- print(res.status, res.body)
+ throw Error(f'Salesforce request to \\'{path}\\' failed with status {res.status}: {res.body}');
}
+
+print(res.status, res.body)
+
+// Updating a record by ID answers with no body, so hand back a shape a workflow can read
+// either way. An upsert already returns success alongside the id it touched.
+return empty(res.body) ? {'success': true} : res.body
""".strip(),
inputs_schema=[
common_inputs["oauth"],
@@ -162,8 +193,8 @@ if (res.status >= 400) {
"key": "path",
"type": "string",
"label": "Object path",
- "description": "The path to the object you want to create or update. This can be a standard object like 'Contact' for creating records or `Lead/Email/{person.properties.email}` for updating a lead by email. See https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_upsert.htm for more information.",
- "default": "Leads/Email/{person.properties.email}",
+ "description": "The object and record to update. Use `Lead/{recordId}` to update by record ID, or `Lead/Email/{person.properties.email}` to update by an external ID field, which must be flagged as an External ID in Salesforce. A bare object name like `Lead` is not valid for updates. Updating by external ID creates the record when nothing matches. See https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_upsert.htm for more information.",
+ "default": "Lead/Email/{person.properties.email}",
"secret": False,
"required": True,
},
diff --git a/posthog/cdp/templates/salesforce/test_template_salesforce.py b/posthog/cdp/templates/salesforce/test_template_salesforce.py
index 2e98a9325a27..1189a85a7b92 100644
--- a/posthog/cdp/templates/salesforce/test_template_salesforce.py
+++ b/posthog/cdp/templates/salesforce/test_template_salesforce.py
@@ -1,5 +1,8 @@
+import pytest
from posthog.test.base import BaseTest
+from parameterized import parameterized
+
from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest
from posthog.cdp.templates.salesforce.template_salesforce import (
TemplatSalesforceMigrator,
@@ -9,6 +12,8 @@ from posthog.cdp.templates.salesforce.template_salesforce import (
from products.cdp.backend.models.plugin import PluginConfig
+from common.hogvm.python.utils import UncaughtHogVMException
+
class TestTemplateSalesforceCreate(BaseHogFunctionTemplateTest):
template = template_salesforce_create
@@ -63,6 +68,16 @@ class TestTemplateSalesforceCreate(BaseHogFunctionTemplateTest):
},
)
+ def test_rejects_path_with_empty_segment(self):
+ with pytest.raises(UncaughtHogVMException) as e:
+ self.run_function(self._inputs(path="Contact/Email/"))
+ assert "is missing a value" in str(e.value)
+ assert self.get_mock_fetch_calls() == []
+
+ def test_returns_response_body(self):
+ self.mock_fetch_response = lambda *args: {"status": 201, "body": {"id": "0031", "success": True}} # type: ignore
+ assert self.run_function(self._inputs()).result == {"id": "0031", "success": True}
+
class TestTemplateSalesforceUpdate(BaseHogFunctionTemplateTest):
template = template_salesforce_update
@@ -117,6 +132,34 @@ class TestTemplateSalesforceUpdate(BaseHogFunctionTemplateTest):
},
)
+ @parameterized.expand(
+ [
+ ("empty external id value", "Lead/Email/"),
+ ("trailing slash", "Lead/"),
+ ("empty path", ""),
+ ]
+ )
+ def test_rejects_path_with_empty_segment(self, _name: str, path: str):
+ with pytest.raises(UncaughtHogVMException) as e:
+ self.run_function(self._inputs(path=path))
+ assert "is missing a value" in str(e.value)
+ assert self.get_mock_fetch_calls() == []
+
+ def test_rejects_bare_object_name(self):
+ with pytest.raises(UncaughtHogVMException) as e:
+ self.run_function(self._inputs(path="Lead"))
+ assert "has no record identifier" in str(e.value)
+ assert self.get_mock_fetch_calls() == []
+
+ def test_returns_response_body(self):
+ self.mock_fetch_response = lambda *args: {"status": 201, "body": {"id": "00Q1", "created": True}} # type: ignore
+ assert self.run_function(self._inputs()).result == {"id": "00Q1", "created": True}
+
+ @parameterized.expand([("no content", 204, None), ("empty body", 200, {})])
+ def test_reports_success_when_salesforce_returns_no_body(self, _name: str, status: int, body: dict | None):
+ self.mock_fetch_response = lambda *args: {"status": status, "body": body} # type: ignore
+ assert self.run_function(self._inputs(path="Lead/00Q1")).result == {"success": True}
+
class TestTemplateMigration(BaseTest):
def get_plugin_config(self, config: dict):