safe_chains/targets/
codex.rs1use 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, })
92 }
93
94 fn render_response(&self, _verdict: Verdict) -> HookResponse {
95 HookResponse {
100 stdout: String::new(),
101 exit_code: 0,
102 }
103 }
104
105 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 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 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 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 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 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 let r = CodexHookFormat.render_context("anything");
304 assert_eq!(r.stdout, "");
305 assert_eq!(r.exit_code, 0);
306 }
307}