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 profile;
16pub use profile::{Approval, ExecProfile, Obligations};
17
18/// How the permission modes treat a tool's calls: `ToolSpec::stance`.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
20#[non_exhaustive]
21pub enum ModeStance {
22    #[default]
23    Normal,
24    /// A coordination primitive that touches no file, shell or network: a
25    /// self-contained call of it is spared `Plan` and `DontAsk`.
26    Coordination,
27    /// The call that takes the session out of plan mode, which plan mode
28    /// would otherwise refuse as a change of state.
29    LeavesPlan,
30}
31
32/// What a call names, as permission rules are matched against it.
33#[derive(Debug, Clone, PartialEq, Eq, Default)]
34#[non_exhaustive]
35pub enum Subject {
36    #[default]
37    None,
38    /// Compared to rule patterns verbatim.
39    Opaque(String),
40    /// A path read; `Read(...)` rules apply to it as well as the tool's own.
41    ReadPath(String),
42    /// A path written; `Edit(...)` rules apply to it as well as the tool's own.
43    WritePath(String),
44    /// A command line, matched one simple command at a time.
45    Shell(String),
46    Url(String),
47}
48
49impl Subject {
50    pub fn content(&self) -> Option<&str> {
51        match self {
52            Self::None => None,
53            Self::Opaque(s)
54            | Self::ReadPath(s)
55            | Self::WritePath(s)
56            | Self::Shell(s)
57            | Self::Url(s) => Some(s),
58        }
59    }
60}
61
62/// How far a call reaches beyond the session itself.
63#[derive(Debug, Clone, PartialEq, Eq)]
64#[non_exhaustive]
65pub enum Reach {
66    /// Only the session's own state: todos, tasks, the mailbox, the plan.
67    SessionOnly,
68    /// Starts other calls, each judged on its own.
69    Delegates,
70    /// Only endpoints the operator configured.
71    Operator,
72    /// Within the roots the session works in without asking: the readable
73    /// ones for a read, the writable ones for a write.
74    Inside,
75    /// A path outside those roots.
76    Outside,
77    /// Runs code the model did not write that may change files inside the
78    /// project only: asked about unless the mode accepts edits.
79    EditsProject,
80    /// A host the model chose; `listed` when `web.allowed_domains` names it.
81    Host {
82        listed: bool,
83    },
84    /// An MCP server's tool, whose word about itself does not count.
85    Server,
86    /// Leaves something behind that acts later on its own.
87    Persists(&'static str),
88    /// The tool knows this input must not run, and says why.
89    Refused(String),
90    Unknown,
91}
92
93/// The call runs a command inside the session's sandbox.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95#[non_exhaustive]
96pub struct Runs {
97    /// It keeps running after the call returns.
98    pub background: bool,
99}
100
101impl Runs {
102    pub fn foreground() -> Self {
103        Self { background: false }
104    }
105    pub fn background() -> Self {
106        Self { background: true }
107    }
108}
109
110/// Content others wrote that a call hands back through an endpoint its
111/// [`Reach`] does not show: an operator's endpoint relaying it.
112#[derive(Debug, Clone, PartialEq, Eq)]
113#[non_exhaustive]
114pub enum Relays {
115    /// What a search found on the web.
116    Web,
117    /// What an MCP server serves, by its configured name when the call names it.
118    McpServer(Option<String>),
119}
120
121/// What a tool says about one call for the permission policy to weigh:
122/// [`Tool::permission_facts`].
123#[derive(Debug, Clone, PartialEq, Eq)]
124#[non_exhaustive]
125pub struct PermissionFacts {
126    pub subject: Subject,
127    pub reach: Reach,
128    pub runs: Option<Runs>,
129    /// What to put to a person when the call is asked about.
130    pub question: Option<String>,
131    pub relays: Option<Relays>,
132    /// A second name the call answers to for deny rules: a tool that acts on
133    /// one MCP server's behalf is also `mcp__<server>`.
134    pub also_named: Option<String>,
135    /// Where a write the call makes lands, as judged: the call writes there
136    /// or nowhere.
137    pub lands_at: Option<std::path::PathBuf>,
138    /// The host's declaration of the tool lets the call through: counted
139    /// only for a tool of [`ToolOrigin::Host`].
140    pub host_permits: bool,
141}
142
143impl PermissionFacts {
144    /// Claims nothing, so the call is asked about.
145    pub fn unknown() -> Self {
146        Self::new(Subject::None, Reach::Unknown)
147    }
148
149    pub fn new(subject: Subject, reach: Reach) -> Self {
150        Self {
151            subject,
152            reach,
153            runs: None,
154            question: None,
155            relays: None,
156            also_named: None,
157            lands_at: None,
158            host_permits: false,
159        }
160    }
161
162    pub fn with_runs(mut self, runs: Runs) -> Self {
163        self.runs = Some(runs);
164        self
165    }
166
167    pub fn with_question(mut self, question: impl Into<String>) -> Self {
168        self.question = Some(question.into());
169        self
170    }
171
172    pub fn relaying(mut self, relays: Relays) -> Self {
173        self.relays = Some(relays);
174        self
175    }
176
177    pub fn also_named(mut self, name: impl Into<String>) -> Self {
178        self.also_named = Some(name.into());
179        self
180    }
181
182    pub fn landing_at(mut self, path: std::path::PathBuf) -> Self {
183        self.lands_at = Some(path);
184        self
185    }
186
187    pub fn permitted_by_host(mut self) -> Self {
188        self.host_permits = true;
189        self
190    }
191}
192
193/// Everything the permission policy reads about one call: the tool's spec,
194/// its [`CallTraits`] for the input and its [`PermissionFacts`].
195#[derive(Debug, Clone, PartialEq, Eq)]
196#[non_exhaustive]
197pub struct ToolFacts {
198    pub subject: Subject,
199    pub traits: CallTraits,
200    pub stance: ModeStance,
201    pub origin: ToolOrigin,
202    pub reach: Reach,
203    pub runs: Option<Runs>,
204    pub question: Option<String>,
205    pub relays: Option<Relays>,
206    pub also_named: Option<String>,
207    pub lands_at: Option<std::path::PathBuf>,
208    /// The host's declaration lets the call through. A tool's own word is
209    /// not enough: the session running the call keeps it only for a host tool
210    /// it admitted under that name.
211    pub host_permits: bool,
212}
213
214impl ToolFacts {
215    /// Gathered once per call, by the session that runs it and with the
216    /// context it runs with.
217    pub async fn gather(tool: &dyn Tool, input: &Value, ctx: &ToolContext) -> Self {
218        let spec = tool.spec();
219        let facts = tool.permission_facts(input, ctx).await;
220        let host_permits = facts.host_permits && spec.origin == ToolOrigin::Host;
221        Self {
222            subject: facts.subject,
223            traits: tool.call_traits(input),
224            stance: spec.stance,
225            origin: spec.origin,
226            reach: facts.reach,
227            runs: facts.runs,
228            question: facts.question,
229            relays: facts.relays,
230            also_named: facts.also_named,
231            lands_at: facts.lands_at,
232            host_permits,
233        }
234    }
235
236    /// For a name no tool answers to: claims nothing, not even a read.
237    pub fn unknown_tool() -> Self {
238        Self {
239            subject: Subject::None,
240            traits: CallTraits::default(),
241            stance: ModeStance::Normal,
242            origin: ToolOrigin::default(),
243            reach: Reach::Unknown,
244            runs: None,
245            question: None,
246            relays: None,
247            also_named: None,
248            lands_at: None,
249            host_permits: false,
250        }
251    }
252}
253
254/// What a `PreToolUse` hook answered about the call.
255#[derive(Debug, Clone, PartialEq, Eq, Default)]
256#[non_exhaustive]
257pub enum HookAnswer {
258    #[default]
259    None,
260    Approve {
261        hook: String,
262    },
263    Block {
264        hook: String,
265        reason: String,
266    },
267}
268
269/// Whether someone can be asked about the call.
270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271#[non_exhaustive]
272pub enum Attendance {
273    Attended,
274    Unattended,
275    /// Nothing could reach a person even if one were there, and why.
276    NoOneToAsk(&'static str),
277}
278
279/// What a policy concluded about one call.
280#[derive(Debug, Clone)]
281pub enum PermissionOutcome {
282    Permit {
283        basis: Basis,
284        profile: ExecProfile,
285        obligations: Obligations,
286    },
287    Deny {
288        reason: Reason,
289    },
290    /// Put to whoever can answer: the engine emits
291    /// `AgentEvent::PermissionPrompt` and waits for the answer.
292    Prompt {
293        prompt_id: String,
294        message: String,
295        paths: Vec<PathBuf>,
296        reason: Reason,
297        answerable: Answerable,
298    },
299}
300
301impl PermissionOutcome {
302    pub fn deny(stage: Stage, message: impl Into<String>) -> Self {
303        Self::Deny {
304            reason: Reason::new(stage, message),
305        }
306    }
307
308    /// A question anyone who can answer may answer, under a fresh id.
309    pub fn prompt(stage: Stage, message: impl Into<String>) -> Self {
310        let message = message.into();
311        Self::Prompt {
312            prompt_id: uuid::Uuid::new_v4().to_string(),
313            reason: Reason::new(stage, message.clone()),
314            message,
315            paths: Vec::new(),
316            answerable: Answerable::HookOrPerson,
317        }
318    }
319
320    pub fn is_permit(&self) -> bool {
321        matches!(self, Self::Permit { .. })
322    }
323}
324
325/// On whose word a call runs.
326#[derive(Debug, Clone, PartialEq, Eq)]
327#[non_exhaustive]
328pub enum Basis {
329    Rule(PermissionRule),
330    /// It stays where the session works without asking.
331    Contained,
332    AcceptEdits,
333    Bypass,
334    /// A `PreToolUse` hook approved it, by name.
335    HookApproved(String),
336    /// A command nobody can be asked about, which the session's sandbox holds.
337    UnattendedConfined,
338    /// The host's declaration of its own tool (`permit: "allow"`).
339    HostDeclared,
340    Person,
341}
342
343impl Basis {
344    pub fn as_str(&self) -> &'static str {
345        match self {
346            Self::Rule(_) => "rule",
347            Self::Contained => "contained",
348            Self::AcceptEdits => "accept_edits",
349            Self::Bypass => "bypass",
350            Self::HookApproved(_) => "hook_approved",
351            Self::UnattendedConfined => "unattended_confined",
352            Self::HostDeclared => "host_declared",
353            Self::Person => "person",
354        }
355    }
356}
357
358/// Who may answer a question a policy asks.
359#[derive(Debug, Clone, Copy, PartialEq, Eq)]
360#[non_exhaustive]
361pub enum Answerable {
362    HookOrPerson,
363    /// The deployment's managed layer asks it: a hook's approve does not
364    /// answer it.
365    PersonOnly,
366}
367
368/// Where in the policy's order a call was refused or asked about.
369#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
370#[non_exhaustive]
371pub enum Stage {
372    ManagedUnreadable,
373    UnknownTool,
374    Credentials,
375    Hook,
376    ToolRefusal,
377    /// The session's sandbox cannot hold the command as fully as
378    /// `sandbox.require` demands.
379    Confinement,
380    Rule,
381    ManagedRule,
382    /// A rule the delegate runs under: its type's deny rules.
383    DelegateRule,
384    BypassImmune,
385    PlanMode,
386    DontAsk,
387    /// A write to the agent's or the repository's configuration, which the
388    /// tool's own word does not let through.
389    Configuration,
390    ModeDefault,
391    Attendance,
392    /// A write under a skill directory a host listed for some session
393    /// (`options.skill_dirs`): read-only to every session.
394    HostSkillDir,
395}
396
397impl Stage {
398    pub fn as_str(self) -> &'static str {
399        match self {
400            Self::ManagedUnreadable => "managed_unreadable",
401            Self::UnknownTool => "unknown_tool",
402            Self::Credentials => "credentials",
403            Self::Hook => "hook",
404            Self::ToolRefusal => "tool_refusal",
405            Self::Confinement => "confinement",
406            Self::Rule => "rule",
407            Self::ManagedRule => "managed_rule",
408            Self::DelegateRule => "delegate_rule",
409            Self::BypassImmune => "bypass_immune",
410            Self::PlanMode => "plan_mode",
411            Self::DontAsk => "dont_ask",
412            Self::Configuration => "configuration",
413            Self::ModeDefault => "mode_default",
414            Self::Attendance => "attendance",
415            Self::HostSkillDir => "host_skill_dir",
416        }
417    }
418}
419
420/// Why a call was refused or asked about.
421#[derive(Debug, Clone, PartialEq, Eq)]
422#[non_exhaustive]
423pub struct Reason {
424    pub stage: Stage,
425    pub rule: Option<PermissionRule>,
426    pub message: String,
427}
428
429impl Reason {
430    pub fn new(stage: Stage, message: impl Into<String>) -> Self {
431        Self {
432            stage,
433            rule: None,
434            message: message.into(),
435        }
436    }
437
438    pub fn with_rule(mut self, rule: PermissionRule) -> Self {
439        self.rule = Some(rule);
440        self
441    }
442}
443
444impl std::fmt::Display for Reason {
445    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
446        f.write_str(&self.message)
447    }
448}
449
450/// One tool call put to a [`PermissionPolicy`].
451#[derive(Clone, Copy)]
452#[non_exhaustive]
453pub struct PermissionRequest<'a> {
454    pub tool_name: &'a str,
455    /// The tool the call dispatches to, looked up in the registry dispatch
456    /// uses. `None` is a name nothing answers to.
457    pub tool: Option<&'a Arc<dyn Tool>>,
458    pub input: &'a serde_json::Value,
459    /// What the tool says about the call, gathered with `ctx`.
460    pub facts: &'a ToolFacts,
461    /// The context the call runs with: the judged session's.
462    pub ctx: &'a ToolContext,
463    /// The live state of the session the policy belongs to: its permission
464    /// mode as it is now, what it has read.
465    pub session: &'a Arc<dyn Session>,
466    /// Set when the call is a delegate's — a sub-agent's, a team member's —
467    /// relayed to this session's policy.
468    pub delegate: Option<Delegate<'a>>,
469    pub hook: &'a HookAnswer,
470    pub attendance: Attendance,
471}
472
473const NO_HOOK: &HookAnswer = &HookAnswer::None;
474
475impl<'a> PermissionRequest<'a> {
476    /// A call no hook answered, as attended as `ctx` says.
477    pub fn new(
478        tool_name: &'a str,
479        tool: Option<&'a Arc<dyn Tool>>,
480        input: &'a serde_json::Value,
481        facts: &'a ToolFacts,
482        ctx: &'a ToolContext,
483        session: &'a Arc<dyn Session>,
484    ) -> Self {
485        Self {
486            tool_name,
487            tool,
488            input,
489            facts,
490            ctx,
491            session,
492            delegate: None,
493            hook: NO_HOOK,
494            attendance: ctx.attendance,
495        }
496    }
497
498    pub fn for_delegate(mut self, delegate: Delegate<'a>) -> Self {
499        self.delegate = Some(delegate);
500        self
501    }
502
503    pub fn with_hook(mut self, hook: &'a HookAnswer) -> Self {
504        self.hook = hook;
505        self
506    }
507
508    pub fn with_attendance(mut self, attendance: Attendance) -> Self {
509        self.attendance = attendance;
510        self
511    }
512
513    /// The state the call is judged against: the delegate's when there is
514    /// one, the session's otherwise.
515    pub fn judged(&self) -> &'a Arc<dyn Session> {
516        self.delegate.map_or(self.session, |d| d.session)
517    }
518}
519
520/// A delegate's call as the session that relays it hands it on: judged
521/// against the delegate's state, in `mode`, and held to `rules` on top of the
522/// policy's own.
523#[derive(Clone, Copy)]
524#[non_exhaustive]
525pub struct Delegate<'a> {
526    /// The session the call runs in.
527    pub session: &'a Arc<dyn Session>,
528    /// The delegate's mode as every session between it and the policy holds
529    /// it (`PermissionMode::for_delegate`, once per relaying session). The
530    /// policy holds it to its own session's mode in turn.
531    pub mode: PermissionMode,
532    /// What the delegation itself adds: its `deny` rules refuse the call in
533    /// any mode; its `allow` rules are the delegate's own grants, which answer
534    /// only the question the mode would put — never a deny, an ask rule, or
535    /// a question only a person may answer.
536    pub rules: &'a [PermissionRule],
537    /// The delegate may only be stricter than each session relaying it: an
538    /// agent type that may not loosen (`AgentTypeSource::may_loosen`) named
539    /// its mode. A session that bypasses does not take it along.
540    pub tightens_only: bool,
541}
542
543impl<'a> Delegate<'a> {
544    /// `session`'s call in its own live mode, with nothing added.
545    pub fn of(session: &'a Arc<dyn Session>) -> Self {
546        Self::new(session, session.permission_mode(), &[])
547    }
548
549    pub fn new(
550        session: &'a Arc<dyn Session>,
551        mode: PermissionMode,
552        rules: &'a [PermissionRule],
553    ) -> Self {
554        Self {
555            session,
556            mode,
557            rules,
558            tightens_only: false,
559        }
560    }
561
562    /// The mode its call is judged in, relayed through a session in `parent`.
563    pub fn mode_under(&self, parent: PermissionMode) -> PermissionMode {
564        if self.tightens_only {
565            self.mode.min_permissive(parent)
566        } else {
567            parent.for_delegate(self.mode)
568        }
569    }
570}
571
572/// Whether a tool call runs. The engine's own is
573/// `permissions::policy::Policy` (rules, modes, the
574/// tools' own verdicts).
575#[async_trait]
576pub trait PermissionPolicy: Send + Sync {
577    async fn decide(&self, req: &PermissionRequest<'_>) -> PermissionOutcome;
578}
579
580/// Which paths a deny rule covers, for a tool that walks a directory on its
581/// own: a search is judged on the directory it starts in, so each file under
582/// it has to be judged as it is reached.
583pub trait PathDenials: Send + Sync {
584    /// The paths `tool` must leave out of its walk. `extra` is the rules a
585    /// delegation adds on top of the policy's own. `None` when no rule
586    /// covers a path.
587    fn denial(
588        &self,
589        tool: &str,
590        cwd: &std::path::Path,
591        extra: &[PermissionRule],
592    ) -> Option<PathDenial>;
593
594    /// The paths `Read` deny rules name outright, resolved from `cwd` as they
595    /// are judged there; a glob other than a trailing `/**` or `/*` names none.
596    fn denied_read_paths(&self, cwd: &std::path::Path, extra: &[PermissionRule]) -> Vec<PathBuf>;
597}
598
599/// Whether a deny rule covers this path.
600pub type PathDenial = Arc<dyn Fn(&std::path::Path) -> bool + Send + Sync>;
601
602/// How long a [`Grant`] lasts.
603#[derive(Clone, Copy, PartialEq, Eq, Debug)]
604#[non_exhaustive]
605pub enum GrantScope {
606    /// Until the next user turn starts: a skill's `allowed-tools`.
607    Turn,
608    /// For the rest of the session: "always allow" answered for this session.
609    Session,
610    /// For this project, kept in its `settings.local.json`; a session with no
611    /// project keeps it for the session.
612    Project,
613}
614
615/// How an allow's content meets a call's.
616#[derive(
617    Clone,
618    Copy,
619    PartialEq,
620    Eq,
621    Debug,
622    Default,
623    serde::Serialize,
624    serde::Deserialize,
625    schemars::JsonSchema,
626)]
627#[serde(rename_all = "lowercase")]
628#[non_exhaustive]
629pub enum GrantMatch {
630    /// As a `settings.json` rule's content is: `*`, `prefix:*`, path and URL
631    /// patterns.
632    #[default]
633    Pattern,
634    /// Only a call whose content is the same text.
635    Exact,
636}
637
638impl GrantMatch {
639    pub fn is_pattern(&self) -> bool {
640        *self == Self::Pattern
641    }
642}
643
644/// An allow for calls to one tool.
645#[derive(Clone, Debug, PartialEq, Eq)]
646#[non_exhaustive]
647pub struct Grant {
648    pub tool_name: String,
649    /// `None` allows every call to the tool. Otherwise matched as `matching`
650    /// says.
651    ///
652    /// A grant relayed from project-controlled data — a skill's frontmatter —
653    /// must not be `None`: anyone who can write a file in the repository could
654    /// then switch off confirmation for `Bash` wholesale.
655    pub content: Option<String>,
656    pub scope: GrantScope,
657    /// A [`GrantScope::Turn`] grant is a skill's rule pattern; a
658    /// [`GrantScope::Session`] or [`GrantScope::Project`] one is a person's
659    /// answer about one call, so it covers that call's content exactly and
660    /// not whatever the text happens to match as a pattern.
661    pub matching: GrantMatch,
662}
663
664impl Grant {
665    pub fn new(tool_name: impl Into<String>, content: Option<String>, scope: GrantScope) -> Self {
666        Self {
667            tool_name: tool_name.into(),
668            content,
669            matching: match scope {
670                GrantScope::Turn => GrantMatch::Pattern,
671                GrantScope::Session | GrantScope::Project => GrantMatch::Exact,
672            },
673            scope,
674        }
675    }
676}
677
678#[derive(Debug, thiserror::Error)]
679#[non_exhaustive]
680pub enum GrantError {
681    /// Kept for the session, but not written where it would outlast it.
682    #[error("kept for this session only, not written to {}: {reason}", .path.display())]
683    NotPersisted { path: PathBuf, reason: String },
684}
685
686/// The file a project-scoped "allow every time" is written to.
687pub trait RuleFile: Send + Sync + std::fmt::Debug {
688    fn path(&self) -> &std::path::Path;
689    /// Add `rule` as an allow. `Ok(false)` when it was already there.
690    fn append_allow(&self, rule: &str, matching: GrantMatch) -> Result<bool, String>;
691}
692
693/// Where the allows handed out during a session are kept.
694#[async_trait]
695pub trait PermissionGrants: Send + Sync {
696    async fn grant(&self, grant: Grant) -> Result<(), GrantError>;
697    /// Drop every grant of `scope`.
698    fn clear(&self, scope: GrantScope);
699}
700
701/// A session's permission: the policy its calls are judged by and where the
702/// allows it is handed are kept. With no `grants` nothing is kept, so nobody
703/// is offered an "allow every time".
704#[derive(Clone)]
705pub struct PermissionSet {
706    pub policy: Arc<dyn PermissionPolicy>,
707    pub grants: Option<Arc<dyn PermissionGrants>>,
708    pub path_denials: Option<Arc<dyn PathDenials>>,
709}
710
711impl PermissionSet {
712    /// One value that both decides and keeps grants, so what it is granted
713    /// changes what it decides.
714    pub fn of<P: PermissionPolicy + PermissionGrants + PathDenials + 'static>(p: Arc<P>) -> Self {
715        Self {
716            policy: p.clone(),
717            grants: Some(p.clone()),
718            path_denials: Some(p),
719        }
720    }
721
722    pub fn without_grants(policy: Arc<dyn PermissionPolicy>) -> Self {
723        Self {
724            policy,
725            grants: None,
726            path_denials: None,
727        }
728    }
729}