openmoat-core 0.27.0

Policy model and decision engine for OpenMoat. Pure: no I/O, no OS calls.
Documentation
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! From an [`Action`] to the atomic actions the policy decides: the shell
//! classifier for commands, one read or write per file a tool names, the
//! files an unquoted glob names, and the resolved path of every read or write
//! that goes through a symlink.

use super::EvalContext;
use crate::action::{Action, AtomicAction};
use crate::expand::Expansion;
use crate::host::web;
use crate::paths;
use crate::realpath::{PathResolver, physical};
use crate::shell::{ParseOutcome, ShellContext, Unparsed, classify_globs, powershell};

mod urls;

/// How an MCP call that only opens a page is decided (`mcp.browser_open`,
/// ADR-047): as a `fetch` of a plain web page, or as a `net` connection.
#[derive(Debug, Clone, Copy)]
pub(super) struct Opens {
    pub(super) as_fetch: bool,
}

/// Classify an [`Action`] into atomic actions for the given context, and list
/// the reads and writes among them whose path is a glob the shell expands.
fn classify_action(
    action: &Action,
    ctx: &EvalContext,
    opens_as: Opens,
) -> (ParseOutcome, Vec<(AtomicAction, bool)>) {
    let outcome = match action {
        Action::Shell { command } => {
            return classify_globs(
                command,
                &ShellContext {
                    home: &ctx.home,
                    cwd: &[Some(ctx.cwd.clone())],
                },
            );
        }
        // PowerShell is read as the POSIX commands it does the same as, and
        // stays `unparseable` whatever it reads (ADR-116)
        Action::ForeignShell { shell, command } if powershell::is_powershell(shell) => {
            return powershell::classify(
                command,
                &ShellContext {
                    home: &ctx.home,
                    cwd: &[Some(ctx.cwd.clone())],
                },
            );
        }
        Action::ForeignShell { shell, .. } => ParseOutcome::Unparseable {
            reason: format!("{shell} commands are not parsed; only POSIX shell is classified"),
            atoms: Vec::new(),
            needs_review: false,
        },
        Action::FsRead { path } => ParseOutcome::Parsed(file_atoms(path, ctx, read).collect()),
        Action::FsWrite { path } => ParseOutcome::Parsed(file_atoms(path, ctx, write).collect()),
        Action::Patch { writes } if writes.is_empty() => ParseOutcome::Unparseable {
            reason: "patch names no files".to_owned(),
            atoms: Vec::new(),
            needs_review: false,
        },
        Action::Patch { writes } => ParseOutcome::Parsed(
            writes
                .iter()
                .flat_map(|p| file_atoms(p, ctx, write))
                .collect(),
        ),
        Action::ReadFiles { paths } if paths.is_empty() => ParseOutcome::Unparseable {
            reason: "read names no files".to_owned(),
            atoms: Vec::new(),
            needs_review: false,
        },
        Action::ReadFiles { paths } => ParseOutcome::Parsed(
            paths
                .iter()
                .flat_map(|p| file_atoms(p, ctx, read))
                .collect(),
        ),
        // every host a client may read the URL as reaching (`host::web`)
        Action::Net { url } => match web::readings(url) {
            hosts if hosts.is_empty() => ParseOutcome::Unparseable {
                reason: format!("no host in url `{url}`"),
                atoms: Vec::new(),
                needs_review: false,
            },
            hosts => ParseOutcome::Parsed(
                hosts
                    .into_iter()
                    .map(|host| AtomicAction::Net { host })
                    .collect(),
            ),
        },
        // a fetch tool opens one page, read as a browser call that only opens
        // one (ADR-047, ADR-112): a domain name is a `fetch`, an address in
        // any spelling `net`, and the URLs inside it are judged too. Each
        // `net` host stays a `fetch` as well, so a `fetch` rule that named it
        // still applies; strictest wins
        Action::Fetch { url } => {
            let mut atoms = Vec::new();
            let unparsed = urls::opened(url, true, "fetch", ctx, &mut atoms);
            let fetches: Vec<AtomicAction> = atoms
                .iter()
                .filter_map(|atom| match atom {
                    AtomicAction::Net { host } => Some(AtomicAction::Fetch { host: host.clone() }),
                    _ => None,
                })
                .collect();
            atoms.extend(fetches);
            match unparsed {
                Some(Unparsed {
                    reason,
                    needs_review,
                }) => ParseOutcome::Unparseable {
                    reason,
                    atoms,
                    needs_review,
                },
                None if atoms.is_empty() => ParseOutcome::Unparseable {
                    reason: format!("no host in url `{url}`"),
                    atoms,
                    needs_review: false,
                },
                None => ParseOutcome::Parsed(atoms),
            }
        }
        Action::WebSearch { query } => ParseOutcome::Parsed(vec![AtomicAction::WebSearch {
            query: query.clone(),
        }]),
        Action::UnknownTool {
            host,
            tool,
            reads,
            writes,
            hosts,
            commands,
        } => {
            let first = AtomicAction::UnknownTool {
                host: host.clone(),
                tool: tool.clone(),
            };
            let named = Named {
                reads,
                writes,
                hosts,
                opens: &[],
                commands,
            };
            return named.atoms(first, "tool", ctx, opens_as);
        }
        Action::McpTool {
            name,
            reads,
            writes,
            hosts,
            opens,
            commands,
            ..
        } => {
            let first = AtomicAction::McpTool { name: name.clone() };
            let named = Named {
                reads,
                writes,
                hosts,
                opens,
                commands,
            };
            return named.atoms(first, "mcp", ctx, opens_as);
        }
        Action::Unchecked { action, .. } => return classify_action(action, ctx, opens_as),
    };
    (outcome, Vec::new())
}

