1use 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#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct Finding {
36 pub node: String,
37 pub why: String,
38}
39
40struct Flow<'a> {
42 nodes: Vec<(&'a FlowNode, Option<BlockKind>)>,
43 index: HashMap<&'a str, usize>,
44 out: HashMap<&'a str, Vec<&'a str>>,
45 past_no: HashMap<&'a str, Vec<&'a str>>,
48 incoming: HashMap<&'a str, Vec<&'a str>>,
49 roots: Vec<&'a str>,
50 foreach_of: HashMap<&'a str, &'a FlowNode>,
52 fields: &'a [PayloadField],
53 outside: HashSet<&'a str>,
55}
56
57fn 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
70fn 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
95pub(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 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
114fn 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
129fn 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 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 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 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 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 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 "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 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 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 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 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 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
291fn sends_credential(node: &FlowNode) -> bool {
294 const NAMES: [&str; 6] = ["auth", "token", "key", "secret", "cookie", "password"];
295 let reads_secret = |t: &str| refs_in(t).iter().any(|r| matches!(r.split('.').next().unwrap_or(""), "env" | "vault" | "secret" | "secrets" | "var" | "vars"));
297 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
311fn 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 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
336pub 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
368pub 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
374const CALL_DEPTH: usize = 8;
376
377fn 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
386pub type LoadDrone<'a> = &'a dyn Fn(&str, Option<i64>) -> Option<(String, DroneGraph)>;
388
389pub 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
415pub 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 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
441pub 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;