Skip to main content

openmoat_core/engine/
labels.rs

1//! Data labels (ADR-126): where the data a session holds came from, kept by
2//! source rather than by text, and the `@data-flow` atoms that let a rule
3//! name a source and a sink together.
4//!
5//! A hook sees tool calls and their outputs, never the model's own values,
6//! so it cannot tell which output a later call used. A label therefore says
7//! "this session read data from this source", not "this value came from it":
8//! once a session holds a label, every later sink of the session carries it,
9//! however the model reworded, summarised or re-encoded what it read. That is
10//! what exact text (ADR-057's tokens, ADR-061's staged files) cannot follow.
11//!
12//! The labels are kept on the session's [`Taint`] (no second store,
13//! ADR-113): the CLI folds them with the rest of the taint. Rules decide the
14//! atoms; a session whose labels no deny or review rule names is untouched.
15
16use serde::{Deserialize, Serialize};
17
18use super::trifecta::owned_by_secrets;
19use super::{CompiledPolicy, Taint, UntrustedKind};
20use crate::action::{Action, AtomicAction};
21use crate::pattern::any_match;
22use crate::verdict::{Decision, Verdict};
23
24/// The first word of a data-flow atom: `@data-flow <label> <sink> <target>`,
25/// with a fifth word `same-source` when the target is where the data came
26/// from (an MCP server's own tool, a brokered secret's own host), or
27/// `flow-trusted` when `mcp.flow_trusted` lists either MCP server.
28pub const DATA_FLOW_ATOM: &str = "@data-flow";
29
30/// Secret material (`secrets-paths`, a brokered secret).
31pub const LABEL_SECRET: &str = "secret";
32/// Private data other than secret material (ADR-113).
33pub const LABEL_PRIVATE: &str = "private";
34/// Any output someone else may have written: what the trifecta's `seen`
35/// counts (a forge's issue text, a read from a host the policy does not allow).
36pub const LABEL_EXTERNAL: &str = "external";
37/// A web page or search result.
38pub const LABEL_WEB: &str = "web";
39/// A host tool OpenMoat does not know.
40pub const LABEL_UNKNOWN_TOOL: &str = "unknown-tool";
41/// Untrusted content whose source kind is not known: a file an exposed
42/// session wrote (ADR-029), or a fold from before labels were kept.
43pub const LABEL_UNTRUSTED: &str = "untrusted";
44/// How the label of an MCP server's results starts: `mcp:<server>`.
45pub const LABEL_MCP_PREFIX: &str = "mcp:";
46
47/// The sink word of a write to a file that runs or steers later
48/// (`taint.protected_writes` and the built-in list).
49const SINK_PROTECTED_WRITE: &str = "protected-write";
50/// The fifth word of an atom whose target is where its data came from.
51const SAME_SOURCE: &str = "same-source";
52/// The fifth word of an MCP flow one of whose servers `mcp.flow_trusted`
53/// lists (ADR-058): the default rule ends at four words, so it skips the flow,
54/// and a person's own rule without `$` still names it.
55const FLOW_TRUSTED: &str = "flow-trusted";
56/// At most this many labels per session; the first ones are kept, so the
57/// first untrusted read always has its label.
58const MAX_LABELS: usize = 32;
59
60/// One label a session holds: its name and the first call that brought it in.
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct Label {
63    /// `secret`, `private`, `external`, `web`, `mcp:<server>`, `unknown-tool`.
64    pub name: String,
65    /// What brought it in, for reasons (`fetch evil.example`).
66    pub source: String,
67}
68
69impl Taint {
70    /// Add the label `name` brought in by `source`, unless the session holds
71    /// it already (first source wins) or holds the most it keeps.
72    pub(super) fn add_label(&mut self, name: &str, source: &str) {
73        if self.labels.len() < MAX_LABELS && !self.labels.iter().any(|l| l.name == name) {
74            self.labels.push(Label {
75                name: name.to_owned(),
76                source: source.to_owned(),
77            });
78        }
79    }
80
81    /// Every label of the session with its source, the ones its other facts
82    /// imply included: a fold from before labels were kept, or untrusted
83    /// content the CLI added itself (file provenance), carries secrets or
84    /// untrusted reads without a label, and those count as `secret`,
85    /// `private`, `untrusted` and `external`, so no source goes unlabelled.
86    #[must_use]
87    pub fn label_set(&self) -> Vec<Label> {
88        let mut out = self.labels.clone();
89        let mut implied = |name: &str, source: &str| {
90            if !out.iter().any(|l| l.name == name) {
91                out.push(Label {
92                    name: name.to_owned(),
93                    source: source.to_owned(),
94                });
95            }
96        };
97        if let Some(secret) = self.secrets.first() {
98            implied(LABEL_SECRET, &secret.source);
99        }
100        if let Some(private) = &self.private {
101            implied(LABEL_PRIVATE, private);
102        }
103        if let Some(untrusted) = &self.untrusted
104            && !self.labels.iter().any(|l| l.source == *untrusted)
105        {
106            implied(LABEL_UNTRUSTED, untrusted);
107        }
108        if let Some(seen) = &self.seen
109            && !self
110                .labels
111                .iter()
112                .any(|l| l.name == LABEL_EXTERNAL && l.source == *seen)
113        {
114            implied(LABEL_EXTERNAL, seen);
115            if self.untrusted.is_none() {
116                implied(LABEL_UNTRUSTED, seen);
117            }
118        }
119        out
120    }
121}
122
123/// The label of untrusted content of `kind` that `atom` read.
124pub(super) fn untrusted_label(kind: UntrustedKind, atom: &AtomicAction) -> String {
125    match (kind, atom) {
126        (UntrustedKind::Web, _) => LABEL_WEB.to_owned(),
127        (UntrustedKind::Mcp, AtomicAction::McpTool { name }) => {
128            format!("{LABEL_MCP_PREFIX}{}", mcp_server(name))
129        }
130        (UntrustedKind::UnknownTool, _) => LABEL_UNKNOWN_TOOL.to_owned(),
131        _ => LABEL_UNTRUSTED.to_owned(),
132    }
133}
134
135/// The server of an MCP tool's full name (`mcp__<server>__<tool>`).
136fn mcp_server(name: &str) -> &str {
137    name.split("__").nth(1).unwrap_or(name)
138}
139
140impl CompiledPolicy<'_> {
141    /// The decisions of the `@data-flow` atoms of `action`, whose atoms are
142    /// `atoms`, in a session holding `taint`'s labels: one atom per label
143    /// and per place the call can send data to or file it writes that runs
144    /// later. Only deny and review rules decide them (an allow or defer rule
145    /// never loosens a flow), so a label no rule names changes nothing.
146    pub(super) fn label_flows(
147        &self,
148        action: &Action,
149        atoms: &[AtomicAction],
150        taint: &Taint,
151    ) -> Vec<Decision> {
152        let labels = taint.label_set();
153        if labels.is_empty() {
154            return Vec::new();
155        }
156        let mut sinks: Vec<(&str, String)> = self
157            .egress_sinks(action, atoms)
158            .into_iter()
159            .map(|(sink, target)| (sink.as_str(), target))
160            .collect();
161        for atom in atoms {
162            if let AtomicAction::FsWrite { path } = atom
163                && any_match(&self.protected, path.as_str())
164            {
165                sinks.push((SINK_PROTECTED_WRITE, path.as_str().to_owned()));
166            }
167        }
168        let mut out = Vec::new();
169        for label in &labels {
170            for (sink, target) in &sinks {
171                let mut argv = vec![
172                    DATA_FLOW_ATOM.to_owned(),
173                    label.name.clone(),
174                    (*sink).to_owned(),
175                    target.clone(),
176                ];
177                if same_source(&label.name, target, taint) {
178                    argv.push(SAME_SOURCE.to_owned());
179                } else if self.flow_trusted(&label.name, target) {
180                    argv.push(FLOW_TRUSTED.to_owned());
181                }
182                let Some(hit) = self.flow_rules(&AtomicAction::Shell { argv }) else {
183                    continue;
184                };
185                let detail = format!(
186                    "this session holds data from {} ({}), and this call can pass it to {sink} {target}, \
187                     however it was reworded",
188                    describe(&label.name),
189                    label.source
190                );
191                let mut named = Decision::new(hit.verdict);
192                for rule in &hit.rules {
193                    named.push(rule, detail.clone());
194                }
195                out.push(named);
196            }
197        }
198        out
199    }
200
201    /// Whether an MCP flow from `label` to `target` has a server the policy's
202    /// `mcp.flow_trusted` lists, as source or destination (ADR-058).
203    fn flow_trusted(&self, label: &str, target: &str) -> bool {
204        let trusted = self.policy.mcp_flow_trusted();
205        [label, target].into_iter().any(|word| {
206            word.strip_prefix(LABEL_MCP_PREFIX)
207                .is_some_and(|server| trusted.iter().any(|t| t == server))
208        })
209    }
210
211    /// The deny and review groups that name `atom`: the user's allow and
212    /// defer lists are not read, so a broad allow (`shell: ["*"]`) cannot
213    /// take a flow out of a review rule.
214    fn flow_rules(&self, atom: &AtomicAction) -> Option<Decision> {
215        Self::hit(&self.deny, Verdict::Deny, atom)
216            .or_else(|| Self::hit(&self.repo_review, Verdict::Review, atom))
217            .or_else(|| Self::hit(&self.review, Verdict::Review, atom))
218    }
219}
220
221/// Whether `target` is where the data of `label` came from: an MCP server's
222/// own tool, or the host every brokered secret of the session belongs to.
223fn same_source(label: &str, target: &str, taint: &Taint) -> bool {
224    if label.starts_with(LABEL_MCP_PREFIX) {
225        return label == target;
226    }
227    label == LABEL_SECRET && owned_by_secrets(taint, target)
228}
229
230/// How a reason names the source of `label`.
231fn describe(label: &str) -> String {
232    match label {
233        LABEL_SECRET => "secret material".to_owned(),
234        LABEL_PRIVATE => "private data".to_owned(),
235        LABEL_EXTERNAL => "content someone else may have written".to_owned(),
236        LABEL_WEB => "the web".to_owned(),
237        LABEL_UNKNOWN_TOOL => "a tool OpenMoat does not know".to_owned(),
238        LABEL_UNTRUSTED => "untrusted content".to_owned(),
239        other => match other.strip_prefix(LABEL_MCP_PREFIX) {
240            Some(server) => format!("MCP server {server}"),
241            None => other.to_owned(),
242        },
243    }
244}