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