forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

client.rs665 lines, 23.6 KiBHistoryRawDownload
1//! SSRF-safe outbound HTTP for webhook deliveries.
2//!
3//! Every destination is checked twice: once when a hook URL is saved ([`validate_url`]) and again
4//! at send time. Hostnames are resolved by [`PolicyResolver`], which drops internal addresses before
5//! reqwest can connect, so a DNS rebind cannot slip past the check. Literal IP hosts are checked
6//! directly, since the resolver is not consulted for them. Redirects are never followed.
7
8use std::fmt;
9use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
10use std::str::FromStr;
11use std::sync::Arc;
12use std::time::{Duration, Instant};
13
14use forge_core::config::WebhookConfig;
15use futures_util::StreamExt;
16use hmac::{Hmac, KeyInit, Mac};
17use ipnet::IpNet;
18use reqwest::Url;
19use reqwest::dns::{Addrs, Name, Resolve, Resolving};
20use reqwest::header::{HeaderName, HeaderValue};
21use sha2::Sha256;
22
23/// Longest accepted hook URL, in bytes.
24pub const MAX_URL_LEN: usize = 2048;
25/// Most response body bytes kept in a [`SendOutcome`].
26pub const MAX_BODY_BYTES: usize = 64 * 1024;
27
28type HmacSha256 = Hmac<Sha256>;
29type BoxError = Box<dyn std::error::Error + Send + Sync>;
30
31/// One entry of the allow list: an exact hostname (case-insensitive) or a CIDR network.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum AllowEntry {
34 Host(String),
35 Net(IpNet),
36}
37
38/// Outbound policy derived from the `[webhooks]` config section.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct WebhookPolicy {
41 pub allow_http: bool,
42 pub allowed_hosts: Vec<AllowEntry>,
43}
44
45impl WebhookPolicy {
46 /// Builds the policy from config. An entry containing `/` must be a CIDR network, a bare IP
47 /// address becomes a single-host network, and anything else is a hostname.
48 pub fn from_config(config: &WebhookConfig) -> Result<Self, String> {
49 let allowed_hosts = config
50 .allowed_hosts
51 .iter()
52 .map(|entry| {
53 let entry = entry.trim();
54 if entry.contains('/') {
55 IpNet::from_str(entry)
56 .map(AllowEntry::Net)
57 .map_err(|e| format!("invalid allowed_hosts entry `{entry}`: {e}"))
58 } else if let Ok(ip) = IpAddr::from_str(entry) {
59 Ok(AllowEntry::Net(IpNet::from(ip)))
60 } else if entry.is_empty() || entry.contains(char::is_whitespace) {
61 Err(format!("invalid allowed_hosts entry `{entry}`"))
62 } else {
63 Ok(AllowEntry::Host(entry.to_ascii_lowercase()))
64 }
65 })
66 .collect::<Result<Vec<_>, _>>()?;
67 Ok(Self {
68 allow_http: config.allow_http,
69 allowed_hosts,
70 })
71 }
72
73 /// True when the hostname is named in the allow list (case-insensitive).
74 pub fn host_allowed(&self, host: &str) -> bool {
75 self.allowed_hosts.iter().any(|entry| match entry {
76 AllowEntry::Host(allowed) => allowed.eq_ignore_ascii_case(host),
77 AllowEntry::Net(_) => false,
78 })
79 }
80
81 /// True when the address falls inside a CIDR network in the allow list.
82 pub fn ip_allowed(&self, ip: IpAddr) -> bool {
83 // An IPv4-mapped address matches an IPv4 network, so check both forms.
84 let mapped = ip.to_canonical();
85 self.allowed_hosts.iter().any(|entry| match entry {
86 AllowEntry::Net(net) => net.contains(&ip) || net.contains(&mapped),
87 AllowEntry::Host(_) => false,
88 })
89 }
90}
91
92/// Why a hook URL was refused.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum UrlError {
95 TooLong,
96 Parse(String),
97 Scheme(String),
98 Userinfo,
99 MissingHost,
100 BadPort,
101 Forbidden(IpAddr),
102}
103
104impl fmt::Display for UrlError {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 match self {
107 Self::TooLong => write!(f, "url is longer than {MAX_URL_LEN} bytes"),
108 Self::Parse(e) => write!(f, "invalid url: {e}"),
109 Self::Scheme(s) => write!(f, "url scheme `{s}` is not allowed"),
110 Self::Userinfo => write!(f, "url must not contain a username or password"),
111 Self::MissingHost => write!(f, "url has no host"),
112 Self::BadPort => write!(f, "url port must be between 1 and 65535"),
113 Self::Forbidden(ip) => write!(f, "destination not allowed: {ip}"),
114 }
115 }
116}
117
118impl std::error::Error for UrlError {}
119
120/// Checks a hook URL against the policy. Used when a hook is saved and again before each send.
121pub fn validate_url(url: &str, policy: &WebhookPolicy) -> Result<Url, UrlError> {
122 if url.len() > MAX_URL_LEN {
123 return Err(UrlError::TooLong);
124 }
125 let parsed = Url::parse(url).map_err(|e| UrlError::Parse(e.to_string()))?;
126 match parsed.scheme() {
127 "https" => {}
128 "http" if policy.allow_http => {}
129 other => return Err(UrlError::Scheme(other.to_owned())),
130 }
131 if !parsed.username().is_empty() || parsed.password().is_some() {
132 return Err(UrlError::Userinfo);
133 }
134 // An explicit port is parsed by `Url` (so >65535 fails above); only 0 needs rejecting here.
135 if parsed.port() == Some(0) {
136 return Err(UrlError::BadPort);
137 }
138 let host = parsed.host_str().unwrap_or_default();
139 if host.is_empty() {
140 return Err(UrlError::MissingHost);
141 }
142 // IPv6 literals come back bracketed, e.g. "[::1]".
143 let bare = host.trim_start_matches('[').trim_end_matches(']');
144 if let Ok(ip) = bare.parse::<IpAddr>() {
145 check_literal(ip, policy)?;
146 }
147 Ok(parsed)
148}
149
150fn check_literal(ip: IpAddr, policy: &WebhookPolicy) -> Result<(), UrlError> {
151 if is_forbidden_ip(ip) && !policy.ip_allowed(ip) {
152 Err(UrlError::Forbidden(ip))
153 } else {
154 Ok(())
155 }
156}
157
158/// True for addresses a webhook must not reach by default: loopback, private, link-local, CGNAT,
159/// unspecified, multicast, broadcast, documentation and reserved ranges. IPv4 addresses embedded
160/// in IPv6 (mapped, compatible, NAT64, 6to4, Teredo) are judged by the embedded IPv4 address.
161pub fn is_forbidden_ip(ip: IpAddr) -> bool {
162 match ip {
163 IpAddr::V4(v4) => is_forbidden_v4(v4),
164 IpAddr::V6(v6) => is_forbidden_v6(v6),
165 }
166}
167
168fn is_forbidden_v4(ip: Ipv4Addr) -> bool {
169 let [a, b, c, _] = ip.octets();
170 ip.is_loopback()
171 || ip.is_private()
172 || ip.is_link_local()
173 || ip.is_unspecified()
174 || ip.is_multicast()
175 || ip.is_broadcast()
176 || ip.is_documentation()
177 || a == 0 // 0.0.0.0/8
178 || (a == 100 && (b & 0xc0) == 64) // 100.64.0.0/10 CGNAT
179 || (a == 192 && b == 0 && c == 0) // 192.0.0.0/24 IETF protocol assignments
180 || (a == 198 && (b & 0xfe) == 18) // 198.18.0.0/15 benchmarking
181 || a >= 240 // 240.0.0.0/4 reserved
182}
183
184fn is_forbidden_v6(ip: Ipv6Addr) -> bool {
185 if let Some(v4) = ip.to_ipv4_mapped() {
186 return is_forbidden_v4(v4);
187 }
188 let s = ip.segments();
189 if ip.is_loopback() || ip.is_unspecified() || ip.is_multicast() {
190 return true;
191 }
192 if (s[0] & 0xfe00) == 0xfc00 // fc00::/7 unique local
193 || (s[0] & 0xffc0) == 0xfe80 // fe80::/10 link-local
194 || (s[0] == 0x2001 && s[1] == 0x0db8) // 2001:db8::/32 documentation
195 || (s[0] == 0x0100 && s[1] == 0 && s[2] == 0 && s[3] == 0)
196 // 100::/64 discard
197 {
198 return true;
199 }
200 // IPv4-compatible ::/96 (deprecated).
201 if s[..6] == [0; 6] {
202 return is_forbidden_v4(v4_from(s[6], s[7]));
203 }
204 // NAT64 well-known prefix 64:ff9b::/96, and the local-use 64:ff9b:1::/48.
205 if s[0] == 0x0064 && s[1] == 0xff9b {
206 return s[2] == 0x0001 || (s[2..6] == [0; 4] && is_forbidden_v4(v4_from(s[6], s[7])));
207 }
208 // 6to4 2002::/16 embeds the IPv4 address in the second and third segments.
209 if s[0] == 0x2002 {
210 return is_forbidden_v4(v4_from(s[1], s[2]));
211 }
212 // Teredo 2001::/32 embeds the server address and an obfuscated client address.
213 if s[0] == 0x2001 && s[1] == 0 {
214 let client = Ipv4Addr::from(!u32::from(v4_from(s[6], s[7])));
215 return is_forbidden_v4(v4_from(s[2], s[3])) || is_forbidden_v4(client);
216 }
217 false
218}
219
220fn v4_from(hi: u16, lo: u16) -> Ipv4Addr {
221 let [a, b] = hi.to_be_bytes();
222 let [c, d] = lo.to_be_bytes();
223 Ipv4Addr::new(a, b, c, d)
224}
225
226/// Resolves hostnames and drops forbidden addresses, unless the host or the address is allowed.
227#[derive(Debug)]
228pub struct PolicyResolver {
229 policy: Arc<WebhookPolicy>,
230}
231
232impl Resolve for PolicyResolver {
233 fn resolve(&self, name: Name) -> Resolving {
234 Box::pin(resolve_allowed(
235 self.policy.clone(),
236 name.as_str().to_owned(),
237 ))
238 }
239}
240
241async fn resolve_allowed(policy: Arc<WebhookPolicy>, host: String) -> Result<Addrs, BoxError> {
242 let found: Vec<SocketAddr> = tokio::net::lookup_host((host.as_str(), 0)).await?.collect();
243 let host_allowed = policy.host_allowed(&host);
244 let kept: Vec<SocketAddr> = found
245 .into_iter()
246 .filter(|addr| host_allowed || !is_forbidden_ip(addr.ip()) || policy.ip_allowed(addr.ip()))
247 .collect();
248 if kept.is_empty() {
249 return Err("destination not allowed".into());
250 }
251 let addrs: Addrs = Box::new(kept.into_iter());
252 Ok(addrs)
253}
254
255/// A reqwest client under the same outbound policy as webhooks: internal addresses are dropped at
256/// resolve time, redirects are never followed and no proxy is used. For API imports.
257pub fn policy_client(
258 policy: WebhookPolicy,
259 timeout: Duration,
260 user_agent: &'static str,
261) -> reqwest::Result<reqwest::Client> {
262 reqwest::Client::builder()
263 .redirect(reqwest::redirect::Policy::none())
264 .connect_timeout(Duration::from_secs(10))
265 .timeout(timeout)
266 .dns_resolver(Arc::new(PolicyResolver {
267 policy: Arc::new(policy),
268 }))
269 .user_agent(user_agent)
270 .no_proxy()
271 .build()
272}
273
274/// What happened when a delivery was sent. A failure leaves `status` as `None` and sets `error`.
275#[derive(Debug, Clone, PartialEq, Eq)]
276pub struct SendOutcome {
277 pub status: Option<u16>,
278 pub headers: Vec<(String, String)>,
279 /// Response body, at most [`MAX_BODY_BYTES`], decoded lossily as UTF-8.
280 pub body: String,
281 pub error: Option<String>,
282 pub duration_ms: u64,
283}
284
285/// Shared HTTP client for webhook deliveries. Build it once and share it behind an `Arc`.
286#[derive(Debug)]
287pub struct HookClient {
288 client: reqwest::Client,
289 policy: Arc<WebhookPolicy>,
290}
291
292impl HookClient {
293 pub fn new(policy: WebhookPolicy) -> reqwest::Result<Arc<Self>> {
294 let policy = Arc::new(policy);
295 let client = reqwest::Client::builder()
296 .redirect(reqwest::redirect::Policy::none())
297 .connect_timeout(Duration::from_secs(10))
298 .timeout(Duration::from_secs(20))
299 .dns_resolver(Arc::new(PolicyResolver {
300 policy: policy.clone(),
301 }))
302 .user_agent(concat!("forge-hookshot/", env!("CARGO_PKG_VERSION")))
303 .no_proxy()
304 .build()?;
305 Ok(Arc::new(Self { client, policy }))
306 }
307
308 /// POSTs `body` to `url`. Never follows redirects, and reads at most [`MAX_BODY_BYTES`] of the response.
309 pub async fn send(
310 &self,
311 url: &str,
312 headers: &[(String, String)],
313 body: Vec<u8>,
314 ) -> SendOutcome {
315 let start = Instant::now();
316 let parsed = match validate_url(url, &self.policy) {
317 Ok(parsed) => parsed,
318 Err(e) => return failed(e.to_string(), start),
319 };
320 let mut request = self.client.post(parsed).body(body);
321 for (name, value) in headers {
322 let name = match HeaderName::from_bytes(name.as_bytes()) {
323 Ok(name) => name,
324 Err(e) => return failed(format!("invalid header name `{name}`: {e}"), start),
325 };
326 let value = match HeaderValue::from_str(value) {
327 Ok(value) => value,
328 Err(e) => return failed(format!("invalid value for header `{name}`: {e}"), start),
329 };
330 request = request.header(name, value);
331 }
332 let response = match request.send().await {
333 Ok(response) => response,
334 Err(e) => return failed(error_chain(&e), start),
335 };
336
337 let status = response.status().as_u16();
338 let headers = response
339 .headers()
340 .iter()
341 .map(|(name, value)| {
342 (
343 name.as_str().to_owned(),
344 String::from_utf8_lossy(value.as_bytes()).into_owned(),
345 )
346 })
347 .collect();
348
349 let mut buf = Vec::new();
350 let mut error = None;
351 let mut stream = response.bytes_stream();
352 while let Some(chunk) = stream.next().await {
353 match chunk {
354 Ok(bytes) => {
355 let room = MAX_BODY_BYTES - buf.len();
356 buf.extend_from_slice(&bytes[..bytes.len().min(room)]);
357 if buf.len() >= MAX_BODY_BYTES {
358 break;
359 }
360 }
361 Err(e) => {
362 error = Some(error_chain(&e));
363 break;
364 }
365 }
366 }
367
368 SendOutcome {
369 status: Some(status),
370 headers,
371 body: String::from_utf8_lossy(&buf).into_owned(),
372 error,
373 duration_ms: elapsed_ms(start),
374 }
375 }
376}
377
378/// Signs a delivery body: `sha256=` followed by the hex HMAC-SHA256 of `body` under `secret`.
379pub fn sign(secret: &[u8], body: &[u8]) -> String {
380 // HMAC accepts keys of any length, so the error branch is unreachable.
381 let mut mac = match HmacSha256::new_from_slice(secret) {
382 Ok(mac) => mac,
383 Err(_) => return String::new(),
384 };
385 mac.update(body);
386 format!("sha256={}", hex::encode(mac.finalize().into_bytes()))
387}
388
389fn failed(error: String, start: Instant) -> SendOutcome {
390 SendOutcome {
391 status: None,
392 headers: Vec::new(),
393 body: String::new(),
394 error: Some(error),
395 duration_ms: elapsed_ms(start),
396 }
397}
398
399fn elapsed_ms(start: Instant) -> u64 {
400 u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX)
401}
402
403/// Formats an error with its source chain, so the resolver's "destination not allowed" shows up.
404fn error_chain(err: &(dyn std::error::Error + 'static)) -> String {
405 let mut out = err.to_string();
406 let mut source = err.source();
407 while let Some(next) = source {
408 out.push_str(": ");
409 out.push_str(&next.to_string());
410 source = next.source();
411 }
412 out
413}
414
415#[cfg(test)]
416mod tests {
417 use super::*;
418 use tokio::io::{AsyncReadExt, AsyncWriteExt};
419 use tokio::net::TcpListener;
420
421 fn policy(allow_http: bool, allowed: &[&str]) -> WebhookPolicy {
422 WebhookPolicy::from_config(&WebhookConfig {
423 allow_http,
424 allowed_hosts: allowed.iter().map(|s| (*s).to_owned()).collect(),
425 })
426 .expect("valid policy")
427 }
428
429 #[test]
430 fn forbidden_ip_table() {
431 let forbidden = [
432 "127.0.0.1",
433 "10.1.2.3",
434 "172.16.0.1",
435 "192.168.1.1",
436 "169.254.169.254",
437 "100.64.0.1",
438 "0.0.0.0",
439 "::1",
440 "fe80::1",
441 "fc00::1",
442 "::ffff:127.0.0.1",
443 "64:ff9b::7f00:1",
444 "::ffff:10.0.0.1",
445 "2002:7f00:0001::1",
446 "224.0.0.1",
447 "255.255.255.255",
448 "192.0.2.1",
449 "2001:db8::1",
450 "ff02::1",
451 "240.0.0.1",
452 ];
453 for ip in forbidden {
454 let parsed: IpAddr = ip.parse().expect("ip literal");
455 assert!(is_forbidden_ip(parsed), "{ip} should be forbidden");
456 }
457 let allowed = [
458 "8.8.8.8",
459 "1.1.1.1",
460 "2001:4860:4860::8888",
461 "64:ff9b::808:808",
462 ];
463 for ip in allowed {
464 let parsed: IpAddr = ip.parse().expect("ip literal");
465 assert!(!is_forbidden_ip(parsed), "{ip} should be allowed");
466 }
467 }
468
469 #[test]
470 fn validate_url_cases() {
471 let strict = policy(false, &[]);
472 let lax = policy(true, &[]);
473 assert!(validate_url("https://hooks.example.com/a?b=1", &strict).is_ok());
474 assert!(validate_url("https://example.com:8443/x", &strict).is_ok());
475 assert!(matches!(
476 validate_url("http://example.com/", &strict),
477 Err(UrlError::Scheme(_))
478 ));
479 assert!(validate_url("http://example.com/", &lax).is_ok());
480 assert!(matches!(
481 validate_url("ftp://example.com/", &lax),
482 Err(UrlError::Scheme(_))
483 ));
484 assert_eq!(
485 validate_url("https://user:pw@example.com/", &strict),
486 Err(UrlError::Userinfo)
487 );
488 assert_eq!(
489 validate_url("https://user@example.com/", &strict),
490 Err(UrlError::Userinfo)
491 );
492 assert_eq!(
493 validate_url("https://example.com:0/", &strict),
494 Err(UrlError::BadPort)
495 );
496 assert!(matches!(
497 validate_url("https://example.com:70000/", &strict),
498 Err(UrlError::Parse(_))
499 ));
500 assert!(matches!(
501 validate_url("https://", &strict),
502 Err(UrlError::Parse(_) | UrlError::MissingHost)
503 ));
504 let long = format!("https://example.com/{}", "a".repeat(MAX_URL_LEN));
505 assert_eq!(validate_url(&long, &strict), Err(UrlError::TooLong));
506 assert_eq!(
507 validate_url("https://127.0.0.1/", &strict),
508 Err(UrlError::Forbidden("127.0.0.1".parse().expect("ip")))
509 );
510 assert!(matches!(
511 validate_url("https://[::1]:8080/", &strict),
512 Err(UrlError::Forbidden(_))
513 ));
514 assert!(validate_url("https://8.8.8.8/", &strict).is_ok());
515 }
516
517 #[test]
518 fn allowed_hosts_cidr_and_hostname() {
519 let p = policy(false, &["Hooks.Internal", "10.20.0.0/16", "192.168.5.7"]);
520 assert!(p.host_allowed("hooks.internal"));
521 assert!(p.host_allowed("HOOKS.INTERNAL"));
522 assert!(!p.host_allowed("other.internal"));
523 assert!(p.ip_allowed("10.20.3.4".parse().expect("ip")));
524 assert!(!p.ip_allowed("10.21.0.1".parse().expect("ip")));
525 assert!(p.ip_allowed("192.168.5.7".parse().expect("ip")));
526 assert!(p.ip_allowed("::ffff:10.20.0.9".parse().expect("ip")));
527 assert!(validate_url("https://10.20.1.1/hook", &p).is_ok());
528 assert!(validate_url("https://10.30.1.1/hook", &p).is_err());
529 assert!(
530 WebhookPolicy::from_config(&WebhookConfig {
531 allow_http: false,
532 allowed_hosts: vec!["10.0.0.0/99".into()],
533 })
534 .is_err()
535 );
536 }
537
538 #[test]
539 fn sign_matches_rfc4231_case_2() {
540 // RFC 4231 test case 2: key "Jefe", data "what do ya want for nothing?".
541 assert_eq!(
542 sign(b"Jefe", b"what do ya want for nothing?"),
543 "sha256=5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
544 );
545 }
546
547 /// Serves one HTTP response per connection with the given status line and body.
548 async fn serve(response: &'static [u8]) -> SocketAddr {
549 let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
550 let addr = listener.local_addr().expect("addr");
551 tokio::spawn(async move {
552 loop {
553 let Ok((mut socket, _)) = listener.accept().await else {
554 return;
555 };
556 tokio::spawn(async move {
557 let mut buf = Vec::new();
558 let mut chunk = [0u8; 1024];
559 loop {
560 match socket.read(&mut chunk).await {
561 Ok(0) | Err(_) => break,
562 Ok(n) => {
563 buf.extend_from_slice(&chunk[..n]);
564 if buf.windows(4).any(|w| w == b"\r\n\r\n") {
565 break;
566 }
567 }
568 }
569 }
570 let _ = socket.write_all(response).await;
571 let _ = socket.shutdown().await;
572 });
573 }
574 });
575 addr
576 }
577
578 fn ok_response() -> &'static [u8] {
579 b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"
580 }
581
582 async fn post(client: &HookClient, url: &str) -> SendOutcome {
583 client
584 .send(url, &[("X-Test".into(), "1".into())], b"{}".to_vec())
585 .await
586 }
587
588 #[tokio::test]
589 async fn send_rejects_loopback_by_default() {
590 let addr = serve(ok_response()).await;
591 let client = HookClient::new(policy(true, &[])).expect("client");
592 for host in ["127.0.0.1", "localhost"] {
593 let outcome = post(&client, &format!("http://{host}:{}/hook", addr.port())).await;
594 assert_eq!(outcome.status, None, "case {host}");
595 assert!(outcome.error.is_some(), "case {host}");
596 if host == "127.0.0.1" {
597 assert!(
598 outcome
599 .error
600 .as_deref()
601 .is_some_and(|e| e.contains("destination not allowed")),
602 "case {host}"
603 );
604 }
605 }
606 }
607
608 #[tokio::test]
609 async fn send_accepts_allowed_cidr_and_hostname() {
610 // (name, allowed entry, host used in the URL); both must deliver the same response.
611 let cases = [
612 ("loopback cidr", "127.0.0.1/32", "127.0.0.1"),
613 ("hostname", "localhost", "localhost"),
614 ];
615 for (name, allowed, host) in cases {
616 let addr = serve(ok_response()).await;
617 let client = HookClient::new(policy(true, &[allowed])).expect("client");
618 let outcome = post(&client, &format!("http://{host}:{}/hook", addr.port())).await;
619 assert_eq!(outcome.error, None, "case {name}");
620 assert_eq!(outcome.status, Some(200), "case {name}");
621 assert_eq!(outcome.body, "ok", "case {name}");
622 assert!(
623 outcome.headers.iter().any(|(k, _)| k == "content-type"),
624 "case {name}"
625 );
626 }
627 }
628
629 #[tokio::test]
630 async fn send_rejects_http_when_not_allowed() {
631 let client = HookClient::new(policy(false, &["127.0.0.1/32"])).expect("client");
632 let outcome = post(&client, "http://127.0.0.1:9/hook").await;
633 assert_eq!(outcome.status, None);
634 assert!(outcome.error.is_some());
635 }
636
637 #[tokio::test]
638 async fn redirects_are_not_followed() {
639 let addr = serve(
640 b"HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:9/elsewhere\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
641 )
642 .await;
643 let client = HookClient::new(policy(true, &["127.0.0.1/32"])).expect("client");
644 let outcome = post(&client, &format!("http://127.0.0.1:{}/hook", addr.port())).await;
645 assert_eq!(outcome.error, None);
646 assert_eq!(outcome.status, Some(302));
647 }
648
649 #[tokio::test]
650 async fn body_is_truncated_to_limit() {
651 let body = "x".repeat(MAX_BODY_BYTES + 50_000);
652 let head = format!(
653 "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
654 body.len()
655 );
656 let mut response = head.into_bytes();
657 response.extend_from_slice(body.as_bytes());
658 let leaked: &'static [u8] = Box::leak(response.into_boxed_slice());
659 let addr = serve(leaked).await;
660 let client = HookClient::new(policy(true, &["127.0.0.1/32"])).expect("client");
661 let outcome = post(&client, &format!("http://127.0.0.1:{}/hook", addr.port())).await;
662 assert_eq!(outcome.status, Some(200));
663 assert_eq!(outcome.body.len(), MAX_BODY_BYTES);
664 }
665}