openmoat 0.29.0

Policy checks for AI coding agents: decides allow, defer, review or deny for each tool call the hook of Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot CLI and seven more agents reports, configures Claude Code's, Codex's and Cursor's own OS sandboxes from the same policy, and keeps a local audit log.
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! The proxy's [`Gate`] (ADR-045): what may reach the MCP server, and the
//! audit row each call leaves.
//!
//! A `tools/call` the pins let through passes only when both hold:
//! - the policy, with the lock intact, does not deny it as it is about to
//!   reach the server: the name `mcp__<server>__<tool>` and every path and URL
//!   its arguments name, read as the hook reads them;
//! - the hook let exactly this call through: a decision for the same tool and
//!   arguments, under an hour old and not used before (`mcp_tickets`). That
//!   decision carries what only the hook knows (the session's taint, a grant,
//!   the person's answer to a `review`), and it names the session: the row this
//!   call leaves carries the hook's session and call id. A call no hook decided
//!   (a host that skipped its hook, or arguments changed after it ran) is
//!   refused.
//!
//! `resources/read` is decided on the policy alone (a `file:` URI as the file
//! it names, any other as a host): a host also reads resources for the person,
//! with no hook. `prompts/get` and the server's own requests are recorded.
//!
//! The answer to each `tools/call` passed on a hook decision, a result or an
//! error (whose `message` and `data` the model reads too), has its pieces
//! kept under that decision's session (`mcp/flow.rs`, ADR-058), so the hook
//! can tell when a later call carries them to another server, and the
//! fingerprints of what it names kept as injected input (ADR-057), so a later
//! call that acts on a host, path or command it planted needs review. That
//! works for every agent, also one whose host reports no call output
//! (ADR-063, proposed).

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Mutex, PoisonError};
use std::time::Instant;

use anyhow::{Context as _, Result, bail};
use openmoat_audit::{KnownSecrets, NewEvent, Store, Ticket};
use openmoat_core::rule_id::{
    MCP_PROXY, MCP_SERVER_CHANGED, MCP_SERVER_REQUEST, MCP_TOOL_HELD, MCP_UNATTRIBUTED,
};
use openmoat_core::{Action, CompiledPolicy, Decision, Verdict};
use openmoat_hosts::Host;
use serde_json::Value;

use crate::environment::{Snapshot, WithOwnBinary};
use crate::home::Home;
use crate::mcp::names_tool;
use crate::mcp::relay::{Call, Gate, Method};
use crate::realpath::FsPathResolver;
use crate::{context, integrity, secrets};

/// Host id of the proxy's audit rows: the name of the rule its passed calls
/// carry.
const AUDIT_HOST: &str = MCP_PROXY;

/// What a call's `_meta` says of the hook session and call it is for (ADR-107).
enum Named<'c> {
    /// Neither key, or an agent that sends none: the argument match decides.
    Neither,
    /// One key, or one that is not a non-empty string: matches no decision.
    Incomplete,
    /// The hook's session id and tool call id.
    Both(&'c str, &'c str),
}

pub struct Gateway {
    home: Home,
    server: String,
    /// Where the host started the server: the context of a call no hook
    /// decision names a directory for.
    cwd: PathBuf,
    /// The session of rows no hook decision names.
    session: String,
    /// The agent whose configuration starts the server (`--host`): only its
    /// hook decisions let a call through. `None` for a definition wrapped
    /// before the proxy took `--host`, which takes any agent's.
    host: Option<Host>,
    /// The host and session of the last hook decision a call passed on: a
    /// host starts a stdio server for one session, so a decision of that
    /// session is taken before another's with the same arguments.
    served: Mutex<Option<(String, String)>>,
    /// What the server sent outside its tool results, and the sessions that
    /// have it (`surface.rs`, ADR-069).
    sent: Mutex<surface::Sent>,
    /// The host and session of each tool call passed on and not answered
    /// yet, by request id: where its result's pieces go (ADR-058).
    awaiting: Mutex<HashMap<String, Awaiting>>,
}

