steid

@jamesgill /

Rust10.3 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::{PrivateTargets, 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 /// Whether an address on this machine's own network is dialled.
50 ///
51 /// Carried rather than read from configuration here, because an adapter that reads
52 /// the environment is one that cannot be tested with the setting off. `Refused` is
53 /// the `Default`, so a sender constructed without thinking about it is the safe one.
54 targets: PrivateTargets,
55}
56
57impl UreqWebhookSender {
58 pub fn new(targets: PrivateTargets) -> Self {
59 Self { targets }
60 }
61}
62
63impl WebhookSender for UreqWebhookSender {
64 async fn send(&self, request: WebhookRequest) -> WebhookOutcome {
65 let started = Instant::now();
66
67 // A panic inside the blocking pool must not take the delivery with it silently;
68 // a join error is reported as an outcome like any other failure.
69 let targets = self.targets;
70
71 match tokio::task::spawn_blocking(move || send_blocking(request, targets)).await {
72 Ok(outcome) => outcome,
73 Err(error) => WebhookOutcome {
74 status: None,
75 body: format!("delivery task failed: {error}"),
76 duration: started.elapsed(),
77 },
78 }
79 }
80}
81
82/// The blocking half, run off the runtime.
83fn send_blocking(request: WebhookRequest, targets: PrivateTargets) -> WebhookOutcome {
84 let started = Instant::now();
85
86 let outcome = |status, body: String| WebhookOutcome {
87 status,
88 body,
89 duration: started.elapsed(),
90 };
91
92 // Skipped only on an instance that has deliberately opted in, which is the half of
93 // the escape hatch the domain cannot provide: a URL that passed
94 // `WebhookUrl::new_allowing_private` would otherwise be refused here instead, one
95 // layer later and with no page to say so.
96 if targets == PrivateTargets::Refused
97 && let Err(reason) = check_resolves_publicly(&request.url)
98 {
99 return outcome(None, reason);
100 }
101
102 let agent: ureq::Agent = ureq::Agent::config_builder()
103 .timeout_global(Some(TIMEOUT))
104 // A 4xx or 5xx is a *result* here, not an error: it is exactly what the delivery
105 // row exists to record, and the default would collapse it into the same variant
106 // as a refused connection.
107 .http_status_as_error(false)
108 .build()
109 .into();
110
111 let mut send = agent.post(&request.url);
112
113 for (name, value) in &request.headers {
114 send = send.header(name.as_str(), value.as_str());
115 }
116
117 match send.send(&request.body[..]) {
118 Ok(mut response) => {
119 let status = response.status().as_u16();
120 let mut body = String::new();
121
122 // Ignoring the read error on purpose: the status is the answer, and a
123 // response whose body could not be read is still a delivery that happened.
124 let _ = response
125 .body_mut()
126 .as_reader()
127 .take(MAX_RESPONSE_BYTES)
128 .read_to_string(&mut body);
129
130 outcome(Some(status), body)
131 }
132 // No status at all: DNS, a refused connection, TLS, or the timeout. git's own
133 // words are carried for the same reason `run_git` carries them — "delivery
134 // failed" sends the next person to read this code instead of the error.
135 Err(error) => outcome(None, error.to_string()),
136 }
137}
138
139/// Refuses a URL whose host resolves to an address inside this machine or its network.
140///
141/// Every address the name answers with has to pass, not merely the first: a name with
142/// both a public and a private answer is the shape of the attack, and connecting to
143/// "whichever came back first" is not a decision worth leaving to a resolver.
144fn check_resolves_publicly(url: &str) -> Result<(), String> {
145 let (scheme, rest) = url.split_once("://").ok_or("that URL has no scheme")?;
146 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
147
148 let default_port = if scheme.eq_ignore_ascii_case("https") {
149 443
150 } else {
151 80
152 };
153
154 // `to_socket_addrs` wants `host:port`, and an IPv6 literal must keep its brackets
155 // for that — which is exactly how the authority already spells it.
156 let target = if authority.contains(':') && !authority.ends_with(']') {
157 authority.to_owned()
158 } else {
159 format!("{authority}:{default_port}")
160 };
161
162 let resolved: Vec<_> = target
163 .to_socket_addrs()
164 .map_err(|error| format!("{authority} did not resolve: {error}"))?
165 .collect();
166
167 if resolved.is_empty() {
168 return Err(format!("{authority} resolved to no addresses"));
169 }
170
171 for address in resolved {
172 if !is_public(address.ip()) {
173 return Err(format!(
174 "{authority} resolves to {}, which is on this machine or its private network",
175 address.ip()
176 ));
177 }
178 }
179
180 Ok(())
181}
182
183/// A sender that records what it was asked to deliver and answers from a script.
184///
185/// The counterpart to [`UreqWebhookSender`], and what lets the delivery use case be
186/// tested without a listening socket. The recorded requests are what a test asserts the
187/// signature and headers on.
188#[derive(Debug, Default, Clone)]
189pub struct InMemoryWebhookSender {
190 sent: Arc<Mutex<Vec<WebhookRequest>>>,
191 /// One outcome per call, in order. The last one repeats once the script runs out, so
192 /// a test that wants "always fails" writes one entry rather than four.
193 script: Arc<Mutex<Vec<WebhookOutcome>>>,
194}
195
196impl InMemoryWebhookSender {
197 /// A sender that always succeeds.
198 pub fn new() -> Self {
199 Self::default()
200 }
201
202 /// A sender that answers with these outcomes in order, repeating the last.
203 pub fn scripted(outcomes: Vec<WebhookOutcome>) -> Self {
204 Self {
205 sent: Arc::default(),
206 script: Arc::new(Mutex::new(outcomes)),
207 }
208 }
209
210 /// Everything it was asked to send, in order.
211 pub fn sent(&self) -> Vec<WebhookRequest> {
212 self.sent.lock().expect("lock poisoned").clone()
213 }
214}
215
216impl WebhookSender for InMemoryWebhookSender {
217 async fn send(&self, request: WebhookRequest) -> WebhookOutcome {
218 let mut sent = self.sent.lock().expect("lock poisoned");
219 sent.push(request);
220
221 let script = self.script.lock().expect("lock poisoned");
222
223 match script.get(sent.len() - 1).or_else(|| script.last()) {
224 Some(outcome) => outcome.clone(),
225 None => WebhookOutcome {
226 status: Some(200),
227 body: String::new(),
228 duration: Duration::from_millis(1),
229 },
230 }
231 }
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237
238 #[test]
239 fn a_name_that_resolves_to_a_private_address_is_refused() {
240 // The half `WebhookUrl` cannot cover: the check is on what the name *resolves
241 // to*, not on how it is spelled. `localhost` stands in for a public name with a
242 // private answer because it needs no resolver to be reachable — the real case
243 // is a domain whose A record points inside the network.
244 assert!(check_resolves_publicly("http://localhost:8080/hook").is_err());
245 assert!(check_resolves_publicly("http://localhost/hook").is_err());
246 }
247
248 #[test]
249 fn a_url_with_no_scheme_never_reaches_a_socket() {
250 assert!(check_resolves_publicly("example.com/hook").is_err());
251 }
252
253 #[test]
254 fn a_name_that_resolves_to_nothing_is_refused_rather_than_dialled() {
255 assert!(check_resolves_publicly("https://this-name-does-not-exist.invalid/hook").is_err());
256 }
257
258 #[tokio::test]
259 async fn the_fake_answers_a_script_in_order_and_then_repeats_it() {
260 let outcome = |status| WebhookOutcome {
261 status,
262 body: String::new(),
263 duration: Duration::from_millis(1),
264 };
265
266 let sender = InMemoryWebhookSender::scripted(vec![outcome(None), outcome(Some(200))]);
267
268 let request = || WebhookRequest {
269 url: "https://example.com/hook".to_owned(),
270 headers: Vec::new(),
271 body: b"{}".to_vec(),
272 };
273
274 assert_eq!(sender.send(request()).await.status, None);
275 assert_eq!(sender.send(request()).await.status, Some(200));
276 assert_eq!(sender.send(request()).await.status, Some(200));
277 assert_eq!(sender.sent().len(), 3);
278 }
279}