Skip to main content

agentmux_srv/drone/
transform.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Transform node's evaluator: shape lists and objects with a restricted
5//! expression language and no code execution
6//! (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md §3.9).
7//!
8//! **Module A of the engine.** The types, the bounds and [`taint_out`] are
9//! fixed here; [`evaluate`] is the module's job. Its acceptance tests are
10//! `transform_acceptance_tests.rs`. The language itself (the tokenizer, the
11//! parser and the evaluator) is in `expr.rs`, the operations are in `ops.rs`,
12//! and the module's own unit tests are in `tests.rs`; all three are private to
13//! this module.
14//!
15//! # Expression grammar
16//!
17//! Lowest precedence first; all binary operators are left associative.
18//!
19//! ```text
20//! expr    := or
21//! or      := and ( "||" and )*
22//! and     := not ( "&&" not )*
23//! not     := "!" not | cmp
24//! cmp     := sum ( ( "==" | "!=" | "<" | "<=" | ">" | ">=" | "contains" | "matches" | "in_set" ) sum )?
25//! sum     := prod ( ( "+" | "-" ) prod )*
26//! prod    := unary ( ( "*" | "/" | "%" ) unary )*
27//! unary   := "-" unary | atom
28//! atom    := number | string | "true" | "false" | "null" | list | call | path | "(" expr ")"
29//! list    := "[" ( expr ( "," expr )* )? "]"
30//! call    := name "(" ( expr ( "," expr )* )? ")"      // lower, trunc, default, exists
31//! path    := name ( "." name )*                         // item, item.user.login, index
32//! string  := 'text' or "text"                           // no escapes beyond \' \" \\
33//! ```
34//!
35//! * `item` is the current element and `index` its position (0-based) inside
36//!   `map`, `filter` and the key expressions (`by`). A missing path is `null`,
37//!   never an error.
38//! * `a contains b`: a string contains a substring, or a list holds an element.
39//!   `a matches 're'`: the Rust `regex` crate (linear time) on a string. The
40//!   pattern must be a string literal, compiled once when the chain is read, so
41//!   no element pays for a compile.
42//!   `a in_set [..]`: the list holds `a` (JSON equality).
43//! * `lower(s)`, `trunc(s, n)` (at most `n` characters), `default(x, d)` (`d`
44//!   when `x` is null), `exists(path)` (the path is not null). **No other
45//!   function exists**, no variable, no assignment, no loop, no recursion, no
46//!   call to the host and no network: an unknown name is [`TransformError::Expr`].
47//! * Arithmetic is on numbers only; `/` by zero and `%` by zero are errors; an
48//!   integer result stays an integer (`1 + 2` is `3`, not `3.0`).
49//! * Comparing values of different types is `false` for `==`, `true` for `!=`,
50//!   and an error for `<`, `<=`, `>`, `>=`.
51
52use std::collections::BTreeMap;
53
54use serde::{Deserialize, Serialize};
55use serde_json::Value;
56
57use super::value::{join, Tv};
58
59mod condition;
60mod expr;
61mod ops;
62
63pub use condition::evaluate_condition;
64use expr::State;
65use ops::apply;
66
67/// An input of at most this many items (§3.9).
68pub const MAX_ITEMS: usize = 10_000;
69/// An evaluation budget per node: one unit per element an operation visits and
70/// per expression node evaluated (§3.9).
71pub const MAX_OPERATIONS: u64 = 100_000;
72/// An output of at most the state cap, in bytes of JSON (§3.2).
73pub const MAX_OUTPUT_BYTES: usize = 256 * 1024;
74/// A compiled `matches` pattern may be at most this big: a pattern that would
75/// compile to more is an expression error, so a hostile one cannot make the
76/// compiler work without bound.
77const MAX_REGEX_BYTES: usize = 1024 * 1024;
78
79/// One step of a chain. A chain reads top to bottom, each result feeding the next.
80#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
81#[serde(tag = "op", rename_all = "snake_case")]
82pub enum TransformOp {
83    /// A list in, a list out: `expr` per element.
84    Map { expr: String },
85    /// Keep the elements for which `expr` is true.
86    Filter { expr: String },
87    /// Keep only these top-level keys of an object, or of every object in a list.
88    Pick { fields: Vec<String> },
89    /// The opposite of `pick`.
90    Omit { fields: Vec<String> },
91    /// Stable sort of a list by the value of `by` (an expression from `item`, such as `item.age`).
92    Sort {
93        by: String,
94        #[serde(default)]
95        desc: bool,
96    },
97    /// An object from the key of `by` (as a string) to the list of elements with it, in input order.
98    Group { by: String },
99    /// Drop repeats, keeping the first: by whole value, or by the value of `by`.
100    Unique {
101        #[serde(default)]
102        by: Option<String>,
103    },
104    /// `start..end` of a list (`end` absent: to the end); out-of-range ends are clamped.
105    Slice {
106        start: usize,
107        #[serde(default)]
108        end: Option<usize>,
109    },
110    /// The first element, or `null` for an empty list.
111    First,
112    /// The last element, or `null` for an empty list.
113    Last,
114    /// One level of lists flattened; non-list elements stay.
115    Flatten,
116    /// A list of strings or numbers as one string.
117    Join { sep: String },
118    /// A string as a list of strings.
119    Split { sep: String },
120    /// The input object with `with` merged over it (shallow; `with` wins).
121    Merge { with: Value },
122    /// The number of elements of a list, of keys of an object, or characters of a string.
123    Count,
124    /// The sum of a list of numbers, or of `by` over a list of objects.
125    Sum {
126        #[serde(default)]
127        by: Option<String>,
128    },
129    /// The smallest, by the same rule as `sum`; `null` for an empty list.
130    Min {
131        #[serde(default)]
132        by: Option<String>,
133    },
134    /// The largest, by the same rule as `sum`; `null` for an empty list.
135    Max {
136        #[serde(default)]
137        by: Option<String>,
138    },
139    /// Whether a list has an element for which `expr` is true (any element when `expr` is absent), or an object has a non-null path `expr` (a dotted path from the object itself, with no `item`).
140    Exists {
141        #[serde(default)]
142        expr: Option<String>,
143    },
144}
145
146#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
147pub struct Transform {
148    pub ops: Vec<TransformOp>,
149}
150
151/// Which bound a node went over.
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
153#[serde(rename_all = "snake_case")]
154pub enum BoundKind {
155    Items,
156    Operations,
157    Output,
158}
159
160#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
161pub enum TransformError {
162    /// A bound of §3.9 was passed. The node fails naming it.
163    #[error("transform: over the limit of {limit} {kind:?}")]
164    Bound { kind: BoundKind, limit: u64 },
165    /// An operation could not be applied (a map on a number, a sum of text...). `index` is its place in the chain.
166    #[error("transform: step {index}: {message}")]
167    Op { index: usize, message: String },
168    /// An expression did not parse or cannot be evaluated (an unknown function, a bad regex, a division by zero).
169    #[error("transform: step {index}: expression: {message}")]
170    Expr { index: usize, message: String },
171}
172
173/// What an operation does to the taint bits of the value it reads (the table
174/// of §3.9 and the derived-value rule of §4.5). Returns `(tainted, derived)`.
175///
176/// * Operations that can carry text (everything but the next line) pass the
177///   input's bits on: tainted in, tainted out.
178/// * `count`, `sum`, `min`, `max` and `exists` cannot carry text: over tainted
179///   input they give a clean value that is **`derived`**, so it is clean as
180///   data and still attacker-chosen as control or as a numeric argument.
181/// * Over clean input they stay clean; over derived input they stay derived.
182pub fn taint_out(op: &TransformOp, input: &Tv) -> (bool, bool) {
183    let carries_no_text = matches!(
184        op,
185        TransformOp::Count
186            | TransformOp::Sum { .. }
187            | TransformOp::Min { .. }
188            | TransformOp::Max { .. }
189            | TransformOp::Exists { .. }
190    );
191    let (tainted, derived) = join(&[input]);
192    if carries_no_text && tainted {
193        (false, true)
194    } else {
195        (tainted, derived)
196    }
197}
198
199/// The bits of a chain's output: [`taint_out`] applied step by step, starting
200/// from the input's.
201pub fn chain_taint(ops: &[TransformOp], input: &Tv) -> (bool, bool) {
202    let mut bits = (input.tainted, input.derived);
203    for op in ops {
204        let probe = Tv {
205            v: Value::Null,
206            tainted: bits.0,
207            derived: bits.1,
208        };
209        bits = taint_out(op, &probe);
210    }
211    bits
212}
213
214/// Run `t` over `input`. The output's bits are [`chain_taint`] of the chain.
215/// Every bound of §3.9 is checked and named in [`TransformError::Bound`].
216pub fn evaluate(t: &Transform, input: &Tv) -> Result<Tv, TransformError> {
217    let mut value = input.v.clone();
218    check_items(&value)?;
219    let mut state = State::default();
220    for (step, op) in t.ops.iter().enumerate() {
221        value = apply(op, &value, step, &mut state)?;
222        check_items(&value)?;
223        check_output(&value, step)?;
224    }
225    let (tainted, derived) = chain_taint(&t.ops, input);
226    Ok(Tv {
227        v: value,
228        tainted,
229        derived,
230    })
231}
232
233/// The item bound: an input list, or a list a step makes, of more than
234/// [`MAX_ITEMS`].
235fn check_items(value: &Value) -> Result<(), TransformError> {
236    match value {
237        Value::Array(items) if items.len() > MAX_ITEMS => Err(TransformError::Bound {
238            kind: BoundKind::Items,
239            limit: MAX_ITEMS as u64,
240        }),
241        _ => Ok(()),
242    }
243}
244
245/// The output bound, checked after every step so a runaway intermediate stops
246/// early rather than filling memory first.
247fn check_output(value: &Value, step: usize) -> Result<(), TransformError> {
248    let bytes = serde_json::to_vec(value)
249        .map_err(|error| op_step(step, &format!("the output cannot be measured: {error}")))?;
250    if bytes.len() > MAX_OUTPUT_BYTES {
251        Err(TransformError::Bound {
252            kind: BoundKind::Output,
253            limit: MAX_OUTPUT_BYTES as u64,
254        })
255    } else {
256        Ok(())
257    }
258}
259
260fn op_step(step: usize, message: &str) -> TransformError {
261    TransformError::Op {
262        index: step,
263        message: message.to_string(),
264    }
265}
266
267fn expr_step(step: usize, message: String) -> TransformError {
268    TransformError::Expr {
269        index: step,
270        message,
271    }
272}
273
274/// The expressions an op carries, for the validator and the canvas.
275pub fn expressions_of(op: &TransformOp) -> Vec<&str> {
276    match op {
277        TransformOp::Map { expr } | TransformOp::Filter { expr } => vec![expr.as_str()],
278        TransformOp::Sort { by, .. } | TransformOp::Group { by } => vec![by.as_str()],
279        TransformOp::Unique { by }
280        | TransformOp::Sum { by }
281        | TransformOp::Min { by }
282        | TransformOp::Max { by } => by.iter().map(String::as_str).collect(),
283        TransformOp::Exists { expr } => expr.iter().map(String::as_str).collect(),
284        _ => Vec::new(),
285    }
286}
287
288/// Every op as it is written in a graph, with a few words for the canvas.
289pub fn op_names() -> BTreeMap<&'static str, &'static str> {
290    [
291        ("map", "an expression per element"),
292        ("filter", "keep where true"),
293        ("pick", "keep fields"),
294        ("omit", "drop fields"),
295        ("sort", "by an expression"),
296        ("group", "by an expression"),
297        ("unique", "drop repeats"),
298        ("slice", "start to end"),
299        ("first", "first element"),
300        ("last", "last element"),
301        ("flatten", "one level"),
302        ("join", "list to string"),
303        ("split", "string to list"),
304        ("merge", "object over object"),
305        ("count", "how many"),
306        ("sum", "total"),
307        ("min", "smallest"),
308        ("max", "largest"),
309        ("exists", "any, or has a path"),
310    ]
311    .into_iter()
312    .collect()
313}
314
315#[cfg(test)]
316mod tests;