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
11impl Target for CodexTarget {
12    fn name(&self) -> &'static str {
13        "codex"
14    }
15
16    fn display_name(&self) -> &'static str {
17        "Codex (OpenAI)"
18    }
19
20    #[cfg(test)]
21    fn sample_envelope(&self, tool: &str, command: &str) -> Option<String> {
22        Some(format!(r#"{{"tool_name":"{tool}","tool_input":{{"command":"{command}"}}}}"#))
23    }
24
25    fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
26        vec![home.join(".codex")]
27    }
28
29    fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
30        let dir = home.join(".codex");
31        if !dir.exists() {
32            return Ok(InstallOutcome::Skipped { reason: format!("~/.codex not found at {} (Codex CLI not installed)", dir.display()) });
33        }
34
35        let path = dir.join("hooks.json");
36        let binary = "safe-chains hook codex";
37
38        if path.exists() {
39            let contents = std::fs::read_to_string(&path).map_err(|e| format!("Could not read {}: {e}", path.display()))?;
40            let mut settings: Value = serde_json::from_str(&contents).map_err(|e| format!("Could not parse {}: {e}", path.display()))?;
41
42            if has_safe_chains_hook(&settings) {
43                return Ok(InstallOutcome::AlreadyConfigured { path });
44            }
45
46            add_hook(&mut settings, binary).map_err(|e| format!("{}: {e}", path.display()))?;
47            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
48            std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
49            Ok(InstallOutcome::Installed { path })
50        } else {
51            let mut settings = Value::Object(Map::new());
52            add_hook(&mut settings, binary).map_err(|e| format!("{}: {e}", path.display()))?;
53            let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
54            std::fs::write(&path, format!("{output}\n")).map_err(|e| format!("Could not write {}: {e}", path.display()))?;
55            Ok(InstallOutcome::Installed { path })
56        }
57    }
58
59    fn hook_format(&self) -> Option<&dyn HookFormat> {
60        Some(&CodexHookFormat)
61    }
62}
63
64struct CodexHookFormat;
65
66#[derive(Deserialize)]
67struct ToolInput {
68    command: String,
69}
70
71#[derive(Deserialize)]
72struct CodexHookEnvelope {
73    /// Optional so a harness that omits it still works; when present and naming another tool we
74    /// abstain (see parse_input).
75    #[serde(default)]
76    tool_name: Option<String>,
77    tool_input: ToolInput,
78    #[serde(default)]
79    cwd: Option<String>,
80}
81
82impl HookFormat for CodexHookFormat {
83    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
84        let envelope: CodexHookEnvelope = serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
85        // Self-filter on the tool: the hook can be delivered for a non-shell call by a
86        // hand-edited matcher, and deciding on one grants or vetoes a tool never analysed.
87        if let Some(name) = &envelope.tool_name
88            && name != "Bash"
89        {
90            return Err(ParseError { message: format!("not a shell tool: {name}") });
91        }
92        Ok(HookInput {
93            command: envelope.tool_input.command,
94            cwd: envelope.cwd,
95            root: None, // codex sends cwd but no distinct project root (HARNESS-BEHAVIORS.md)
96            // No scratchpad layout researched for this harness yet (see docs/design/agent-scratchpad.md).
97            session_id: None,
98        })
99    }
100
101    fn decision_pointer(&self) -> &'static str {
102        "/hookSpecificOutput/permissionDecision" // mirrors Claude's nesting
103    }
104
105    fn render_response(&self, _verdict: Verdict) -> HookResponse {
106        // SAFE command → emit nothing. Codex has no `grant`: `permissionDecision:"allow"` is
107        // rejected as unsupported on v0.144.3 (docs list it, but it errored — version drift), and
108        // Codex "continues on unsupported output" anyway. Silence lets the safe command run through
109        // Codex's own flow, version-robustly. (Gated commands go through `render_deny`, not here.)
110        HookResponse { stdout: String::new(), exit_code: 0 }
111    }
112
113    // Codex has no human-review-on-silence (only sandbox-escape prompts) and no `ask`, but its
114    // sandbox permits BROAD READS (`cat /etc/shadow` runs), so a gated command must be denied by
115    // the hook. See docs/design/harness-capability-model.md. Verified against v0.144.3, 2026-07-13.
116    fn gated_policy(&self) -> super::GatedPolicy {
117        super::GatedPolicy::Deny
118    }
119
120    fn render_deny(&self, reason: &str) -> HookResponse {
121        let body = json!({
122            "hookSpecificOutput": {
123                "hookEventName": "PreToolUse",
124                "permissionDecision": "deny",
125                "permissionDecisionReason": reason,
126            }
127        });
128        HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
129    }
130}
131
132fn hook_entry(binary: &str) -> Value {
133    json!({
134        "matcher": "Bash",
135        "hooks": [{
136            "type": "command",
137            "command": binary,
138        }]
139    })
140}
141
142fn has_safe_chains_hook(settings: &Value) -> bool {
143    settings
144        .get("hooks")
145        .and_then(|h| h.get("PreToolUse"))
146        .and_then(|arr| arr.as_array())
147        .is_some_and(|entries| {
148            entries.iter().any(|entry| {
149                entry.get("hooks").and_then(|h| h.as_array()).is_some_and(|hooks| {
150                    hooks
151                        .iter()
152                        .any(|hook| hook.get("command").and_then(|c| c.as_str()).is_some_and(|cmd| cmd.contains("safe-chains")))
153                })
154            })
155        })
156}
157
158/// Codex nests lifecycle events under a top-level `hooks` object (NOT Claude's flat `PreToolUse`
159/// key) — a flat key makes Codex reject the whole file. See developers.openai.com/codex/hooks.
160///
161/// This used to REPLACE a wrong-typed `hooks` or `PreToolUse` value with an empty one, destroying
162/// whatever the user had there without saying so. The shared helper refuses instead: an unreadable
163/// value is usually a hand-edit or a schema we don't know, and rewriting config we did not
164/// understand is not ours to do.
165fn add_hook(settings: &mut Value, binary: &str) -> Result<(), String> {
166    super::append_hook_entry(settings, "hooks", "PreToolUse", hook_entry(binary))
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172    use crate::verdict::SafetyLevel;
173
174    fn target() -> CodexTarget {
175        CodexTarget
176    }
177
178    #[test]
179    fn install_no_codex_dir_skips() {
180        let dir = tempfile::tempdir().unwrap();
181        let outcome = target().install(dir.path()).unwrap();
182        assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
183    }
184
185    #[test]
186    fn install_creates_hooks_file() {
187        let dir = tempfile::tempdir().unwrap();
188        std::fs::create_dir(dir.path().join(".codex")).unwrap();
189        let outcome = target().install(dir.path()).unwrap();
190        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
191        let contents = std::fs::read_to_string(dir.path().join(".codex/hooks.json")).unwrap();
192        let settings: Value = serde_json::from_str(&contents).unwrap();
193        assert!(has_safe_chains_hook(&settings));
194        // Codex nests events under a top-level `hooks` object; a flat top-level `PreToolUse`
195        // (Claude's shape) makes Codex reject the entire file (`unknown field PreToolUse`).
196        assert!(settings.get("hooks").and_then(|h| h.get("PreToolUse")).is_some());
197        assert!(settings.get("PreToolUse").is_none(), "must not use Claude's flat PreToolUse key");
198    }
199
200    #[test]
201    fn install_idempotent() {
202        let dir = tempfile::tempdir().unwrap();
203        std::fs::create_dir(dir.path().join(".codex")).unwrap();
204        target().install(dir.path()).unwrap();
205        let outcome = target().install(dir.path()).unwrap();
206        assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
207    }
208
209    #[test]
210    fn install_uses_subcommand_invocation() {
211        // The binary entry must be `safe-chains hook codex`, not just
212        // `safe-chains`, so the runtime knows which envelope to emit.
213        let dir = tempfile::tempdir().unwrap();
214        std::fs::create_dir(dir.path().join(".codex")).unwrap();
215        target().install(dir.path()).unwrap();
216        let contents = std::fs::read_to_string(dir.path().join(".codex/hooks.json")).unwrap();
217        assert!(contents.contains("safe-chains hook codex"));
218    }
219
220    #[test]
221    fn install_preserves_existing_hooks() {
222        let dir = tempfile::tempdir().unwrap();
223        let codex_dir = dir.path().join(".codex");
224        std::fs::create_dir(&codex_dir).unwrap();
225        std::fs::write(
226            codex_dir.join("hooks.json"),
227            r#"{"PostToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "log-it"}]}]}"#,
228        )
229        .unwrap();
230        target().install(dir.path()).unwrap();
231        let contents = std::fs::read_to_string(codex_dir.join("hooks.json")).unwrap();
232        let settings: Value = serde_json::from_str(&contents).unwrap();
233        assert!(has_safe_chains_hook(&settings));
234        assert!(settings.get("PostToolUse").is_some(), "existing PostToolUse must be preserved");
235    }
236
237    #[test]
238    fn parse_input_extracts_command() {
239        let stdin = r#"{"tool_name": "Bash", "tool_input": {"command": "ls -la"}}"#;
240        let parsed = CodexHookFormat.parse_input(stdin).unwrap();
241        assert_eq!(parsed.command, "ls -la");
242    }
243
244    #[test]
245    fn parse_input_with_optional_cwd() {
246        let stdin = r#"{"tool_input": {"command": "pwd"}, "cwd": "/Users/me"}"#;
247        let parsed = CodexHookFormat.parse_input(stdin).unwrap();
248        assert_eq!(parsed.cwd.as_deref(), Some("/Users/me"));
249    }
250
251    #[test]
252    fn parse_input_rejects_garbage() {
253        assert!(CodexHookFormat.parse_input("not json").is_err());
254        assert!(CodexHookFormat.parse_input("{}").is_err());
255    }
256
257    #[test]
258    fn render_response_safe_emits_empty_body() {
259        // Codex has no `grant` — `permissionDecision:"allow"` is unsupported on v0.144.3. A safe
260        // command emits nothing (Codex continues → runs it); it must NOT emit an allow envelope.
261        let r = CodexHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
262        assert_eq!(r.stdout, "");
263        let r = CodexHookFormat.render_response(Verdict::Denied);
264        assert_eq!(r.stdout, "");
265    }
266
267    #[test]
268    fn gated_command_is_denied_with_the_supported_shape() {
269        // Codex handles a gated command by DENYING (no interactive approval, sandbox permits reads).
270        assert_eq!(CodexHookFormat.gated_policy(), super::super::GatedPolicy::Deny);
271        let r = CodexHookFormat.render_deny("blocked: not on the allowlist");
272        let v: Value = serde_json::from_str(&r.stdout).unwrap();
273        assert_eq!(v.pointer("/hookSpecificOutput/permissionDecision").and_then(|d| d.as_str()), Some("deny"));
274        assert_eq!(v.pointer("/hookSpecificOutput/hookEventName").and_then(|d| d.as_str()), Some("PreToolUse"));
275        assert_eq!(
276            v.pointer("/hookSpecificOutput/permissionDecisionReason").and_then(|d| d.as_str()),
277            Some("blocked: not on the allowlist"),
278        );
279        assert_eq!(r.exit_code, 0);
280    }
281
282    #[test]
283    fn render_context_defaults_to_abstain() {
284        // Codex's hook schema isn't verified for context injection, so it keeps
285        // the safe default: emit nothing, leaving the normal flow untouched.
286        let r = CodexHookFormat.render_context("anything");
287        assert_eq!(r.stdout, "");
288        assert_eq!(r.exit_code, 0);
289    }
290}