actrpc-interceptor 0.1.0

Concrete interceptors for ActRPC.
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
521
522
523
524
525
526
use actrpc_core::{
    action::{ActionKind, ResolvedActionRecord},
    interception::{InterceptionRequest, InterceptorContinuation},
    json_rpc::{
        JsonRpcId, JsonRpcMessage, JsonRpcParams, JsonRpcRequest, JsonRpcSingleMessage,
        JsonRpcVersion,
    },
    participant::{Participant, ParticipantType},
};
use actrpc_interceptor::interceptors::policy::{
    PolicyInterceptor,
    config::{
        MatchExpr, PolicyApply, PolicyConfig, PolicyEffect, PolicyMatcher, PolicyReview,
        PolicyReviewSeverity, PolicyRule,
    },
};
use actrpc_orchestrator::{
    action::actions::request_review::{
        REVIEW_DECISION_APPROVED, REVIEW_DECISION_DENIED, REVIEW_SEVERITY_HIGH,
    },
    interceptor::Interceptor,
};
use serde_json::json;

#[tokio::test]
async fn no_matching_rule_emits_no_actions_and_stops() {
    let interceptor = PolicyInterceptor::new(PolicyConfig {
        rules: vec![PolicyRule {
            name: "reject_write_file".to_owned(),
            match_expr: MatchExpr::condition("message.method", PolicyMatcher::exact("write_file")),
            apply: PolicyApply {
                immediate: vec![PolicyEffect::reject_call(json_rpc_error(-32010, "denied"))],
                review: None,
            },
        }],
    })
    .unwrap();

    let request = outbound_request("read_file", json!({ "path": "/tmp/a.txt" }));

    let response = interceptor.intercept(&request).await.unwrap();

    assert_eq!(response.continuation, InterceptorContinuation::Stop);
    assert!(response.actions.is_empty());
}

#[tokio::test]
async fn matching_reject_call_rule_emits_reject_call_action() {
    let interceptor = PolicyInterceptor::new(PolicyConfig {
        rules: vec![PolicyRule {
            name: "reject_write_file".to_owned(),
            match_expr: MatchExpr::condition("message.method", PolicyMatcher::exact("write_file")),
            apply: PolicyApply {
                immediate: vec![PolicyEffect::reject_call(json_rpc_error(
                    -32010,
                    "write denied",
                ))],
                review: None,
            },
        }],
    })
    .unwrap();

    let request = outbound_request("write_file", json!({ "path": "/tmp/a.txt" }));

    let response = interceptor.intercept(&request).await.unwrap();

    assert_eq!(response.continuation, InterceptorContinuation::Stop);
    assert_eq!(response.actions.len(), 1);

    let action = &response.actions[0];

    assert_eq!(action.kind, ActionKind::from("reject_call"));
    assert_eq!(
        action.params,
        Some(json!({
            "error": {
                "code": -32010,
                "message": "write denied"
            }
        }))
    );
}

#[tokio::test]
async fn matching_exclude_interceptors_rule_emits_exclude_interceptors_action() {
    let interceptor = PolicyInterceptor::new(PolicyConfig {
        rules: vec![PolicyRule {
            name: "exclude_loggers".to_owned(),
            match_expr: MatchExpr::condition("message.method", PolicyMatcher::exact("read_file")),
            apply: PolicyApply {
                immediate: vec![PolicyEffect::exclude_interceptors(vec![
                    "audit_logger".to_owned(),
                    "transcript_logger".to_owned(),
                ])],
                review: None,
            },
        }],
    })
    .unwrap();

    let request = outbound_request("read_file", json!({ "path": "/secrets/key.txt" }));

    let response = interceptor.intercept(&request).await.unwrap();

    assert_eq!(response.continuation, InterceptorContinuation::Stop);
    assert_eq!(response.actions.len(), 1);

    let action = &response.actions[0];

    assert_eq!(action.kind, ActionKind::from("exclude_interceptors"));
    assert_eq!(
        action.params,
        Some(json!({
            "names": ["audit_logger", "transcript_logger"]
        }))
    );
}

