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
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
//! ComputerUseGuard - coarse gate for Computer Use Agent (CUA) actions.
//!
//! Roadmap phase 5.1.  Ported from ClawdStrike's
//! `guards/computer_use.rs` and adapted to Chio's synchronous
//! [`chio_kernel::Guard`] trait.
//!
//! The guard is a coarse-grained allowlist for CUA action types.  It
//! recognises three surfaces that arrive on the kernel:
//!
//! 1. **Remote-session and side-channel actions** - tool names or
//!    `action_type`/`custom_type` arguments that start with `remote.` or
//!    `input.` (e.g., `remote.clipboard`, `input.inject`).  The action-type
//!    string is matched against a configurable allowlist.
//! 2. **[`ToolAction::BrowserAction`]** - browser navigation verbs.  The
//!    guard denies navigation to configured blocked domains.
//! 3. **Screenshot actions** (subset of [`ToolAction::BrowserAction`] with
//!    a `screenshot`-family verb) - rate-limited via a token bucket so a
//!    runaway agent cannot drain the capture channel.
//!
//! Enforcement modes:
//!
//! | Mode         | Behavior                                              |
//! |--------------|-------------------------------------------------------|
//! | [`EnforcementMode::Observe`]     | Always allow; logs every decision |
//! | [`EnforcementMode::Guardrail`]   | Allow if in allowlist, warn otherwise (default) |
//! | [`EnforcementMode::FailClosed`]  | Allow if in allowlist, deny otherwise |
//!
//! Fail-closed semantics:
//!
//! - [`ToolAction::Unknown`] / non-CUA actions → [`Verdict::Allow`];
//! - invalid configuration → best-effort fallback to defaults at build
//!   time (never panics);
//! - token-bucket mutex poisoning → treated as no-tokens (deny).

use std::collections::HashSet;

use serde::{Deserialize, Serialize};

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

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

/// Default allowlist of CUA action-type strings.
///
/// Mirrors the ClawdStrike default set so upstream policy taxonomies
/// continue to work without translation.
pub fn default_allowed_action_types() -> Vec<String> {
    vec![
        "remote.session.connect".to_string(),
        "remote.session.disconnect".to_string(),
        "remote.session.reconnect".to_string(),
        "input.inject".to_string(),
        "remote.clipboard".to_string(),
        "remote.file_transfer".to_string(),
        "remote.audio".to_string(),
        "remote.drive_mapping".to_string(),
        "remote.printing".to_string(),
        "remote.session_share".to_string(),
    ]
}

/// Enforcement modes for [`ComputerUseGuard`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EnforcementMode {
    /// Always allow, regardless of allowlist membership.
    Observe,
    /// Allow if in allowlist; allow-with-warning otherwise.
    #[default]
    Guardrail,
    /// Allow if in allowlist; deny otherwise (fail-closed).
    FailClosed,
}

/// Configuration for [`ComputerUseGuard`].
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ComputerUseConfig {
    /// Enable/disable the guard.  When `false`, [`Guard::evaluate`] always
    /// returns `Allow`.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Allowed CUA action-type strings (for `remote.*` / `input.*` flows).
    #[serde(default = "default_allowed_action_types")]
    pub allowed_action_types: Vec<String>,
    /// Enforcement mode.
    #[serde(default)]
    pub mode: EnforcementMode,
    /// Domain patterns (exact host match or `*.suffix` wildcard) that are
    /// blocked for browser navigation.
    #[serde(default)]
    pub blocked_domains: Vec<String>,
    /// Optional allowlist of navigation hosts.  When non-empty, navigation
    /// to a host outside the allowlist is treated the same as a blocked
    /// domain in `FailClosed` mode, warned in `Guardrail`, ignored in
    /// `Observe`.
    #[serde(default)]
    pub allowed_domains: Vec<String>,
    /// Maximum screenshots per second (token-bucket refill rate).  `None`
    /// disables rate limiting.
    #[serde(default)]
    pub screenshot_rate_per_second: Option<f64>,
    /// Token-bucket burst capacity for screenshot rate limiting.  Defaults
    /// to `5` when [`Self::screenshot_rate_per_second`] is set.
    #[serde(default)]
    pub screenshot_burst: Option<u32>,
}

fn default_true() -> bool {
    true
}

