astrid-hooks 2026.9.4

Hook system for Astrid secure agent runtime
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
//! Command hook handler - executes shell commands.
//!
//! # Security
//!
//! This handler implements several security measures:
//! - Environment variable clearing (inherits only from allowlist)
//! - PATH restriction to safe directories
//! - Working directory isolation

use std::process::Stdio;
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;
use tokio::time::timeout;
use tracing::{debug, warn};

use super::{HandlerError, HandlerResult, parse_hook_result};
use crate::hook::HookHandler;
use crate::result::{HookContext, HookExecutionResult, HookResult};

/// Environment variables that are safe to inherit from the parent process.
const ALLOWED_ENV_VARS: &[&str] = &[
    // Essential system variables
    "PATH", "HOME", "USER", "SHELL", "TERM", "LANG", "LC_ALL", "LC_CTYPE",
    // Temporary directories
    "TMPDIR", "TMP", "TEMP",
];

/// Returns true if `key` matches a blocked env var or a blocked prefix.
///
/// Delegates to the shared blocklist in `astrid_core::env_policy`.
fn is_blocked_hook_env(key: &str) -> bool {
    astrid_core::env_policy::is_blocked_spawn_env(key)
}

/// Safe directories to include in PATH for sandboxed execution.
/// These are common system directories that contain safe utilities.
#[cfg(unix)]
const SAFE_PATH_DIRS: &[&str] = &["/usr/bin", "/bin", "/usr/local/bin"];

#[cfg(windows)]
const SAFE_PATH_DIRS: &[&str] = &[r"C:\Windows\System32", r"C:\Windows"];

/// Handler for executing shell commands with security sandboxing.
#[derive(Debug, Clone)]
pub(crate) struct CommandHandler {
    /// Whether to enable strict sandboxing (clear env, restrict PATH).
    sandboxed: bool,
}

impl Default for CommandHandler {
    fn default() -> Self {
        Self { sandboxed: true }
    }
}

impl CommandHandler {
    /// Create a new command handler with default sandboxing enabled.
    #[must_use]
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Create a new command handler with explicit sandbox setting.
    #[must_use]
    pub(crate) fn with_sandbox(sandboxed: bool) -> Self {
        Self { sandboxed }
    }

    /// Get the restricted PATH for sandboxed execution.
    fn safe_path() -> String {
        SAFE_PATH_DIRS.join(if cfg!(windows) { ";" } else { ":" })
    }

    /// Apply environment variables to a command, respecting sandbox policy.
    ///
    /// When sandboxed: clears env, re-adds safe allowlist, restricts PATH,
    /// then filters custom env vars against both allowlist and dangerous-var
    /// blocklist. When not sandboxed: applies custom env vars directly.
    fn apply_env(
        &self,
        cmd: &mut Command,
        custom_env: &std::collections::HashMap<String, String>,
        context: &HookContext,
    ) {
        if self.sandboxed {
            cmd.env_clear();

            for var in ALLOWED_ENV_VARS {
                if let Ok(value) = std::env::var(var) {
                    if *var == "PATH" {
                        cmd.env("PATH", Self::safe_path());
                    } else if *var == "HOME" {
                        // Validate HOME before relaying to child process
                        let p = std::path::Path::new(&value);
                        if p.is_absolute()
                            && !p
                                .components()
                                .any(|c| matches!(c, std::path::Component::ParentDir))
                        {
                            cmd.env(var, value);
                        } else {
                            warn!("Skipping HOME with invalid path in sandboxed hook");
                        }
                    } else {
                        cmd.env(var, value);
                    }
                }
            }
        }

        for (key, value) in custom_env {
            if self.sandboxed {
                if ALLOWED_ENV_VARS.iter().any(|k| k.eq_ignore_ascii_case(key)) {
                    warn!(
                        key = %key,
                        "Ignoring hook env var that would override sandboxed allowlist"
                    );
                    continue;
                }
                if is_blocked_hook_env(key) {
                    warn!(
                        key = %key,
                        "Blocking dangerous env var in sandboxed hook"
                    );
                    continue;
                }
            }
            cmd.env(key, value);
        }

        // Apply context env vars, filtering through the blocklist for safety.
        for (key, value) in context.to_env_vars() {
            if self.sandboxed && is_blocked_hook_env(&key) {
                warn!(
                    key = %key,
                    "Blocking dangerous context env var in sandboxed hook"
                );
                continue;
            }
            cmd.env(key, value);
        }
    }

