| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | use std::{fmt, net::IpAddr, time::SystemTime}; |
| 12 | |
| 13 | use hmac::{Hmac, Mac}; |
| 14 | use sha2::Sha256; |
| 15 | |
| 16 | use super::{DomainError, RepoId, WebhookId}; |
| 17 | |
| 18 | |
| 19 | const SECRET_PREFIX: &str = "steid_whs_"; |
| 20 | |
| 21 | type HmacSha256 = Hmac<Sha256>; |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | #[derive(Clone, PartialEq, Eq)] |
| 28 | pub struct WebhookSecret(String); |
| 29 | |
| 30 | impl WebhookSecret { |
| 31 | |
| 32 | const BYTES: usize = 32; |
| 33 | |
| 34 | |
| 35 | pub fn generate() -> Self { |
| 36 | use rand::Rng; |
| 37 | |
| 38 | let mut bytes = [0u8; Self::BYTES]; |
| 39 | rand::rng().fill_bytes(&mut bytes); |
| 40 | |
| 41 | let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect(); |
| 42 | |
| 43 | Self(format!("{SECRET_PREFIX}{random}")) |
| 44 | } |
| 45 | |
| 46 | |
| 47 | pub fn from_trusted(value: impl Into<String>) -> Self { |
| 48 | Self(value.into()) |
| 49 | } |
| 50 | |
| 51 | |
| 52 | pub fn reveal(&self) -> &str { |
| 53 | &self.0 |
| 54 | } |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | pub fn sign(&self, body: &[u8]) -> String { |
| 63 | |
| 64 | let mut mac = HmacSha256::new_from_slice(self.0.as_bytes()).expect("hmac takes any key"); |
| 65 | mac.update(body); |
| 66 | |
| 67 | let digest = mac.finalize().into_bytes(); |
| 68 | |
| 69 | format!( |
| 70 | "sha256={}", |
| 71 | digest |
| 72 | .iter() |
| 73 | .map(|byte| format!("{byte:02x}")) |
| 74 | .collect::<String>() |
| 75 | ) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | impl fmt::Debug for WebhookSecret { |
| 80 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 81 | f.write_str("WebhookSecret(redacted)") |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 101 | pub struct WebhookUrl(String); |
| 102 | |
| 103 | impl WebhookUrl { |
| 104 | |
| 105 | pub const MAX_LEN: usize = 2000; |
| 106 | |
| 107 | |
| 108 | const BLOCKED_NAMES: [&'static str; 3] = |
| 109 | ["localhost", "localhost.localdomain", "ip6-localhost"]; |
| 110 | |
| 111 | |
| 112 | |
| 113 | const BLOCKED_SUFFIXES: [&'static str; 4] = |
| 114 | [".localhost", ".local", ".internal", ".localdomain"]; |
| 115 | |
| 116 | pub fn new(value: impl AsRef<str>) -> Result<Self, DomainError> { |
| 117 | let value = value.as_ref().trim(); |
| 118 | |
| 119 | if value.is_empty() { |
| 120 | return Err(invalid("give the hook a URL to POST to")); |
| 121 | } |
| 122 | |
| 123 | if value.len() > Self::MAX_LEN { |
| 124 | return Err(invalid(format!( |
| 125 | "a URL is at most {} characters", |
| 126 | Self::MAX_LEN |
| 127 | ))); |
| 128 | } |
| 129 | |
| 130 | if value.chars().any(|c| c.is_ascii_control() || c == ' ') { |
| 131 | return Err(invalid("a URL cannot contain spaces or control characters")); |
| 132 | } |
| 133 | |
| 134 | let Some((scheme, rest)) = value.split_once("://") else { |
| 135 | return Err(invalid("a URL starts with http:// or https://")); |
| 136 | }; |
| 137 | |
| 138 | if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") { |
| 139 | return Err(invalid( |
| 140 | "only http:// and https:// URLs can be delivered to", |
| 141 | )); |
| 142 | } |
| 143 | |
| 144 | let authority = rest |
| 145 | .split(['/', '?', '#']) |
| 146 | .next() |
| 147 | .expect("split always yields one part"); |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | if authority.contains('@') { |
| 153 | return Err(invalid("a URL cannot carry credentials")); |
| 154 | } |
| 155 | |
| 156 | let host = host_of(authority)?; |
| 157 | |
| 158 | if host.is_empty() { |
| 159 | return Err(invalid("a URL needs a host")); |
| 160 | } |
| 161 | |
| 162 | if let Ok(address) = host.parse::<IpAddr>() { |
| 163 | if !is_public(address) { |
| 164 | return Err(invalid( |
| 165 | "that address is on this machine or its private network", |
| 166 | )); |
| 167 | } |
| 168 | } else { |
| 169 | let lowered = host.to_ascii_lowercase(); |
| 170 | |
| 171 | if Self::BLOCKED_NAMES.contains(&lowered.as_str()) |
| 172 | || Self::BLOCKED_SUFFIXES |
| 173 | .iter() |
| 174 | .any(|suffix| lowered.ends_with(suffix)) |
| 175 | { |
| 176 | return Err(invalid("that host names this machine or its own network")); |
| 177 | } |
| 178 | |
| 179 | if !lowered.contains('.') { |
| 180 | return Err(invalid( |
| 181 | "that host has no domain, so it can only name something local", |
| 182 | )); |
| 183 | } |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | let last = lowered.rsplit('.').next().unwrap_or_default(); |
| 191 | |
| 192 | if last.starts_with(|c: char| c.is_ascii_digit()) { |
| 193 | return Err(invalid( |
| 194 | "that is not a host name — write an address out in full", |
| 195 | )); |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | Ok(Self(value.to_owned())) |
| 200 | } |
| 201 | |
| 202 | |
| 203 | pub fn from_trusted(value: impl Into<String>) -> Self { |
| 204 | Self(value.into()) |
| 205 | } |
| 206 | |
| 207 | pub fn as_str(&self) -> &str { |
| 208 | &self.0 |
| 209 | } |
| 210 | |
| 211 | |
| 212 | pub fn host(&self) -> &str { |
| 213 | let rest = self.0.split_once("://").map(|(_, rest)| rest).unwrap_or(""); |
| 214 | let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); |
| 215 | |
| 216 | host_of(authority).unwrap_or_default() |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | impl fmt::Display for WebhookUrl { |
| 221 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 222 | f.write_str(&self.0) |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | |
| 227 | fn host_of(authority: &str) -> Result<&str, DomainError> { |
| 228 | if let Some(rest) = authority.strip_prefix('[') { |
| 229 | let Some((host, after)) = rest.split_once(']') else { |
| 230 | return Err(invalid("that IPv6 address is missing its closing bracket")); |
| 231 | }; |
| 232 | |
| 233 | check_port(after.strip_prefix(':'))?; |
| 234 | |
| 235 | return Ok(host); |
| 236 | } |
| 237 | |
| 238 | match authority.split_once(':') { |
| 239 | Some((host, port)) => { |
| 240 | check_port(Some(port))?; |
| 241 | Ok(host) |
| 242 | } |
| 243 | None => Ok(authority), |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | fn check_port(port: Option<&str>) -> Result<(), DomainError> { |
| 248 | let Some(port) = port else { |
| 249 | return Ok(()); |
| 250 | }; |
| 251 | |
| 252 | match port.parse::<u16>() { |
| 253 | Ok(port) if port > 0 => Ok(()), |
| 254 | _ => Err(invalid("that is not a port number")), |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | |
| 262 | |
| 263 | pub fn is_public(address: IpAddr) -> bool { |
| 264 | match address { |
| 265 | IpAddr::V4(v4) => { |
| 266 | !(v4.is_loopback() |
| 267 | || v4.is_private() |
| 268 | || v4.is_link_local() |
| 269 | || v4.is_broadcast() |
| 270 | || v4.is_multicast() |
| 271 | || v4.is_unspecified() |
| 272 | || v4.is_documentation() |
| 273 | |
| 274 | |
| 275 | || (v4.octets()[0] == 100 && (64..128).contains(&v4.octets()[1])) |
| 276 | |
| 277 | || v4.octets()[..3] == [192, 0, 0] |
| 278 | |
| 279 | || v4.octets()[0] >= 240) |
| 280 | } |
| 281 | IpAddr::V6(v6) => { |
| 282 | if v6.is_loopback() || v6.is_multicast() || v6.is_unspecified() { |
| 283 | return false; |
| 284 | } |
| 285 | |
| 286 | |
| 287 | |
| 288 | if let Some(v4) = v6.to_ipv4_mapped() { |
| 289 | return is_public(IpAddr::V4(v4)); |
| 290 | } |
| 291 | |
| 292 | let first = v6.segments()[0]; |
| 293 | |
| 294 | |
| 295 | !((first & 0xfe00) == 0xfc00 || (first & 0xffc0) == 0xfe80) |
| 296 | } |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | fn invalid(reason: impl Into<String>) -> DomainError { |
| 301 | DomainError::validation("URL", reason) |
| 302 | } |
| 303 | |
| 304 | |
| 305 | |
| 306 | |
| 307 | |
| 308 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 309 | pub struct Webhook { |
| 310 | pub id: WebhookId, |
| 311 | pub repo_id: RepoId, |
| 312 | pub url: WebhookUrl, |
| 313 | pub secret: WebhookSecret, |
| 314 | |
| 315 | |
| 316 | pub active: bool, |
| 317 | pub created_at: SystemTime, |
| 318 | } |
| 319 | |
| 320 | impl Webhook { |
| 321 | |
| 322 | pub fn new( |
| 323 | id: WebhookId, |
| 324 | repo_id: RepoId, |
| 325 | url: impl AsRef<str>, |
| 326 | secret: WebhookSecret, |
| 327 | created_at: SystemTime, |
| 328 | ) -> Result<Self, DomainError> { |
| 329 | Ok(Self { |
| 330 | id, |
| 331 | repo_id, |
| 332 | url: WebhookUrl::new(url)?, |
| 333 | secret, |
| 334 | active: true, |
| 335 | created_at, |
| 336 | }) |
| 337 | } |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | |
| 344 | |
| 345 | pub fn from_trusted( |
| 346 | id: WebhookId, |
| 347 | repo_id: RepoId, |
| 348 | url: WebhookUrl, |
| 349 | secret: WebhookSecret, |
| 350 | active: bool, |
| 351 | created_at: SystemTime, |
| 352 | ) -> Self { |
| 353 | Self { |
| 354 | id, |
| 355 | repo_id, |
| 356 | url, |
| 357 | secret, |
| 358 | active, |
| 359 | created_at, |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | #[cfg(test)] |
| 365 | mod tests { |
| 366 | use super::*; |
| 367 | |
| 368 | #[test] |
| 369 | fn a_generated_secret_is_recognisable_and_full_width() { |
| 370 | let secret = WebhookSecret::generate(); |
| 371 | |
| 372 | assert!(secret.reveal().starts_with("steid_whs_")); |
| 373 | assert_eq!( |
| 374 | secret.reveal().len(), |
| 375 | "steid_whs_".len() + WebhookSecret::BYTES * 2 |
| 376 | ); |
| 377 | assert_ne!( |
| 378 | WebhookSecret::generate().reveal(), |
| 379 | WebhookSecret::generate().reveal() |
| 380 | ); |
| 381 | } |
| 382 | |
| 383 | #[test] |
| 384 | fn a_secret_never_reaches_debug_output() { |
| 385 | let secret = WebhookSecret::generate(); |
| 386 | |
| 387 | assert_eq!(format!("{secret:?}"), "WebhookSecret(redacted)"); |
| 388 | |
| 389 | let hook = Webhook::new( |
| 390 | WebhookId::generate(), |
| 391 | RepoId::generate(), |
| 392 | "https://example.com/hook", |
| 393 | secret.clone(), |
| 394 | SystemTime::UNIX_EPOCH, |
| 395 | ) |
| 396 | .expect("valid"); |
| 397 | |
| 398 | assert!(!format!("{hook:?}").contains(secret.reveal())); |
| 399 | } |
| 400 | |
| 401 | #[test] |
| 402 | fn signing_matches_a_known_hmac() { |
| 403 | |
| 404 | |
| 405 | let secret = WebhookSecret::from_trusted("key"); |
| 406 | |
| 407 | assert_eq!( |
| 408 | secret.sign(b"The quick brown fox jumps over the lazy dog"), |
| 409 | "sha256=f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8" |
| 410 | ); |
| 411 | } |
| 412 | |
| 413 | #[test] |
| 414 | fn signing_is_stable_and_body_dependent() { |
| 415 | let secret = WebhookSecret::generate(); |
| 416 | |
| 417 | assert_eq!(secret.sign(b"{}"), secret.sign(b"{}")); |
| 418 | assert_ne!(secret.sign(b"{}"), secret.sign(b"{ }")); |
| 419 | assert_ne!(secret.sign(b"{}"), WebhookSecret::generate().sign(b"{}")); |
| 420 | } |
| 421 | |
| 422 | #[test] |
| 423 | fn ordinary_public_urls_are_accepted() { |
| 424 | for url in [ |
| 425 | "https://example.com/hook", |
| 426 | "http://example.com:8080/a/b?c=d", |
| 427 | "https://hooks.example.co.uk/services/T/B/x", |
| 428 | "https://93.184.216.34/hook", |
| 429 | "https://[2606:2800:220:1:248:1893:25c8:1946]/hook", |
| 430 | ] { |
| 431 | assert!(WebhookUrl::new(url).is_ok(), "{url} should be accepted"); |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | #[test] |
| 436 | fn only_http_urls_can_be_delivered_to() { |
| 437 | for url in [ |
| 438 | "file:///etc/passwd", |
| 439 | "gopher://example.com/", |
| 440 | "ftp://example.com/", |
| 441 | "example.com/hook", |
| 442 | "", |
| 443 | ] { |
| 444 | assert!(WebhookUrl::new(url).is_err(), "{url:?} should be refused"); |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | #[test] |
| 449 | fn nothing_on_this_machine_or_its_network_can_be_delivered_to() { |
| 450 | |
| 451 | |
| 452 | for url in [ |
| 453 | "http://127.0.0.1:3000/hook", |
| 454 | "http://127.1/hook", |
| 455 | "http://2130706433/hook", |
| 456 | "http://0177.0.0.1/hook", |
| 457 | "http://localhost:3000/hook", |
| 458 | "http://LOCALHOST/hook", |
| 459 | "http://steid.local/hook", |
| 460 | "http://db.internal/hook", |
| 461 | "http://redis/hook", |
| 462 | "http://10.0.0.5/hook", |
| 463 | "http://192.168.1.1/hook", |
| 464 | "http://172.16.0.1/hook", |
| 465 | "http://100.64.0.1/hook", |
| 466 | "http://169.254.169.254/latest/meta-data/", |
| 467 | "http://0.0.0.0/hook", |
| 468 | "http://[::1]/hook", |
| 469 | "http://[fe80::1]/hook", |
| 470 | "http://[fd00::1]/hook", |
| 471 | "http://[::ffff:127.0.0.1]/hook", |
| 472 | ] { |
| 473 | assert!(WebhookUrl::new(url).is_err(), "{url} should be refused"); |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | #[test] |
| 478 | fn credentials_in_the_authority_are_refused() { |
| 479 | assert!(WebhookUrl::new("https://user:pass@example.com/hook").is_err()); |
| 480 | assert!(WebhookUrl::new("https://example.com@127.0.0.1/hook").is_err()); |
| 481 | } |
| 482 | |
| 483 | #[test] |
| 484 | fn a_url_that_is_not_addressable_is_refused() { |
| 485 | assert!(WebhookUrl::new("https://example.com:0/hook").is_err()); |
| 486 | assert!(WebhookUrl::new("https://example.com:notaport/hook").is_err()); |
| 487 | assert!(WebhookUrl::new("https://[::1/hook").is_err()); |
| 488 | assert!(WebhookUrl::new("https:///hook").is_err()); |
| 489 | assert!(WebhookUrl::new(format!("https://example.com/{}", "a".repeat(2000))).is_err()); |
| 490 | } |
| 491 | |
| 492 | #[test] |
| 493 | fn the_host_is_readable_back_for_the_adapters_second_check() { |
| 494 | assert_eq!( |
| 495 | WebhookUrl::new("https://example.com:8443/hook") |
| 496 | .expect("valid") |
| 497 | .host(), |
| 498 | "example.com" |
| 499 | ); |
| 500 | assert_eq!( |
| 501 | WebhookUrl::new("https://[2606:2800:220:1:248:1893:25c8:1946]:8443/hook") |
| 502 | .expect("valid") |
| 503 | .host(), |
| 504 | "2606:2800:220:1:248:1893:25c8:1946" |
| 505 | ); |
| 506 | } |
| 507 | |
| 508 | #[test] |
| 509 | fn a_new_hook_is_active() { |
| 510 | let hook = Webhook::new( |
| 511 | WebhookId::generate(), |
| 512 | RepoId::generate(), |
| 513 | "https://example.com/hook", |
| 514 | WebhookSecret::generate(), |
| 515 | SystemTime::UNIX_EPOCH, |
| 516 | ) |
| 517 | .expect("valid"); |
| 518 | |
| 519 | assert!(hook.active); |
| 520 | } |
| 521 | } |