rusty_claw 0.1.0

Rust implementation of the Claude Agent SDK
Documentation
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! Default permission handler implementation.

use crate::control::handlers::CanUseToolHandler;
use crate::error::ClawError;
use crate::options::PermissionMode;
use crate::permissions::PermissionDecision;
use async_trait::async_trait;
use serde_json::Value;

/// Default implementation of tool permission checking.
///
/// This handler evaluates tool usage requests through multiple layers:
///
/// 1. **Explicit Deny** - Check disallowed_tools first (highest priority)
/// 2. **Explicit Allow** - Check allowed_tools second
/// 3. **Default Policy** - Fall back to PermissionMode setting
///
/// All decisions are returned as [`PermissionDecision`] for rich control,
/// including optional input mutation for `Allow` results.
///
/// # Examples
///
/// ```rust
/// use rusty_claw::permissions::DefaultPermissionHandler;
/// use rusty_claw::options::PermissionMode;
///
/// // Allow only specific tools
/// let handler = DefaultPermissionHandler::builder()
///     .mode(PermissionMode::Deny)
///     .allowed_tools(vec!["bash".to_string(), "read".to_string()])
///     .build();
/// ```
#[derive(Debug, Clone)]
pub struct DefaultPermissionHandler {
    mode: PermissionMode,
    allowed_tools: Vec<String>,
    disallowed_tools: Vec<String>,
}

impl DefaultPermissionHandler {
    /// Create a new builder for configuring permission handler.
    pub fn builder() -> DefaultPermissionHandlerBuilder {
        DefaultPermissionHandlerBuilder::default()
    }

    /// Check if a tool is explicitly allowed.
    fn is_allowed(&self, tool_name: &str) -> bool {
        self.allowed_tools.is_empty() || self.allowed_tools.iter().any(|t| t == tool_name)
    }

    /// Check if a tool is explicitly denied.
    fn is_denied(&self, tool_name: &str) -> bool {
        self.disallowed_tools.iter().any(|t| t == tool_name)
    }

    /// Evaluate default policy based on PermissionMode.
    fn default_policy(&self) -> bool {
        match self.mode {
            PermissionMode::Allow => true,
            PermissionMode::Deny => false,
            PermissionMode::Ask => false, // Default to deny, CLI should prompt
            PermissionMode::Custom => false, // Require hook, deny if no hook
            // Legacy modes default to allow for backward compatibility
            PermissionMode::Default
            | PermissionMode::AcceptEdits
            | PermissionMode::BypassPermissions
            | PermissionMode::Plan => true,
        }
    }
}

#[async_trait]
impl CanUseToolHandler for DefaultPermissionHandler {
    async fn can_use_tool(
        &self,
        tool_name: &str,
        _tool_input: &Value,
    ) -> Result<PermissionDecision, ClawError> {
        // 1. Explicit deny list has highest priority
        if self.is_denied(tool_name) {
            return Ok(PermissionDecision::Deny { interrupt: false });
        }

        // 2. Explicit allow list (only applies when non-empty)
        if !self.allowed_tools.is_empty() && self.is_allowed(tool_name) {
            return Ok(PermissionDecision::Allow {
                updated_input: None,
            });
        }

        // 3. Fall back to default policy (covers: tool not in allowlist, or allowlist empty)
        if self.default_policy() {
            Ok(PermissionDecision::Allow {
                updated_input: None,
            })
        } else {
            Ok(PermissionDecision::Deny { interrupt: false })
        }
    }
}

/// Builder for [`DefaultPermissionHandler`].
///
/// # Examples
///
/// ```rust
/// use rusty_claw::permissions::DefaultPermissionHandler;
/// use rusty_claw::options::PermissionMode;
///
/// let handler = DefaultPermissionHandler::builder()
///     .mode(PermissionMode::Ask)
///     .allowed_tools(vec!["bash".to_string()])
///     .disallowed_tools(vec!["write".to_string()])
///     .build();
/// ```
#[derive(Debug, Default)]
pub struct DefaultPermissionHandlerBuilder {
    mode: Option<PermissionMode>,
    allowed_tools: Vec<String>,
    disallowed_tools: Vec<String>,
}

