use async_trait::async_trait;
use serde_json::Value;
use std::path::PathBuf;
use std::sync::Arc;
use crate::context::Session;
use crate::interface::tool::{CallTraits, Tool, ToolContext, ToolOrigin};
use crate::permission::{PermissionMode, PermissionRule};
mod profile;
pub use profile::{Approval, ExecProfile, Obligations};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum ModeStance {
#[default]
Normal,
Coordination,
LeavesPlan,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum Subject {
#[default]
None,
Opaque(String),
ReadPath(String),
WritePath(String),
Shell(String),
Url(String),
}
impl Subject {
pub fn content(&self) -> Option<&str> {
match self {
Self::None => None,
Self::Opaque(s)
| Self::ReadPath(s)
| Self::WritePath(s)
| Self::Shell(s)
| Self::Url(s) => Some(s),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Reach {
SessionOnly,
Delegates,
Operator,
Inside,
Outside,
EditsProject,
Host {
listed: bool,
},
Server,
Persists(&'static str),
Refused(String),
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Runs {
pub background: bool,
}
impl Runs {
pub fn foreground() -> Self {
Self { background: false }
}
pub fn background() -> Self {
Self { background: true }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Relays {
Web,
McpServer(Option<String>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PermissionFacts {
pub subject: Subject,
pub reach: Reach,
pub runs: Option<Runs>,
pub question: Option<String>,
pub relays: Option<Relays>,
pub also_named: Option<String>,
pub lands_at: Option<std::path::PathBuf>,
pub host_permits: bool,
}
impl PermissionFacts {
pub fn unknown() -> Self {
Self::new(Subject::None, Reach::Unknown)
}
pub fn new(subject: Subject, reach: Reach) -> Self {
Self {
subject,
reach,
runs: None,
question: None,
relays: None,
also_named: None,
lands_at: None,
host_permits: false,
}
}
pub fn with_runs(mut self, runs: Runs) -> Self {
self.runs = Some(runs);
self
}
pub fn with_question(mut self, question: impl Into<String>) -> Self {
self.question = Some(question.into());
self
}
pub fn relaying(mut self, relays: Relays) -> Self {
self.relays = Some(relays);
self
}
pub fn also_named(mut self, name: impl Into<String>) -> Self {
self.also_named = Some(name.into());
self
}
pub fn landing_at(mut self, path: std::path::PathBuf) -> Self {
self.lands_at = Some(path);
self
}
pub fn permitted_by_host(mut self) -> Self {
self.host_permits = true;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ToolFacts {
pub subject: Subject,
pub traits: CallTraits,
pub stance: ModeStance,
pub origin: ToolOrigin,
pub reach: Reach,
pub runs: Option<Runs>,
pub question: Option<String>,
pub relays: Option<Relays>,
pub also_named: Option<String>,
pub lands_at: Option<std::path::PathBuf>,
pub host_permits: bool,
}
impl ToolFacts {
pub async fn gather(tool: &dyn Tool, input: &Value, ctx: &ToolContext) -> Self {
let spec = tool.spec();
let facts = tool.permission_facts(input, ctx).await;
let host_permits = facts.host_permits && spec.origin == ToolOrigin::Host;
Self {
subject: facts.subject,
traits: tool.call_traits(input),
stance: spec.stance,
origin: spec.origin,
reach: facts.reach,
runs: facts.runs,
question: facts.question,
relays: facts.relays,
also_named: facts.also_named,
lands_at: facts.lands_at,
host_permits,
}
}
pub fn unknown_tool() -> Self {
Self {
subject: Subject::None,
traits: CallTraits::default(),
stance: ModeStance::Normal,
origin: ToolOrigin::default(),
reach: Reach::Unknown,
runs: None,
question: None,
relays: None,
also_named: None,
lands_at: None,
host_permits: false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum HookAnswer {
#[default]
None,
Approve {
hook: String,
},
Block {
hook: String,
reason: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Attendance {
Attended,
Unattended,
NoOneToAsk(&'static str),
}
#[derive(Debug, Clone)]
pub enum PermissionOutcome {
Permit {
basis: Basis,
profile: ExecProfile,
obligations: Obligations,
},
Deny {
reason: Reason,
},
Prompt {
prompt_id: String,
message: String,
paths: Vec<PathBuf>,
reason: Reason,
answerable: Answerable,
},
}
impl PermissionOutcome {
pub fn deny(stage: Stage, message: impl Into<String>) -> Self {
Self::Deny {
reason: Reason::new(stage, message),
}
}
pub fn prompt(stage: Stage, message: impl Into<String>) -> Self {
let message = message.into();
Self::Prompt {
prompt_id: uuid::Uuid::new_v4().to_string(),
reason: Reason::new(stage, message.clone()),
message,
paths: Vec::new(),
answerable: Answerable::HookOrPerson,
}
}
pub fn is_permit(&self) -> bool {
matches!(self, Self::Permit { .. })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Basis {
Rule(PermissionRule),
Contained,
AcceptEdits,
Bypass,
HookApproved(String),
UnattendedConfined,
HostDeclared,
Person,
}
impl Basis {
pub fn as_str(&self) -> &'static str {
match self {
Self::Rule(_) => "rule",
Self::Contained => "contained",
Self::AcceptEdits => "accept_edits",
Self::Bypass => "bypass",
Self::HookApproved(_) => "hook_approved",
Self::UnattendedConfined => "unattended_confined",
Self::HostDeclared => "host_declared",
Self::Person => "person",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Answerable {
HookOrPerson,
PersonOnly,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Stage {
ManagedUnreadable,
UnknownTool,
Credentials,
Hook,
ToolRefusal,
Confinement,
Rule,
ManagedRule,
DelegateRule,
BypassImmune,
PlanMode,
DontAsk,
Configuration,
ModeDefault,
Attendance,
HostSkillDir,
}
impl Stage {
pub fn as_str(self) -> &'static str {
match self {
Self::ManagedUnreadable => "managed_unreadable",
Self::UnknownTool => "unknown_tool",
Self::Credentials => "credentials",
Self::Hook => "hook",
Self::ToolRefusal => "tool_refusal",
Self::Confinement => "confinement",
Self::Rule => "rule",
Self::ManagedRule => "managed_rule",
Self::DelegateRule => "delegate_rule",
Self::BypassImmune => "bypass_immune",
Self::PlanMode => "plan_mode",
Self::DontAsk => "dont_ask",
Self::Configuration => "configuration",
Self::ModeDefault => "mode_default",
Self::Attendance => "attendance",
Self::HostSkillDir => "host_skill_dir",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Reason {
pub stage: Stage,
pub rule: Option<PermissionRule>,
pub message: String,
}
impl Reason {
pub fn new(stage: Stage, message: impl Into<String>) -> Self {
Self {
stage,
rule: None,
message: message.into(),
}
}
pub fn with_rule(mut self, rule: PermissionRule) -> Self {
self.rule = Some(rule);
self
}
}
impl std::fmt::Display for Reason {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
#[derive(Clone, Copy)]
#[non_exhaustive]
pub struct PermissionRequest<'a> {
pub tool_name: &'a str,
pub tool: Option<&'a Arc<dyn Tool>>,
pub input: &'a serde_json::Value,
pub facts: &'a ToolFacts,
pub ctx: &'a ToolContext,
pub session: &'a Arc<dyn Session>,
pub delegate: Option<Delegate<'a>>,
pub hook: &'a HookAnswer,
pub attendance: Attendance,
}
const NO_HOOK: &HookAnswer = &HookAnswer::None;
impl<'a> PermissionRequest<'a> {
pub fn new(
tool_name: &'a str,
tool: Option<&'a Arc<dyn Tool>>,
input: &'a serde_json::Value,
facts: &'a ToolFacts,
ctx: &'a ToolContext,
session: &'a Arc<dyn Session>,
) -> Self {
Self {
tool_name,
tool,
input,
facts,
ctx,
session,
delegate: None,
hook: NO_HOOK,
attendance: ctx.attendance,
}
}
pub fn for_delegate(mut self, delegate: Delegate<'a>) -> Self {
self.delegate = Some(delegate);
self
}
pub fn with_hook(mut self, hook: &'a HookAnswer) -> Self {
self.hook = hook;
self
}
pub fn with_attendance(mut self, attendance: Attendance) -> Self {
self.attendance = attendance;
self
}
pub fn judged(&self) -> &'a Arc<dyn Session> {
self.delegate.map_or(self.session, |d| d.session)
}
}
#[derive(Clone, Copy)]
#[non_exhaustive]
pub struct Delegate<'a> {
pub session: &'a Arc<dyn Session>,
pub mode: PermissionMode,
pub rules: &'a [PermissionRule],
pub tightens_only: bool,
}
impl<'a> Delegate<'a> {
pub fn of(session: &'a Arc<dyn Session>) -> Self {
Self::new(session, session.permission_mode(), &[])
}
pub fn new(
session: &'a Arc<dyn Session>,
mode: PermissionMode,
rules: &'a [PermissionRule],
) -> Self {
Self {
session,
mode,
rules,
tightens_only: false,
}
}
pub fn mode_under(&self, parent: PermissionMode) -> PermissionMode {
if self.tightens_only {
self.mode.min_permissive(parent)
} else {
parent.for_delegate(self.mode)
}
}
}
#[async_trait]
pub trait PermissionPolicy: Send + Sync {
async fn decide(&self, req: &PermissionRequest<'_>) -> PermissionOutcome;
}
pub trait PathDenials: Send + Sync {
fn denial(
&self,
tool: &str,
cwd: &std::path::Path,
extra: &[PermissionRule],
) -> Option<PathDenial>;
fn denied_read_paths(&self, cwd: &std::path::Path, extra: &[PermissionRule]) -> Vec<PathBuf>;
}
pub type PathDenial = Arc<dyn Fn(&std::path::Path) -> bool + Send + Sync>;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum GrantScope {
Turn,
Session,
Project,
}
#[derive(
Clone,
Copy,
PartialEq,
Eq,
Debug,
Default,
serde::Serialize,
serde::Deserialize,
schemars::JsonSchema,
)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum GrantMatch {
#[default]
Pattern,
Exact,
}
impl GrantMatch {
pub fn is_pattern(&self) -> bool {
*self == Self::Pattern
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Grant {
pub tool_name: String,
pub content: Option<String>,
pub scope: GrantScope,
pub matching: GrantMatch,
}
impl Grant {
pub fn new(tool_name: impl Into<String>, content: Option<String>, scope: GrantScope) -> Self {
Self {
tool_name: tool_name.into(),
content,
matching: match scope {
GrantScope::Turn => GrantMatch::Pattern,
GrantScope::Session | GrantScope::Project => GrantMatch::Exact,
},
scope,
}
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum GrantError {
#[error("kept for this session only, not written to {}: {reason}", .path.display())]
NotPersisted { path: PathBuf, reason: String },
}
pub trait RuleFile: Send + Sync + std::fmt::Debug {
fn path(&self) -> &std::path::Path;
fn append_allow(&self, rule: &str, matching: GrantMatch) -> Result<bool, String>;
}
#[async_trait]
pub trait PermissionGrants: Send + Sync {
async fn grant(&self, grant: Grant) -> Result<(), GrantError>;
fn clear(&self, scope: GrantScope);
}
#[derive(Clone)]
pub struct PermissionSet {
pub policy: Arc<dyn PermissionPolicy>,
pub grants: Option<Arc<dyn PermissionGrants>>,
pub path_denials: Option<Arc<dyn PathDenials>>,
}
impl PermissionSet {
pub fn of<P: PermissionPolicy + PermissionGrants + PathDenials + 'static>(p: Arc<P>) -> Self {
Self {
policy: p.clone(),
grants: Some(p.clone()),
path_denials: Some(p),
}
}
pub fn without_grants(policy: Arc<dyn PermissionPolicy>) -> Self {
Self {
policy,
grants: None,
path_denials: None,
}
}
}