: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
chore(workflows): read a single workflow through the facade (#113179)
Harley Alexander19dac2e45ddb
diff --git a/products/workflows/backend/facade/api.py b/products/workflows/backend/facade/api.pyindex c088dbd58675..10f7ecac3fba 100644--- a/products/workflows/backend/facade/api.py+++ b/products/workflows/backend/facade/api.py@@ -15,7 +15,9 @@ from products.workflows.backend.facade.contracts import (TierDecision,TwilioAccount,TwilioPhoneNumber,+ WorkflowAccessDenied,WorkflowActivitySummary,+ WorkflowNotFound,WorkflowSummary,WorkflowTaskDailyLimits,)@@ -41,6 +43,8 @@ from products.workflows.backend.utils.email_sending_tiers import (from products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrule__all__ = [+ "WorkflowAccessDenied",+ "WorkflowNotFound","MIN_EMAIL_SENDING_TIER","compute_next_occurrences","create_batch_job",@@ -57,14 +61,6 @@ __all__ = []-class WorkflowNotFound(Exception):- pass---class WorkflowAccessDenied(Exception):- pass--class WorkflowArchived(Exception):pass@@ -192,7 +188,7 @@ def set_workflow_enabled(*, team_id: int, user_id: int, workflow_id: UUID, enablraise WorkflowArchived()user = User.objects.get(id=user_id)if not UserAccessControl(user=user, team=hog_flow.team).check_access_level_for_object(hog_flow, "editor"):- raise WorkflowAccessDenied()+ raise WorkflowAccessDenied("editor")target = HogFlow.State.ACTIVE if enabled else HogFlow.State.DRAFTif hog_flow.status != target:if enabled:diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex 4e62400db22e..7f4bebf4ec3c 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -382,6 +382,63 @@ class WorkflowHasNoDraft(Exception):"""Publish found no staged draft."""+@frozen+class Workflow:+ """A workflow as the API reads it.++ Each set secret input in ``actions``, ``trigger`` and ``draft`` is already replaced by the+ ``{"secret": True}`` presence marker, so the contract never carries a secret value.+ ``created_by`` carries the core ``User`` row, so the presentation layer keeps serializing it+ through core's ``UserBasicSerializer``. ``user_access_level`` is the reader's access level, or+ None when the reader is a service credential.++ ``edges`` and ``actions`` hold lists, but a row saved without them keeps the model default+ ``{}``, so both fields can also be a dict.+ """++ id: UUID+ team_id: int+ name: str | None+ description: str+ version: int+ status: str+ origin_product: str | None+ created_at: datetime+ created_by: "User | None"+ updated_at: datetime+ trigger: Any+ trigger_masking: dict[str, Any] | None+ conversion: dict[str, Any] | None+ exit_condition: str+ email_sending_rate_limit: dict[str, Any] | None+ edges: list[dict[str, Any]] | dict[str, Any]+ actions: list[dict[str, Any]] | dict[str, Any]+ abort_action: str | None+ variables: list[dict[str, Any]] | None+ billable_action_types: list[str] | None+ schedules: tuple[WorkflowSchedule, ...]+ draft: dict[str, Any] | None+ draft_updated_at: datetime | None+ action_redirects: dict[str, str] | None+ email_sending_paused_at: datetime | None+ email_sending_paused_reason: str+ email_sending_paused_by: str+ email_sending_resumed_at: datetime | None+ user_access_level: str | None+++class WorkflowNotFound(Exception):+ pass+++class WorkflowAccessDenied(Exception):+ """The caller's access level for the workflow is below `required_level`."""++ def __init__(self, required_level: str) -> None:+ super().__init__(required_level)+ self.required_level = required_level++@frozenclass WorkflowWriteResult:previous: Mapping[str, object]diff --git a/products/workflows/backend/facade/secrets.py b/products/workflows/backend/facade/secrets.pyindex d112803a1a76..add2e31f5c93 100644--- a/products/workflows/backend/facade/secrets.py+++ b/products/workflows/backend/facade/secrets.py@@ -5,6 +5,7 @@ from products.workflows.backend.services.hog_flow_secrets import (TemplateCache,mask_derived_trigger,mask_secret_action_inputs,+ mask_workflow_fields,merge_secret_maps,partition_flow_secrets,plaintext_secret_map,@@ -19,6 +20,7 @@ __all__ = ["TemplateCache","mask_derived_trigger","mask_secret_action_inputs",+ "mask_workflow_fields","merge_secret_maps","partition_flow_secrets","plaintext_secret_map",diff --git a/products/workflows/backend/facade/workflows.py b/products/workflows/backend/facade/workflows.pynew file mode 100644index 000000000000..9f575cdd1871--- /dev/null+++ b/products/workflows/backend/facade/workflows.py@@ -0,0 +1,7 @@+"""Reading workflows: one workflow behind the reader's object access check, with its secret inputs masked."""++from products.workflows.backend.services.hog_flow_reads import get_workflow++__all__ = [+ "get_workflow",+]diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 96d081505414..0c9db0a89f20 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -85,7 +85,7 @@ from posthog.event_usage import AGENT_EVENT_SOURCES, EventSource, get_event_sourfrom posthog.models import Team, Userfrom posthog.models.integration import Integrationfrom posthog.models.property.parse import expand_cohort_properties, parse_property_group_data-from posthog.permissions import posthog_feature_flag_enabled+from posthog.permissions import AccessControlPermission, is_service_auth, posthog_feature_flag_enabledfrom posthog.plugins.plugin_server_api import (cancel_hog_flow_batch_job,cancel_hog_flow_invocations,@@ -136,10 +136,13 @@ from products.workflows.backend.facade.contracts import (EmailDesignRenderFailed,EmailDesignRenderingNotConfigured,StaffPausedError,+ Workflow,+ WorkflowAccessDenied,WorkflowBatchJobNotFound,WorkflowDraftChanged,WorkflowDraftExists,WorkflowHasNoDraft,+ WorkflowNotFound,WorkflowProposalRecord,WorkflowRevisionNotFound,WorkflowRevisionSummary,@@ -198,8 +201,7 @@ from products.workflows.backend.facade.schedules import ()from products.workflows.backend.facade.secrets import (TemplateCache,- mask_derived_trigger,- mask_secret_action_inputs,+ mask_workflow_fields,merge_secret_maps,plaintext_secret_map,recover_or_drop_masked_inputs,@@ -218,6 +220,7 @@ from products.workflows.backend.facade.validation import (is_duration,is_signed_duration,)+from products.workflows.backend.facade.workflows import get_workflowfrom products.workflows.backend.facade.writes import (build_publish_impact,create_workflow,@@ -366,27 +369,6 @@ def existing_secret_map(instance: "HogFlow", template_cache: Optional[TemplateCareturn merge_secret_maps(result, instance.draft_encrypted_inputs)-def mask_trigger_config(- instance: "HogFlow", secrets_by_action: dict[str, dict], template_cache: Optional[TemplateCache] = None-) -> Any:- # Mask the standalone `trigger` field. Both the minimal and (crucially) the summary serializer- # return `trigger` while the summary omits `actions`, so it can't be re-derived from masked actions- # there - a function-shaped trigger's secret would otherwise leak on the MCP list endpoint. Mask- # from the instance's own trigger action (or the stored trigger config as a fallback for legacy- # rows whose actions may be empty).- trigger_action = next(- (a for a in (instance.actions or []) if isinstance(a, dict) and a.get("type") == "trigger"),- None,- )- trigger_action = (- deepcopy(trigger_action)- if trigger_action is not None- else {"type": "trigger", "config": deepcopy(instance.trigger) if instance.trigger else {}}- )- masked = mask_secret_action_inputs([trigger_action], secrets_by_action, template_cache)- return masked[0].get("config")--def snapshot_flow_content(flow: HogFlow) -> dict:return snapshot_content({field: getattr(flow, field) for field in DRAFT_CONTENT_FIELDS})@@ -2566,35 +2548,31 @@ class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Mod# A workflow with suggestions on but none waiting is still worth telling apart in the list.return getattr(hog_flow, "suggestions_enabled", None)+ def get_user_access_level(self, obj: Any) -> Optional[str]:+ if isinstance(obj, Workflow):+ # The service resolved the level when it built the contract.+ return obj.user_access_level+ return super().get_user_access_level(obj)+def to_representation(self, instance):- # Never return secret function inputs. Replace each set secret with the {"secret": True}- # presence marker in the live actions and, when present, the staged draft's actions. Values- # come from the encrypted columns (or legacy plaintext); see mask_secret_action_inputs.- live_secrets = instance.encrypted_inputs or {} if isinstance(instance, HogFlow) else {}- draft_secrets = instance.draft_encrypted_inputs or {} if isinstance(instance, HogFlow) else {}data = super().to_representation(instance)-- # `actions`/`draft` come back from super() by reference (JSONField doesn't copy), so masking in- # place would rewrite the live model instance. Deepcopy first to keep serialization side-effect- # free. The template cache lives on the context so a list render dedupes lookups across flows.- template_cache: TemplateCache = self.context.setdefault("_hogflow_template_cache", {})- if isinstance(data.get("actions"), list):- data["actions"] = mask_secret_action_inputs(deepcopy(data["actions"]), live_secrets, template_cache)- # `trigger` is a separately-serialized field derived from the trigger action. Mask it from the- # instance directly (not from data["actions"]) so it's covered even by the summary serializer,- # which returns `trigger` but omits `actions` - otherwise a function-shaped trigger's secret- # would leak on the MCP list endpoint.- if "trigger" in data and isinstance(instance, HogFlow):- data["trigger"] = mask_trigger_config(instance, live_secrets, template_cache)- draft = data.get("draft")- if isinstance(draft, dict) and isinstance(draft.get("actions"), list):- draft = deepcopy(draft)- draft["actions"] = mask_secret_action_inputs(- draft["actions"], merge_secret_maps(live_secrets, draft_secrets), template_cache- )- mask_derived_trigger(draft, template_cache)- data["draft"] = draft-+ if isinstance(instance, Workflow):+ # The service masked the secret inputs when it built the contract.+ return data+ # Never return secret function inputs. Replace each set secret with the {"secret": True}+ # presence marker in the live actions, the trigger and, when present, the staged draft's+ # actions. Values come from the encrypted columns (or legacy plaintext).+ # The template cache lives on the context so a list render dedupes lookups across flows.+ is_row = isinstance(instance, HogFlow)+ mask_workflow_fields(+ data,+ live_actions=instance.actions if is_row else None,+ live_trigger=instance.trigger if is_row else None,+ encrypted_inputs=instance.encrypted_inputs if is_row else None,+ draft_encrypted_inputs=instance.draft_encrypted_inputs if is_row else None,+ template_cache=self.context.setdefault("_hogflow_template_cache", {}),+ mask_trigger=is_row,+ )return data@@ -4501,6 +4479,31 @@ class HogFlowViewSet(# TODO(team-workflows): Somehow implement version lookupsreturn super().safely_get_object(queryset)+ def _object_access(self) -> tuple[UserAccessControl | None, str | None]:+ """The access control and level that `AccessControlPermission.has_object_permission` would check."""+ # Service credentials are synthetic users that UserAccessControl cannot evaluate.+ if is_service_auth(self.request):+ return None, None+ return self.user_access_control, AccessControlPermission()._get_required_access_level(self.request, self)++ def _workflow(self) -> Workflow:+ """The workflow in the URL, or 404 when the team has none with that id, or 403 below the required level."""+ user_access_control, required_level = self._object_access()+ try:+ return get_workflow(+ team_id=self.team_id,+ workflow_id=self.kwargs["pk"],+ user_access_control=user_access_control,+ required_level=required_level,+ )+ except WorkflowNotFound:+ raise exceptions.NotFound()+ except WorkflowAccessDenied as denied:+ raise exceptions.PermissionDenied(f"You do not have {denied.required_level} access to this resource.")++ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ return Response(self.get_serializer(self._workflow()).data)+@staticmethoddef _is_mcp_request(request: Request) -> bool:return request.headers.get("x-posthog-client") == "mcp"diff --git a/products/workflows/backend/services/hog_flow_reads.py b/products/workflows/backend/services/hog_flow_reads.pynew file mode 100644index 000000000000..260e7c0bb381--- /dev/null+++ b/products/workflows/backend/services/hog_flow_reads.py@@ -0,0 +1,90 @@+"""Reading one workflow for the API: the reader's object access check, then the workflow as a contract+with its secret inputs masked."""++from typing import TYPE_CHECKING, Optional, cast+from uuid import UUID++from django.core.exceptions import ValidationError++from products.workflows.backend.facade.contracts import Workflow, WorkflowAccessDenied, WorkflowNotFound+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.services.hog_flow_schedules import list_schedules_oldest_first+from products.workflows.backend.services.hog_flow_secrets import TemplateCache, mask_workflow_fields++if TYPE_CHECKING:+ from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl+++def get_workflow(+ *,+ team_id: int,+ workflow_id: UUID | str,+ user_access_control: "UserAccessControl | None",+ required_level: str | None,+) -> Workflow:+ """The team's workflow, or WorkflowNotFound, or WorkflowAccessDenied when the reader's level for+ it is below `required_level`. Pass None for both access arguments to skip the check, as a+ service credential does."""+ try:+ flow = HogFlow.objects.select_related("created_by").get(team_id=team_id, pk=workflow_id)+ except (HogFlow.DoesNotExist, ValidationError, ValueError):+ # ValidationError and ValueError fire when the id is not a parseable UUID.+ raise WorkflowNotFound()+ # The same check AccessControlPermission.has_object_permission runs on a model viewset's object.+ if (+ user_access_control is not None+ and required_level is not None+ and not user_access_control.check_access_level_for_object(+ flow, required_level=cast("AccessControlLevel", required_level)+ )+ ):+ raise WorkflowAccessDenied(required_level)+ return _to_workflow(flow, user_access_control, template_cache={})+++def _to_workflow(+ flow: HogFlow, user_access_control: "UserAccessControl | None", template_cache: TemplateCache+) -> Workflow:+ masked: dict[str, object] = {"actions": flow.actions, "trigger": flow.trigger, "draft": flow.draft}+ mask_workflow_fields(+ masked,+ live_actions=flow.actions,+ live_trigger=flow.trigger,+ encrypted_inputs=flow.encrypted_inputs,+ draft_encrypted_inputs=flow.draft_encrypted_inputs,+ template_cache=template_cache,+ )+ access_level: Optional[str] = (+ user_access_control.get_user_access_level(flow) if user_access_control is not None else None+ )+ return Workflow(+ id=flow.id,+ team_id=flow.team_id,+ name=flow.name,+ description=flow.description,+ version=flow.version,+ status=flow.status,+ origin_product=flow.origin_product,+ created_at=flow.created_at,+ created_by=flow.created_by,+ updated_at=flow.updated_at,+ trigger=masked["trigger"],+ trigger_masking=flow.trigger_masking,+ conversion=flow.conversion,+ exit_condition=flow.exit_condition,+ email_sending_rate_limit=flow.email_sending_rate_limit,+ edges=flow.edges,+ actions=cast("list[dict] | dict", masked["actions"]),+ abort_action=flow.abort_action,+ variables=flow.variables,+ billable_action_types=flow.billable_action_types,+ schedules=tuple(list_schedules_oldest_first(team_id=flow.team_id, hog_flow_id=flow.id)),+ draft=cast("dict | None", masked["draft"]),+ draft_updated_at=flow.draft_updated_at,+ action_redirects=flow.action_redirects,+ email_sending_paused_at=flow.email_sending_paused_at,+ email_sending_paused_reason=flow.email_sending_paused_reason,+ email_sending_paused_by=flow.email_sending_paused_by,+ email_sending_resumed_at=flow.email_sending_resumed_at,+ user_access_level=access_level,+ )diff --git a/products/workflows/backend/services/hog_flow_schedules.py b/products/workflows/backend/services/hog_flow_schedules.pyindex f3b50e7aa365..20e3a05e9701 100644--- a/products/workflows/backend/services/hog_flow_schedules.py+++ b/products/workflows/backend/services/hog_flow_schedules.py@@ -51,6 +51,12 @@ def list_schedules(*, team_id: int, hog_flow_id: UUID) -> list[WorkflowSchedule]return [_to_schedule(s) for s in schedules]+def list_schedules_oldest_first(*, team_id: int, hog_flow_id: UUID) -> list[WorkflowSchedule]:+ """The schedules a workflow response embeds, in the order they were added."""+ schedules = HogFlowSchedule.objects.filter(hog_flow_id=hog_flow_id, team_id=team_id).order_by("created_at", "id")+ return [_to_schedule(s) for s in schedules]++def get_schedule(*, team_id: int, hog_flow_id: UUID, schedule_id: str) -> WorkflowSchedule:return _to_schedule(_get_schedule_row(team_id, hog_flow_id, schedule_id))diff --git a/products/workflows/backend/services/hog_flow_secrets.py b/products/workflows/backend/services/hog_flow_secrets.pyindex 95cd998f6fbd..9cfc84357fbf 100644--- a/products/workflows/backend/services/hog_flow_secrets.py+++ b/products/workflows/backend/services/hog_flow_secrets.py@@ -135,6 +135,55 @@ def mask_derived_trigger(content: dict, template_cache: Optional[TemplateCache]content["trigger"] = trigger_action.get("config")+def mask_trigger_config(+ actions: Any, trigger: Any, secrets_by_action: dict[str, dict], template_cache: Optional[TemplateCache] = None+) -> Any:+ # Mask the standalone `trigger` field. Both the minimal and (crucially) the summary serializer+ # return `trigger` while the summary omits `actions`, so it can't be re-derived from masked actions+ # there - a function-shaped trigger's secret would otherwise leak on the MCP list endpoint. Mask+ # from the workflow's own trigger action (or the stored trigger config as a fallback for legacy+ # rows whose actions may be empty).+ trigger_action = next(+ (a for a in (actions or []) if isinstance(a, dict) and a.get("type") == "trigger"),+ None,+ )+ trigger_action = (+ deepcopy(trigger_action)+ if trigger_action is not None+ else {"type": "trigger", "config": deepcopy(trigger) if trigger else {}}+ )+ masked = mask_secret_action_inputs([trigger_action], secrets_by_action, template_cache)+ return masked[0].get("config")+++def mask_workflow_fields(+ fields: dict[str, Any],+ *,+ live_actions: Any,+ live_trigger: Any,+ encrypted_inputs: Optional[dict],+ draft_encrypted_inputs: Optional[dict],+ template_cache: TemplateCache,+ mask_trigger: bool = True,+) -> None:+ """Replace each set secret input in the `actions`, `trigger` and `draft` entries of `fields` with+ the {"secret": True} presence marker. Rewrites the entries of `fields`, never the values they+ point to, so the stored workflow stays unchanged."""+ live_secrets = encrypted_inputs or {}+ if isinstance(fields.get("actions"), list):+ fields["actions"] = mask_secret_action_inputs(deepcopy(fields["actions"]), live_secrets, template_cache)+ if mask_trigger and "trigger" in fields:+ fields["trigger"] = mask_trigger_config(live_actions, live_trigger, live_secrets, template_cache)+ draft = fields.get("draft")+ if isinstance(draft, dict) and isinstance(draft.get("actions"), list):+ draft = deepcopy(draft)+ draft["actions"] = mask_secret_action_inputs(+ draft["actions"], merge_secret_maps(live_secrets, draft_encrypted_inputs), template_cache+ )+ mask_derived_trigger(draft, template_cache)+ fields["draft"] = draft++def strip_secrets_from_content(content: dict, template_cache: Optional[TemplateCache] = None) -> dict[str, dict]:# Move secret inputs out of content["actions"] into an encrypted map, updating content["actions"]# (stripped) and the derived content["trigger"] in place. Returns the {action_id: {key: value}} map.diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.pyindex e61fea0b02fb..8a781e0fb95c 100644--- a/products/workflows/backend/tests/api/test_hog_flow.py+++ b/products/workflows/backend/tests/api/test_hog_flow.py@@ -5098,6 +5098,20 @@ class TestHogFlowAPI(APIBaseTest):response = self.client.get(f"/api/projects/{another_team.id}/hog_flows/{flow_id}")assert response.status_code == status.HTTP_403_FORBIDDEN+ @parameterized.expand([("another_projects_workflow",), ("sibling_environment_workflow",), ("malformed_id",)])+ def test_hog_flow_retrieve_404s_for_an_id_outside_the_team(self, case: str):+ if case == "malformed_id":+ workflow_id = "not-a-uuid"+ else:+ project = self.project if case == "sibling_environment_workflow" else None+ other_team = Team.objects.create(organization=self.organization, project=project)+ workflow_id = str(HogFlow.objects.create(team=other_team, name="Other team's flow").id)++ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{workflow_id}")++ assert response.status_code == status.HTTP_404_NOT_FOUND, response.json()+ assert response.json()["detail"] == "Not found."+def test_hog_flow_create_does_not_leak_between_teams(self):another_org = Organization.objects.create(name="other org")another_team = Team.objects.create(organization=another_org)