steid

@jamesgill /

Rust9.5 KBCode·Blame·History·Raw
1//! Delivering a webhook over HTTP.
2//!
3//! `ureq` rather than `reqwest`: it is already in the dependency tree — Topcoat pulls it
4//! in through its `tailwind` and `icon-iconify` features — and it already brings
5//! `rustls` with it, so this adds a feature flag rather than a TLS stack. It is a
6//! *blocking* client, which is why every call runs inside
7//! [`spawn_blocking`](tokio::task::spawn_blocking): a blocking socket read on a runtime
8//! worker stalls every other request the process is serving.
9//!
10//! **The second half of the SSRF defence lives here.**
11//! [`WebhookUrl`](crate::domain::WebhookUrl) refuses an address at the moment a person
12//! saves one, which is when they can be told why. That cannot cover a public name that
13//! resolves to a private address, so the host is resolved here and every address it
14//! answers with is checked before the request is made.
15//!
16//! What it does *not* close is the gap between that resolution and `ureq`'s own — a name
17//! whose answer changes in between (DNS rebinding) is still reachable. Closing it needs a
18//! custom resolver or connecting to a pinned address with the `Host` header set by hand,
19//! and neither is worth the machinery until a hook is something a *second* user can add.
20
21use std::{
22 io::Read,
23 net::ToSocketAddrs,
24 sync::{Arc, Mutex},
25 time::{Duration, Instant},
26};
27
28use crate::{
29 application::port::{WebhookOutcome, WebhookRequest, WebhookSender},
30 domain::is_public,
31};
32
33/// How long one attempt may take, connection through body.
34///
35/// Whole-request rather than per-phase: a receiver that dribbles a response one byte at
36/// a time is the same problem as one that never answers, and the caller is a retry loop
37/// that has somewhere better to be.
38const TIMEOUT: Duration = Duration::from_secs(10);
39
40/// How much of a response body is read.
41///
42/// Read short rather than read-then-truncate: the domain caps what is *stored*, and
43/// without a cap here a hostile endpoint could stream forever inside the timeout.
44const MAX_RESPONSE_BYTES: u64 = 8 * 1024;
45
46/// Webhook delivery over real HTTP.
47#[derive(Debug, Clone, Default)]
48pub struct UreqWebhookSender;
49
50impl UreqWebhookSender {
51 pub fn new() -> Self {
52 Self
53 }
54}
55
56impl WebhookSender for UreqWebhookSender {
57 async fn send(&self, request: WebhookRequest) -> WebhookOutcome {
58 let started = Instant::now();
59
60 // A panic inside the blocking pool must not take the delivery with it silently;
61 // a join error is reported as an outcome like any other failure.
62 match tokio::task::spawn_blocking(move || send_blocking(request)).await {
63 Ok(outcome) => outcome,
64 Err(error) => WebhookOutcome {
65 status: None,
66 body: format!("delivery task failed: {error}"),
67 duration: started.elapsed(),
68 },
69 }
70 }
71}
72
73/// The blocking half, run off the runtime.
74fn send_blocking(request: WebhookRequest) -> WebhookOutcome {
75 let started = Instant::now();
76
77 let outcome = |status, body: String| WebhookOutcome {
78 status,
79 body,
80 duration: started.elapsed(),
81 };
82
83 if let Err(reason) = check_resolves_publicly(&request.url) {
84 return outcome(None, reason);
85 }
86
87 let agent: ureq::Agent = ureq::Agent::config_builder()
88 .timeout_global(Some(TIMEOUT))
89 // A 4xx or 5xx is a *result* here, not an error: it is exactly what the delivery
90 // row exists to record, and the default would collapse it into the same variant
91 // as a refused connection.
92 .http_status_as_error(false)
93 .build()
94 .into();
95
96 let mut send = agent.post(&request.url);
97
98 for (name, value) in &request.headers {
99 send = send.header(name.as_str(), value.as_str());
100 }
101
102 match send.send(&request.body[..]) {
103 Ok(mut response) => {
104 let status = response.status().as_u16();
105 let mut body = String::new();
106
107 // Ignoring the read error on purpose: the status is the answer, and a
108 // response whose body could not be read is still a delivery that happened.
109 let _ = response
110 .body_mut()
111 .as_reader()
112 .take(MAX_RESPONSE_BYTES)
113 .read_to_string(&mut body);
114
115 outcome(Some(status), body)
116 }
117 // No status at all: DNS, a refused connection, TLS, or the timeout. git's own
118 // words are carried for the same reason `run_git` carries them — "delivery
119 // failed" sends the next person to read this code instead of the error.
120 Err(error) => outcome(None, error.to_string()),
121 }
122}
123
124/// Refuses a URL whose host resolves to an address inside this machine or its network.
125///
126/// Every address the name answers with has to pass, not merely the first: a name with
127/// both a public and a private answer is the shape of the attack, and connecting to
128/// "whichever came back first" is not a decision worth leaving to a resolver.
129fn check_resolves_publicly(url: &str) -> Result<(), String> {
130 let (scheme, rest) = url.split_once("://").ok_or("that URL has no scheme")?;
131 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
132
133 let default_port = if scheme.eq_ignore_ascii_case("https") {
134 443
135 } else {
136 80
137 };
138
139 // `to_socket_addrs` wants `host:port`, and an IPv6 literal must keep its brackets
140 // for that — which is exactly how the authority already spells it.
141 let target = if authority.contains(':') && !authority.ends_with(']') {
142 authority.to_owned()
143 } else {
144 format!("{authority}:{default_port}")
145 };
146
147 let resolved: Vec<_> = target
148 .to_socket_addrs()
149 .map_err(|error| format!("{authority} did not resolve: {error}"))?
150 .collect();
151
152 if resolved.is_empty() {
153 return Err(format!("{authority} resolved to no addresses"));
154 }
155
156 for address in resolved {
157 if !is_public(address.ip()) {
158 return Err(format!(
159 "{authority} resolves to {}, which is on this machine or its private network",
160 address.ip()
161 ));
162 }
163 }
164
165 Ok(())
166}
167
168/// A sender that records what it was asked to deliver and answers from a script.
169///
170/// The counterpart to [`UreqWebhookSender`], and what lets the delivery use case be
171/// tested without a listening socket. The recorded requests are what a test asserts the
172/// signature and headers on.
173#[derive(Debug, Default, Clone)]
174pub struct InMemoryWebhookSender {
175 sent: Arc<Mutex<Vec<WebhookRequest>>>,
176 /// One outcome per call, in order. The last one repeats once the script runs out, so
177 /// a test that wants "always fails" writes one entry rather than four.
178 script: Arc<Mutex<Vec<WebhookOutcome>>>,
179}
180
181impl InMemoryWebhookSender {
182 /// A sender that always succeeds.
183 pub fn new() -> Self {
184 Self::default()
185 }
186
187 /// A sender that answers with these outcomes in order, repeating the last.
188 pub fn scripted(outcomes: Vec<WebhookOutcome>) -> Self {
189 Self {
190 sent: Arc::default(),
191 script: Arc::new(Mutex::new(outcomes)),
192 }
193 }
194
195 /// Everything it was asked to send, in order.
196 pub fn sent(&self) -> Vec<WebhookRequest> {
197 self.sent.lock().expect("lock poisoned").clone()
198 }
199}
200
201impl WebhookSender for InMemoryWebhookSender {
202 async fn send(&self, request: WebhookRequest) -> WebhookOutcome {
203 let mut sent = self.sent.lock().expect("lock poisoned");
204 sent.push(request);
205
206 let script = self.script.lock().expect("lock poisoned");
207
208 match script.get(sent.len() - 1).or_else(|| script.last()) {
209 Some(outcome) => outcome.clone(),
210 None => WebhookOutcome {
211 status: Some(200),
212 body: String::new(),
213 duration: Duration::from_millis(1),
214 },
215 }
216 }
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222
223 #[test]
224 fn a_name_that_resolves_to_a_private_address_is_refused() {
225 // The half `WebhookUrl` cannot cover: the check is on what the name *resolves
226 // to*, not on how it is spelled. `localhost` stands in for a public name with a
227 // private answer because it needs no resolver to be reachable — the real case
228 // is a domain whose A record points inside the network.
229 assert!(check_resolves_publicly("http://localhost:8080/hook").is_err());
230 assert!(check_resolves_publicly("http://localhost/hook").is_err());
231 }
232
233 #[test]
234 fn a_url_with_no_scheme_never_reaches_a_socket() {
235 assert!(check_resolves_publicly("example.com/hook").is_err());
236 }
237
238 #[test]
239 fn a_name_that_resolves_to_nothing_is_refused_rather_than_dialled() {
240 assert!(check_resolves_publicly("https://this-name-does-not-exist.invalid/hook").is_err());
241 }
242
243 #[tokio::test]
244 async fn the_fake_answers_a_script_in_order_and_then_repeats_it() {
245 let outcome = |status| WebhookOutcome {
246 status,
247 body: String::new(),
248 duration: Duration::from_millis(1),
249 };
250
251 let sender = InMemoryWebhookSender::scripted(vec![outcome(None), outcome(Some(200))]);
252
253 let request = || WebhookRequest {
254 url: "https://example.com/hook".to_owned(),
255 headers: Vec::new(),
256 body: b"{}".to_vec(),
257 };
258
259 assert_eq!(sender.send(request()).await.status, None);
260 assert_eq!(sender.send(request()).await.status, Some(200));
261 assert_eq!(sender.send(request()).await.status, Some(200));
262 assert_eq!(sender.sent().len(), 3);
263 }
264}