mirror of
https://github.com/instructkr/claw-code.git
synced 2026-10-28 00:05:50 +08:00
* fix(runtime): prompt permission mode never invokes the prompter
PermissionMode derives Ord from declaration order, placing Prompt (and Allow)
above the real privilege ladder (ReadOnly < WorkspaceWrite < DangerFullAccess).
In PermissionPolicy::authorize_with_context the ladder check
'current_mode >= required_mode' therefore evaluates true for every tool when the
active mode is Prompt (3 >= {0,1,2}), returning Allow and making the subsequent
'if current_mode == PermissionMode::Prompt' branch that routes to prompt_or_deny
unreachable.
Effect: a session configured with the 'prompt' permission mode silently
auto-allows every tool and never calls the prompter (reached via
ConversationRuntime::run_turn with an interactive prompter), defeating the mode's
entire purpose. The sibling PermissionEnforcer already special-cases Prompt
before its own 'active_mode >= required_mode' check, confirming Prompt is not
meant to be part of the ordered ladder.
Fix: exclude Prompt from the ordered-ladder comparison so Prompt mode falls
through to the interactive prompt path. Allow remains handled by its explicit
equality check. The same comparison appears twice in authorize_with_context —
once in the shared tail and once inside the 'Some(PermissionOverride::Allow)'
arm, which is reached when a hook emits permissionDecision "allow" — so both
copies carry the guard; guarding only the tail still left a hook able to
auto-allow every tool in Prompt mode without ever consulting the prompter.
Adds regression tests covering Prompt mode with a prompter, without a prompter,
and with a hook allow override.
* refactor(runtime): make the permission privilege ladder an explicit rank
`PermissionMode` derived `PartialOrd`/`Ord`, so the ladder deciding whether a
tool runs without asking was declaration order. A variant inserted in the middle
of the enum re-ranked it silently, and the difference between "this tool may
run" and "this tool may run after a prompt" was a property of where an `enum`
line happened to sit. That is how `Prompt` came to outrank `DangerFullAccess`,
satisfy `current_mode >= required_mode` for every tool, and skip the prompter.
Replace the derive with `privilege_rank`, an exhaustive `match` naming every
variant, so inserting one is a build failure rather than a silent re-ranking.
`Ord` is deliberately not derived, so a stray `>=` on two modes no longer
compiles; the two comparisons outside this module now say which rank they read
(`PermissionEnforcer::check_with_required_mode` and the `claw doctor` permission
check). Both keep their previous answers, since `privilege_rank` reproduces the
old declaration order exactly, including `Prompt` and `Allow` above the tiers.
`Prompt` and `Allow` are modes of operation, not privilege tiers, so they are
never ranked *against* a tool requirement. The new `covers` predicate states
that by name rather than by number: `Allow` always covers, `Prompt` never does
(it asks), and only the three tiers compare ranks.
That also collapses the duplicated ladder in `authorize_with_context`. The
`Some(PermissionOverride::Allow)` arm carried a second, identical copy of the
ask-rule check and the ladder; it now falls through to the single copy below,
so a hook `allow` is an override rather than a bypass and the two copies can no
longer drift apart.
Behaviour is unchanged for every (mode, requirement, rule, override)
combination. The tests pin the `Prompt` routes — plain and hook-`allow` — across
all three tiers, plus the rank ordering itself.
894 lines
30 KiB
Rust
894 lines
30 KiB
Rust
use std::collections::BTreeMap;
|
|
|
|
use serde_json::Value;
|
|
|
|
use crate::config::RuntimePermissionRuleConfig;
|
|
|
|
/// Permission level assigned to a tool invocation or runtime session.
|
|
///
|
|
/// Deliberately **not** `PartialOrd`/`Ord`: see [`PermissionMode::privilege_rank`]
|
|
/// for why ordering is a named function here rather than declaration order.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum PermissionMode {
|
|
ReadOnly,
|
|
WorkspaceWrite,
|
|
DangerFullAccess,
|
|
Prompt,
|
|
Allow,
|
|
}
|
|
|
|
impl PermissionMode {
|
|
#[must_use]
|
|
pub fn as_str(self) -> &'static str {
|
|
match self {
|
|
Self::ReadOnly => "read-only",
|
|
Self::WorkspaceWrite => "workspace-write",
|
|
Self::DangerFullAccess => "danger-full-access",
|
|
Self::Prompt => "prompt",
|
|
Self::Allow => "allow",
|
|
}
|
|
}
|
|
|
|
/// Position on the privilege ladder used by [`PermissionPolicy`].
|
|
///
|
|
/// This is the only ranking, and `Ord` is intentionally not derived, so a
|
|
/// stray `active_mode >= required_mode` no longer compiles. Ranking through
|
|
/// declaration order meant a variant inserted in the middle of the enum
|
|
/// silently re-ranked the ladder, and the difference between "this tool may
|
|
/// run" and "this tool may run after a prompt" was therefore a property of
|
|
/// where an `enum` line happened to sit. Every variant is named here, so an
|
|
/// insertion is a build failure instead of a silent re-ranking; the two
|
|
/// comparisons outside this module that do read a rank — the
|
|
/// `PermissionEnforcer`'s `check_with_required_mode` and the `claw doctor`
|
|
/// permission check — now say so at the call site.
|
|
///
|
|
/// `Prompt` and `Allow` are *modes of operation*, not privilege tiers. They
|
|
/// rank above every tier so those two callers keep the answers they had, but
|
|
/// they are never ranked *against* a tier: see [`Self::covers`].
|
|
#[must_use]
|
|
pub const fn privilege_rank(self) -> u8 {
|
|
match self {
|
|
Self::ReadOnly => 0,
|
|
Self::WorkspaceWrite => 1,
|
|
Self::DangerFullAccess => 2,
|
|
Self::Prompt => 3,
|
|
Self::Allow => 4,
|
|
}
|
|
}
|
|
|
|
/// Whether a session running in `self` may use a tool that requires
|
|
/// `required` without asking.
|
|
///
|
|
/// Only tiers answer this by rank. `Allow` never asks and `Prompt` always
|
|
/// asks — it is the exact opposite of a silent allow — so neither is a
|
|
/// statement about how much of the workspace the session may touch, and
|
|
/// comparing either to `required` is comparing a mode to a tier. That
|
|
/// comparison is what let `Prompt`, which outranks `DangerFullAccess`, make
|
|
/// the ladder return `Allow` for every tool and skip the prompter entirely.
|
|
#[must_use]
|
|
pub const fn covers(self, required: Self) -> bool {
|
|
match self {
|
|
Self::Allow => true,
|
|
Self::Prompt => false,
|
|
Self::ReadOnly | Self::WorkspaceWrite | Self::DangerFullAccess => {
|
|
self.privilege_rank() >= required.privilege_rank()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Hook-provided override applied before standard permission evaluation.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum PermissionOverride {
|
|
Allow,
|
|
Deny,
|
|
Ask,
|
|
}
|
|
|
|
/// Additional permission context supplied by hooks or higher-level orchestration.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
|
pub struct PermissionContext {
|
|
override_decision: Option<PermissionOverride>,
|
|
override_reason: Option<String>,
|
|
}
|
|
|
|
impl PermissionContext {
|
|
#[must_use]
|
|
pub fn new(
|
|
override_decision: Option<PermissionOverride>,
|
|
override_reason: Option<String>,
|
|
) -> Self {
|
|
Self {
|
|
override_decision,
|
|
override_reason,
|
|
}
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn override_decision(&self) -> Option<PermissionOverride> {
|
|
self.override_decision
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn override_reason(&self) -> Option<&str> {
|
|
self.override_reason.as_deref()
|
|
}
|
|
}
|
|
|
|
/// Full authorization request presented to a permission prompt.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct PermissionRequest {
|
|
pub tool_name: String,
|
|
pub input: String,
|
|
pub current_mode: PermissionMode,
|
|
pub required_mode: PermissionMode,
|
|
pub reason: Option<String>,
|
|
}
|
|
|
|
/// User-facing decision returned by a [`PermissionPrompter`].
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum PermissionPromptDecision {
|
|
Allow,
|
|
Deny { reason: String },
|
|
}
|
|
|
|
/// Prompting interface used when policy requires interactive approval.
|
|
pub trait PermissionPrompter {
|
|
fn decide(&mut self, request: &PermissionRequest) -> PermissionPromptDecision;
|
|
}
|
|
|
|
/// Final authorization result after evaluating static rules and prompts.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum PermissionOutcome {
|
|
Allow,
|
|
Deny { reason: String },
|
|
}
|
|
|
|
/// Evaluates permission mode requirements plus allow/deny/ask rules.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct PermissionPolicy {
|
|
active_mode: PermissionMode,
|
|
tool_requirements: BTreeMap<String, PermissionMode>,
|
|
allow_rules: Vec<PermissionRule>,
|
|
deny_rules: Vec<PermissionRule>,
|
|
ask_rules: Vec<PermissionRule>,
|
|
/// #159: simple tool-name denials. Tools in this list are unconditionally
|
|
/// denied regardless of permission mode, checked before the rule-based
|
|
/// deny/allow/ask evaluation.
|
|
denied_tools: Vec<String>,
|
|
}
|
|
|
|
impl PermissionPolicy {
|
|
#[must_use]
|
|
pub fn new(active_mode: PermissionMode) -> Self {
|
|
Self {
|
|
active_mode,
|
|
tool_requirements: BTreeMap::new(),
|
|
allow_rules: Vec::new(),
|
|
deny_rules: Vec::new(),
|
|
ask_rules: Vec::new(),
|
|
denied_tools: Vec::new(),
|
|
}
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn with_tool_requirement(
|
|
mut self,
|
|
tool_name: impl Into<String>,
|
|
required_mode: PermissionMode,
|
|
) -> Self {
|
|
self.tool_requirements
|
|
.insert(tool_name.into(), required_mode);
|
|
self
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn with_permission_rules(mut self, config: &RuntimePermissionRuleConfig) -> Self {
|
|
self.allow_rules = config
|
|
.allow()
|
|
.iter()
|
|
.map(|rule| PermissionRule::parse(rule))
|
|
.collect();
|
|
self.deny_rules = config
|
|
.deny()
|
|
.iter()
|
|
.map(|rule| PermissionRule::parse(rule))
|
|
.collect();
|
|
self.ask_rules = config
|
|
.ask()
|
|
.iter()
|
|
.map(|rule| PermissionRule::parse(rule))
|
|
.collect();
|
|
// #94: normalize denied tool names to lowercase to match runtime convention
|
|
self.denied_tools = config
|
|
.denied_tools()
|
|
.iter()
|
|
.map(|t| t.to_lowercase())
|
|
.collect();
|
|
self
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn active_mode(&self) -> PermissionMode {
|
|
self.active_mode
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn required_mode_for(&self, tool_name: &str) -> PermissionMode {
|
|
self.tool_requirements
|
|
.get(tool_name)
|
|
.copied()
|
|
.unwrap_or(PermissionMode::DangerFullAccess)
|
|
}
|
|
|
|
#[must_use]
|
|
pub fn authorize(
|
|
&self,
|
|
tool_name: &str,
|
|
input: &str,
|
|
prompter: Option<&mut dyn PermissionPrompter>,
|
|
) -> PermissionOutcome {
|
|
self.authorize_with_context(tool_name, input, &PermissionContext::default(), prompter)
|
|
}
|
|
|
|
#[must_use]
|
|
#[allow(clippy::too_many_lines)]
|
|
pub fn authorize_with_context(
|
|
&self,
|
|
tool_name: &str,
|
|
input: &str,
|
|
context: &PermissionContext,
|
|
prompter: Option<&mut dyn PermissionPrompter>,
|
|
) -> PermissionOutcome {
|
|
// #159: check denied_tools before rule-based evaluation. Tools listed
|
|
// in the denied_tools config are unconditionally denied regardless of
|
|
// permission mode.
|
|
if self.denied_tools.iter().any(|t| t == tool_name) {
|
|
return PermissionOutcome::Deny {
|
|
reason: format!("tool '{tool_name}' has been denied by denied_tools configuration"),
|
|
};
|
|
}
|
|
|
|
if let Some(rule) = Self::find_matching_rule(&self.deny_rules, tool_name, input) {
|
|
return PermissionOutcome::Deny {
|
|
reason: format!(
|
|
"Permission to use {tool_name} has been denied by rule '{}'",
|
|
rule.raw
|
|
),
|
|
};
|
|
}
|
|
|
|
let current_mode = self.active_mode();
|
|
let required_mode = self.required_mode_for(tool_name);
|
|
let ask_rule = Self::find_matching_rule(&self.ask_rules, tool_name, input);
|
|
let allow_rule = Self::find_matching_rule(&self.allow_rules, tool_name, input);
|
|
|
|
match context.override_decision() {
|
|
Some(PermissionOverride::Deny) => {
|
|
return PermissionOutcome::Deny {
|
|
reason: context.override_reason().map_or_else(
|
|
|| format!("tool '{tool_name}' denied by hook"),
|
|
ToOwned::to_owned,
|
|
),
|
|
};
|
|
}
|
|
Some(PermissionOverride::Ask) => {
|
|
let reason = context.override_reason().map_or_else(
|
|
|| format!("tool '{tool_name}' requires approval due to hook guidance"),
|
|
ToOwned::to_owned,
|
|
);
|
|
return Self::prompt_or_deny(
|
|
tool_name,
|
|
input,
|
|
current_mode,
|
|
required_mode,
|
|
Some(reason),
|
|
prompter,
|
|
);
|
|
}
|
|
// A hook `allow` is an override, not a bypass: the ask-rule check
|
|
// and the privilege ladder below still run for it. Both used to be
|
|
// spelled out a second time inside this arm, which is why the ladder
|
|
// existed in two copies that had to be corrected in step — and the
|
|
// second copy is exactly what a fix for one of them is easy to miss.
|
|
Some(PermissionOverride::Allow) | None => {}
|
|
}
|
|
|
|
if let Some(rule) = ask_rule {
|
|
let reason = format!(
|
|
"tool '{tool_name}' requires approval due to ask rule '{}'",
|
|
rule.raw
|
|
);
|
|
return Self::prompt_or_deny(
|
|
tool_name,
|
|
input,
|
|
current_mode,
|
|
required_mode,
|
|
Some(reason),
|
|
prompter,
|
|
);
|
|
}
|
|
|
|
// The ladder, in one place. An `allow` rule is an explicit grant for
|
|
// this tool and outranks the mode; otherwise the mode decides through
|
|
// [`PermissionMode::covers`].
|
|
if allow_rule.is_some() || current_mode.covers(required_mode) {
|
|
return PermissionOutcome::Allow;
|
|
}
|
|
|
|
if current_mode == PermissionMode::Prompt
|
|
|| (current_mode == PermissionMode::WorkspaceWrite
|
|
&& required_mode == PermissionMode::DangerFullAccess)
|
|
{
|
|
let reason = Some(format!(
|
|
"tool '{tool_name}' requires approval to escalate from {} to {}",
|
|
current_mode.as_str(),
|
|
required_mode.as_str()
|
|
));
|
|
return Self::prompt_or_deny(
|
|
tool_name,
|
|
input,
|
|
current_mode,
|
|
required_mode,
|
|
reason,
|
|
prompter,
|
|
);
|
|
}
|
|
|
|
PermissionOutcome::Deny {
|
|
reason: format!(
|
|
"tool '{tool_name}' requires {} permission; current mode is {}",
|
|
required_mode.as_str(),
|
|
current_mode.as_str()
|
|
),
|
|
}
|
|
}
|
|
|
|
fn prompt_or_deny(
|
|
tool_name: &str,
|
|
input: &str,
|
|
current_mode: PermissionMode,
|
|
required_mode: PermissionMode,
|
|
reason: Option<String>,
|
|
mut prompter: Option<&mut dyn PermissionPrompter>,
|
|
) -> PermissionOutcome {
|
|
let request = PermissionRequest {
|
|
tool_name: tool_name.to_string(),
|
|
input: input.to_string(),
|
|
current_mode,
|
|
required_mode,
|
|
reason: reason.clone(),
|
|
};
|
|
|
|
match prompter.as_mut() {
|
|
Some(prompter) => match prompter.decide(&request) {
|
|
PermissionPromptDecision::Allow => PermissionOutcome::Allow,
|
|
PermissionPromptDecision::Deny { reason } => PermissionOutcome::Deny { reason },
|
|
},
|
|
None => PermissionOutcome::Deny {
|
|
reason: reason.unwrap_or_else(|| {
|
|
format!(
|
|
"tool '{tool_name}' requires approval to run while mode is {}",
|
|
current_mode.as_str()
|
|
)
|
|
}),
|
|
},
|
|
}
|
|
}
|
|
|
|
fn find_matching_rule<'a>(
|
|
rules: &'a [PermissionRule],
|
|
tool_name: &str,
|
|
input: &str,
|
|
) -> Option<&'a PermissionRule> {
|
|
rules.iter().find(|rule| rule.matches(tool_name, input))
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
struct PermissionRule {
|
|
raw: String,
|
|
tool_name: String,
|
|
matcher: PermissionRuleMatcher,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
enum PermissionRuleMatcher {
|
|
Any,
|
|
Exact(String),
|
|
Prefix(String),
|
|
}
|
|
|
|
impl PermissionRule {
|
|
fn parse(raw: &str) -> Self {
|
|
let trimmed = raw.trim();
|
|
let open = find_first_unescaped(trimmed, '(');
|
|
let close = find_last_unescaped(trimmed, ')');
|
|
|
|
if let (Some(open), Some(close)) = (open, close) {
|
|
if close == trimmed.len() - 1 && open < close {
|
|
let tool_name = trimmed[..open].trim();
|
|
let content = &trimmed[open + 1..close];
|
|
if !tool_name.is_empty() {
|
|
let matcher = parse_rule_matcher(content);
|
|
return Self {
|
|
raw: trimmed.to_string(),
|
|
// #94: normalize tool name to lowercase to match runtime convention
|
|
tool_name: tool_name.to_lowercase(),
|
|
matcher,
|
|
};
|
|
}
|
|
}
|
|
}
|
|
|
|
Self {
|
|
raw: trimmed.to_string(),
|
|
// #94: normalize tool name to lowercase to match runtime convention
|
|
tool_name: trimmed.to_lowercase(),
|
|
matcher: PermissionRuleMatcher::Any,
|
|
}
|
|
}
|
|
|
|
fn matches(&self, tool_name: &str, input: &str) -> bool {
|
|
if self.tool_name != tool_name {
|
|
return false;
|
|
}
|
|
|
|
match &self.matcher {
|
|
PermissionRuleMatcher::Any => true,
|
|
PermissionRuleMatcher::Exact(expected) => {
|
|
extract_permission_subject(input).is_some_and(|candidate| candidate == *expected)
|
|
}
|
|
PermissionRuleMatcher::Prefix(prefix) => extract_permission_subject(input)
|
|
.is_some_and(|candidate| candidate.starts_with(prefix)),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn parse_rule_matcher(content: &str) -> PermissionRuleMatcher {
|
|
let unescaped = unescape_rule_content(content.trim());
|
|
if unescaped.is_empty() || unescaped == "*" {
|
|
PermissionRuleMatcher::Any
|
|
} else if let Some(prefix) = unescaped.strip_suffix(":*") {
|
|
PermissionRuleMatcher::Prefix(prefix.to_string())
|
|
} else {
|
|
PermissionRuleMatcher::Exact(unescaped)
|
|
}
|
|
}
|
|
|
|
fn unescape_rule_content(content: &str) -> String {
|
|
content
|
|
.replace(r"\(", "(")
|
|
.replace(r"\)", ")")
|
|
.replace(r"\\", r"\")
|
|
}
|
|
|
|
fn find_first_unescaped(value: &str, needle: char) -> Option<usize> {
|
|
let mut escaped = false;
|
|
for (idx, ch) in value.char_indices() {
|
|
if ch == '\\' {
|
|
escaped = !escaped;
|
|
continue;
|
|
}
|
|
if ch == needle && !escaped {
|
|
return Some(idx);
|
|
}
|
|
escaped = false;
|
|
}
|
|
None
|
|
}
|
|
|
|
fn find_last_unescaped(value: &str, needle: char) -> Option<usize> {
|
|
let chars = value.char_indices().collect::<Vec<_>>();
|
|
for (pos, (idx, ch)) in chars.iter().enumerate().rev() {
|
|
if *ch != needle {
|
|
continue;
|
|
}
|
|
let mut backslashes = 0;
|
|
for (_, prev) in chars[..pos].iter().rev() {
|
|
if *prev == '\\' {
|
|
backslashes += 1;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
if backslashes % 2 == 0 {
|
|
return Some(*idx);
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
fn extract_permission_subject(input: &str) -> Option<String> {
|
|
let parsed = serde_json::from_str::<Value>(input).ok();
|
|
if let Some(Value::Object(object)) = parsed {
|
|
for key in [
|
|
"command",
|
|
"path",
|
|
"file_path",
|
|
"filePath",
|
|
"notebook_path",
|
|
"notebookPath",
|
|
"url",
|
|
"pattern",
|
|
"code",
|
|
"message",
|
|
] {
|
|
if let Some(value) = object.get(key).and_then(Value::as_str) {
|
|
return Some(value.to_string());
|
|
}
|
|
}
|
|
}
|
|
|
|
(!input.trim().is_empty()).then(|| input.to_string())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::{
|
|
PermissionContext, PermissionMode, PermissionOutcome, PermissionOverride, PermissionPolicy,
|
|
PermissionPromptDecision, PermissionPrompter, PermissionRequest,
|
|
};
|
|
use crate::config::RuntimePermissionRuleConfig;
|
|
|
|
struct RecordingPrompter {
|
|
seen: Vec<PermissionRequest>,
|
|
allow: bool,
|
|
}
|
|
|
|
impl PermissionPrompter for RecordingPrompter {
|
|
fn decide(&mut self, request: &PermissionRequest) -> PermissionPromptDecision {
|
|
self.seen.push(request.clone());
|
|
if self.allow {
|
|
PermissionPromptDecision::Allow
|
|
} else {
|
|
PermissionPromptDecision::Deny {
|
|
reason: "not now".to_string(),
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn allows_tools_when_active_mode_meets_requirement() {
|
|
let policy = PermissionPolicy::new(PermissionMode::WorkspaceWrite)
|
|
.with_tool_requirement("read_file", PermissionMode::ReadOnly)
|
|
.with_tool_requirement("write_file", PermissionMode::WorkspaceWrite);
|
|
|
|
assert_eq!(
|
|
policy.authorize("read_file", "{}", None),
|
|
PermissionOutcome::Allow
|
|
);
|
|
assert_eq!(
|
|
policy.authorize("write_file", "{}", None),
|
|
PermissionOutcome::Allow
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn denies_read_only_escalations_without_prompt() {
|
|
let policy = PermissionPolicy::new(PermissionMode::ReadOnly)
|
|
.with_tool_requirement("write_file", PermissionMode::WorkspaceWrite)
|
|
.with_tool_requirement("bash", PermissionMode::DangerFullAccess);
|
|
|
|
assert!(matches!(
|
|
policy.authorize("write_file", "{}", None),
|
|
PermissionOutcome::Deny { reason } if reason.contains("requires workspace-write permission")
|
|
));
|
|
assert!(matches!(
|
|
policy.authorize("bash", "{}", None),
|
|
PermissionOutcome::Deny { reason } if reason.contains("requires danger-full-access permission")
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn prompts_for_workspace_write_to_danger_full_access_escalation() {
|
|
let policy = PermissionPolicy::new(PermissionMode::WorkspaceWrite)
|
|
.with_tool_requirement("bash", PermissionMode::DangerFullAccess);
|
|
let mut prompter = RecordingPrompter {
|
|
seen: Vec::new(),
|
|
allow: true,
|
|
};
|
|
|
|
let outcome = policy.authorize("bash", "echo hi", Some(&mut prompter));
|
|
|
|
assert_eq!(outcome, PermissionOutcome::Allow);
|
|
assert_eq!(prompter.seen.len(), 1);
|
|
assert_eq!(prompter.seen[0].tool_name, "bash");
|
|
assert_eq!(
|
|
prompter.seen[0].current_mode,
|
|
PermissionMode::WorkspaceWrite
|
|
);
|
|
assert_eq!(
|
|
prompter.seen[0].required_mode,
|
|
PermissionMode::DangerFullAccess
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn honors_prompt_rejection_reason() {
|
|
let policy = PermissionPolicy::new(PermissionMode::WorkspaceWrite)
|
|
.with_tool_requirement("bash", PermissionMode::DangerFullAccess);
|
|
let mut prompter = RecordingPrompter {
|
|
seen: Vec::new(),
|
|
allow: false,
|
|
};
|
|
|
|
assert!(matches!(
|
|
policy.authorize("bash", "echo hi", Some(&mut prompter)),
|
|
PermissionOutcome::Deny { reason } if reason == "not now"
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn prompt_mode_routes_to_prompter_instead_of_auto_allowing() {
|
|
// Regression: `Prompt` sorts above `DangerFullAccess` in the
|
|
// `PermissionMode` `Ord` derivation, so the `current_mode >= required_mode`
|
|
// ladder check used to auto-allow every tool in `Prompt` mode and never
|
|
// invoke the prompter — defeating the entire purpose of the mode.
|
|
let policy = PermissionPolicy::new(PermissionMode::Prompt)
|
|
.with_tool_requirement("read_file", PermissionMode::ReadOnly);
|
|
let mut prompter = RecordingPrompter {
|
|
seen: Vec::new(),
|
|
allow: true,
|
|
};
|
|
|
|
let outcome = policy.authorize("read_file", "{}", Some(&mut prompter));
|
|
|
|
assert_eq!(outcome, PermissionOutcome::Allow);
|
|
assert_eq!(prompter.seen.len(), 1);
|
|
assert_eq!(prompter.seen[0].tool_name, "read_file");
|
|
assert_eq!(prompter.seen[0].current_mode, PermissionMode::Prompt);
|
|
}
|
|
|
|
#[test]
|
|
fn prompt_mode_denies_when_no_prompter_is_available() {
|
|
let policy = PermissionPolicy::new(PermissionMode::Prompt)
|
|
.with_tool_requirement("read_file", PermissionMode::ReadOnly);
|
|
|
|
assert!(matches!(
|
|
policy.authorize("read_file", "{}", None),
|
|
PermissionOutcome::Deny { .. }
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn prompt_mode_prompts_for_every_privilege_tier() {
|
|
// The ladder used to exist twice — once on the plain path and once inside
|
|
// the `Some(PermissionOverride::Allow)` arm — so a hook emitting
|
|
// `permissionDecision: "allow"` (see `hooks.rs`) had its own route to the
|
|
// auto-allow. Sweeping the tiers against both routes keeps them honest now
|
|
// that they are one predicate.
|
|
for required in [
|
|
PermissionMode::ReadOnly,
|
|
PermissionMode::WorkspaceWrite,
|
|
PermissionMode::DangerFullAccess,
|
|
] {
|
|
for override_decision in [None, Some(PermissionOverride::Allow)] {
|
|
let policy = PermissionPolicy::new(PermissionMode::Prompt)
|
|
.with_tool_requirement("read_file", required);
|
|
let context = PermissionContext::new(
|
|
override_decision,
|
|
override_decision.map(|_| "hook approved".to_string()),
|
|
);
|
|
let mut prompter = RecordingPrompter {
|
|
seen: Vec::new(),
|
|
allow: true,
|
|
};
|
|
|
|
let outcome =
|
|
policy.authorize_with_context("read_file", "{}", &context, Some(&mut prompter));
|
|
|
|
assert_eq!(
|
|
outcome,
|
|
PermissionOutcome::Allow,
|
|
"an approving prompter must still pass a {required:?} tool"
|
|
);
|
|
assert_eq!(
|
|
prompter.seen.len(),
|
|
1,
|
|
"prompt mode skipped the prompter for a {required:?} tool \
|
|
(override = {override_decision:?})"
|
|
);
|
|
assert_eq!(prompter.seen[0].tool_name, "read_file");
|
|
assert_eq!(prompter.seen[0].current_mode, PermissionMode::Prompt);
|
|
assert_eq!(prompter.seen[0].required_mode, required);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn privilege_rank_orders_the_privilege_tiers() {
|
|
assert!(
|
|
PermissionMode::ReadOnly.privilege_rank()
|
|
< PermissionMode::WorkspaceWrite.privilege_rank()
|
|
);
|
|
assert!(
|
|
PermissionMode::WorkspaceWrite.privilege_rank()
|
|
< PermissionMode::DangerFullAccess.privilege_rank()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn privilege_rank_places_the_operating_modes_above_every_tier() {
|
|
// `Prompt` and `Allow` are modes of operation rather than tiers, so
|
|
// `covers` answers for them by name and never consults this number. They
|
|
// still have to rank above every tier, because two callers outside this
|
|
// module — the `PermissionEnforcer`'s `check_with_required_mode` and the
|
|
// `claw doctor` permission check — compare ranks, and a `Prompt`/`Allow`
|
|
// session must keep the result it had under the old derived `Ord`.
|
|
for mode in [PermissionMode::Prompt, PermissionMode::Allow] {
|
|
assert!(
|
|
mode.privilege_rank() > PermissionMode::DangerFullAccess.privilege_rank(),
|
|
"{mode:?} must outrank danger-full-access"
|
|
);
|
|
assert!(
|
|
mode.privilege_rank() > PermissionMode::WorkspaceWrite.privilege_rank(),
|
|
"{mode:?} must outrank workspace-write"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn covers_never_compares_an_operating_mode_against_a_tier() {
|
|
for required in [
|
|
PermissionMode::ReadOnly,
|
|
PermissionMode::WorkspaceWrite,
|
|
PermissionMode::DangerFullAccess,
|
|
] {
|
|
assert!(
|
|
!PermissionMode::Prompt.covers(required),
|
|
"prompt mode must ask before running a {required:?} tool"
|
|
);
|
|
}
|
|
assert!(PermissionMode::Allow.covers(PermissionMode::DangerFullAccess));
|
|
assert!(PermissionMode::DangerFullAccess.covers(PermissionMode::WorkspaceWrite));
|
|
assert!(!PermissionMode::WorkspaceWrite.covers(PermissionMode::DangerFullAccess));
|
|
}
|
|
|
|
#[test]
|
|
fn applies_rule_based_denials_and_allows() {
|
|
let rules = RuntimePermissionRuleConfig::new(
|
|
vec!["bash(git:*)".to_string()],
|
|
vec!["bash(rm -rf:*)".to_string()],
|
|
Vec::new(),
|
|
Vec::new(),
|
|
);
|
|
let policy = PermissionPolicy::new(PermissionMode::ReadOnly)
|
|
.with_tool_requirement("bash", PermissionMode::DangerFullAccess)
|
|
.with_permission_rules(&rules);
|
|
|
|
assert_eq!(
|
|
policy.authorize("bash", r#"{"command":"git status"}"#, None),
|
|
PermissionOutcome::Allow
|
|
);
|
|
assert!(matches!(
|
|
policy.authorize("bash", r#"{"command":"rm -rf /tmp/x"}"#, None),
|
|
PermissionOutcome::Deny { reason } if reason.contains("denied by rule")
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn denied_tools_denies_listed_tools_unconditionally() {
|
|
let rules = RuntimePermissionRuleConfig::new(
|
|
Vec::new(),
|
|
Vec::new(),
|
|
Vec::new(),
|
|
vec!["bash".to_string(), "write_file".to_string()],
|
|
);
|
|
let policy = PermissionPolicy::new(PermissionMode::Allow).with_permission_rules(&rules);
|
|
|
|
let result = policy.authorize("bash", "echo hello", None);
|
|
assert!(matches!(
|
|
result,
|
|
PermissionOutcome::Deny { reason } if reason.contains("denied_tools")
|
|
));
|
|
|
|
let result = policy.authorize("write_file", "{}", None);
|
|
assert!(matches!(
|
|
result,
|
|
PermissionOutcome::Deny { reason } if reason.contains("denied_tools")
|
|
));
|
|
|
|
let result = policy.authorize("read_file", "{}", None);
|
|
assert_eq!(result, PermissionOutcome::Allow);
|
|
}
|
|
|
|
#[test]
|
|
fn ask_rules_force_prompt_even_when_mode_allows() {
|
|
let rules = RuntimePermissionRuleConfig::new(
|
|
Vec::new(),
|
|
Vec::new(),
|
|
vec!["bash(git:*)".to_string()],
|
|
Vec::new(),
|
|
);
|
|
let policy = PermissionPolicy::new(PermissionMode::DangerFullAccess)
|
|
.with_tool_requirement("bash", PermissionMode::DangerFullAccess)
|
|
.with_permission_rules(&rules);
|
|
let mut prompter = RecordingPrompter {
|
|
seen: Vec::new(),
|
|
allow: true,
|
|
};
|
|
|
|
let outcome = policy.authorize("bash", r#"{"command":"git status"}"#, Some(&mut prompter));
|
|
|
|
assert_eq!(outcome, PermissionOutcome::Allow);
|
|
assert_eq!(prompter.seen.len(), 1);
|
|
assert!(prompter.seen[0]
|
|
.reason
|
|
.as_deref()
|
|
.is_some_and(|reason| reason.contains("ask rule")));
|
|
}
|
|
|
|
#[test]
|
|
fn hook_allow_still_respects_ask_rules() {
|
|
let rules = RuntimePermissionRuleConfig::new(
|
|
Vec::new(),
|
|
Vec::new(),
|
|
vec!["bash(git:*)".to_string()],
|
|
Vec::new(),
|
|
);
|
|
let policy = PermissionPolicy::new(PermissionMode::ReadOnly)
|
|
.with_tool_requirement("bash", PermissionMode::DangerFullAccess)
|
|
.with_permission_rules(&rules);
|
|
let context = PermissionContext::new(
|
|
Some(PermissionOverride::Allow),
|
|
Some("hook approved".to_string()),
|
|
);
|
|
let mut prompter = RecordingPrompter {
|
|
seen: Vec::new(),
|
|
allow: true,
|
|
};
|
|
|
|
let outcome = policy.authorize_with_context(
|
|
"bash",
|
|
r#"{"command":"git status"}"#,
|
|
&context,
|
|
Some(&mut prompter),
|
|
);
|
|
|
|
assert_eq!(outcome, PermissionOutcome::Allow);
|
|
assert_eq!(prompter.seen.len(), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn hook_deny_short_circuits_permission_flow() {
|
|
let policy = PermissionPolicy::new(PermissionMode::DangerFullAccess)
|
|
.with_tool_requirement("bash", PermissionMode::DangerFullAccess);
|
|
let context = PermissionContext::new(
|
|
Some(PermissionOverride::Deny),
|
|
Some("blocked by hook".to_string()),
|
|
);
|
|
|
|
assert_eq!(
|
|
policy.authorize_with_context("bash", "{}", &context, None),
|
|
PermissionOutcome::Deny {
|
|
reason: "blocked by hook".to_string(),
|
|
}
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn hook_ask_forces_prompt() {
|
|
let policy = PermissionPolicy::new(PermissionMode::DangerFullAccess)
|
|
.with_tool_requirement("bash", PermissionMode::DangerFullAccess);
|
|
let context = PermissionContext::new(
|
|
Some(PermissionOverride::Ask),
|
|
Some("hook requested confirmation".to_string()),
|
|
);
|
|
let mut prompter = RecordingPrompter {
|
|
seen: Vec::new(),
|
|
allow: true,
|
|
};
|
|
|
|
let outcome = policy.authorize_with_context("bash", "{}", &context, Some(&mut prompter));
|
|
|
|
assert_eq!(outcome, PermissionOutcome::Allow);
|
|
assert_eq!(prompter.seen.len(), 1);
|
|
assert_eq!(
|
|
prompter.seen[0].reason.as_deref(),
|
|
Some("hook requested confirmation")
|
|
);
|
|
}
|
|
}
|