1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
//! Permission evaluation for tool execution
//!
//! Provides a permission system that controls whether tools are allowed to execute.
//! Supports fail-safe defaults (DENY), auto-approval modes, and audit trails.
use crate::error::Result as AgentResult;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::time::{Duration, timeout};
use turboclaude_protocol::{
PermissionBehavior, PermissionCheckRequest, PermissionMode, PermissionResponse,
PermissionUpdate,
};
/// Type alias for async permission handlers
///
/// Handlers take a PermissionCheckRequest and return a Future with a PermissionResponse.
pub type PermissionHandler = Arc<
dyn Fn(
PermissionCheckRequest,
) -> Pin<Box<dyn Future<Output = AgentResult<PermissionResponse>> + Send>>
+ Send
+ Sync,
>;
/// Handle for a registered permission handler
#[derive(Debug, Clone)]
pub struct PermissionHandle {
_id: String,
}
/// Permission state tracking rules and directories
#[derive(Debug, Clone, Default)]
struct PermissionState {
/// Allow rules: tool name -> rule content
allow_rules: HashMap<String, Option<String>>,
/// Deny rules: tool name -> rule content
deny_rules: HashMap<String, Option<String>>,
/// Ask rules: tool name -> rule content
ask_rules: HashMap<String, Option<String>>,
/// Allowed directories
allowed_directories: Vec<String>,
}
/// Permission evaluator
///
/// Evaluates permission requests with configurable behavior based on the permission mode.
/// Provides fail-safe defaults: denies permission unless explicitly approved.
pub struct PermissionEvaluator {
/// Optional permission handler
handler: Arc<Mutex<Option<PermissionHandler>>>,
/// Current permission mode
mode: Arc<Mutex<PermissionMode>>,
/// Permission state (rules and directories)
state: Arc<Mutex<PermissionState>>,
}
impl PermissionEvaluator {
/// Create a new permission evaluator with the given default mode
pub fn new(mode: PermissionMode) -> Self {
Self {
handler: Arc::new(Mutex::new(None)),
mode: Arc::new(Mutex::new(mode)),
state: Arc::new(Mutex::new(PermissionState::default())),
}
}
/// Register a permission handler
///
/// The handler is called when a tool needs permission.
pub async fn register<F>(&self, handler: F) -> PermissionHandle
where
F: Fn(
PermissionCheckRequest,
) -> Pin<Box<dyn Future<Output = AgentResult<PermissionResponse>> + Send>>
+ Send
+ Sync
+ 'static,
{
let handler = Arc::new(handler);
let id = format!("permission-{}", uuid::Uuid::new_v4());
*self.handler.lock().await = Some(handler);
PermissionHandle { _id: id }
}
/// Check if a tool use is permitted
///
/// Returns the permission response. Semantics depend on the permission mode:
///
/// - `Default`: Requires handler to approve (fails closed - denies by default)
/// - `AcceptEdits`: Auto-approves but allows handler to modify inputs
/// - `BypassPermissions`: Always approves without consulting handler
pub async fn check(&self, request: PermissionCheckRequest) -> AgentResult<PermissionResponse> {
let mode = *self.mode.lock().await;
match mode {
PermissionMode::BypassPermissions => {
// Auto-approve all
Ok(PermissionResponse {
allow: true,
modified_input: None,
reason: Some("Permissions bypassed".to_string()),
})
}
PermissionMode::AcceptEdits => {
// Auto-approve but allow handler to modify inputs
let handler = self.handler.lock().await;
if let Some(handler) = handler.as_ref() {
let response = match timeout(Duration::from_secs(30), handler(request)).await {
Ok(Ok(resp)) => resp,
Ok(Err(e)) => return Err(e),
Err(_) => {
// Timeout - still auto-approve but log it
PermissionResponse {
allow: true,
modified_input: None,
reason: Some(
"Accepted after handler timeout (AcceptEdits mode)".to_string(),
),
}
}
};
return Ok(response);
}
// No handler registered, auto-approve with warning
Ok(PermissionResponse {
allow: true,
modified_input: None,
reason: Some(
"Accepted without explicit approval (AcceptEdits mode)".to_string(),
),
})
}
PermissionMode::Default => {
// Require explicit permission
let handler = self.handler.lock().await;
if let Some(handler) = handler.as_ref() {
let response = timeout(Duration::from_secs(30), handler(request)).await;
match response {
Ok(Ok(resp)) => return Ok(resp),
Ok(Err(e)) => return Err(e),
Err(_) => {
// Timeout - fail-safe DENY
return Ok(PermissionResponse {
allow: false,
modified_input: None,
reason: Some(
"Permission check timeout (fail-safe deny)".to_string(),
),
});
}
}
}
// No handler registered - fail-safe DENY
Ok(PermissionResponse {
allow: false,
modified_input: None,
reason: Some("No permission handler registered (fail-safe deny)".to_string()),
})
}
}
}
/// Change the permission mode
pub async fn set_mode(&self, mode: PermissionMode) {
*self.mode.lock().await = mode;
}
/// Get the current permission mode
pub async fn get_mode(&self) -> PermissionMode {
*self.mode.lock().await
}
/// Update permissions dynamically
///
/// Applies a permission update to the evaluator state. Updates are atomic
/// and thread-safe. Validates the update before applying.
///
/// # Arguments
///
/// * `update` - The permission update to apply
///
/// # Returns
///
/// Returns `Ok(())` if the update was applied successfully, or an error
/// if the update was invalid or could not be applied.
///
/// # Thread Safety
///
/// This method is thread-safe and can be called concurrently from multiple
/// threads. Updates are applied atomically.
pub async fn update_permissions(&self, update: PermissionUpdate) -> AgentResult<()> {
// Validate the update first
update.validate().map_err(|e| {
crate::error::AgentError::Config(format!("Invalid permission update: {}", e))
})?;
let mut state = self.state.lock().await;
match update {
PermissionUpdate::AddRules(add_rules) => {
// Add rules to the appropriate behavior map
let target_map = match add_rules.behavior {
PermissionBehavior::Allow => &mut state.allow_rules,
PermissionBehavior::Deny => &mut state.deny_rules,
PermissionBehavior::Ask => &mut state.ask_rules,
};
for rule in add_rules.rules {
target_map.insert(rule.tool_name, rule.rule_content);
}
}
PermissionUpdate::ReplaceRules(replace_rules) => {
// Clear existing rules for this behavior and add new ones
let target_map = match replace_rules.behavior {
PermissionBehavior::Allow => &mut state.allow_rules,
PermissionBehavior::Deny => &mut state.deny_rules,
PermissionBehavior::Ask => &mut state.ask_rules,
};
target_map.clear();
for rule in replace_rules.rules {
target_map.insert(rule.tool_name, rule.rule_content);
}
}
PermissionUpdate::RemoveRules(remove_rules) => {
// Remove rules from all behavior maps
for rule in remove_rules.rules {
state.allow_rules.remove(&rule.tool_name);
state.deny_rules.remove(&rule.tool_name);
state.ask_rules.remove(&rule.tool_name);
}
}
PermissionUpdate::SetMode(set_mode) => {
// Update the permission mode
*self.mode.lock().await = set_mode.mode;
}
PermissionUpdate::AddDirectories(add_dirs) => {
// Add directories to the allowed list
for dir in add_dirs.directories {
if !state.allowed_directories.contains(&dir) {
state.allowed_directories.push(dir);
}
}
}
PermissionUpdate::RemoveDirectories(remove_dirs) => {
// Remove directories from the allowed list
state
.allowed_directories
.retain(|d| !remove_dirs.directories.contains(d));
}
}
Ok(())
}
/// Get current permission state (for debugging/inspection)
pub async fn get_state(&self) -> (PermissionMode, Vec<String>) {
let mode = *self.mode.lock().await;
let state = self.state.lock().await;
(mode, state.allowed_directories.clone())
}
}
impl Default for PermissionEvaluator {
fn default() -> Self {
Self::new(PermissionMode::Default)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_permission_evaluator_creation() {
let evaluator = PermissionEvaluator::new(PermissionMode::Default);
assert_eq!(evaluator.get_mode().await, PermissionMode::Default);
}
#[tokio::test]
async fn test_permission_default_deny_no_handler() {
let evaluator = PermissionEvaluator::new(PermissionMode::Default);
let request = PermissionCheckRequest {
tool: "web_search".to_string(),
input: serde_json::json!({}),
suggestion: "Use web_search?".to_string(),
};
let response = evaluator.check(request).await.unwrap();
assert!(!response.allow); // Fail-safe DENY
assert!(response.reason.is_some());
}
#[tokio::test]
async fn test_permission_bypass_mode() {
let evaluator = PermissionEvaluator::new(PermissionMode::BypassPermissions);
let request = PermissionCheckRequest {
tool: "web_search".to_string(),
input: serde_json::json!({}),
suggestion: "Use web_search?".to_string(),
};
let response = evaluator.check(request).await.unwrap();
assert!(response.allow); // Auto-approve
}
#[tokio::test]
async fn test_permission_accept_edits_auto_approve() {
let evaluator = PermissionEvaluator::new(PermissionMode::AcceptEdits);
let request = PermissionCheckRequest {
tool: "web_search".to_string(),
input: serde_json::json!({}),
suggestion: "Use web_search?".to_string(),
};
let response = evaluator.check(request).await.unwrap();
assert!(response.allow); // Auto-approve
}
#[tokio::test]
async fn test_permission_handler_approve() {
let evaluator = PermissionEvaluator::new(PermissionMode::Default);
evaluator
.register(|_req| {
Box::pin(async {
Ok(PermissionResponse {
allow: true,
modified_input: None,
reason: Some("User approved".to_string()),
})
})
})
.await;
let request = PermissionCheckRequest {
tool: "web_search".to_string(),
input: serde_json::json!({}),
suggestion: "Use web_search?".to_string(),
};
let response = evaluator.check(request).await.unwrap();
assert!(response.allow);
}
#[tokio::test]
async fn test_permission_handler_deny() {
let evaluator = PermissionEvaluator::new(PermissionMode::Default);
evaluator
.register(|_req| {
Box::pin(async {
Ok(PermissionResponse {
allow: false,
modified_input: None,
reason: Some("User denied".to_string()),
})
})
})
.await;
let request = PermissionCheckRequest {
tool: "web_search".to_string(),
input: serde_json::json!({}),
suggestion: "Use web_search?".to_string(),
};
let response = evaluator.check(request).await.unwrap();
assert!(!response.allow);
}
#[tokio::test]
async fn test_permission_mode_change() {
let evaluator = PermissionEvaluator::new(PermissionMode::Default);
assert_eq!(evaluator.get_mode().await, PermissionMode::Default);
evaluator.set_mode(PermissionMode::BypassPermissions).await;
assert_eq!(
evaluator.get_mode().await,
PermissionMode::BypassPermissions
);
}
}