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