omamori 0.6.0

AI Agent's Omamori — protect your system from dangerous commands executed via AI CLI tools
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
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};

use crate::config::BLOCKED_DESTINATION_PREFIXES;
use crate::rules::{ActionKind, CommandInvocation, RuleConfig};

fn exit_code_from_status(status: ExitStatus) -> i32 {
    if let Some(code) = status.code() {
        return code;
    }
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        if let Some(sig) = status.signal() {
            return 128 + sig;
        }
    }
    1
}

#[derive(Debug, Clone)]
pub enum ActionOutcome {
    PassedThrough { exit_code: i32 },
    Trashed { exit_code: i32, message: String },
    ExecutedAfterStash { exit_code: i32, message: String },
    LoggedOnly { exit_code: i32, message: String },
    MovedTo { exit_code: i32, message: String },
    Blocked { message: String },
    Failed { message: String },
}

impl ActionOutcome {
    pub fn exit_code(&self) -> i32 {
        match self {
            Self::PassedThrough { exit_code }
            | Self::Trashed { exit_code, .. }
            | Self::ExecutedAfterStash { exit_code, .. }
            | Self::LoggedOnly { exit_code, .. }
            | Self::MovedTo { exit_code, .. } => *exit_code,
            Self::Blocked { .. } | Self::Failed { .. } => 1,
        }
    }

    pub fn message(&self) -> &str {
        match self {
            Self::PassedThrough { .. } => "omamori allowed the command to run unchanged",
            Self::Trashed { message, .. }
            | Self::ExecutedAfterStash { message, .. }
            | Self::LoggedOnly { message, .. }
            | Self::MovedTo { message, .. }
            | Self::Blocked { message }
            | Self::Failed { message } => message,
        }
    }

    pub fn label(&self) -> &'static str {
        match self {
            Self::PassedThrough { .. } => "passthrough",
            Self::Trashed { .. } => "trash",
            Self::ExecutedAfterStash { .. } => "stash-then-exec",
            Self::LoggedOnly { .. } => "log-only",
            Self::MovedTo { .. } => "move-to",
            Self::Blocked { .. } => "block",
            Self::Failed { .. } => "failed",
        }
    }
}

pub trait ExecOps {
    fn passthrough(&mut self, invocation: &CommandInvocation) -> io::Result<i32>;
    fn move_to_trash(&mut self, targets: &[String]) -> Result<(), String>;
    fn move_to_dir(&mut self, targets: &[String], destination: &Path) -> Result<usize, String>;
    fn git_stash(&mut self) -> Result<(), String>;
}

pub struct SystemOps {
    real_program: PathBuf,
    detector_env_keys: Vec<String>,
}

impl SystemOps {
    pub fn new(real_program: PathBuf, detector_env_keys: Vec<String>) -> Self {
        Self {
            real_program,
            detector_env_keys,
        }
    }
}

impl ExecOps for SystemOps {
    fn passthrough(&mut self, invocation: &CommandInvocation) -> io::Result<i32> {
        let status = Command::new(&self.real_program)
            .args(&invocation.args)
            .status()?;
        Ok(exit_code_from_status(status))
    }

    fn move_to_trash(&mut self, targets: &[String]) -> Result<(), String> {
        let paths = targets.iter().map(PathBuf::from).collect::<Vec<_>>();
        trash::delete_all(paths).map_err(|error| error.to_string())
    }