/// What a tool's arguments name: the paths, hosts and shell commands an
/// adapter found in them (MCP and unknown tools).
struct Named<'a> {
    reads: &'a [String],
    writes: &'a [String],
    hosts: &'a [String],
    /// The page a read-only call opens (MCP `opens`, ADR-047).
    opens: &'a [String],
    commands: &'a [String],
}

impl Named<'_> {
    /// `first` (the tool's own atom) and the atoms of everything named, with
    /// the globs the commands' shell expands. `what` names the arguments in a
    /// reason (`mcp argument`).
    fn atoms(
        &self,
        first: AtomicAction,
        what: &str,
        ctx: &EvalContext,
        opens_as: Opens,
    ) -> (ParseOutcome, Vec<(AtomicAction, bool)>) {
        let mut atoms = vec![first];
        atoms.extend(self.reads.iter().flat_map(|p| file_atoms(p, ctx, read)));
        atoms.extend(self.writes.iter().flat_map(|p| file_atoms(p, ctx, write)));
        let mut unparsed: Option<Unparsed> = None;
        let mut note = |why: Option<Unparsed>| {
            // a URL that needs review wins over one that only cannot be read
            if let Some(why) = why
                && (why.needs_review || unparsed.is_none())
                && !unparsed.as_ref().is_some_and(|u| u.needs_review)
            {
                unparsed = Some(why);
            }
        };
        for url in self.hosts {
            note(urls::named(url, what, ctx, &mut atoms));
        }
        for url in self.opens {
            note(urls::opened(url, opens_as.as_fetch, what, ctx, &mut atoms));
        }
        let mut globs = Vec::new();
        let cwd = [Some(ctx.cwd.clone())];
        let shell = ShellContext {
            home: &ctx.home,
            cwd: &cwd,
        };
        for command in self.commands {
            let (outcome, expanded) = classify_globs(command, &shell);
            globs.extend(expanded);
            let (found, why) = outcome.into_parts();
            atoms.extend(found);
            if let Some(why) = why {
                // a line not read in full needs review, whichever part said so
                let needs_review =
                    why.needs_review || unparsed.as_ref().is_some_and(|u| u.needs_review);
                let reason = unparsed.take().map_or(why.reason, |u| u.reason);
                unparsed = Some(Unparsed {
                    reason,
                    needs_review,
                });
            }
        }
        let outcome = match unparsed {
            Some(Unparsed {
                reason,
                needs_review,
            }) => ParseOutcome::Unparseable {
                reason,
                atoms,
                needs_review,
            },
            None => ParseOutcome::Parsed(atoms),
        };
        (outcome, globs)
    }
}

