omamori 0.10.9

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
//! `omamori explain [--json] [--config PATH] -- <command...>` subcommand.
//!
//! Simulate evaluation of a command through both defense layers without executing it.
//! Shows what would happen and why — answering "why was this blocked?"
//!
//! SECURITY (DI-8): blocked in AI environments to prevent oracle attacks.

use std::ffi::OsString;

use crate::AppError;
use crate::config::{self, ConfigLoadResult, load_config};
use crate::context;
use crate::engine::guard::guard_ai_config_modification;
use crate::engine::hook::{HookCheckResult, check_command_for_hook};
use crate::rules::{CommandInvocation, match_rule};
use crate::util::{parse_config_flag, usage_text};

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

pub(crate) fn run_explain_command(args: &[OsString]) -> Result<i32, AppError> {
    // DI-8: explain is blocked in AI environments (oracle attack prevention)
    guard_ai_config_modification("explain")?;

    let mut json = false;
    let mut config_args: Vec<OsString> = Vec::new();
    let mut command_parts: Vec<String> = Vec::new();
    let mut saw_separator = false;
    let mut index = 2usize;

    while index < args.len() {
        let arg = args[index].to_str().unwrap_or("");
        if saw_separator {
            command_parts.push(arg.to_string());
            index += 1;
            continue;
        }
        match arg {
            "--" => {
                saw_separator = true;
                index += 1;
            }
            "--json" => {
                json = true;
                index += 1;
            }
            "--config" => {
                config_args.push(args[index].clone());
                if let Some(val) = args.get(index + 1) {
                    config_args.push(val.clone());
                }
                index += 2;
            }
            _ => {
                return Err(AppError::Usage(format!(
                    "unknown explain flag: {arg}\n\nUsage: omamori explain [--json] [--config PATH] -- <command...>\n\n{}",
                    usage_text()
                )));
            }
        }
    }

    if command_parts.is_empty() {
        return Err(AppError::Usage(format!(
            "explain requires a command after `--`\n\nUsage: omamori explain [--json] [--config PATH] -- <command...>\n\n{}",
            usage_text()
        )));
    }

    let config_path = parse_config_flag(&config_args)?;
    // Preserve shell quoting for Layer 2 (hook evaluation operates on shell strings)
    let command_str = shell_words::join(&command_parts);

    // --- Layer 1 evaluation (shim / PATH-level) ---
    let layer1 = evaluate_layer1(&command_parts, config_path.as_deref());

    // --- Layer 2 evaluation (hook / token-level) ---
    let layer2 = evaluate_layer2(&command_str);

    // --- Verdict ---
    let blocked = layer1.blocked || layer2.blocked;
    let exit_code = if blocked { 2 } else { 0 };

    if json {
        print_json(&command_str, &layer1, &layer2, blocked);
    } else {
        print_report(&command_str, &layer1, &layer2, blocked);
    }

    Ok(exit_code)
}

// ---------------------------------------------------------------------------
// Layer evaluation results
// ---------------------------------------------------------------------------

struct Layer1Result {
    blocked: bool,
    matched_rule: Option<String>,
    action: String,
    context_override: Option<String>,
    detail: String,
}

struct Layer2Result {
    blocked: bool,
    phase: String,
    detail: String,
}

// ---------------------------------------------------------------------------
// Layer 1: shim evaluation (rule matching + context)
// ---------------------------------------------------------------------------

