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 profile;
16pub use profile::{Approval, ExecProfile, Obligations};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
20#[non_exhaustive]
21pub enum ModeStance {
22 #[default]
23 Normal,
24 Coordination,
27 LeavesPlan,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq, Default)]
34#[non_exhaustive]
35pub enum Subject {
36 #[default]
37 None,
38 Opaque(String),
40 ReadPath(String),
42 WritePath(String),
44 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#[derive(Debug, Clone, PartialEq, Eq)]
64#[non_exhaustive]
65pub enum Reach {
66 SessionOnly,
68 Delegates,
70 Operator,
72 Inside,
75 Outside,
77 EditsProject,
80 Host {
82 listed: bool,
83 },
84 Server,
86 Persists(&'static str),
88 Refused(String),
90 Unknown,
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95#[non_exhaustive]
96pub struct Runs {
97 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#[derive(Debug, Clone, PartialEq, Eq)]
113#[non_exhaustive]
114pub enum Relays {
115 Web,
117 McpServer(Option<String>),
119}
120
121#[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 pub question: Option<String>,
131 pub relays: Option<Relays>,
132 pub also_named: Option<String>,
135 pub lands_at: Option<std::path::PathBuf>,
138 pub host_permits: bool,
141}
142
143impl PermissionFacts {
144 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#[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 pub host_permits: bool,
212}
213
214impl ToolFacts {
215 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 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271#[non_exhaustive]
272pub enum Attendance {
273 Attended,
274 Unattended,
275 NoOneToAsk(&'static str),
277}
278
279#[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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
327#[non_exhaustive]
328pub enum Basis {
329 Rule(PermissionRule),
330 Contained,
332 AcceptEdits,
333 Bypass,
334 HookApproved(String),
336 UnattendedConfined,
338 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
360#[non_exhaustive]
361pub enum Answerable {
362 HookOrPerson,
363 PersonOnly,
366}
367
368#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
370#[non_exhaustive]
371pub enum Stage {
372 ManagedUnreadable,
373 UnknownTool,
374 Credentials,
375 Hook,
376 ToolRefusal,
377 Confinement,
380 Rule,
381 ManagedRule,
382 DelegateRule,
384 BypassImmune,
385 PlanMode,
386 DontAsk,
387 Configuration,
390 ModeDefault,
391 Attendance,
392 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#[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#[derive(Clone, Copy)]
452#[non_exhaustive]
453pub struct PermissionRequest<'a> {
454 pub tool_name: &'a str,
455 pub tool: Option<&'a Arc<dyn Tool>>,
458 pub input: &'a serde_json::Value,
459 pub facts: &'a ToolFacts,
461 pub ctx: &'a ToolContext,
463 pub session: &'a Arc<dyn Session>,
466 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 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 pub fn judged(&self) -> &'a Arc<dyn Session> {
516 self.delegate.map_or(self.session, |d| d.session)
517 }
518}
519
520#[derive(Clone, Copy)]
524#[non_exhaustive]
525pub struct Delegate<'a> {
526 pub session: &'a Arc<dyn Session>,
528 pub mode: PermissionMode,
532 pub rules: &'a [PermissionRule],
537 pub tightens_only: bool,
541}
542
543impl<'a> Delegate<'a> {
544 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 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#[async_trait]
576pub trait PermissionPolicy: Send + Sync {
577 async fn decide(&self, req: &PermissionRequest<'_>) -> PermissionOutcome;
578}
579
580pub trait PathDenials: Send + Sync {
584 fn denial(
588 &self,
589 tool: &str,
590 cwd: &std::path::Path,
591 extra: &[PermissionRule],
592 ) -> Option<PathDenial>;
593
594 fn denied_read_paths(&self, cwd: &std::path::Path, extra: &[PermissionRule]) -> Vec<PathBuf>;
597}
598
599pub type PathDenial = Arc<dyn Fn(&std::path::Path) -> bool + Send + Sync>;
601
602#[derive(Clone, Copy, PartialEq, Eq, Debug)]
604#[non_exhaustive]
605pub enum GrantScope {
606 Turn,
608 Session,
610 Project,
613}
614
615#[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 #[default]
633 Pattern,
634 Exact,
636}
637
638impl GrantMatch {
639 pub fn is_pattern(&self) -> bool {
640 *self == Self::Pattern
641 }
642}
643
644#[derive(Clone, Debug, PartialEq, Eq)]
646#[non_exhaustive]
647pub struct Grant {
648 pub tool_name: String,
649 pub content: Option<String>,
656 pub scope: GrantScope,
657 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 #[error("kept for this session only, not written to {}: {reason}", .path.display())]
683 NotPersisted { path: PathBuf, reason: String },
684}
685
686pub trait RuleFile: Send + Sync + std::fmt::Debug {
688 fn path(&self) -> &std::path::Path;
689 fn append_allow(&self, rule: &str, matching: GrantMatch) -> Result<bool, String>;
691}
692
693#[async_trait]
695pub trait PermissionGrants: Send + Sync {
696 async fn grant(&self, grant: Grant) -> Result<(), GrantError>;
697 fn clear(&self, scope: GrantScope);
699}
700
701#[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 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}