impl Default for ComputerUseConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            allowed_action_types: default_allowed_action_types(),
            mode: EnforcementMode::Guardrail,
            blocked_domains: Vec::new(),
            allowed_domains: Vec::new(),
            screenshot_rate_per_second: None,
            screenshot_burst: None,
        }
    }
}

/// Coarse gate for CUA actions.
///
/// See [module docs](self) for the policy surface.
pub struct ComputerUseGuard {
    enabled: bool,
    mode: EnforcementMode,
    allowed_actions: HashSet<String>,
    blocked_domains: Vec<String>,
    allowed_domains: Vec<String>,
    screenshot_bucket: Option<TokenBucket>,
}

impl ComputerUseGuard {
    /// Build a guard with default configuration.
    pub fn new() -> Self {
        Self::with_config(ComputerUseConfig::default())
    }

    /// Build a guard with an explicit configuration.
    pub fn with_config(config: ComputerUseConfig) -> Self {
        let allowed_actions: HashSet<String> = config.allowed_action_types.into_iter().collect();
        let screenshot_bucket = match config.screenshot_rate_per_second {
            Some(rate) if rate > 0.0 && rate.is_finite() => {
                let burst = config.screenshot_burst.unwrap_or(5).max(1);
                Some(TokenBucket::new(rate, burst))
            }
            _ => None,
        };
        Self {
            enabled: config.enabled,
            mode: config.mode,
            allowed_actions,
            blocked_domains: config.blocked_domains,
            allowed_domains: config.allowed_domains,
            screenshot_bucket,
        }
    }

    /// Returns `true` if the verb indicates a screenshot/screen-capture
    /// browser action.
    fn is_screenshot_verb(verb: &str) -> bool {
        let v = verb.to_ascii_lowercase();
        matches!(
            v.as_str(),
            "screenshot"
                | "screen_capture"
                | "screen_shot"
                | "capture"
                | "capture_screen"
                | "browser_screenshot"
        )
    }

    /// Extract the CUA `action_type` string from a tool call, if any.
    ///
    /// Checks (in priority order):
    /// 1. `tool_name` itself if it starts with `remote.` or `input.`;
    /// 2. the `action_type` / `actionType` argument;
    /// 3. the `custom_type` / `customType` argument.
    fn extract_cua_action_type<'a>(
        tool_name: &'a str,
        arguments: &'a serde_json::Value,
    ) -> Option<String> {
        if tool_name.starts_with("remote.") || tool_name.starts_with("input.") {
            return Some(tool_name.to_string());
        }
        for key in ["action_type", "actionType", "custom_type", "customType"] {
            if let Some(value) = arguments.get(key).and_then(|v| v.as_str()) {
                if value.starts_with("remote.") || value.starts_with("input.") {
                    return Some(value.to_string());
                }
            }
        }
        None
    }

    /// Apply the configured enforcement mode to an allowlist decision.
    fn apply_mode(&self, in_allowlist: bool) -> Verdict {
        match (self.mode, in_allowlist) {
            (EnforcementMode::Observe, _) => Verdict::Allow,
            (EnforcementMode::Guardrail, _) => Verdict::Allow,
            (EnforcementMode::FailClosed, true) => Verdict::Allow,
            (EnforcementMode::FailClosed, false) => Verdict::Deny,
        }
    }

    /// Check browser navigation against the blocked/allowed domain sets.
    fn check_navigation(&self, target: &str) -> Verdict {
        // Only apply navigation gating when either list has content; the
        // module docs call this out as opt-in.
        if self.blocked_domains.is_empty() && self.allowed_domains.is_empty() {
            return Verdict::Allow;
        }
        let host = match extract_host(target) {
            Some(host) => host,
            None => {
                // Opaque navigation targets (selectors, data URIs) are
                // allowed here - finer checks belong to
                // `BrowserNavigationGuard`.
                return Verdict::Allow;
            }
        };
        let blocked = self
            .blocked_domains
            .iter()
            .any(|pat| matches_domain(pat, &host));
        if blocked {
            return match self.mode {
                EnforcementMode::Observe => Verdict::Allow,
                EnforcementMode::Guardrail | EnforcementMode::FailClosed => Verdict::Deny,
            };
        }
        if !self.allowed_domains.is_empty() {
            let allowed = self
                .allowed_domains
                .iter()
                .any(|pat| matches_domain(pat, &host));
            if !allowed {
                return match self.mode {
                    EnforcementMode::Observe | EnforcementMode::Guardrail => Verdict::Allow,
                    EnforcementMode::FailClosed => Verdict::Deny,
                };
            }
        }
        Verdict::Allow
    }
}

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