fn evaluate_layer1(
    command_parts: &[String],
    config_path: Option<&std::path::Path>,
) -> Layer1Result {
    let load_result = match load_config(config_path) {
        Ok(r) => r,
        Err(e) => {
            if config_path.is_some() {
                // Explicit --config: surface the error — don't silently use defaults
                return Layer1Result {
                    blocked: false,
                    matched_rule: None,
                    action: "error".to_string(),
                    context_override: None,
                    detail: format!("config load failed: {e} (using defaults)"),
                };
            }
            ConfigLoadResult {
                config: config::Config::default(),
                warnings: vec![],
            }
        }
    };

    if command_parts.is_empty() {
        return Layer1Result {
            blocked: false,
            matched_rule: None,
            action: "allow".to_string(),
            context_override: None,
            detail: "no command provided".to_string(),
        };
    }

    let program = &command_parts[0];
    let args: Vec<String> = command_parts[1..].to_vec();
    let invocation = CommandInvocation::new(program.clone(), args);

    let matched = match_rule(&load_result.config.rules, &invocation);

    let Some(rule) = matched else {
        return Layer1Result {
            blocked: false,
            matched_rule: None,
            action: "allow".to_string(),
            context_override: None,
            detail: "no rule matched — command would be passed through".to_string(),
        };
    };

    // Context evaluation
    let context_override = if let Some(ctx_config) = &load_result.config.context {
        let ctx = context::evaluate_context(&invocation, rule, ctx_config);
        ctx.action_override
            .map(|action| format!("{} ({})", action.as_str(), ctx.reason))
    } else {
        None
    };

    let effective_action = if let Some(ref ctx_str) = context_override {
        // Extract action name from "action (reason)" format
        ctx_str.split(' ').next().unwrap_or("block")
    } else {
        rule.action.as_str()
    };

    let blocked = effective_action == "block";
    let detail = rule
        .message
        .clone()
        .unwrap_or_else(|| format!("matched rule: {}", rule.name));

    Layer1Result {
        blocked,
        matched_rule: Some(rule.name.clone()),
        action: effective_action.to_string(),
        context_override,
        detail,
    }
}

// ---------------------------------------------------------------------------
// Layer 2: hook evaluation (Phase 1B detectors + Phase 2 rules + unwrap stack)
// ---------------------------------------------------------------------------

fn evaluate_layer2(command_str: &str) -> Layer2Result {
    match check_command_for_hook(command_str) {
        HookCheckResult::Allow => Layer2Result {
            blocked: false,
            phase: "allow".to_string(),
            detail: "no Phase 1B or rule match".to_string(),
        },
        HookCheckResult::BlockMeta { reason, .. } => Layer2Result {
            blocked: true,
            phase: "meta-pattern".to_string(),
            detail: reason.to_string(),
        },
        HookCheckResult::BlockRule {
            rule_name,
            message,
            unwrap_chain,
            ..
        } => {
            let detail = if let Some(chain) = unwrap_chain {
                format!("{message} ({chain})")
            } else {
                message
            };
            Layer2Result {
                blocked: true,
                phase: format!("rule: {rule_name}"),
                detail,
            }
        }
        HookCheckResult::BlockStructural {
            message,
            wrapper_kind: _,
            ..
        } => Layer2Result {
            // `wrapper_kind` is forensic-side only (audit `detection_layer`),
            // not surfaced via `omamori explain`. v0.9.7 #181 C-1.
            blocked: true,
            phase: "structural".to_string(),
            detail: message,
        },
    }
}

// ---------------------------------------------------------------------------
// Display
// ---------------------------------------------------------------------------

fn print_report(command_str: &str, layer1: &Layer1Result, layer2: &Layer2Result, blocked: bool) {
    let verdict = if blocked { "BLOCK" } else { "ALLOW" };
    println!("omamori explain: {command_str}\n");
    println!("  Verdict: {verdict}\n");

    // Layer 1
    println!("  Layer 1 (PATH shim):");
    if let Some(ref rule) = layer1.matched_rule {
        println!("    rule: {rule}");
        println!("    action: {}", layer1.action);
        if let Some(ref ctx) = layer1.context_override {
            println!("    context override: {ctx}");
        }
        println!("    detail: {}", layer1.detail);
    } else {
        println!("    {}", layer1.detail);
    }

    // Layer 2
    println!();
    println!("  Layer 2 (hooks):");
    if layer2.blocked {
        println!("    phase: {}", layer2.phase);
        println!("    detail: {}", layer2.detail);
    } else {
        println!("    {}", layer2.detail);
    }
    println!("    note: Layer 2 applies rule action directly (no context override)");

    // Guidance
    println!();
    if blocked {
        println!("  Guidance: run this command directly in your terminal (not via AI)");
    } else {
        println!("  Guidance: this command would be allowed through omamori");
    }
}

