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(actions): match compound and nested-quote attribute selectors (#108533)

Sam Pennington9dd46cd1dc13
diff --git a/posthog/models/event/event.py b/posthog/models/event/event.py
index b69cbc125b2a..784503319850 100644
--- a/posthog/models/event/event.py
+++ b/posthog/models/event/event.py
@@ -12,6 +12,7 @@ from dateutil.relativedelta import relativedelta
from posthog.models.team import Team
SELECTOR_ATTRIBUTE_REGEX = r"([a-zA-Z]*)\[(.*)=[\'|\"](.*)[\'|\"]\]"
+ATTRIBUTE_PAIR_REGEX = r"\[\s*([^\]\s=\"']+)\s*=\s*(['\"])((?:\\.|(?!\\|\2).)*)\2\s*\]"
LAST_UPDATED_TEAM_ACTION: dict[int, datetime.datetime] = {}
@@ -31,6 +32,13 @@ class SelectorPart:
self.ch_attributes: dict[str, Union[str, list]] = {} # attributes for CH
result = re.search(SELECTOR_ATTRIBUTE_REGEX, tag)
+ pairs = self._attribute_pairs(tag, result)
+ self.confine_to_element = bool(pairs)
+ if result and pairs:
+ for key, value in pairs.items():
+ self.data[f"attributes__attr__{key}"] = value
+ self.ch_attributes[key] = value
+ tag = result[1]
if result and "[id=" in tag:
self.data["attr_id"] = result[3]
self.ch_attributes["attr_id"] = result[3]
@@ -80,6 +88,24 @@ class SelectorPart:
params.append(value)
return {"where": where, "params": params}
+ @staticmethod
+ def _attribute_pairs(tag: str, result: Optional[re.Match[str]]) -> dict[str, str]:
+ # The greedy SELECTOR_ATTRIBUTE_REGEX folds [a="1"][b="2"], or a value with a nested
+ # quote, into one key that contains a quote. The chain escapes quotes inside keys and
+ # values, so that key can never match. Only those parts are parsed again, which means
+ # a selector that matches events today compiles exactly as before.
+ # A prefix like .btn or :nth-child(2) before the tag letters is not parsed here.
+ if not result or tag[: result.start(1)] or "[id=" in tag or not re.search(r"[\"']", result[2]):
+ return {}
+ # Fall back unless the pairs run to the end of the part, so a trailing .class or a
+ # repeated key never turns into a match that ignores it.
+ brackets = tag[result.end(1) :]
+ matches = re.findall(ATTRIBUTE_PAIR_REGEX, brackets)
+ pairs = {key: re.sub(r"\\(.)", r"\1", value) for key, _quote, value in matches}
+ if re.sub(ATTRIBUTE_PAIR_REGEX, "", brackets) or len(pairs) != len(matches):
+ return {}
+ return pairs
+
def _unescape_class(self, class_name):
r"""Separate all double slashes "\\" (replace them with "\") and remove all single slashes between them."""
return "\\".join([p.replace("\\", "") for p in class_name.split("\\\\")])
diff --git a/posthog/models/property/util.py b/posthog/models/property/util.py
index 0ac11dffdd80..616f6c337417 100644
--- a/posthog/models/property/util.py
+++ b/posthog/models/property/util.py
@@ -125,6 +125,17 @@ def _chain_escaped_value(value: str) -> str:
return value.replace(r"\"", '"').replace('"', r"\"")
+# Custom attributes sort under attr__<key> in the chain (see elements_to_string), and the
+# regex has to name them in chain order to match.
+_UNPREFIXED_CHAIN_ATTRIBUTES = {"attr_id", "href", "text", "nth-child", "nth-of-type"}
+# A `;` inside a quoted value, like style="a: b; c: d", does not end the element.
+_WITHIN_ELEMENT = r'(?:[^;"]|"(?:\\.|[^"\\])*")*?'
+
+
+def _chain_attribute_order(key: str) -> str:
+ return key if key in _UNPREFIXED_CHAIN_ATTRIBUTES else f"attr__{key}"
+
+
def build_selector_regex(selector: Selector) -> str:
regex = r""
for tag in selector.parts:
@@ -134,9 +145,13 @@ def build_selector_regex(selector: Selector) -> str:
if tag.data.get("attr_class__contains"):
regex += r".*?\." + r"\..*?".join([re.escape(s) for s in sorted(tag.data["attr_class__contains"])])
if tag.ch_attributes:
- regex += r".*?"
- for key, value in sorted(tag.ch_attributes.items()):
- regex += rf'{re.escape(key)}="{re.escape(_chain_escaped_value(str(value)))}".*?'
+ # Attributes parsed from [a="1"][b="2"] must all be on one element.
+ separator = _WITHIN_ELEMENT if tag.confine_to_element else r".*?"
+ regex += separator
+ for key, value in sorted(tag.ch_attributes.items(), key=lambda kv: _chain_attribute_order(kv[0])):
+ # The full chain key stops [foo="1"] from matching inside attr__data-foo="1".
+ name = _chain_attribute_order(key) if tag.confine_to_element else key
+ regex += rf'{re.escape(name)}="{re.escape(_chain_escaped_value(str(value)))}"' + separator
# The rest of the element can carry characters an allowlist cannot
# anticipate (classes like w-1/2 or !mt-0), so skip anything up to the
# `;` element separator.
diff --git a/posthog/models/test/test_event_model.py b/posthog/models/test/test_event_model.py
index 0d149c2bc398..a2a9cb376622 100644
--- a/posthog/models/test/test_event_model.py
+++ b/posthog/models/test/test_event_model.py
@@ -207,6 +207,81 @@ class TestSelectorRegexMatching(SimpleTestCase):
],
True,
),
+ (
+ "two attributes with others between them, in any order",
+ '[type="button"][ng-click="continue()"]',
+ [
+ Element(
+ tag_name="button",
+ attributes={
+ "attr__type": "button",
+ "attr__ng-disabled": "busy",
+ "attr__ng-click": "continue()",
+ },
+ )
+ ],
+ True,
+ ),
+ (
+ "two attributes in single quotes after a tag",
+ "button[type='button'][data-x='a']",
+ [Element(tag_name="button", attributes={"attr__data-x": "a", "attr__type": "button"})],
+ True,
+ ),
+ (
+ "two attributes on different elements",
+ '[type="button"][ng-click="continue()"]',
+ [
+ Element(tag_name="button", attributes={"attr__type": "button"}),
+ Element(tag_name="div", attributes={"attr__ng-click": "continue()"}),
+ ],
+ False,
+ ),
+ (
+ "a tag and its two attributes on different elements",
+ "button[type='button'][data-x='a']",
+ [
+ Element(tag_name="button"),
+ Element(tag_name="div", attributes={"attr__data-x": "a", "attr__type": "button"}),
+ ],
+ False,
+ ),
+ (
+ "two attributes followed by a class the element does not have",
+ 'button[type="button"][data-x="a"].active',
+ [Element(tag_name="button", attributes={"attr__data-x": "a", "attr__type": "button"})],
+ False,
+ ),
+ (
+ "the same attribute with two different values",
+ '[data-x="a"][data-x="b"]',
+ [Element(tag_name="div", attributes={"attr__data-x": "b"})],
+ False,
+ ),
+ (
+ "two attributes with an escaped quote in a value",
+ "[title='it\\'s'][data-x='a']",
+ [Element(tag_name="div", attributes={"attr__data-x": "a", "attr__title": "it's"})],
+ True,
+ ),
+ (
+ "two attribute names that only match the end of longer names",
+ 'button[foo="1"][bar="2"]',
+ [Element(tag_name="button", attributes={"attr__data-bar": "2", "attr__data-foo": "1"})],
+ False,
+ ),
+ (
+ "two attributes after a tag and a position the element does not have",
+ 'button:nth-child(2)[type="button"][data-x="a"]',
+ [Element(tag_name="div", nth_child=1, attributes={"attr__data-x": "a", "attr__type": "button"})],
+ False,
+ ),
+ (
+ "an attribute value with nested quotes and an equals sign",
+ "[ng-class=\"{'selected': data.raising_for=='myself'}\"]",
+ [Element(tag_name="div", attributes={"attr__ng-class": "{'selected': data.raising_for=='myself'}"})],
+ True,
+ ),
(
"attribute value mismatch",
'div[title="hi"]',