    fn move_to_dir(&mut self, targets: &[String], destination: &Path) -> Result<usize, String> {
        // Validate destination at execution time (fail-close)
        if !destination.exists() {
            return Err(format!(
                "move-to directory `{}` does not exist; refusing to run the original command",
                destination.display()
            ));
        }
        if !destination.is_dir() {
            return Err(format!(
                "move-to path `{}` is not a directory",
                destination.display()
            ));
        }

        // Check for symlink at execution time (TOCTOU mitigation)
        let meta = std::fs::symlink_metadata(destination).map_err(|e| e.to_string())?;
        if meta.file_type().is_symlink() {
            return Err(format!(
                "move-to directory `{}` is a symlink; refusing for security",
                destination.display()
            ));
        }

        // Re-check blocked prefixes at execution time (M1 fix: canonicalize may
        // have failed at config-load time if the directory didn't exist yet)
        if let Ok(canonical) = destination.canonicalize() {
            let canonical_str = canonical.to_string_lossy();
            for prefix in BLOCKED_DESTINATION_PREFIXES {
                if canonical_str.starts_with(prefix) {
                    return Err(format!(
                        "move-to directory `{}` resolves to blocked system path `{canonical_str}`",
                        destination.display()
                    ));
                }
            }
        }

        // Create timestamped subdirectory to avoid filename collisions
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let sub_dir = destination.join(format!("{timestamp}"));
        std::fs::create_dir_all(&sub_dir)
            .map_err(|e| format!("failed to create subdirectory `{}`: {e}", sub_dir.display()))?;

        let mut moved = 0usize;
        let mut used_names = std::collections::HashSet::new();
        for target in targets {
            let src = PathBuf::from(target);
            let base_name = src
                .file_name()
                .unwrap_or(src.as_os_str())
                .to_string_lossy()
                .into_owned();
            // Deduplicate basenames: append _2, _3, etc. if collision
            let unique_name = if used_names.contains(&base_name) {
                let mut counter = 2u32;
                loop {
                    let candidate = format!("{base_name}_{counter}");
                    if !used_names.contains(&candidate) {
                        break candidate;
                    }
                    counter += 1;
                }
            } else {
                base_name.clone()
            };
            used_names.insert(unique_name.clone());
            let dest = sub_dir.join(&unique_name);

            std::fs::rename(&src, &dest).map_err(|e| {
                if e.raw_os_error() == Some(18) {
                    // EXDEV: cross-device link
                    format!(
                        "cannot move `{target}` to `{}`: cross-device move is not supported (use a destination on the same volume)",
                        destination.display()
                    )
                } else {
                    format!("failed to move `{target}` to `{}`: {e}", dest.display())
                }
            })?;
            moved += 1;
        }
        Ok(moved)
    }

    fn git_stash(&mut self) -> Result<(), String> {
        // Remove AI detector env vars so the internal git call does not
        // trigger omamori's own protection (self-interference prevention).
        let mut cmd = Command::new("git");
        cmd.arg("stash").arg("push").arg("--include-untracked");
        for key in &self.detector_env_keys {
            cmd.env_remove(key);
        }
        let status = cmd.status().map_err(|error| error.to_string())?;
        if status.success() {
            Ok(())
        } else {
            Err(format!("git stash exited with status {:?}", status.code()))
        }
    }
}

pub struct ActionExecutor<T: ExecOps> {
    ops: T,
}

impl<T: ExecOps> ActionExecutor<T> {
    pub fn new(ops: T) -> Self {
        Self { ops }
    }

    pub fn exec_passthrough(
        &mut self,
        invocation: &CommandInvocation,
    ) -> Result<ActionOutcome, io::Error> {
        let exit_code = self.ops.passthrough(invocation)?;
        Ok(ActionOutcome::PassedThrough { exit_code })
    }

