Skip to main content

agentmux_srv/drone/
rule_of_two.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Rule of Two, made checkable (docs/specs/SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md §6.2 and §6.3).
5//!
6//! A drone that reads outside text (a pull request title, a CI log, a webhook body, an API response, an agent's reply)
7//! must not let it reach a node that changes the world without a person in between. This reads a graph, before it is
8//! turned on, and says which nodes break that. Two rules:
9//!
10//! * **Writes outside.** An API call that is not a read, a command, an Agent block that may run commands, and a call to
11//!   another drone are nodes that change things outside AgentMux. One of them may not read a value that is outside
12//!   text unless an Approval block stands on every path from where that text came in to the node.
13//! * **Where outside text may not go.** Never into a header name, the address (scheme and host) of a request that
14//!   carries a credential or changes something, a Vault credential, the target of a Message or a Task, or the place a command runs, however it got there. It may go
15//!   into the text of a Message, a Task or a Notify: those say it is data.
16//!
17//! What counts as outside text is the engine's own rule (`scheduler::mark_bits`), read from the graph instead of a
18//! run: the trigger's fields that its schema does not call clean (`payload_schema`), and the output of an API call, an
19//! Agent, a Message reply, an app query, a command, a callee and an event wait, and whatever a Response, Variables,
20//! Transform, For-each or Join makes from them. A Condition, a Once, an Approval, a Task, a Notify and a Spawn give
21//! nothing outside. An Approval is the one thing that clears it: a person read the card.
22//!
23//! It is conservative. A reference it cannot place on a path counts as unapproved, and nothing here promises a graph
24//! that passes is safe, only that it does not skip the person where the spec says the person must be.
25
26use std::collections::{HashMap, HashSet, VecDeque};
27
28use serde_json::Value;
29
30use crate::drone::payload_schema::{is_tainted, PayloadField};
31use crate::drone::types::{BlockKind, DroneGraph, FlowNode};
32
33/// One node that breaks a rule, and why, in words for the person.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct Finding {
36    pub node: String,
37    pub why: String,
38}
39
40/// What the check knows about a graph.
41struct Flow<'a> {
42    nodes: Vec<(&'a FlowNode, Option<BlockKind>)>,
43    index: HashMap<&'a str, usize>,
44    out: HashMap<&'a str, Vec<&'a str>>,
45    /// Where an Approval's `error` edges go. A no and a silence fail the block, and only an `error` edge takes them, so these
46    /// blocks run exactly when the person did not approve: an Approval does not clear them.
47    past_no: HashMap<&'a str, Vec<&'a str>>,
48    incoming: HashMap<&'a str, Vec<&'a str>>,
49    roots: Vec<&'a str>,
50    /// A for-each's body block, to the for-each.
51    foreach_of: HashMap<&'a str, &'a FlowNode>,
52    fields: &'a [PayloadField],
53    /// The blocks whose output is outside text.
54    outside: HashSet<&'a str>,
55}
56
57/// Every `{{reference}}` in `text`, as the path it names (a filter after `|` is not part of it).
58fn refs_in(text: &str) -> Vec<String> {
59    let mut found = Vec::new();
60    let mut rest = text;
61    while let Some(open) = rest.find("{{") {
62        let Some(len) = rest[open + 2..].find("}}") else { break };
63        let token = &rest[open + 2..open + 2 + len];
64        found.push(token.split('|').next().unwrap_or("").trim().to_string());
65        rest = &rest[open + 2 + len + 2..];
66    }
67    found
68}
69
70/// Every text a node holds, with the name of the field it is in.
71fn texts_of<'a>(node: &'a FlowNode) -> Vec<(&'a str, &'a str)> {
72    fn walk<'a>(v: &'a Value, field: &'a str, out: &mut Vec<(&'a str, &'a str)>) {
73        match v {
74            Value::String(s) => out.push((field, s.as_str())),
75            Value::Array(a) => a.iter().for_each(|e| walk(e, field, out)),
76            Value::Object(m) => m.values().for_each(|e| walk(e, field, out)),
77            _ => {}
78        }
79    }
80    let mut out = Vec::new();
81    if let Some(map) = node.data.as_object() {
82        for (field, v) in map {
83            if field != "kind" {
84                walk(v, field.as_str(), &mut out);
85            }
86        }
87    }
88    out
89}
90
91pub(crate) fn kind_of(node: &FlowNode) -> Option<BlockKind> {
92    node.data.get("kind").and_then(Value::as_str).and_then(BlockKind::parse)
93}
94
95/// Whether `node` changes things outside AgentMux. A Drone block is counted: what the callee does is not known here.
96pub(crate) fn writes_outside(node: &FlowNode, kind: BlockKind) -> bool {
97    match kind {
98        BlockKind::Api => {
99            let method = node.data.get("method").and_then(Value::as_str).unwrap_or("GET").to_uppercase();
100            !matches!(method.as_str(), "GET" | "HEAD" | "OPTIONS")
101        }
102        BlockKind::Run | BlockKind::Drone => true,
103        // `allow_commands` is `true`, or the list of command lines the agent may run: either one lets it run commands.
104        BlockKind::Agent => match node.data.get("allow_commands") {
105            Some(Value::Bool(b)) => *b,
106            Some(Value::Array(list)) => !list.is_empty(),
107            Some(Value::String(s)) => !s.trim().is_empty(),
108            _ => false,
109        },
110        _ => false,
111    }
112}
113
114/// Where the scheme ends: just after the first `:` that is not inside a `{{reference}}`.
115fn scheme_end(url: &str) -> Option<usize> {
116    let mut i = 0;
117    while i < url.len() {
118        if url[i..].starts_with("{{") {
119            i = url[i + 2..].find("}}").map_or(url.len(), |close| i + 2 + close + 2);
120        } else if url[i..].starts_with(':') {
121            return Some(i + 1);
122        } else {
123            i += url[i..].chars().next().map_or(1, char::len_utf8);
124        }
125    }
126    None
127}
128
129/// The part of a request address that names where it goes: the scheme and the host. The request is made the way a browser
130/// reads a URL, so any run of slashes or backslashes after the scheme (`https:/x`, `https:///x`) is one `//`, and a backslash
131/// ends the host as a slash does. A delimiter inside a `{{reference | filter:arg}}`, or a `:` inside one, does not count.
132fn address_of(url: &str) -> &str {
133    let bytes = url.as_bytes();
134    let mut i = scheme_end(url).unwrap_or(0);
135    while i < bytes.len() && matches!(bytes[i], b'/' | b'\\') {
136        i += 1;
137    }
138    while i < bytes.len() {
139        if bytes[i..].starts_with(b"{{") {
140            // Skip the whole reference; one that never closes runs to the end of the address.
141            i = url[i + 2..].find("}}").map_or(bytes.len(), |close| i + 2 + close + 2);
142            continue;
143        }
144        if matches!(bytes[i], b'/' | b'\\' | b'?' | b'#') {
145            break;
146        }
147        i += 1;
148    }
149    &url[..i]
150}
151
152impl<'a> Flow<'a> {
153    fn new(graph: &'a DroneGraph, fields: &'a [PayloadField]) -> Self {
154        let nodes: Vec<(&FlowNode, Option<BlockKind>)> = graph.nodes.iter().map(|n| (n, kind_of(n))).collect();
155        let index: HashMap<&str, usize> = nodes.iter().enumerate().map(|(i, (n, _))| (n.id.as_str(), i)).collect();
156        let mut out: HashMap<&str, Vec<&str>> = HashMap::new();
157        let mut past_no: HashMap<&str, Vec<&str>> = HashMap::new();
158        let mut incoming: HashMap<&str, Vec<&str>> = HashMap::new();
159        let mut foreach_of = HashMap::new();
160        for e in &graph.edges {
161            let from_approval = index.get(e.source.as_str()).is_some_and(|i| nodes[*i].1 == Some(BlockKind::Approval));
162            if from_approval && e.source_handle.as_deref() == Some("error") {
163                past_no.entry(e.source.as_str()).or_default().push(e.target.as_str());
164            } else {
165                out.entry(e.source.as_str()).or_default().push(e.target.as_str());
166            }
167            incoming.entry(e.target.as_str()).or_default().push(e.source.as_str());
168        }
169        // A for-each's body has no edges of its own: it runs where the for-each does.
170        for &(n, kind) in &nodes {
171            if kind != Some(BlockKind::ForEach) {
172                continue;
173            }
174            if let Some(body) = n.data.get("body").and_then(Value::as_str) {
175                if let Some(&i) = index.get(body.trim()) {
176                    let b: &'a FlowNode = nodes[i].0;
177                    out.entry(n.id.as_str()).or_default().push(b.id.as_str());
178                    incoming.entry(b.id.as_str()).or_default().push(n.id.as_str());
179                    foreach_of.insert(b.id.as_str(), n);
180                }
181            }
182        }
183        let roots = nodes.iter().map(|(n, _)| n.id.as_str()).filter(|id| !incoming.contains_key(id)).collect();
184        let mut flow = Self { nodes, index, out, past_no, incoming, roots, foreach_of, fields, outside: HashSet::new() };
185        flow.settle();
186        flow
187    }
188
189    /// The blocks reached from `start` (themselves included), without passing through an Approval when `stop`.
190    fn reach(&self, start: &[&'a str], stop: bool) -> HashSet<&'a str> {
191        let mut seen: HashSet<&str> = HashSet::new();
192        let mut queue: VecDeque<&str> = start.iter().copied().collect();
193        while let Some(id) = queue.pop_front() {
194            if !seen.insert(id) {
195                continue;
196            }
197            let approval = self.index.get(id).is_some_and(|i| self.nodes[*i].1 == Some(BlockKind::Approval));
198            if approval {
199                queue.extend(self.past_no.get(id).into_iter().flatten().copied());
200                if stop {
201                    continue;
202                }
203            }
204            queue.extend(self.out.get(id).into_iter().flatten().copied());
205        }
206        seen
207    }
208
209    /// Whether text that came in at `source` (the trigger when none) can reach `at` with no Approval on some path. A node
210    /// the text cannot be placed on a path to counts as reached.
211    fn reaches_unapproved(&self, source: Option<&'a str>, at: &str) -> bool {
212        let start: Vec<&'a str> = match source {
213            None => self.roots.clone(),
214            Some(id) => self.out.get(id).cloned().unwrap_or_default(),
215        };
216        let without_approval = self.reach(&start, true);
217        without_approval.contains(at) || !self.reach(&start, false).contains(at)
218    }
219
220    /// Whether `{{path}}`, read by the block `at`, is outside text no Approval has cleared.
221    fn ref_is_outside(&self, path: &str, at: &str) -> bool {
222        let (head, rest) = path.split_once('.').unwrap_or((path, ""));
223        match head {
224            "trigger" => is_tainted(self.fields, rest) && self.reaches_unapproved(None, at),
225            "env" => false,
226            // Outside a loop body there is no local: the runtime reads `item` and `index` as block ids then.
227            "item" | "index" if self.foreach_of.contains_key(at) => self.foreach_of.get(at).is_some_and(|fe| self.items_outside(fe)),
228            "var" | "vars" => self
229                .nodes
230                .iter()
231                .filter(|(n, k)| matches!(k, Some(BlockKind::Variables | BlockKind::Transform)) && self.outside.contains(n.id.as_str()))
232                .any(|(n, _)| self.reaches_unapproved(Some(n.id.as_str()), at)),
233            id => self.outside.contains(id) && self.reaches_unapproved(self.index.get(id).map(|i| self.nodes[*i].0.id.as_str()), at),
234        }
235    }
236
237    fn items_outside(&self, foreach: &FlowNode) -> bool {
238        let items = foreach.data.get("items").and_then(Value::as_str).unwrap_or("");
239        !self.outside_refs(items, foreach.id.as_str()).is_empty()
240    }
241
242    /// The references in `text`, read by `at`, that are outside text.
243    fn outside_refs(&self, text: &str, at: &str) -> Vec<String> {
244        refs_in(text).into_iter().filter(|r| self.ref_is_outside(r, at)).collect()
245    }
246
247    /// The references anywhere in `node` that are outside text.
248    fn outside_refs_of(&self, node: &FlowNode) -> Vec<String> {
249        let mut found: Vec<String> = texts_of(node).iter().flat_map(|(_, t)| self.outside_refs(t, node.id.as_str())).collect();
250        found.sort();
251        found.dedup();
252        found
253    }
254
255    /// Whether the output of `node` is outside text, given what is known so far.
256    fn makes_outside_text(&self, node: &FlowNode, kind: BlockKind) -> bool {
257        match kind {
258            BlockKind::Agent | BlockKind::Api | BlockKind::Message | BlockKind::AppQuery | BlockKind::Run | BlockKind::Drone => true,
259            BlockKind::Wait => node.data.get("on").is_some(),
260            BlockKind::Condition | BlockKind::Approval | BlockKind::Task | BlockKind::Notify | BlockKind::Spawn => false,
261            // A Once answers with its key as well as true or false, so what its key reads is what it makes.
262            BlockKind::Response | BlockKind::Variables | BlockKind::Transform | BlockKind::Once => !self.outside_refs_of(node).is_empty(),
263            BlockKind::ForEach => {
264                let body = node.data.get("body").and_then(Value::as_str).unwrap_or("").trim();
265                self.items_outside(node) || self.outside.contains(body)
266            }
267            BlockKind::Join => self.incoming.get(node.id.as_str()).is_some_and(|from| from.iter().any(|f| self.outside.contains(f))),
268        }
269    }
270
271    /// Work out which blocks give outside text: a block can make it from another's, so go round until nothing changes.
272    fn settle(&mut self) {
273        for _ in 0..=self.nodes.len() {
274            let found: Vec<&'a str> = self
275                .nodes
276                .iter()
277                .filter_map(|&(n, kind)| kind.filter(|k| self.makes_outside_text(n, *k)).map(|_| n.id.as_str()))
278                .collect();
279            if found.len() == self.outside.len() {
280                return;
281            }
282            self.outside = found.into_iter().collect();
283        }
284    }
285}
286
287fn join(refs: &[String]) -> String {
288    refs.iter().map(|r| format!("{{{{{r}}}}}")).collect::<Vec<_>>().join(", ")
289}
290
291/// Whether a request carries a credential: its `auth`, a header that names one (`Authorization`, a key, a token, a cookie) or
292/// whose value reads the environment or the Vault, or any text in it that reads them.
293fn sends_credential(node: &FlowNode) -> bool {
294    const NAMES: [&str; 6] = ["auth", "token", "key", "secret", "cookie", "password"];
295    // A reference to the environment or the Vault, however it is spaced: the references are parsed, not matched as text.
296    let reads_secret = |t: &str| refs_in(t).iter().any(|r| matches!(r.split('.').next().unwrap_or(""), "env" | "vault" | "secret" | "secrets" | "var" | "vars"));
297    // A header value that reads anything but the trigger (a variable, a block's answer) may be a secret kept there.
298    let from_elsewhere = |t: &str| refs_in(t).iter().any(|r| r.split('.').next().unwrap_or("") != "trigger");
299    if node.data.get("auth").is_some() {
300        return true;
301    }
302    let header = node.data.get("headers").and_then(Value::as_object).is_some_and(|m| {
303        m.iter().any(|(name, value)| {
304            let name = name.to_lowercase();
305            NAMES.iter().any(|n| name.contains(n)) || reads_secret(&value.to_string()) || from_elsewhere(&value.to_string())
306        })
307    });
308    header || texts_of(node).iter().any(|(_, t)| reads_secret(t))
309}
310
311/// The places in `node` that outside text may not choose, each with what it is.
312fn forbidden_places<'a>(node: &'a FlowNode, kind: BlockKind) -> Vec<(&'static str, String)> {
313    let text = |key: &str| node.data.get(key).and_then(Value::as_str).unwrap_or("").to_string();
314    let keys = |key: &str| node.data.get(key).and_then(Value::as_object).map(|m| m.keys().cloned().collect::<Vec<_>>().join(" ")).unwrap_or_default();
315    match kind {
316        BlockKind::Api => {
317            let mut places = vec![("the name of a header", keys("headers")), ("a credential", node.data.get("auth").map(Value::to_string).unwrap_or_default())];
318            // Where a request goes matters when it carries a credential or changes something. A plain read with no
319            // credential may follow an address an earlier answer gave (a redirect to a log, a next page): what it can
320            // reach is limited by the engine's own refusal of private addresses, and it sends nothing secret.
321            if writes_outside(node, kind) || sends_credential(node) {
322                places.push(("the address a request goes to", address_of(&text("url")).to_string()));
323            }
324            places
325        }
326        BlockKind::Message => vec![("who a message goes to", text("to"))],
327        BlockKind::Task => vec![("who a task is for", text("target"))],
328        BlockKind::Run => vec![
329            ("where a command runs", format!("{} {} {}", text("where"), text("cwd"), text("image"))),
330            ("the name of an environment variable", keys("env")),
331        ],
332        _ => Vec::new(),
333    }
334}
335
336/// Every way `graph` breaks the Rule of Two when its trigger has `fields`.
337pub fn check(graph: &DroneGraph, fields: &[PayloadField]) -> Vec<Finding> {
338    let flow = Flow::new(graph, fields);
339    let mut findings = Vec::new();
340    for (node, kind) in &flow.nodes {
341        let Some(kind) = *kind else { continue };
342        let id = node.id.clone();
343        for (place, text) in forbidden_places(node, kind) {
344            let refs = flow.outside_refs(&text, &id);
345            if !refs.is_empty() {
346                findings.push(Finding {
347                    node: id.clone(),
348                    why: format!("{id}: {} is text from outside and may not choose {place}; only the graph's own words may. An Approval on the path before it clears it", join(&refs)),
349                });
350            }
351        }
352        if writes_outside(node, kind) {
353            let refs = flow.outside_refs_of(node);
354            if !refs.is_empty() {
355                findings.push(Finding {
356                    node: id.clone(),
357                    why: format!(
358                        "{id}: changes things outside AgentMux and reads text from outside ({}) with no Approval on the way. Put an Approval block before it, or give it only values the trigger declares clean",
359                        join(&refs)
360                    ),
361                });
362            }
363        }
364    }
365    findings
366}
367
368/// The Agent blocks of `graph` that read text from outside with no Approval on the way: the ones the turn-on prompt names.
369pub fn agents_reading_outside(graph: &DroneGraph, fields: &[PayloadField]) -> Vec<String> {
370    let flow = Flow::new(graph, fields);
371    flow.nodes.iter().filter(|(n, k)| *k == Some(BlockKind::Agent) && !flow.outside_refs_of(n).is_empty()).map(|(n, _)| n.id.clone()).collect()
372}
373
374/// How deep a chain of Drone blocks calling drones is followed.
375const CALL_DEPTH: usize = 8;
376
377/// What a drone reads as `{{trigger.*}}` when another drone calls it: the names the caller passes. What a caller passes
378/// that is outside text is the caller's own finding (its Drone block reads it), so these count as clean here.
379fn callee_fields(inputs: &[(String, String)]) -> Vec<PayloadField> {
380    inputs
381        .iter()
382        .map(|(name, _)| PayloadField { path: name.clone(), kind: "any".to_string(), clean: true, note: "what the calling drone passed".to_string() })
383        .collect()
384}
385
386/// A drone `load` finds by id (and saved version): its name and graph.
387pub type LoadDrone<'a> = &'a dyn Fn(&str, Option<i64>) -> Option<(String, DroneGraph)>;
388
389/// `check`, and the same for every drone `graph` calls, however deep, a pinned version as pinned: moving a graph into a
390/// drone it calls does not get it past the rule. A finding in a callee names it.
391pub fn check_tree(graph: &DroneGraph, fields: &[PayloadField], load: LoadDrone) -> Vec<Finding> {
392    let mut findings = check(graph, fields);
393    let mut seen = HashSet::new();
394    check_callees(graph, load, &mut seen, 0, &mut findings);
395    findings
396}
397
398fn check_callees(graph: &DroneGraph, load: LoadDrone, seen: &mut HashSet<(String, Option<i64>)>, depth: usize, findings: &mut Vec<Finding>) {
399    if depth >= CALL_DEPTH {
400        return;
401    }
402    for node in graph.nodes.iter().filter(|n| kind_of(n) == Some(BlockKind::Drone)) {
403        let Ok(spec) = crate::drone::executor::blocks::call::parse(node) else { continue };
404        if !seen.insert((spec.drone.clone(), spec.version)) {
405            continue;
406        }
407        let Some((name, callee)) = load(&spec.drone, spec.version) else { continue };
408        for f in check(&callee, &callee_fields(&spec.inputs)) {
409            findings.push(Finding { node: node.id.clone(), why: format!("{} (in the drone {name:?}, which {} calls)", f.why, node.id) });
410        }
411        check_callees(&callee, load, seen, depth + 1, findings);
412    }
413}
414
415/// Whether `graph` calls the drone `id` as it is saved now, directly or through the drones it calls (a pinned version is followed as pinned).
416pub fn calls(graph: &DroneGraph, id: &str, load: LoadDrone) -> bool {
417    fn walk(graph: &DroneGraph, id: &str, load: LoadDrone, seen: &mut HashSet<(String, Option<i64>)>, depth: usize) -> bool {
418        if depth >= CALL_DEPTH {
419            return false;
420        }
421        for node in graph.nodes.iter().filter(|n| kind_of(n) == Some(BlockKind::Drone)) {
422            let Ok(spec) = crate::drone::executor::blocks::call::parse(node) else { continue };
423            // A call pinned to a saved version runs that version, which a later save does not change.
424            if spec.drone == id && spec.version.is_none() {
425                return true;
426            }
427            if !seen.insert((spec.drone.clone(), spec.version)) {
428                continue;
429            }
430            if let Some((_, callee)) = load(&spec.drone, spec.version) {
431                if walk(&callee, id, load, seen, depth + 1) {
432                    return true;
433                }
434            }
435        }
436        false
437    }
438    walk(graph, id, load, &mut HashSet::new(), 0)
439}
440
441/// The findings as one message for a refusal, or `Ok` when there are none.
442pub fn refuse(graph: &DroneGraph, fields: &[PayloadField], load: LoadDrone) -> Result<(), String> {
443    let findings = check_tree(graph, fields, load);
444    if findings.is_empty() {
445        return Ok(());
446    }
447    let list: Vec<&str> = findings.iter().map(|f| f.why.as_str()).collect();
448    Err(format!("this drone cannot be turned on: {}", list.join("; ")))
449}
450
451#[cfg(test)]
452#[path = "rule_of_two_tests.rs"]
453mod tests;