1use std::collections::HashMap;
13use std::net::{IpAddr, SocketAddr};
14use std::sync::{Arc, Mutex};
15use std::time::Duration;
16
17use hmac::{Hmac, Mac};
18use serde_json::{Value, json};
19use sha2::Sha256;
20use tokio::task::JoinHandle;
21
22use crate::service::Service;
23
24const RETRIES: u32 = 3;
25const DELIVERY_TIMEOUT: Duration = Duration::from_secs(15);
26pub const SIGNATURE_HEADER: &str = "x-interloper-signature";
27
28fn blocked(ip: IpAddr) -> bool {
29 match ip {
30 IpAddr::V4(v4) => {
31 let o = v4.octets();
32 v4.is_private()
33 || v4.is_loopback()
34 || v4.is_link_local()
35 || v4.is_multicast()
36 || v4.is_unspecified()
37 || v4.is_broadcast()
38 || v4.is_documentation()
39 || o[0] == 0
40 || (o[0] == 100 && (64..128).contains(&o[1])) || o[0] >= 240
42 }
43 IpAddr::V6(v6) => {
44 let seg = v6.segments();
45 if let Some(v4) = v6.to_ipv4_mapped() {
46 return blocked(IpAddr::V4(v4));
47 }
48 v6.is_loopback()
49 || v6.is_unspecified()
50 || v6.is_multicast()
51 || (seg[0] & 0xfe00) == 0xfc00 || (seg[0] & 0xffc0) == 0xfe80 || seg[0] == 0x2001 && seg[1] == 0x0db8 }
55 }
56}
57
58#[derive(Debug, Clone)]
60pub struct Target {
61 pub url: url::Url,
62 pub pinned: Option<Vec<SocketAddr>>,
63}
64
65pub async fn validate(raw: &str, allow_private: bool) -> Result<Target, String> {
66 let url =
67 url::Url::parse(raw).map_err(|_| "url must be an absolute http(s) URL".to_string())?;
68 if !matches!(url.scheme(), "http" | "https") {
69 return Err("url must be http or https".into());
70 }
71 let host = url.host_str().ok_or("url missing host")?.to_string();
72 if !url.username().is_empty() || url.password().is_some() {
73 return Err("url must not carry credentials".into());
74 }
75 if allow_private {
76 return Ok(Target { url, pinned: None });
77 }
78 let port = url.port_or_known_default().unwrap_or(443);
79 let bare = host.trim_start_matches('[').trim_end_matches(']');
80 let addrs: Vec<SocketAddr> = match bare.parse::<IpAddr>() {
81 Ok(ip) => vec![SocketAddr::new(ip, port)],
82 Err(_) => tokio::net::lookup_host((bare, port))
83 .await
84 .map_err(|e| format!("cannot resolve webhook host: {e}"))?
85 .collect(),
86 };
87 if addrs.is_empty() {
88 return Err("webhook host resolves to nothing".into());
89 }
90 if addrs.iter().any(|a| blocked(a.ip())) {
91 return Err(
92 "webhook host resolves to a private or loopback address (set INTERLOPER_WEBHOOK_ALLOW_PRIVATE=1 to override)"
93 .into(),
94 );
95 }
96 Ok(Target {
97 url,
98 pinned: Some(addrs),
99 })
100}
101
102pub fn sign(secret: &str, body: &[u8]) -> String {
103 let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("hmac takes any key");
104 mac.update(body);
105 format!("sha256={}", hex::encode(mac.finalize().into_bytes()))
106}
107
108#[derive(Debug, Clone, serde::Serialize)]
109pub struct Hook {
110 pub id: String,
111 pub address: String,
112 pub url: String,
113 pub timeout: u64,
114}
115
116pub struct Webhooks {
117 service: Arc<Service>,
118 allow_private: bool,
119 secret: Option<String>,
120 hooks: Mutex<HashMap<String, (Hook, JoinHandle<()>)>>,
121}
122
123impl Webhooks {
124 pub fn new(service: Arc<Service>, allow_private: bool, secret: Option<String>) -> Arc<Self> {
125 Arc::new(Webhooks {
126 service,
127 allow_private,
128 secret,
129 hooks: Mutex::new(HashMap::new()),
130 })
131 }
132
133 pub async fn create(
134 self: &Arc<Self>,
135 address: String,
136 url: &str,
137 timeout: Duration,
138 ) -> Result<String, String> {
139 let target = validate(url, self.allow_private).await?;
140 let id = format!("{:012x}", rand::random::<u64>() & 0xffff_ffff_ffff);
141 let hook = Hook {
142 id: id.clone(),
143 address: address.clone(),
144 url: url.to_string(),
145 timeout: timeout.as_secs(),
146 };
147 let me = self.clone();
148 let hook_id = id.clone();
149 let mut hooks = self.hooks.lock().unwrap();
152 let task = tokio::spawn(async move {
153 me.run(&address, &target, timeout).await;
154 me.hooks.lock().unwrap().remove(&hook_id);
155 });
156 hooks.insert(id.clone(), (hook, task));
157 Ok(id)
158 }
159
160 pub fn list(&self) -> Vec<Hook> {
161 let mut v: Vec<Hook> = self
162 .hooks
163 .lock()
164 .unwrap()
165 .values()
166 .map(|(h, _)| h.clone())
167 .collect();
168 v.sort_by(|a, b| a.id.cmp(&b.id));
169 v
170 }
171
172 pub fn cancel(&self, id: &str) -> bool {
173 match self.hooks.lock().unwrap().remove(id) {
174 Some((_, task)) => {
175 task.abort();
176 true
177 }
178 None => false,
179 }
180 }
181
182 pub fn shutdown(&self) {
183 for (_, (_, task)) in self.hooks.lock().unwrap().drain() {
184 task.abort();
185 }
186 }
187
188 async fn run(&self, address: &str, target: &Target, timeout: Duration) {
189 let payload = match self
190 .service
191 .wait(address, timeout, None, false, &Default::default())
192 .await
193 {
194 Ok(Some((m, code))) => {
195 let mut p = crate::message_json(&m, code.as_deref());
196 p["event"] = json!("message");
197 p["address"] = json!(address);
198 p
199 }
200 Ok(None) => json!({"event": "timeout", "address": address}),
201 Err(e) => {
202 tracing::warn!(address, error = ?e, "webhook wait failed");
203 json!({"event": "error", "address": address})
204 }
205 };
206 self.deliver(target, &payload).await;
207 }
208
209 async fn deliver(&self, target: &Target, payload: &Value) {
210 let body = serde_json::to_vec(payload).expect("json");
211 let mut b = wreq::Client::builder()
212 .redirect(wreq::redirect::Policy::none())
213 .timeout(DELIVERY_TIMEOUT);
214 if let (Some(addrs), Some(host)) = (&target.pinned, target.url.host_str()) {
215 b = b.resolve_to_addrs(host.to_string(), addrs.iter().copied());
216 }
217 let Ok(client) = b.build() else {
218 tracing::warn!("webhook client could not be built");
219 return;
220 };
221 for attempt in 1..=RETRIES {
222 let mut req = client
223 .post(target.url.as_str())
224 .header("content-type", "application/json")
225 .body(body.clone());
226 if let Some(secret) = &self.secret {
227 req = req.header(SIGNATURE_HEADER, sign(secret, &body));
228 }
229 match req.send().await {
230 Ok(r) if r.status().as_u16() < 400 => return,
231 Ok(r) => {
232 tracing::info!(url = %target.url, status = r.status().as_u16(), attempt, "webhook delivery refused")
233 }
234 Err(e) => {
235 tracing::info!(url = %target.url, error = %e, attempt, "webhook delivery error")
236 }
237 }
238 tokio::time::sleep(Duration::from_secs(2 * attempt as u64)).await;
239 }
240 tracing::warn!(url = %target.url, "webhook delivery failed after {RETRIES} attempts");
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 #[tokio::test]
249 async fn private_targets_are_refused() {
250 for u in [
251 "http://127.0.0.1/x",
252 "http://10.0.0.5/",
253 "http://[::1]:8080/",
254 "http://169.254.169.254/latest/meta-data",
255 "http://100.64.1.1/",
256 "http://[::ffff:127.0.0.1]/",
257 "http://localhost/",
258 ] {
259 assert!(validate(u, false).await.is_err(), "{u}");
260 }
261 }
262
263 #[tokio::test]
264 async fn bad_shapes_are_refused() {
265 for u in ["ftp://x.test/", "not a url", "http://user:pw@example.com/"] {
266 assert!(validate(u, false).await.is_err(), "{u}");
267 }
268 }
269
270 #[tokio::test]
271 async fn public_literal_is_pinned() {
272 let t = validate("https://93.184.215.14/hook", false).await.unwrap();
273 assert_eq!(
274 t.pinned.unwrap(),
275 vec!["93.184.215.14:443".parse::<SocketAddr>().unwrap()]
276 );
277 }
278
279 #[tokio::test]
280 async fn allow_private_skips_resolution() {
281 assert!(
282 validate("http://127.0.0.1:9/", true)
283 .await
284 .unwrap()
285 .pinned
286 .is_none()
287 );
288 }
289
290 #[test]
291 fn signature_is_hmac_sha256() {
292 let sig = sign("Jefe", b"what do ya want for nothing?");
294 assert_eq!(
295 sig,
296 "sha256=5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
297 );
298 }
299}