: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cdp): use oauth client credentials in zendesk destination (#125590)
Kyle Swank3696f2089ca9
diff --git a/products/cdp/backend/templates/zendesk/template_zendesk.py b/products/cdp/backend/templates/zendesk/template_zendesk.pyindex aabf1bdf07c5..d06ccc7a3d6d 100644--- a/products/cdp/backend/templates/zendesk/template_zendesk.py+++ b/products/cdp/backend/templates/zendesk/template_zendesk.py@@ -33,39 +33,62 @@ for (let key, value in inputs.attributes) {}}-fetch(f'https://{inputs.subdomain}.zendesk.com/api/v2/users/create_or_update', {+// Zendesk is retiring API tokens, so exchange the OAuth client for a short-lived access token on each run.+let tokenRes := fetch(f'https://{inputs.subdomain}.zendesk.com/oauth/tokens', {'headers': {- 'Authorization': f'Basic {base64Encode(f'{inputs.admin_email}/token:{inputs.token}')}',+ 'Content-Type': 'application/json'+ },+ 'body': {+ 'grant_type': 'client_credentials',+ 'client_id': inputs.client_id,+ 'client_secret': inputs.client_secret,+ 'scope': 'users:write',+ 'expires_in': 3600+ },+ 'method': 'POST'+});++if (tokenRes.status >= 400 or empty(tokenRes.body.access_token)) {+ throw Error(f'Could not get an access token from {inputs.subdomain}.zendesk.com (status {tokenRes.status}). Check the OAuth client identifier and secret, and that the client allows the client credentials grant.')+}++let res := fetch(f'https://{inputs.subdomain}.zendesk.com/api/v2/users/create_or_update', {+ 'headers': {+ 'Authorization': f'Bearer {tokenRes.body.access_token}','Content-Type': 'application/json'},'body': body,'method': 'POST'});++if (res.status >= 400) {+ throw Error(f'Error from {inputs.subdomain}.zendesk.com (status {res.status}): {res.body}')+}""".strip(),inputs_schema=[{"key": "subdomain","type": "string","label": "Zendesk subdomain",- "description": "Generally, Your Zendesk URL has two parts: a subdomain name you chose when you set up your account, followed by zendesk.com (for example: mycompany.zendesk.com). Please share the subdomain name with us so we can set up your account.",+ "description": "The first part of your Zendesk URL. For mycompany.zendesk.com, enter mycompany.","secret": False,"required": True,},{- "key": "admin_email",+ "key": "client_id","type": "string",- "label": "API user email",- "secret": True,+ "label": "OAuth client identifier",+ "description": "In Zendesk Admin Center, go to Apps and integrations > APIs > OAuth clients. Create a confidential client that allows the client credentials grant and the users:write scope, then copy its identifier here. Changes are attributed to the admin who created the client.",+ "secret": False,"required": True,- "description": "Enter the email of an admin in Zendesk. Activity using the API key will be attributed to this user.",},{- "key": "token",+ "key": "client_secret","type": "string",- "label": "API token",+ "label": "OAuth client secret",+ "description": "The secret Zendesk shows when you create the OAuth client.","secret": True,"required": True,- "hint": "Enter your Zendesk API Token",},{"key": "email",diff --git a/products/cdp/backend/templates/zendesk/test_template_zendesk.py b/products/cdp/backend/templates/zendesk/test_template_zendesk.pyindex 8d9e58ae6789..e5b2de8945a0 100644--- a/products/cdp/backend/templates/zendesk/test_template_zendesk.py+++ b/products/cdp/backend/templates/zendesk/test_template_zendesk.py@@ -1,12 +1,16 @@+import pytest+from products.cdp.backend.templates.helpers import BaseHogFunctionTemplateTestfrom products.cdp.backend.templates.zendesk.template_zendesk import template as template_zendesk+from common.hogvm.python.utils import UncaughtHogVMException+def create_inputs(**kwargs):inputs = {"subdomain": "zendeskhelp",- "admin_email": "[email protected]",- "token": "Q0UlvCexisMu6Je5MHG72ev16Tz68Tw8PRRpb5SX",+ "client_id": "posthog_destination",+ "client_secret": "fake-client-secret","email": "[email protected]","name": "Max","attributes": {"phone": "0123456789", "plan": "starship-enterprise"},@@ -19,6 +23,14 @@ def create_inputs(**kwargs):class TestTemplateZendesk(BaseHogFunctionTemplateTest):template = template_zendesk+ def setUp(self):+ super().setUp()+ self.mock_fetch_response = lambda url, *args: ( # type: ignore+ {"status": 200, "body": {"access_token": "fake-access-token", "token_type": "bearer"}}+ if url.endswith("/oauth/tokens")+ else {"status": 200, "body": {"user": {"id": 1}}}+ )+def test_function_works(self):self.run_function(inputs=create_inputs(),@@ -27,24 +39,49 @@ class TestTemplateZendesk(BaseHogFunctionTemplateTest):},)- assert self.get_mock_fetch_calls()[0] == (- "https://zendeskhelp.zendesk.com/api/v2/users/create_or_update",- {- "method": "POST",- "headers": {- "Authorization": "Basic YWRtaW5AemVuZGVzay5jb20vdG9rZW46UTBVbHZDZXhpc011NkplNU1IRzcyZXYxNlR6NjhUdzhQUlJwYjVTWA==",- "Content-Type": "application/json",+ assert self.get_mock_fetch_calls() == [+ (+ "https://zendeskhelp.zendesk.com/oauth/tokens",+ {+ "method": "POST",+ "headers": {"Content-Type": "application/json"},+ "body": {+ "grant_type": "client_credentials",+ "client_id": "posthog_destination",+ "client_secret": "fake-client-secret",+ "scope": "users:write",+ "expires_in": 3600,+ },},- "body": {- "user": {- "email": "[email protected]",- "name": "Max",- "user_fields": {"phone": "0123456789", "plan": "starship-enterprise"},- "skip_verify_email": True,- }+ ),+ (+ "https://zendeskhelp.zendesk.com/api/v2/users/create_or_update",+ {+ "method": "POST",+ "headers": {+ "Authorization": "Bearer fake-access-token",+ "Content-Type": "application/json",+ },+ "body": {+ "user": {+ "email": "[email protected]",+ "name": "Max",+ "user_fields": {"phone": "0123456789", "plan": "starship-enterprise"},+ "skip_verify_email": True,+ }+ },},- },- )+ ),+ ]++ def test_function_stops_when_token_request_fails(self):+ self.mock_fetch_response = lambda *args: {"status": 401, "body": {"error": "invalid_client"}} # type: ignore++ with pytest.raises(UncaughtHogVMException) as e:+ self.run_function(inputs=create_inputs())++ assert e.value.message.startswith("Could not get an access token from zendeskhelp.zendesk.com (status 401)")+ assert len(self.get_mock_fetch_calls()) == 1def test_function_requires_identifier(self):self.run_function(inputs=create_inputs(name=""))