Skip to main content

openmoat_core/engine/
injection.rs

1//! Injected input (ADR-057): which call outputs are untrusted, what of them is
2//! kept, and how a later call that acts on it is tightened.
3//!
4//! Only tightens: a later shell command or write whose network target, path
5//! or command came from untrusted content needs review, unless the policy
6//! allows that part of it outright (a host on the allow list, a project
7//! file, `cargo build`). A fetch, a search, an MCP call or an unknown tool
8//! is not checked: following a link or a search result is how reading works,
9//! and the host's own prompt decides those (`fetch: defer`).
10
11use super::{CompiledPolicy, EvalContext, UntrustedKind, checked_atoms};
12use crate::action::{Action, AtomicAction};
13use crate::injection::{
14    self, InjectedLookup, MAX_COMMAND_LEN, MAX_TOKENS_PER_OUTPUT, MIN_COMMAND_LEN, Token, TokenKind,
15};
16use crate::programs::NoResolver;
17use crate::realpath::PathResolver;
18use crate::verdict::{Decision, Verdict};
19
20/// Programs whose output is text from a forge's issues, pull requests and
21/// comments, which anyone may write: their hosts are on the allow list
22/// (`registries`), so they are named here.
23const REMOTE_TEXT_PROGRAMS: [&str; 3] = ["gh", "glab", "tea"];
24
25impl CompiledPolicy<'_> {
26    /// What the output of `action`, run in `cwd`, is, when it is content an
27    /// attacker may control (`fetch https://docs.example/page`): what session
28    /// taint calls untrusted (a fetch, a web search, an MCP result, an unknown
29    /// tool; a metadata tool too, which does not taint the session, since a
30    /// page sets the title and URL a tab list shows), and a shell command that
31    /// reads from a network host the policy does not allow or from a forge's
32    /// command-line client (`gh issue view`). `None` for everything else: a
33    /// read of a file, a local command. Never cut: a caller that keeps it
34    /// redacts the whole of it first, then shortens it (the audit store), so
35    /// a credential in the command is never split where no pattern sees it.
36    #[must_use]
37    pub fn output_source(
38        &self,
39        action: &Action,
40        cwd: &str,
41        paths: &dyn PathResolver,
42    ) -> Option<String> {
43        let ctx = EvalContext {
44            cwd: cwd.to_owned(),
45            ..self.ctx.clone()
46        };
47        let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
48        self.output_source_in(action, &atoms)
49    }
50
51    /// [`Self::output_source`] of `action`, whose checked atoms are `atoms`.
52    pub(super) fn output_source_in(
53        &self,
54        action: &Action,
55        atoms: &[AtomicAction],
56    ) -> Option<String> {
57        // a PowerShell line's output is judged on its text (`foreign.rs`), as
58        // before the reader gave it atoms (ADR-116): those only add to its verdict
59        if let Action::ForeignShell { command, .. } = action.shown() {
60            return self
61                .foreign_reads_remote(command)
62                .then(|| format!("the output of `{command}`"));
63        }
64        if let Some(exposed) = atoms.iter().find(|atom| UntrustedKind::of(atom).is_some()) {
65            let source = match action.shown() {
66                Action::Fetch { url } => format!("the page fetched from {url}"),
67                Action::WebSearch { query } => format!("the web search results for \"{query}\""),
68                Action::McpTool { name, .. } => format!("the result of MCP tool {name}"),
69                Action::UnknownTool { tool, .. } => format!("the output of tool {tool}"),
70                Action::Shell { command } => format!("the output of `{command}`"),
71                _ => exposed.describe(),
72            };
73            return Some(source);
74        }
75        let Action::Shell { command } = action.shown() else {
76            return None;
77        };
78        let reads_remote = atoms.iter().any(|atom| match atom {
79            AtomicAction::Net { host } | AtomicAction::Fetch { host } => {
80                !crate::host::is_loopback(host) && !self.allows(atom)
81            }
82            AtomicAction::Shell { argv } => argv
83                .first()
84                .is_some_and(|p| REMOTE_TEXT_PROGRAMS.contains(&program_name(p))),
85            _ => false,
86        });
87        reads_remote.then(|| format!("the output of `{command}`"))
88    }
89
90    /// The tokens of `output`, the output of `source` (an action
91    /// [`Self::output_source`] names), worth keeping: hosts other than the
92    /// ones `source` itself reached and than loopback, absolute paths outside
93    /// the project, and commands of its code spans as the classifier reads
94    /// them. Hosts are kept in their canonical spelling
95    /// (`host::canonical`, ADR-063 §4), as a later call's hosts are
96    /// compared. De-duplicated, at most [`MAX_TOKENS_PER_OUTPUT`]: URL hosts
97    /// first, then commands, paths, and words that look like hosts.
98    #[must_use]
99    pub fn injected_tokens(&self, source: &Action, cwd: &str, output: &str) -> Vec<Token> {
100        let found = injection::candidates(output);
101        let ctx = EvalContext {
102            cwd: cwd.to_owned(),
103            ..self.ctx.clone()
104        };
105        let (source_atoms, _) = checked_atoms(source, &ctx, self.opens_as(), &NoResolver);
106        // Never kept, so never a parent a later call links to (ADR-063 §4):
107        // `docs.github.com` named by a page on `github.com` links nothing new.
108        let foreign_hosts = match source.shown() {
109            Action::ForeignShell { command, .. } => foreign::named(command).remote,
110            _ => Vec::new(),
111        };
112        let own_hosts: Vec<String> = source_atoms
113            .iter()
114            .filter_map(host_of)
115            .chain(foreign_hosts.iter().map(String::as_str))
116            .map(crate::host::canonical)
117            .collect();
118        let host_token = |kind: TokenKind| {
119            let own_hosts = &own_hosts;
120            move |host: String| {
121                let text = crate::host::canonical(&host);
122                let foreign = !own_hosts.contains(&text) && !crate::host::is_loopback(&host);
123                foreign.then_some(Token { kind, text })
124            }
125        };
126        let commands = found
127            .commands
128            .iter()
129            .flat_map(|line| self.commands_of(line, &ctx));
130        // a relative path is placed against the directory the output was
131        // read in, as the agent would place it (ADR-113)
132        let paths = found.paths.iter().chain(&found.relative).filter_map(|raw| {
133            let path =
134                crate::paths::resolve(raw, &ctx.home, ctx.project.as_deref(), Some(&ctx.cwd))?;
135            (path.len() > 1 && !self.in_project(&path)).then(|| Token {
136                kind: TokenKind::Path,
137                text: self.path_key(&path),
138            })
139        });
140        let mut tokens: Vec<Token> = Vec::new();
141        let all = found
142            .url_hosts
143            .into_iter()
144            .filter_map(host_token(TokenKind::UrlHost))
145            .chain(commands)
146            .chain(paths)
147            .chain(
148                found
149                    .word_hosts
150                    .into_iter()
151                    .filter_map(host_token(TokenKind::WordHost)),
152            );
153        for token in all {
154            if tokens.len() >= MAX_TOKENS_PER_OUTPUT {
155                break;
156            }
157            if !tokens.contains(&token) {
158                tokens.push(token);
159            }
160        }
161        tokens
162    }
163
164    /// `decision` for `action`, tightened by the tokens of untrusted content
165    /// `seen` knows: a shell command or a write needs review when a host it
166    /// reaches, a file it writes or a command it runs came from that content,
167    /// and the policy does not allow that atom. A command counts only when the
168    /// call also reaches a host or a file outside the project that the policy
169    /// does not allow. A command of a shell the classifier cannot read
170    /// (PowerShell) is checked on its text: a host or a path outside the
171    /// project it names ([`foreign`]). Never loosens; a deny stays.
172    #[must_use]
173    pub fn with_injected(
174        &self,
175        decision: Decision,
176        action: &Action,
177        paths: &dyn PathResolver,
178        seen: &dyn InjectedLookup,
179    ) -> Decision {
180        let checked = matches!(
181            action.shown(),
182            Action::Shell { .. }
183                | Action::ForeignShell { .. }
184                | Action::FsWrite { .. }
185                | Action::Patch { .. }
186        );
187        if !checked || decision.verdict == Verdict::Deny {
188            return decision;
189        }
190        if let Action::ForeignShell { command, .. } = action.shown() {
191            return planted(decision, self.foreign_injected(command, seen));
192        }
193        let (atoms, _) = self.atoms(action, paths);
194        // A command copied from the content counts only when it reaches past
195        // what the policy allows outside the project: a host or a file. Docs
196        // tell people to run `git push origin main`; that is daily work.
197        let reaches_outside = atoms.iter().any(|atom| match atom {
198            AtomicAction::Net { .. } | AtomicAction::Fetch { .. } => !self.allows(atom),
199            AtomicAction::FsRead { path } | AtomicAction::FsWrite { path } => {
200                !self.in_project(path) && !self.allows(atom)
201            }
202            _ => false,
203        });
204        let found = atoms
205            .iter()
206            .filter(|atom| reaches_outside || !matches!(atom, AtomicAction::Shell { .. }))
207            .filter_map(|atom| self.injected(atom, seen))
208            .collect();
209        planted(decision, found)
210    }
211
212    /// The part of `atom` that came from untrusted content, unless the policy
213    /// allows the atom; `None` when no part did.
214    fn injected(&self, atom: &AtomicAction, seen: &dyn InjectedLookup) -> Option<Found> {
215        let (token, source) = match atom {
216            AtomicAction::Net { host } | AtomicAction::Fetch { host } => {
217                let kinds = [TokenKind::UrlHost, TokenKind::WordHost];
218                probe(seen, host_tokens(host, &kinds))
219                    .or_else(|| self.parent_source(atom, host, seen))
220            }
221            // a word that only looks like a host (`app.run`) is compared with
222            // hosts of URLs alone, which prose does not invent, and not with
223            // their parents: it is not a request to any of them
224            AtomicAction::NetWord { host } => probe(seen, host_tokens(host, &[TokenKind::UrlHost])),
225            AtomicAction::FsWrite { path } => probe(
226                seen,
227                [Token {
228                    kind: TokenKind::Path,
229                    text: self.path_key(path),
230                }],
231            ),
232            // a command is compared as the classifier reads it, which also
233            // yields the command a wrapper runs (`sudo`, `env`, `nohup`,
234            // `sh -c`) and leaves `VAR=value` out, at keep and at check alike
235            // and with its program's directory, `./` and `~` taken out, and
236            // its paths placed against the working directory (ADR-113)
237            AtomicAction::Shell { argv } => probe(
238                seen,
239                command_texts(argv, &self.ctx)
240                    .into_iter()
241                    .map(|text| Token {
242                        kind: TokenKind::Command,
243                        text,
244                    }),
245            ),
246            _ => None,
247        }?;
248        if self.allows(atom) {
249            return None;
250        }
251        let what = match token.kind {
252            TokenKind::UrlHost | TokenKind::WordHost => "host",
253            TokenKind::Path => "path",
254            TokenKind::Command => "command",
255        };
256        Some(Found {
257            part: format!("the {what} `{}`", token.text),
258            source,
259        })
260    }
261
262    /// The kept URL host a parent domain of `host` matches, and its source:
263    /// a kept URL host links a request to any of its subdomains (ADR-063 §4).
264    /// One probe per parent, nearest first; a parent the policy allows on its
265    /// own (`github.com`) links nothing, so a page naming an allowed site
266    /// does not tighten every call to its subdomains. Word hosts are compared
267    /// exactly: a name in prose is weaker evidence than a URL (ADR-057 §4).
268    fn parent_source(
269        &self,
270        atom: &AtomicAction,
271        host: &str,
272        seen: &dyn InjectedLookup,
273    ) -> Option<(Token, String)> {
274        let host = crate::host::canonical(host);
275        crate::host::parents(&host).find_map(|parent| {
276            let token = Token {
277                kind: TokenKind::UrlHost,
278                text: parent.to_owned(),
279            };
280            let source = seen.source_of(&token)?;
281            (!self.allows(&with_host(atom, parent))).then_some((token, source))
282        })
283    }
284
285    /// Whether the policy decides `atom` `allow` on its own.
286    fn allows(&self, atom: &AtomicAction) -> bool {
287        self.evaluate_atomic(atom)
288            .is_some_and(|d| d.verdict == Verdict::Allow)
289    }
290
291    /// The commands `line` runs, as [`Self::with_injected`] compares them.
292    fn commands_of(&self, line: &str, ctx: &EvalContext) -> Vec<Token> {
293        let action = Action::Shell {
294            command: line.to_owned(),
295        };
296        let (atoms, _) = checked_atoms(&action, ctx, self.opens_as(), &NoResolver);
297        atoms
298            .iter()
299            .filter_map(|atom| match atom {
300                AtomicAction::Shell { argv } => command_texts(argv, ctx).into_iter().next(),
301                _ => None,
302            })
303            .map(|text| Token {
304                kind: TokenKind::Command,
305                text,
306            })
307            .collect()
308    }
309
310    /// Whether `path` is the project or below it, under either spelling.
311    fn in_project(&self, path: &str) -> bool {
312        let key = self.path_key(path);
313        [&self.ctx.project, &self.ctx.real_project]
314            .into_iter()
315            .flatten()
316            .any(|root| {
317                let root = self.path_key(root);
318                let root = root.trim_end_matches('/');
319                key == root
320                    || key
321                        .strip_prefix(root)
322                        .is_some_and(|rest| rest.starts_with('/'))
323            })
324    }
325
326    /// `path` as tokens compare it: lowercase where file names ignore case.
327    pub(super) fn path_key(&self, path: &str) -> String {
328        if self.ctx.case_insensitive_paths {
329            path.to_lowercase()
330        } else {
331            path.to_owned()
332        }
333    }
334}
335
336/// The texts a command is compared by, when it has arguments and is long
337/// enough to be distinctive: its words normalised ([`normalised_words`]) and
338/// joined by spaces, which is what is kept; then, when that differs, its words
339/// as the classifier gave them, which rows kept before ADR-113 hold.
340fn command_texts(argv: &[String], ctx: &EvalContext) -> Vec<String> {
341    let fits = |text: &String| {
342        argv.len() >= 2 && (MIN_COMMAND_LEN..=MAX_COMMAND_LEN).contains(&text.len())
343    };
344    let normalised = normalised_words(argv, ctx).join(" ");
345    let written = argv.join(" ");
346    let mut out: Vec<String> = [normalised, written].into_iter().filter(fits).collect();
347    out.dedup();
348    out
349}
350
351/// A command's words in one spelling (ADR-113): the program without its
352/// directory (`/usr/bin/tar` is `tar`; lowercase where file names ignore
353/// case), a leading `./` taken off a word (`./out.tgz` is `out.tgz`), and a
354/// home path, an absolute path or one that climbs (`../x`) placed against the
355/// home and working directories. Options and other words stay as written:
356/// flags are not re-ordered, nothing is dropped.
357fn normalised_words(argv: &[String], ctx: &EvalContext) -> Vec<String> {
358    argv.iter()
359        .enumerate()
360        .map(|(n, word)| {
361            if n == 0 {
362                let program = program_name(word);
363                return if ctx.case_insensitive_paths {
364                    program.to_lowercase()
365                } else {
366                    program.to_owned()
367                };
368            }
369            let mut rest = word.as_str();
370            while let Some(tail) = rest.strip_prefix("./") {
371                rest = tail;
372            }
373            let placed = rest == "~"
374                || rest.starts_with("~/")
375                || rest.starts_with('/')
376                || rest.starts_with("../");
377            if placed
378                && let Some(path) =
379                    crate::paths::resolve(rest, &ctx.home, ctx.project.as_deref(), Some(&ctx.cwd))
380            {
381                return path;
382            }
383            rest.to_owned()
384        })
385        .collect()
386}
387
388/// One part of a call that came from untrusted content, worded as the reason
389/// names it (the host `x`), and where it came from.
390struct Found {
391    part: String,
392    source: String,
393}
394
395/// `decision` with one review per source of `found` merged in, naming each
396/// part once: "the command `x`,
397/// the host `h` and the path `p` came from …". A planted command makes several
398/// atoms (the command, the host it reaches, the file it writes), and the
399/// person reads one sentence for them, not one per atom.
400fn planted(decision: Decision, found: Vec<Found>) -> Decision {
401    let mut sources: Vec<(String, Vec<String>)> = Vec::new();
402    for Found { part, source } in found {
403        match sources.iter_mut().find(|(known, _)| *known == source) {
404            Some((_, parts)) if !parts.contains(&part) => parts.push(part),
405            Some(_) => {}
406            None => sources.push((source, vec![part])),
407        }
408    }
409    sources
410        .into_iter()
411        .map(|(source, parts)| {
412            Decision::single(
413                Verdict::Review,
414                crate::rule_id::INJECTED_INPUT,
415                format!(
416                    "{} came from {source}, untrusted content this session read; the call may \
417                     follow an instruction planted there",
418                    listed(&parts)
419                ),
420            )
421        })
422        .fold(decision, |mut acc, next| {
423            acc.merge(next);
424            acc
425        })
426}
427
428/// `a`, `a and b`, `a, b and c`.
429fn listed(parts: &[String]) -> String {
430    match parts {
431        [] => String::new(),
432        [one] => one.clone(),
433        [init @ .., last] => format!("{} and {last}", init.join(", ")),
434    }
435}
436
437/// The first of `tokens` the session kept, with its source.
438fn probe(
439    seen: &dyn InjectedLookup,
440    tokens: impl IntoIterator<Item = Token>,
441) -> Option<(Token, String)> {
442    tokens
443        .into_iter()
444        .find_map(|token| seen.source_of(&token).map(|source| (token, source)))
445}
446
447/// The tokens a call's `host` is compared with, one per kind of `kinds`: in
448/// its canonical spelling ([`crate::host::canonical`]), which tokens are kept
449/// in, then as written (lowercase, no trailing dot) when that differs, which
450/// rows kept before ADR-063 hold for an address spelled another way.
451pub(super) fn host_tokens(host: &str, kinds: &[TokenKind]) -> Vec<Token> {
452    let canonical = crate::host::canonical(host);
453    let written = host.trim_end_matches('.').to_ascii_lowercase();
454    let spellings = if written == canonical {
455        vec![canonical]
456    } else {
457        vec![canonical, written]
458    };
459    spellings
460        .iter()
461        .flat_map(|text| {
462            kinds.iter().map(|kind| Token {
463                kind: *kind,
464                text: text.clone(),
465            })
466        })
467        .collect()
468}
469
470/// `atom`, a `Net` or `Fetch` atom, reaching `host` instead.
471fn with_host(atom: &AtomicAction, host: &str) -> AtomicAction {
472    let host = host.to_owned();
473    if matches!(atom, AtomicAction::Fetch { .. }) {
474        AtomicAction::Fetch { host }
475    } else {
476        AtomicAction::Net { host }
477    }
478}
479
480/// The host a network atom reaches.
481fn host_of(atom: &AtomicAction) -> Option<&str> {
482    match atom {
483        AtomicAction::Net { host }
484        | AtomicAction::Fetch { host }
485        | AtomicAction::NetWord { host } => Some(host),
486        _ => None,
487    }
488}
489
490/// The file name of a program word (`/usr/bin/gh` → `gh`).
491fn program_name(word: &str) -> &str {
492    word.rsplit(['/', '\\']).next().unwrap_or(word)
493}
494
495mod foreign;
496#[cfg(test)]
497mod tests;