| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | use std::{ |
| 30 | fmt, |
| 31 | io::Read, |
| 32 | net::IpAddr, |
| 33 | sync::{Arc, Mutex}, |
| 34 | time::{Duration, Instant}, |
| 35 | }; |
| 36 | |
| 37 | use ureq::{ |
| 38 | config::Config, |
| 39 | http::Uri, |
| 40 | unversioned::{ |
| 41 | resolver::{DefaultResolver, ResolvedSocketAddrs, Resolver}, |
| 42 | transport::{DefaultConnector, NextTimeout}, |
| 43 | }, |
| 44 | }; |
| 45 | |
| 46 | use crate::{ |
| 47 | application::port::{WebhookOutcome, WebhookRequest, WebhookSender}, |
| 48 | domain::{PrivateTargets, is_public}, |
| 49 | infrastructure::metrics::{DeliveryOutcome, metrics}, |
| 50 | }; |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | const TIMEOUT: Duration = Duration::from_secs(10); |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | const MAX_RESPONSE_BYTES: u64 = 8 * 1024; |
| 64 | |
| 65 | |
| 66 | #[derive(Debug, Clone, Default)] |
| 67 | pub struct UreqWebhookSender { |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | targets: PrivateTargets, |
| 74 | } |
| 75 | |
| 76 | impl UreqWebhookSender { |
| 77 | pub fn new(targets: PrivateTargets) -> Self { |
| 78 | Self { targets } |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | impl WebhookSender for UreqWebhookSender { |
| 83 | async fn send(&self, request: WebhookRequest) -> WebhookOutcome { |
| 84 | let started = Instant::now(); |
| 85 | |
| 86 | |
| 87 | |
| 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 | |
| 104 | |
| 105 | |
| 106 | metrics().record_delivery(DeliveryOutcome::of(outcome.status)); |
| 107 | |
| 108 | outcome |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | fn 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 | |
| 138 | |
| 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 | |
| 148 | |
| 149 | |
| 150 | Err(ureq::Error::Other(error)) if error.is::<Refused>() => outcome(None, error.to_string()), |
| 151 | |
| 152 | |
| 153 | |
| 154 | Err(error) => outcome(None, error.to_string()), |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | fn agent(resolver: impl Resolver, targets: PrivateTargets) -> ureq::Agent { |
| 164 | let config = ureq::Agent::config_builder() |
| 165 | .timeout_global(Some(TIMEOUT)) |
| 166 | |
| 167 | |
| 168 | |
| 169 | .http_status_as_error(false) |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | .max_redirects(0) |
| 178 | |
| 179 | |
| 180 | |
| 181 | |
| 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 | |
| 196 | |
| 197 | |
| 198 | |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | #[derive(Debug)] |
| 211 | struct PublicOnly<R: Resolver> { |
| 212 | inner: R, |
| 213 | |
| 214 | |
| 215 | |
| 216 | |
| 217 | targets: PrivateTargets, |
| 218 | } |
| 219 | |
| 220 | impl<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 | |
| 243 | |
| 244 | |
| 245 | |
| 246 | #[derive(Debug)] |
| 247 | struct Refused { |
| 248 | host: String, |
| 249 | address: IpAddr, |
| 250 | } |
| 251 | |
| 252 | impl 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 | |
| 262 | impl std::error::Error for Refused {} |
| 263 | |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | #[derive(Debug, Default, Clone)] |
| 270 | pub struct InMemoryWebhookSender { |
| 271 | sent: Arc<Mutex<Vec<WebhookRequest>>>, |
| 272 | |
| 273 | |
| 274 | script: Arc<Mutex<Vec<WebhookOutcome>>>, |
| 275 | } |
| 276 | |
| 277 | impl InMemoryWebhookSender { |
| 278 | |
| 279 | pub fn new() -> Self { |
| 280 | Self::default() |
| 281 | } |
| 282 | |
| 283 | |
| 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 | |
| 292 | pub fn sent(&self) -> Vec<WebhookRequest> { |
| 293 | self.sent.lock().expect("lock poisoned").clone() |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | impl 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)] |
| 316 | mod tests { |
| 317 | use std::{ |
| 318 | io::{ErrorKind, Write}, |
| 319 | net::{SocketAddr, TcpListener, TcpStream}, |
| 320 | thread, |
| 321 | }; |
| 322 | |
| 323 | use super::*; |
| 324 | |
| 325 | |
| 326 | |
| 327 | |
| 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 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | |
| 344 | |
| 345 | |
| 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 | |
| 381 | |
| 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 | |
| 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 | |
| 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 | |
| 434 | |
| 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 | |
| 450 | |
| 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 | |
| 459 | |
| 460 | |
| 461 | |
| 462 | |
| 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 | |
| 510 | |
| 511 | |
| 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 | } |