impl DefaultPermissionHandlerBuilder {
    /// Set the permission mode.
    pub fn mode(mut self, mode: PermissionMode) -> Self {
        self.mode = Some(mode);
        self
    }

    /// Set the list of allowed tools.
    pub fn allowed_tools(mut self, tools: Vec<String>) -> Self {
        self.allowed_tools = tools;
        self
    }

    /// Set the list of disallowed tools.
    pub fn disallowed_tools(mut self, tools: Vec<String>) -> Self {
        self.disallowed_tools = tools;
        self
    }

    /// Build the permission handler.
    pub fn build(self) -> DefaultPermissionHandler {
        DefaultPermissionHandler {
            mode: self.mode.unwrap_or(PermissionMode::Default),
            allowed_tools: self.allowed_tools,
            disallowed_tools: self.disallowed_tools,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// Helper: returns true if decision is Allow.
    fn is_allowed(d: PermissionDecision) -> bool {
        d.is_allowed()
    }

    /// Helper: returns true if decision is Deny.
    fn is_denied(d: PermissionDecision) -> bool {
        d.is_denied()
    }

    #[tokio::test]
    async fn test_allow_mode_allows_all() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Allow)
            .build();

        assert!(is_allowed(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));
        assert!(is_allowed(
            handler.can_use_tool("read", &Value::Null).await.unwrap()
        ));
        assert!(is_allowed(
            handler.can_use_tool("write", &Value::Null).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_deny_mode_denies_all() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Deny)
            .build();

        assert!(is_denied(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));
        assert!(is_denied(
            handler.can_use_tool("read", &Value::Null).await.unwrap()
        ));
        assert!(is_denied(
            handler.can_use_tool("write", &Value::Null).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_explicit_allow_overrides_deny_mode() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Deny)
            .allowed_tools(vec!["bash".to_string(), "read".to_string()])
            .build();

        assert!(is_allowed(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));
        assert!(is_allowed(
            handler.can_use_tool("read", &Value::Null).await.unwrap()
        ));
        assert!(is_denied(
            handler.can_use_tool("write", &Value::Null).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_explicit_deny_overrides_allow_mode() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Allow)
            .disallowed_tools(vec!["bash".to_string(), "write".to_string()])
            .build();

        assert!(is_denied(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));
        assert!(is_allowed(
            handler.can_use_tool("read", &Value::Null).await.unwrap()
        ));
        assert!(is_denied(
            handler.can_use_tool("write", &Value::Null).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_explicit_deny_beats_explicit_allow() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Allow)
            .allowed_tools(vec!["bash".to_string()])
            .disallowed_tools(vec!["bash".to_string()])
            .build();

        assert!(is_denied(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_ask_mode_defaults_to_deny() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Ask)
            .build();

        // Ask mode should default to deny, expecting CLI to prompt
        assert!(is_denied(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_custom_mode_defaults_to_deny() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Custom)
            .build();

        // Custom mode should default to deny, expecting hooks
        assert!(is_denied(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_legacy_mode_defaults_to_allow() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Default)
            .build();

        assert!(is_allowed(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));

        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::AcceptEdits)
            .build();

        assert!(is_allowed(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_empty_lists_uses_default_policy() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Allow)
            .allowed_tools(vec![])
            .disallowed_tools(vec![])
            .build();

        assert!(is_allowed(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));

        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Deny)
            .allowed_tools(vec![])
            .disallowed_tools(vec![])
            .build();

        assert!(is_denied(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_allowlist_restricts_when_not_empty() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Allow)
            .allowed_tools(vec!["bash".to_string()])
            .build();

        assert!(is_allowed(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));
        // Tools not in allowlist should follow default policy
        assert!(is_allowed(
            handler.can_use_tool("read", &Value::Null).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_builder_defaults() {
        let handler = DefaultPermissionHandler::builder().build();

        // Should use Default mode with empty lists
        assert!(is_allowed(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_bypass_permissions_mode() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::BypassPermissions)
            .build();

        // Legacy modes should allow all tools
        assert!(is_allowed(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));
        assert!(is_allowed(
            handler.can_use_tool("write", &Value::Null).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_plan_mode() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Plan)
            .build();

        // Plan mode should allow all tools (legacy behavior)
        assert!(is_allowed(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_complex_allowlist_denylist() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Ask)
            .allowed_tools(vec![
                "bash".to_string(),
                "read".to_string(),
                "write".to_string(),
            ])
            .disallowed_tools(vec!["write".to_string()])
            .build();

        // bash and read are in allowlist
        assert!(is_allowed(
            handler.can_use_tool("bash", &Value::Null).await.unwrap()
        ));
        assert!(is_allowed(
            handler.can_use_tool("read", &Value::Null).await.unwrap()
        ));

        // write is in both allowlist and denylist - deny wins
        assert!(is_denied(
            handler.can_use_tool("write", &Value::Null).await.unwrap()
        ));

        // grep not in allowlist, but not denied - follows default policy
        assert!(is_denied(
            handler.can_use_tool("grep", &Value::Null).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_tool_input_parameter_ignored() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Allow)
            .build();

        // Should ignore tool_input parameter (for now)
        let complex_input = serde_json::json!({
            "command": "rm -rf /",
            "dangerous": true
        });

        assert!(is_allowed(
            handler.can_use_tool("bash", &complex_input).await.unwrap()
        ));
    }

    // Integration scenarios
    #[tokio::test]
    async fn test_realistic_read_only_policy() {
        // Scenario: Agent that can only read, not write
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Deny)
            .allowed_tools(vec![
                "read".to_string(),
                "glob".to_string(),
                "grep".to_string(),
            ])
            .build();

        // Read operations allowed
        assert!(is_allowed(
            handler.can_use_tool("read", &json!({})).await.unwrap()
        ));
        assert!(is_allowed(
            handler.can_use_tool("glob", &json!({})).await.unwrap()
        ));
        assert!(is_allowed(
            handler.can_use_tool("grep", &json!({})).await.unwrap()
        ));

        // Write operations denied
        assert!(is_denied(
            handler.can_use_tool("write", &json!({})).await.unwrap()
        ));
        assert!(is_denied(
            handler.can_use_tool("edit", &json!({})).await.unwrap()
        ));
        assert!(is_denied(
            handler.can_use_tool("bash", &json!({})).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_safe_tools_policy() {
        // Scenario: Allow all except dangerous tools
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Allow)
            .disallowed_tools(vec![
                "bash".to_string(),
                "write".to_string(),
                "delete".to_string(),
            ])
            .build();

        // Safe tools allowed
        assert!(is_allowed(
            handler.can_use_tool("read", &json!({})).await.unwrap()
        ));
        assert!(is_allowed(
            handler.can_use_tool("grep", &json!({})).await.unwrap()
        ));

        // Dangerous tools denied
        assert!(is_denied(
            handler.can_use_tool("bash", &json!({})).await.unwrap()
        ));
        assert!(is_denied(
            handler.can_use_tool("write", &json!({})).await.unwrap()
        ));
        assert!(is_denied(
            handler.can_use_tool("delete", &json!({})).await.unwrap()
        ));
    }

    #[tokio::test]
    async fn test_can_use_tool_trait() {
        // Verify that DefaultPermissionHandler properly implements CanUseToolHandler
        let handler: Box<dyn CanUseToolHandler> = Box::new(
            DefaultPermissionHandler::builder()
                .mode(PermissionMode::Allow)
                .build(),
        );

        let result = handler.can_use_tool("bash", &json!({})).await;
        assert!(result.is_ok());
        assert!(result.unwrap().is_allowed());
    }

    #[tokio::test]
    async fn test_permission_decision_updated_input_is_none_by_default() {
        // DefaultPermissionHandler returns None for updated_input
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Allow)
            .build();
        let decision = handler.can_use_tool("bash", &json!({})).await.unwrap();
        assert!(decision.updated_input().is_none());
    }

    #[tokio::test]
    async fn test_permission_decision_deny_has_no_interrupt_by_default() {
        let handler = DefaultPermissionHandler::builder()
            .mode(PermissionMode::Deny)
            .build();
        let decision = handler.can_use_tool("bash", &json!({})).await.unwrap();
        match decision {
            PermissionDecision::Deny { interrupt } => assert!(!interrupt),
            PermissionDecision::Allow { .. } => panic!("Expected Deny"),
        }
    }
}