impl Guard for ComputerUseGuard {
    fn name(&self) -> &str {
        "computer-use"
    }

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

        // 1. Direct CUA action-type dispatch (remote.*, input.*).
        if let Some(action_type) =
            Self::extract_cua_action_type(&ctx.request.tool_name, &ctx.request.arguments)
        {
            let in_allowlist = self.allowed_actions.contains(&action_type);
            return Ok(self.apply_mode(in_allowlist));
        }

        // 2. BrowserAction: navigation domain checks + screenshot rate limit.
        let action = extract_action(&ctx.request.tool_name, &ctx.request.arguments);
        if let ToolAction::BrowserAction { verb, target } = &action {
            // Screenshot rate-limit.
            if Self::is_screenshot_verb(verb) {
                if let Some(bucket) = &self.screenshot_bucket {
                    if !bucket.try_acquire() {
                        return Ok(match self.mode {
                            EnforcementMode::Observe => Verdict::Allow,
                            EnforcementMode::Guardrail | EnforcementMode::FailClosed => {
                                Verdict::Deny
                            }
                        });
                    }
                }
                return Ok(Verdict::Allow);
            }

            // Navigation domain check.
            if matches!(
                verb.to_ascii_lowercase().as_str(),
                "navigate" | "goto" | "open"
            ) {
                if let Some(url) = target {
                    return Ok(self.check_navigation(url));
                }
            }
        }

        // 3. Non-CUA actions pass through.
        Ok(Verdict::Allow)
    }
}

/// Match a domain host against a pattern.  Supports exact match and
/// `*.suffix` wildcard patterns (same semantics as Chio's egress allowlist).
fn matches_domain(pattern: &str, host: &str) -> bool {
    let pattern = pattern.trim().to_ascii_lowercase();
    let host = host.trim().to_ascii_lowercase();
    if pattern.is_empty() || host.is_empty() {
        return false;
    }
    if let Some(suffix) = pattern.strip_prefix("*.") {
        return host == suffix || host.ends_with(&format!(".{suffix}"));
    }
    pattern == host
}

