| 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 | use std::{ |
| 27 | io::Read, |
| 28 | net::ToSocketAddrs, |
| 29 | sync::{Arc, Mutex}, |
| 30 | time::{Duration, Instant}, |
| 31 | }; |
| 32 | |
| 33 | use crate::{ |
| 34 | application::port::{WebhookOutcome, WebhookRequest, WebhookSender}, |
| 35 | domain::{PrivateTargets, is_public}, |
| 36 | infrastructure::metrics::{DeliveryOutcome, metrics}, |
| 37 | }; |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | const TIMEOUT: Duration = Duration::from_secs(10); |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | const MAX_RESPONSE_BYTES: u64 = 8 * 1024; |
| 51 | |
| 52 | |
| 53 | #[derive(Debug, Clone, Default)] |
| 54 | pub struct UreqWebhookSender { |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | targets: PrivateTargets, |
| 61 | } |
| 62 | |
| 63 | impl UreqWebhookSender { |
| 64 | pub fn new(targets: PrivateTargets) -> Self { |
| 65 | Self { targets } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | impl WebhookSender for UreqWebhookSender { |
| 70 | async fn send(&self, request: WebhookRequest) -> WebhookOutcome { |
| 71 | let started = Instant::now(); |
| 72 | |
| 73 | |
| 74 | |
| 75 | let targets = self.targets; |
| 76 | |
| 77 | let outcome = |
| 78 | match tokio::task::spawn_blocking(move || send_blocking(request, targets)).await { |
| 79 | Ok(outcome) => outcome, |
| 80 | Err(error) => WebhookOutcome { |
| 81 | status: None, |
| 82 | body: format!("delivery task failed: {error}"), |
| 83 | duration: started.elapsed(), |
| 84 | }, |
| 85 | }; |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | metrics().record_delivery(DeliveryOutcome::of(outcome.status)); |
| 91 | |
| 92 | outcome |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | |
| 97 | fn send_blocking(request: WebhookRequest, targets: PrivateTargets) -> WebhookOutcome { |
| 98 | let started = Instant::now(); |
| 99 | |
| 100 | let outcome = |status, body: String| WebhookOutcome { |
| 101 | status, |
| 102 | body, |
| 103 | duration: started.elapsed(), |
| 104 | }; |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | if targets == PrivateTargets::Refused |
| 111 | && let Err(reason) = check_resolves_publicly(&request.url) |
| 112 | { |
| 113 | return outcome(None, reason); |
| 114 | } |
| 115 | |
| 116 | let mut send = agent().post(&request.url); |
| 117 | |
| 118 | for (name, value) in &request.headers { |
| 119 | send = send.header(name.as_str(), value.as_str()); |
| 120 | } |
| 121 | |
| 122 | match send.send(&request.body[..]) { |
| 123 | Ok(mut response) => { |
| 124 | let status = response.status().as_u16(); |
| 125 | let mut body = String::new(); |
| 126 | |
| 127 | |
| 128 | |
| 129 | let _ = response |
| 130 | .body_mut() |
| 131 | .as_reader() |
| 132 | .take(MAX_RESPONSE_BYTES) |
| 133 | .read_to_string(&mut body); |
| 134 | |
| 135 | outcome(Some(status), body) |
| 136 | } |
| 137 | |
| 138 | |
| 139 | |
| 140 | Err(error) => outcome(None, error.to_string()), |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | |
| 145 | |
| 146 | |
| 147 | |
| 148 | fn agent() -> ureq::Agent { |
| 149 | ureq::Agent::config_builder() |
| 150 | .timeout_global(Some(TIMEOUT)) |
| 151 | |
| 152 | |
| 153 | |
| 154 | .http_status_as_error(false) |
| 155 | |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | .max_redirects(0) |
| 163 | .build() |
| 164 | .into() |
| 165 | } |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | fn check_resolves_publicly(url: &str) -> Result<(), String> { |
| 173 | let (scheme, rest) = url.split_once("://").ok_or("that URL has no scheme")?; |
| 174 | let authority = rest.split(['/', '?', '#']).next().unwrap_or_default(); |
| 175 | |
| 176 | let default_port = if scheme.eq_ignore_ascii_case("https") { |
| 177 | 443 |
| 178 | } else { |
| 179 | 80 |
| 180 | }; |
| 181 | |
| 182 | |
| 183 | |
| 184 | let target = if authority.contains(':') && !authority.ends_with(']') { |
| 185 | authority.to_owned() |
| 186 | } else { |
| 187 | format!("{authority}:{default_port}") |
| 188 | }; |
| 189 | |
| 190 | let resolved: Vec<_> = target |
| 191 | .to_socket_addrs() |
| 192 | .map_err(|error| format!("{authority} did not resolve: {error}"))? |
| 193 | .collect(); |
| 194 | |
| 195 | if resolved.is_empty() { |
| 196 | return Err(format!("{authority} resolved to no addresses")); |
| 197 | } |
| 198 | |
| 199 | for address in resolved { |
| 200 | if !is_public(address.ip()) { |
| 201 | return Err(format!( |
| 202 | "{authority} resolves to {}, which is on this machine or its private network", |
| 203 | address.ip() |
| 204 | )); |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | Ok(()) |
| 209 | } |
| 210 | |
| 211 | |
| 212 | |
| 213 | |
| 214 | |
| 215 | |
| 216 | #[derive(Debug, Default, Clone)] |
| 217 | pub struct InMemoryWebhookSender { |
| 218 | sent: Arc<Mutex<Vec<WebhookRequest>>>, |
| 219 | |
| 220 | |
| 221 | script: Arc<Mutex<Vec<WebhookOutcome>>>, |
| 222 | } |
| 223 | |
| 224 | impl InMemoryWebhookSender { |
| 225 | |
| 226 | pub fn new() -> Self { |
| 227 | Self::default() |
| 228 | } |
| 229 | |
| 230 | |
| 231 | pub fn scripted(outcomes: Vec<WebhookOutcome>) -> Self { |
| 232 | Self { |
| 233 | sent: Arc::default(), |
| 234 | script: Arc::new(Mutex::new(outcomes)), |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | |
| 239 | pub fn sent(&self) -> Vec<WebhookRequest> { |
| 240 | self.sent.lock().expect("lock poisoned").clone() |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | impl WebhookSender for InMemoryWebhookSender { |
| 245 | async fn send(&self, request: WebhookRequest) -> WebhookOutcome { |
| 246 | let mut sent = self.sent.lock().expect("lock poisoned"); |
| 247 | sent.push(request); |
| 248 | |
| 249 | let script = self.script.lock().expect("lock poisoned"); |
| 250 | |
| 251 | match script.get(sent.len() - 1).or_else(|| script.last()) { |
| 252 | Some(outcome) => outcome.clone(), |
| 253 | None => WebhookOutcome { |
| 254 | status: Some(200), |
| 255 | body: String::new(), |
| 256 | duration: Duration::from_millis(1), |
| 257 | }, |
| 258 | } |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | #[cfg(test)] |
| 263 | mod tests { |
| 264 | |
| 265 | |
| 266 | |
| 267 | #[test] |
| 268 | fn a_delivery_follows_no_redirects() { |
| 269 | assert_eq!(agent().config().max_redirects(), 0); |
| 270 | } |
| 271 | |
| 272 | use super::*; |
| 273 | |
| 274 | #[test] |
| 275 | fn a_name_that_resolves_to_a_private_address_is_refused() { |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | assert!(check_resolves_publicly("http://localhost:8080/hook").is_err()); |
| 281 | assert!(check_resolves_publicly("http://localhost/hook").is_err()); |
| 282 | } |
| 283 | |
| 284 | #[test] |
| 285 | fn a_url_with_no_scheme_never_reaches_a_socket() { |
| 286 | assert!(check_resolves_publicly("example.com/hook").is_err()); |
| 287 | } |
| 288 | |
| 289 | #[test] |
| 290 | fn a_name_that_resolves_to_nothing_is_refused_rather_than_dialled() { |
| 291 | assert!(check_resolves_publicly("https://this-name-does-not-exist.invalid/hook").is_err()); |
| 292 | } |
| 293 | |
| 294 | #[tokio::test] |
| 295 | async fn the_fake_answers_a_script_in_order_and_then_repeats_it() { |
| 296 | let outcome = |status| WebhookOutcome { |
| 297 | status, |
| 298 | body: String::new(), |
| 299 | duration: Duration::from_millis(1), |
| 300 | }; |
| 301 | |
| 302 | let sender = InMemoryWebhookSender::scripted(vec![outcome(None), outcome(Some(200))]); |
| 303 | |
| 304 | let request = || WebhookRequest { |
| 305 | url: "https://example.com/hook".to_owned(), |
| 306 | headers: Vec::new(), |
| 307 | body: b"{}".to_vec(), |
| 308 | }; |
| 309 | |
| 310 | assert_eq!(sender.send(request()).await.status, None); |
| 311 | assert_eq!(sender.send(request()).await.status, Some(200)); |
| 312 | assert_eq!(sender.send(request()).await.status, Some(200)); |
| 313 | assert_eq!(sender.sent().len(), 3); |
| 314 | } |
| 315 | } |