1use std::fmt;
10
11mod check_diff;
12mod ports;
13mod requests;
14mod secrets;
15mod staging;
16mod taint;
17mod titles;
18
19pub use secrets::{exposed_source, write_denied};
20
21pub use titles::untitled;
22
23use crate::kind::Kind;
24use crate::paths;
25use crate::pattern::{self, GlobPattern, ShellPattern};
26use crate::policy::{Defaults, Policy, RuleGroup};
27
28fn old_names(policy: &Policy, out: &mut Vec<Warning>) {
31 let upgrade = "`openmoat policy upgrade` renames it";
32 if policy.old_names.ask_list {
33 out.push(Warning {
34 rule: "ask".to_owned(),
35 message: format!("`ask:` is the old name of `review:` and is read as it; {upgrade}"),
36 });
37 }
38 if policy.old_names.ask_default {
39 out.push(Warning {
40 rule: "defaults".to_owned(),
41 message: format!(
42 "`ask` is the old name of the `review` verdict and is read as it; {upgrade}"
43 ),
44 });
45 }
46}
47
48const HOME: &str = "/__home__";
51const PROJECT: &str = "/__project__";
52
53#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct Warning {
56 pub rule: String,
58 pub message: String,
60}
61
62impl fmt::Display for Warning {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 write!(f, "rule `{}`: {}", self.rule, self.message)
65 }
66}
67
68#[must_use]
70pub fn warnings(policy: &Policy) -> Vec<Warning> {
71 let mut out = unknown_default_kinds(&policy.defaults);
72 old_names(policy, &mut out);
73 for (key, present) in [
74 ("approval", policy.approval.is_some()),
75 ("scope", policy.scope.is_some()),
76 ] {
77 if present {
78 out.push(Warning {
79 rule: key.to_owned(),
80 message: format!(
81 "`{key}` is reserved and has no effect yet; approvals are made with `openmoat allow` \
82 and the project root is the git root of the call's working directory"
83 ),
84 });
85 }
86 }
87 shadowed(&policy.review, &policy.allow, "review", "allow", &mut out);
88 shadowed(&policy.defer, &policy.allow, "defer", "allow", &mut out);
89 shadowed(&policy.allow, &policy.deny, "allow", "deny", &mut out);
90 for group in policy
91 .deny
92 .iter()
93 .chain(&policy.allow)
94 .chain(&policy.review)
95 .chain(&policy.defer)
96 {
97 excluded_positives(group, &mut out);
98 fetch_exclusions_net_matches(group, &mut out);
99 }
100 ports::malformed(policy, &mut out);
101 secrets::warn(policy, &mut out);
102 requests::warn(policy, &mut out);
103 if policy.sandbox.as_ref().is_some_and(|s| s.proxy_allow_ech) {
104 out.push(Warning {
105 rule: "sandbox.proxy_allow_ech".to_owned(),
106 message: "`openmoat proxy` forwards encrypted server names (ECH): an allowed host's \
107 provider may serve another site it hosts through it"
108 .to_owned(),
109 });
110 }
111 if policy
112 .sandbox
113 .as_ref()
114 .is_some_and(|s| s.proxy_serve_without_credential)
115 {
116 out.push(Warning {
117 rule: "sandbox.proxy_serve_without_credential".to_owned(),
118 message: "`openmoat proxy` serves requests without a session credential: any local \
119 process may use it, and a session that read a secret escapes its taint \
120 by sending no credential"
121 .to_owned(),
122 });
123 }
124 if policy.project_top() == crate::policy::ProjectTop::Writable {
125 out.push(Warning {
126 rule: "sandbox.project_top".to_owned(),
127 message: "`openmoat run` without bubblewrap grants the project's top whole: commands \
128 the agent starts can read `.env` and write `.git/hooks` there"
129 .to_owned(),
130 });
131 }
132 if policy.project_hook_off() == crate::policy::ProjectHookOff::Start {
133 out.push(Warning {
134 rule: "sandbox.project_hook_off".to_owned(),
135 message: "`openmoat run` starts an agent whose project turns its OpenMoat hook off: \
136 the hook then checks none of that session's calls, and only the sandbox \
137 holds"
138 .to_owned(),
139 });
140 }
141 check_diff::turned_off(policy, &mut out);
142 taint::metadata_tools(policy, &mut out);
143 staging::agent_temp(policy, &mut out);
144 if policy.trust_mcp_first_sight() {
145 out.push(Warning {
146 rule: "mcp.trust_first_sight".to_owned(),
147 message: "`openmoat mcp proxy` pins a new server's tools as it first lists them: a \
148 server that is malicious from the start gets its tool descriptions \
149 pinned without a person reading them"
150 .to_owned(),
151 });
152 }
153 let trusted = policy.mcp_flow_trusted();
154 if !trusted.is_empty() {
155 out.push(Warning {
156 rule: "mcp.flow_trusted".to_owned(),
157 message: format!(
158 "text these MCP servers return may reach another server's tools that write or \
159 send, and calls to them may carry other servers' text, with no \
160 `mcp-cross-server` review: {}",
161 trusted.join(", ")
162 ),
163 });
164 }
165 if policy.allow_mcp_sampling() {
166 out.push(Warning {
167 rule: "mcp.allow_sampling".to_owned(),
168 message: "`openmoat mcp proxy` passes a server's sampling requests to the agent: the \
169 model answers text the server chose, as a user turn"
170 .to_owned(),
171 });
172 }
173 out
174}
175
176fn listed(groups: &[RuleGroup], kinds: &[Kind], candidate: &str) -> bool {
179 groups.iter().any(|g| {
180 kinds.iter().any(|k| {
181 let list: Vec<GlobPattern> = g.patterns(*k).iter().filter_map(|p| glob(p)).collect();
182 pattern::any_match(&list, candidate)
183 })
184 })
185}
186
187fn unknown_default_kinds(defaults: &Defaults) -> Vec<Warning> {
188 let Defaults::PerKind(map) = defaults else {
189 return Vec::new();
190 };
191 let known: Vec<&str> = std::iter::once("*")
192 .chain(Kind::ALL.iter().map(|k| k.as_str()))
193 .collect();
194 map.keys()
195 .filter(|k| !known.contains(&k.as_str()))
196 .map(|k| Warning {
197 rule: "defaults".to_owned(),
198 message: format!(
199 "unknown kind `{k}` is ignored; known kinds: {}",
200 known.join(", ")
201 ),
202 })
203 .collect()
204}
205
206fn shadowed(
211 later: &[RuleGroup],
212 earlier: &[RuleGroup],
213 later_name: &str,
214 earlier_name: &str,
215 out: &mut Vec<Warning>,
216) {
217 for group in later {
218 for kind in Kind::ALL {
219 for pattern in group.patterns(kind) {
220 let hit = earlier.iter().find_map(|e| {
221 kind.rule_kinds().iter().find_map(|by_kind| {
222 let list = e.patterns(*by_kind);
223 if list.iter().any(|p| p.starts_with('!')) {
224 return None;
225 }
226 list.iter()
227 .find(|by| covers(kind, by, pattern))
228 .map(|by| (&e.id, *by_kind, by))
229 })
230 });
231 if let Some((by_rule, by_kind, by_pattern)) = hit {
232 out.push(Warning {
233 rule: group.id.clone(),
234 message: format!(
235 "{later_name} {kind} pattern `{pattern}` is unreachable: \
236 {earlier_name} rule `{by_rule}` {by_kind} pattern `{by_pattern}` \
237 matches everything it matches and {earlier_name} is evaluated first"
238 ),
239 });
240 }
241 }
242 }
243 }
244}
245
246fn excluded_positives(group: &RuleGroup, out: &mut Vec<Warning>) {
249 for kind in Kind::ALL {
250 let list = group.patterns(kind);
251 for target in list.iter().filter(|p| !p.starts_with('!')) {
252 let by = list.iter().find(|p| {
253 let (negated, body) = pattern::split_negation(p);
254 negated && covers(kind, body, target)
255 });
256 if let Some(by) = by {
257 out.push(Warning {
258 rule: group.id.clone(),
259 message: format!(
260 "{kind} pattern `{target}` is unreachable: exclusion `{by}` in the same \
261 list removes everything it matches, wherever it is placed"
262 ),
263 });
264 }
265 }
266 }
267}
268
269fn fetch_exclusions_net_matches(group: &RuleGroup, out: &mut Vec<Warning>) {
272 let net = group.patterns(Kind::Net);
273 for excluded in group.patterns(Kind::Fetch) {
274 let (true, body) = pattern::split_negation(excluded) else {
275 continue;
276 };
277 let net_excludes = net.iter().any(|p| {
278 let (negated, by) = pattern::split_negation(p);
279 negated && covers(Kind::Net, by, body)
280 });
281 let by = net
282 .iter()
283 .find(|p| !p.starts_with('!') && covers(Kind::Net, p, body));
284 if let Some(by) = by.filter(|_| !net_excludes) {
285 out.push(Warning {
286 rule: group.id.clone(),
287 message: format!(
288 "fetch exclusion `{excluded}` does not stop fetches of `{body}`: net pattern \
289 `{by}` of the same rule matches them too; add `{excluded}` to `net` as well"
290 ),
291 });
292 }
293 }
294}
295
296#[must_use]
301pub fn covers(kind: Kind, by: &str, target: &str) -> bool {
302 if kind == Kind::Shell {
303 match (ShellPattern::compile(by), ShellPattern::compile(target)) {
304 (Ok(by), Ok(target)) => by.covers(&target),
305 _ => false,
306 }
307 } else {
308 matches!((glob(by), glob(target)), (Some(by), Some(target)) if by.covers(&target))
309 }
310}
311
312fn glob(raw: &str) -> Option<GlobPattern> {
313 GlobPattern::compile(&paths::expand_pattern(raw, HOME, Some(PROJECT))?, false).ok()
314}
315
316#[cfg(test)]
317mod tests {
318 use super::*;
319
320 fn warn(yaml: &str) -> Vec<String> {
321 warnings(&Policy::parse(yaml).unwrap())
322 .iter()
323 .map(ToString::to_string)
324 .collect()
325 }
326
327 #[test]
328 fn review_shadowed_by_allow_shell_prefix() {
329 let w = warn(
330 "version: 1\nallow:\n - id: dev\n shell: ['cargo *']\n\
331 review:\n - id: push\n shell: ['cargo publish*', 'git push*']\n",
332 );
333 assert_eq!(w.len(), 1, "{w:?}");
334 assert!(w[0].contains("rule `push`") && w[0].contains("`cargo publish*`"));
335 assert!(w[0].contains("rule `dev`") && w[0].contains("`cargo *`"));
336 }
337
338 #[test]
339 fn allow_shadowed_by_deny_glob() {
340 let w = warn(
341 "version: 1\ndeny:\n - id: secrets\n fs.read: ['~/.ssh/**']\n\
342 allow:\n - id: keys\n fs.read: ['~/.ssh/config', '${project}/**']\n",
343 );
344 assert_eq!(w.len(), 1, "{w:?}");
345 assert!(w[0].contains("allow fs.read pattern `~/.ssh/config`"));
346 }
347
348 #[test]
349 fn net_patterns_shadow_fetch_patterns_but_not_the_reverse() {
350 let w = warn(
351 "version: 1\nallow:\n - id: reg\n net: ['*.crates.io']\n fetch: ['docs.rs']\n\
352 review:\n - id: web\n fetch: ['static.crates.io']\n net: ['docs.rs']\n",
353 );
354 assert_eq!(w.len(), 1, "{w:?}");
355 assert!(
356 w[0].contains("review fetch pattern `static.crates.io`"),
357 "{w:?}"
358 );
359 assert!(
360 w[0].contains("rule `reg` net pattern `*.crates.io`"),
361 "{w:?}"
362 );
363 }
364
365 #[test]
366 fn negated_lists_are_not_assumed_to_cover() {
367 let w = warn(
368 "version: 1\nallow:\n - id: proj\n fs.write: ['${project}/**', '!${project}/.git/**']\n\
369 review:\n - id: git\n fs.write: ['${project}/.git/**']\n",
370 );
371 assert!(w.is_empty(), "{w:?}");
372 }
373
374 #[test]
375 fn a_positive_inside_an_exclusion_of_its_list_is_reported() {
376 let w = warn(
377 "version: 1\nallow:\n - id: env\n fs.read: ['!**/.env', '**/.env', '${project}/**']\n",
378 );
379 assert_eq!(w.len(), 1, "{w:?}");
380 assert!(
381 w[0].contains("fs.read pattern `**/.env` is unreachable"),
382 "{w:?}"
383 );
384 assert!(w[0].contains("exclusion `!**/.env`"), "{w:?}");
385 }
386
387 #[test]
388 fn a_fetch_exclusion_a_net_pattern_still_matches_is_reported() {
389 let w = warn(
390 "version: 1\nallow:\n - id: web\n net: ['*.example']\n fetch: ['!api.example']\n",
391 );
392 assert_eq!(w.len(), 1, "{w:?}");
393 assert!(
394 w[0].contains("rule `web`: fetch exclusion `!api.example`"),
395 "{w:?}"
396 );
397 assert!(w[0].contains("net pattern `*.example`"), "{w:?}");
398 for quiet in [
399 "net: ['*.example', '!api.example']\n fetch: ['!api.example']",
400 "net: ['docs.example']\n fetch: ['!api.example']",
401 ] {
402 let w = warn(&format!("version: 1\nallow:\n - id: web\n {quiet}\n"));
403 assert!(w.is_empty(), "{quiet}: {w:?}");
404 }
405 }
406
407 #[test]
408 fn reserved_blocks_are_reported() {
409 let w =
410 warn("version: 1\napproval:\n channel: telegram\nscope:\n project_roots: ['.']\n");
411 assert_eq!(w.len(), 2, "{w:?}");
412 assert!(w[0].contains("`approval` is reserved") && w[1].contains("`scope` is reserved"));
413 assert_eq!(warn("version: 1\n"), Vec::<String>::new());
414 }
415
416 #[test]
417 fn unknown_default_kinds() {
418 let w = warn("version: 1\ndefaults: { network: deny, net: deny, '*': review }\n");
419 assert_eq!(w.len(), 1, "{w:?}");
420 assert!(w[0].contains("`network`"));
421 assert_eq!(warn("version: 1\ndefaults: allow\n"), Vec::<String>::new());
422 }
423
424 #[test]
425 fn secrets_the_proxy_refuses_or_the_agent_can_read() {
426 let secrets = "secrets:\n - id: gh\n host: api.github.com\n header: Authorization\n \
427 source: { file: ~/.config/moat/gh }\n - id: npm\n host: registry.npmjs.org\n \
428 header: Authorization\n source: { env: NPM_TOKEN }\n";
429 let w = warn(&format!("version: 1\n{secrets}"));
430 assert_eq!(w.len(), 4, "{w:?}");
431 assert!(
432 w[0].contains("secrets.gh") && w[0].contains("refuses it"),
433 "{w:?}"
434 );
435 assert!(
436 w[1].contains("`~/.config/moat/gh`, so the agent can read it"),
437 "{w:?}"
438 );
439 assert!(
440 w[3].contains("`NPM_TOKEN`, so the agent can read it"),
441 "{w:?}"
442 );
443 let covered = warn(&format!(
444 "version: 1\ndeny:\n - id: s\n fs.read: ['~/.config/moat/**']\n env.read: ['*_TOKEN']\n\
445 allow:\n - id: n\n net: ['api.github.com', '*.npmjs.org']\n{secrets}"
446 ));
447 assert!(covered.is_empty(), "{covered:?}");
448 let excluded = warn(&format!(
449 "version: 1\ndeny:\n - id: s\n fs.read: ['~/.config/**', '!~/.config/moat/**']\n \
450 env.read: ['*']\nallow:\n - id: n\n net: ['*', '!api.github.com']\n{secrets}"
451 ));
452 assert_eq!(excluded.len(), 2, "{excluded:?}");
453 }
454
455 #[test]
456 fn forwarding_encrypted_server_names_is_reported() {
457 let w = warn("version: 1\nsandbox: { proxy_allow_ech: true }\n");
458 assert_eq!(w.len(), 1, "{w:?}");
459 assert!(w[0].contains("ECH"), "{w:?}");
460 assert_eq!(
461 warn("version: 1\nsandbox: { proxy_allow_ech: false }\n"),
462 Vec::<String>::new()
463 );
464 }
465
466 #[test]
467 fn a_writable_project_top_is_reported() {
468 let w = warn("version: 1\nsandbox: { project_top: writable }\n");
469 assert_eq!(w.len(), 1, "{w:?}");
470 assert!(w[0].contains("`.git/hooks`"), "{w:?}");
471 assert_eq!(
472 warn("version: 1\nsandbox: { project_top: protected }\n"),
473 Vec::<String>::new()
474 );
475 }
476
477 #[test]
478 fn starting_over_a_hook_a_project_turns_off_is_reported() {
479 let w = warn("version: 1\nsandbox: { project_hook_off: start }\n");
480 assert_eq!(w.len(), 1, "{w:?}");
481 assert!(w[0].contains("only the sandbox"), "{w:?}");
482 assert_eq!(
483 warn("version: 1\nsandbox: { project_hook_off: refuse }\n"),
484 Vec::<String>::new()
485 );
486 }
487
488 #[test]
489 fn serving_without_a_session_credential_is_reported() {
490 let w = warn("version: 1\nsandbox: { proxy_serve_without_credential: true }\n");
491 assert_eq!(w.len(), 1, "{w:?}");
492 assert!(w[0].contains("escapes its taint"), "{w:?}");
493 assert_eq!(
494 warn("version: 1\nsandbox: { proxy_serve_without_credential: false }\n"),
495 Vec::<String>::new()
496 );
497 }
498
499 #[test]
500 fn trusting_a_new_mcp_servers_tools_is_reported() {
501 let w = warn("version: 1\nmcp: { trust_first_sight: true }\n");
502 assert_eq!(w.len(), 1, "{w:?}");
503 assert!(w[0].contains("mcp.trust_first_sight"), "{w:?}");
504 let quiet = "version: 1\nmcp: { trust_first_sight: false, allow_sampling: false }\n";
505 assert_eq!(warn(quiet), Vec::<String>::new());
506 let w = warn("version: 1\nmcp: { flow_trusted: [github, linear] }\n");
508 assert!(w.len() == 1 && w[0].contains("`mcp.flow_trusted`"), "{w:?}");
509 assert!(w[0].contains("github, linear"), "{w:?}");
510 let w = warn("version: 1\nmcp: { allow_sampling: true }\n");
511 assert!(w.len() == 1 && w[0].contains("mcp.allow_sampling"), "{w:?}");
512 }
513
514 #[test]
515 fn plain_http_injection_off_this_machine_is_reported() {
516 let policy = |host: &str| {
517 format!(
518 "version: 1\ndeny:\n - id: s\n env.read: ['*']\nallow:\n - id: n\n net: ['*']\n\
519 secrets:\n - id: s\n host: {host}\n header: X-K\n source: {{ env: K }}\n \
520 plain_http: true\n"
521 )
522 };
523 let w = warn(&policy("api.example.com"));
524 assert_eq!(w.len(), 1, "{w:?}");
525 assert!(w[0].contains("in clear text"), "{w:?}");
526 }
527
528 #[test]
529 fn plain_http_injection_to_loopback_is_reported_as_never_injected() {
530 let policy = |host: &str| {
531 format!(
532 "version: 1\ndeny:\n - id: s\n env.read: ['*']\nallow:\n - id: n\n net: ['*']\n\
533 secrets:\n - id: s\n host: {host}\n header: X-K\n source: {{ env: K }}\n \
534 plain_http: true\n"
535 )
536 };
537 for host in ["localhost", "api.localhost", "127.0.0.1", "127.8.9.10"] {
538 let w = warn(&policy(host));
539 assert_eq!(w.len(), 1, "{host}: {w:?}");
540 assert!(
541 w[0].contains("never connects to a loopback address"),
542 "{w:?}"
543 );
544 assert!(!w[0].contains("in clear text"), "{w:?}");
545 }
546 }
547
548 #[test]
549 fn tls_termination_to_loopback_is_reported_as_never_injected() {
550 let policy = |host: &str| {
551 format!(
552 "version: 1\ndeny:\n - id: s\n env.read: ['*']\nallow:\n - id: n\n net: ['*']\n\
553 secrets:\n - id: s\n host: {host}\n header: X-K\n source: {{ env: K }}\n \
554 tls: terminate\n"
555 )
556 };
557 assert_eq!(warn(&policy("api.example.com")), Vec::<String>::new());
558 let w = warn(&policy("api.localhost"));
559 assert_eq!(w.len(), 1, "{w:?}");
560 assert!(
561 w[0].contains("`tls: terminate` names api.localhost"),
562 "{w:?}"
563 );
564 }
565}