chio-guards 0.1.0

Security guards for the Chio runtime kernel, adapted from ClawdStrike
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
//! Patch integrity guard -- validates patch/diff safety.
//!
//! Adapted from ClawdStrike's `guards/patch_integrity.rs`. Checks for:
//! - Maximum additions/deletions thresholds
//! - Forbidden patterns in added lines (security disablement, backdoors, etc.)
//! - Optional addition/deletion imbalance checks

use regex::Regex;

use chio_kernel::{GuardContext, KernelError, Verdict};

use crate::action::{extract_action, ToolAction};

/// Errors produced when building a [`PatchIntegrityGuard`].
#[derive(Debug, thiserror::Error)]
pub enum PatchIntegrityConfigError {
    /// A forbidden pattern was not a valid regex.
    #[error("invalid patch integrity forbidden pattern `{pattern}`: {source}")]
    InvalidForbiddenPattern {
        pattern: String,
        #[source]
        source: regex::Error,
    },
}

/// Configuration for `PatchIntegrityGuard`.
pub struct PatchIntegrityConfig {
    /// Enable/disable this guard.
    pub enabled: bool,
    /// Maximum lines added in a single patch.
    pub max_additions: usize,
    /// Maximum lines deleted in a single patch.
    pub max_deletions: usize,
    /// Patterns that are forbidden in added patch lines.
    pub forbidden_patterns: Vec<String>,
    /// Require patches to have balanced additions/deletions.
    pub require_balance: bool,
    /// Maximum imbalance ratio (additions / deletions).
    pub max_imbalance_ratio: f64,
}

fn default_forbidden_patterns() -> Vec<String> {
    vec![
        // Disable security features
        r"(?i)disable[ _\-]?(security|auth|ssl|tls)".to_string(),
        r"(?i)skip[ _\-]?(verify|validation|check)".to_string(),
        // Dangerous operations
        r"(?i)rm\s+-rf\s+/".to_string(),
        r"(?i)chmod\s+777".to_string(),
        r"(?i)eval\s*\(".to_string(),
        r"(?i)exec\s*\(".to_string(),
        // Backdoor indicators
        r"(?i)reverse[_\-]?shell".to_string(),
        r"(?i)bind[_\-]?shell".to_string(),
        r"base64[_\-]?decode.*exec".to_string(),
    ]
}

impl Default for PatchIntegrityConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_additions: 1000,
            max_deletions: 500,
            forbidden_patterns: default_forbidden_patterns(),
            require_balance: false,
            max_imbalance_ratio: 10.0,
        }
    }
}

/// A forbidden pattern match found in a patch.
#[derive(Clone, Debug)]
pub struct ForbiddenMatch {
    pub line: String,
    pub pattern: String,
}

/// Analysis result for a patch.
#[derive(Clone, Debug)]
pub struct PatchAnalysis {
    pub additions: usize,
    pub deletions: usize,
    pub imbalance_ratio: f64,
    pub forbidden_matches: Vec<ForbiddenMatch>,
    pub exceeds_max_additions: bool,
    pub exceeds_max_deletions: bool,
    pub exceeds_imbalance: bool,
}

impl PatchAnalysis {
    /// Returns true when the patch passes all safety checks.
    pub fn is_safe(&self) -> bool {
        self.forbidden_matches.is_empty()
            && !self.exceeds_max_additions
            && !self.exceeds_max_deletions
            && !self.exceeds_imbalance
    }
}

/// Guard that validates the safety of applied patches/diffs.
pub struct PatchIntegrityGuard {
    enabled: bool,
    config: PatchIntegrityConfig,
    forbidden_regexes: Vec<Regex>,
}

impl PatchIntegrityGuard {
    pub fn new() -> Self {
        match Self::with_config(PatchIntegrityConfig::default()) {
            Ok(guard) => guard,
            Err(error) => panic!("default patch integrity config must be valid: {error}"),
        }
    }

    pub fn with_config(config: PatchIntegrityConfig) -> Result<Self, PatchIntegrityConfigError> {
        let enabled = config.enabled;
        let forbidden_regexes = config
            .forbidden_patterns
            .iter()
            .map(|pattern| {
                Regex::new(pattern).map_err(|source| {
                    PatchIntegrityConfigError::InvalidForbiddenPattern {
                        pattern: pattern.clone(),
                        source,
                    }
                })
            })
            .collect::<Result<Vec<_>, _>>()?;

        Ok(Self {
            enabled,
            config,
            forbidden_regexes,
        })
    }

