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(customer-analytics): allow workflow property overrides (#92860)

Arthur Moreira de Deus9e88bb312a9f
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 9b4317ff320a..7bf8274e014f 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -164,7 +164,11 @@ from products.notebooks.backend.facade import (
# the notebooks legacy-leak interface block.
from products.notebooks.backend.models import ResourceNotebook
from products.warehouse_sources.backend.facade.hooks import WarehouseBinding, saved_query_binding, schema_binding
-from products.workflows.backend.services.template_input_usage import get_hog_flows_referencing_template_input_keys
+from products.workflows.backend.services.template_input_usage import (
+ HogFlowReference,
+ filter_hog_flow_references_by_access_level,
+ get_hog_flows_referencing_template_input_keys,
+)
from . import contracts
@@ -1127,6 +1131,7 @@ def delete_customer_profile_config(
def _to_custom_property_definition_view(
definition: CustomPropertyDefinition,
references: list[contracts.CustomPropertyReference] | None = None,
+ has_workflow_reference: bool = False,
user_access_control: "UserAccessControl | None" = None,
enrichment_by_source_id: "dict[Any, tuple[Any, CustomPropertySyncRun | None]] | None" = None,
) -> contracts.CustomPropertyDefinitionView:
@@ -1143,6 +1148,7 @@ def _to_custom_property_definition_view(
created_by=definition.created_by_id,
updated_at=definition.updated_at,
references=references or [],
+ has_workflow_reference=has_workflow_reference,
source=_definition_source_view(definition, user_access_control, enrichment_by_source_id),
options=_to_custom_property_options(definition.options),
)
@@ -1156,32 +1162,30 @@ def _to_custom_property_options(
return [contracts.CustomPropertyOption(**option) for option in options]
-def _can_read_workflow_references(user_access_control: "UserAccessControl") -> bool:
- """Whether the caller may see the workflows that reference a custom property.
-
- ``references`` exposes HogFlow metadata (id, name, status), so it's gated on the caller
- having at least viewer access to the ``hog_flow`` resource — the property-definition API is
- authorized as ``account``, and a caller without workflow read access must not enumerate
- workflows through it. Without RBAC restrictions this resolves to the default (allowed)."""
- return user_access_control.check_access_level_for_resource("hog_flow", "viewer")
-
-
def _custom_property_references_by_definition_id(
team_id: int, definition_id: str | None = None
-) -> dict[str, list[contracts.CustomPropertyReference]]:
+) -> dict[str, list[HogFlowReference]]:
"""Map each referenced definition id to the workflows that set it via the "Update account
property" action. One scan of the team's workflows, matched by definition id. Pass
``definition_id`` to scan for just that one definition (the single-definition lookup)."""
usage = get_hog_flows_referencing_template_input_keys(
- team_id, _ACCOUNT_PROPERTY_TEMPLATE_ID, _ACCOUNT_PROPERTY_INPUT_KEY, only_value_key=definition_id
+ team_id,
+ _ACCOUNT_PROPERTY_TEMPLATE_ID,
+ _ACCOUNT_PROPERTY_INPUT_KEY,
+ only_value_key=definition_id,
)
- return {
- referenced_id: [
- contracts.CustomPropertyReference(id=ref.id, name=ref.name, status=ref.status, type="workflow")
- for ref in refs
- ]
- for referenced_id, refs in usage.items()
- }
+ return usage
+
+
+def _to_custom_property_references(
+ workflow_references: list[HogFlowReference],
+) -> list[contracts.CustomPropertyReference]:
+ return [
+ contracts.CustomPropertyReference(
+ id=reference.id, name=reference.name, status=reference.status, type="workflow"
+ )
+ for reference in workflow_references
+ ]
def _definition_source_view(
@@ -1215,19 +1219,16 @@ def list_custom_property_definitions(
) -> tuple[list[contracts.CustomPropertyDefinitionView], int]:
"""Custom property definitions for the team, ordered by name. Returns ``(page, total_count)``.
- ``references`` (the workflows referencing each definition) is included only when the caller can
- read workflows — see ``_can_read_workflow_references``. ``exclude_group_targets`` hides group-target
- definitions from callers without ``group`` read authorization."""
+ ``has_workflow_reference`` is included for every caller. ``references`` carries only workflow
+ metadata the caller can read. ``exclude_group_targets`` hides group-target definitions from callers
+ without ``group`` read authorization."""
queryset = CustomPropertyDefinition.objects.filter(team_id=team_id).select_related("source").order_by("name")
if exclude_group_targets:
queryset = queryset.exclude(target_type=TargetType.GROUP.value)
total_count = queryset.count()
page = list(queryset[offset : offset + limit])
- references = (
- _custom_property_references_by_definition_id(team_id)
- if _can_read_workflow_references(user_access_control)
- else {}
- )
+ workflow_references = _custom_property_references_by_definition_id(team_id)
+ references = filter_hog_flow_references_by_access_level(team_id, workflow_references, user_access_control)
sources: list[CustomPropertySource] = []
for d in page:
try:
@@ -1236,23 +1237,41 @@ def list_custom_property_definitions(
pass
enrichment = _batch_source_enrichment(team_id, sources, user_access_control)
return [
- _to_custom_property_definition_view(d, references.get(str(d.id), []), user_access_control, enrichment)
+ _to_custom_property_definition_view(
+ d,
+ _to_custom_property_references(references.get(str(d.id), [])),
+ has_workflow_reference=bool(workflow_references.get(str(d.id))),
+ user_access_control=user_access_control,
+ enrichment_by_source_id=enrichment,
+ )
for d in page
], total_count
+def get_custom_property_definition_target_type(team_id: int, definition_id: str) -> str | None:
+ definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)
+ return definition.target_type if definition is not None else None
+
+
def get_custom_property_definition(
team_id: int, definition_id: str, *, user_access_control: "UserAccessControl"
) -> contracts.CustomPropertyDefinitionView | None:
definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)
if definition is None:
return None
- references: list[contracts.CustomPropertyReference] = []
- if _can_read_workflow_references(user_access_control):
- references = _custom_property_references_by_definition_id(team_id, definition_id=str(definition.id)).get(
- str(definition.id), []
- )
- return _to_custom_property_definition_view(definition, references, user_access_control)
+ workflow_references_by_definition_id = _custom_property_references_by_definition_id(
+ team_id, definition_id=str(definition.id)
+ )
+ workflow_references = workflow_references_by_definition_id.get(str(definition.id), [])
+ references = filter_hog_flow_references_by_access_level(
+ team_id, workflow_references_by_definition_id, user_access_control
+ ).get(str(definition.id), [])
+ return _to_custom_property_definition_view(
+ definition,
+ _to_custom_property_references(references),
+ has_workflow_reference=bool(workflow_references),
+ user_access_control=user_access_control,
+ )
def list_custom_property_value_suggestions(team_id: int, definition_id: str, search: str | None) -> list[str]:
@@ -1370,7 +1389,23 @@ def update_custom_property_definition(
was_impersonated=was_impersonated,
previous=previous,
)
- return _to_custom_property_definition_view(definition, user_access_control=user_access_control)
+ workflow_references_by_definition_id = _custom_property_references_by_definition_id(
+ team_id, definition_id=str(definition.id)
+ )
+ workflow_references = workflow_references_by_definition_id.get(str(definition.id), [])
+ references = (
+ filter_hog_flow_references_by_access_level(
+ team_id, workflow_references_by_definition_id, user_access_control
+ ).get(str(definition.id), [])
+ if user_access_control is not None
+ else []
+ )
+ return _to_custom_property_definition_view(
+ definition,
+ _to_custom_property_references(references),
+ has_workflow_reference=bool(workflow_references),
+ user_access_control=user_access_control,
+ )
def delete_custom_property_definition(
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 290b8f279019..46407aebda28 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -912,6 +912,7 @@ class CustomPropertyDefinitionView:
created_by: int | None = None
updated_at: datetime | None = None
references: list[CustomPropertyReference] = field(default_factory=list)
+ has_workflow_reference: bool = False
source: "CustomPropertySourceView | None" = None
options: list[CustomPropertyOption] | None = None
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 8f3c0c25eb37..4b3f25726250 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -1834,7 +1834,11 @@ class CustomPropertyDefinitionSerializer(DataclassSerializer):
references = CustomPropertyReferenceSerializer(
many=True,
read_only=True,
- help_text="Workflows that use this property, resolved by definition id.",
+ help_text="Workflows that use this property, resolved by definition id when the caller can view workflows.",
+ )
+ has_workflow_reference = serializers.BooleanField(
+ read_only=True,
+ help_text="Whether a workflow updates this property. Always returned, even when workflow details are hidden.",
)
def validate(self, attrs):
@@ -1869,6 +1873,7 @@ class CustomPropertyDefinitionSerializer(DataclassSerializer):
"created_by",
"updated_at",
"references",
+ "has_workflow_reference",
]
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index e58b24d1ce74..7012a8b0d611 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -120,20 +120,18 @@ _OBJECT_WRITE_LEVEL = "editor"
_ICON_DOMAIN_VALIDATOR = DomainNameValidator(accept_idna=False)
-# The warehouse resources a person/group-property source can bind to: the import source behind a
-# table, or a materialized view. Each needs its own API-token scope folded into the object check.
-_WAREHOUSE_SCOPE_GATED_RESOURCES = frozenset({"external_data_source", "warehouse_view"})
+# Custom-property responses can include metadata from these resources. Token scopes must apply even
+# though the endpoint itself is authorized as an account resource.
+_SCOPE_GATED_RESOURCES = frozenset({"external_data_source", "warehouse_view", "hog_flow"})
-class _WarehouseScopeGatedAccessControl:
- """Wraps ``UserAccessControl`` so object-level warehouse access additionally requires the request
- token to carry the matching scope for that resource (``read`` for viewer, ``write`` for editor) —
- ``external_data_source`` for a table binding, ``warehouse_view`` for a view binding.
- Person-property sources gate all warehouse read/write through ``check_access_level_for_object`` on
- the bound warehouse object, so folding the token scope in here enforces the cross-resource scope on
- every path without threading it through the facade. Session auth (no token scopes) and ``*`` tokens
- are unaffected — API scopes never gate session requests, which stay RBAC-only. Everything else
- delegates to the wrapped instance."""
+class _ScopeGatedAccessControl:
+ """Wraps ``UserAccessControl`` so cross-resource reads require the matching token scope.
+
+ Custom-property sources and workflow references resolve through object access checks and queryset
+ filtering. Applying token scopes here keeps those secondary resources from leaking through an
+ account-scoped endpoint. Session auth and ``*`` tokens keep the wrapped access-control behavior.
+ """
def __init__(self, inner: UserAccessControl, token_scopes: list[str]) -> None:
self._inner = inner
@@ -143,27 +141,31 @@ class _WarehouseScopeGatedAccessControl:
return getattr(self._inner, name)
def check_access_level_for_object(self, obj: Any, required_level: Any, *args: Any, **kwargs: Any) -> bool:
- if self._token_lacks_scope_for(obj, required_level):
+ if self._token_lacks_scope_for_resource(model_to_resource(obj), required_level):
return False
return self._inner.check_access_level_for_object(obj, required_level, *args, **kwargs)
- def _token_lacks_scope_for(self, obj: Any, required_level: Any) -> bool:
+ def filter_queryset_by_access_level(self, queryset: Any, *args: Any, **kwargs: Any) -> Any:
+ resource = kwargs.get("resource") or model_to_resource(queryset.model)
+ if self._token_lacks_scope_for_resource(resource, "viewer"):
+ return queryset.none()
+ return self._inner.filter_queryset_by_access_level(queryset, *args, **kwargs)
+
+ def _token_lacks_scope_for_resource(self, resource: str | None, required_level: Any) -> bool:
scopes = self._token_scopes
- resource = model_to_resource(obj)
- if "*" in scopes or resource not in _WAREHOUSE_SCOPE_GATED_RESOURCES:
+ if "*" in scopes or resource not in _SCOPE_GATED_RESOURCES:
return False
if f"{resource}:write" in scopes:
- return False # write implies read, so it satisfies both viewer and editor
+ return False
return not (required_level == "viewer" and f"{resource}:read" in scopes)
def _warehouse_scoped_uac(view: Any) -> UserAccessControl:
- """The view's ``UserAccessControl``, additionally gating warehouse object access on the request
- token's scope for that resource. A no-op for session/other non-token auth (no token scopes)."""
+ """The view's ``UserAccessControl``, with token scopes applied to secondary resource reads."""
scopes = get_authenticator_scopes(getattr(view.request, "successful_authenticator", None))
if scopes is None:
return view.user_access_control
- return cast(UserAccessControl, _WarehouseScopeGatedAccessControl(view.user_access_control, scopes))
+ return cast(UserAccessControl, _ScopeGatedAccessControl(view.user_access_control, scopes))
# drf-spectacular auto-describes the pk path param for a model-backed viewset as
@@ -980,10 +982,7 @@ class CustomPropertyDefinitionViewSet(
def _guard_group_definition(self, request: Request, definition_id) -> None:
# Group-target definitions gate the group-writing pipeline, so mutating one needs group scope.
- definition = api.get_custom_property_definition(
- self.team_id, definition_id, user_access_control=self.user_access_control
- )
- if definition is not None and definition.target_type == _GROUP_TARGET_TYPE:
+ if api.get_custom_property_definition_target_type(self.team_id, definition_id) == _GROUP_TARGET_TYPE:
_assert_group_scope(request, write=True)
def update(self, request: Request, *args, **kwargs) -> Response:
diff --git a/products/customer_analytics/backend/presentation/views/warehouse_scope_gate_test.py b/products/customer_analytics/backend/presentation/views/warehouse_scope_gate_test.py
index 358fcb0648d7..ca1fd7c6d6d3 100644
--- a/products/customer_analytics/backend/presentation/views/warehouse_scope_gate_test.py
+++ b/products/customer_analytics/backend/presentation/views/warehouse_scope_gate_test.py
@@ -4,7 +4,7 @@ from django.test import SimpleTestCase
from parameterized import parameterized
-from products.customer_analytics.backend.presentation.views.views import _WarehouseScopeGatedAccessControl
+from products.customer_analytics.backend.presentation.views.views import _ScopeGatedAccessControl
class _Meta:
@@ -17,11 +17,11 @@ class _FakeModel:
self._meta = _Meta(model_name)
-class TestWarehouseScopeGatedAccessControl(SimpleTestCase):
- def _gate(self, scopes: list[str]) -> tuple[_WarehouseScopeGatedAccessControl, MagicMock]:
+class TestScopeGatedAccessControl(SimpleTestCase):
+ def _gate(self, scopes: list[str]) -> tuple[_ScopeGatedAccessControl, MagicMock]:
inner = MagicMock()
inner.check_access_level_for_object.return_value = True
- return _WarehouseScopeGatedAccessControl(inner, scopes), inner
+ return _ScopeGatedAccessControl(inner, scopes), inner
@parameterized.expand(
[
diff --git a/products/customer_analytics/backend/test/test_custom_property_values.py b/products/customer_analytics/backend/test/test_custom_property_values.py
index 8ff7c925f62e..f35c7ee44f4e 100644
--- a/products/customer_analytics/backend/test/test_custom_property_values.py
+++ b/products/customer_analytics/backend/test/test_custom_property_values.py
@@ -662,7 +662,9 @@ class TestSetExternalAccountCustomProperties(BaseTest):
class TestCustomPropertyDefinitionReferences(BaseTest):
def _uac(self, *, can_read_workflows: bool = True) -> MagicMock:
uac = MagicMock()
- uac.check_access_level_for_resource.return_value = can_read_workflows
+ uac.filter_queryset_by_access_level.side_effect = lambda queryset: (
+ queryset if can_read_workflows else queryset.none()
+ )
return uac
def _create_workflow_setting(self, definition_id: str, *, name: str = "Onboarding", status: str = "active"):
@@ -695,9 +697,10 @@ class TestCustomPropertyDefinitionReferences(BaseTest):
assert [(r.id, r.name, r.status, r.type) for r in by_id[plan.id].references] == [
(str(workflow.id), "Onboarding", "active", "workflow")
]
- # A definition no workflow references carries an empty list.
+ assert by_id[plan.id].has_workflow_reference is True
unused = next(v for v in page if v.name == "Unused")
assert unused.references == []
+ assert unused.has_workflow_reference is False
def test_reference_matches_id_not_name(self):
# A workflow keyed by a stale/foreign id must not attach to a same-named definition.
@@ -722,6 +725,28 @@ class TestCustomPropertyDefinitionReferences(BaseTest):
assert [(r.id, r.name, r.status, r.type) for r in view.references] == [
(str(workflow.id), "Onboarding", "active", "workflow")
]
+ assert view.has_workflow_reference is True
+
+ def test_update_attaches_workflow_references_for_workflow_viewers(self):
+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ workflow = self._create_workflow_setting(str(plan.id))
+
+ with team_scope(self.team.id):
+ view = facade.update_custom_property_definition(
+ team_id=self.team.id,
+ definition_id=str(plan.id),
+ fields={"description": "Customer plan"},
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ user_access_control=self._uac(),
+ )
+
+ assert view is not None
+ assert [(r.id, r.name, r.status, r.type) for r in view.references] == [
+ (str(workflow.id), "Onboarding", "active", "workflow")
+ ]
+ assert view.has_workflow_reference is True
def test_references_hidden_without_workflow_read_access(self):
# references expose HogFlow metadata, so a caller without hog_flow read access sees none.
@@ -736,6 +761,28 @@ class TestCustomPropertyDefinitionReferences(BaseTest):
self.team.id, str(plan.id), user_access_control=self._uac(can_read_workflows=False)
)
- assert next(v for v in page if v.id == plan.id).references == []
+ list_view = next(v for v in page if v.id == plan.id)
+ assert list_view.references == []
+ assert list_view.has_workflow_reference is True
+ assert view is not None
+ assert view.references == []
+ assert view.has_workflow_reference is True
+
+ def test_update_preserves_workflow_reference_presence_when_details_are_hidden(self):
+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ self._create_workflow_setting(str(plan.id))
+
+ with team_scope(self.team.id):
+ view = facade.update_custom_property_definition(
+ team_id=self.team.id,
+ definition_id=str(plan.id),
+ fields={"description": "Customer plan"},
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ user_access_control=self._uac(can_read_workflows=False),
+ )
+
assert view is not None
assert view.references == []
+ assert view.has_workflow_reference is True
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index c8bf2d63c33a..20f608596fa4 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -55,6 +55,7 @@ from products.product_analytics.backend.facade.models import Insight
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
+from products.workflows.backend.models import HogFlow
class TestCustomerProfileConfigViewSet(APIBaseTest):
@@ -1857,6 +1858,34 @@ class TestCustomPropertyDefinitionAccessControl(APIBaseTest):
organization_member=membership,
)
+ def _create_workflow_reference(self, *, name: str) -> HogFlow:
+ return HogFlow.objects.create(
+ team=self.team,
+ name=name,
+ status="active",
+ actions=[
+ {
+ "type": "function",
+ "config": {
+ "template_id": "template-posthog-update-account-property",
+ "inputs": {"properties": {"value": {str(self.definition.id): "enterprise"}}},
+ },
+ }
+ ],
+ )
+
+ def _token(self, scopes: list[str]) -> str:
+ value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="custom property definitions",
+ user=self.user,
+ secure_value=hash_key_value(value),
+ scopes=scopes,
+ scoped_teams=[],
+ scoped_organizations=[],
+ )
+ return value
+
def test_viewer_can_list(self):
self._set_access_level(self.viewer_user, access_level="viewer")
self.client.force_login(self.viewer_user)
@@ -1868,6 +1897,73 @@ class TestCustomPropertyDefinitionAccessControl(APIBaseTest):
response = self.client.get(f"{self.endpoint_base}{self.definition.id}/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
+ def test_workflow_presence_is_exposed_when_object_access_hides_references(self):
+ denied = self._create_workflow_reference(name="Update plan")
+ self._set_access_level(self.editor_user, resource="account", access_level="editor")
+ self._set_access_level(self.editor_user, resource="hog_flow", access_level="viewer")
+ self._set_access_level(
+ self.editor_user,
+ resource="hog_flow",
+ resource_id=str(denied.id),
+ access_level="none",
+ )
+ self.client.force_login(self.editor_user)
+
+ list_response = self.client.get(self.endpoint_base)
+ retrieve_response = self.client.get(f"{self.endpoint_base}{self.definition.id}/")
+ update_response = self.client.patch(
+ f"{self.endpoint_base}{self.definition.id}/", {"description": "Customer plan"}, format="json"
+ )
+
+ for response in (list_response, retrieve_response, update_response):
+ definition = response.json()["results"][0] if response is list_response else response.json()
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ self.assertTrue(definition["has_workflow_reference"])
+ self.assertEqual(definition["references"], [])
+
+ def test_personal_api_key_without_workflow_scope_cannot_read_references(self):
+ self._create_workflow_reference(name="Update plan")
+ token = self._token(["account:read"])
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
+
+ list_response = self.client.get(self.endpoint_base)
+ retrieve_response = self.client.get(f"{self.endpoint_base}{self.definition.id}/")
+
+ for response in (list_response, retrieve_response):
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ definition = response.json()["results"][0] if response is list_response else response.json()
+ self.assertTrue(definition["has_workflow_reference"])
+ self.assertEqual(definition["references"], [])
+
+ def test_object_level_workflow_denial_filters_only_the_denied_reference(self):
+ visible = self._create_workflow_reference(name="Visible workflow")
+ denied = self._create_workflow_reference(name="Denied workflow")
+ self._set_access_level(self.editor_user, resource="account", access_level="editor")
+ self._set_access_level(self.editor_user, resource="hog_flow", access_level="viewer")
+ self._set_access_level(
+ self.editor_user,
+ resource="hog_flow",
+ resource_id=str(denied.id),
+ access_level="none",
+ )
+ self.client.force_login(self.editor_user)
+
+ list_response = self.client.get(self.endpoint_base)
+ retrieve_response = self.client.get(f"{self.endpoint_base}{self.definition.id}/")
+ update_response = self.client.patch(
+ f"{self.endpoint_base}{self.definition.id}/", {"description": "Customer plan"}, format="json"
+ )
+
+ for response in (list_response, retrieve_response, update_response):
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ definition = response.json()["results"][0] if response is list_response else response.json()
+ self.assertTrue(definition["has_workflow_reference"])
+ self.assertEqual(
+ definition["references"],
+ [{"id": str(visible.id), "name": visible.name, "status": "active", "type": "workflow"}],
+ )
+
def test_viewer_cannot_create(self):
self._set_access_level(self.viewer_user, access_level="viewer")
self.client.force_login(self.viewer_user)
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 351c70796f96..e65c44c9e57c 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -42,7 +42,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc
| Logic | Owns |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `accountsLogic` | The hub. Search (debounced), tag / assigned-to/unassigned / native-field / relationship / custom-property filters, sort, inline role and editable custom-property assignment, typed Postgres list and metrics queries, shareable URL-hash view state, and `openAccount` (the Max entry point). `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references. `connect`s column-config, overview-tiles, and expansion logics. |
+| `accountsLogic` | The hub. Search (debounced), tag / assigned-to/unassigned / native-field / relationship / custom-property filters, sort, inline role and custom-property assignment, typed Postgres list and metrics queries, shareable URL-hash view state, and `openAccount` (the Max entry point). Canonical and warehouse-backed property values are read-only. Workflow-backed properties stay editable, but a future workflow run overwrites a manual value. `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references. `connect`s column-config, overview-tiles, and expansion logics. |
| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select) and browser-persisted column widths. Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |
| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), Postgres-backed column-picker groups, the per-team saved column config (`columnConfigurations` API), and custom-property definitions. It seeds `propertyDefinitionsModel` so the filter UI resolves per-type operator sets. Warehouse-backed columns and SQL expressions are not offered. |
| `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. |
@@ -105,7 +105,7 @@ Operator sets honor each field's type because `accountsColumnConfigLogic` seeds
`accountsTableQuery.ts` translates all three filter kinds into typed query filters. The backend filters relationships through active assignments, native model or JSON fields directly, and custom properties through storage chosen from the definition type. Negative operators include accounts where the value is unset. Invalid native combinations and deleted or incompatible custom properties are omitted rather than changing query engines.
Custom property value suggestions load from `GET /api/projects/:team_id/custom_property_definitions/values/?key=<definition-id>&value=<search>`. Native account fields do not fetch suggestions.
-A custom-property column is editable only when its definition has no data warehouse source or workflow references and is not canonical. `AccountsTable` passes this condition as `isEditable` to `CustomPropertyCell`. Editable cells show a pencil that replaces the rendered value with a compact, type-aware editor. Date and datetime properties use the Lemon Calendar picker and save from its Apply action. Link properties reject values outside HTTP and HTTPS before saving. `accountsLogic.updateAccountCustomProperty` writes through the generated custom-property-values endpoint, blocks duplicate writes, masks stale query data with a per-account override, refreshes the list and metrics, and clears the override after the next list response or a failed write. The event records only the display type, never the property name or value.
+A custom-property column is editable unless its definition is canonical or has a data warehouse source. Workflow-referenced properties stay editable and show a warning that a future workflow run overwrites a manual value. `AccountsTable` passes this condition as `isEditable` to `CustomPropertyCell`. Editable cells show a pencil that replaces the rendered value with a compact, type-aware editor. Date and datetime properties use the Lemon Calendar picker and save from its Apply action. Link properties reject values outside HTTP and HTTPS before saving. `accountsLogic.updateAccountCustomProperty` writes through the generated custom-property-values endpoint, blocks duplicate writes, masks stale query data with a per-account override, refreshes the list and metrics, and clears the override after the next list response or a failed write. The event records only the display type, never the property name or value.
**Overview tile math** (`accountsOverviewTilesLogic` / `AccountsOverviewTilesEditor`). A tile's metric is a discriminated union: `count`, the column aggregations `sum`/`avg`/`min`/`max`/`median`, and `count_threshold`. `tileQueryMetric` translates these into the typed `AccountsTableMetric` union. Column aggregations carry an optional `scale` multiplier, and threshold tiles translate into typed custom-property filters when clicked.
@@ -322,7 +322,7 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions
| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner` for the seeded definitions, else the definition name), `is_assigned`, `assigned_user_id`, `source` (`list_row` from `accountsLogic.updateAccountRole` \| `relationships_tab` from `accountRelationshipsLogic` assign/end) |
| `customer analytics accounts relationship deleted` | `accountRelationshipsLogic` `deleteRelationship` listener (after the DELETE succeeds) | _(none - count only; relationship and account identifiers stay out)_ |
| `customer analytics account tags updated` | `accountsLogic` `updateAccountTags` listener (after the debounced PATCH succeeds; dispatched by the tags cell editor) | `tag_count` (tag names kept out — they can name customers) |
-| `customer analytics account custom property updated` | `accountsLogic` `updateAccountCustomProperty` listener (after the custom-property-values write succeeds) | `display_type` (property name and value stay out because they can contain customer data) |
+| `customer analytics account custom property updated` | `accountsLogic` `updateAccountCustomProperty` listener (after the custom-property-values write succeeds) | `display_type`, `workflow_reference` (property name and value stay out because they can contain customer data) |
| `customer analytics account link clicked` | `AccountNotebooksExpansion.tsx` useful-link `onClick` (incl. the "Copy link to account" row, `link_key: 'copy-account-link'`) | `link_key`, `has_destination` |
| `customer analytics account note clicked` | `AccountNotebooksExpansion.tsx` note `<Link>` `onClick` | `notebook_short_id` |
| `customer analytics accounts note created` | `accountNotebooksLogic` `createNoteSuccess` listener | `notebook_short_id` |
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.test.ts b/products/customer_analytics/frontend/components/Accounts/AccountsTable.test.ts
index 5debc85315f7..e6f15e0873fc 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.test.ts
@@ -79,6 +79,7 @@ const createCustomPropertyDefinition = (
display_type: 'number',
is_canonical: false,
source: null,
+ has_workflow_reference: false,
created_at: '2026-01-01T00:00:00Z',
created_by: null,
updated_at: null,
@@ -91,14 +92,8 @@ describe('isCustomPropertyEditable', () => {
['manual', createCustomPropertyDefinition(), true],
['canonical', createCustomPropertyDefinition({ is_canonical: true }), false],
['data warehouse managed', createCustomPropertyDefinition({ source: createCustomPropertySource() }), false],
- [
- 'workflow managed',
- createCustomPropertyDefinition({
- references: [{ id: 'workflow-1', name: 'Update value', status: 'active', type: 'workflow' }],
- }),
- false,
- ],
- ])('marks %s definitions editable only when users can safely set their value', (_, value, expected) => {
+ ['workflow managed', createCustomPropertyDefinition({ has_workflow_reference: true }), true],
+ ])('marks %s definitions editable unless PostHog or the warehouse manages their values', (_, value, expected) => {
expect(isCustomPropertyEditable(value)).toBe(expected)
})
})
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
index 7d22235112a3..7dd7eed800d0 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { useMemo, useState } from 'react'
-import { IconCheck, IconPencil, IconX } from '@posthog/icons'
+import { IconCheck, IconInfo, IconPencil, IconX } from '@posthog/icons'
import {
LemonButton,
LemonColorGlyph,
@@ -354,7 +354,7 @@ function CanonicalTimestampCell({
}
export function isCustomPropertyEditable(definition: CustomPropertyDefinitionApi): boolean {
- return !definition.is_canonical && !definition.source && definition.references.length === 0
+ return !definition.is_canonical && !definition.source
}
type CustomPropertyDraft = boolean | string
@@ -640,6 +640,11 @@ function CustomPropertyCell({
return (
<div className="flex min-w-0 items-center gap-1">
<span className="min-w-0 truncate">{renderedValue}</span>
+ {definition.has_workflow_reference && (
+ <Tooltip title="A workflow is configured to update this property. If it runs again, it will overwrite any value you set manually.">
+ <IconInfo className="text-warning shrink-0" />
+ </Tooltip>
+ )}
{isEditable && accountId && (
<LemonButton
type="tertiary"
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
index 98ab6d675515..7ba702c6272f 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
@@ -33,6 +33,7 @@ function definition(
created_by: null,
updated_at: null,
references: [],
+ has_workflow_reference: false,
source: null,
...overrides,
}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
index d7d13d529384..769298fadaa6 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
@@ -154,6 +154,7 @@ const buildCustomPropertyDefinition = (
is_canonical: false,
source: null,
references: [],
+ has_workflow_reference: false,
created_at: '2026-01-01T00:00:00Z',
created_by: null,
updated_at: null,
@@ -820,18 +821,15 @@ describe('accountsLogic', () => {
logic.values.customPropertyOverrides[customPropertySavingKey('acc-1', definition.id)]
).toBeUndefined()
expect(logic.values.isCustomPropertySaving('acc-1', definition.id)).toBe(false)
- expect(capture).toHaveBeenCalledWith(AccountsEvents.CustomPropertyUpdated, { display_type: 'number' })
+ expect(capture).toHaveBeenCalledWith(AccountsEvents.CustomPropertyUpdated, {
+ display_type: 'number',
+ workflow_reference: false,
+ })
})
it.each([
['canonical', buildCustomPropertyDefinition({ is_canonical: true })],
['data warehouse managed', buildCustomPropertyDefinition({ source: createCustomPropertySource() })],
- [
- 'workflow managed',
- buildCustomPropertyDefinition({
- references: [{ id: 'workflow-1', name: 'Update health score', status: 'active', type: 'workflow' }],
- }),
- ],
])('does not write a %s property', async (_, definition) => {
logic.actions.updateAccountCustomProperty('acc-1', definition, 42)
await expectLogic(logic).toFinishAllListeners()
@@ -839,6 +837,31 @@ describe('accountsLogic', () => {
expect(mockCustomPropertyValuesCreate).not.toHaveBeenCalled()
})
+ it('writes a workflow-managed property', async () => {
+ const definition = buildCustomPropertyDefinition({ has_workflow_reference: true })
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
+ mockCustomPropertyValuesCreate.mockResolvedValue({
+ id: 'value-1',
+ account_id: 'acc-1',
+ definition_id: definition.id,
+ value: 42,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by_id: 1,
+ })
+
+ logic.actions.updateAccountCustomProperty('acc-1', definition, 42)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockCustomPropertyValuesCreate).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), 'acc-1', {
+ definition: definition.id,
+ value: 42,
+ })
+ expect(capture).toHaveBeenCalledWith(AccountsEvents.CustomPropertyUpdated, {
+ display_type: 'number',
+ workflow_reference: true,
+ })
+ })
+
it('reverts the optimistic override after a failed write', async () => {
const definition = buildCustomPropertyDefinition()
mockCustomPropertyValuesCreate.mockRejectedValueOnce(new Error('boom'))
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index 679756d9e3e0..5ea628b40b14 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -1249,7 +1249,6 @@ export const accountsLogic = kea<accountsLogicType>([
if (
definition.is_canonical ||
definition.source ||
- definition.references.length > 0 ||
values.isCustomPropertySaving(accountId, definition.id)
) {
return
@@ -1263,7 +1262,10 @@ export const accountsLogic = kea<accountsLogicType>([
definition: definition.id,
value,
})
- posthog.capture(AccountsEvents.CustomPropertyUpdated, { display_type: definition.display_type })
+ posthog.capture(AccountsEvents.CustomPropertyUpdated, {
+ display_type: definition.display_type,
+ workflow_reference: definition.has_workflow_reference,
+ })
cache.awaitingCustomPropertyRefresh = true
dataNodeLogic.findMounted({ key: ACCOUNTS_TABLE_DATA_NODE_KEY })?.actions.loadData('force_async')
dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 8e5d1501c7c3..2376eae035e8 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -2536,8 +2536,10 @@ export interface CustomPropertyDefinitionApi {
readonly created_by: number | null
/** @nullable */
readonly updated_at: string | null
- /** Workflows that use this property, resolved by definition id. */
+ /** Workflows that use this property, resolved by definition id when the caller can view workflows. */
readonly references: readonly CustomPropertyReferenceApi[]
+ /** Whether a workflow updates this property. Always returned, even when workflow details are hidden. */
+ readonly has_workflow_reference: boolean
}
export interface PaginatedCustomPropertyDefinitionListApi {
@@ -2608,8 +2610,10 @@ export interface PatchedCustomPropertyDefinitionApi {
readonly created_by?: number | null
/** @nullable */
readonly updated_at?: string | null
- /** Workflows that use this property, resolved by definition id. */
+ /** Workflows that use this property, resolved by definition id when the caller can view workflows. */
readonly references?: readonly CustomPropertyReferenceApi[]
+ /** Whether a workflow updates this property. Always returned, even when workflow details are hidden. */
+ readonly has_workflow_reference?: boolean
}
/**
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.stories.tsx
index 6c23d6d87810..339324f466c3 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.stories.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.stories.tsx
@@ -111,6 +111,7 @@ const meta: Meta = {
description: 'Monthly recurring revenue',
display_type: 'currency',
is_canonical: false,
+ has_workflow_reference: false,
is_big_number: false,
options: null,
},
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.test.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.test.tsx
index d9bab1b65006..47467f1d76b5 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.test.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.test.tsx
@@ -37,6 +37,7 @@ describe('CustomPropertiesConfig', () => {
created_by: 1,
updated_at: null,
references: [],
+ has_workflow_reference: false,
}
beforeEach(() => {
@@ -75,6 +76,34 @@ describe('CustomPropertiesConfig', () => {
afterEach(cleanup)
+ it('shows workflow as the source without exposing a redacted workflow', () => {
+ ;(useValues as jest.Mock).mockImplementation((logic) => {
+ if (logic === featureFlagLogic) {
+ return { featureFlags: {} }
+ }
+ if (logic === customPropertyDefinitionsLogic) {
+ return {
+ filteredDefinitions: [{ ...propertyDefinition, has_workflow_reference: true }],
+ definitionsLoading: false,
+ searchTerm: '',
+ targetTypeFilter: 'all',
+ runsBySourceId: {},
+ runsCountBySourceId: {},
+ runsOffsetBySourceId: {},
+ runsSearchBySourceId: {},
+ runsLoadingBySourceId: {},
+ runsLoadFailedBySourceId: {},
+ }
+ }
+ throw new Error('Unexpected logic')
+ })
+
+ const { getAllByText, queryByText } = render(<CustomPropertiesConfig />)
+
+ expect(getAllByText('Workflow')).toHaveLength(2)
+ expect(queryByText('Visible workflow')).not.toBeInTheDocument()
+ })
+
it('opens a confirmation dialog before deleting a custom property', () => {
render(<CustomPropertiesConfig />)
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx
index 321d3a9cb8c0..b60f4bd75476 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertiesConfig.tsx
@@ -133,7 +133,12 @@ export function CustomPropertiesConfig(): JSX.Element {
</Tooltip>
</span>
),
- render: (_, definition) => <ReferencesCell references={definition.references} />,
+ render: (_, definition) => (
+ <ReferencesCell
+ hasWorkflowReference={definition.has_workflow_reference}
+ references={definition.references}
+ />
+ ),
},
{
title: 'Last updated',
@@ -158,7 +163,13 @@ export function CustomPropertiesConfig(): JSX.Element {
return <span className="text-secondary">Auto</span>
}
if (!definition.source) {
- return <span className="text-secondary">Manual</span>
+ return definition.has_workflow_reference ? (
+ <Tooltip title="This property is updated by a workflow.">
+ <span className="text-secondary">Workflow</span>
+ </Tooltip>
+ ) : (
+ <span className="text-secondary">Manual</span>
+ )
}
const status = sourceSyncStatus(definition.source)
return (
@@ -304,13 +315,27 @@ export function CustomPropertiesConfig(): JSX.Element {
)
}
-function ReferencesCell({ references }: { references: readonly CustomPropertyReferenceApi[] }): JSX.Element {
+function ReferencesCell({
+ hasWorkflowReference,
+ references,
+}: {
+ hasWorkflowReference: boolean
+ references: readonly CustomPropertyReferenceApi[]
+}): JSX.Element {
const [open, setOpen] = useState(false)
- if (!references.length) {
+ if (!hasWorkflowReference) {
return <span className="text-secondary">0</span>
}
+ if (!references.length) {
+ return (
+ <Tooltip title="You don't have access to view the workflow.">
+ <span className="text-secondary">Workflow</span>
+ </Tooltip>
+ )
+ }
+
return (
<Popover
visible={open}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
index 31fd31b44555..5bd2a3597e85 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
@@ -531,6 +531,7 @@ export function CustomPropertyModal(): JSX.Element {
selectedSourceColumns,
savedQueriesLoading,
definitionsLoading,
+ editingHasWorkflowReference,
editingReferences,
newWorkflowUrlLoading,
targetTypeLocked,
@@ -556,7 +557,7 @@ export function CustomPropertyModal(): JSX.Element {
// While a workflow references the property it stays workflow-sourced no matter what is picked
// here, so the other options are locked until it's removed from the workflow(s).
- const lockedToWorkflow = editingReferences.length > 0 && !hasExistingSource
+ const lockedToWorkflow = editingHasWorkflowReference && !hasExistingSource
const sourceModeOptions = SOURCE_MODE_OPTIONS.map((option) =>
option.value !== 'workflow' && lockedToWorkflow
? {
@@ -577,7 +578,7 @@ export function CustomPropertyModal(): JSX.Element {
: (profileMappingDisabledReason ??
(targetType === 'account' && sourceMode === 'data_warehouse' && noViews
? 'No materialized views are available'
- : targetType === 'account' && sourceMode === 'workflow' && editingReferences.length === 0
+ : targetType === 'account' && sourceMode === 'workflow' && !editingHasWorkflowReference
? 'Create a workflow that updates this property first'
: undefined))
@@ -769,19 +770,19 @@ export function CustomPropertyModal(): JSX.Element {
</LemonField>
</>
))}
- {sourceMode === 'workflow' && (
- <div className="flex flex-col gap-2">
- <div className="flex items-center justify-between">
- <span className="font-semibold">Workflows updating this property</span>
- <LemonButton
- size="small"
- icon={<IconRefresh />}
- tooltip="Refresh"
- onClick={loadDefinitions}
- loading={definitionsLoading}
- />
- </div>
- {editingReferences.length > 0 ? (
+ {sourceMode === 'workflow' &&
+ (editingReferences.length > 0 ? (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center justify-between">
+ <span className="font-semibold">Workflows updating this property</span>
+ <LemonButton
+ size="small"
+ icon={<IconRefresh />}
+ tooltip="Refresh"
+ onClick={loadDefinitions}
+ loading={definitionsLoading}
+ />
+ </div>
<div className="flex flex-col gap-1">
{editingReferences.map((reference) => (
<div
@@ -799,24 +800,25 @@ export function CustomPropertyModal(): JSX.Element {
</div>
))}
</div>
- ) : (
- <div className="border rounded p-4 flex flex-col items-center gap-2 text-center">
- <span className="text-secondary">
- No workflows update this property yet. Create one with an "Update account
- property" action that sets this property — the editor opens in a new tab.
- Once you save the workflow there, refresh this list.
- </span>
- <LemonButton
- type="primary"
- onClick={createWorkflowForProperty}
- loading={newWorkflowUrlLoading}
- >
- Create workflow
- </LemonButton>
- </div>
- )}
- </div>
- )}
+ </div>
+ ) : editingHasWorkflowReference ? (
+ <LemonBanner type="warning">You don't have access to view the workflow.</LemonBanner>
+ ) : (
+ <div className="border rounded p-4 flex flex-col items-center gap-2 text-center">
+ <span className="text-secondary">
+ No workflows update this property yet. Create one with an "Update account
+ property" action that sets this property — the editor opens in a new tab. Once
+ you save the workflow there, refresh this list.
+ </span>
+ <LemonButton
+ type="primary"
+ onClick={createWorkflowForProperty}
+ loading={newWorkflowUrlLoading}
+ >
+ Create workflow
+ </LemonButton>
+ </div>
+ ))}
</>
)}
</Form>
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
index 0838ae12d1e3..79f0646206e0 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
@@ -57,6 +57,7 @@ const buildDefinition = (overrides: Partial<CustomPropertyDefinitionApi> = {}):
is_big_number: true,
source: null,
references: [],
+ has_workflow_reference: false,
created_at: '2026-01-01T00:00:00Z',
created_by: 1,
updated_at: '2026-01-01T00:00:00Z',
@@ -175,9 +176,13 @@ describe('customPropertyDefinitionsLogic', () => {
it.each([
[
'workflow references',
- { references: [{ id: 'flow-1', name: 'Flow', status: 'draft', type: 'workflow' }] },
+ {
+ has_workflow_reference: true,
+ references: [{ id: 'flow-1', name: 'Flow', status: 'draft', type: 'workflow' }],
+ },
'workflow',
],
+ ['a redacted workflow reference', { has_workflow_reference: true }, 'workflow'],
['no source or references', {}, 'manual'],
] as [string, Partial<CustomPropertyDefinitionApi>, string][])(
'derives the source mode when editing a definition with %s',
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
index 638c5cb0604c..fc4494c25193 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
@@ -246,6 +246,7 @@ export interface customPropertyDefinitionsLogicValues {
definitionsInitialLoading: boolean
definitionsLoading: boolean
editingDefinition: CustomPropertyDefinitionApi | null
+ editingHasWorkflowReference: boolean
editingReferences: readonly CustomPropertyReferenceApi[]
filteredDefinitions: CustomPropertyDefinitionApi[]
hasSyncedWarehouseTables: boolean | null
@@ -555,6 +556,10 @@ export interface customPropertyDefinitionsLogicMeta {
searchTerm: string,
targetTypeFilter: CustomPropertyTargetTypeFilter
) => CustomPropertyDefinitionApi[]
+ editingHasWorkflowReference: (
+ definitions: CustomPropertyDefinitionApi[],
+ editingDefinition: CustomPropertyDefinitionApi | null
+ ) => boolean
editingReferences: (
definitions: CustomPropertyDefinitionApi[],
editingDefinition: CustomPropertyDefinitionApi | null
@@ -1222,6 +1227,19 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
)
},
],
+ editingHasWorkflowReference: [
+ (s) => [s.definitions, s.editingDefinition],
+ (
+ definitions: CustomPropertyDefinitionApi[],
+ editingDefinition: CustomPropertyDefinitionApi | null
+ ): boolean => {
+ if (!editingDefinition) {
+ return false
+ }
+ const fresh = definitions.find((definition) => definition.id === editingDefinition.id)
+ return fresh?.has_workflow_reference ?? editingDefinition.has_workflow_reference
+ },
+ ],
editingReferences: [
(s) => [s.definitions, s.editingDefinition],
(
@@ -1294,7 +1312,7 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
groupTypeIndex: definition.group_type_index ?? null,
sourceMode: definition.source
? 'data_warehouse'
- : definition.references?.length
+ : definition.has_workflow_reference
? 'workflow'
: 'manual',
savedQuery: definition.source?.saved_query ?? null,
diff --git a/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsx b/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsx
index 04fe083bee38..fdf9c828430f 100644
--- a/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsx
+++ b/products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene.stories.tsx
@@ -31,6 +31,7 @@ const definitions: CustomPropertyDefinitionApi[] = [
created_by: null,
updated_at: null,
references: [],
+ has_workflow_reference: false,
source: {
id: '01890000-0000-0000-0000-0000000000a1',
definition: '01890000-0000-0000-0000-000000000001',
@@ -82,6 +83,7 @@ const definitions: CustomPropertyDefinitionApi[] = [
created_by: null,
updated_at: null,
references: [],
+ has_workflow_reference: false,
source: {
id: '01890000-0000-0000-0000-0000000000a2',
definition: '01890000-0000-0000-0000-000000000002',
@@ -114,6 +116,7 @@ const definitions: CustomPropertyDefinitionApi[] = [
created_by: null,
updated_at: null,
references: [],
+ has_workflow_reference: false,
source: {
id: '01890000-0000-0000-0000-0000000000a3',
definition: '01890000-0000-0000-0000-000000000003',
@@ -145,6 +148,7 @@ const definitions: CustomPropertyDefinitionApi[] = [
created_by: null,
updated_at: null,
references: [],
+ has_workflow_reference: false,
// View-backed: bound to a materialized view rather than an imported table, so it carries a
// saved_query and no warehouse source to link through.
source: {
diff --git a/products/workflows/backend/services/template_input_usage.py b/products/workflows/backend/services/template_input_usage.py
index 6974bd5d9ae3..7f7bd8bb609d 100644
--- a/products/workflows/backend/services/template_input_usage.py
+++ b/products/workflows/backend/services/template_input_usage.py
@@ -7,9 +7,13 @@ definition via the "Update account property" action's ``properties`` input.
"""
from dataclasses import dataclass
+from typing import TYPE_CHECKING
from products.workflows.backend.models import HogFlow
+if TYPE_CHECKING:
+ from products.access_control.backend.facade.user_access_control import UserAccessControl
+
@dataclass(frozen=True)
class HogFlowReference:
@@ -19,7 +23,11 @@ class HogFlowReference:
def get_hog_flows_referencing_template_input_keys(
- team_id: int, template_id: str, input_key: str, *, only_value_key: str | None = None
+ team_id: int,
+ template_id: str,
+ input_key: str,
+ *,
+ only_value_key: str | None = None,
) -> dict[str, list[HogFlowReference]]:
"""Map each key present in ``input_key``'s dict (across the team's workflows) to the workflows
that set it.
@@ -43,6 +51,29 @@ def get_hog_flows_referencing_template_input_keys(
return references
+def filter_hog_flow_references_by_access_level(
+ team_id: int,
+ references_by_key: dict[str, list[HogFlowReference]],
+ user_access_control: "UserAccessControl",
+) -> dict[str, list[HogFlowReference]]:
+ """Remove references the caller cannot view without reading workflow actions again."""
+ reference_ids = {reference.id for references in references_by_key.values() for reference in references}
+ if not reference_ids:
+ return {}
+
+ accessible_ids = {
+ str(flow_id)
+ for flow_id in user_access_control.filter_queryset_by_access_level(
+ HogFlow.objects.filter(team_id=team_id, id__in=reference_ids)
+ ).values_list("id", flat=True)
+ }
+ return {
+ key: filtered_references
+ for key, references in references_by_key.items()
+ if (filtered_references := [reference for reference in references if reference.id in accessible_ids])
+ }
+
+
def _referenced_keys(
actions: list[dict], template_id: str, input_key: str, *, only_value_key: str | None = None
) -> set[str]:
diff --git a/products/workflows/backend/test/test_template_input_usage.py b/products/workflows/backend/test/test_template_input_usage.py
index e627b7ca0aa9..a6238f39570e 100644
--- a/products/workflows/backend/test/test_template_input_usage.py
+++ b/products/workflows/backend/test/test_template_input_usage.py
@@ -1,7 +1,12 @@
from posthog.test.base import BaseTest
+from unittest.mock import MagicMock
from products.workflows.backend.models import HogFlow
-from products.workflows.backend.services.template_input_usage import get_hog_flows_referencing_template_input_keys
+from products.workflows.backend.services.template_input_usage import (
+ HogFlowReference,
+ filter_hog_flow_references_by_access_level,
+ get_hog_flows_referencing_template_input_keys,
+)
TEMPLATE_ID = "template-posthog-update-account-property"
@@ -76,3 +81,34 @@ class TestTemplateInputUsage(BaseTest):
usage = get_hog_flows_referencing_template_input_keys(self.team.id + 1, TEMPLATE_ID, "properties")
assert usage == {}
+
+ def test_filters_pre_scanned_references_without_loading_actions(self):
+ visible = self._create_flow(name="Visible", status="active", actions=[_account_property_action({"def-a": "1"})])
+ denied = self._create_flow(name="Denied", status="active", actions=[_account_property_action({"def-a": "1"})])
+ user_access_control = MagicMock()
+ user_access_control.filter_queryset_by_access_level.side_effect = lambda queryset: queryset.exclude(
+ id=denied.id
+ )
+
+ with self.assertNumQueries(1) as queries:
+ references = filter_hog_flow_references_by_access_level(
+ self.team.id,
+ {
+ "def-a": [
+ HogFlowReference(
+ id=str(visible.id), name=visible.name or str(visible.id), status=visible.status
+ ),
+ HogFlowReference(id=str(denied.id), name=denied.name or str(denied.id), status=denied.status),
+ ]
+ },
+ user_access_control,
+ )
+
+ assert references == {
+ "def-a": [HogFlowReference(id=str(visible.id), name=visible.name or str(visible.id), status=visible.status)]
+ }
+ assert all(
+ '"actions"' not in query["sql"]
+ for context in queries.contexts.values()
+ for query in context.captured_queries
+ )
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d46e657d3db9..a3a6192a7d82 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20417,8 +20417,10 @@ export namespace Schemas {
readonly created_by: number | null;
/** @nullable */
readonly updated_at: string | null;
- /** Workflows that use this property, resolved by definition id. */
+ /** Workflows that use this property, resolved by definition id when the caller can view workflows. */
readonly references: readonly CustomPropertyReference[];
+ /** Whether a workflow updates this property. Always returned, even when workflow details are hidden. */
+ readonly has_workflow_reference: boolean;
}
/**
@@ -60879,8 +60881,10 @@ export namespace Schemas {
readonly created_by?: number | null;
/** @nullable */
readonly updated_at?: string | null;
- /** Workflows that use this property, resolved by definition id. */
+ /** Workflows that use this property, resolved by definition id when the caller can view workflows. */
readonly references?: readonly CustomPropertyReference[];
+ /** Whether a workflow updates this property. Always returned, even when workflow details are hidden. */
+ readonly has_workflow_reference?: boolean;
}
/**