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.

feat(messaging): let the transactional email scope make a template transactional (#129864)

Michael Reichenbacheb8ec951955e
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 415e60253ff9..b41c23e90194 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -355,7 +355,7 @@ export const API_SCOPES: APIScope[] = [
key: 'transactional_email',
objectName: 'Transactional email',
objectPlural: 'transactional emails',
- info: "Write sends transactional email from a template. Read gets a sent email's status and works only with a project secret API key. This scope can't change templates or workflows.",
+ info: "Write makes a template transactional and sends email from it. Read gets a sent email's status and works only with a project secret API key. This scope can't edit templates or workflows.",
},
{ key: 'field_note', objectName: 'Field note', objectPlural: 'field notes' },
{ key: 'uploaded_media', objectName: 'Uploaded media', objectPlural: 'uploaded media' },
diff --git a/products/messaging/backend/presentation/views/message_templates.py b/products/messaging/backend/presentation/views/message_templates.py
index 8ecad7f50dc3..8945dc955ccb 100644
--- a/products/messaging/backend/presentation/views/message_templates.py
+++ b/products/messaging/backend/presentation/views/message_templates.py
@@ -37,7 +37,11 @@ from posthog.event_usage import groups, report_user_action
from posthog.integrations import IntegrationManager, IntegrationNotFound
from posthog.models import ProjectSecretAPIKey, User
from posthog.models.tag import tagify
-from posthog.permissions import is_authenticated_via_project_secret_api_key, legacy_scope_object_used
+from posthog.permissions import (
+ is_authenticated_via_project_secret_api_key,
+ legacy_scope_object_used,
+ scopes_caller_lacks,
+)
from posthog.rate_limit import PersonalOrProjectSecretApiKeyRateThrottle, ProjectSecretApiKeyTeamRateThrottle
from products.cdp.backend.presentation.hog_functions import build_html_wrap_design, html_wrap_design_needs_refresh
@@ -961,8 +965,8 @@ class MessageTemplatesViewSet(
):
scope_object = "hog_flow"
permission_classes = [IsAuthenticated]
- # `design` and `make_transactional` are custom write actions; list them so programmatic callers (MCP/personal
- # API key) get hog_flow:write checked instead of being rejected as an action with no declared scope.
+ # `design` is a custom write action; list it so programmatic callers (MCP/personal API key) get hog_flow:write
+ # checked instead of being rejected as an action with no declared scope.
scope_object_write_actions = [
"create",
"update",
@@ -970,7 +974,6 @@ class MessageTemplatesViewSet(
"patch",
"destroy",
"design",
- "make_transactional",
]
authentication_classes = [ProjectSecretAPIKeyAuthentication]
# A project secret API key can only send. Template CRUD stays session/personal API key/OAuth only.
@@ -1203,11 +1206,13 @@ class MessageTemplatesViewSet(
"Make this template sendable over the transactional email API. This creates the workflow that sends it, "
"with its own metrics, run history and versions. This can't be undone: the template stays transactional. "
"Transactional sends ignore marketing opt-outs. Calling it again on a transactional template changes "
- "nothing."
+ "nothing. Needs the `transactional_email:write` scope, the same scope as sending. A key with "
+ "`hog_flow:write` also works, but that scope reaches the rest of Workflows too. Without `hog_flow:read`, "
+ "the response leaves out `content` and `draft_content`."
),
parameters=[TEMPLATE_ID_PARAMETER],
)
- @action(detail=True, methods=["POST"], pagination_class=None)
+ @action(detail=True, methods=["POST"], pagination_class=None, required_scopes=[TRANSACTIONAL_EMAIL_SEND_SCOPE])
def make_transactional(self, request: Any, *args: Any, **kwargs: Any) -> Response:
self._require_transactional_email_flag()
template = self.get_object()
@@ -1239,7 +1244,12 @@ class MessageTemplatesViewSet(
)
except Exception as e:
logger.warning("Failed to capture message template usage event", error=str(e))
- return Response(self._serialize(updated))
+ data = self._serialize(updated)
+ # A send-scoped key can't read templates, so converting one must not hand it their content.
+ if scopes_caller_lacks(request, ["hog_flow:read"]):
+ data.pop("content", None)
+ data.pop("draft_content", None)
+ return Response(data)
class MessagingSendViewSet(TransactionalEmailSendMixin, TeamAndOrgViewSetMixin, viewsets.ViewSet):
diff --git a/products/messaging/backend/tests/api/test_transactional_email.py b/products/messaging/backend/tests/api/test_transactional_email.py
index 08ba3ab86eae..ed7ed1f1c467 100644
--- a/products/messaging/backend/tests/api/test_transactional_email.py
+++ b/products/messaging/backend/tests/api/test_transactional_email.py
@@ -251,6 +251,13 @@ class TestTransactionalEmail(APIBaseTest):
["hog_flow:write"],
status.HTTP_403_FORBIDDEN,
),
+ (
+ "make_transactional_is_not_a_psak_action_with_send_scope",
+ "post",
+ "make_transactional/",
+ ["transactional_email:write"],
+ status.HTTP_403_FORBIDDEN,
+ ),
]
)
def test_project_secret_api_key_can_only_send(
@@ -297,6 +304,33 @@ class TestTransactionalEmail(APIBaseTest):
assert response.status_code == status.HTTP_202_ACCEPTED, response.json()
assert capture.call_args.kwargs["properties"]["authorized_by"] == expected_authorized_by
+ @parameterized.expand(
+ [
+ ("send_scope", ["transactional_email:write"], status.HTTP_200_OK, False),
+ ("workflow_scope", ["hog_flow:write"], status.HTTP_200_OK, True),
+ ("send_and_workflow_read_scopes", ["transactional_email:write", "hog_flow:read"], status.HTTP_200_OK, True),
+ ("status_scope", ["transactional_email:read"], status.HTTP_403_FORBIDDEN, False),
+ ]
+ )
+ def test_making_a_template_transactional_needs_the_send_scope(
+ self, _mock_post, _flag, _capture, _name, scopes, expected_status, returns_content
+ ):
+ template = self._template()
+ client = APIClient()
+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {self.create_personal_api_key_with_scopes(scopes)}")
+
+ response = client.post(
+ f"/api/projects/{self.team.id}/messaging_templates/{template.id}/make_transactional/", {}, format="json"
+ )
+
+ assert response.status_code == expected_status, response.json()
+ template.refresh_from_db()
+ assert (template.transactional_hog_flow_id is not None) == (expected_status == status.HTTP_200_OK)
+ if expected_status == status.HTTP_200_OK:
+ body = response.json()
+ assert body["transactional_hog_flow_id"] == str(template.transactional_hog_flow_id)
+ assert ("content" in body, "draft_content" in body) == (returns_content, returns_content)
+
def test_a_personal_api_key_with_the_send_scope_cannot_change_the_template(self, mock_post, _flag, _capture):
self._cdp_accepts(mock_post)
client = APIClient()
diff --git a/products/messaging/frontend/generated/api.ts b/products/messaging/frontend/generated/api.ts
index 3e3de191036a..0c0c5dff3d02 100644
--- a/products/messaging/frontend/generated/api.ts
+++ b/products/messaging/frontend/generated/api.ts
@@ -962,7 +962,7 @@ export const getMessagingTemplatesMakeTransactionalCreateUrl = (projectId: strin
}
/**
- * Make this template sendable over the transactional email API. This creates the workflow that sends it, with its own metrics, run history and versions. This can't be undone: the template stays transactional. Transactional sends ignore marketing opt-outs. Calling it again on a transactional template changes nothing.
+ * Make this template sendable over the transactional email API. This creates the workflow that sends it, with its own metrics, run history and versions. This can't be undone: the template stays transactional. Transactional sends ignore marketing opt-outs. Calling it again on a transactional template changes nothing. Needs the `transactional_email:write` scope, the same scope as sending. A key with `hog_flow:write` also works, but that scope reaches the rest of Workflows too. Without `hog_flow:read`, the response leaves out `content` and `draft_content`.
* @summary Make a template transactional
*/
export const messagingTemplatesMakeTransactionalCreate = async (
diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.ts
index 29fae7004f98..a487441b2840 100644
--- a/products/messaging/frontend/generated/api.zod.ts
+++ b/products/messaging/frontend/generated/api.zod.ts
@@ -1433,7 +1433,7 @@ export const MessagingTemplatesDesignPartialUpdateBody = /* @__PURE__ */ zod.obj
})
/**
- * Make this template sendable over the transactional email API. This creates the workflow that sends it, with its own metrics, run history and versions. This can't be undone: the template stays transactional. Transactional sends ignore marketing opt-outs. Calling it again on a transactional template changes nothing.
+ * Make this template sendable over the transactional email API. This creates the workflow that sends it, with its own metrics, run history and versions. This can't be undone: the template stays transactional. Transactional sends ignore marketing opt-outs. Calling it again on a transactional template changes nothing. Needs the `transactional_email:write` scope, the same scope as sending. A key with `hog_flow:write` also works, but that scope reaches the rest of Workflows too. Without `hog_flow:read`, the response leaves out `content` and `draft_content`.
* @summary Make a template transactional
*/
export const MessagingTemplatesMakeTransactionalCreateBody = /* @__PURE__ */ zod.object({
diff --git a/products/workflows/mcp/email_templates.yaml b/products/workflows/mcp/email_templates.yaml
index d85d9888986c..a57a09a5bed4 100644
--- a/products/workflows/mcp/email_templates.yaml
+++ b/products/workflows/mcp/email_templates.yaml
@@ -81,7 +81,7 @@ tools:
operation: messaging_templates_make_transactional_create
enabled: true
scopes:
- - hog_flow:write
+ - transactional_email:write
annotations:
readOnly: false
destructive: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index d8c523f278af..78631553bdd3 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -17241,7 +17241,7 @@
"feature": "workflows",
"summary": "Make email template transactional (execute)",
"title": "Make email template transactional (execute)",
- "required_scopes": ["hog_flow:write"],
+ "required_scopes": ["transactional_email:write"],
"api_operations": ["POST /api/projects/{project_id}/messaging_templates/{id}/make_transactional/"],
"annotations": {
"destructiveHint": true,
@@ -17257,7 +17257,7 @@
"feature": "workflows",
"summary": "Make email template transactional (prepare)",
"title": "Make email template transactional (prepare)",
- "required_scopes": ["hog_flow:write"],
+ "required_scopes": ["transactional_email:write"],
"annotations": {
"destructiveHint": false,
"idempotentHint": true,
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 911c139e150d..b4fbcfea0c42 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -18058,7 +18058,7 @@
"feature": "workflows",
"summary": "Make email template transactional (execute)",
"title": "Make email template transactional (execute)",
- "required_scopes": ["hog_flow:write"],
+ "required_scopes": ["transactional_email:write"],
"api_operations": ["POST /api/projects/{project_id}/messaging_templates/{id}/make_transactional/"],
"annotations": {
"destructiveHint": true,
@@ -18074,7 +18074,7 @@
"feature": "workflows",
"summary": "Make email template transactional (prepare)",
"title": "Make email template transactional (prepare)",
- "required_scopes": ["hog_flow:write"],
+ "required_scopes": ["transactional_email:write"],
"annotations": {
"destructiveHint": false,
"idempotentHint": true,
diff --git a/services/mcp/src/generated/email_templates/api.ts b/services/mcp/src/generated/email_templates/api.ts
index e72c16fef73e..dc3e6523091e 100644
--- a/services/mcp/src/generated/email_templates/api.ts
+++ b/services/mcp/src/generated/email_templates/api.ts
@@ -473,7 +473,7 @@ export const MessagingTemplatesDesignPartialUpdateBody = () => zod.strictObject(
})
/**
- * Make this template sendable over the transactional email API. This creates the workflow that sends it, with its own metrics, run history and versions. This can't be undone: the template stays transactional. Transactional sends ignore marketing opt-outs. Calling it again on a transactional template changes nothing.
+ * Make this template sendable over the transactional email API. This creates the workflow that sends it, with its own metrics, run history and versions. This can't be undone: the template stays transactional. Transactional sends ignore marketing opt-outs. Calling it again on a transactional template changes nothing. Needs the `transactional_email:write` scope, the same scope as sending. A key with `hog_flow:write` also works, but that scope reaches the rest of Workflows too. Without `hog_flow:read`, the response leaves out `content` and `draft_content`.
* @summary Make a template transactional
*/
export const MessagingTemplatesMakeTransactionalCreateParams = () => zod.object({
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index a4f08e414c46..31942bffc65b 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -342,6 +342,25 @@ describe('Tool Filtering - API Scopes', () => {
expect(tools.some((tool) => tool.name === 'inbox-report-checks-replace')).toBe(visible)
})
+ // The legacy fallback lets codegen accept `hog_flow:write` here, which would hide these tools from send-scoped keys.
+ it.each([
+ { scopes: ['transactional_email:write'], visible: true },
+ { scopes: ['hog_flow:write'], visible: true },
+ { scopes: ['transactional_email:read'], visible: false },
+ ])('making a template transactional needs the send scope: $scopes', async ({ scopes, visible }) => {
+ const tools = await getToolsFromContext(createMockContext(scopes), {
+ featureFlags: { 'workflows-transactional-email-api': true },
+ })
+ const names = tools.map((tool) => tool.name)
+
+ for (const name of [
+ 'workflows-make-email-template-transactional-prepare',
+ 'workflows-make-email-template-transactional-execute',
+ ]) {
+ expect(names.includes(name)).toBe(visible)
+ }
+ })
+
it.each([
{ scopes: ['billing:read'], visible: true },
{ scopes: [], visible: false },