steid

@jamesgill /

steid/src/domain/webhook.rs
Rust17.4 KBCode·Blame·History·Raw
1//! A webhook: where to POST when something happens in a repository, and what to sign
2//! the body with.
3//!
4//! Unlike a personal access token, **the secret is stored in the clear**. It has to be:
5//! the signature is an HMAC computed on every delivery, and a hash cannot produce one.
6//! It is still shown only once, so it does not sit on a page waiting to be
7//! shoulder-surfed, and it authenticates Steid *to the receiver* rather than anyone to
8//! Steid — a leaked hook secret lets someone forge a payload at that one endpoint, not
9//! act as the owner.
10
11use std::{fmt, net::IpAddr, time::SystemTime};
12
13use hmac::{Hmac, Mac};
14use sha2::Sha256;
15
16use super::{DomainError, RepoId, WebhookId};
17
18/// The prefix every hook secret carries, so a leaked one is recognisable as Steid's.
19const SECRET_PREFIX: &str = "steid_whs_";
20
21type HmacSha256 = Hmac<Sha256>;
22
23/// A hook's shared secret, in the clear.
24///
25/// Redacted in `Debug` for the same reason a token is: the value is the whole of the
26/// authentication, and a log line is a place it must not reach.
27#[derive(Clone, PartialEq, Eq)]
28pub struct WebhookSecret(String);
29
30impl WebhookSecret {
31 /// Bytes of entropy, matching [`TokenSecret`](super::TokenSecret).
32 const BYTES: usize = 32;
33
34 /// Mints a fresh secret from the OS random source.
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 /// Wraps a stored secret without generating a new one.
47 pub fn from_trusted(value: impl Into<String>) -> Self {
48 Self(value.into())
49 }
50
51 /// The secret itself, to be shown exactly once and used to sign.
52 pub fn reveal(&self) -> &str {
53 &self.0
54 }
55
56 /// The `sha256=<hex>` signature of a body, as it goes on the wire.
57 ///
58 /// HMAC-SHA-256 over the exact bytes sent, which is what every other forge does and
59 /// what every receiving library already knows how to check. The `sha256=` prefix is
60 /// part of the value rather than implied, so a future second algorithm is a new
61 /// prefix rather than a silent reinterpretation of the same header.
62 pub fn sign(&self, body: &[u8]) -> String {
63 // Infallible for HMAC: the construction accepts a key of any length.
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
79impl fmt::Debug for WebhookSecret {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 f.write_str("WebhookSecret(redacted)")
82 }
83}
84
85/// Where a delivery is POSTed.
86///
87/// Validated here rather than at the call site, because this is the one value in Steid
88/// that makes the server open a connection to an address a *user* chose. That is
89/// server-side request forgery, and the defence is a rule about what the value may name
90/// — not a check somewhere along the way that a later caller can forget.
91///
92/// What is refused: anything but `http`/`https`, credentials in the authority, and any
93/// host that names the machine Steid runs on or the network it sits in — loopback,
94/// private ranges, link-local (which includes the cloud metadata endpoint at
95/// `169.254.169.254`), and the names that conventionally resolve to them.
96///
97/// **This is a syntactic rule and cannot be the whole defence**: a public name can
98/// resolve to a private address. The sending adapter re-checks the resolved address, so
99/// this is the cheap half, made at the moment a person can be told why.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct WebhookUrl(String);
102
103impl WebhookUrl {
104 /// Well past any real endpoint, and a bound on what goes in a row.
105 pub const MAX_LEN: usize = 2000;
106
107 /// Host names that name this machine by convention rather than by address.
108 const BLOCKED_NAMES: [&'static str; 3] =
109 ["localhost", "localhost.localdomain", "ip6-localhost"];
110
111 /// Suffixes that resolve inside the local network by convention: mDNS, and the
112 /// spellings container and cloud platforms use for their own services.
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 // A URL carrying credentials is refused rather than stripped: `user@host` is
150 // also how a parser can be confused into connecting somewhere other than where
151 // the value appears to name.
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 // A real name's last label is a TLD, which is never numeric. This is what
186 // catches the short and packed spellings of an address that `IpAddr` will
187 // not parse but a resolver will happily accept: `127.1`, `2130706433`,
188 // `0177.0.0.1`, `0x7f.1`. Refusing by shape beats enumerating the
189 // encodings.
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 /// Wraps a URL already known to have passed the rules above.
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 /// The host, for the adapter's second check against what it resolves to.
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
220impl fmt::Display for WebhookUrl {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 f.write_str(&self.0)
223 }
224}
225
226/// Pulls the host out of an authority, unwrapping an IPv6 literal's brackets.
227fn 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
247fn 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/// Whether an address is one Steid will connect to.
259///
260/// Everything reachable only from this machine or its own network is refused. Named as
261/// a positive so a range nobody thought about is refused rather than allowed — the
262/// safer default when the value comes from a form.
263pub 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 // 100.64.0.0/10, carrier-grade NAT — and what container runtimes and
274 // Tailscale hand out.
275 || (v4.octets()[0] == 100 && (64..128).contains(&v4.octets()[1]))
276 // 192.0.0.0/24, IETF protocol assignments.
277 || v4.octets()[..3] == [192, 0, 0]
278 // 240.0.0.0/4, reserved.
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 // An IPv4 address wearing an IPv6 costume resolves to the same host, so it
287 // is judged by the IPv4 rules rather than escaping them.
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 // fc00::/7 unique-local, fe80::/10 link-local.
295 !((first & 0xfe00) == 0xfc00 || (first & 0xffc0) == 0xfe80)
296 }
297 }
298}
299
300fn invalid(reason: impl Into<String>) -> DomainError {
301 DomainError::validation("URL", reason)
302}
303
304/// A webhook, as recorded.
305///
306/// Belongs to a repository rather than to a user: it is the repository's pushes it
307/// reacts to, and it survives the person who added it changing role.
308#[derive(Debug, Clone, PartialEq, Eq)]
309pub struct Webhook {
310 pub id: WebhookId,
311 pub repo_id: RepoId,
312 pub url: WebhookUrl,
313 pub secret: WebhookSecret,
314 /// Whether deliveries are attempted. A hook that is off is kept rather than deleted
315 /// so its delivery history — the reason it was turned off — stays readable.
316 pub active: bool,
317 pub created_at: SystemTime,
318}
319
320impl Webhook {
321 /// Validates a new hook.
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 /// Rebuilds a row from storage without revalidating it.
340 ///
341 /// Deliberately does not re-run [`WebhookUrl::new`]: tightening the SSRF rules must
342 /// not make an existing row unreadable, which would hide the hook from the page
343 /// where it could be deleted. A row that no longer passes is still refused *at
344 /// delivery*, by the adapter's check on the resolved address.
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)]
365mod 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 // The vector every HMAC-SHA-256 implementation agrees on, so a library swap
404 // that changes the answer fails here rather than at somebody's receiver.
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 // The whole SSRF surface, named case by case: a hook is a URL a user chose and
451 // the server dials it.
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}