Skip to main content

base/interface/
permission.rs

1//! Tool authorization, in two parts: [`PermissionPolicy`] decides whether a
2//! call runs, [`PermissionGrants`] keeps the allows a person or a skill hands
3//! out along the way. A session holds the two together as a [`PermissionSet`].
4//! What a policy weighs about a call is its [`ToolFacts`].
5
6use 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/// How the permission modes treat a tool's calls: `ToolSpec::stance`.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26#[non_exhaustive]
27pub enum ModeStance {
28    #[default]
29    Normal,
30    /// A coordination primitive that touches no file, shell or network: a
31    /// self-contained call of it is spared `Plan` and `DontAsk`.
32    Coordination,
33    /// The call that takes the session out of plan mode, which plan mode
34    /// would otherwise refuse as a change of state.
35    LeavesPlan,
36}
37
38/// What a call names, as permission rules are matched against it.
39#[derive(Debug, Clone, PartialEq, Eq, Default)]
40#[non_exhaustive]
41pub enum Subject {
42    #[default]
43    None,
44    /// Compared to rule patterns verbatim.
45    Opaque(String),
46    /// A path read; `Read(...)` rules apply to it as well as the tool's own.
47    ReadPath(String),
48    /// A path written; `Edit(...)` rules apply to it as well as the tool's own.
49    WritePath(String),
50    /// A command line, matched one simple command at a time.
51    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/// How far a call reaches beyond the session itself.
69#[derive(Debug, Clone, PartialEq, Eq)]
70#[non_exhaustive]
71pub enum Reach {
72    /// Only the session's own state: todos, tasks, the mailbox, the plan.
73    SessionOnly,
74    /// Starts other calls, each judged on its own.
75    Delegates,
76    /// Only endpoints the operator configured.
77    Operator,
78    /// Within the roots the session works in without asking: the readable
79    /// ones for a read, the writable ones for a write.
80    Inside,
81    /// A path outside those roots.
82    Outside,
83    /// Runs code the model did not write that may change files inside the
84    /// project only: asked about unless the mode accepts edits.
85    EditsProject,
86    /// A host the model chose; `listed` when `web.allowed_domains` names it.
87    Host {
88        listed: bool,
89    },
90    /// An MCP server's tool, whose word about itself does not count.
91    Server,
92    /// Leaves something behind that acts later on its own.
93    Persists(&'static str),
94    /// The tool knows this input must not run, and says why.
95    Refused(String),
96    Unknown,
97}
98
99/// The call runs a command inside the session's sandbox.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101#[non_exhaustive]
102pub struct Runs {
103    /// It keeps running after the call returns.
104    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/// Content others wrote that a call hands back through an endpoint its
117/// [`Reach`] does not show: an operator's endpoint relaying it.
118#[derive(Debug, Clone, PartialEq, Eq)]
119#[non_exhaustive]
120pub enum Relays {
121    /// What a search found on the web.
122    Web,
123    /// What an MCP server serves, by its configured name when the call names it.
124    McpServer(Option<String>),
125}
126
127/// What a tool says about one call for the permission policy to weigh:
128/// [`Tool::permission_facts`].
129#[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    /// What to put to a person when the call is asked about.
136    pub question: Option<String>,
137    pub relays: Option<Relays>,
138    /// A second name the call answers to for deny rules: a tool that acts on
139    /// one MCP server's behalf is also `mcp__<server>`.
140    pub also_named: Option<String>,
141    /// Where a write the call makes lands, as judged: the call writes there
142    /// or nowhere.
143    pub lands_at: Option<std::path::PathBuf>,
144    /// The host's declaration of the tool lets the call through: counted
145    /// only for a tool of [`ToolOrigin::Host`].
146    pub host_permits: bool,
147}
148
149impl PermissionFacts {
150    /// Claims nothing, so the call is asked about.
151    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/// Everything the permission policy reads about one call: the tool's spec,
200/// its [`CallTraits`] for the input and its [`PermissionFacts`].
201#[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    /// The host's declaration lets the call through. A tool's own word is
215    /// not enough: the session running the call keeps it only for a host tool
216    /// it admitted under that name.
217    pub host_permits: bool,
218}
219
220impl ToolFacts {
221    /// Gathered once per call, by the session that runs it and with the
222    /// context it runs with.
223    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    /// For a name no tool answers to: claims nothing, not even a read.
243    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/// What a `PreToolUse` hook answered about the call.
261#[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/// Whether someone can be asked about the call.
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277#[non_exhaustive]
278pub enum Attendance {
279    Attended,
280    Unattended,
281    /// Nothing could reach a person even if one were there, and why.
282    NoOneToAsk(&'static str),
283}
284
285/// What a policy concluded about one call.
286#[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    /// Put to whoever can answer: the engine emits
297    /// `AgentEvent::PermissionPrompt` and waits for the answer.
298    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    /// A question anyone who can answer may answer, under a fresh id.
315    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/// On whose word a call runs.
332#[derive(Debug, Clone, PartialEq, Eq)]
333#[non_exhaustive]
334pub enum Basis {
335    Rule(PermissionRule),
336    /// It stays where the session works without asking.
337    Contained,
338    AcceptEdits,
339    Bypass,
340    /// A `PreToolUse` hook approved it, by name.
341    HookApproved(String),
342    /// A command nobody can be asked about, which the session's sandbox holds.
343    UnattendedConfined,
344    /// The host's declaration of its own tool (`permit: "allow"`).
345    HostDeclared,
346    Person,
347    /// Nothing judges the session's calls: a build without the permission
348    /// engine ([`PermitAll`]).
349    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/// Who may answer a question a policy asks.
369#[derive(Debug, Clone, Copy, PartialEq, Eq)]
370#[non_exhaustive]
371pub enum Answerable {
372    HookOrPerson,
373    /// The deployment's managed layer asks it: a hook's approve does not
374    /// answer it.
375    PersonOnly,
376}
377
378/// Where in the policy's order a call was refused or asked about.
379#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
380#[non_exhaustive]
381pub enum Stage {
382    ManagedUnreadable,
383    UnknownTool,
384    Credentials,
385    Hook,
386    ToolRefusal,
387    /// The session's sandbox cannot hold the command as fully as
388    /// `sandbox.require` demands.
389    Confinement,
390    Rule,
391    ManagedRule,
392    /// A rule the delegate runs under: its type's deny rules.
393    DelegateRule,
394    BypassImmune,
395    PlanMode,
396    DontAsk,
397    /// A write to the agent's or the repository's configuration, which the
398    /// tool's own word does not let through.
399    Configuration,
400    ModeDefault,
401    Attendance,
402    /// A write under a skill directory a host listed for some session
403    /// (`options.skill_dirs`): read-only to every session.
404    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/// Why a call was refused or asked about.
431#[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/// One tool call put to a [`PermissionPolicy`].
461#[derive(Clone, Copy)]
462#[non_exhaustive]
463pub struct PermissionRequest<'a> {
464    pub tool_name: &'a str,
465    /// The tool the call dispatches to, looked up in the registry dispatch
466    /// uses. `None` is a name nothing answers to.
467    pub tool: Option<&'a Arc<dyn Tool>>,
468    pub input: &'a serde_json::Value,
469    /// What the tool says about the call, gathered with `ctx`.
470    pub facts: &'a ToolFacts,
471    /// The context the call runs with: the judged session's.
472    pub ctx: &'a ToolContext,
473    /// The live state of the session the policy belongs to: its permission
474    /// mode as it is now, what it has read.
475    pub session: &'a Arc<dyn Session>,
476    /// Set when the call is a delegate's — a sub-agent's, a team member's —
477    /// relayed to this session's policy.
478    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    /// A call no hook answered, as attended as `ctx` says.
487    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    /// The state the call is judged against: the delegate's when there is
524    /// one, the session's otherwise.
525    pub fn judged(&self) -> &'a Arc<dyn Session> {
526        self.delegate.map_or(self.session, |d| d.session)
527    }
528}
529
530/// A delegate's call as the session that relays it hands it on: judged
531/// against the delegate's state, in `mode`, and held to `rules` on top of the
532/// policy's own.
533#[derive(Clone, Copy)]
534#[non_exhaustive]
535pub struct Delegate<'a> {
536    /// The session the call runs in.
537    pub session: &'a Arc<dyn Session>,
538    /// The delegate's mode as every session between it and the policy holds
539    /// it (`PermissionMode::for_delegate`, once per relaying session). The
540    /// policy holds it to its own session's mode in turn.
541    pub mode: PermissionMode,
542    /// What the delegation itself adds: its `deny` rules refuse the call in
543    /// any mode; its `allow` rules are the delegate's own grants, which answer
544    /// only the question the mode would put — never a deny, an ask rule, or
545    /// a question only a person may answer.
546    pub rules: &'a [PermissionRule],
547    /// The delegate may only be stricter than each session relaying it: an
548    /// agent type that may not loosen (`AgentTypeSource::may_loosen`) named
549    /// its mode. A session that bypasses does not take it along.
550    pub tightens_only: bool,
551}
552
553impl<'a> Delegate<'a> {
554    /// `session`'s call in its own live mode, with nothing added.
555    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    /// The mode its call is judged in, relayed through a session in `parent`.
573    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/// Whether a tool call runs. The engine's own is
583/// `permissions::policy::Policy` (rules, modes, the
584/// tools' own verdicts).
585#[async_trait]
586pub trait PermissionPolicy: Send + Sync {
587    async fn decide(&self, req: &PermissionRequest<'_>) -> PermissionOutcome;
588}
589
590/// Which paths a deny rule covers, for a tool that walks a directory on its
591/// own: a search is judged on the directory it starts in, so each file under
592/// it has to be judged as it is reached.
593pub trait PathDenials: Send + Sync {
594    /// The paths `tool` must leave out of its walk. `extra` is the rules a
595    /// delegation adds on top of the policy's own. `None` when no rule
596    /// covers a path.
597    fn denial(
598        &self,
599        tool: &str,
600        cwd: &std::path::Path,
601        extra: &[PermissionRule],
602    ) -> Option<PathDenial>;
603
604    /// The paths `Read` deny rules name outright, resolved from `cwd` as they
605    /// are judged there; a glob other than a trailing `/**` or `/*` names none.
606    fn denied_read_paths(&self, cwd: &std::path::Path, extra: &[PermissionRule]) -> Vec<PathBuf>;
607}
608
609/// Whether a deny rule covers this path.
610pub type PathDenial = Arc<dyn Fn(&std::path::Path) -> bool + Send + Sync>;
611
612/// How long a [`Grant`] lasts.
613#[derive(Clone, Copy, PartialEq, Eq, Debug)]
614#[non_exhaustive]
615pub enum GrantScope {
616    /// Until the next user turn starts: a skill's `allowed-tools`.
617    Turn,
618    /// For the rest of the session: "always allow" answered for this session.
619    Session,
620    /// For this project, kept in its `settings.local.json`; a session with no
621    /// project keeps it for the session.
622    Project,
623}
624
625/// How an allow's content meets a call's.
626#[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    /// As a `settings.json` rule's content is: `*`, `prefix:*`, path and URL
641    /// patterns.
642    #[default]
643    Pattern,
644    /// Only a call whose content is the same text.
645    Exact,
646}
647
648impl GrantMatch {
649    pub fn is_pattern(&self) -> bool {
650        *self == Self::Pattern
651    }
652}
653
654/// An allow for calls to one tool.
655#[derive(Clone, Debug, PartialEq, Eq)]
656#[non_exhaustive]
657pub struct Grant {
658    pub tool_name: String,
659    /// `None` allows every call to the tool. Otherwise matched as `matching`
660    /// says.
661    ///
662    /// A grant relayed from project-controlled data — a skill's frontmatter —
663    /// must not be `None`: anyone who can write a file in the repository could
664    /// then switch off confirmation for `Bash` wholesale.
665    pub content: Option<String>,
666    pub scope: GrantScope,
667    /// A [`GrantScope::Turn`] grant is a skill's rule pattern; a
668    /// [`GrantScope::Session`] or [`GrantScope::Project`] one is a person's
669    /// answer about one call, so it covers that call's content exactly and
670    /// not whatever the text happens to match as a pattern.
671    pub matching: GrantMatch,
672    /// Set for a grant from someone else's or the repository's files — a
673    /// project, plugin or host skill: it must narrow its tool to content
674    /// that stays inside this directory, a program or a registrable domain,
675    /// or it is refused ([`GrantError::TooBroad`]).
676    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    /// Kept for the session, but not written where it would outlast it.
703    #[error("kept for this session only, not written to {}: {reason}", .path.display())]
704    NotPersisted { path: PathBuf, reason: String },
705    /// A narrow-only grant that reaches as far as the bare tool, or out of
706    /// the project.
707    #[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
727/// The file a project-scoped "allow every time" is written to.
728pub trait RuleFile: Send + Sync + std::fmt::Debug {
729    fn path(&self) -> &std::path::Path;
730    /// Add `rule` as an allow. `Ok(false)` when it was already there.
731    fn append_allow(&self, rule: &str, matching: GrantMatch) -> Result<bool, String>;
732}
733
734/// Where the allows handed out during a session are kept.
735#[async_trait]
736pub trait PermissionGrants: Send + Sync {
737    async fn grant(&self, grant: Grant) -> Result<(), GrantError>;
738    /// Drop every grant of `scope`.
739    fn clear(&self, scope: GrantScope);
740}