use async_trait::async_trait;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use super::{
Answerable, Attendance, Basis, ExecProfile, HookAnswer, Obligations, PermissionOutcome,
PermissionPolicy, PermissionRequest, Reach, Reason, Stage, Subject,
};
use crate::interface::exec::Enforcement;
use crate::interface::tool::ToolOrigin;
use crate::permission::{is_path_bypass_immune, RuleBehavior};
pub struct PermitAll {
host: Option<Arc<dyn PermissionPolicy>>,
}
impl PermitAll {
pub fn new(host: Option<Arc<dyn PermissionPolicy>>) -> Self {
Self { host }
}
}
#[async_trait]
impl PermissionPolicy for PermitAll {
async fn decide(&self, req: &PermissionRequest<'_>) -> PermissionOutcome {
match self.judge(req).await {
Judged::Permit(basis) => {
let profile = ExecProfile::for_permit(&basis, req.facts.runs, req.attendance);
PermissionOutcome::Permit {
basis,
profile,
obligations: Obligations::after(req.facts.runs, profile),
}
}
Judged::Otherwise(outcome) => outcome,
}
}
}
enum Judged {
Permit(Basis),
Otherwise(PermissionOutcome),
}
impl PermitAll {
async fn judge(&self, req: &PermissionRequest<'_>) -> Judged {
if let Some((stage, message)) = refusal(req) {
return Judged::Otherwise(PermissionOutcome::deny(stage, message));
}
if let Some(host) = &self.host {
match host.decide(req).await {
PermissionOutcome::Permit { .. } => return Judged::Permit(Basis::NoPolicy),
PermissionOutcome::Deny { reason } => {
return Judged::Otherwise(PermissionOutcome::Deny { reason })
}
PermissionOutcome::Prompt {
reason, answerable, ..
} => return asked(req, reason, answerable, None),
}
}
match default_mode_question(req) {
None => Judged::Permit(Basis::NoPolicy),
Some(reason)
if reason.stage == Stage::ModeDefault
&& req.attendance == Attendance::Unattended
&& req.facts.runs.is_some()
&& matches!(req.facts.reach, Reach::Unknown | Reach::Inside)
&& req.ctx.confinement.holds_unattended() =>
{
Judged::Permit(Basis::UnattendedConfined)
}
Some(reason) => {
let remedy = match req.facts.origin {
ToolOrigin::Host => {
"declare it `permit: \"allow\"`, or build with the `permissions` unit"
}
_ => "build with the `permissions` unit",
};
asked(req, reason, Answerable::HookOrPerson, Some(remedy))
}
}
}
}
fn refusal(req: &PermissionRequest<'_>) -> Option<(Stage, String)> {
if let Some(word) = credential_named(req) {
return Some((
Stage::Credentials,
format!("'{word}' holds credentials; no tool reads or writes it"),
));
}
if let Some(word) = host_skill_dir_named(req) {
return Some((
Stage::HostSkillDir,
format!(
"'{word}' is under a directory of the host's: a skill directory it lists for \
a session or one of its own packages; no tool writes under it, in any \
permission mode"
),
));
}
if let HookAnswer::Block { reason, .. } = req.hook {
return Some((Stage::Hook, format!("Blocked by PreToolUse hook: {reason}")));
}
if req.tool.is_none() {
return Some((
Stage::UnknownTool,
format!("`{}` is not a tool this session has", req.tool_name),
));
}
let held = req.delegate.is_some_and(|d| {
d.rules
.iter()
.any(|rule| rule.behavior != RuleBehavior::Allow)
});
if held {
return Some((
Stage::DelegateRule,
"this call is held to rules of the delegation it runs in, and this build has no \
permission engine to read them"
.into(),
));
}
if runs_in_required_sandbox(req) && req.ctx.confinement.session != Enforcement::Full {
return Some((
Stage::Confinement,
format!(
"Refused: {} would run under a sandbox policy this build cannot enforce all \
of, and `sandbox.require` is on",
req.tool_name
),
));
}
if let Reach::Refused(why) = &req.facts.reach {
return Some((Stage::ToolRefusal, why.clone()));
}
if let Some(word) = bypass_immune_named(req) {
return Some((
Stage::BypassImmune,
format!(
"access to protected path '{word}' is blocked regardless of permission mode \
— this path is bypass-immune"
),
));
}
None
}
fn default_mode_question(req: &PermissionRequest<'_>) -> Option<Reason> {
let facts = req.facts;
if facts.host_permits {
return None;
}
let writes_configuration = !facts.traits.read_only && names_configuration(req);
let background = facts.runs.is_some_and(|r| r.background);
let strict_unheld =
runs_in_required_sandbox(req) && req.ctx.confinement.strict != Enforcement::Full;
let contained = matches!(
facts.reach,
Reach::SessionOnly | Reach::Delegates | Reach::Operator | Reach::Inside
);
if contained && !background && !writes_configuration && !strict_unheld {
return None;
}
let stage = if writes_configuration {
Stage::Configuration
} else {
Stage::ModeDefault
};
let message = match (&facts.origin, &facts.question) {
(ToolOrigin::Host, _) => format!(
"`{}` is a host tool declared to be asked about (`permit: \"ask\"`)",
req.tool_name
),
(_, Some(question)) => question.clone(),
(_, None) => format!("Allow {}?", req.tool_name),
};
Some(Reason::new(stage, message))
}
fn runs_in_required_sandbox(req: &PermissionRequest<'_>) -> bool {
req.facts.runs.is_some()
&& !req.ctx.config.sandbox.disabled
&& req.ctx.confinement.require_enforcement
}
fn asked(
req: &PermissionRequest<'_>,
reason: Reason,
answerable: Answerable,
remedy: Option<&str>,
) -> Judged {
if let (HookAnswer::Approve { hook }, Answerable::HookOrPerson) = (req.hook, answerable) {
return Judged::Permit(Basis::HookApproved(hook.clone()));
}
let why = match req.attendance {
Attendance::Attended => {
return Judged::Otherwise(PermissionOutcome::Prompt {
prompt_id: uuid::Uuid::new_v4().to_string(),
message: reason.message.clone(),
paths: Vec::new(),
reason,
answerable,
})
}
Attendance::Unattended => "nobody is attending this session to approve it",
Attendance::NoOneToAsk(why) => why,
};
let message = match remedy {
Some(remedy) => format!(
"{} — {why}. This build has no permission layer to allow it unattended: {remedy}",
reason.message
),
None => format!("{} — {why}", reason.message),
};
Judged::Otherwise(PermissionOutcome::deny(Stage::Attendance, message))
}
fn credential_named(req: &PermissionRequest<'_>) -> Option<String> {
let sensitive = &req.ctx.config.sandbox.paths;
word_naming(req, |_, paths| {
paths.iter().any(|p| sensitive.is_credential(p))
})
}
fn host_skill_dir_named(req: &PermissionRequest<'_>) -> Option<String> {
if req.facts.traits.read_only || matches!(req.facts.subject, Subject::ReadPath(_)) {
return None;
}
let protected = &req.ctx.session.env().protected_dirs;
word_naming(req, |_, paths| {
paths.iter().any(|p| protected.holding(p).is_some())
})
}
fn bypass_immune_named(req: &PermissionRequest<'_>) -> Option<String> {
let content = req.facts.subject.content()?;
if is_path_bypass_immune(content) {
return Some(content.to_string());
}
word_naming(req, |word, paths| {
is_path_bypass_immune(word)
|| paths
.iter()
.any(|p| is_path_bypass_immune(&p.to_string_lossy()))
})
}
fn names_configuration(req: &PermissionRequest<'_>) -> bool {
let sensitive = &req.ctx.config.sandbox.paths;
word_naming(req, |word, paths| {
sensitive.names_configuration(word)
|| paths
.iter()
.any(|p| sensitive.names_configuration(&p.to_string_lossy()))
})
.is_some()
}
fn word_naming(
req: &PermissionRequest<'_>,
names: impl Fn(&str, &[PathBuf]) -> bool,
) -> Option<String> {
let content = req.facts.subject.content()?;
let words: Vec<String> = match &req.facts.subject {
Subject::Shell(line) => line
.split(|c: char| c.is_whitespace() || ";|&<>()`".contains(c))
.map(|word| word.replace(['\'', '"', '\\'], ""))
.collect(),
_ => vec![content.to_string()],
};
words.into_iter().find(|word| {
std::iter::once(word.as_str())
.chain(word.split_once('=').map(|(_, value)| value))
.filter(|w| !w.is_empty())
.any(|w| names(w, &spellings(w, &req.ctx.cwd)))
})
}
fn spellings(word: &str, cwd: &Path) -> Vec<PathBuf> {
let written = match word.strip_prefix("~/").zip(crate::paths::home_dir()) {
Some((rest, home)) => home.join(rest),
None => cwd.join(word),
};
let lexical = crate::path::normalize_lexically(&written);
vec![
crate::path::resolve_physically(&lexical),
crate::path::resolve_physically(&written),
lexical,
]
}