Skip to main content

safe_chains/engine/
plain.rs

1//! Plain words for what `--explain` prints in facet terms.
2//!
3//! `--explain` shows the behaviour a command resolved to as facet terms (`locus.local = machine`),
4//! which mean nothing to someone who has not read the taxonomy. This is the dictionary of short,
5//! everyday phrases that replace them: one for every operation in every local place (the line that
6//! says what the command does), and one for every term of every other axis.
7//!
8//! The tests derive the vocabulary from the code (`FacetTerm::all()` per axis, and the axis names
9//! `Capability::set_facets` prints), so a new axis or term fails until it has a phrase.
10
11use super::facet::*;
12
13/// What a command does in a place: `(operation, locus.local, phrase)`.
14pub const ACTIONS: &[(&str, &str, &str)] = &[
15    ("observe", "process", "looks only at its own input"),
16    ("observe", "temp", "reads a file in a temporary folder"),
17    ("observe", "sandbox-scope", "reads a file in this session's scratch folder"),
18    ("observe", "worktree", "reads files in your project"),
19    ("observe", "adjacent", "reads files in a project next to this one"),
20    ("observe", "worktree-trusted", "reads your project's .git, hooks or CI settings"),
21    ("observe", "user", "reads a file in your home folder"),
22    ("observe", "machine", "reads files in a place safe-chains has no rule for"),
23    ("observe", "system-integrity", "reads the files that control login and startup"),
24    ("observe", "device", "reads a disk or device directly"),
25    ("observe", "kernel", "reads the operating system's core"),
26    ("create", "process", "makes something that lasts only while it runs"),
27    ("create", "temp", "creates a file in a temporary folder"),
28    ("create", "sandbox-scope", "creates a file in this session's scratch folder"),
29    ("create", "worktree", "creates files in your project"),
30    ("create", "adjacent", "creates files in a project next to this one"),
31    ("create", "worktree-trusted", "adds to your project's .git, hooks or CI settings"),
32    ("create", "user", "creates a file in your home folder"),
33    ("create", "machine", "creates files in a place safe-chains has no rule for"),
34    ("create", "system-integrity", "adds to the files that control login and startup"),
35    ("create", "device", "creates a device"),
36    ("create", "kernel", "adds to the operating system's core"),
37    ("mutate", "process", "changes only its own running state"),
38    ("mutate", "temp", "changes a file in a temporary folder"),
39    ("mutate", "sandbox-scope", "changes a file in this session's scratch folder"),
40    ("mutate", "worktree", "changes files in your project"),
41    ("mutate", "adjacent", "changes files in a project next to this one"),
42    ("mutate", "worktree-trusted", "changes your project's .git, hooks or CI settings"),
43    ("mutate", "user", "changes a file in your home folder"),
44    ("mutate", "machine", "changes files in a place safe-chains has no rule for"),
45    ("mutate", "system-integrity", "changes the files that control login and startup"),
46    ("mutate", "device", "writes to a disk or device directly"),
47    ("mutate", "kernel", "changes the operating system's core"),
48    ("destroy", "process", "removes only what it made while running"),
49    ("destroy", "temp", "deletes files in a temporary folder"),
50    ("destroy", "sandbox-scope", "deletes files in this session's scratch folder"),
51    ("destroy", "worktree", "deletes files in your project"),
52    ("destroy", "adjacent", "deletes files in a project next to this one"),
53    ("destroy", "worktree-trusted", "deletes from your project's .git, hooks or CI settings"),
54    ("destroy", "user", "deletes files in your home folder"),
55    ("destroy", "machine", "deletes files in a place safe-chains has no rule for"),
56    ("destroy", "system-integrity", "deletes files that control login and startup"),
57    ("destroy", "device", "erases a disk or device"),
58    ("destroy", "kernel", "removes part of the operating system's core"),
59    ("execute", "process", "runs code that stays inside the command"),
60    ("execute", "temp", "runs code from a temporary folder"),
61    ("execute", "sandbox-scope", "runs code from this session's scratch folder"),
62    ("execute", "worktree", "runs your project's code"),
63    ("execute", "adjacent", "runs code from a project next to this one"),
64    ("execute", "worktree-trusted", "runs your project's hooks"),
65    ("execute", "user", "runs code from your home folder"),
66    ("execute", "machine", "runs code from a place safe-chains has no rule for"),
67    ("execute", "system-integrity", "runs system programs in a way that can change them"),
68    ("execute", "device", "runs code straight from a device"),
69    ("execute", "kernel", "loads code into the operating system's core"),
70    ("communicate", "process", "talks to another system without touching your files"),
71    ("communicate", "temp", "sends or fetches data using a temporary folder"),
72    ("communicate", "sandbox-scope", "sends or fetches data using this session's scratch folder"),
73    ("communicate", "worktree", "sends or fetches data for your project"),
74    ("communicate", "adjacent", "sends or fetches data for a project next to this one"),
75    ("communicate", "worktree-trusted", "sends or fetches data using your project's .git settings"),
76    ("communicate", "user", "sends or fetches data using files in your home folder"),
77    ("communicate", "machine", "sends or fetches data using files in a place safe-chains has no rule for"),
78    ("communicate", "system-integrity", "sends or fetches data using login or startup files"),
79    ("communicate", "device", "talks to a device directly"),
80    ("communicate", "kernel", "talks to the operating system's core"),
81    ("configure", "process", "changes settings only for itself"),
82    ("configure", "temp", "changes settings kept in a temporary folder"),
83    ("configure", "sandbox-scope", "changes settings kept in this session's scratch folder"),
84    ("configure", "worktree", "changes your project's settings"),
85    ("configure", "adjacent", "changes the settings of a project next to this one"),
86    ("configure", "worktree-trusted", "changes your project's .git, hooks or CI settings"),
87    ("configure", "user", "changes your personal settings"),
88    ("configure", "machine", "changes this computer's settings"),
89    ("configure", "system-integrity", "changes how this computer logs in or starts up"),
90    ("configure", "device", "changes a device's settings"),
91    ("configure", "kernel", "changes the operating system's core settings"),
92    ("authorize", "process", "changes permissions only for itself"),
93    ("authorize", "temp", "changes permissions on a temporary folder"),
94    ("authorize", "sandbox-scope", "changes permissions on this session's scratch folder"),
95    ("authorize", "worktree", "changes permissions in your project"),
96    ("authorize", "adjacent", "changes permissions in a project next to this one"),
97    ("authorize", "worktree-trusted", "changes what your project's .git or CI trusts"),
98    ("authorize", "user", "changes your keys, passwords or trusted accounts"),
99    ("authorize", "machine", "changes what this computer trusts"),
100    ("authorize", "system-integrity", "changes who may log in or use admin rights"),
101    ("authorize", "device", "changes who may use a device"),
102    ("authorize", "kernel", "changes what the operating system's core trusts"),
103    ("control", "process", "signals only its own processes"),
104    ("control", "temp", "starts or stops a program from a temporary folder"),
105    ("control", "sandbox-scope", "starts or stops a program from this session's scratch folder"),
106    ("control", "worktree", "starts or stops your project's programs"),
107    ("control", "adjacent", "starts or stops programs from a project next to this one"),
108    ("control", "worktree-trusted", "starts or stops your project's hooks or services"),
109    ("control", "user", "starts or stops programs running as you"),
110    ("control", "machine", "starts or stops services on this computer"),
111    ("control", "system-integrity", "starts, stops or restarts the system itself"),
112    ("control", "device", "starts, stops or resets a device"),
113    ("control", "kernel", "loads or unloads parts of the operating system's core"),
114];
115
116/// Every other axis: `(axis, term, phrase)`. `operation` and `locus.local` are here too, for a
117/// line that names one without the other (a refusal saying which places a level allows).
118pub const TERMS: &[(&str, &str, &str)] = &[
119    ("operation", "observe", "reads or looks"),
120    ("operation", "create", "creates"),
121    ("operation", "mutate", "changes"),
122    ("operation", "destroy", "deletes"),
123    ("operation", "execute", "runs code"),
124    ("operation", "communicate", "talks to another system"),
125    ("operation", "configure", "changes settings that affect later commands"),
126    ("operation", "authorize", "changes what is trusted"),
127    ("operation", "control", "starts, stops or signals programs"),
128    ("locus.local", "process", "nowhere outside the command"),
129    ("locus.local", "temp", "a temporary folder"),
130    ("locus.local", "sandbox-scope", "this session's scratch folder"),
131    ("locus.local", "worktree", "your project"),
132    ("locus.local", "adjacent", "a project next to this one"),
133    ("locus.local", "worktree-trusted", "your project's .git, hooks or CI settings"),
134    ("locus.local", "user", "your home folder"),
135    ("locus.local", "machine", "a place safe-chains has no rule for"),
136    ("locus.local", "system-integrity", "the files that control login and startup"),
137    ("locus.local", "device", "a disk or device directly"),
138    ("locus.local", "kernel", "the operating system's core"),
139    ("locus.remote", "none", "no other computer"),
140    ("locus.remote", "fixed", "one other computer or service, named in the command"),
141    ("locus.remote", "arbitrary", "any computer or service the command chooses"),
142    ("locus.binding", "n/a", "does not apply"),
143    ("locus.binding", "pinned", "the account or host is named in the command"),
144    ("locus.binding", "ambient", "uses whichever account or host is set up already"),
145    ("locus.provenance", "n/a", "does not apply"),
146    ("locus.provenance", "established", "a remote you set up before"),
147    ("locus.provenance", "literal", "an address typed in the command"),
148    ("locus.provenance", "opaque", "an address that comes from a variable, so it cannot be seen"),
149    ("scale", "single", "one thing"),
150    ("scale", "bounded", "a set of things it names"),
151    ("scale", "unbounded", "everything it finds, without limit"),
152    ("retrieval", "metadata", "only names and details"),
153    ("retrieval", "record", "data records"),
154    ("retrieval", "bulk-content", "whole files or stored data"),
155    ("authority", "user", "as you"),
156    ("authority", "elevated", "with admin rights (sudo)"),
157    ("authority", "root", "as the system administrator"),
158    ("authority", "other-user", "as another user"),
159    ("isolation", "none", "with no sandbox"),
160    ("isolation", "view", "in a restricted view of the files"),
161    ("isolation", "namespace", "in a container"),
162    ("isolation", "userns", "in a container with its own users"),
163    ("isolation", "vm", "in a virtual machine"),
164    ("isolation", "ocap", "with only the access it is handed"),
165    ("reversibility", "none", "nothing to undo"),
166    ("reversibility", "trivial", "one command undoes it"),
167    (
168        "reversibility",
169        "recoverable",
170        "can usually be undone from version control, the trash or a snapshot, or by running the opposite command",
171    ),
172    ("reversibility", "effortful", "hard to undo; it may take a backup, a rebuild or a reverse operation"),
173    ("reversibility", "exposed", "cannot be taken back once seen"),
174    ("reversibility", "irreversible", "cannot be undone"),
175    ("persistence.level", "transient", "leaves nothing behind"),
176    ("persistence.level", "data", "leaves data behind"),
177    ("persistence.level", "reconfiguring", "changes how later commands behave"),
178    ("persistence.level", "installing", "installs programs, services or hooks"),
179    ("persistence.trigger.escape", "immediate", "finishes when the command does"),
180    ("persistence.trigger.escape", "detached", "keeps running after the session ends"),
181    ("persistence.trigger.escape", "recurring", "runs again on a schedule or an event"),
182    ("persistence.trigger.escape", "boot", "runs again every time the computer starts"),
183    ("persistence.trigger.kind", "none", "does not repeat"),
184    ("persistence.trigger.kind", "clock", "repeats on a schedule"),
185    ("persistence.trigger.kind", "event", "repeats when something happens"),
186    ("disclosure.audience", "none", "shows nothing"),
187    ("disclosure.audience", "local-process", "shows its output to the agent"),
188    ("disclosure.audience", "local-persistent", "saves output where other people on this computer can read it"),
189    ("disclosure.audience", "trusted-remote", "sends output to a service you trust"),
190    ("disclosure.audience", "shared-remote", "sends output to a shared service"),
191    ("disclosure.audience", "public", "makes output public"),
192    ("disclosure.channel", "none", "through no channel"),
193    ("disclosure.channel", "filesystem", "through a file"),
194    ("disclosure.channel", "stdout-to-model", "to the agent's screen"),
195    ("disclosure.channel", "network", "over the network"),
196    ("disclosure.channel", "clipboard", "through the clipboard"),
197    ("disclosure.channel", "ipc", "to another running program"),
198    ("disclosure.channel", "credential-store", "through your keychain or password store"),
199    ("disclosure.channel", "cross-process", "by reading another program's memory"),
200    ("disclosure.channel", "unknown", "by a route safe-chains cannot tell"),
201    ("disclosure.principal", "own", "your own data"),
202    ("disclosure.principal", "cross", "someone else's data"),
203    ("secret.level", "none", "touches no passwords or keys"),
204    ("secret.level", "uses-ambient", "uses sign-ins you already set up, without reading them"),
205    ("secret.level", "reads", "reads a password, key or token"),
206    ("secret.level", "writes", "stores a password, key or token"),
207    ("secret.level", "transmits", "sends a password, key or token somewhere"),
208    ("secret.channel", "none", "through no channel"),
209    ("secret.channel", "filesystem", "from a file"),
210    ("secret.channel", "stdout-to-model", "onto the agent's screen"),
211    ("secret.channel", "network", "over the network"),
212    ("secret.channel", "clipboard", "through the clipboard"),
213    ("secret.channel", "ipc", "from another running program"),
214    ("secret.channel", "credential-store", "from your keychain or password store"),
215    ("secret.channel", "cross-process", "from another program's memory"),
216    ("secret.channel", "unknown", "by a route safe-chains cannot tell"),
217    ("secret.principal", "own", "your own"),
218    ("secret.principal", "cross", "someone else's"),
219    ("network.direction", "none", "no network"),
220    ("network.direction", "loopback", "only to this computer"),
221    ("network.direction", "outbound", "connects out to the internet"),
222    ("network.direction", "inbound-listen", "listens for connections from outside"),
223    ("network.destination", "n/a", "no network"),
224    ("network.destination", "fixed", "to a destination named in the command"),
225    ("network.destination", "arbitrary", "to any destination"),
226    ("network.payload", "none", "sends nothing"),
227    ("network.payload", "fetches", "downloads data"),
228    ("network.payload", "sends-host-data", "sends data from this computer"),
229    ("execution.trust", "none", "runs no code"),
230    ("execution.trust", "self", "runs only its own code"),
231    ("execution.trust", "caller-inline", "runs code written in the command"),
232    ("execution.trust", "caller-file", "runs a script you point it at"),
233    ("execution.trust", "ambient-config", "runs code from files it finds, such as a Makefile or hooks"),
234    ("execution.trust", "network-sourced", "runs code downloaded from the internet"),
235    ("cost", "none", "costs nothing"),
236    ("cost", "local-resource", "uses a lot of this computer's resources"),
237    ("cost", "metered", "can cost money"),
238    ("cost", "quota", "uses up a quota"),
239    ("supply_chain.source", "unverified-url", "from an unchecked web address"),
240    ("supply_chain.source", "public-registry", "from a public package registry"),
241    ("supply_chain.source", "signed-repo", "from a signed repository"),
242    ("supply_chain.source", "private-registry", "from a private registry"),
243    ("supply_chain.source", "vendored", "from a copy kept in your project"),
244    ("supply_chain.pinning", "floating", "whatever the latest version is"),
245    ("supply_chain.pinning", "version", "a named version"),
246    ("supply_chain.pinning", "hash-verified", "a version checked against a hash"),
247    ("supply_chain.pinning", "digest", "one exact build, checked by its digest"),
248    ("supply_chain.exec_surface", "none", "runs nothing it downloads"),
249    ("supply_chain.exec_surface", "install-hook", "runs downloaded code while installing"),
250    ("supply_chain.exec_surface", "build-script", "runs downloaded code while building"),
251    ("supply_chain.exec_surface", "call-time", "runs downloaded code when your program runs"),
252    ("supply_chain.exec_surface", "run-artifact", "runs the downloaded program itself"),
253];
254
255/// An empty phrase is a row whose wording awaits the owner's approval: `--explain` keeps printing
256/// today's term for it. Approving the wording is replacing the empty string, and removing the row
257/// from `HELD` in the tests.
258pub fn is_held(phrase: &str) -> bool {
259    phrase.is_empty()
260}
261
262/// The phrase for what a command does: an operation in a local place.
263pub fn action(operation: &str, local: &str) -> Option<&'static str> {
264    ACTIONS.iter().find(|(o, l, _)| *o == operation && *l == local).map(|(_, _, p)| *p)
265}
266
267/// The phrase for one term of one axis.
268pub fn term(axis: &str, value: &str) -> Option<&'static str> {
269    TERMS.iter().find(|(a, t, _)| *a == axis && *t == value).map(|(_, _, p)| *p)
270}
271
272/// The phrase for a term whose wording is approved; `None` while it is held or unknown.
273pub fn spoken(axis: &str, value: &str) -> Option<&'static str> {
274    term(axis, value).filter(|p| !is_held(p))
275}
276
277/// What to print for a term: its phrase, or the term itself while its wording is held or unknown.
278pub fn words<'a>(axis: &str, value: &'a str) -> &'a str {
279    match term(axis, value) {
280        Some(p) if !is_held(p) => p,
281        _ => value,
282    }
283}
284
285/// The rows `--explain` prints for one capability's facets, in order. The operation and the local
286/// place become one row of what the command does; while that wording is held the two rows stay as
287/// they were. Every other axis keeps its name and prints its phrase. With `named_place` (the command
288/// reaches a place its Why line names, such as a credential store) a row that would call the
289/// place one without a rule says only what the command does.
290pub fn rows(facets: &[(&'static str, &'static str)], named_place: bool) -> Vec<(String, String)> {
291    let find = |axis: &str| facets.iter().find(|(a, _)| *a == axis).map(|(_, t)| *t);
292    let operation = find("operation");
293    let place = find("locus.local").unwrap_or("process");
294    let unruled = |p: &str| term("locus.local", "machine").is_some_and(|t| p.ends_with(t));
295    let does = operation.and_then(|o| match action(o, place) {
296        Some(p) if named_place && unruled(p) => spoken("operation", o),
297        phrase => phrase,
298    });
299    let does = does.filter(|p| !is_held(p));
300    let mut out = Vec::new();
301    for (axis, value) in facets {
302        match (*axis, does) {
303            ("operation", Some(phrase)) => out.push(("does".to_string(), phrase.to_string())),
304            ("locus.local", Some(_)) => {}
305            ("operation", None) => out.push((String::from("operation"), (*value).to_string())),
306            _ => out.push(((*axis).to_string(), words(axis, value).to_string())),
307        }
308    }
309    out
310}
311
312/// The body of the `resolved profile` section: each capability's rows, then the verdict of the band.
313pub fn render(ex: &super::bridge::ProfileExplanation, named_place: bool) -> String {
314    let mut out = String::new();
315    for (because, facets) in &ex.capabilities {
316        out.push_str(&format!("    ยท {because}\n"));
317        for (name, words) in rows(facets, named_place) {
318            out.push_str(&format!("        {name:<28} {words}\n"));
319        }
320    }
321    match &ex.blocked_by {
322        Some((level, miss)) => {
323            out.push_str(&format!("\n  refused by `{level}` (the most permissive auto-approving level):\n    {}\n", mismatch(miss)));
324        }
325        None => out.push_str("\n  admitted by the auto-approve band.\n"),
326    }
327    out
328}
329
330/// The refusal line for a facet that stopped a level, in plain words.
331pub fn mismatch(m: &super::level::FacetMismatch) -> String {
332    match term(m.facet, m.actual) {
333        Some(p) if !is_held(p) => match &m.plain_bound {
334            Some(bound) => format!("{p} ({bound})"),
335            None => m.to_string(),
336        },
337        _ => m.to_string(),
338    }
339}
340
341/// Every axis `--explain` can print, with every term it can take, from the facet types.
342pub fn vocabulary() -> Vec<(&'static str, Vec<&'static str>)> {
343    fn all<T: FacetTerm>() -> Vec<&'static str> {
344        T::all().iter().map(|t| t.as_str()).collect()
345    }
346    vec![
347        ("operation", all::<Operation>()),
348        ("locus.local", all::<LocalLocus>()),
349        ("locus.remote", all::<RemoteReach>()),
350        ("locus.binding", all::<RemoteBinding>()),
351        ("locus.provenance", all::<Provenance>()),
352        ("scale", all::<Scale>()),
353        ("retrieval", all::<RetrievalGranularity>()),
354        ("authority", all::<Authority>()),
355        ("isolation", all::<Isolation>()),
356        ("reversibility", all::<Reversibility>()),
357        ("persistence.level", all::<PersistenceLevel>()),
358        ("persistence.trigger.escape", all::<TriggerEscape>()),
359        ("persistence.trigger.kind", all::<TriggerKind>()),
360        ("disclosure.audience", all::<DisclosureAudience>()),
361        ("disclosure.channel", all::<Channel>()),
362        ("disclosure.principal", all::<Principal>()),
363        ("secret.level", all::<SecretLevel>()),
364        ("secret.channel", all::<Channel>()),
365        ("secret.principal", all::<Principal>()),
366        ("network.direction", all::<NetDirection>()),
367        ("network.destination", all::<NetDestination>()),
368        ("network.payload", all::<NetPayload>()),
369        ("execution.trust", all::<ExecutionTrust>()),
370        ("cost", all::<Cost>()),
371        ("supply_chain.source", all::<SupplySource>()),
372        ("supply_chain.pinning", all::<Pinning>()),
373        ("supply_chain.exec_surface", all::<ExecSurface>()),
374    ]
375}
376
377#[cfg(test)]
378mod tests;