    /// Analyze a unified diff and return a `PatchAnalysis`.
    pub fn analyze(&self, diff: &str) -> PatchAnalysis {
        let mut additions = 0;
        let mut deletions = 0;
        let mut forbidden_matches = Vec::new();

        for line in diff.lines() {
            if line.starts_with('+') && !line.starts_with("+++") {
                additions += 1;

                // Check added lines for forbidden patterns.
                for (idx, regex) in self.forbidden_regexes.iter().enumerate() {
                    if regex.is_match(line) {
                        forbidden_matches.push(ForbiddenMatch {
                            line: line.to_string(),
                            pattern: self.config.forbidden_patterns[idx].clone(),
                        });
                    }
                }
            } else if line.starts_with('-') && !line.starts_with("---") {
                deletions += 1;
            }
        }

        let imbalance_ratio = if deletions > 0 {
            additions as f64 / deletions as f64
        } else if additions > 0 {
            f64::INFINITY
        } else {
            1.0
        };

        PatchAnalysis {
            additions,
            deletions,
            imbalance_ratio,
            forbidden_matches,
            exceeds_max_additions: additions > self.config.max_additions,
            exceeds_max_deletions: deletions > self.config.max_deletions,
            exceeds_imbalance: self.config.require_balance
                && imbalance_ratio > self.config.max_imbalance_ratio,
        }
    }
}

impl Default for PatchIntegrityGuard {
    fn default() -> Self {
        Self::new()
    }
}

impl chio_kernel::Guard for PatchIntegrityGuard {
    fn name(&self) -> &str {
        "patch-integrity"
    }

