steid

@jamesgill /

Rust21.7 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 every address the name resolves to is checked
14//! here — **by the resolver `ureq` dials from**, [`PublicOnly`]. The address checked is
15//! the address connected to.
16//!
17//! That is what closes DNS rebinding (launch 2.18). Until then the host was resolved
18//! and checked first, and `ureq` resolved it again to connect, so a name that answered
19//! public for the check and private for the connection got through — and the response
20//! body came back on the deliveries page. Nothing about the request is set by hand to
21//! make the pin work: `ureq` takes the `Host` header and the TLS server name from the
22//! URL, and only the socket address from the resolver.
23//!
24//! The third piece is that **no redirect is followed** — see [`agent`]. Resolving the
25//! saved URL says nothing about where a `302` would send the next request, so a public
26//! receiver could otherwise walk a delivery into this machine's own network and hand the
27//! response body back through the deliveries page.
28
29use std::{
30 fmt,
31 io::Read,
32 net::IpAddr,
33 sync::{Arc, Mutex},
34 time::{Duration, Instant},
35};
36
37use ureq::{
38 config::Config,
39 http::Uri,
40 unversioned::{
41 resolver::{DefaultResolver, ResolvedSocketAddrs, Resolver},
42 transport::{DefaultConnector, NextTimeout},
43 },
44};
45
46use crate::{
47 application::port::{WebhookOutcome, WebhookRequest, WebhookSender},
48 domain::{PrivateTargets, is_public},
49 infrastructure::metrics::{DeliveryOutcome, metrics},
50};
51
52/// How long one attempt may take, connection through body.
53///
54/// Whole-request rather than per-phase: a receiver that dribbles a response one byte at
55/// a time is the same problem as one that never answers, and the caller is a retry loop
56/// that has somewhere better to be.
57const TIMEOUT: Duration = Duration::from_secs(10);
58
59/// How much of a response body is read.
60///
61/// Read short rather than read-then-truncate: the domain caps what is *stored*, and
62/// without a cap here a hostile endpoint could stream forever inside the timeout.
63const MAX_RESPONSE_BYTES: u64 = 8 * 1024;
64
65/// Webhook delivery over real HTTP.
66#[derive(Debug, Clone, Default)]
67pub struct UreqWebhookSender {
68 /// Whether an address on this machine's own network is dialled.
69 ///
70 /// Carried rather than read from configuration here, because an adapter that reads
71 /// the environment is one that cannot be tested with the setting off. `Refused` is
72 /// the `Default`, so a sender constructed without thinking about it is the safe one.
73 targets: PrivateTargets,
74}
75
76impl UreqWebhookSender {
77 pub fn new(targets: PrivateTargets) -> Self {
78 Self { targets }
79 }
80}
81
82impl WebhookSender for UreqWebhookSender {
83 async fn send(&self, request: WebhookRequest) -> WebhookOutcome {
84 let started = Instant::now();
85
86 // A panic inside the blocking pool must not take the delivery with it silently;
87 // a join error is reported as an outcome like any other failure.
88 let targets = self.targets;
89
90 let outcome = match tokio::task::spawn_blocking(move || {
91 deliver(&agent(DefaultResolver::default(), targets), request)
92 })
93 .await
94 {
95 Ok(outcome) => outcome,
96 Err(error) => WebhookOutcome {
97 status: None,
98 body: format!("delivery task failed: {error}"),
99 duration: started.elapsed(),
100 },
101 };
102
103 // Counted in the adapter rather than in `application::webhook`, which is where the
104 // retry loop lives: the application layer knows nothing of infrastructure, and this
105 // is the one place every attempt — first try and retry alike — actually goes out.
106 metrics().record_delivery(DeliveryOutcome::of(outcome.status));
107
108 outcome
109 }
110}
111
112/// The blocking half, run off the runtime.
113///
114/// Takes the agent rather than building it, so a test can hand it one whose resolver
115/// answers what the test needs — which is the only way to stand in for a name that
116/// resolves differently the second time it is asked.
117fn deliver(agent: &ureq::Agent, request: WebhookRequest) -> WebhookOutcome {
118 let started = Instant::now();
119
120 let outcome = |status, body: String| WebhookOutcome {
121 status,
122 body,
123 duration: started.elapsed(),
124 };
125
126 let mut send = agent.post(&request.url);
127
128 for (name, value) in &request.headers {
129 send = send.header(name.as_str(), value.as_str());
130 }
131
132 match send.send(&request.body[..]) {
133 Ok(mut response) => {
134 let status = response.status().as_u16();
135 let mut body = String::new();
136
137 // Ignoring the read error on purpose: the status is the answer, and a
138 // response whose body could not be read is still a delivery that happened.
139 let _ = response
140 .body_mut()
141 .as_reader()
142 .take(MAX_RESPONSE_BYTES)
143 .read_to_string(&mut body);
144
145 outcome(Some(status), body)
146 }
147 // The resolver's own refusal, in its own words. `ureq` would print it as
148 // "other: …", which reads as though something unexpected happened rather than as
149 // the rule doing its job.
150 Err(ureq::Error::Other(error)) if error.is::<Refused>() => outcome(None, error.to_string()),
151 // No status at all: DNS, a refused connection, TLS, or the timeout. The
152 // library's own words are carried for the same reason `run_git` carries git's —
153 // "delivery failed" sends the next person to read this code instead of the error.
154 Err(error) => outcome(None, error.to_string()),
155 }
156}
157
158/// The client every delivery is made with.
159///
160/// A function rather than an inline builder so the rules below are ones a test can read
161/// back. Generic over the inner resolver only so a test can stand in for DNS; every
162/// delivery passes [`DefaultResolver`].
163fn agent(resolver: impl Resolver, targets: PrivateTargets) -> ureq::Agent {
164 let config = ureq::Agent::config_builder()
165 .timeout_global(Some(TIMEOUT))
166 // A 4xx or 5xx is a *result* here, not an error: it is exactly what the delivery
167 // row exists to record, and the default would collapse it into the same variant
168 // as a refused connection.
169 .http_status_as_error(false)
170 // **No redirects, and this is the third half of the SSRF defence.** `ureq`
171 // follows ten by default, and `PublicOnly` only ever sees the URL that was
172 // saved — so a public host answering `302 Location: http://169.254.169.254/…`
173 // walked the delivery straight past both checks, and the response body came back
174 // onto the deliveries page for whoever asked. A webhook receiver has no business
175 // redirecting: with this at zero the 3xx is recorded as the delivery's own
176 // answer, which is the honest thing to show.
177 .max_redirects(0)
178 // **No proxy, or the resolver below is never asked.** `ureq` reads `HTTPS_PROXY`
179 // and friends from the environment by default, and through a proxy it skips its
180 // resolver entirely and lets the proxy resolve the name — which would put the
181 // whole address check back on the far side of a lookup Steid never sees.
182 .proxy(None)
183 .build();
184
185 ureq::Agent::with_parts(
186 config,
187 DefaultConnector::default(),
188 PublicOnly {
189 inner: resolver,
190 targets,
191 },
192 )
193}
194
195/// A resolver that refuses any answer inside this machine's own network.
196///
197/// Wrapped around the resolver `ureq` connects from, rather than run beside it, so the
198/// address checked is the address dialled. A separate lookup before the request — what
199/// this replaced — answers for *that* lookup only: a name with a short TTL can answer
200/// public to the check and private to the connection a moment later.
201///
202/// **Every address must pass, not merely the first.** A name with both a public and a
203/// private answer is the shape of the attack, and `ureq` tries each address in turn
204/// until one connects — so "whichever came back first" is not a decision worth leaving
205/// to a resolver.
206///
207/// `ureq`'s resolver interface is under its `unversioned` module, which may change in a
208/// minor release. That is accepted rather than pinned around: a change breaks the build
209/// here, and the listener tests below fail if the resolver stops being the one dialled.
210#[derive(Debug)]
211struct PublicOnly<R: Resolver> {
212 inner: R,
213 /// `Allowed` passes every answer through, which is the half of
214 /// `STEID_ALLOW_PRIVATE_WEBHOOKS` the domain cannot provide: a URL that passed
215 /// `WebhookUrl::new_allowing_private` would otherwise be refused here instead, one
216 /// layer later and with no page to say so.
217 targets: PrivateTargets,
218}
219
220impl<R: Resolver> Resolver for PublicOnly<R> {
221 fn resolve(
222 &self,
223 uri: &Uri,
224 config: &Config,
225 timeout: NextTimeout,
226 ) -> Result<ResolvedSocketAddrs, ureq::Error> {
227 let addresses = self.inner.resolve(uri, config, timeout)?;
228
229 if self.targets == PrivateTargets::Refused
230 && let Some(private) = addresses.iter().find(|address| !is_public(address.ip()))
231 {
232 return Err(ureq::Error::Other(Box::new(Refused {
233 host: uri.host().unwrap_or_default().to_owned(),
234 address: private.ip(),
235 })));
236 }
237
238 Ok(addresses)
239 }
240}
241
242/// A delivery refused because its host resolved inside this machine's own network.
243///
244/// A type of its own so [`deliver`] can tell the refusal apart from every other way a
245/// connection fails, and record it in its own words.
246#[derive(Debug)]
247struct Refused {
248 host: String,
249 address: IpAddr,
250}
251
252impl fmt::Display for Refused {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254 write!(
255 f,
256 "{} resolves to {}, which is on this machine or its private network",
257 self.host, self.address
258 )
259 }
260}
261
262impl std::error::Error for Refused {}
263
264/// A sender that records what it was asked to deliver and answers from a script.
265///
266/// The counterpart to [`UreqWebhookSender`], and what lets the delivery use case be
267/// tested without a listening socket. The recorded requests are what a test asserts the
268/// signature and headers on.
269#[derive(Debug, Default, Clone)]
270pub struct InMemoryWebhookSender {
271 sent: Arc<Mutex<Vec<WebhookRequest>>>,
272 /// One outcome per call, in order. The last one repeats once the script runs out, so
273 /// a test that wants "always fails" writes one entry rather than four.
274 script: Arc<Mutex<Vec<WebhookOutcome>>>,
275}
276
277impl InMemoryWebhookSender {
278 /// A sender that always succeeds.
279 pub fn new() -> Self {
280 Self::default()
281 }
282
283 /// A sender that answers with these outcomes in order, repeating the last.
284 pub fn scripted(outcomes: Vec<WebhookOutcome>) -> Self {
285 Self {
286 sent: Arc::default(),
287 script: Arc::new(Mutex::new(outcomes)),
288 }
289 }
290
291 /// Everything it was asked to send, in order.
292 pub fn sent(&self) -> Vec<WebhookRequest> {
293 self.sent.lock().expect("lock poisoned").clone()
294 }
295}
296
297impl WebhookSender for InMemoryWebhookSender {
298 async fn send(&self, request: WebhookRequest) -> WebhookOutcome {
299 let mut sent = self.sent.lock().expect("lock poisoned");
300 sent.push(request);
301
302 let script = self.script.lock().expect("lock poisoned");
303
304 match script.get(sent.len() - 1).or_else(|| script.last()) {
305 Some(outcome) => outcome.clone(),
306 None => WebhookOutcome {
307 status: Some(200),
308 body: String::new(),
309 duration: Duration::from_millis(1),
310 },
311 }
312 }
313}
314
315#[cfg(test)]
316mod tests {
317 use std::{
318 io::{ErrorKind, Write},
319 net::{SocketAddr, TcpListener, TcpStream},
320 thread,
321 };
322
323 use super::*;
324
325 /// The redirect hole this closed. `ureq`'s default is ten, and the address check
326 /// only ever sees the URL that was saved — so a public receiver answering a 302 to
327 /// `169.254.169.254` reached it, and its body came back onto the deliveries page.
328 #[test]
329 fn a_delivery_follows_no_redirects() {
330 assert_eq!(
331 agent(DefaultResolver::default(), PrivateTargets::Refused)
332 .config()
333 .max_redirects(),
334 0
335 );
336 }
337
338 /// Through a proxy `ureq` never asks its resolver, so the address check would never
339 /// run. `ureq` takes a proxy from the environment by default; this is the setting
340 /// that stops it.
341 ///
342 /// The environment of a test process cannot be changed without `unsafe` (Rust
343 /// 2024), so the test runs itself again as a child with `HTTPS_PROXY` set, and the
344 /// child makes the claim. Without that it would pass on any machine with no proxy
345 /// configured, whether or not the agent turned the proxy off.
346 #[test]
347 fn a_delivery_ignores_any_proxy_in_the_environment() {
348 const NAME: &str =
349 "infrastructure::webhook::tests::a_delivery_ignores_any_proxy_in_the_environment";
350
351 if std::env::var_os("STEID_TEST_PROXY_CHILD").is_some() {
352 assert!(
353 Config::default().proxy().is_some(),
354 "ureq's own default takes the proxy, which is why the agent must not"
355 );
356 assert!(
357 agent(DefaultResolver::default(), PrivateTargets::Refused)
358 .config()
359 .proxy()
360 .is_none()
361 );
362 return;
363 }
364
365 let output = std::process::Command::new(std::env::current_exe().expect("test binary"))
366 .args(["--exact", NAME, "--test-threads=1"])
367 .env("STEID_TEST_PROXY_CHILD", "1")
368 .env("HTTPS_PROXY", "http://127.0.0.1:9")
369 .output()
370 .expect("run the test binary");
371 let stdout = String::from_utf8_lossy(&output.stdout);
372
373 assert!(
374 output.status.success() && stdout.contains("1 passed"),
375 "the child run failed or ran nothing:\n{stdout}\n{}",
376 String::from_utf8_lossy(&output.stderr)
377 );
378 }
379
380 /// A resolver that answers every name with one address — standing in for the
381 /// second answer a rebinding record gives, the one the connection is made from.
382 #[derive(Debug)]
383 struct AlwaysAnswers(SocketAddr);
384
385 impl Resolver for AlwaysAnswers {
386 fn resolve(
387 &self,
388 _uri: &Uri,
389 _config: &Config,
390 _timeout: NextTimeout,
391 ) -> Result<ResolvedSocketAddrs, ureq::Error> {
392 let mut addresses = self.empty();
393 addresses.push(self.0);
394
395 Ok(addresses)
396 }
397 }
398
399 fn post_to(url: String) -> WebhookRequest {
400 WebhookRequest {
401 url,
402 headers: Vec::new(),
403 body: b"{}".to_vec(),
404 }
405 }
406
407 /// A listener on loopback that does not block the test if nothing ever arrives.
408 fn listener() -> (TcpListener, SocketAddr) {
409 let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback");
410 listener.set_nonblocking(true).expect("nonblocking");
411 let address = listener.local_addr().expect("local address");
412
413 (listener, address)
414 }
415
416 /// The first connection within a few seconds, or `None`.
417 fn accept_within(listener: &TcpListener, wait: Duration) -> Option<TcpStream> {
418 let deadline = Instant::now() + wait;
419
420 while Instant::now() < deadline {
421 match listener.accept() {
422 Ok((stream, _)) => return Some(stream),
423 Err(error) if error.kind() == ErrorKind::WouldBlock => {
424 thread::sleep(Duration::from_millis(10));
425 }
426 Err(error) => panic!("accept failed: {error}"),
427 }
428 }
429
430 None
431 }
432
433 /// The rebinding hole, closed: the resolver the connection is made from refuses a
434 /// private answer, so no socket is opened at all.
435 #[test]
436 fn a_private_answer_is_refused_by_the_resolver_that_dials() {
437 let (listener, address) = listener();
438
439 let outcome = deliver(
440 &agent(AlwaysAnswers(address), PrivateTargets::Refused),
441 post_to(format!("http://hook.test:{}/hook", address.port())),
442 );
443
444 assert_eq!(outcome.status, None);
445 assert_eq!(
446 outcome.body,
447 "hook.test resolves to 127.0.0.1, which is on this machine or its private network"
448 );
449 // A connection would sit in the backlog whether or not anyone accepted it, so
450 // an empty backlog means no connection was made.
451 assert_eq!(
452 listener.accept().map(|_| ()).map_err(|error| error.kind()),
453 Err(ErrorKind::WouldBlock),
454 "nothing may connect to an address the resolver refused"
455 );
456 }
457
458 /// The resolver's answer is what is dialled, and the request still names the host.
459 ///
460 /// `.test` is reserved and never resolves, so the request can only have reached the
461 /// listener through the address the resolver handed over — and the `Host` header is
462 /// still the URL's, so nothing about the request had to be set by hand.
463 #[test]
464 fn the_address_the_resolver_answers_is_the_one_dialled() {
465 let (listener, address) = listener();
466
467 let received = thread::spawn(move || {
468 let mut stream =
469 accept_within(&listener, Duration::from_secs(10)).expect("a connection");
470 stream.set_nonblocking(false).expect("blocking");
471 stream
472 .set_read_timeout(Some(Duration::from_secs(5)))
473 .expect("timeout");
474
475 let mut head = Vec::new();
476 let mut buffer = [0u8; 1024];
477
478 while !head.windows(4).any(|window| window == b"\r\n\r\n") {
479 let read = stream.read(&mut buffer).expect("read the request");
480 if read == 0 {
481 break;
482 }
483 head.extend_from_slice(&buffer[..read]);
484 }
485
486 stream
487 .write_all(
488 b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
489 )
490 .expect("answer");
491
492 String::from_utf8_lossy(&head).into_owned()
493 });
494
495 let outcome = deliver(
496 &agent(AlwaysAnswers(address), PrivateTargets::Allowed),
497 post_to(format!("http://hook.test:{}/hook", address.port())),
498 );
499 let head = received.join().expect("the listener thread");
500
501 assert_eq!(outcome.status, Some(204), "{}", outcome.body);
502 assert!(
503 head.to_ascii_lowercase()
504 .contains(&format!("\r\nhost: hook.test:{}\r\n", address.port())),
505 "expected the URL's host in the request, got {head:?}"
506 );
507 }
508
509 /// The same refusal through the real resolver. `localhost` stands in for a public
510 /// name with a private answer because it needs no DNS to resolve — the real case
511 /// is a domain whose record points inside the network.
512 #[test]
513 fn a_name_that_resolves_to_a_private_address_is_refused() {
514 let (listener, address) = listener();
515
516 let outcome = deliver(
517 &agent(DefaultResolver::default(), PrivateTargets::Refused),
518 post_to(format!("http://localhost:{}/hook", address.port())),
519 );
520
521 assert_eq!(outcome.status, None);
522 assert!(
523 outcome.body.starts_with("localhost resolves to")
524 && outcome.body.contains("on this machine"),
525 "{}",
526 outcome.body
527 );
528 assert_eq!(
529 listener.accept().map(|_| ()).map_err(|error| error.kind()),
530 Err(ErrorKind::WouldBlock)
531 );
532 }
533
534 #[test]
535 fn a_url_with_no_scheme_never_reaches_a_socket() {
536 let outcome = deliver(
537 &agent(DefaultResolver::default(), PrivateTargets::Refused),
538 post_to("example.com/hook".to_owned()),
539 );
540
541 assert_eq!(outcome.status, None);
542 }
543
544 #[test]
545 fn a_name_that_resolves_to_nothing_is_refused_rather_than_dialled() {
546 let outcome = deliver(
547 &agent(DefaultResolver::default(), PrivateTargets::Refused),
548 post_to("https://this-name-does-not-exist.invalid/hook".to_owned()),
549 );
550
551 assert_eq!(outcome.status, None);
552 }
553
554 #[tokio::test]
555 async fn the_fake_answers_a_script_in_order_and_then_repeats_it() {
556 let outcome = |status| WebhookOutcome {
557 status,
558 body: String::new(),
559 duration: Duration::from_millis(1),
560 };
561
562 let sender = InMemoryWebhookSender::scripted(vec![outcome(None), outcome(Some(200))]);
563
564 let request = || WebhookRequest {
565 url: "https://example.com/hook".to_owned(),
566 headers: Vec::new(),
567 body: b"{}".to_vec(),
568 };
569
570 assert_eq!(sender.send(request()).await.status, None);
571 assert_eq!(sender.send(request()).await.status, Some(200));
572 assert_eq!(sender.send(request()).await.status, Some(200));
573 assert_eq!(sender.sent().len(), 3);
574 }
575}