/// Whose tool call a result answers, and the call itself.
struct Awaiting {
    host: String,
    session: String,
    /// The call as the policy read it, for injected input (ADR-057).
    action: Action,
    /// The directory the hook decided it in.
    cwd: Option<String>,
}

/// The most passed calls awaiting a result the gateway keeps, as many as the
/// relay lets the server leave unanswered.
const MAX_AWAITING: usize = 4096;

/// What the gateway made of one call.
struct Outcome {
    action: Action,
    decision: Decision,
    /// The hook's decision the call matched.
    ticket: Option<Ticket>,
    /// The directory the call was decided in.
    cwd: Option<String>,
    /// The brokered secret values the row masks, from the policy that
    /// decided the call.
    known: KnownSecrets,
}

impl Gateway {
    pub fn new(home: Home, server: &str, host: Option<Host>) -> Result<Self> {
        Ok(Self {
            home,
            server: server.to_owned(),
            cwd: std::env::current_dir().context("reading the working directory")?,
            session: format!(
                "mcp-{server}-{}-{}",
                std::process::id(),
                crate::time::now_ms()
            ),
            host,
            served: Mutex::new(None),
            sent: Mutex::default(),
            awaiting: Mutex::new(HashMap::new()),
        })
    }

    /// Remember that the tool call `request`, `action` decided in `cwd`, was
    /// passed on for the hook's decision `ticket`, so its result is kept under
    /// that session.
    fn await_result(&self, request: &str, ticket: &Ticket, action: Action, cwd: Option<String>) {
        let mut awaiting = self.awaiting.lock().unwrap_or_else(PoisonError::into_inner);
        if awaiting.len() >= MAX_AWAITING
            && let Some(any) = awaiting.keys().next().cloned()
        {
            // A request the server never answered (cancelled, or lost).
            awaiting.remove(&any);
        }
        awaiting.insert(
            request.to_owned(),
            Awaiting {
                host: ticket.host.clone(),
                session: ticket.session_id.clone(),
                action,
                cwd,
            },
        );
    }

    /// The name the policy and the audit log give `call`.
    fn name(&self, call: &Call<'_>) -> String {
        match call.method {
            Method::Tool | Method::Prompt => format!("mcp__{}__{}", self.server, call.name),
            Method::Resource => format!("mcp__{}__read_resource", self.server),
        }
    }

    fn decide(&self, call: &Call<'_>, store: &Store) -> Result<Outcome> {
        let name = self.name(call);
        let none = Value::Null;
        let action = match call.method {
            Method::Tool => {
                openmoat_hosts::mcp_call_action(&name, call.arguments.unwrap_or(&none))?
            }
            Method::Resource => openmoat_hosts::mcp_resource_action(&self.server, call.name)?,
            Method::Prompt => {
                let decision = Decision::single(Verdict::Allow, MCP_PROXY, "a prompt, recorded");
                return Ok(self.outcome(Action::mcp(name), decision, None, None));
            }
        };
        // Taken before the policy is read: the hook's directory is the
        // context the call is decided in, as the hook decided it.
        let ticket = match call.method {
            Method::Tool => self.take_ticket(store, call)?,
            _ => None,
        };
        let cwd = match &ticket {
            Some(t) => store.get(t.event_id)?.and_then(|e| e.cwd),
            None => None,
        };
        let (decided, known) = self.policy(&action, cwd.as_deref())?;
        let decision = match (&ticket, call.method) {
            _ if decided.verdict == Verdict::Deny => decided,
            (None, Method::Tool) => Decision::single(
                Verdict::Deny,
                MCP_UNATTRIBUTED,
                "OpenMoat's hook made no decision on this exact call (the same tool and \
                 arguments, within the hour): the host did not run the hook for it, or sent \
                 other arguments than it checked, so it is not passed on",
            ),
            (Some(t), _) => Decision::single(
                Verdict::Allow,
                MCP_PROXY,
                format!(
                    "passed to the server: the hook decided `{}` for this call (event {})",
                    t.verdict, t.event_id.0
                ),
            ),
            (None, _) => Decision::single(Verdict::Allow, MCP_PROXY, "passed to the server"),
        };
        Ok(Outcome {
            action,
            decision,
            ticket,
            cwd,
            known,
        })
    }

