Skip to main content

base/interface/permission/
permit_all.rs

1//! The policy of a build without the permission engine: the engine's default
2//! mode with no rules. What reaches the policy as data still counts: a
3//! credential path the call names, a change under a host skill directory, a
4//! system file or destructive command line (`is_path_bypass_immune`), all
5//! refused in every mode, a `PreToolUse` hook's block or approve, the
6//! tool's own refusal, the sandbox `sandbox.require` holds a command to, the
7//! host's own policy, a host tool's declaration, and the deny rules a
8//! delegation adds, which nothing here can read and so refuse the call. A call
9//! that stays where the session works runs; any other is asked about, and
10//! refused where nobody can be asked.
11//!
12//! The default mode's table, and the reading of a call's words as paths, are
13//! kept here rather than taken from the engine, which is an optional unit base
14//! cannot depend on: the engine reads them through its own shell lexer and
15//! path resolution. What the refusals look for — `SensitivePaths`, the host's
16//! `protected_dirs`, `is_path_bypass_immune` — is base's, shared with it.
17//! PERMIT-1 (`crates/permissions/src/policy/tests/permit_all_parity.rs`)
18//! holds this copy to never let through more than the engine does.
19
20use async_trait::async_trait;
21use std::path::{Path, PathBuf};
22use std::sync::Arc;
23
24use super::{
25    Answerable, Attendance, Basis, ExecProfile, HookAnswer, Obligations, PermissionOutcome,
26    PermissionPolicy, PermissionRequest, Reach, Reason, Stage, Subject,
27};
28use crate::interface::exec::Enforcement;
29use crate::interface::tool::ToolOrigin;
30use crate::permission::{is_path_bypass_immune, RuleBehavior};
31
32pub struct PermitAll {
33    host: Option<Arc<dyn PermissionPolicy>>,
34}
35
36impl PermitAll {
37    pub fn new(host: Option<Arc<dyn PermissionPolicy>>) -> Self {
38        Self { host }
39    }
40}
41
42#[async_trait]
43impl PermissionPolicy for PermitAll {
44    async fn decide(&self, req: &PermissionRequest<'_>) -> PermissionOutcome {
45        match self.judge(req).await {
46            Judged::Permit(basis) => {
47                let profile = ExecProfile::for_permit(&basis, req.facts.runs, req.attendance);
48                PermissionOutcome::Permit {
49                    basis,
50                    profile,
51                    obligations: Obligations::after(req.facts.runs, profile),
52                }
53            }
54            Judged::Otherwise(outcome) => outcome,
55        }
56    }
57}
58
59enum Judged {
60    Permit(Basis),
61    Otherwise(PermissionOutcome),
62}
63
64impl PermitAll {
65    async fn judge(&self, req: &PermissionRequest<'_>) -> Judged {
66        if let Some((stage, message)) = refusal(req) {
67            return Judged::Otherwise(PermissionOutcome::deny(stage, message));
68        }
69        if let Some(host) = &self.host {
70            match host.decide(req).await {
71                PermissionOutcome::Permit { .. } => return Judged::Permit(Basis::NoPolicy),
72                PermissionOutcome::Deny { reason } => {
73                    return Judged::Otherwise(PermissionOutcome::Deny { reason })
74                }
75                PermissionOutcome::Prompt {
76                    reason, answerable, ..
77                } => return asked(req, reason, answerable, None),
78            }
79        }
80        match default_mode_question(req) {
81            None => Judged::Permit(Basis::NoPolicy),
82            Some(reason)
83                if reason.stage == Stage::ModeDefault
84                    && req.attendance == Attendance::Unattended
85                    && req.facts.runs.is_some()
86                    && matches!(req.facts.reach, Reach::Unknown | Reach::Inside)
87                    && req.ctx.confinement.holds_unattended() =>
88            {
89                Judged::Permit(Basis::UnattendedConfined)
90            }
91            Some(reason) => {
92                let remedy = match req.facts.origin {
93                    ToolOrigin::Host => {
94                        "declare it `permit: \"allow\"`, or build with the `permissions` unit"
95                    }
96                    _ => "build with the `permissions` unit",
97                };
98                asked(req, reason, Answerable::HookOrPerson, Some(remedy))
99            }
100        }
101    }
102}
103
104/// What every mode refuses, whoever attends: a credential, a host skill
105/// directory or a bypass-immune path named, a hook's block, a tool the
106/// session lacks, a delegation's rules nothing here reads, a command the
107/// required sandbox cannot hold, the tool's own refusal.
108fn refusal(req: &PermissionRequest<'_>) -> Option<(Stage, String)> {
109    if let Some(word) = credential_named(req) {
110        return Some((
111            Stage::Credentials,
112            format!("'{word}' holds credentials; no tool reads or writes it"),
113        ));
114    }
115    if let Some(word) = host_skill_dir_named(req) {
116        return Some((
117            Stage::HostSkillDir,
118            format!(
119                "'{word}' is under a directory of the host's: a skill directory it lists for \
120                     a session or one of its own packages; no tool writes under it, in any \
121                     permission mode"
122            ),
123        ));
124    }
125    if let HookAnswer::Block { reason, .. } = req.hook {
126        return Some((Stage::Hook, format!("Blocked by PreToolUse hook: {reason}")));
127    }
128    if req.tool.is_none() {
129        return Some((
130            Stage::UnknownTool,
131            format!("`{}` is not a tool this session has", req.tool_name),
132        ));
133    }
134    let held = req.delegate.is_some_and(|d| {
135        d.rules
136            .iter()
137            .any(|rule| rule.behavior != RuleBehavior::Allow)
138    });
139    if held {
140        return Some((
141            Stage::DelegateRule,
142            "this call is held to rules of the delegation it runs in, and this build has no \
143                 permission engine to read them"
144                .into(),
145        ));
146    }
147    if runs_in_required_sandbox(req) && req.ctx.confinement.session != Enforcement::Full {
148        return Some((
149            Stage::Confinement,
150            format!(
151                "Refused: {} would run under a sandbox policy this build cannot enforce all \
152                     of, and `sandbox.require` is on",
153                req.tool_name
154            ),
155        ));
156    }
157    if let Reach::Refused(why) = &req.facts.reach {
158        return Some((Stage::ToolRefusal, why.clone()));
159    }
160    if let Some(word) = bypass_immune_named(req) {
161        return Some((
162            Stage::BypassImmune,
163            format!(
164                "access to protected path '{word}' is blocked regardless of permission mode \
165                     — this path is bypass-immune"
166            ),
167        ));
168    }
169    None
170}
171
172/// What the engine's default mode asks about the call when no rule matches
173/// it, or `None` where it lets the call through: a call that stays where the
174/// session works, unless it runs on in the background, writes configuration,
175/// or would run under a strict profile the required sandbox does not hold;
176/// and a host tool its host declared `permit: "allow"`.
177fn default_mode_question(req: &PermissionRequest<'_>) -> Option<Reason> {
178    let facts = req.facts;
179    if facts.host_permits {
180        return None;
181    }
182    let writes_configuration = !facts.traits.read_only && names_configuration(req);
183    let background = facts.runs.is_some_and(|r| r.background);
184    let strict_unheld =
185        runs_in_required_sandbox(req) && req.ctx.confinement.strict != Enforcement::Full;
186    let contained = matches!(
187        facts.reach,
188        Reach::SessionOnly | Reach::Delegates | Reach::Operator | Reach::Inside
189    );
190    if contained && !background && !writes_configuration && !strict_unheld {
191        return None;
192    }
193    let stage = if writes_configuration {
194        Stage::Configuration
195    } else {
196        Stage::ModeDefault
197    };
198    let message = match (&facts.origin, &facts.question) {
199        (ToolOrigin::Host, _) => format!(
200            "`{}` is a host tool declared to be asked about (`permit: \"ask\"`)",
201            req.tool_name
202        ),
203        (_, Some(question)) => question.clone(),
204        (_, None) => format!("Allow {}?", req.tool_name),
205    };
206    Some(Reason::new(stage, message))
207}
208
209fn runs_in_required_sandbox(req: &PermissionRequest<'_>) -> bool {
210    req.facts.runs.is_some()
211        && !req.ctx.config.sandbox.disabled
212        && req.ctx.confinement.require_enforcement
213}
214
215/// A question: answered by a hook's approve where a hook may answer it, put
216/// to the person attending, and refused where nobody can be asked, with
217/// `remedy` for a question only the missing permission layer could answer.
218fn asked(
219    req: &PermissionRequest<'_>,
220    reason: Reason,
221    answerable: Answerable,
222    remedy: Option<&str>,
223) -> Judged {
224    if let (HookAnswer::Approve { hook }, Answerable::HookOrPerson) = (req.hook, answerable) {
225        return Judged::Permit(Basis::HookApproved(hook.clone()));
226    }
227    let why = match req.attendance {
228        Attendance::Attended => {
229            return Judged::Otherwise(PermissionOutcome::Prompt {
230                prompt_id: uuid::Uuid::new_v4().to_string(),
231                message: reason.message.clone(),
232                paths: Vec::new(),
233                reason,
234                answerable,
235            })
236        }
237        Attendance::Unattended => "nobody is attending this session to approve it",
238        Attendance::NoOneToAsk(why) => why,
239    };
240    let message = match remedy {
241        Some(remedy) => format!(
242            "{} — {why}. This build has no permission layer to allow it unattended: {remedy}",
243            reason.message
244        ),
245        None => format!("{} — {why}", reason.message),
246    };
247    Judged::Otherwise(PermissionOutcome::deny(Stage::Attendance, message))
248}
249
250/// The first word of the call that names a credential location, each taken
251/// as a path from the session's cwd, as is the value of a `--flag=value`.
252/// A command line is split on blanks and operators with its quotes and
253/// escapes dropped: coarser than the permission engine's reading, and only
254/// ever refusing more.
255fn credential_named(req: &PermissionRequest<'_>) -> Option<String> {
256    let sensitive = &req.ctx.config.sandbox.paths;
257    word_naming(req, |_, paths| {
258        paths.iter().any(|p| sensitive.is_credential(p))
259    })
260}
261
262/// The first word of a call that changes something naming a path under a
263/// host skill directory, read as `credential_named` reads its words.
264fn host_skill_dir_named(req: &PermissionRequest<'_>) -> Option<String> {
265    if req.facts.traits.read_only || matches!(req.facts.subject, Subject::ReadPath(_)) {
266        return None;
267    }
268    let protected = &req.ctx.session.env().protected_dirs;
269    word_naming(req, |_, paths| {
270        paths.iter().any(|p| protected.holding(p).is_some())
271    })
272}
273
274/// The call's content, or the first of its words, that is bypass-immune: the
275/// whole line for a destructive command, a word or its path for a system file.
276fn bypass_immune_named(req: &PermissionRequest<'_>) -> Option<String> {
277    let content = req.facts.subject.content()?;
278    if is_path_bypass_immune(content) {
279        return Some(content.to_string());
280    }
281    word_naming(req, |word, paths| {
282        is_path_bypass_immune(word)
283            || paths
284                .iter()
285                .any(|p| is_path_bypass_immune(&p.to_string_lossy()))
286    })
287}
288
289fn names_configuration(req: &PermissionRequest<'_>) -> bool {
290    let sensitive = &req.ctx.config.sandbox.paths;
291    word_naming(req, |word, paths| {
292        sensitive.names_configuration(word)
293            || paths
294                .iter()
295                .any(|p| sensitive.names_configuration(&p.to_string_lossy()))
296    })
297    .is_some()
298}
299
300fn word_naming(
301    req: &PermissionRequest<'_>,
302    names: impl Fn(&str, &[PathBuf]) -> bool,
303) -> Option<String> {
304    let content = req.facts.subject.content()?;
305    let words: Vec<String> = match &req.facts.subject {
306        Subject::Shell(line) => line
307            .split(|c: char| c.is_whitespace() || ";|&<>()`".contains(c))
308            .map(|word| word.replace(['\'', '"', '\\'], ""))
309            .collect(),
310        _ => vec![content.to_string()],
311    };
312    words.into_iter().find(|word| {
313        std::iter::once(word.as_str())
314            .chain(word.split_once('=').map(|(_, value)| value))
315            .filter(|w| !w.is_empty())
316            .any(|w| names(w, &spellings(w, &req.ctx.cwd)))
317    })
318}
319
320fn spellings(word: &str, cwd: &Path) -> Vec<PathBuf> {
321    let written = match word.strip_prefix("~/").zip(crate::paths::home_dir()) {
322        Some((rest, home)) => home.join(rest),
323        None => cwd.join(word),
324    };
325    let lexical = crate::path::normalize_lexically(&written);
326    vec![
327        crate::path::resolve_physically(&lexical),
328        crate::path::resolve_physically(&written),
329        lexical,
330    ]
331}