base/interface/permission/
permit_all.rs1use 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
104fn 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
172fn 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
215fn 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
250fn 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
262fn 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
274fn 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}