    /// The hook's decision for `call`, taken so it lets no second call
    /// through: one of the agent the proxy serves (`--host`) that names this
    /// server's tool, of the session the proxy served last when one of its
    /// decisions matches. Two sessions that send the same call each take
    /// their own decision, so each result's pieces and fingerprints go to the
    /// session that asked for it.
    fn take_ticket(&self, store: &Store, call: &Call<'_>) -> Result<Option<Ticket>> {
        let arguments = openmoat_hosts::mcp_call_arguments(call.arguments);
        let digest = integrity::sha256_hex(arguments.as_bytes());
        let (server, tool) = (self.server.as_str(), call.name);
        let ours = |t: &Ticket| {
            t.host.parse::<Host>().is_ok_and(|host| {
                self.host.is_none_or(|own| own == host) && names_tool(host, &t.tool, server, tool)
            })
        };
        // A call that names its hook session and call (ADR-107) takes only
        // that decision, or none: never the argument match below.
        match self.names_its_call(call) {
            Named::Neither => {}
            Named::Incomplete => return Ok(None),
            Named::Both(session, call_id) => {
                return Ok(store.take_mcp_ticket(&digest, |ticket| {
                    ours(ticket)
                        && ticket.session_id == session
                        && ticket.call_id.as_deref() == Some(call_id)
                        && ticket.verdict == "allow"
                })?);
            }
        }
        let last = self
            .served
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone();
        let mut taken = None;
        if let Some((host, session)) = &last {
            taken = store.take_mcp_ticket(&digest, |t| {
                ours(t) && &t.host == host && &t.session_id == session
            })?;
        }
        if taken.is_none() {
            taken = store.take_mcp_ticket(&digest, ours)?;
        }
        if let Some(ticket) = &taken {
            *self.served.lock().unwrap_or_else(PoisonError::into_inner) =
                Some((ticket.host.clone(), ticket.session_id.clone()));
        }
        Ok(taken)
    }