#[tokio::test]
async fn review_rule_emits_request_review_and_reinvokes() {
    let interceptor = PolicyInterceptor::new(review_policy_config(
        vec![],
        vec![PolicyEffect::reject_call(json_rpc_error(
            -32051,
            "user denied sensitive write",
        ))],
    ))
    .unwrap();

    let request = outbound_request("write_file", json!({ "path": "/home/mortal/file.txt" }));

    let response = interceptor.intercept(&request).await.unwrap();

    assert_eq!(response.continuation, InterceptorContinuation::Reinvoke);
    assert_eq!(response.actions.len(), 1);

    let action = &response.actions[0];

    assert_eq!(action.kind, ActionKind::from("request_review"));
    assert_eq!(
        action.params,
        Some(json!({
            "rule_name": "review_sensitive_write",
            "title": "Sensitive file write",
            "reason": "Agent wants to write inside a user-owned directory.",
            "severity": REVIEW_SEVERITY_HIGH
        }))
    );
}

#[tokio::test]
async fn approved_review_emits_on_approve_effects_and_stops() {
    let interceptor = PolicyInterceptor::new(review_policy_config(
        vec![PolicyEffect::exclude_interceptors(vec![
            "audit_logger".to_owned(),
        ])],
        vec![PolicyEffect::reject_call(json_rpc_error(
            -32051,
            "user denied sensitive write",
        ))],
    ))
    .unwrap();

    let mut request = outbound_request("write_file", json!({ "path": "/home/mortal/file.txt" }));
    request.resolved_action_history = vec![vec![resolved_request_review(
        "review_sensitive_write",
        REVIEW_DECISION_APPROVED,
    )]];

    let response = interceptor.intercept(&request).await.unwrap();

    assert_eq!(response.continuation, InterceptorContinuation::Stop);
    assert_eq!(response.actions.len(), 1);

    let action = &response.actions[0];

    assert_eq!(action.kind, ActionKind::from("exclude_interceptors"));
    assert_eq!(
        action.params,
        Some(json!({
            "names": ["audit_logger"]
        }))
    );
}

#[tokio::test]
async fn denied_review_emits_on_deny_effects_and_stops() {
    let interceptor = PolicyInterceptor::new(review_policy_config(
        vec![],
        vec![PolicyEffect::reject_call(json_rpc_error(
            -32051,
            "user denied sensitive write",
        ))],
    ))
    .unwrap();

    let mut request = outbound_request("write_file", json!({ "path": "/home/mortal/file.txt" }));
    request.resolved_action_history = vec![vec![resolved_request_review(
        "review_sensitive_write",
        REVIEW_DECISION_DENIED,
    )]];

    let response = interceptor.intercept(&request).await.unwrap();

    assert_eq!(response.continuation, InterceptorContinuation::Stop);
    assert_eq!(response.actions.len(), 1);

    let action = &response.actions[0];

    assert_eq!(action.kind, ActionKind::from("reject_call"));
    assert_eq!(
        action.params,
        Some(json!({
            "error": {
                "code": -32051,
                "message": "user denied sensitive write"
            }
        }))
    );
}

#[tokio::test]
async fn denied_review_without_on_deny_uses_default_reject_call() {
    let interceptor = PolicyInterceptor::new(review_policy_config(vec![], vec![])).unwrap();

    let mut request = outbound_request("write_file", json!({ "path": "/home/mortal/file.txt" }));
    request.resolved_action_history = vec![vec![resolved_request_review(
        "review_sensitive_write",
        REVIEW_DECISION_DENIED,
    )]];

    let response = interceptor.intercept(&request).await.unwrap();

    assert_eq!(response.continuation, InterceptorContinuation::Stop);
    assert_eq!(response.actions.len(), 1);

    let action = &response.actions[0];

    assert_eq!(action.kind, ActionKind::from("reject_call"));
    assert_eq!(
        action.params,
        Some(json!({
            "error": {
                "code": -32050,
                "message": "operation denied by user review"
            }
        }))
    );
}

#[tokio::test]
async fn glob_matcher_matches_nested_param_path() {
    let interceptor = PolicyInterceptor::new(PolicyConfig {
        rules: vec![PolicyRule {
            name: "reject_secret_read".to_owned(),
            match_expr: MatchExpr::all(vec![
                MatchExpr::condition("message.method", PolicyMatcher::exact("read_file")),
                MatchExpr::condition("message.params.path", PolicyMatcher::glob("/secrets/**")),
            ]),
            apply: PolicyApply {
                immediate: vec![PolicyEffect::reject_call(json_rpc_error(
                    -32020,
                    "secret read denied",
                ))],
                review: None,
            },
        }],
    })
    .unwrap();

    let request = outbound_request("read_file", json!({ "path": "/secrets/key.txt" }));

    let response = interceptor.intercept(&request).await.unwrap();

    assert_eq!(response.continuation, InterceptorContinuation::Stop);
    assert_eq!(response.actions.len(), 1);
    assert_eq!(response.actions[0].kind, ActionKind::from("reject_call"));
}

