| 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::{PrivateTargets, 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 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | targets: PrivateTargets, |
| 55 | } |
| 56 | |
| 57 | impl UreqWebhookSender { |
| 58 | pub fn new(targets: PrivateTargets) -> Self { |
| 59 | Self { targets } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | impl WebhookSender for UreqWebhookSender { |
| 64 | async fn send(&self, request: WebhookRequest) -> WebhookOutcome { |
| 65 | let started = Instant::now(); |
| 66 | |
| 67 | |
| 68 | |
| 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 | |
| 83 | fn 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 | |
| 93 | |
| 94 | |
| 95 | |
| 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 | |
| 105 | |
| 106 | |
| 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 | |
| 123 | |
| 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 | |
| 133 | |
| 134 | |
| 135 | Err(error) => outcome(None, error.to_string()), |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | |
| 144 | fn 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 | |
| 155 | |
| 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 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | #[derive(Debug, Default, Clone)] |
| 189 | pub struct InMemoryWebhookSender { |
| 190 | sent: Arc<Mutex<Vec<WebhookRequest>>>, |
| 191 | |
| 192 | |
| 193 | script: Arc<Mutex<Vec<WebhookOutcome>>>, |
| 194 | } |
| 195 | |
| 196 | impl InMemoryWebhookSender { |
| 197 | |
| 198 | pub fn new() -> Self { |
| 199 | Self::default() |
| 200 | } |
| 201 | |
| 202 | |
| 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 | |
| 211 | pub fn sent(&self) -> Vec<WebhookRequest> { |
| 212 | self.sent.lock().expect("lock poisoned").clone() |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | impl 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)] |
| 235 | mod tests { |
| 236 | use super::*; |
| 237 | |
| 238 | #[test] |
| 239 | fn a_name_that_resolves_to_a_private_address_is_refused() { |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 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 | } |