Spaces:
Running

File size: 6,570 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
"""``$.`` 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)