| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | use std::{ |
| 22 | io::Read, |
| 23 | net::ToSocketAddrs, |
| 24 | sync::{Arc, Mutex}, |
| 25 | time::{Duration, Instant}, |
| 26 | }; |
| 27 | |
| 28 | use crate::{ |
| 29 | application::port::{WebhookOutcome, WebhookRequest, WebhookSender}, |
| 30 | domain::is_public, |
| 31 | }; |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | const TIMEOUT: Duration = Duration::from_secs(10); |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | const MAX_RESPONSE_BYTES: u64 = 8 * 1024; |
| 45 | |
| 46 | |
| 47 | #[derive(Debug, Clone, Default)] |
| 48 | pub struct UreqWebhookSender; |
| 49 | |
| 50 | impl UreqWebhookSender { |
| 51 | pub fn new() -> Self { |
| 52 | Self |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | impl WebhookSender for UreqWebhookSender { |
| 57 | async fn send(&self, request: WebhookRequest) -> WebhookOutcome { |
| 58 | let started = Instant::now(); |
| 59 | |
| 60 | |
| 61 | |
| 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 | |
| 74 | fn 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 | |
| 90 | |
| 91 | |
| 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 | |
| 108 | |
| 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 | |
| 118 | |
| 119 | |
| 120 | Err(error) => outcome(None, error.to_string()), |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | fn 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 | |
| 140 | |
| 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 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | #[derive(Debug, Default, Clone)] |
| 174 | pub struct InMemoryWebhookSender { |
| 175 | sent: Arc<Mutex<Vec<WebhookRequest>>>, |
| 176 | |
| 177 | |
| 178 | script: Arc<Mutex<Vec<WebhookOutcome>>>, |
| 179 | } |
| 180 | |
| 181 | impl InMemoryWebhookSender { |
| 182 | |
| 183 | pub fn new() -> Self { |
| 184 | Self::default() |
| 185 | } |
| 186 | |
| 187 | |
| 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 | |
| 196 | pub fn sent(&self) -> Vec<WebhookRequest> { |
| 197 | self.sent.lock().expect("lock poisoned").clone() |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | impl 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)] |
| 220 | mod tests { |
| 221 | use super::*; |
| 222 | |
| 223 | #[test] |
| 224 | fn a_name_that_resolves_to_a_private_address_is_refused() { |
| 225 | |
| 226 | |
| 227 | |
| 228 | |
| 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 | } |