#[tokio::test]
async fn regex_matcher_matches_method() {
    let interceptor = PolicyInterceptor::new(PolicyConfig {
        rules: vec![PolicyRule {
            name: "reject_write_methods".to_owned(),
            match_expr: MatchExpr::condition("message.method", PolicyMatcher::regex("^write_.*")),
            apply: PolicyApply {
                immediate: vec![PolicyEffect::reject_call(json_rpc_error(
                    -32021,
                    "write method denied",
                ))],
                review: None,
            },
        }],
    })
    .unwrap();

    let request = outbound_request("write_file", json!({ "path": "/tmp/a.txt" }));

    let response = interceptor.intercept(&request).await.unwrap();

    assert_eq!(response.continuation, InterceptorContinuation::Stop);
    assert_eq!(response.actions.len(), 1);
    assert_eq!(response.actions[0].kind, ActionKind::from("reject_call"));
}

#[tokio::test]
async fn negated_matcher_works() {
    let interceptor = PolicyInterceptor::new(PolicyConfig {
        rules: vec![PolicyRule {
            name: "reject_non_read".to_owned(),
            match_expr: MatchExpr::condition(
                "message.method",
                PolicyMatcher::exact_not("read_file"),
            ),
            apply: PolicyApply {
                immediate: vec![PolicyEffect::reject_call(json_rpc_error(
                    -32022,
                    "non-read denied",
                ))],
                review: None,
            },
        }],
    })
    .unwrap();

    let request = outbound_request("write_file", json!({ "path": "/tmp/a.txt" }));

    let response = interceptor.intercept(&request).await.unwrap();

    assert_eq!(response.continuation, InterceptorContinuation::Stop);
    assert_eq!(response.actions.len(), 1);
    assert_eq!(response.actions[0].kind, ActionKind::from("reject_call"));
}

#[test]
fn invalid_config_rejects_empty_rule_name() {
    let err = PolicyInterceptor::new(PolicyConfig {
        rules: vec![PolicyRule {
            name: "".to_owned(),
            match_expr: MatchExpr::condition("message.method", PolicyMatcher::exact("write_file")),
            apply: PolicyApply {
                immediate: vec![PolicyEffect::reject_call(json_rpc_error(-32010, "denied"))],
                review: None,
            },
        }],
    })
    .unwrap_err();

    assert!(err.to_string().contains("policy rule name cannot be empty"));
}

#[test]
fn invalid_config_rejects_duplicate_rule_names() {
    let rule = PolicyRule {
        name: "duplicate".to_owned(),
        match_expr: MatchExpr::condition("message.method", PolicyMatcher::exact("write_file")),
        apply: PolicyApply {
            immediate: vec![PolicyEffect::reject_call(json_rpc_error(-32010, "denied"))],
            review: None,
        },
    };

    let err = PolicyInterceptor::new(PolicyConfig {
        rules: vec![rule.clone(), rule],
    })
    .unwrap_err();

    assert!(err.to_string().contains("duplicate policy rule name"));
}

#[test]
fn invalid_config_rejects_empty_exclude_interceptors() {
    let err = PolicyInterceptor::new(PolicyConfig {
        rules: vec![PolicyRule {
            name: "bad_exclude".to_owned(),
            match_expr: MatchExpr::condition("message.method", PolicyMatcher::exact("write_file")),
            apply: PolicyApply {
                immediate: vec![PolicyEffect::exclude_interceptors(vec![])],
                review: None,
            },
        }],
    })
    .unwrap_err();

    assert!(
        err.to_string()
            .contains("exclude_interceptors effect with empty names")
    );
}

