1use async_trait::async_trait;
7use serde_json::Value;
8use std::path::PathBuf;
9use std::sync::Arc;
10
11use crate::context::Session;
12use crate::interface::tool::{CallTraits, Tool, ToolContext, ToolOrigin};
13use crate::permission::{PermissionMode, PermissionRule};
14
15mod paths;
16mod permit_all;
17mod profile;
18mod set;
19pub use paths::{NoWrites, PathGuard, WriteScope};
20pub use permit_all::PermitAll;
21pub use profile::{Approval, ExecProfile, Obligations};
22pub use set::PermissionSet;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26#[non_exhaustive]
27pub enum ModeStance {
28 #[default]
29 Normal,
30 Coordination,
33 LeavesPlan,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq, Default)]
40#[non_exhaustive]
41pub enum Subject {
42 #[default]
43 None,
44 Opaque(String),
46 ReadPath(String),
48 WritePath(String),
50 Shell(String),
52 Url(String),
53}
54
55impl Subject {
56 pub fn content(&self) -> Option<&str> {
57 match self {
58 Self::None => None,
59 Self::Opaque(s)
60 | Self::ReadPath(s)
61 | Self::WritePath(s)
62 | Self::Shell(s)
63 | Self::Url(s) => Some(s),
64 }
65 }
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
70#[non_exhaustive]
71pub enum Reach {
72 SessionOnly,
74 Delegates,
76 Operator,
78 Inside,
81 Outside,
83 EditsProject,
86 Host {
88 listed: bool,
89 },
90 Server,
92 Persists(&'static str),
94 Refused(String),
96 Unknown,
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101#[non_exhaustive]
102pub struct Runs {
103 pub background: bool,
105}
106
107impl Runs {
108 pub fn foreground() -> Self {
109 Self { background: false }
110 }
111 pub fn background() -> Self {
112 Self { background: true }
113 }
114}
115
116#[derive(Debug, Clone, PartialEq, Eq)]
119#[non_exhaustive]
120pub enum Relays {
121 Web,
123 McpServer(Option<String>),
125}
126
127#[derive(Debug, Clone, PartialEq, Eq)]
130#[non_exhaustive]
131pub struct PermissionFacts {
132 pub subject: Subject,
133 pub reach: Reach,
134 pub runs: Option<Runs>,
135 pub question: Option<String>,
137 pub relays: Option<Relays>,
138 pub also_named: Option<String>,
141 pub lands_at: Option<std::path::PathBuf>,
144 pub host_permits: bool,
147}
148
149impl PermissionFacts {
150 pub fn unknown() -> Self {
152 Self::new(Subject::None, Reach::Unknown)
153 }
154
155 pub fn new(subject: Subject, reach: Reach) -> Self {
156 Self {
157 subject,
158 reach,
159 runs: None,
160 question: None,
161 relays: None,
162 also_named: None,
163 lands_at: None,
164 host_permits: false,
165 }
166 }
167
168 pub fn with_runs(mut self, runs: Runs) -> Self {
169 self.runs = Some(runs);
170 self
171 }
172
173 pub fn with_question(mut self, question: impl Into<String>) -> Self {
174 self.question = Some(question.into());
175 self
176 }
177
178 pub fn relaying(mut self, relays: Relays) -> Self {
179 self.relays = Some(relays);
180 self
181 }
182
183 pub fn also_named(mut self, name: impl Into<String>) -> Self {
184 self.also_named = Some(name.into());
185 self
186 }
187
188 pub fn landing_at(mut self, path: std::path::PathBuf) -> Self {
189 self.lands_at = Some(path);
190 self
191 }
192
193 pub fn permitted_by_host(mut self) -> Self {
194 self.host_permits = true;
195 self
196 }
197}
198
199#[derive(Debug, Clone, PartialEq, Eq)]
202#[non_exhaustive]
203pub struct ToolFacts {
204 pub subject: Subject,
205 pub traits: CallTraits,
206 pub stance: ModeStance,
207 pub origin: ToolOrigin,
208 pub reach: Reach,
209 pub runs: Option<Runs>,
210 pub question: Option<String>,
211 pub relays: Option<Relays>,
212 pub also_named: Option<String>,
213 pub lands_at: Option<std::path::PathBuf>,
214 pub host_permits: bool,
218}
219
220impl ToolFacts {
221 pub async fn gather(tool: &dyn Tool, input: &Value, ctx: &ToolContext) -> Self {
224 let spec = tool.spec();
225 let facts = tool.permission_facts(input, ctx).await;
226 let host_permits = facts.host_permits && spec.origin == ToolOrigin::Host;
227 Self {
228 subject: facts.subject,
229 traits: tool.call_traits(input),
230 stance: spec.stance,
231 origin: spec.origin,
232 reach: facts.reach,
233 runs: facts.runs,
234 question: facts.question,
235 relays: facts.relays,
236 also_named: facts.also_named,
237 lands_at: facts.lands_at,
238 host_permits,
239 }
240 }
241
242 pub fn unknown_tool() -> Self {
244 Self {
245 subject: Subject::None,
246 traits: CallTraits::default(),
247 stance: ModeStance::Normal,
248 origin: ToolOrigin::default(),
249 reach: Reach::Unknown,
250 runs: None,
251 question: None,
252 relays: None,
253 also_named: None,
254 lands_at: None,
255 host_permits: false,
256 }
257 }
258}
259
260#[derive(Debug, Clone, PartialEq, Eq, Default)]
262#[non_exhaustive]
263pub enum HookAnswer {
264 #[default]
265 None,
266 Approve {
267 hook: String,
268 },
269 Block {
270 hook: String,
271 reason: String,
272 },
273}
274
275#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277#[non_exhaustive]
278pub enum Attendance {
279 Attended,
280 Unattended,
281 NoOneToAsk(&'static str),
283}
284
285#[derive(Debug, Clone)]
287pub enum PermissionOutcome {
288 Permit {
289 basis: Basis,
290 profile: ExecProfile,
291 obligations: Obligations,
292 },
293 Deny {
294 reason: Reason,
295 },
296 Prompt {
299 prompt_id: String,
300 message: String,
301 paths: Vec<PathBuf>,
302 reason: Reason,
303 answerable: Answerable,
304 },
305}
306
307impl PermissionOutcome {
308 pub fn deny(stage: Stage, message: impl Into<String>) -> Self {
309 Self::Deny {
310 reason: Reason::new(stage, message),
311 }
312 }
313
314 pub fn prompt(stage: Stage, message: impl Into<String>) -> Self {
316 let message = message.into();
317 Self::Prompt {
318 prompt_id: uuid::Uuid::new_v4().to_string(),
319 reason: Reason::new(stage, message.clone()),
320 message,
321 paths: Vec::new(),
322 answerable: Answerable::HookOrPerson,
323 }
324 }
325
326 pub fn is_permit(&self) -> bool {
327 matches!(self, Self::Permit { .. })
328 }
329}
330
331#[derive(Debug, Clone, PartialEq, Eq)]
333#[non_exhaustive]
334pub enum Basis {
335 Rule(PermissionRule),
336 Contained,
338 AcceptEdits,
339 Bypass,
340 HookApproved(String),
342 UnattendedConfined,
344 HostDeclared,
346 Person,
347 NoPolicy,
350}
351
352impl Basis {
353 pub fn as_str(&self) -> &'static str {
354 match self {
355 Self::Rule(_) => "rule",
356 Self::Contained => "contained",
357 Self::AcceptEdits => "accept_edits",
358 Self::Bypass => "bypass",
359 Self::HookApproved(_) => "hook_approved",
360 Self::UnattendedConfined => "unattended_confined",
361 Self::HostDeclared => "host_declared",
362 Self::Person => "person",
363 Self::NoPolicy => "no_policy",
364 }
365 }
366}
367
368#[derive(Debug, Clone, Copy, PartialEq, Eq)]
370#[non_exhaustive]
371pub enum Answerable {
372 HookOrPerson,
373 PersonOnly,
376}
377
378#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
380#[non_exhaustive]
381pub enum Stage {
382 ManagedUnreadable,
383 UnknownTool,
384 Credentials,
385 Hook,
386 ToolRefusal,
387 Confinement,
390 Rule,
391 ManagedRule,
392 DelegateRule,
394 BypassImmune,
395 PlanMode,
396 DontAsk,
397 Configuration,
400 ModeDefault,
401 Attendance,
402 HostSkillDir,
405}
406
407impl Stage {
408 pub fn as_str(self) -> &'static str {
409 match self {
410 Self::ManagedUnreadable => "managed_unreadable",
411 Self::UnknownTool => "unknown_tool",
412 Self::Credentials => "credentials",
413 Self::Hook => "hook",
414 Self::ToolRefusal => "tool_refusal",
415 Self::Confinement => "confinement",
416 Self::Rule => "rule",
417 Self::ManagedRule => "managed_rule",
418 Self::DelegateRule => "delegate_rule",
419 Self::BypassImmune => "bypass_immune",
420 Self::PlanMode => "plan_mode",
421 Self::DontAsk => "dont_ask",
422 Self::Configuration => "configuration",
423 Self::ModeDefault => "mode_default",
424 Self::Attendance => "attendance",
425 Self::HostSkillDir => "host_skill_dir",
426 }
427 }
428}
429
430#[derive(Debug, Clone, PartialEq, Eq)]
432#[non_exhaustive]
433pub struct Reason {
434 pub stage: Stage,
435 pub rule: Option<PermissionRule>,
436 pub message: String,
437}
438
439impl Reason {
440 pub fn new(stage: Stage, message: impl Into<String>) -> Self {
441 Self {
442 stage,
443 rule: None,
444 message: message.into(),
445 }
446 }
447
448 pub fn with_rule(mut self, rule: PermissionRule) -> Self {
449 self.rule = Some(rule);
450 self
451 }
452}
453
454impl std::fmt::Display for Reason {
455 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
456 f.write_str(&self.message)
457 }
458}
459
460#[derive(Clone, Copy)]
462#[non_exhaustive]
463pub struct PermissionRequest<'a> {
464 pub tool_name: &'a str,
465 pub tool: Option<&'a Arc<dyn Tool>>,
468 pub input: &'a serde_json::Value,
469 pub facts: &'a ToolFacts,
471 pub ctx: &'a ToolContext,
473 pub session: &'a Arc<dyn Session>,
476 pub delegate: Option<Delegate<'a>>,
479 pub hook: &'a HookAnswer,
480 pub attendance: Attendance,
481}
482
483const NO_HOOK: &HookAnswer = &HookAnswer::None;
484
485impl<'a> PermissionRequest<'a> {
486 pub fn new(
488 tool_name: &'a str,
489 tool: Option<&'a Arc<dyn Tool>>,
490 input: &'a serde_json::Value,
491 facts: &'a ToolFacts,
492 ctx: &'a ToolContext,
493 session: &'a Arc<dyn Session>,
494 ) -> Self {
495 Self {
496 tool_name,
497 tool,
498 input,
499 facts,
500 ctx,
501 session,
502 delegate: None,
503 hook: NO_HOOK,
504 attendance: ctx.attendance,
505 }
506 }
507
508 pub fn for_delegate(mut self, delegate: Delegate<'a>) -> Self {
509 self.delegate = Some(delegate);
510 self
511 }
512
513 pub fn with_hook(mut self, hook: &'a HookAnswer) -> Self {
514 self.hook = hook;
515 self
516 }
517
518 pub fn with_attendance(mut self, attendance: Attendance) -> Self {
519 self.attendance = attendance;
520 self
521 }
522
523 pub fn judged(&self) -> &'a Arc<dyn Session> {
526 self.delegate.map_or(self.session, |d| d.session)
527 }
528}
529
530#[derive(Clone, Copy)]
534#[non_exhaustive]
535pub struct Delegate<'a> {
536 pub session: &'a Arc<dyn Session>,
538 pub mode: PermissionMode,
542 pub rules: &'a [PermissionRule],
547 pub tightens_only: bool,
551}
552
553impl<'a> Delegate<'a> {
554 pub fn of(session: &'a Arc<dyn Session>) -> Self {
556 Self::new(session, session.permission_mode(), &[])
557 }
558
559 pub fn new(
560 session: &'a Arc<dyn Session>,
561 mode: PermissionMode,
562 rules: &'a [PermissionRule],
563 ) -> Self {
564 Self {
565 session,
566 mode,
567 rules,
568 tightens_only: false,
569 }
570 }
571
572 pub fn mode_under(&self, parent: PermissionMode) -> PermissionMode {
574 if self.tightens_only {
575 self.mode.min_permissive(parent)
576 } else {
577 parent.for_delegate(self.mode)
578 }
579 }
580}
581
582#[async_trait]
586pub trait PermissionPolicy: Send + Sync {
587 async fn decide(&self, req: &PermissionRequest<'_>) -> PermissionOutcome;
588}
589
590pub trait PathDenials: Send + Sync {
594 fn denial(
598 &self,
599 tool: &str,
600 cwd: &std::path::Path,
601 extra: &[PermissionRule],
602 ) -> Option<PathDenial>;
603
604 fn denied_read_paths(&self, cwd: &std::path::Path, extra: &[PermissionRule]) -> Vec<PathBuf>;
607}
608
609pub type PathDenial = Arc<dyn Fn(&std::path::Path) -> bool + Send + Sync>;
611
612#[derive(Clone, Copy, PartialEq, Eq, Debug)]
614#[non_exhaustive]
615pub enum GrantScope {
616 Turn,
618 Session,
620 Project,
623}
624
625#[derive(
627 Clone,
628 Copy,
629 PartialEq,
630 Eq,
631 Debug,
632 Default,
633 serde::Serialize,
634 serde::Deserialize,
635 schemars::JsonSchema,
636)]
637#[serde(rename_all = "lowercase")]
638#[non_exhaustive]
639pub enum GrantMatch {
640 #[default]
643 Pattern,
644 Exact,
646}
647
648impl GrantMatch {
649 pub fn is_pattern(&self) -> bool {
650 *self == Self::Pattern
651 }
652}
653
654#[derive(Clone, Debug, PartialEq, Eq)]
656#[non_exhaustive]
657pub struct Grant {
658 pub tool_name: String,
659 pub content: Option<String>,
666 pub scope: GrantScope,
667 pub matching: GrantMatch,
672 pub narrow_only: Option<PathBuf>,
677}
678
679impl Grant {
680 pub fn new(tool_name: impl Into<String>, content: Option<String>, scope: GrantScope) -> Self {
681 Self {
682 tool_name: tool_name.into(),
683 content,
684 matching: match scope {
685 GrantScope::Turn => GrantMatch::Pattern,
686 GrantScope::Session | GrantScope::Project => GrantMatch::Exact,
687 },
688 scope,
689 narrow_only: None,
690 }
691 }
692
693 pub fn narrow_only_within(mut self, root: PathBuf) -> Self {
694 self.narrow_only = Some(root);
695 self
696 }
697}
698
699#[derive(Debug, thiserror::Error)]
700#[non_exhaustive]
701pub enum GrantError {
702 #[error("kept for this session only, not written to {}: {reason}", .path.display())]
704 NotPersisted { path: PathBuf, reason: String },
705 #[error(
708 "`{tool}{}` reaches further than a grant from this source may; scope it as \
709 `Tool(pattern)` to a path inside the project, a program or a registrable domain",
710 .content.as_deref().map(|c| format!("({c})")).unwrap_or_default()
711 )]
712 TooBroad {
713 tool: String,
714 content: Option<String>,
715 },
716}
717
718impl GrantError {
719 pub fn too_broad(grant: &Grant) -> Self {
720 Self::TooBroad {
721 tool: grant.tool_name.clone(),
722 content: grant.content.clone(),
723 }
724 }
725}
726
727pub trait RuleFile: Send + Sync + std::fmt::Debug {
729 fn path(&self) -> &std::path::Path;
730 fn append_allow(&self, rule: &str, matching: GrantMatch) -> Result<bool, String>;
732}
733
734#[async_trait]
736pub trait PermissionGrants: Send + Sync {
737 async fn grant(&self, grant: Grant) -> Result<(), GrantError>;
738 fn clear(&self, scope: GrantScope);
740}