    /// Execute a command handler.
    ///
    /// # Security
    ///
    /// When sandboxing is enabled:
    /// - Clears environment variables except for allowlisted ones
    /// - Restricts PATH to safe system directories
    /// - Runs the command with minimal privileges
    ///
    /// # Errors
    ///
    /// Returns an error if the handler configuration is invalid.
    pub(crate) async fn execute(
        &self,
        handler: &HookHandler,
        context: &HookContext,
        timeout_duration: Duration,
    ) -> HandlerResult<HookExecutionResult> {
        let HookHandler::Command {
            command,
            args,
            env,
            working_dir,
        } = handler
        else {
            return Err(HandlerError::InvalidConfiguration(
                "expected Command handler".to_string(),
            ));
        };

        debug!(command = %command, args = ?args, sandboxed = %self.sandboxed, "Executing command hook");

        // Build the command
        let mut cmd = Command::new(command);
        cmd.args(args);
        cmd.stdin(Stdio::piped());
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());

        // Set working directory if specified
        if let Some(dir) = working_dir {
            cmd.current_dir(dir);
        }

        // Apply sandboxing, custom env vars, and context env vars.
        self.apply_env(&mut cmd, env, context);

        // Serialize context JSON for stdin delivery
        let context_json = context.to_json().to_string();

        // Execute with timeout, piping context JSON on stdin
        let output = match timeout(timeout_duration, async {
            let mut child = cmd.spawn()?;

            // Write context JSON to stdin, then close it so the child sees EOF
            if let Some(mut stdin) = child.stdin.take() {
                let _ = stdin.write_all(context_json.as_bytes()).await;
                let _ = stdin.shutdown().await;
            }

            child.wait_with_output().await
        })
        .await
        {
            Ok(Ok(output)) => output,
            Ok(Err(e)) => {
                return Ok(HookExecutionResult::Failure {
                    error: format!("Failed to execute command: {e}"),
                    stderr: None,
                });
            },
            Err(_) => {
                return Ok(HookExecutionResult::Timeout {
                    timeout_secs: timeout_duration.as_secs(),
                });
            },
        };

        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();

        if !output.status.success() {
            let exit_code = output.status.code().unwrap_or(-1);
            warn!(
                command = %command,
                exit_code = exit_code,
                stderr = %stderr,
                "Command hook failed"
            );

            return Ok(HookExecutionResult::Failure {
                error: format!("Command exited with code {exit_code}"),
                stderr: Some(stderr),
            });
        }

        // Parse the result from stdout
        let result = parse_hook_result(&stdout).unwrap_or_else(|e| {
            warn!(error = %e, "Failed to parse hook result, defaulting to Continue");
            HookResult::Continue
        });

