"""``$.`` references and conditions: resolution at run time, extraction for static checks. Resolution is deterministic code, never a model. Values that come from the triggering event (``$.event``) are untrusted (a webhook body), so they are reported as tainted and the gateway treats them like extractor output. """ from __future__ import annotations import re from collections.abc import Iterator from dataclasses import dataclass, field from typing import Any from core.workflows.dsl import Condition TEMPLATE = re.compile(r"\{\{\s*(\$\.[A-Za-z0-9_.\-]+)\s*\}\}") UNTRUSTED_ROOTS = frozenset({"event"}) class RefError(LookupError): """A reference points at something that does not exist (missing step output or key).""" def is_ref(v: Any) -> bool: return isinstance(v, str) and v.startswith("$.") def segments(ref: str) -> list[str | int]: if not is_ref(ref) or len(ref) < 3: raise RefError(f"not a reference: {ref!r}") out: list[str | int] = [] for part in ref[2:].split("."): if part == "": raise RefError(f"empty segment in {ref!r}") out.append(int(part) if part.isdigit() else part) return out def root(ref: str) -> str: return str(segments(ref)[0]) def refs_in(value: Any) -> Iterator[str]: """Every reference inside an argument value (plain refs and ``{{ }}`` templates).""" if is_ref(value): yield value elif isinstance(value, str): for m in TEMPLATE.finditer(value): yield m.group(1) elif isinstance(value, list): for v in value: yield from refs_in(v) elif isinstance(value, dict): for v in value.values(): yield from refs_in(v) @dataclass class Scope: steps: dict[str, Any] = field(default_factory=dict) event: dict[str, Any] | None = None trigger: dict[str, Any] = field(default_factory=dict) workflow: dict[str, Any] = field(default_factory=dict) item: Any = None index: int | None = None in_loop: bool = False item_tainted: bool = False def with_item(self, item: Any, index: int, tainted: bool) -> Scope: return Scope( steps=self.steps, event=self.event, trigger=self.trigger, workflow=self.workflow, item=item, index=index, in_loop=True, item_tainted=tainted, ) def _walk(value: Any, path: list[str | int], ref: str) -> Any: cur = value for seg in path: if isinstance(cur, dict) and str(seg) in cur: cur = cur[str(seg)] elif isinstance(cur, list) and isinstance(seg, int) and -len(cur) <= seg < len(cur): cur = cur[seg] elif isinstance(cur, list) and seg == "length": cur = len(cur) else: raise RefError(f"{ref}: no {seg!r}") return cur def resolve(ref: str, scope: Scope) -> tuple[Any, bool]: """Value of ``ref`` plus whether it is tainted (derived from untrusted input).""" segs = segments(ref) head, rest = str(segs[0]), segs[1:] if head == "item": if not scope.in_loop: raise RefError(f"{ref}: $.item outside for_each") return _walk(scope.item, rest, ref), scope.item_tainted if head == "index": if not scope.in_loop: raise RefError(f"{ref}: $.index outside for_each") return scope.index, False if head == "event": if scope.event is None: raise RefError(f"{ref}: this run has no triggering event") return _walk(scope.event, rest, ref), True if head == "trigger": return _walk(scope.trigger, rest, ref), False if head == "workflow": return _walk(scope.workflow, rest, ref), False if head not in scope.steps: raise RefError(f"{ref}: step {head!r} has no output (not run yet, or skipped)") out = scope.steps[head] tainted = bool(isinstance(out, dict) and out.get("__tainted__")) return _walk(out, rest, ref), tainted def render(value: Any, scope: Scope) -> tuple[Any, bool]: """Replace references in an argument value. Returns (value, tainted).""" if is_ref(value): return resolve(value, scope) if isinstance(value, str): tainted = False def sub(m: re.Match[str]) -> str: nonlocal tainted v, t = resolve(m.group(1), scope) tainted = tainted or t return "" if v is None else str(v) return TEMPLATE.sub(sub, value), tainted if isinstance(value, list): pairs = [render(v, scope) for v in value] return [p[0] for p in pairs], any(p[1] for p in pairs) if isinstance(value, dict): out: dict[str, Any] = {} tainted = False for k, v in value.items(): out[k], t = render(v, scope) tainted = tainted or t return out, tainted return value, False def _num(v: Any) -> float | None: if isinstance(v, bool): return None if isinstance(v, int | float): return float(v) if isinstance(v, str): try: return float(v) except ValueError: return None return None def evaluate(c: Condition, scope: Scope) -> bool: try: left, _ = resolve(c.left, scope) present = True except RefError: left, present = None, False if c.op == "exists": return present and left is not None if c.op == "not_exists": return not present or left is None if c.op == "truthy": return bool(left) if c.op == "falsy": return not left right, _ = render(c.right, scope) if c.op == "eq": return bool(left == right) if c.op == "ne": return bool(left != right) if c.op in ("in", "not_in"): inside = isinstance(right, list) and left in right return inside if c.op == "in" else not inside if c.op == "contains": if isinstance(left, str) and isinstance(right, str): return right.lower() in left.lower() return isinstance(left, list) and right in left a, b = _num(left), _num(right) if a is None or b is None: return False return {"gt": a > b, "gte": a >= b, "lt": a < b, "lte": a <= b}[c.op] def all_hold(conditions: list[Condition], scope: Scope) -> bool: return all(evaluate(c, scope) for c in conditions)