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(workflows): scope the audience confirm token to interactive agent surfaces (#73522)

Harley Alexander82959d283b31
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index a7330ab5f8c2..7aee33d8e690 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -1663,6 +1663,13 @@ def mint_publish_confirm_token(hog_flow: HogFlow) -> str:
AUDIENCE_CONFIRM_TOKEN_MAX_AGE = timedelta(minutes=15)
_AUDIENCE_CONFIRM_SALT = "hogflow-batch-audience"
+# Surfaces where an LLM drives the request through a managed channel (classification is stamped by
+# the harness, not self-reported by the model). These get the audience-confirm gate; the web builder
+# has its own confirm UI, and headless callers (raw API keys, Terraform) dispatch in one call.
+AGENT_EVENT_SOURCES = frozenset(
+ {EventSource.MCP, EventSource.POSTHOG_CODE, EventSource.WIZARD, EventSource.CLI, EventSource.POSTHOG_AI}
+)
+
def _audience_confirm_value(
team_id: int, filters: dict, group_type_index: Optional[int] = None, dedupe_key: Optional[str] = None
@@ -1728,7 +1735,12 @@ class HogFlowViewSet(
# lists above can't distinguish GET (read) from POST (write) on the same action. Without
# this, these actions declare no scope and reject all personal-API-key (MCP) access.
if self.action in ("batch_jobs", "schedules"):
- return ["hog_flow:read"] if request.method in ("GET", "HEAD", "OPTIONS") else ["hog_flow:write"]
+ # Dispatching (or scheduling) fans out to persons and renders person properties into
+ # outbound messages, so it's person-data access on top of the workflow write - same
+ # rationale as user_blast_radius. Listing jobs/schedules stays workflow-read.
+ if request.method in ("GET", "HEAD", "OPTIONS"):
+ return ["hog_flow:read"]
+ return ["hog_flow:write", "person:read"]
# Sizing an audience runs a person/group count over caller-supplied filters — that's person-data
# access, so require person:read on top of workflow read. Without it a hog_flow:read-only token
# could use this as a person-existence oracle (e.g. "does email X exist?"). The web builder uses
@@ -2924,11 +2936,12 @@ class HogFlowViewSet(
if hog_flow.status != HogFlow.State.ACTIVE:
raise exceptions.ValidationError("Workflow must be active to run a batch. Enable it first.")
- # A batch run is an irreversible mass send: programmatic callers must prove they previewed
- # the audience, because only the blast-radius preview mints this token and it signs the
- # exact filters being dispatched. The web builder has its own confirmation UI and stays
- # token-free.
- if get_event_source(request) != EventSource.WEB:
+ # A batch run is an irreversible mass send: interactive agent surfaces must prove they
+ # previewed the audience, because only the blast-radius preview mints this token and it
+ # signs the exact filters being dispatched. The web builder has its own confirmation UI,
+ # and headless callers (raw API keys, Terraform) are professional surfaces where the
+ # two-step would be ceremony with no human to read the count - they stay token-free.
+ if get_event_source(request) in AGENT_EVENT_SOURCES:
self._require_audience_confirm_token(request, hog_flow)
serializer = HogFlowBatchJobSerializer(
@@ -2956,10 +2969,10 @@ class HogFlowViewSet(
hog_flow = self.get_object()
if request.method == "POST":
- # A schedule is a recurring batch dispatch - without this, a programmatic caller could
- # sidestep the batch_jobs token gate by scheduling the send instead. Same rules: the
- # web builder keeps its own confirm UI and stays token-free.
- if get_event_source(request) != EventSource.WEB:
+ # A schedule is a recurring batch dispatch - without this, an agent could sidestep the
+ # batch_jobs token gate by scheduling the send instead. Same scoping: the web builder
+ # keeps its own confirm UI, headless callers stay token-free.
+ if get_event_source(request) in AGENT_EVENT_SOURCES:
# A draft's trigger can still be edited after the audience was sized, so a schedule
# staged on a draft could fire on a broadened audience once enabled. Same rule the
# MCP tool enforces, applied at the API boundary.
diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.py
index bc3188964c2f..bd2cc9c94ad2 100644
--- a/products/workflows/backend/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -2696,12 +2696,13 @@ class TestHogFlowAPI(APIBaseTest):
"products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"
)
def test_programmatic_batch_dispatch_requires_audience_confirm_token(self, mock_create_invocation):
- # A batch run is an irreversible mass send. Programmatic callers must hold a token only the
+ # A batch run is an irreversible mass send. Agent surfaces must hold a token only the
# blast-radius preview mints, signed over the workflow's stored trigger filters - the audience
# the dispatch actually fans out to. A token minted for other (e.g. narrower) filters is
# rejected, so an agent can't size one audience and send to another, and an edited trigger
- # invalidates earlier previews. The web builder (session auth) keeps its own confirm UI and
- # stays token-free (covered by the existing batch job tests, which run as WEB).
+ # invalidates earlier previews. The web builder (session auth) keeps its own confirm UI
+ # (covered by the existing batch job tests, which run as WEB), and headless callers (raw API
+ # keys) dispatch in one call - the gate targets agents, not automation.
flow_id = self._create_active_hog_flow()
trigger_filters = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}").json()["trigger"][
"filters"
@@ -2794,6 +2795,40 @@ class TestHogFlowAPI(APIBaseTest):
assert draft_schedule.status_code == 400, draft_schedule.json()
assert "active" in draft_schedule.json()["detail"].lower()
+ # A raw API key is a headless professional surface - no agent in the loop to read a count,
+ # so the two-step would be ceremony. Dispatches in one call, no token. A fresh client keeps
+ # the request session-free so it classifies as API, not WEB.
+ api_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="batch dispatch",
+ user=self.user,
+ secure_value=hash_key_value(api_key),
+ scopes=["hog_flow:write", "person:read"],
+ )
+ api_client = self.client_class()
+ api_dispatch = api_client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/batch_jobs",
+ {},
+ headers={"authorization": f"Bearer {api_key}"},
+ )
+ assert api_dispatch.status_code == 200, api_dispatch.json()
+ assert api_dispatch.json()["filters"] == trigger_filters
+ assert mock_create_invocation.call_count == 2
+
+ # Fanning out renders person properties into outbound sends, so the write scope alone
+ # isn't enough - person:read is required, same as the blast-radius preview.
+ write_only_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="write only", user=self.user, secure_value=hash_key_value(write_only_key), scopes=["hog_flow:write"]
+ )
+ write_only = api_client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/batch_jobs",
+ {},
+ headers={"authorization": f"Bearer {write_only_key}"},
+ )
+ assert write_only.status_code == 403, write_only.json()
+ assert "person:read" in write_only.json().get("detail", "")
+
def test_post_hog_flow_batch_jobs_endpoint_rejects_non_active_workflow(self):
# A batch run is gated on an enabled workflow — a draft (or archived) one can't start a broadcast.
hog_flow, _ = self._create_hog_flow_with_action(