    /// Whether `call`'s `_meta` names the hook session and call it was sent
    /// for, in the keys the agent's spec gives (`McpSpec::call_ids`).
    fn names_its_call<'c>(&self, call: &Call<'c>) -> Named<'c> {
        let keys = self
            .host
            .and_then(|host| host.spec().mcp.as_ref())
            .and_then(|mcp| mcp.call_ids);
        let (Some(keys), Some(meta)) = (keys, call.metadata) else {
            return Named::Neither;
        };
        if meta.get(keys.session).is_none() && meta.get(keys.call).is_none() {
            return Named::Neither;
        }
        let id = |key: &str| {
            meta.get(key)
                .and_then(Value::as_str)
                .filter(|id| !id.is_empty())
        };
        match (id(keys.session), id(keys.call)) {
            (Some(session), Some(call_id)) => Named::Both(session, call_id),
            _ => Named::Incomplete,
        }
    }

    /// The policy's decision for `action` in `cwd` (the server's own when
    /// `None`), with the lock checked first as the hook checks it, and the
    /// brokered secrets that policy names.
    fn policy(&self, action: &Action, cwd: Option<&str>) -> Result<(Decision, KnownSecrets)> {
        let verified = integrity::check(&self.home)?;
        if let Some(deny) = verified.checked.deny {
            return Ok((deny, self.known()));
        }
        let home = verified.home;
        let cwd = cwd.map_or_else(|| self.cwd.clone(), PathBuf::from);
        let ctx = context::eval_context(&home, Some(&cwd), None)?;
        let policy = crate::repo::effective_policy(&home, &ctx)?;
        let compiled = CompiledPolicy::compile(&policy, &ctx)?;
        let snapshot = Snapshot::load_in(&home)?;
        let programs = WithOwnBinary {
            snapshot: &snapshot,
            binary: &verified.lock.binary,
        };
        let known = secrets::known(&policy.secrets, &ctx.home)?;
        Ok((
            compiled.decide_with(action, &programs, &FsPathResolver),
            known,
        ))
    }

    /// The brokered secrets of the user's policy, for a row no policy decided;
    /// none when it cannot be read (the row names no arguments).
    fn known(&self) -> KnownSecrets {
        let Ok(policy) = self.home.load_policy() else {
            return KnownSecrets::default();
        };
        context::home_spellings()
            .and_then(|(home, _)| secrets::known(&policy.secrets, &home))
            .unwrap_or_default()
    }

    /// `outcome` for a call no policy decided.
    fn outcome(
        &self,
        action: Action,
        decision: Decision,
        ticket: Option<Ticket>,
        cwd: Option<String>,
    ) -> Outcome {
        Outcome {
            action,
            decision,
            ticket,
            cwd,
            known: self.known(),
        }
    }

    /// Record that the server was not started (ADR-049): a deny with the rule
    /// `moat guard` gives the tool calls of a server whose definition is not
    /// the accepted one, under the server's name.
    pub fn refused_start(&self, why: &str) -> Result<()> {
        let store = self.store()?.with_secrets(self.known());
        let name = format!("mcp__{}", self.server);
        let decision = Decision::single(Verdict::Deny, MCP_SERVER_CHANGED, why);
        store.record(&NewEvent {
            host: AUDIT_HOST,
            session_id: &self.session,
            call_id: None,
            cwd: self.cwd.to_str(),
            tool: &name,
            action: Some(&Action::mcp(name.clone())),
            decision: &decision,
            latency_us: 0,
        })?;
        Ok(())
    }

    /// The audit log.
    fn store(&self) -> Result<Store> {
        crate::audit_key::open_existing(&self.home).context("audit log unavailable")
    }

    /// Record `outcome`, masking the secrets its policy names as the hook's
    /// rows do.
    fn record(&self, store: Store, tool: &str, outcome: Outcome, started: Instant) -> Result<()> {
        let store = store.with_secrets(outcome.known);
        let ticket = outcome.ticket.as_ref();
        let latency_us = u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX);
        store.record(&NewEvent {
            host: AUDIT_HOST,
            session_id: ticket.map_or(self.session.as_str(), |t| t.session_id.as_str()),
            call_id: ticket.and_then(|t| t.call_id.as_deref()),
            cwd: outcome.cwd.as_deref(),
            tool,
            action: Some(&outcome.action),
            decision: &outcome.decision,
            latency_us,
        })?;
        Ok(())
    }
}

impl Gate for Gateway {
    fn check(&self, call: &Call<'_>, held: Option<&str>) -> Result<Option<String>> {
        let started = Instant::now();
        let store = self.store()?;
        let name = self.name(call);
        let outcome = match held {
            Some(why) => self.outcome(
                Action::mcp(name.clone()),
                Decision::single(Verdict::Deny, MCP_TOOL_HELD, why),
                None,
                None,
            ),
            None => self.decide(call, &store)?,
        };
        let refused = match outcome.decision.verdict {
            Verdict::Deny => Some(refusal(&outcome.decision)),
            _ => None,
        };
        if let (Some(ticket), None) = (&outcome.ticket, &refused) {
            // The session's model read the server's instructions before this
            // call: they are its untrusted content before the result is.
            self.credit(ticket, outcome.cwd.as_deref())?;
        }
        let awaits = match (&outcome.ticket, call.request, &refused) {
            (Some(ticket), Some(request), None) => Some((
                request,
                ticket.clone(),
                outcome.action.clone(),
                outcome.cwd.clone(),
            )),
            _ => None,
        };
        self.record(store, &name, outcome, started)?;
        if let Some((request, ticket, action, cwd)) = awaits {
            self.await_result(request, &ticket, action, cwd);
        }
        Ok(refused)
    }

    /// Keep the pieces of a passed tool call's answer, its result or its error
    /// object (ADR-058), and the fingerprints of what it names (ADR-057) under
    /// the session the hook's decision named; the call no longer awaits an
    /// answer either way. A response to anything else is not a tool result of
    /// a session and is let through as it is.
    fn result(&self, request: &str, result: &Value) -> Result<()> {
        let awaiting = self
            .awaiting
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(request);
        let Some(awaiting) = awaiting else {
            return Ok(());
        };
        let store = self.store()?.with_secrets(self.known());
        self.keep(&store, &awaiting, result)
    }

