Skip to main content

safe_chains/targets/
codex.rs

1use std::path::{Path, PathBuf};
2
3use serde::Deserialize;
4use serde_json::{Map, Value, json};
5
6use super::{HookFormat, HookInput, HookResponse, InstallOutcome, ParseError, Target};
7use crate::verdict::Verdict;
8
9pub struct CodexTarget;
10
11const HOOK_COMMAND: &str = "safe-chains hook codex";
12
13/// The events `--setup` registers, both answered by `safe-chains hook codex`. `PreToolUse` vetoes
14/// gated commands before they run; `PermissionRequest` approves safe reads when Codex would
15/// otherwise prompt (a sandbox escalation, or an `untrusted` approval policy).
16const EVENTS: [&str; 2] = ["PreToolUse", "PermissionRequest"];
17
18impl Target for CodexTarget {
19    fn name(&self) -> &'static str {
20        "codex"
21    }
22
23    fn display_name(&self) -> &'static str {
24        "Codex (OpenAI)"
25    }
26
27    #[cfg(test)]
28    fn sample_envelope(&self, tool: &str, command: &str) -> Option<String> {
29        Some(format!(r#"{{"tool_name":"{tool}","tool_input":{{"command":"{command}"}}}}"#))
30    }
31
32    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
33        vec![home.join(".codex")]
34    }
35
36    /// Adds whichever of `EVENTS` is missing, so a user who installed the `PreToolUse` hook
37    /// before `PermissionRequest` support gets the second entry from a re-run of `--setup`.
38    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
39        let dir = home.join(".codex");
40        if !dir.exists() {
41            return Ok(InstallOutcome::Skipped { reason: format!("~/.codex not found at {} (Codex CLI not installed)", dir.display()) });
42        }
43
44        let path = dir.join("hooks.json");
45        let mut settings = if path.exists() {
46            let contents = std::fs::read_to_string(&path).map_err(|e| format!("Could not read {}: {e}", path.display()))?;
47            serde_json::from_str(&contents).map_err(|e| format!("Could not parse {}: {e}", path.display()))?
48        } else {
49            Value::Object(Map::new())
50        };
51
52        let missing: Vec<&str> = EVENTS.into_iter().filter(|event| !has_safe_chains_hook(&settings, event)).collect();
53        if missing.is_empty() {
54            return Ok(InstallOutcome::AlreadyConfigured { path });
55        }
56        for event in missing {
57            add_hook(&mut settings, event, HOOK_COMMAND).map_err(|e| format!("{}: {e}", path.display()))?;
58        }
59        let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
60        std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
61        Ok(InstallOutcome::Installed { path })
62    }
63
64    fn hook_format(&self) -> Option<&dyn HookFormat> {
65        Some(&CodexHookFormat)
66    }
67
68    /// Codex names the event in `hook_event_name`, which it sets itself (the agent cannot reach
69    /// it). Anything that is not a `PermissionRequest`, an envelope without the field included,
70    /// keeps the `PreToolUse` answer this target has always given.
71    fn hook_format_for(&self, stdin: &str) -> Option<&dyn HookFormat> {
72        if event_name(stdin).as_deref() == Some("PermissionRequest") { Some(&CodexPermissionRequestFormat) } else { Some(&CodexHookFormat) }
73    }
74
75    fn hook_formats(&self) -> Vec<&dyn HookFormat> {
76        vec![&CodexHookFormat, &CodexPermissionRequestFormat]
77    }
78}
79
80#[derive(Deserialize)]
81struct EventProbe {
82    #[serde(default)]
83    hook_event_name: Option<String>,
84}
85
86fn event_name(stdin: &str) -> Option<String> {
87    serde_json::from_str::<EventProbe>(stdin).ok().and_then(|probe| probe.hook_event_name)
88}
89
90struct CodexHookFormat;
91
92#[derive(Deserialize)]
93struct ToolInput {
94    command: String,
95}
96
97#[derive(Deserialize)]
98struct CodexHookEnvelope {
99    /// Optional so a harness that omits it still works; when present and naming another tool we
100    /// abstain (see parse_input).
101    #[serde(default)]
102    tool_name: Option<String>,
103    tool_input: ToolInput,
104    #[serde(default)]
105    cwd: Option<String>,
106}
107
108impl HookFormat for CodexHookFormat {
109    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
110        let envelope: CodexHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
111        // Self-filter on the tool: the hook can be delivered for a non-shell call by a
112        // hand-edited matcher, and deciding on one grants or vetoes a tool never analysed.
113        if let Some(name) = &envelope.tool_name
114            && name != "Bash"
115        {
116            return Err(ParseError { message: format!("not a shell tool: {name}") });
117        }
118        Ok(HookInput {
119            command: envelope.tool_input.command,
120            cwd: envelope.cwd,
121            root: None, // codex sends cwd but no distinct project root (HARNESS-BEHAVIORS.md)
122            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
123            session_id: None,
124            permission_mode: None,
125        })
126    }
127
128    fn decision_pointer(&self) -> &'static str {
129        "/hookSpecificOutput/permissionDecision" // mirrors Claude's nesting
130    }
131
132    fn render_response(&self, _verdict: Verdict) -> HookResponse {
133        // SAFE command → emit nothing. A PreToolUse `permissionDecision:"allow"` is still rejected
134        // as unsupported (v0.144.3 through v0.160.1), and Codex "continues on unsupported output"
135        // anyway. Silence lets the safe command run through Codex's own flow; where that flow
136        // would prompt, the PermissionRequest format below approves it.
137        HookResponse { stdout: String::new(), exit_code: 0 }
138    }
139
140    // Codex has no human-review-on-silence (only sandbox-escape prompts) and no `ask`, but its
141    // sandbox permits BROAD READS (`cat /etc/shadow` runs), so a gated command must be denied by
142    // the hook. See docs/design/harness-capability-model.md. Verified against v0.144.3, 2026-07-13.
143    fn gated_policy(&self) -> super::GatedPolicy {
144        super::GatedPolicy::Deny
145    }
146
147    fn render_deny(&self, reason: &str) -> HookResponse {
148        let body = json!({
149            "hookSpecificOutput": {
150                "hookEventName": "PreToolUse",
151                "permissionDecision": "deny",
152                "permissionDecisionReason": reason,
153            }
154        });
155        HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
156    }
157}
158
159/// Codex's `PermissionRequest` event (v0.122.0 and later): it fires only when Codex is about to
160/// ask for approval, and an `allow` answers that prompt. Anything short of a safe read emits
161/// nothing, which leaves Codex's normal approval in place, so `gated_policy` keeps the `Defer`
162/// default. Only `allow` is ever emitted: `updatedInput`, `updatedPermissions` and
163/// `interrupt:true` make Codex fail the hook.
164struct CodexPermissionRequestFormat;
165
166/// A host-level network approval arrives as the command with a `network-access <host>`
167/// description, and is classified like any other request: the classifier judges network commands
168/// for Codex as it does for Claude Code.
169#[derive(Deserialize)]
170struct PermissionRequestToolInput {
171    command: String,
172}
173
174#[derive(Deserialize)]
175struct PermissionRequestEnvelope {
176    hook_event_name: String,
177    tool_name: String,
178    tool_input: PermissionRequestToolInput,
179    cwd: String,
180}
181
182impl HookFormat for CodexPermissionRequestFormat {
183    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
184        let envelope: PermissionRequestEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
185        if envelope.hook_event_name != "PermissionRequest" {
186            return Err(ParseError { message: format!("not a PermissionRequest: {}", envelope.hook_event_name) });
187        }
188        // Required here, not optional: this event also carries `apply_patch`, whose
189        // `tool_input.command` is a patch, and MCP calls, `write_stdin` and `request_permissions`.
190        if envelope.tool_name != "Bash" {
191            return Err(ParseError { message: format!("not a shell tool: {}", envelope.tool_name) });
192        }
193        // The cwd is the workspace root here (see `cwd_is_the_commands`), so a root that is the
194        // whole filesystem, or one that is not a path at all, would put every write inside it.
195        if !bounds_a_workspace(&envelope.cwd) {
196            return Err(ParseError { message: format!("no usable workspace in cwd: {}", envelope.cwd) });
197        }
198        Ok(HookInput { command: envelope.tool_input.command, cwd: Some(envelope.cwd), root: None, session_id: None, permission_mode: None })
199    }
200
201    /// Codex reports the turn's cwd, but `exec_command` runs in its own `workdir`, which this
202    /// payload leaves out. An approval here runs outside the sandbox, so a relative path must not be
203    /// trusted to land where the reported cwd says: the model could set `workdir` to `~` and have
204    /// `echo x >> .zshrc` approved as a worktree write.
205    fn cwd_is_the_commands(&self) -> bool {
206        false
207    }
208
209    fn decision_pointer(&self) -> &'static str {
210        "/hookSpecificOutput/decision/behavior"
211    }
212
213    fn render_response(&self, verdict: Verdict) -> HookResponse {
214        if !verdict.is_allowed() {
215            return HookResponse { stdout: String::new(), exit_code: 0 };
216        }
217        let body = json!({
218            "hookSpecificOutput": {
219                "hookEventName": "PermissionRequest",
220                "decision": { "behavior": "allow" },
221            }
222        });
223        HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
224    }
225}
226
227/// An absolute path that still names a directory below `/` once `.` and `..` are folded away, so
228/// `/.`, `/Users/..` and `//` are refused like `/` itself.
229fn bounds_a_workspace(cwd: &str) -> bool {
230    if !cwd.starts_with('/') {
231        return false;
232    }
233    let mut depth = 0usize;
234    for part in cwd.split('/') {
235        match part {
236            "" | "." => {}
237            ".." => depth = depth.saturating_sub(1),
238            _ => depth += 1,
239        }
240    }
241    depth > 0
242}
243
244fn hook_entry(binary: &str) -> Value {
245    json!({
246        "matcher": "Bash",
247        "hooks": [{
248            "type": "command",
249            "command": binary,
250        }]
251    })
252}
253
254/// An entry counts only when it runs `safe-chains hook codex` on shell calls: one under an
255/// `apply_patch` matcher, or running another target's hook, leaves `Bash` uncovered on that event.
256fn has_safe_chains_hook(settings: &Value, event: &str) -> bool {
257    settings
258        .get("hooks")
259        .and_then(|h| h.get(event))
260        .and_then(|arr| arr.as_array())
261        .is_some_and(|entries| {
262            entries.iter().any(|entry| {
263                matcher_covers_bash(entry.get("matcher"))
264                    && entry.get("hooks").and_then(|h| h.as_array()).is_some_and(|hooks| {
265                        hooks
266                            .iter()
267                            .any(|hook| hook.get("command").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains(HOOK_COMMAND)))
268                    })
269            })
270        })
271}
272
273fn matcher_covers_bash(matcher: Option<&Value>) -> bool {
274    match matcher {
275        None | Some(Value::Null) => true,
276        Some(Value::String(m)) => m.is_empty() || m == "*" || m.contains("Bash"),
277        Some(_) => false,
278    }
279}
280
281/// Codex nests lifecycle events under a top-level `hooks` object (NOT Claude's flat `PreToolUse`
282/// key) — a flat key makes Codex reject the whole file. See developers.openai.com/codex/hooks.
283///
284/// This used to REPLACE a wrong-typed `hooks` or `PreToolUse` value with an empty one, destroying
285/// whatever the user had there without saying so. The shared helper refuses instead: an unreadable
286/// value is usually a hand-edit or a schema we don't know, and rewriting config we did not
287/// understand is not ours to do.
288fn add_hook(settings: &mut Value, event: &str, binary: &str) -> Result<(), String> {
289    super::append_hook_entry(settings, "hooks", event, hook_entry(binary))
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295    use crate::verdict::SafetyLevel;
296
297    fn target() -> CodexTarget {
298        CodexTarget
299    }
300
301    fn installed(home: &Path) -> Value {
302        let contents = std::fs::read_to_string(home.join(".codex/hooks.json")).unwrap();
303        serde_json::from_str(&contents).unwrap()
304    }
305
306    fn permission_request(tool: &str, command: &str) -> String {
307        json!({
308            "session_id": "s",
309            "turn_id": "t",
310            "transcript_path": null,
311            "cwd": "/w",
312            "hook_event_name": "PermissionRequest",
313            "model": "m",
314            "permission_mode": "default",
315            "tool_name": tool,
316            "tool_input": { "command": command, "description": "needs to write outside the sandbox" },
317        })
318        .to_string()
319    }
320
321    #[test]
322    fn install_no_codex_dir_skips() {
323        let dir = tempfile::tempdir().unwrap();
324        let outcome = target().install(dir.path()).unwrap();
325        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
326    }
327
328    #[test]
329    fn install_creates_hooks_file() {
330        let dir = tempfile::tempdir().unwrap();
331        std::fs::create_dir(dir.path().join(".codex")).unwrap();
332        let outcome = target().install(dir.path()).unwrap();
333        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
334        let settings = installed(dir.path());
335        for event in EVENTS {
336            assert!(has_safe_chains_hook(&settings, event), "{event} not installed");
337        }
338        // Codex nests events under a top-level `hooks` object; a flat top-level `PreToolUse`
339        // (Claude's shape) makes Codex reject the entire file (`unknown field PreToolUse`).
340        assert!(settings.get("PreToolUse").is_none(), "must not use Claude's flat PreToolUse key");
341        assert!(settings.get("PermissionRequest").is_none(), "must not use a flat PermissionRequest key");
342        assert_eq!(settings.as_object().map(|o| o.len()), Some(1), "only the `hooks` key: {settings}");
343    }
344
345    #[test]
346    fn install_idempotent() {
347        let dir = tempfile::tempdir().unwrap();
348        std::fs::create_dir(dir.path().join(".codex")).unwrap();
349        target().install(dir.path()).unwrap();
350        let first = installed(dir.path());
351        let outcome = target().install(dir.path()).unwrap();
352        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
353        assert_eq!(installed(dir.path()), first, "a second run must not add duplicate entries");
354    }
355
356    #[test]
357    fn install_adds_permission_request_beside_an_older_pre_tool_use_install() {
358        let dir = tempfile::tempdir().unwrap();
359        let codex_dir = dir.path().join(".codex");
360        std::fs::create_dir(&codex_dir).unwrap();
361        let older = json!({"hooks": {"PreToolUse": [hook_entry(HOOK_COMMAND)]}});
362        std::fs::write(codex_dir.join("hooks.json"), older.to_string()).unwrap();
363
364        let outcome = target().install(dir.path()).unwrap();
365        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
366        let settings = installed(dir.path());
367        assert!(has_safe_chains_hook(&settings, "PermissionRequest"));
368        assert_eq!(settings["hooks"]["PreToolUse"], older["hooks"]["PreToolUse"], "the existing entry must be left exactly as it was");
369    }
370
371    #[test]
372    fn install_uses_subcommand_invocation() {
373        // The binary entry must be `safe-chains hook codex`, not just
374        // `safe-chains`, so the runtime knows which envelope to emit.
375        let dir = tempfile::tempdir().unwrap();
376        std::fs::create_dir(dir.path().join(".codex")).unwrap();
377        target().install(dir.path()).unwrap();
378        let settings = installed(dir.path());
379        for event in EVENTS {
380            assert_eq!(settings["hooks"][event][0]["hooks"][0]["command"], HOOK_COMMAND);
381            assert_eq!(settings["hooks"][event][0]["matcher"], "Bash");
382        }
383    }
384
385    #[test]
386    fn install_preserves_existing_hooks() {
387        let dir = tempfile::tempdir().unwrap();
388        let codex_dir = dir.path().join(".codex");
389        std::fs::create_dir(&codex_dir).unwrap();
390        std::fs::write(
391            codex_dir.join("hooks.json"),
392            r#"{"hooks": {"PostToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "log-it"}]}], "PermissionRequest": [{"matcher": "apply_patch", "hooks": [{"type": "command", "command": "mine"}]}]}}"#,
393        )
394        .unwrap();
395        target().install(dir.path()).unwrap();
396        let settings = installed(dir.path());
397        assert!(has_safe_chains_hook(&settings, "PreToolUse"));
398        assert!(has_safe_chains_hook(&settings, "PermissionRequest"));
399        assert!(settings["hooks"].get("PostToolUse").is_some(), "existing PostToolUse must be preserved");
400        assert_eq!(settings["hooks"]["PermissionRequest"][0]["hooks"][0]["command"], "mine", "the user's own entry comes first, untouched");
401    }
402
403    #[test]
404    fn parse_input_extracts_command() {
405        let stdin = r#"{"tool_name": "Bash", "tool_input": {"command": "ls -la"}}"#;
406        let parsed = CodexHookFormat.parse_input(stdin).unwrap();
407        assert_eq!(parsed.command, "ls -la");
408    }
409
410    #[test]
411    fn parse_input_with_optional_cwd() {
412        let stdin = r#"{"tool_input": {"command": "pwd"}, "cwd": "/Users/me"}"#;
413        let parsed = CodexHookFormat.parse_input(stdin).unwrap();
414        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me"));
415    }
416
417    #[test]
418    fn parse_input_rejects_garbage() {
419        assert!(CodexHookFormat.parse_input("not json").is_err());
420        assert!(CodexHookFormat.parse_input("{}").is_err());
421    }
422
423    #[test]
424    fn render_response_safe_emits_empty_body() {
425        // A PreToolUse `permissionDecision:"allow"` is unsupported on Codex. A safe command emits
426        // nothing (Codex continues → runs it); it must NOT emit an allow envelope.
427        let r = CodexHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
428        assert_eq!(r.stdout, "");
429        let r = CodexHookFormat.render_response(Verdict::Denied);
430        assert_eq!(r.stdout, "");
431    }
432
433    #[test]
434    fn gated_command_is_denied_with_the_supported_shape() {
435        // Codex handles a gated command by DENYING (no interactive approval, sandbox permits reads).
436        assert_eq!(CodexHookFormat.gated_policy(), super::super::GatedPolicy::Deny);
437        let r = CodexHookFormat.render_deny("blocked: not on the allowlist");
438        let v: Value = serde_json::from_str(&r.stdout).unwrap();
439        assert_eq!(v.pointer("/hookSpecificOutput/permissionDecision").and_then(|d| d.as_str()), Some("deny"));
440        assert_eq!(v.pointer("/hookSpecificOutput/hookEventName").and_then(|d| d.as_str()), Some("PreToolUse"));
441        assert_eq!(
442            v.pointer("/hookSpecificOutput/permissionDecisionReason").and_then(|d| d.as_str()),
443            Some("blocked: not on the allowlist"),
444        );
445        assert_eq!(r.exit_code, 0);
446    }
447
448    #[test]
449    fn render_context_defaults_to_abstain() {
450        // Codex's hook schema isn't verified for context injection, so it keeps
451        // the safe default: emit nothing, leaving the normal flow untouched.
452        let r = CodexHookFormat.render_context("anything");
453        assert_eq!(r.stdout, "");
454        assert_eq!(r.exit_code, 0);
455    }
456
457    #[test]
458    fn routes_only_a_permission_request_to_the_permission_format() {
459        let t = target();
460        let pointer = |stdin: &str| t.hook_format_for(stdin).map(|f| f.decision_pointer());
461        let permission = CodexPermissionRequestFormat.decision_pointer();
462        let pre_tool_use = CodexHookFormat.decision_pointer();
463        assert_eq!(pointer(&permission_request("Bash", "ls")), Some(permission));
464        for other in [
465            r#"{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"ls"}}"#,
466            r#"{"tool_name":"Bash","tool_input":{"command":"ls"}}"#,
467            r#"{"hook_event_name":"permissionrequest","tool_name":"Bash","tool_input":{"command":"ls"}}"#,
468            r#"{"hook_event_name":7,"tool_name":"Bash","tool_input":{"command":"ls"}}"#,
469            "not json",
470            "",
471        ] {
472            assert_eq!(pointer(other), Some(pre_tool_use), "{other} must keep the PreToolUse answer");
473        }
474    }
475
476    #[test]
477    fn permission_request_passes_shell_syntax_and_network_approvals_to_the_classifier() {
478        for command in [
479            "echo $(cat x)", "echo `cat x`", "diff <(ls) b", "curl https://x/$HOME", "read l < f", "cat f | xargs curl",
480            "git status && ls", "ls; ls", "ls\nls", "cat *", "cat ~/x", "ls {a,b}", "git status", "bash -c 'ls -la'",
481        ] {
482            let parsed = CodexPermissionRequestFormat.parse_input(&permission_request("Bash", command)).unwrap();
483            assert_eq!(parsed.command, command);
484        }
485        let mut network: Value = serde_json::from_str(&permission_request("Bash", "curl https://example.com")).unwrap();
486        for description in [json!("network-access example.com"), json!(null), json!(7)] {
487            network["tool_input"]["description"] = description.clone();
488            let parsed = CodexPermissionRequestFormat.parse_input(&network.to_string());
489            assert_eq!(parsed.map(|p| p.command).ok().as_deref(), Some("curl https://example.com"), "{description}");
490        }
491    }
492
493    #[test]
494    fn permission_request_parses_a_bash_envelope() {
495        let parsed = CodexPermissionRequestFormat.parse_input(&permission_request("Bash", "git status")).unwrap();
496        assert_eq!(parsed.command, "git status");
497        assert_eq!(parsed.cwd.as_deref(), Some("/w"));
498    }
499
500    #[test]
501    fn permission_request_abstains_on_every_other_tool() {
502        for tool in ["apply_patch", "write_stdin", "request_permissions", "mcp__server__tool", "Edit", "bash"] {
503            assert!(
504                CodexPermissionRequestFormat.parse_input(&permission_request(tool, "ls")).is_err(),
505                "{tool} must not be classified as a shell command"
506            );
507        }
508        let no_tool = r#"{"hook_event_name":"PermissionRequest","tool_input":{"command":"ls"},"cwd":"/w"}"#;
509        assert!(CodexPermissionRequestFormat.parse_input(no_tool).is_err(), "tool_name is required on this event");
510        let pre_tool_use = r#"{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"ls"},"cwd":"/w"}"#;
511        assert!(CodexPermissionRequestFormat.parse_input(pre_tool_use).is_err());
512        let argv = r#"{"hook_event_name":"PermissionRequest","tool_name":"Bash","tool_input":{"command":["ls"]},"cwd":"/w"}"#;
513        assert!(CodexPermissionRequestFormat.parse_input(argv).is_err(), "only a command string is classified");
514    }
515
516    #[test]
517    fn permission_request_allows_exactly_the_documented_shape() {
518        for level in [SafetyLevel::Inert, SafetyLevel::SafeRead, SafetyLevel::SafeWrite] {
519            let r = CodexPermissionRequestFormat.render_response(Verdict::Allowed(level));
520            assert_eq!(r.exit_code, 0);
521            let v: Value = serde_json::from_str(&r.stdout).unwrap();
522            assert_eq!(v, json!({"hookSpecificOutput": {"hookEventName": "PermissionRequest", "decision": {"behavior": "allow"}}}));
523        }
524    }
525
526    #[test]
527    fn permission_request_emits_nothing_short_of_a_safe_verdict() {
528        assert_eq!(CodexPermissionRequestFormat.gated_policy(), super::super::GatedPolicy::Defer);
529        for r in [
530            CodexPermissionRequestFormat.render_response(Verdict::Denied),
531            CodexPermissionRequestFormat.render_deny("x"),
532            CodexPermissionRequestFormat.render_ask("x"),
533            CodexPermissionRequestFormat.render_context("x"),
534        ] {
535            assert_eq!(r.stdout, "");
536            assert_eq!(r.exit_code, 0);
537        }
538    }
539
540    #[test]
541    fn permission_request_needs_a_cwd_that_bounds_a_workspace() {
542        let with_cwd = |cwd: Value| {
543            json!({"hook_event_name":"PermissionRequest","tool_name":"Bash","tool_input":{"command":"ls"},"cwd":cwd}).to_string()
544        };
545        for unusable in [json!("/"), json!("//"), json!(""), json!("relative/dir"), json!(null), json!(7)] {
546            assert!(CodexPermissionRequestFormat.parse_input(&with_cwd(unusable.clone())).is_err(), "cwd {unusable} must abstain");
547        }
548        let missing = r#"{"hook_event_name":"PermissionRequest","tool_name":"Bash","tool_input":{"command":"ls"}}"#;
549        assert!(CodexPermissionRequestFormat.parse_input(missing).is_err());
550        assert!(CodexPermissionRequestFormat.parse_input(&with_cwd(json!("/w"))).is_ok());
551    }
552
553    #[test]
554    fn only_the_permission_request_cwd_is_not_the_commands() {
555        assert!(CodexHookFormat.cwd_is_the_commands());
556        assert!(!CodexPermissionRequestFormat.cwd_is_the_commands());
557        let input = CodexPermissionRequestFormat.parse_input(&permission_request("Bash", "ls")).unwrap();
558        let (cwd, root) = super::super::evaluation_dirs(&CodexPermissionRequestFormat, &input);
559        assert_eq!(cwd.as_deref(), Some(super::super::UNKNOWN_WORKDIR));
560        assert_eq!(root.as_deref(), Some("/w"), "the reported cwd stays the workspace");
561    }
562
563    #[test]
564    fn install_ignores_an_entry_that_does_not_run_this_hook_on_shell_calls() {
565        let dir = tempfile::tempdir().unwrap();
566        let codex_dir = dir.path().join(".codex");
567        std::fs::create_dir(&codex_dir).unwrap();
568        let elsewhere = json!({"hooks": {
569            "PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "safe-chains hook claude"}]}],
570            "PermissionRequest": [{"matcher": "apply_patch", "hooks": [{"type": "command", "command": HOOK_COMMAND}]}],
571        }});
572        std::fs::write(codex_dir.join("hooks.json"), elsewhere.to_string()).unwrap();
573
574        assert!(matches!(target().install(dir.path()).unwrap(), InstallOutcome::Installed { .. }));
575        let settings = installed(dir.path());
576        for event in EVENTS {
577            let entries = settings["hooks"][event].as_array().unwrap();
578            assert_eq!(entries.len(), 2, "{event}: ours is added beside the other entry");
579            assert_eq!(entries[1], hook_entry(HOOK_COMMAND));
580        }
581    }
582
583    #[test]
584    fn matcher_coverage_of_shell_calls() {
585        for covers in [None, Some(json!(null)), Some(json!("")), Some(json!("*")), Some(json!("Bash")), Some(json!("Bash|apply_patch"))] {
586            assert!(matcher_covers_bash(covers.as_ref()), "{covers:?}");
587        }
588        for misses in [json!("apply_patch"), json!("mcp__x__y"), json!(["Bash"]), json!(1)] {
589            assert!(!matcher_covers_bash(Some(&misses)), "{misses}");
590        }
591    }
592
593    #[test]
594    fn install_refuses_a_wrong_typed_permission_request_slot_and_writes_nothing() {
595        let dir = tempfile::tempdir().unwrap();
596        let codex_dir = dir.path().join(".codex");
597        std::fs::create_dir(&codex_dir).unwrap();
598        let path = codex_dir.join("hooks.json");
599        std::fs::write(&path, r#"{"hooks": {"PermissionRequest": "corrupted"}}"#).unwrap();
600        let before = std::fs::read(&path).unwrap();
601
602        let Err(err) = target().install(dir.path()) else { panic!("a wrong-typed slot must be refused") };
603        assert!(err.contains("hooks.PermissionRequest"), "the error names the slot: {err}");
604        assert_eq!(std::fs::read(&path).unwrap(), before, "PreToolUse must not be written alone either");
605    }
606
607    #[test]
608    fn only_a_read_is_granted_where_the_workdir_is_unknown() {
609        use super::super::respond;
610        let grants = |format: &dyn HookFormat, level| respond(format, "x", Verdict::Allowed(level)).is_some_and(|r| !r.stdout.is_empty());
611        assert!(grants(&CodexPermissionRequestFormat, SafetyLevel::Inert));
612        assert!(grants(&CodexPermissionRequestFormat, SafetyLevel::SafeRead));
613        assert!(!grants(&CodexPermissionRequestFormat, SafetyLevel::SafeWrite), "a write could land anywhere");
614        assert!(
615            respond(&CodexHookFormat, "x", Verdict::Allowed(SafetyLevel::SafeWrite)).is_some(),
616            "where the cwd is the command's, the ceiling does not apply"
617        );
618    }
619
620    #[test]
621    fn a_cwd_that_folds_to_the_filesystem_root_bounds_nothing() {
622        for root in ["/", "//", "/.", "/./", "/Users/..", "/tmp/..", "/a/b/../..", "/../.."] {
623            assert!(!bounds_a_workspace(root), "{root}");
624        }
625        for dir in ["/w", "/Users/me/proj", "/a/b/..", "/./w", "/../w"] {
626            assert!(bounds_a_workspace(dir), "{dir}");
627        }
628    }
629
630    proptest::proptest! {
631        /// Folding `.` and `..` is the whole rule: a directory stays a workspace however many `.`
632        /// segments it carries, and climbing back out of every segment it named reaches `/`.
633        #[test]
634        fn bounds_a_workspace_follows_the_folded_depth(
635            names in proptest::collection::vec("[a-zA-Z0-9_-]{1,8}", 1..6),
636            dots in 0usize..4,
637        ) {
638            let dir = format!("/{}", names.join("/"));
639            proptest::prop_assert!(bounds_a_workspace(&dir));
640            let dotted = dir.clone() + &"/.".repeat(dots);
641            let climbed = dir.clone() + &"/..".repeat(names.len() + dots);
642            let relative = names.join("/");
643            proptest::prop_assert!(bounds_a_workspace(&dotted), "{}", dotted);
644            proptest::prop_assert!(!bounds_a_workspace(&climbed), "{}", climbed);
645            proptest::prop_assert!(!bounds_a_workspace(&relative), "a relative path is never a workspace: {}", relative);
646        }
647
648        /// Whatever the command says and whatever the model wrote as its justification, a Bash
649        /// request with a usable cwd reaches the classifier unchanged: the event adds no rule of its
650        /// own about the command's text, only the read ceiling on the verdict.
651        #[test]
652        fn every_bash_request_reaches_the_classifier_verbatim(command in "\\PC*", description in proptest::option::of("\\PC*")) {
653            let mut payload: Value = serde_json::from_str(&permission_request("Bash", &command)).unwrap();
654            payload["tool_input"]["description"] = description.map_or(Value::Null, Value::String);
655            let parsed = CodexPermissionRequestFormat.parse_input(&payload.to_string());
656            proptest::prop_assert_eq!(parsed.map(|p| p.command).ok(), Some(command));
657        }
658    }
659}