fn print_json(command_str: &str, layer1: &Layer1Result, layer2: &Layer2Result, blocked: bool) {
    let output = serde_json::json!({
        "command": command_str,
        "verdict": if blocked { "block" } else { "allow" },
        "layer1": {
            "blocked": layer1.blocked,
            "matched_rule": layer1.matched_rule,
            "action": layer1.action,
            "context_override": layer1.context_override,
            "detail": layer1.detail,
        },
        "layer2": {
            "blocked": layer2.blocked,
            "phase": layer2.phase,
            "detail": layer2.detail,
        },
    });
    println!("{}", serde_json::to_string_pretty(&output).unwrap());
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn layer1_no_rule_match_is_allow() {
        let parts = vec!["ls".to_string(), "/tmp".to_string()];
        let result = evaluate_layer1(&parts, None);
        assert!(!result.blocked);
        assert!(result.matched_rule.is_none());
        assert_eq!(result.action, "allow");
    }

    #[test]
    fn layer1_rm_recursive_matches_rule() {
        let parts = vec!["rm".to_string(), "-rf".to_string(), "/tmp/test".to_string()];
        let result = evaluate_layer1(&parts, None);
        assert!(result.matched_rule.is_some());
        // Whether blocked depends on context config — the rule exists
        assert!(result.matched_rule.unwrap().contains("rm"));
    }

    #[test]
    fn layer2_safe_command_is_allow() {
        let result = evaluate_layer2("ls /tmp");
        assert!(!result.blocked);
        assert_eq!(result.phase, "allow");
    }

    #[test]
    fn layer2_phase1b_env_tampering_blocks() {
        let result = evaluate_layer2("unset CLAUDECODE");
        assert!(result.blocked);
        assert_eq!(result.phase, "meta-pattern");
    }

    #[test]
    fn layer2_phase2_rule_blocks_explain() {
        let result = evaluate_layer2("omamori explain -- rm -rf /");
        assert!(result.blocked);
    }

    #[test]
    fn layer2_phase2_rule_blocks_doctor_fix() {
        let result = evaluate_layer2("omamori doctor --fix");
        assert!(result.blocked);
    }

    #[test]
    fn verdict_blocked_if_either_layer_blocks() {
        // Layer 1 allow + Layer 2 block = blocked
        let l1 = Layer1Result {
            blocked: false,
            matched_rule: None,
            action: "allow".to_string(),
            context_override: None,
            detail: "no match".to_string(),
        };
        let l2 = Layer2Result {
            blocked: true,
            phase: "meta-pattern".to_string(),
            detail: "blocked".to_string(),
        };
        assert!(l1.blocked || l2.blocked);

        // Layer 1 block + Layer 2 allow = blocked
        let l1b = Layer1Result {
            blocked: true,
            matched_rule: Some("rm-recursive".to_string()),
            action: "block".to_string(),
            context_override: None,
            detail: "blocked".to_string(),
        };
        let l2b = Layer2Result {
            blocked: false,
            phase: "allow".to_string(),
            detail: "ok".to_string(),
        };
        assert!(l1b.blocked || l2b.blocked);
    }

    #[test]
    fn json_output_is_valid() {
        let l1 = Layer1Result {
            blocked: false,
            matched_rule: None,
            action: "allow".to_string(),
            context_override: None,
            detail: "no match".to_string(),
        };
        let l2 = Layer2Result {
            blocked: false,
            phase: "allow".to_string(),
            detail: "ok".to_string(),
        };
        // Just ensure it doesn't panic
        print_json("ls /tmp", &l1, &l2, false);
    }
}