#[test]
fn invalid_config_rejects_empty_all_expression() {
    let err = PolicyInterceptor::new(PolicyConfig {
        rules: vec![PolicyRule {
            name: "bad_all".to_owned(),
            match_expr: MatchExpr::all(vec![]),
            apply: PolicyApply {
                immediate: vec![PolicyEffect::reject_call(json_rpc_error(-32010, "denied"))],
                review: None,
            },
        }],
    })
    .unwrap_err();

    assert!(err.to_string().contains("empty all expression"));
}

#[test]
fn invalid_config_rejects_empty_any_expression() {
    let err = PolicyInterceptor::new(PolicyConfig {
        rules: vec![PolicyRule {
            name: "bad_any".to_owned(),
            match_expr: MatchExpr::any(vec![]),
            apply: PolicyApply {
                immediate: vec![PolicyEffect::reject_call(json_rpc_error(-32010, "denied"))],
                review: None,
            },
        }],
    })
    .unwrap_err();

    assert!(err.to_string().contains("empty any expression"));
}

#[test]
fn invalid_config_rejects_rule_with_no_effects() {
    let err = PolicyInterceptor::new(PolicyConfig {
        rules: vec![PolicyRule {
            name: "no_effects".to_owned(),
            match_expr: MatchExpr::condition("message.method", PolicyMatcher::exact("write_file")),
            apply: PolicyApply {
                immediate: vec![],
                review: None,
            },
        }],
    })
    .unwrap_err();

    assert!(err.to_string().contains("has no effects"));
}

#[test]
fn invalid_config_rejects_invalid_regex() {
    let err = PolicyInterceptor::new(PolicyConfig {
        rules: vec![PolicyRule {
            name: "bad_regex".to_owned(),
            match_expr: MatchExpr::condition("message.method", PolicyMatcher::regex("[")),
            apply: PolicyApply {
                immediate: vec![PolicyEffect::reject_call(json_rpc_error(-32010, "denied"))],
                review: None,
            },
        }],
    })
    .unwrap_err();

    assert!(err.to_string().contains("invalid regex"));
}

fn review_policy_config(on_approve: Vec<PolicyEffect>, on_deny: Vec<PolicyEffect>) -> PolicyConfig {
    PolicyConfig {
        rules: vec![PolicyRule {
            name: "review_sensitive_write".to_owned(),
            match_expr: MatchExpr::all(vec![
                MatchExpr::condition("phase", PolicyMatcher::exact("outbound")),
                MatchExpr::condition("message.method", PolicyMatcher::exact("write_file")),
                MatchExpr::condition("message.params.path", PolicyMatcher::glob("/home/*/**")),
            ]),
            apply: PolicyApply {
                immediate: vec![],
                review: Some(PolicyReview {
                    title: "Sensitive file write".to_owned(),
                    reason: "Agent wants to write inside a user-owned directory.".to_owned(),
                    severity: PolicyReviewSeverity::High,
                    on_approve,
                    on_deny,
                }),
            },
        }],
    }
}

fn outbound_request(method: &str, params: serde_json::Value) -> InterceptionRequest {
    let params = match params {
        serde_json::Value::Array(values) => Some(JsonRpcParams::Array(values)),
        serde_json::Value::Object(map) => Some(JsonRpcParams::Object(map)),
        other => panic!("test params must be array or object, got {other}"),
    };

    InterceptionRequest {
        origin: Participant {
            kind: ParticipantType::Orchestrator,
            id: "orchestrator".to_owned(),
        },
        message: JsonRpcMessage::Single(JsonRpcSingleMessage::Request(JsonRpcRequest {
            jsonrpc: JsonRpcVersion::V2_0,
            id: JsonRpcId::Number(1.into()),
            method: method.to_owned(),
            params,
        })),
        resolved_action_history: vec![],
    }
}

fn resolved_request_review(rule_name: &str, decision: &str) -> ResolvedActionRecord {
    ResolvedActionRecord {
        kind: ActionKind::from("request_review"),
        params: Some(json!({
            "rule_name": rule_name,
            "title": "Sensitive file write",
            "reason": "Agent wants to write inside a user-owned directory.",
            "severity": REVIEW_SEVERITY_HIGH
        })),
        result: Ok(Some(json!({
            "decision": decision
        }))),
    }
}

fn json_rpc_error(code: i32, message: &str) -> actrpc_core::json_rpc::JsonRpcError {
    actrpc_core::json_rpc::JsonRpcError {
        code,
        message: message.to_owned(),
        data: None,
    }
}