    pub fn execute(
        &mut self,
        invocation: &CommandInvocation,
        rule: &RuleConfig,
    ) -> Result<ActionOutcome, io::Error> {
        let message = rule
            .message
            .clone()
            .unwrap_or_else(|| format!("omamori applied `{}`", rule.name));

        let outcome = match rule.action {
            ActionKind::Trash => {
                let targets: Vec<String> = invocation
                    .target_args()
                    .into_iter()
                    .map(String::from)
                    .collect();
                if targets.is_empty() {
                    ActionOutcome::Failed {
                        message: "omamori could not identify any rm targets to move to Trash"
                            .to_string(),
                    }
                } else {
                    match self.ops.move_to_trash(&targets) {
                        Ok(()) => ActionOutcome::Trashed {
                            exit_code: 0,
                            message,
                        },
                        Err(error) => ActionOutcome::Failed {
                            message: format!(
                                "omamori failed to move the targets to Trash and refused to run rm: {error}"
                            ),
                        },
                    }
                }
            }
            ActionKind::StashThenExec => match self.ops.git_stash() {
                Ok(()) => {
                    let exit_code = self.ops.passthrough(invocation)?;
                    ActionOutcome::ExecutedAfterStash { exit_code, message }
                }
                Err(error) => ActionOutcome::Failed {
                    message: format!(
                        "omamori could not create a git stash before execution: {error}"
                    ),
                },
            },
            ActionKind::MoveTo => {
                let destination = match &rule.destination {
                    Some(dest) => PathBuf::from(dest),
                    None => {
                        return Ok(ActionOutcome::Failed {
                            message: "omamori move-to rule has no destination configured"
                                .to_string(),
                        });
                    }
                };
                let targets: Vec<String> = invocation
                    .target_args()
                    .into_iter()
                    .map(String::from)
                    .collect();
                if targets.is_empty() {
                    ActionOutcome::Failed {
                        message: "omamori could not identify any targets to move".to_string(),
                    }
                } else {
                    match self.ops.move_to_dir(&targets, &destination) {
                        Ok(count) => ActionOutcome::MovedTo {
                            exit_code: 0,
                            message: format!(
                                "{message} ({count} target(s) moved to {})",
                                destination.display()
                            ),
                        },
                        Err(error) => ActionOutcome::Failed {
                            message: format!(
                                "omamori failed to move targets to `{}` and refused to run the original command: {error}",
                                destination.display()
                            ),
                        },
                    }
                }
            }
            ActionKind::Block => ActionOutcome::Blocked { message },
            ActionKind::LogOnly => {
                let exit_code = self.ops.passthrough(invocation)?;
                ActionOutcome::LoggedOnly { exit_code, message }
            }
        };

        Ok(outcome)
    }
}

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

    #[derive(Default)]
    struct FakeOps {
        passthrough_calls: usize,
        passthrough_status: i32,
        trash_error: Option<String>,
        move_to_dir_error: Option<String>,
        stash_error: Option<String>,
        last_trash_targets: Vec<String>,
        last_move_targets: Vec<String>,
        last_move_destination: Option<PathBuf>,
    }

    impl ExecOps for FakeOps {
        fn passthrough(&mut self, _invocation: &CommandInvocation) -> io::Result<i32> {
            self.passthrough_calls += 1;
            Ok(self.passthrough_status)
        }

        fn move_to_trash(&mut self, targets: &[String]) -> Result<(), String> {
            self.last_trash_targets = targets.to_vec();
            match &self.trash_error {
                Some(error) => Err(error.clone()),
                None => Ok(()),
            }
        }

        fn move_to_dir(&mut self, targets: &[String], destination: &Path) -> Result<usize, String> {
            self.last_move_targets = targets.to_vec();
            self.last_move_destination = Some(destination.to_path_buf());
            match &self.move_to_dir_error {
                Some(error) => Err(error.clone()),
                None => Ok(targets.len()),
            }
        }

        fn git_stash(&mut self) -> Result<(), String> {
            match &self.stash_error {
                Some(error) => Err(error.clone()),
                None => Ok(()),
            }
        }
    }

    fn rule(action: ActionKind, command: &str) -> RuleConfig {
        RuleConfig::new(
            "test",
            command,
            action,
            Vec::new(),
            Vec::new(),
            Some("message".to_string()),
        )
    }

    #[test]
    fn trash_failure_does_not_fall_back_to_passthrough() {
        let mut executor = ActionExecutor::new(FakeOps {
            trash_error: Some("no trash".to_string()),
            ..Default::default()
        });
        let invocation = CommandInvocation::new(
            "rm".to_string(),
            vec!["-rf".to_string(), "danger".to_string()],
        );
        let outcome = executor
            .execute(&invocation, &rule(ActionKind::Trash, "rm"))
            .unwrap();
        assert!(matches!(outcome, ActionOutcome::Failed { .. }));
    }

    #[test]
    fn stash_then_exec_runs_both_steps() {
        let mut executor = ActionExecutor::new(FakeOps::default());
        let invocation = CommandInvocation::new(
            "git".to_string(),
            vec!["reset".to_string(), "--hard".to_string()],
        );
        let outcome = executor
            .execute(&invocation, &rule(ActionKind::StashThenExec, "git"))
            .unwrap();
        assert!(matches!(outcome, ActionOutcome::ExecutedAfterStash { .. }));
    }

    #[test]
    fn trash_with_double_dash_captures_dash_prefixed_targets() {
        let mut executor = ActionExecutor::new(FakeOps::default());
        let invocation = CommandInvocation::new(
            "rm".to_string(),
            vec![
                "-rf".to_string(),
                "--".to_string(),
                "-dangerous.txt".to_string(),
            ],
        );
        let outcome = executor
            .execute(&invocation, &rule(ActionKind::Trash, "rm"))
            .unwrap();
        assert!(matches!(outcome, ActionOutcome::Trashed { .. }));
        assert_eq!(executor.ops.last_trash_targets, vec!["-dangerous.txt"]);
    }

    #[test]
    fn move_to_succeeds_with_destination() {
        let mut executor = ActionExecutor::new(FakeOps::default());
        let invocation = CommandInvocation::new(
            "rm".to_string(),
            vec!["-rf".to_string(), "target/".to_string()],
        );
        let rule = RuleConfig::new(
            "rm-move",
            "rm",
            ActionKind::MoveTo,
            Vec::new(),
            Vec::new(),
            Some("moved".to_string()),
        )
        .with_destination("/tmp/backup".to_string());
        let outcome = executor.execute(&invocation, &rule).unwrap();
        assert!(matches!(outcome, ActionOutcome::MovedTo { .. }));
        assert_eq!(executor.ops.last_move_targets, vec!["target/"]);
    }

    #[test]
    fn move_to_without_destination_fails() {
        let mut executor = ActionExecutor::new(FakeOps::default());
        let invocation = CommandInvocation::new(
            "rm".to_string(),
            vec!["-rf".to_string(), "target/".to_string()],
        );
        let rule = RuleConfig::new(
            "rm-move",
            "rm",
            ActionKind::MoveTo,
            Vec::new(),
            Vec::new(),
            None,
        );
        let outcome = executor.execute(&invocation, &rule).unwrap();
        assert!(matches!(outcome, ActionOutcome::Failed { .. }));
    }

    #[test]
    fn move_to_failure_does_not_fall_back_to_passthrough() {
        let mut executor = ActionExecutor::new(FakeOps {
            move_to_dir_error: Some("disk full".to_string()),
            ..Default::default()
        });
        let invocation = CommandInvocation::new(
            "rm".to_string(),
            vec!["-rf".to_string(), "target/".to_string()],
        );
        let rule = RuleConfig::new(
            "rm-move",
            "rm",
            ActionKind::MoveTo,
            Vec::new(),
            Vec::new(),
            None,
        )
        .with_destination("/tmp/backup".to_string());
        let outcome = executor.execute(&invocation, &rule).unwrap();
        assert!(matches!(outcome, ActionOutcome::Failed { .. }));
        assert_eq!(executor.ops.passthrough_calls, 0);
    }

    #[test]
    fn trash_with_only_double_dash_fails() {
        let mut executor = ActionExecutor::new(FakeOps::default());
        let invocation =
            CommandInvocation::new("rm".to_string(), vec!["-rf".to_string(), "--".to_string()]);
        let outcome = executor
            .execute(&invocation, &rule(ActionKind::Trash, "rm"))
            .unwrap();
        assert!(matches!(outcome, ActionOutcome::Failed { .. }));
    }
}