返回 CodeWhale
lib.rs
根目录 / crates / hooks / src / lib.rs
1 use std::path::{Path, PathBuf};
2
3 use anyhow::{Context, Result};
4
5 mod lifecycle_outbox;
6
7 pub use lifecycle_outbox::{
8 LifecycleEvent, LifecycleOutbox, OUTBOX_DETAIL_MAX_CHARS, OUTBOX_HEADLINE_MAX_CHARS,
9 OUTBOX_PREVIEW_MAX_CHARS, OUTBOX_TRUNCATION_MARKER, bounded_text,
10 };
11
12 /// Expand a leading `~` in a configured sink path, reusing the one expansion
13 /// rule global path overrides use. Documented examples write
14 /// `~/.codewhale/...`; taken literally that created a directory named `~` in
15 /// the working directory. A path without `~` (absolute or relative) is
16 /// returned unchanged, as is `~` when no home resolves.
17 pub(crate) fn expand_home(path: PathBuf) -> PathBuf {
18 codewhale_paths::validate_absolute_path("hook sink path", path.clone()).unwrap_or(path)
19 }
20
21 /// Open a JSONL sink for append, creating it privately: on Unix new parent
22 /// directories are 0700 and a new file 0600 (existing modes are left alone).
23 /// Hook and lifecycle events carry tool payloads, prompts, and paths; under
24 /// an ordinary umask the old defaults were readable by every local user.
25 pub(crate) fn open_private_append_sync(path: &Path) -> Result<std::fs::File> {
26 if let Some(parent) = path
27 .parent()
28 .filter(|parent| !parent.as_os_str().is_empty())
29 {
30 let mut dirs = std::fs::DirBuilder::new();
31 dirs.recursive(true);
32 #[cfg(unix)]
33 {
34 use std::os::unix::fs::DirBuilderExt;
35 dirs.mode(0o700);
36 }
37 dirs.create(parent)
38 .with_context(|| format!("failed to create sink directory {}", parent.display()))?;
39 }
40 let mut options = std::fs::OpenOptions::new();
41 options.create(true).append(true);
42 #[cfg(unix)]
43 {
44 use std::os::unix::fs::OpenOptionsExt;
45 options.mode(0o600);
46 }
47 options
48 .open(path)
49 .with_context(|| format!("failed to open sink file {}", path.display()))
50 }
51
52 pub(crate) fn open_private_lock_file_sync(outbox_path: &Path) -> Result<std::fs::File> {
53 let mut lock_name = outbox_path
54 .file_name()
55 .map(std::ffi::OsString::from)
56 .unwrap_or_else(|| std::ffi::OsString::from("outbox"));
57 lock_name.push(".lock");
58 let lock_path = match outbox_path.parent() {
59 Some(parent) if !parent.as_os_str().is_empty() => {
60 let mut dirs = std::fs::DirBuilder::new();
61 dirs.recursive(true);
62 #[cfg(unix)]
63 {
64 use std::os::unix::fs::DirBuilderExt;
65 dirs.mode(0o700);
66 }
67 dirs.create(parent)
68 .with_context(|| format!("failed to create sink directory {}", parent.display()))?;
69 parent.join(lock_name)
70 }
71 _ => PathBuf::from(lock_name),
72 };
73 let mut options = std::fs::OpenOptions::new();
74 options.create(true).read(true).write(true);
75 #[cfg(unix)]
76 {
77 use std::os::unix::fs::OpenOptionsExt;
78 options.mode(0o600);
79 }
80 options
81 .open(&lock_path)
82 .with_context(|| format!("failed to open lock file {}", lock_path.display()))
83 }
84
85 fn is_loopback_host(url: &reqwest::Url) -> bool {
86 let Some(host) = url.host_str() else {
87 return false;
88 };
89 let bare = host
90 .strip_prefix('[')
91 .and_then(|rest| rest.strip_suffix(']'))
92 .unwrap_or(host)
93 .trim_end_matches('.');
94 bare.eq_ignore_ascii_case("localhost")
95 || bare
96 .parse::<std::net::IpAddr>()
97 .is_ok_and(|ip| ip.is_loopback())
98 }
99
100 fn validate_webhook_url(url: &str) -> Result<()> {
101 let parsed = reqwest::Url::parse(url).context("webhook URL is not a valid URL")?;
102 match parsed.scheme() {
103 "https" => Ok(()),
104 "http" if is_loopback_host(&parsed) => Ok(()),
105 "http" => anyhow::bail!(
106 "refusing cleartext http:// webhook URL for non-loopback host; use https://"
107 ),
108 scheme => anyhow::bail!("unsupported webhook URL scheme '{scheme}'; use https://"),
109 }
110 }
111
112 /// Header carrying the stable per-event idempotency key across webhook retries.
113 pub const WEBHOOK_IDEMPOTENCY_KEY_HEADER: &str = "Idempotency-Key";
114
115 /// HTTP transport for lifecycle outbox webhooks: POSTs a JSON payload to a
116 /// remote endpoint. Failed requests are retried up to 2 times with exponential
117 /// back-off (200 ms, 400 ms). After exhausting retries the error is propagated.
118 #[derive(Clone)]
119 pub struct WebhookHookSink {
120 url: String,
121 /// Optional bearer token sent as `Authorization: Bearer <token>`.
122 bearer_token: Option<String>,
123 client: reqwest::Client,
124 }
125
126 impl WebhookHookSink {
127 /// Create a new sink that sends events to the given `url`, attaching
128 /// `Authorization: Bearer <token>` when a token is provided.
129 pub fn new_with_token(url: String, bearer_token: Option<String>) -> Self {
130 Self {
131 url,
132 bearer_token,
133 client: codewhale_release::platform_http_client_builder()
134 .redirect(reqwest::redirect::Policy::none())
135 .timeout(std::time::Duration::from_secs(10))
136 .build()
137 .unwrap_or_else(|_| {
138 codewhale_release::tls::reqwest_client_builder()
139 .redirect(reqwest::redirect::Policy::none())
140 .timeout(std::time::Duration::from_secs(10))
141 .build()
142 .expect("non-redirecting webhook HTTP client")
143 }),
144 }
145 }
146
147 /// POST an arbitrary JSON payload to the configured endpoint with a stable
148 /// `Idempotency-Key` header reused across retries.
149 ///
150 /// This is the delivery path behind the lifecycle outbox fan-out.
151 pub async fn post_payload(
152 &self,
153 payload: serde_json::Value,
154 idempotency_key: &str,
155 ) -> Result<()> {
156 validate_webhook_url(&self.url)?;
157 let mut retries = 0usize;
158 loop {
159 let mut request = self
160 .client
161 .post(&self.url)
162 .header(WEBHOOK_IDEMPOTENCY_KEY_HEADER, idempotency_key)
163 .json(&payload);
164 if let Some(token) = self.bearer_token.as_deref().filter(|t| !t.is_empty()) {
165 request = request.bearer_auth(token);
166 }
167 let resp = request.send().await;
168 match resp {
169 Ok(response) if response.status().is_success() => return Ok(()),
170 Ok(response) => {
171 if retries >= 2 {
172 anyhow::bail!("webhook returned non-success status {}", response.status());
173 }
174 }
175 Err(err) => {
176 if retries >= 2 {
177 return Err(err).context("webhook request failed");
178 }
179 }
180 }
181 retries += 1;
182 tokio::time::sleep(std::time::Duration::from_millis(200 * retries as u64)).await;
183 }
184 }
185 }
186
187 #[cfg(test)]
188 mod tests {
189 use super::*;
190
191 #[test]
192 fn expand_home_expands_tilde_and_leaves_other_paths() {
193 let home = codewhale_paths::user_home().expect("test home");
194 assert_eq!(
195 expand_home(PathBuf::from("~/.codewhale/events.jsonl")),
196 home.join(".codewhale/events.jsonl")
197 );
198 assert_eq!(
199 expand_home(PathBuf::from("relative/events.jsonl")),
200 PathBuf::from("relative/events.jsonl")
201 );
202 }
203
204 #[cfg(unix)]
205 #[tokio::test]
206 async fn open_private_append_creates_private_files() {
207 use std::os::unix::fs::PermissionsExt;
208 use std::time::{SystemTime, UNIX_EPOCH};
209
210 let nanos = SystemTime::now()
211 .duration_since(UNIX_EPOCH)
212 .unwrap()
213 .as_nanos();
214 let root = std::env::temp_dir().join(format!(
215 "deepseek-hooks-private-{}-{nanos}",
216 std::process::id()
217 ));
218 let path = root.join("nested").join("events.jsonl");
219 open_private_append_sync(&path).expect("open");
220 let file_mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
221 let dir_mode = std::fs::metadata(path.parent().unwrap())
222 .unwrap()
223 .permissions()
224 .mode()
225 & 0o777;
226 let _ = std::fs::remove_dir_all(&root);
227 assert_eq!(file_mode, 0o600);
228 assert_eq!(dir_mode, 0o700);
229 }
230
231 #[test]
232 fn webhook_sink_new_does_not_panic() {
233 let sink =
234 WebhookHookSink::new_with_token("https://example.invalid/webhook".to_string(), None);
235 let _ = sink;
236 }
237
238 #[test]
239 fn validate_webhook_url_enforces_https_except_loopback() {
240 assert!(validate_webhook_url("https://collector.example.com/hook").is_ok());
241 assert!(validate_webhook_url("http://127.0.0.1:8080/hook").is_ok());
242 assert!(validate_webhook_url("http://[::1]:8080/hook").is_ok());
243 assert!(validate_webhook_url("http://localhost:8080/hook").is_ok());
244 assert!(validate_webhook_url("http://collector.internal:8080/hook").is_err());
245 assert!(validate_webhook_url("http://192.168.1.10:8080/hook").is_err());
246 assert!(validate_webhook_url("ftp://collector.example.com/hook").is_err());
247 assert!(validate_webhook_url("not-a-url").is_err());
248 }
249
250 #[tokio::test]
251 async fn webhook_rejects_cleartext_non_loopback_http_with_bearer_token() {
252 let sink = WebhookHookSink::new_with_token(
253 "http://collector.internal:8080/hook".to_string(),
254 Some("secret-token".to_string()),
255 );
256 let err = sink
257 .post_payload(serde_json::json!({"event": "test"}), "test-idem-key")
258 .await
259 .expect_err("cleartext non-loopback http webhook must be rejected");
260 assert!(err.to_string().contains("https://"), "{err}");
261 }
262 }
263
263 lines RUST