    fn evaluate(&self, ctx: &GuardContext) -> Result<Verdict, KernelError> {
        if !self.enabled {
            return Ok(Verdict::Allow);
        }

        let action = extract_action(&ctx.request.tool_name, &ctx.request.arguments);

        let diff = match &action {
            ToolAction::Patch(_, diff) => diff.as_str(),
            _ => return Ok(Verdict::Allow),
        };

        let analysis = self.analyze(diff);

        if analysis.is_safe() {
            Ok(Verdict::Allow)
        } else {
            Ok(Verdict::Deny)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chio_kernel::Guard;

    #[test]
    fn safe_patch_is_allowed() {
        let guard = PatchIntegrityGuard::new();

        let diff = "\
--- a/file.txt
+++ b/file.txt
@@ -1,3 +1,4 @@
 unchanged
+added line 1
+added line 2
-deleted line";

        let analysis = guard.analyze(diff);
        assert_eq!(analysis.additions, 2);
        assert_eq!(analysis.deletions, 1);
        assert!(analysis.is_safe());
    }

    #[test]
    fn forbidden_pattern_blocks() {
        let guard = PatchIntegrityGuard::new();

        let diff = "\
+disable_security = True
+disable security = True
+rm -rf /";

        let analysis = guard.analyze(diff);
        assert!(!analysis.forbidden_matches.is_empty());
        assert!(analysis
            .forbidden_matches
            .iter()
            .any(|m| m.line.contains("disable security")));
        assert!(!analysis.is_safe());
    }

    #[test]
    fn eval_blocks_patch_with_eval() {
        let guard = PatchIntegrityGuard::new();

        let diff = "+eval(user_input)";
        let analysis = guard.analyze(diff);
        assert!(!analysis.is_safe());
    }

    #[test]
    fn max_additions_exceeded() {
        let config = PatchIntegrityConfig {
            max_additions: 5,
            ..Default::default()
        };
        let guard = PatchIntegrityGuard::with_config(config).expect("valid patch integrity config");

        let diff = "+line1\n+line2\n+line3\n+line4\n+line5\n+line6";
        let analysis = guard.analyze(diff);
        assert!(analysis.exceeds_max_additions);
        assert!(!analysis.is_safe());
    }

    #[test]
    fn max_deletions_exceeded() {
        let config = PatchIntegrityConfig {
            max_deletions: 2,
            ..Default::default()
        };
        let guard = PatchIntegrityGuard::with_config(config).expect("valid patch integrity config");

        let diff = "-del1\n-del2\n-del3";
        let analysis = guard.analyze(diff);
        assert!(analysis.exceeds_max_deletions);
        assert!(!analysis.is_safe());
    }

    #[test]
    fn imbalance_check() {
        let config = PatchIntegrityConfig {
            require_balance: true,
            max_imbalance_ratio: 2.0,
            ..Default::default()
        };
        let guard = PatchIntegrityGuard::with_config(config).expect("valid patch integrity config");

        // 6 additions, 1 deletion = ratio 6.0, exceeds 2.0
        let diff = "+a\n+b\n+c\n+d\n+e\n+f\n-x";
        let analysis = guard.analyze(diff);
        assert!(analysis.exceeds_imbalance);
        assert!(!analysis.is_safe());
    }

    #[test]
    fn evaluate_allows_safe_patch() {
        let guard = PatchIntegrityGuard::new();

        let kp = chio_core::crypto::Keypair::generate();
        let scope = chio_core::capability::ChioScope::default();
        let agent_id = kp.public_key().to_hex();
        let server_id = "srv-test".to_string();

        let cap_body = chio_core::capability::CapabilityTokenBody {
            id: "cap-test".to_string(),
            issuer: kp.public_key(),
            subject: kp.public_key(),
            scope: scope.clone(),
            issued_at: 0,
            expires_at: u64::MAX,
            delegation_chain: vec![],
        };
        let cap = chio_core::capability::CapabilityToken::sign(cap_body, &kp).expect("sign cap");

        let request = chio_kernel::ToolCallRequest {
            request_id: "req-test".to_string(),
            capability: cap,
            tool_name: "apply_patch".to_string(),
            server_id: server_id.clone(),
            agent_id: agent_id.clone(),
            arguments: serde_json::json!({
                "path": "file.txt",
                "diff": "+added line\n-deleted line",
            }),
            dpop_proof: None,
            governed_intent: None,
            approval_token: None,
            model_metadata: None,
            federated_origin_kernel_id: None,
        };

        let ctx = chio_kernel::GuardContext {
            request: &request,
            scope: &scope,
            agent_id: &agent_id,
            server_id: &server_id,
            session_filesystem_roots: None,
            matched_grant_index: None,
        };

        let result = guard.evaluate(&ctx).expect("evaluate should not error");
        assert_eq!(result, Verdict::Allow);
    }

    #[test]
    fn evaluate_blocks_unsafe_patch() {
        let guard = PatchIntegrityGuard::new();

        let kp = chio_core::crypto::Keypair::generate();
        let scope = chio_core::capability::ChioScope::default();
        let agent_id = kp.public_key().to_hex();
        let server_id = "srv-test".to_string();

        let cap_body = chio_core::capability::CapabilityTokenBody {
            id: "cap-test".to_string(),
            issuer: kp.public_key(),
            subject: kp.public_key(),
            scope: scope.clone(),
            issued_at: 0,
            expires_at: u64::MAX,
            delegation_chain: vec![],
        };
        let cap = chio_core::capability::CapabilityToken::sign(cap_body, &kp).expect("sign cap");

        let request = chio_kernel::ToolCallRequest {
            request_id: "req-test".to_string(),
            capability: cap,
            tool_name: "apply_patch".to_string(),
            server_id: server_id.clone(),
            agent_id: agent_id.clone(),
            arguments: serde_json::json!({
                "path": "file.py",
                "diff": "+eval(user_input)",
            }),
            dpop_proof: None,
            governed_intent: None,
            approval_token: None,
            model_metadata: None,
            federated_origin_kernel_id: None,
        };

        let ctx = chio_kernel::GuardContext {
            request: &request,
            scope: &scope,
            agent_id: &agent_id,
            server_id: &server_id,
            session_filesystem_roots: None,
            matched_grant_index: None,
        };

        let result = guard.evaluate(&ctx).expect("evaluate should not error");
        assert_eq!(result, Verdict::Deny);
    }

    #[test]
    fn disabled_guard_allows_everything() {
        let config = PatchIntegrityConfig {
            enabled: false,
            ..Default::default()
        };
        let guard = PatchIntegrityGuard::with_config(config).expect("valid patch integrity config");

        let kp = chio_core::crypto::Keypair::generate();
        let scope = chio_core::capability::ChioScope::default();
        let agent_id = kp.public_key().to_hex();
        let server_id = "srv-test".to_string();

        let cap_body = chio_core::capability::CapabilityTokenBody {
            id: "cap-test".to_string(),
            issuer: kp.public_key(),
            subject: kp.public_key(),
            scope: scope.clone(),
            issued_at: 0,
            expires_at: u64::MAX,
            delegation_chain: vec![],
        };
        let cap = chio_core::capability::CapabilityToken::sign(cap_body, &kp).expect("sign cap");

        let request = chio_kernel::ToolCallRequest {
            request_id: "req-test".to_string(),
            capability: cap,
            tool_name: "apply_patch".to_string(),
            server_id: server_id.clone(),
            agent_id: agent_id.clone(),
            arguments: serde_json::json!({
                "path": "file.py",
                "diff": "+eval(user_input)\n+reverse_shell()",
            }),
            dpop_proof: None,
            governed_intent: None,
            approval_token: None,
            model_metadata: None,
            federated_origin_kernel_id: None,
        };

        let ctx = chio_kernel::GuardContext {
            request: &request,
            scope: &scope,
            agent_id: &agent_id,
            server_id: &server_id,
            session_filesystem_roots: None,
            matched_grant_index: None,
        };

        let result = guard.evaluate(&ctx).expect("evaluate should not error");
        assert_eq!(result, Verdict::Allow);
    }

    #[test]
    fn with_config_rejects_invalid_forbidden_regex() {
        let config = PatchIntegrityConfig {
            forbidden_patterns: vec!["[".to_string()],
            ..Default::default()
        };

        let error = match PatchIntegrityGuard::with_config(config) {
            Ok(_) => panic!("invalid forbidden regex should fail closed"),
            Err(error) => error,
        };
        assert!(matches!(
            error,
            PatchIntegrityConfigError::InvalidForbiddenPattern { .. }
        ));
    }
}