/// The atoms of `action` in `ctx` with an extra atom for every path a glob
/// operand names (`crate::expand`) and for every read or write `paths`
/// resolves through a symlink, and why part of the action cannot be checked.
pub(super) fn checked_atoms(
    action: &Action,
    ctx: &EvalContext,
    opens_as: Opens,
    paths: &dyn PathResolver,
) -> (Vec<AtomicAction>, Option<Unparsed>) {
    let (outcome, globs) = classify_action(action, ctx, opens_as);
    let (mut atoms, unparsed) = outcome.into_parts();
    let mut expansion = Expansion::new(paths);
    for (glob, dot_dirs) in &globs {
        if let Some(pattern) = glob.subject() {
            // a glob that kept its `..` is listed where the OS would look
            let pattern = if paths::has_dotdot(pattern) {
                physical(pattern, paths)
            } else {
                pattern.to_owned()
            };
            let named = expansion.paths(&pattern, *dot_dirs);
            atoms.extend(named.into_iter().filter_map(|path| glob.with_path(path)));
        }
    }
    // A glob not expanded in full may name a file no atom checks, as a line
    // cut at the atom or length limit does: the call needs review, so padding
    // a glob past the bound cannot turn a deny into the catch-all's `defer`.
    let unparsed = match (unparsed, expansion.overflow()) {
        (Some(why), Some(_)) => Some(Unparsed {
            reason: why.reason,
            needs_review: true,
        }),
        (None, Some(reason)) => Some(Unparsed {
            reason,
            needs_review: true,
        }),
        (why, None) => why,
    };
    let atoms = with_environ_reads(with_resolved_paths(atoms, paths));
    (atoms, unparsed)
}

/// The read atoms of the paths an MCP call's values only look like
/// ([`Action::McpTool`]'s `value_reads`), normalised, followed through `..`
/// and symlinks like any other read. The engine checks them against `deny`
/// rules alone; they are never writes.
pub(super) fn value_read_atoms(
    action: &Action,
    ctx: &EvalContext,
    paths: &dyn PathResolver,
) -> Vec<AtomicAction> {
    let Action::McpTool { value_reads, .. } = action.shown() else {
        return Vec::new();
    };
    let atoms = value_reads
        .iter()
        .flat_map(|p| file_atoms(p, ctx, read))
        .collect();
    with_environ_reads(with_resolved_paths(atoms, paths))
}

/// Add `@proc-environ <path>` for every read of a process's environment
/// (`/proc/self/environ`, `/proc/1/task/1/environ`): the same variables as
/// `printenv`, secrets included, which `env-dump` denies. A shell atom, not a
/// path rule, so no OS sandbox is asked to deny a glob under `/proc`.
fn with_environ_reads(atoms: Vec<AtomicAction>) -> Vec<AtomicAction> {
    let environ: Vec<AtomicAction> = atoms
        .iter()
        .filter_map(|atom| match atom {
            AtomicAction::FsRead { path } if is_proc_environ(path) => Some(AtomicAction::Shell {
                argv: vec!["@proc-environ".to_owned(), path.clone()],
            }),
            _ => None,
        })
        .collect();
    atoms.into_iter().chain(environ).collect()
}