/// Extract the host portion of a URL.  Returns `None` for opaque targets
/// like CSS selectors, data URIs, or empty strings.
fn extract_host(url: &str) -> Option<String> {
    let url = url.trim();
    if url.is_empty() {
        return None;
    }
    // Reject obvious non-URL targets used by browser click/type actions.
    if url.starts_with('#') || url.starts_with('.') || url.starts_with('[') {
        return None;
    }
    // Reject data / javascript / about URIs - no network host.
    let lowered = url.to_ascii_lowercase();
    if lowered.starts_with("data:")
        || lowered.starts_with("javascript:")
        || lowered.starts_with("about:")
        || lowered.starts_with("file:")
    {
        return None;
    }
    let rest = if lowered.starts_with("https://") {
        &url["https://".len()..]
    } else if lowered.starts_with("http://") {
        &url["http://".len()..]
    } else if let Some(rest) = url.strip_prefix("//") {
        rest
    } else {
        url
    };
    let host_with_port = rest.split(['/', '?', '#']).next().unwrap_or(rest);
    let host_without_userinfo = host_with_port
        .rsplit_once('@')
        .map(|(_, host)| host)
        .unwrap_or(host_with_port);
    let host = if let Some(bracketed) = host_without_userinfo.strip_prefix('[') {
        let (host, remainder) = bracketed.split_once(']')?;
        if !remainder.is_empty() && !remainder.starts_with(':') {
            return None;
        }
        host
    } else {
        host_without_userinfo
            .rsplit_once(':')
            .map(|(h, _)| h)
            .unwrap_or(host_without_userinfo)
    }
    .trim_matches(|c: char| c == '/' || c == '.');
    if host.is_empty() {
        return None;
    }
    Some(host.to_ascii_lowercase())
}

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

    #[test]
    fn matches_domain_exact_and_wildcard() {
        assert!(matches_domain("example.com", "example.com"));
        assert!(!matches_domain("example.com", "evil.com"));
        assert!(matches_domain("*.example.com", "api.example.com"));
        assert!(matches_domain("*.example.com", "example.com"));
        assert!(!matches_domain("*.example.com", "example.org"));
    }

    #[test]
    fn extract_host_handles_common_urls() {
        assert_eq!(
            extract_host("https://example.com/x"),
            Some("example.com".into())
        );
        assert_eq!(
            extract_host("HTTPS://169.254.169.254/latest"),
            Some("169.254.169.254".into())
        );
        assert_eq!(
            extract_host("https://user:pass@example.com:8443/x"),
            Some("example.com".into())
        );
        assert_eq!(
            extract_host("https://user@[fd00:ec2::254]:8443/x"),
            Some("fd00:ec2::254".into())
        );
        assert_eq!(
            extract_host("http://localhost:8080"),
            Some("localhost".into())
        );
        assert_eq!(
            extract_host("example.com:443/y"),
            Some("example.com".into())
        );
        assert_eq!(
            extract_host("//169.254.169.254/latest"),
            Some("169.254.169.254".into())
        );
        assert_eq!(
            extract_host("https://blocked.example?redir=1"),
            Some("blocked.example".into())
        );
        assert_eq!(
            extract_host("https://blocked.example#anchor"),
            Some("blocked.example".into())
        );
        assert_eq!(extract_host("#submit"), None);
        assert_eq!(extract_host("data:text/plain,hi"), None);
    }

    #[test]
    fn check_navigation_blocks_scheme_relative_urls() {
        let guard = ComputerUseGuard::with_config(ComputerUseConfig {
            mode: EnforcementMode::FailClosed,
            blocked_domains: vec!["169.254.169.254".into()],
            ..ComputerUseConfig::default()
        });

        assert_eq!(
            guard.check_navigation("//169.254.169.254/latest"),
            Verdict::Deny
        );
    }

    #[test]
    fn check_navigation_blocks_urls_with_userinfo() {
        let guard = ComputerUseGuard::with_config(ComputerUseConfig {
            mode: EnforcementMode::FailClosed,
            blocked_domains: vec!["blocked.example".into()],
            ..ComputerUseConfig::default()
        });

        assert_eq!(
            guard.check_navigation("https://user@blocked.example/path"),
            Verdict::Deny
        );
    }

    #[test]
    fn check_navigation_blocks_bracketed_ipv6_hosts() {
        let guard = ComputerUseGuard::with_config(ComputerUseConfig {
            mode: EnforcementMode::FailClosed,
            blocked_domains: vec!["fd00:ec2::254".into()],
            ..ComputerUseConfig::default()
        });

        assert_eq!(
            guard.check_navigation("https://[fd00:ec2::254]/latest"),
            Verdict::Deny
        );
    }

    #[test]
    fn check_navigation_blocks_query_and_fragment_only_urls() {
        let guard = ComputerUseGuard::with_config(ComputerUseConfig {
            mode: EnforcementMode::FailClosed,
            blocked_domains: vec!["blocked.example".into()],
            ..ComputerUseConfig::default()
        });

        assert_eq!(
            guard.check_navigation("https://blocked.example?redir=1"),
            Verdict::Deny
        );
        assert_eq!(
            guard.check_navigation("https://blocked.example#anchor"),
            Verdict::Deny
        );
    }

    #[test]
    fn check_navigation_blocks_mixed_case_scheme_urls() {
        let guard = ComputerUseGuard::with_config(ComputerUseConfig {
            mode: EnforcementMode::FailClosed,
            blocked_domains: vec!["169.254.169.254".into()],
            ..ComputerUseConfig::default()
        });

        assert_eq!(
            guard.check_navigation("HTTPS://169.254.169.254/latest"),
            Verdict::Deny
        );
    }

    #[test]
    fn is_screenshot_verb_matches_common_names() {
        assert!(ComputerUseGuard::is_screenshot_verb("screenshot"));
        assert!(ComputerUseGuard::is_screenshot_verb("capture_screen"));
        assert!(!ComputerUseGuard::is_screenshot_verb("click"));
    }

    #[test]
    fn extract_cua_action_type_reads_args() {
        let args = serde_json::json!({"action_type": "remote.clipboard"});
        assert_eq!(
            ComputerUseGuard::extract_cua_action_type("unknown", &args),
            Some("remote.clipboard".to_string())
        );
    }
}