    fn instructions(&self, text: &str) {
        self.keep_instructions(text);
    }

    /// The page of a URL-mode elicitation is decided as a connection to its
    /// host, as a `resources/read` of an `https:` URI is: a deny refuses it
    /// (ADR-114). A review passes: the host shows the person the URL and
    /// asks before opening it.
    fn url_refusal(&self, url: &str) -> Result<Option<String>> {
        let action = openmoat_hosts::mcp_resource_action(&self.server, url)?;
        let (decision, _) = self.policy(&action, None)?;
        Ok((decision.verdict == Verdict::Deny).then(|| {
            format!(
                "the policy denies its host ({}: {})",
                decision.rules.join(", "),
                decision.reasons.join("; ")
            )
        }))
    }

    fn server_request(&self, method: &str, params: Option<&Value>) -> Result<()> {
        let decision = Decision::single(
            Verdict::Allow,
            MCP_SERVER_REQUEST,
            format!("MCP server `{}` asked the agent: {method}", self.server),
        );
        self.record_request(method, &decision)?;
        // What the host puts before the model or the person is the server's
        // text, untrusted as a result is.
        let text = params.map(crate::mcp::flow::value_text).unwrap_or_default();
        self.server_text(method, &text)
    }

    fn server_refused(&self, method: &str, why: &str) -> Result<()> {
        let decision = Decision::single(Verdict::Deny, MCP_SERVER_REQUEST, why);
        self.record_request(method, &decision)
    }
}

impl Gateway {
    /// Keep what `value`, untrusted content the server sent for `awaiting`'s
    /// session, holds: its pieces for the cross-server flow check (ADR-058)
    /// and the fingerprints of what it names (ADR-057).
    fn keep(&self, store: &Store, awaiting: &Awaiting, value: &Value) -> Result<()> {
        let pieces = crate::mcp::flow::hashed(crate::mcp::flow::value_pieces(value));
        if !pieces.is_empty() {
            store
                .add_mcp_flow(&awaiting.host, &awaiting.session, &self.server, &pieces)
                .context("recording what the tool's result held")?;
        }
        self.injected(store, awaiting, value)
    }

    /// Keep the injected-input fingerprints of a passed call's result, as the
    /// hook keeps those of a host's `PostToolUse` (`taint::injected`), with
    /// the policy of the directory the hook decided the call in. Under a
    /// drifted lock nothing is kept and the host gets an error in place of
    /// the result, as the hook denies every call then.
    fn injected(&self, store: &Store, awaiting: &Awaiting, result: &Value) -> Result<()> {
        let text = crate::mcp::flow::value_text(result);
        if text.trim().is_empty() {
            return Ok(());
        }
        let Ok(host) = awaiting.host.parse::<Host>() else {
            bail!(
                "the hook's decision names no known host (`{}`)",
                awaiting.host
            );
        };
        let verified = integrity::check(&self.home)?;
        if verified.checked.deny.is_some() {
            bail!("the policy lock does not match, so this tool's result is not kept");
        }
        let home = verified.home;
        let cwd = awaiting
            .cwd
            .as_deref()
            .map_or_else(|| self.cwd.clone(), PathBuf::from);
        let ctx = context::eval_context(&home, Some(&cwd), None)?;
        let policy = crate::repo::effective_policy(&home, &ctx)?;
        let compiled = CompiledPolicy::compile(&policy, &ctx)?;
        let output = crate::taint::injected::Output {
            host,
            session: &awaiting.session,
            action: &awaiting.action,
            cwd: &ctx.cwd,
            text: &text,
        };
        crate::taint::injected::record(&home, store, &compiled, &output)
            .context("keeping what the tool's result named")?;
        Ok(())
    }
}

/// What the host is told about a refused call.
fn refusal(decision: &Decision) -> String {
    let rules = decision.rules.join(", ");
    let reasons = decision.reasons.join("; ");
    format!("OpenMoat refused this call [{rules}]: {reasons}")
}

mod surface;

#[cfg(test)]
mod tests;