steid

@jamesgill /

steid/src/domain/webhook.rs
Rust19.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::{
17 DomainError, RepoId, WebhookId,
18 net::{is_public, names_local_network},
19};
20
21/// The prefix every hook secret carries, so a leaked one is recognisable as Steid's.
22const SECRET_PREFIX: &str = "steid_whs_";
23
24type HmacSha256 = Hmac<Sha256>;
25
26/// A hook's shared secret, in the clear.
27///
28/// Redacted in `Debug` for the same reason a token is: the value is the whole of the
29/// authentication, and a log line is a place it must not reach.
30#[derive(Clone, PartialEq, Eq)]
31pub struct WebhookSecret(String);
32
33impl WebhookSecret {
34 /// Bytes of entropy, matching [`TokenSecret`](super::TokenSecret).
35 const BYTES: usize = 32;
36
37 /// Mints a fresh secret from the OS random source.
38 pub fn generate() -> Self {
39 use rand::Rng;
40
41 let mut bytes = [0u8; Self::BYTES];
42 rand::rng().fill_bytes(&mut bytes);
43
44 let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
45
46 Self(format!("{SECRET_PREFIX}{random}"))
47 }
48
49 /// Wraps a stored secret without generating a new one.
50 pub fn from_trusted(value: impl Into<String>) -> Self {
51 Self(value.into())
52 }
53
54 /// The secret itself, to be shown exactly once and used to sign.
55 pub fn reveal(&self) -> &str {
56 &self.0
57 }
58
59 /// The `sha256=<hex>` signature of a body, as it goes on the wire.
60 ///
61 /// HMAC-SHA-256 over the exact bytes sent, which is what every other forge does and
62 /// what every receiving library already knows how to check. The `sha256=` prefix is
63 /// part of the value rather than implied, so a future second algorithm is a new
64 /// prefix rather than a silent reinterpretation of the same header.
65 pub fn sign(&self, body: &[u8]) -> String {
66 // Infallible for HMAC: the construction accepts a key of any length.
67 let mut mac = HmacSha256::new_from_slice(self.0.as_bytes()).expect("hmac takes any key");
68 mac.update(body);
69
70 let digest = mac.finalize().into_bytes();
71
72 format!(
73 "sha256={}",
74 digest
75 .iter()
76 .map(|byte| format!("{byte:02x}"))
77 .collect::<String>()
78 )
79 }
80}
81
82impl fmt::Debug for WebhookSecret {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 f.write_str("WebhookSecret(redacted)")
85 }
86}
87
88/// Where a delivery is POSTed.
89///
90/// Validated here rather than at the call site, because this is the one value in Steid
91/// that makes the server open a connection to an address a *user* chose. That is
92/// server-side request forgery, and the defence is a rule about what the value may name
93/// — not a check somewhere along the way that a later caller can forget.
94///
95/// What is refused: anything but `http`/`https`, credentials in the authority, and any
96/// host that names the machine Steid runs on or the network it sits in — loopback,
97/// private ranges, link-local (which includes the cloud metadata endpoint at
98/// `169.254.169.254`), and the names that conventionally resolve to them.
99///
100/// **This is a syntactic rule and cannot be the whole defence**: a public name can
101/// resolve to a private address. The sending adapter re-checks the resolved address, so
102/// this is the cheap half, made at the moment a person can be told why.
103/// Whether a hook may point inside this machine's own network.
104///
105/// `Refused` is the only value in production and the default everywhere. `Allowed` exists
106/// because **the end-to-end check cannot be run without it**: verifying that a real push
107/// signs and delivers a real payload needs a receiver, the obvious receiver is a script
108/// listening on `127.0.0.1`, and the SSRF rule refuses exactly that. Before this, the
109/// check needed a temporary patch to the source — which is a worse thing to have to do,
110/// because a patch is invisible and a flag is not.
111///
112/// Reached only through `STEID_ALLOW_PRIVATE_WEBHOOKS=true`, documented in
113/// `plans/runbook.md` beside `STEID_INSECURE_COOKIES` and never to be deployed: with it
114/// on, anyone who can add a hook can make the server dial its own network and read the
115/// response body off the deliveries page.
116#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
117pub enum PrivateTargets {
118 #[default]
119 Refused,
120 Allowed,
121}
122
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct WebhookUrl(String);
125
126impl WebhookUrl {
127 /// Well past any real endpoint, and a bound on what goes in a row.
128 pub const MAX_LEN: usize = 2000;
129
130 /// Validates a URL a person typed, refusing anything on this machine or its own
131 /// network.
132 pub fn new(value: impl AsRef<str>) -> Result<Self, DomainError> {
133 Self::new_with(value, PrivateTargets::Refused)
134 }
135
136 /// Validates a URL, allowing one that points inside this machine's own network.
137 ///
138 /// **Development only**, and reached only through
139 /// `STEID_ALLOW_PRIVATE_WEBHOOKS` — see the note on [`PrivateTargets`]. Everything
140 /// else still applies: the scheme, credentials in the authority, the port, the
141 /// length and the packed spellings of an address are refused exactly as before,
142 /// because none of those is about where the address points.
143 pub fn new_allowing_private(value: impl AsRef<str>) -> Result<Self, DomainError> {
144 Self::new_with(value, PrivateTargets::Allowed)
145 }
146
147 fn new_with(value: impl AsRef<str>, targets: PrivateTargets) -> Result<Self, DomainError> {
148 let value = value.as_ref().trim();
149
150 if value.is_empty() {
151 return Err(invalid("give the hook a URL to POST to"));
152 }
153
154 if value.len() > Self::MAX_LEN {
155 return Err(invalid(format!(
156 "a URL is at most {} characters",
157 Self::MAX_LEN
158 )));
159 }
160
161 if value.chars().any(|c| c.is_ascii_control() || c == ' ') {
162 return Err(invalid("a URL cannot contain spaces or control characters"));
163 }
164
165 let Some((scheme, rest)) = value.split_once("://") else {
166 return Err(invalid("a URL starts with http:// or https://"));
167 };
168
169 if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") {
170 return Err(invalid(
171 "only http:// and https:// URLs can be delivered to",
172 ));
173 }
174
175 let authority = rest
176 .split(['/', '?', '#'])
177 .next()
178 .expect("split always yields one part");
179
180 // A URL carrying credentials is refused rather than stripped: `user@host` is
181 // also how a parser can be confused into connecting somewhere other than where
182 // the value appears to name.
183 if authority.contains('@') {
184 return Err(invalid("a URL cannot carry credentials"));
185 }
186
187 let host = host_of(authority)?;
188
189 if host.is_empty() {
190 return Err(invalid("a URL needs a host"));
191 }
192
193 let local_allowed = targets == PrivateTargets::Allowed;
194
195 if let Ok(address) = host.parse::<IpAddr>() {
196 if !local_allowed && !is_public(address) {
197 return Err(invalid(
198 "that address is on this machine or its private network",
199 ));
200 }
201 } else {
202 let lowered = host.to_ascii_lowercase();
203
204 // The lists live in `domain::net`, shared with `ImportSource`.
205 if !local_allowed && names_local_network(&lowered) {
206 return Err(invalid("that host names this machine or its own network"));
207 }
208
209 if !local_allowed && !lowered.contains('.') {
210 return Err(invalid(
211 "that host has no domain, so it can only name something local",
212 ));
213 }
214
215 // A real name's last label is a TLD, which is never numeric. This is what
216 // catches the short and packed spellings of an address that `IpAddr` will
217 // not parse but a resolver will happily accept: `127.1`, `2130706433`,
218 // `0177.0.0.1`, `0x7f.1`. Refusing by shape beats enumerating the
219 // encodings.
220 let last = lowered.rsplit('.').next().unwrap_or_default();
221
222 // Unconditional, escape hatch or not: `127.1` is not a host name under any
223 // configuration, and a value that reaches a resolver by accident of parsing
224 // is worth refusing on its own account.
225 if last.starts_with(|c: char| c.is_ascii_digit()) {
226 return Err(invalid(
227 "that is not a host name — write an address out in full",
228 ));
229 }
230 }
231
232 Ok(Self(value.to_owned()))
233 }
234
235 /// Wraps a URL already known to have passed the rules above.
236 pub fn from_trusted(value: impl Into<String>) -> Self {
237 Self(value.into())
238 }
239
240 pub fn as_str(&self) -> &str {
241 &self.0
242 }
243
244 /// The host, for the adapter's second check against what it resolves to.
245 pub fn host(&self) -> &str {
246 let rest = self.0.split_once("://").map(|(_, rest)| rest).unwrap_or("");
247 let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
248
249 host_of(authority).unwrap_or_default()
250 }
251}
252
253impl fmt::Display for WebhookUrl {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 f.write_str(&self.0)
256 }
257}
258
259/// Pulls the host out of an authority, unwrapping an IPv6 literal's brackets.
260fn host_of(authority: &str) -> Result<&str, DomainError> {
261 if let Some(rest) = authority.strip_prefix('[') {
262 let Some((host, after)) = rest.split_once(']') else {
263 return Err(invalid("that IPv6 address is missing its closing bracket"));
264 };
265
266 check_port(after.strip_prefix(':'))?;
267
268 return Ok(host);
269 }
270
271 match authority.split_once(':') {
272 Some((host, port)) => {
273 check_port(Some(port))?;
274 Ok(host)
275 }
276 None => Ok(authority),
277 }
278}
279
280fn check_port(port: Option<&str>) -> Result<(), DomainError> {
281 let Some(port) = port else {
282 return Ok(());
283 };
284
285 match port.parse::<u16>() {
286 Ok(port) if port > 0 => Ok(()),
287 _ => Err(invalid("that is not a port number")),
288 }
289}
290
291fn invalid(reason: impl Into<String>) -> DomainError {
292 DomainError::validation("URL", reason)
293}
294
295/// A webhook, as recorded.
296///
297/// Belongs to a repository rather than to a user: it is the repository's pushes it
298/// reacts to, and it survives the person who added it changing role.
299#[derive(Debug, Clone, PartialEq, Eq)]
300pub struct Webhook {
301 pub id: WebhookId,
302 pub repo_id: RepoId,
303 pub url: WebhookUrl,
304 pub secret: WebhookSecret,
305 /// Whether deliveries are attempted. A hook that is off is kept rather than deleted
306 /// so its delivery history — the reason it was turned off — stays readable.
307 pub active: bool,
308 pub created_at: SystemTime,
309}
310
311impl Webhook {
312 /// Validates a new hook.
313 pub fn new(
314 id: WebhookId,
315 repo_id: RepoId,
316 url: impl AsRef<str>,
317 secret: WebhookSecret,
318 created_at: SystemTime,
319 // Whether a local target is allowed: `Refused` everywhere but a development
320 // instance that has opted in. Passed rather than defaulted, so every
321 // construction of a hook says which it is.
322 targets: PrivateTargets,
323 ) -> Result<Self, DomainError> {
324 Ok(Self {
325 id,
326 repo_id,
327 url: match targets {
328 PrivateTargets::Refused => WebhookUrl::new(url)?,
329 PrivateTargets::Allowed => WebhookUrl::new_allowing_private(url)?,
330 },
331 secret,
332 active: true,
333 created_at,
334 })
335 }
336
337 /// Rebuilds a row from storage without revalidating it.
338 ///
339 /// Deliberately does not re-run [`WebhookUrl::new`]: tightening the SSRF rules must
340 /// not make an existing row unreadable, which would hide the hook from the page
341 /// where it could be deleted. A row that no longer passes is still refused *at
342 /// delivery*, by the adapter's check on the resolved address.
343 pub fn from_trusted(
344 id: WebhookId,
345 repo_id: RepoId,
346 url: WebhookUrl,
347 secret: WebhookSecret,
348 active: bool,
349 created_at: SystemTime,
350 ) -> Self {
351 Self {
352 id,
353 repo_id,
354 url,
355 secret,
356 active,
357 created_at,
358 }
359 }
360}
361
362#[cfg(test)]
363mod tests {
364 use super::*;
365
366 #[test]
367 fn a_generated_secret_is_recognisable_and_full_width() {
368 let secret = WebhookSecret::generate();
369
370 assert!(secret.reveal().starts_with("steid_whs_"));
371 assert_eq!(
372 secret.reveal().len(),
373 "steid_whs_".len() + WebhookSecret::BYTES * 2
374 );
375 assert_ne!(
376 WebhookSecret::generate().reveal(),
377 WebhookSecret::generate().reveal()
378 );
379 }
380
381 #[test]
382 fn a_secret_never_reaches_debug_output() {
383 let secret = WebhookSecret::generate();
384
385 assert_eq!(format!("{secret:?}"), "WebhookSecret(redacted)");
386
387 let hook = Webhook::new(
388 WebhookId::generate(),
389 RepoId::generate(),
390 "https://example.com/hook",
391 secret.clone(),
392 SystemTime::UNIX_EPOCH,
393 PrivateTargets::Refused,
394 )
395 .expect("valid");
396
397 assert!(!format!("{hook:?}").contains(secret.reveal()));
398 }
399
400 #[test]
401 fn signing_matches_a_known_hmac() {
402 // The vector every HMAC-SHA-256 implementation agrees on, so a library swap
403 // that changes the answer fails here rather than at somebody's receiver.
404 let secret = WebhookSecret::from_trusted("key");
405
406 assert_eq!(
407 secret.sign(b"The quick brown fox jumps over the lazy dog"),
408 "sha256=f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"
409 );
410 }
411
412 #[test]
413 fn signing_is_stable_and_body_dependent() {
414 let secret = WebhookSecret::generate();
415
416 assert_eq!(secret.sign(b"{}"), secret.sign(b"{}"));
417 assert_ne!(secret.sign(b"{}"), secret.sign(b"{ }"));
418 assert_ne!(secret.sign(b"{}"), WebhookSecret::generate().sign(b"{}"));
419 }
420
421 #[test]
422 fn ordinary_public_urls_are_accepted() {
423 for url in [
424 "https://example.com/hook",
425 "http://example.com:8080/a/b?c=d",
426 "https://hooks.example.co.uk/services/T/B/x",
427 "https://93.184.216.34/hook",
428 "https://[2606:2800:220:1:248:1893:25c8:1946]/hook",
429 ] {
430 assert!(WebhookUrl::new(url).is_ok(), "{url} should be accepted");
431 }
432 }
433
434 #[test]
435 fn only_http_urls_can_be_delivered_to() {
436 for url in [
437 "file:///etc/passwd",
438 "gopher://example.com/",
439 "ftp://example.com/",
440 "example.com/hook",
441 "",
442 ] {
443 assert!(WebhookUrl::new(url).is_err(), "{url:?} should be refused");
444 }
445 }
446
447 #[test]
448 fn nothing_on_this_machine_or_its_network_can_be_delivered_to() {
449 // The whole SSRF surface, named case by case: a hook is a URL a user chose and
450 // the server dials it.
451 for url in [
452 "http://127.0.0.1:3000/hook",
453 "http://127.1/hook",
454 "http://2130706433/hook",
455 "http://0177.0.0.1/hook",
456 "http://localhost:3000/hook",
457 "http://LOCALHOST/hook",
458 "http://steid.local/hook",
459 // The fully qualified spellings of the same names.
460 "http://localhost./hook",
461 "http://steid.local./hook",
462 "http://db.internal/hook",
463 "http://redis/hook",
464 "http://10.0.0.5/hook",
465 "http://192.168.1.1/hook",
466 "http://172.16.0.1/hook",
467 "http://100.64.0.1/hook",
468 "http://169.254.169.254/latest/meta-data/",
469 "http://0.0.0.0/hook",
470 "http://[::1]/hook",
471 "http://[fe80::1]/hook",
472 "http://[fd00::1]/hook",
473 "http://[::ffff:127.0.0.1]/hook",
474 ] {
475 assert!(WebhookUrl::new(url).is_err(), "{url} should be refused");
476 }
477 }
478
479 #[test]
480 fn the_development_escape_hatch_allows_a_local_receiver() {
481 // What the end-to-end check needs, and nothing more: a script listening on
482 // loopback.
483 for url in [
484 "http://127.0.0.1:9099/hook",
485 "http://localhost:9099/hook",
486 "http://[::1]:9099/hook",
487 "http://192.168.1.10/hook",
488 ] {
489 assert!(
490 WebhookUrl::new_allowing_private(url).is_ok(),
491 "{url} should be accepted with the escape hatch on"
492 );
493 assert!(
494 WebhookUrl::new(url).is_err(),
495 "{url} should still be refused without it"
496 );
497 }
498 }
499
500 #[test]
501 fn the_escape_hatch_relaxes_addresses_and_nothing_else() {
502 // It is a development convenience, not a way to store a URL that cannot be
503 // delivered to: everything that is wrong with these is wrong wherever they point.
504 for url in [
505 "ftp://127.0.0.1/hook",
506 "http://user:pass@127.0.0.1/hook",
507 "http://127.0.0.1:0/hook",
508 // Not a host name under any configuration.
509 "http://127.1/hook",
510 "http://2130706433/hook",
511 ] {
512 assert!(
513 WebhookUrl::new_allowing_private(url).is_err(),
514 "{url} should be refused even with the escape hatch on"
515 );
516 }
517 }
518
519 #[test]
520 fn credentials_in_the_authority_are_refused() {
521 assert!(WebhookUrl::new("https://user:pass@example.com/hook").is_err());
522 assert!(WebhookUrl::new("https://example.com@127.0.0.1/hook").is_err());
523 }
524
525 #[test]
526 fn a_url_that_is_not_addressable_is_refused() {
527 assert!(WebhookUrl::new("https://example.com:0/hook").is_err());
528 assert!(WebhookUrl::new("https://example.com:notaport/hook").is_err());
529 assert!(WebhookUrl::new("https://[::1/hook").is_err());
530 assert!(WebhookUrl::new("https:///hook").is_err());
531 assert!(WebhookUrl::new(format!("https://example.com/{}", "a".repeat(2000))).is_err());
532 }
533
534 #[test]
535 fn the_host_is_readable_back_for_the_adapters_second_check() {
536 assert_eq!(
537 WebhookUrl::new("https://example.com:8443/hook")
538 .expect("valid")
539 .host(),
540 "example.com"
541 );
542 assert_eq!(
543 WebhookUrl::new("https://[2606:2800:220:1:248:1893:25c8:1946]:8443/hook")
544 .expect("valid")
545 .host(),
546 "2606:2800:220:1:248:1893:25c8:1946"
547 );
548 }
549
550 #[test]
551 fn a_new_hook_is_active() {
552 let hook = Webhook::new(
553 WebhookId::generate(),
554 RepoId::generate(),
555 "https://example.com/hook",
556 WebhookSecret::generate(),
557 SystemTime::UNIX_EPOCH,
558 PrivateTargets::Refused,
559 )
560 .expect("valid");
561
562 assert!(hook.active);
563 }
564}