        Ok(HookExecutionResult::Success {
            result,
            stdout: Some(stdout),
        })
    }
}

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

    #[tokio::test]
    async fn test_command_handler_echo() {
        let handler = CommandHandler::new();
        let hook_handler = HookHandler::Command {
            command: "echo".to_string(),
            args: vec!["continue".to_string()],
            env: std::collections::HashMap::default(),
            working_dir: None,
        };
        let context = HookContext::new(HookEvent::SessionStart);

        let result = handler
            .execute(&hook_handler, &context, Duration::from_secs(5))
            .await
            .unwrap();

        assert!(result.is_success());
        if let HookExecutionResult::Success { result, .. } = result {
            assert!(matches!(result, HookResult::Continue));
        }
    }

    #[tokio::test]
    async fn test_command_handler_with_env() {
        let handler = CommandHandler::new();
        let hook_handler = HookHandler::Command {
            command: "sh".to_string(),
            args: vec!["-c".to_string(), "echo $ASTRID_HOOK_EVENT".to_string()],
            env: std::collections::HashMap::default(),
            working_dir: None,
        };
        let context = HookContext::new(HookEvent::PreToolCall);

        let result = handler
            .execute(&hook_handler, &context, Duration::from_secs(5))
            .await
            .unwrap();

        if let HookExecutionResult::Success { stdout, .. } = result {
            assert!(stdout.unwrap_or_default().contains("pre_tool_call"));
        }
    }

    #[tokio::test]
    async fn test_command_handler_timeout() {
        let handler = CommandHandler::new();
        let hook_handler = HookHandler::Command {
            command: "sleep".to_string(),
            args: vec!["10".to_string()],
            env: std::collections::HashMap::default(),
            working_dir: None,
        };
        let context = HookContext::new(HookEvent::SessionStart);

        let result = handler
            .execute(&hook_handler, &context, Duration::from_millis(100))
            .await
            .unwrap();

        assert!(matches!(result, HookExecutionResult::Timeout { .. }));
    }

    #[tokio::test]
    async fn test_command_handler_failure() {
        let handler = CommandHandler::new();
        let hook_handler = HookHandler::Command {
            command: "sh".to_string(),
            args: vec!["-c".to_string(), "exit 1".to_string()],
            env: std::collections::HashMap::default(),
            working_dir: None,
        };
        let context = HookContext::new(HookEvent::SessionStart);

        let result = handler
            .execute(&hook_handler, &context, Duration::from_secs(5))
            .await
            .unwrap();

        assert!(matches!(result, HookExecutionResult::Failure { .. }));
    }

    #[tokio::test]
    async fn test_command_handler_sandboxed() {
        // Create a sandboxed handler
        let handler = CommandHandler::with_sandbox(true);
        let hook_handler = HookHandler::Command {
            command: "sh".to_string(),
            args: vec!["-c".to_string(), "echo $HOME".to_string()],
            env: std::collections::HashMap::default(),
            working_dir: None,
        };
        let context = HookContext::new(HookEvent::SessionStart);

        let result = handler
            .execute(&hook_handler, &context, Duration::from_secs(5))
            .await
            .unwrap();

        // HOME should still be available (it's in the allowlist)
        if let HookExecutionResult::Success { stdout, .. } = result {
            let output = stdout.unwrap_or_default();
            // Should have some output (HOME is typically set)
            assert!(!output.trim().is_empty() || std::env::var("HOME").is_err());
        }
    }

    #[tokio::test]
    async fn test_command_handler_unsandboxed() {
        // Create an unsandboxed handler
        let handler = CommandHandler::with_sandbox(false);
        let hook_handler = HookHandler::Command {
            command: "echo".to_string(),
            args: vec!["continue".to_string()],
            env: std::collections::HashMap::default(),
            working_dir: None,
        };
        let context = HookContext::new(HookEvent::SessionStart);

        let result = handler
            .execute(&hook_handler, &context, Duration::from_secs(5))
            .await
            .unwrap();

        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_command_handler_custom_env_in_sandbox() {
        let handler = CommandHandler::with_sandbox(true);

        let mut custom_env = std::collections::HashMap::new();
        custom_env.insert("CUSTOM_VAR".to_string(), "custom_value".to_string());

        let hook_handler = HookHandler::Command {
            command: "sh".to_string(),
            args: vec!["-c".to_string(), "echo $CUSTOM_VAR".to_string()],
            env: custom_env,
            working_dir: None,
        };
        let context = HookContext::new(HookEvent::SessionStart);

        let result = handler
            .execute(&hook_handler, &context, Duration::from_secs(5))
            .await
            .unwrap();

        // Custom env vars should still be set even in sandbox mode
        if let HookExecutionResult::Success { stdout, .. } = result {
            assert!(stdout.unwrap_or_default().contains("custom_value"));
        }
    }

    #[tokio::test]
    async fn test_command_handler_stdin_context() {
        let handler = CommandHandler::new();
        // Read JSON from stdin and extract the event field
        let hook_handler = HookHandler::Command {
            command: "sh".to_string(),
            args: vec![
                "-c".to_string(),
                // Read stdin fully, then extract the event field with basic shell tools
                r#"INPUT=$(cat); echo "$INPUT" | grep -o '"event":"[^"]*"' | head -1"#.to_string(),
            ],
            env: std::collections::HashMap::default(),
            working_dir: None,
        };
        let context = HookContext::new(HookEvent::PreToolCall)
            .with_data("tool_name", serde_json::json!("Bash"));

        let result = handler
            .execute(&hook_handler, &context, Duration::from_secs(5))
            .await
            .unwrap();

        assert!(result.is_success());
        if let HookExecutionResult::Success { stdout, .. } = result {
            let output = stdout.unwrap_or_default();
            assert!(
                output.contains("pre_tool_call"),
                "stdin should contain context JSON with event field, got: {output}"
            );
        }
    }

    #[test]
    fn test_safe_path() {
        let path = CommandHandler::safe_path();
        // Should contain at least one standard directory
        #[cfg(unix)]
        assert!(path.contains("/bin") || path.contains("/usr/bin"));
        #[cfg(windows)]
        assert!(path.contains("System32"));
    }

    #[test]
    fn test_allowed_env_vars() {
        // Verify the allowlist contains expected variables
        assert!(ALLOWED_ENV_VARS.contains(&"PATH"));
        assert!(ALLOWED_ENV_VARS.contains(&"HOME"));
        assert!(ALLOWED_ENV_VARS.contains(&"USER"));

        // Verify potentially dangerous variables are NOT in the list
        assert!(!ALLOWED_ENV_VARS.contains(&"LD_PRELOAD"));
        assert!(!ALLOWED_ENV_VARS.contains(&"LD_LIBRARY_PATH"));
        assert!(!ALLOWED_ENV_VARS.contains(&"DYLD_INSERT_LIBRARIES"));
    }
}