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, allow_reason};
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 })
91 }
92
93 fn render_response(&self, verdict: Verdict) -> HookResponse {
94 if verdict.is_allowed() {
95 let reason = allow_reason(verdict);
96 let body = json!({
97 "hookSpecificOutput": {
98 "hookEventName": "PreToolUse",
99 "permissionDecision": "allow",
100 "permissionDecisionReason": reason,
101 }
102 });
103 HookResponse {
104 stdout: serde_json::to_string(&body).unwrap_or_default(),
105 exit_code: 0,
106 }
107 } else {
108 HookResponse {
109 stdout: String::new(),
110 exit_code: 0,
111 }
112 }
113 }
114}
115
116fn hook_entry(binary: &str) -> Value {
117 json!({
118 "matcher": "Bash",
119 "hooks": [{
120 "type": "command",
121 "command": binary,
122 }]
123 })
124}
125
126fn has_safe_chains_hook(settings: &Value) -> bool {
127 settings
128 .get("PreToolUse")
129 .and_then(|arr| arr.as_array())
130 .is_some_and(|entries| {
131 entries.iter().any(|entry| {
132 entry
133 .get("hooks")
134 .and_then(|h| h.as_array())
135 .is_some_and(|hooks| {
136 hooks.iter().any(|hook| {
137 hook.get("command")
138 .and_then(|c| c.as_str())
139 .is_some_and(|cmd| cmd.contains("safe-chains"))
140 })
141 })
142 })
143 })
144}
145
146fn add_hook(settings: &mut Value, binary: &str) {
147 if !settings.is_object() {
148 *settings = json!({});
149 }
150 let Some(obj) = settings.as_object_mut() else {
151 unreachable!("settings was just set to an object");
152 };
153 let pre_tool_use = obj
154 .entry("PreToolUse")
155 .or_insert_with(|| json!([]))
156 .as_array_mut()
157 .expect("PreToolUse key was created above as an array");
158 pre_tool_use.push(hook_entry(binary));
159}
160
161#[cfg(test)]
162mod tests {
163 use super::*;
164 use crate::verdict::SafetyLevel;
165
166 fn target() -> CodexTarget {
167 CodexTarget
168 }
169
170 #[test]
171 fn install_no_codex_dir_skips() {
172 let dir = tempfile::tempdir().unwrap();
173 let outcome = target().install(dir.path()).unwrap();
174 assert!(matches!(outcome, InstallOutcome::Skipped { .. }));
175 }
176
177 #[test]
178 fn install_creates_hooks_file() {
179 let dir = tempfile::tempdir().unwrap();
180 std::fs::create_dir(dir.path().join(".codex")).unwrap();
181 let outcome = target().install(dir.path()).unwrap();
182 assert!(matches!(outcome, InstallOutcome::Installed { .. }));
183 let contents = std::fs::read_to_string(dir.path().join(".codex/hooks.json")).unwrap();
184 let settings: Value = serde_json::from_str(&contents).unwrap();
185 assert!(has_safe_chains_hook(&settings));
186 }
187
188 #[test]
189 fn install_idempotent() {
190 let dir = tempfile::tempdir().unwrap();
191 std::fs::create_dir(dir.path().join(".codex")).unwrap();
192 target().install(dir.path()).unwrap();
193 let outcome = target().install(dir.path()).unwrap();
194 assert!(matches!(outcome, InstallOutcome::AlreadyConfigured { .. }));
195 }
196
197 #[test]
198 fn install_uses_subcommand_invocation() {
199 let dir = tempfile::tempdir().unwrap();
202 std::fs::create_dir(dir.path().join(".codex")).unwrap();
203 target().install(dir.path()).unwrap();
204 let contents = std::fs::read_to_string(dir.path().join(".codex/hooks.json")).unwrap();
205 assert!(contents.contains("safe-chains hook codex"));
206 }
207
208 #[test]
209 fn install_preserves_existing_hooks() {
210 let dir = tempfile::tempdir().unwrap();
211 let codex_dir = dir.path().join(".codex");
212 std::fs::create_dir(&codex_dir).unwrap();
213 std::fs::write(
214 codex_dir.join("hooks.json"),
215 r#"{"PostToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "log-it"}]}]}"#,
216 )
217 .unwrap();
218 target().install(dir.path()).unwrap();
219 let contents = std::fs::read_to_string(codex_dir.join("hooks.json")).unwrap();
220 let settings: Value = serde_json::from_str(&contents).unwrap();
221 assert!(has_safe_chains_hook(&settings));
222 assert!(
223 settings.get("PostToolUse").is_some(),
224 "existing PostToolUse must be preserved"
225 );
226 }
227
228 #[test]
229 fn parse_input_extracts_command() {
230 let stdin = r#"{"tool_name": "Bash", "tool_input": {"command": "ls -la"}}"#;
231 let parsed = CodexHookFormat.parse_input(stdin).unwrap();
232 assert_eq!(parsed.command, "ls -la");
233 }
234
235 #[test]
236 fn parse_input_with_optional_cwd() {
237 let stdin = r#"{"tool_input": {"command": "pwd"}, "cwd": "/Users/me"}"#;
238 let parsed = CodexHookFormat.parse_input(stdin).unwrap();
239 assert_eq!(parsed.cwd.as_deref(), Some("/Users/me"));
240 }
241
242 #[test]
243 fn parse_input_rejects_garbage() {
244 assert!(CodexHookFormat.parse_input("not json").is_err());
245 assert!(CodexHookFormat.parse_input("{}").is_err());
246 }
247
248 #[test]
249 fn render_response_allow_emits_allow_envelope() {
250 let r = CodexHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
251 let v: Value = serde_json::from_str(&r.stdout).unwrap();
252 assert_eq!(
253 v.pointer("/hookSpecificOutput/permissionDecision")
254 .and_then(|d| d.as_str()),
255 Some("allow"),
256 );
257 assert_eq!(
258 v.pointer("/hookSpecificOutput/hookEventName")
259 .and_then(|d| d.as_str()),
260 Some("PreToolUse"),
261 );
262 }
263
264 #[test]
265 fn render_response_deny_emits_empty_body() {
266 let r = CodexHookFormat.render_response(Verdict::Denied);
267 assert_eq!(r.stdout, "");
268 }
269}