/// `/proc/<pid>/environ` or `/proc/<pid>/task/<tid>/environ`, any spelling of the ids.
fn is_proc_environ(path: &str) -> bool {
    let parts: Vec<&str> = path.split('/').collect();
    let id = |s: &str| !s.is_empty();
    match parts.as_slice() {
        ["", "proc", pid, "environ"] => id(pid),
        ["", "proc", pid, "task", tid, "environ"] => id(pid) && id(tid),
        _ => false,
    }
}

/// The read or write of a file a tool names: its collapsed path, and the form
/// that kept its `..`, if any, for [`with_resolved_paths`] to follow.
fn file_atoms(
    raw: &str,
    ctx: &EvalContext,
    atom: fn(String) -> AtomicAction,
) -> impl Iterator<Item = AtomicAction> {
    let project = ctx.project.as_deref();
    let collapsed = paths::normalise(raw, &ctx.home, project, &ctx.cwd);
    let traversal = paths::traversal(raw, &ctx.home, project, Some(&ctx.cwd));
    std::iter::once(atom(collapsed)).chain(traversal.map(atom))
}

fn read(path: String) -> AtomicAction {
    AtomicAction::FsRead { path }
}

fn write(path: String) -> AtomicAction {
    AtomicAction::FsWrite { path }
}

/// The path of a read or write atom.
fn file_path(atom: &AtomicAction) -> Option<&str> {
    match atom {
        AtomicAction::FsRead { path } | AtomicAction::FsWrite { path } => Some(path),
        _ => None,
    }
}

/// Add an atom for the resolved path of every read and write that goes
/// through a symlink. The literal atom stays: a rule may name either location.
/// A path that kept its `..` ([`paths::traversal`]) is not checked as
/// written: it is replaced by where the OS lands ([`physical`]), since each
/// `..` steps up from where a symlink before it points.
fn with_resolved_paths(atoms: Vec<AtomicAction>, paths: &dyn PathResolver) -> Vec<AtomicAction> {
    let atoms: Vec<AtomicAction> = atoms
        .into_iter()
        .filter_map(|atom| match file_path(&atom) {
            Some(path) if paths::has_dotdot(path) => atom.with_path(physical(path, paths)),
            _ => Some(atom),
        })
        .collect();
    let resolved: Vec<AtomicAction> = atoms
        .iter()
        .filter_map(|atom| {
            let (AtomicAction::FsRead { path } | AtomicAction::FsWrite { path }) = atom else {
                return None;
            };
            atom.with_path(paths.resolve(path).filter(|real| real != path)?)
        })
        .collect();
    atoms.into_iter().chain(resolved).collect()
}

/// The files the shell command `command` runs as code (`shell/executes.rs`),
/// as canonical paths: a glob word as the files it names, a `..` where the OS
/// lands, and a path through a symlink also as where it points, so a file is
/// found under any of the names a write of it was recorded with.
pub(super) fn executed_files(
    command: &str,
    ctx: &EvalContext,
    paths: &dyn PathResolver,
) -> Vec<String> {
    let cwd = [Some(ctx.cwd.clone())];
    let shell = ShellContext {
        home: &ctx.home,
        cwd: &cwd,
    };
    let mut expansion = Expansion::new(paths);
    let mut atoms = Vec::new();
    for (path, glob) in crate::shell::executes::executed(command, &shell) {
        if glob {
            let pattern = if paths::has_dotdot(&path) {
                physical(&path, paths)
            } else {
                path.clone()
            };
            atoms.extend(
                expansion
                    .paths(&pattern, true)
                    .into_iter()
                    .map(|path| AtomicAction::FsRead { path }),
            );
        }
        atoms.push(AtomicAction::FsRead { path });
    }
    let mut files: Vec<String> = with_resolved_paths(atoms, paths)
        .into_iter()
        .filter_map(|atom| match atom {
            AtomicAction::FsRead { path } => Some(path),
            _ => None,
        })
        .collect();
    files.sort_unstable();
    files.dedup();
    files
}