1use std::fmt;
54use std::sync::{Arc, Mutex};
55use std::time::Duration;
56
57use axum::http::{Method, StatusCode};
58use serde::Serialize;
59use serde::de::DeserializeOwned;
60
61use crate::{Error, Result};
62
63const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
65
66#[derive(Clone, Default)]
68pub struct Http {
69 fake: Arc<Mutex<Option<Arc<Mutex<FakeState>>>>>,
70}
71
72impl fmt::Debug for Http {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 f.write_str("Http")
75 }
76}
77
78impl Http {
79 pub fn get(&self, url: impl Into<String>) -> Request {
81 self.request(Method::GET, url)
82 }
83
84 pub fn post(&self, url: impl Into<String>) -> Request {
86 self.request(Method::POST, url)
87 }
88
89 pub fn put(&self, url: impl Into<String>) -> Request {
91 self.request(Method::PUT, url)
92 }
93
94 pub fn patch(&self, url: impl Into<String>) -> Request {
96 self.request(Method::PATCH, url)
97 }
98
99 pub fn delete(&self, url: impl Into<String>) -> Request {
101 self.request(Method::DELETE, url)
102 }
103
104 pub fn request(&self, method: Method, url: impl Into<String>) -> Request {
106 Request {
107 http: self.clone(),
108 method,
109 url: url.into(),
110 query: Vec::new(),
111 headers: Vec::new(),
112 body: None,
113 timeout: DEFAULT_TIMEOUT,
114 retries: 0,
115 retry_delay: Duration::from_millis(100),
116 follow_redirects: true,
117 error: None,
118 }
119 }
120
121 pub fn fake(&self) -> FakeHttp {
124 let mut slot = self.fake.lock().unwrap_or_else(|e| e.into_inner());
125 let state = slot.get_or_insert_with(Arc::default).clone();
126 FakeHttp(state)
127 }
128
129 fn faked(&self) -> Option<Arc<Mutex<FakeState>>> {
130 self.fake.lock().unwrap_or_else(|e| e.into_inner()).clone()
131 }
132}
133
134#[must_use = "a request does nothing until sent"]
136pub struct Request {
137 http: Http,
138 method: Method,
139 url: String,
140 query: Vec<(String, String)>,
141 headers: Vec<(String, String)>,
142 body: Option<(String, Vec<u8>)>,
143 timeout: Duration,
144 retries: u32,
145 retry_delay: Duration,
146 follow_redirects: bool,
147 error: Option<Error>,
148}
149
150impl Request {
151 pub fn query(mut self, pairs: &[(&str, &str)]) -> Self {
153 self.query.extend(
154 pairs
155 .iter()
156 .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())),
157 );
158 self
159 }
160
161 pub fn header(mut self, name: &str, value: impl Into<String>) -> Self {
163 self.headers.push((name.to_owned(), value.into()));
164 self
165 }
166
167 pub fn bearer(self, token: &str) -> Self {
169 self.header("authorization", format!("Bearer {token}"))
170 }
171
172 pub fn basic_auth(self, user: &str, password: &str) -> Self {
174 use base64::Engine;
175 let encoded =
176 base64::engine::general_purpose::STANDARD.encode(format!("{user}:{password}"));
177 self.header("authorization", format!("Basic {encoded}"))
178 }
179
180 pub fn json(mut self, body: &impl Serialize) -> Self {
182 match serde_json::to_vec(body) {
183 Ok(bytes) => self.body = Some(("application/json".into(), bytes)),
184 Err(err) => self.error = Some(err.into()),
185 }
186 self
187 }
188
189 pub fn form(mut self, body: &impl Serialize) -> Self {
191 match serde_urlencoded::to_string(body) {
192 Ok(text) => {
193 self.body = Some((
194 "application/x-www-form-urlencoded".into(),
195 text.into_bytes(),
196 ));
197 }
198 Err(err) => self.error = Some(anyhow::Error::new(err).into()),
199 }
200 self
201 }
202
203 pub fn body(mut self, content_type: &str, body: impl Into<Vec<u8>>) -> Self {
205 self.body = Some((content_type.to_owned(), body.into()));
206 self
207 }
208
209 pub fn sign(mut self, key_id: &str, secret: &str) -> Self {
216 let id = format!("msg_{}", crate::db::Ulid::new().as_str());
217 let timestamp = crate::clock::unix_secs();
218 let body = self.body.as_ref().map_or(&[][..], |(_, body)| &body[..]);
219 match crate::webhook::signing::sign(secret, &id, timestamp, body) {
220 Ok(signature) => {
221 self.headers
222 .retain(|(name, _)| !name.to_ascii_lowercase().starts_with("webhook-"));
223 self = self
224 .header("webhook-id", id)
225 .header("webhook-timestamp", timestamp.to_string())
226 .header("webhook-signature", signature)
227 .header("webhook-key-id", key_id);
228 }
229 Err(err) => self.error = Some(err),
230 }
231 self
232 }
233
234 pub fn timeout(mut self, timeout: Duration) -> Self {
236 self.timeout = timeout;
237 self
238 }
239
240 pub fn retry(mut self, times: u32, delay: Duration) -> Self {
243 self.retries = times;
244 self.retry_delay = delay;
245 self
246 }
247
248 pub(crate) fn no_redirects(mut self) -> Self {
251 self.follow_redirects = false;
252 self
253 }
254
255 fn full_url(&self) -> Result<String> {
257 if self.query.is_empty() {
258 return Ok(self.url.clone());
259 }
260 let query = serde_urlencoded::to_string(&self.query).map_err(anyhow::Error::new)?;
261 let joiner = if self.url.contains('?') { '&' } else { '?' };
262 Ok(format!("{}{joiner}{query}", self.url))
263 }
264
265 pub async fn send(mut self) -> Result<Response> {
268 if let Some(err) = self.error.take() {
269 return Err(err);
270 }
271 let url = self.full_url()?;
272 let mut attempt = 0;
273 loop {
274 attempt += 1;
275 let outcome = match self.http.faked() {
276 Some(fake) => fake_send(&fake, &self, &url),
277 None => self.send_once(&url).await,
278 };
279 let retryable = match &outcome {
280 Ok(response) => {
281 response.status == StatusCode::TOO_MANY_REQUESTS
282 || response.status.is_server_error()
283 }
284 Err(_) => true,
285 };
286 if !retryable || attempt > self.retries {
287 return outcome;
288 }
289 tracing::debug!(url = %url, attempt, "HTTP request failed, retrying");
290 tokio::time::sleep(self.retry_delay * attempt).await;
291 }
292 }
293
294 #[cfg(feature = "http")]
295 async fn send_once(&self, url: &str) -> Result<Response> {
296 let client = if self.follow_redirects {
297 client()
298 } else {
299 client_without_redirects()
300 };
301 let mut request = client
302 .request(self.method.clone(), url)
303 .timeout(self.timeout);
304 for (name, value) in &self.headers {
305 request = request.header(name, value);
306 }
307 if let Some((content_type, body)) = &self.body {
308 request = request
309 .header("content-type", content_type)
310 .body(body.clone());
311 }
312 let response = request
313 .send()
314 .await
315 .map_err(|err| anyhow::anyhow!("{} {url}: {}", self.method, err_chain(&err)))?;
316 let status = response.status();
317 let headers = response
318 .headers()
319 .iter()
320 .map(|(k, v)| {
321 (
322 k.as_str().to_owned(),
323 v.to_str().unwrap_or_default().to_owned(),
324 )
325 })
326 .collect();
327 let body = response
328 .bytes()
329 .await
330 .map_err(|err| anyhow::anyhow!("{} {url}: {}", self.method, err_chain(&err)))?;
331 Ok(Response {
332 status,
333 headers,
334 body: body.to_vec(),
335 url: url.to_owned(),
336 })
337 }
338
339 #[cfg(not(feature = "http"))]
340 async fn send_once(&self, url: &str) -> Result<Response> {
341 Err(anyhow::anyhow!(
342 "{} {url}: Renox was built without the `http` feature",
343 self.method
344 )
345 .into())
346 }
347}
348
349#[cfg(feature = "http")]
350fn err_chain(err: &dyn std::error::Error) -> String {
351 let mut text = err.to_string();
352 let mut source = err.source();
353 while let Some(cause) = source {
354 text.push_str(": ");
355 text.push_str(&cause.to_string());
356 source = cause.source();
357 }
358 text
359}
360
361#[cfg(feature = "http")]
363pub(crate) fn client() -> &'static reqwest::Client {
364 static CLIENT: std::sync::LazyLock<reqwest::Client> = std::sync::LazyLock::new(|| {
365 let _ = rustls::crypto::ring::default_provider().install_default();
368 reqwest::Client::builder()
369 .user_agent(concat!("renox/", env!("CARGO_PKG_VERSION")))
370 .build()
371 .unwrap_or_default()
372 });
373 &CLIENT
374}
375
376#[cfg(feature = "http")]
378fn client_without_redirects() -> &'static reqwest::Client {
379 static CLIENT: std::sync::LazyLock<reqwest::Client> = std::sync::LazyLock::new(|| {
380 let _ = rustls::crypto::ring::default_provider().install_default();
381 reqwest::Client::builder()
382 .user_agent(concat!("renox/", env!("CARGO_PKG_VERSION")))
383 .redirect(reqwest::redirect::Policy::none())
384 .build()
385 .unwrap_or_default()
386 });
387 &CLIENT
388}
389
390#[derive(Debug, Clone)]
392pub struct Response {
393 status: StatusCode,
394 headers: Vec<(String, String)>,
395 body: Vec<u8>,
396 url: String,
397}
398
399impl Response {
400 pub fn status(&self) -> StatusCode {
402 self.status
403 }
404
405 pub fn ok(&self) -> bool {
407 self.status.is_success()
408 }
409
410 pub fn header(&self, name: &str) -> Option<&str> {
412 self.headers
413 .iter()
414 .find(|(k, _)| k.eq_ignore_ascii_case(name))
415 .map(|(_, v)| v.as_str())
416 }
417
418 pub fn bytes(&self) -> &[u8] {
420 &self.body
421 }
422
423 pub fn text(&self) -> String {
425 String::from_utf8_lossy(&self.body).into_owned()
426 }
427
428 pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
430 serde_json::from_slice(&self.body).map_err(|err| {
431 anyhow::anyhow!(
432 "the response of {} is not the expected JSON: {err}",
433 self.url
434 )
435 .into()
436 })
437 }
438
439 pub fn error_for_status(self) -> Result<Self> {
442 if self.status.is_client_error() || self.status.is_server_error() {
443 let body = self.text();
444 let excerpt: String = body.chars().take(300).collect();
445 return Err(anyhow::anyhow!("{} answered {}: {excerpt}", self.url, self.status).into());
446 }
447 Ok(self)
448 }
449}
450
451#[derive(Debug, Clone)]
453#[non_exhaustive]
454pub struct SentRequest {
455 pub method: String,
457 pub url: String,
459 pub headers: Vec<(String, String)>,
461 pub body: String,
463}
464
465impl SentRequest {
466 pub fn header(&self, name: &str) -> Option<&str> {
468 self.headers
469 .iter()
470 .find(|(k, _)| k.eq_ignore_ascii_case(name))
471 .map(|(_, v)| v.as_str())
472 }
473
474 pub fn json(&self) -> serde_json::Value {
476 serde_json::from_str(&self.body).unwrap_or_default()
477 }
478}
479
480#[derive(Debug, Clone)]
482pub struct FakeResponse {
483 status: StatusCode,
484 headers: Vec<(String, String)>,
485 body: Vec<u8>,
486 fails: bool,
488}
489
490impl FakeResponse {
491 pub fn status(status: u16) -> Self {
493 Self {
494 status: StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
495 headers: Vec::new(),
496 body: Vec::new(),
497 fails: false,
498 }
499 }
500
501 pub fn json(status: u16, body: serde_json::Value) -> Self {
503 Self::status(status)
504 .header("content-type", "application/json")
505 .body(body.to_string())
506 }
507
508 pub fn text(status: u16, body: impl Into<String>) -> Self {
510 Self::status(status).body(body.into())
511 }
512
513 pub fn connection_error() -> Self {
515 Self {
516 fails: true,
517 ..Self::status(500)
518 }
519 }
520
521 pub fn header(mut self, name: &str, value: &str) -> Self {
523 self.headers.push((name.to_owned(), value.to_owned()));
524 self
525 }
526
527 pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
529 self.body = body.into();
530 self
531 }
532}
533
534#[derive(Default)]
535struct FakeState {
536 routes: Vec<(String, Vec<FakeResponse>)>,
538 sent: Vec<SentRequest>,
539}
540
541#[derive(Clone)]
544pub struct FakeHttp(Arc<Mutex<FakeState>>);
545
546impl FakeHttp {
547 pub fn on(&self, pattern: &str, response: FakeResponse) -> &Self {
552 let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner());
553 match state.routes.iter_mut().find(|(p, _)| p == pattern) {
554 Some((_, answers)) => answers.push(response),
555 None => state.routes.push((pattern.to_owned(), vec![response])),
556 }
557 self
558 }
559
560 pub fn sent(&self) -> Vec<SentRequest> {
562 self.0
563 .lock()
564 .unwrap_or_else(|e| e.into_inner())
565 .sent
566 .clone()
567 }
568
569 #[track_caller]
571 pub fn assert_sent(&self, check: impl Fn(&SentRequest) -> bool) {
572 let sent = self.sent();
573 assert!(
574 sent.iter().any(check),
575 "no matching HTTP request was sent; sent: {:#?}",
576 sent.iter()
577 .map(|r| format!("{} {}", r.method, r.url))
578 .collect::<Vec<_>>()
579 );
580 }
581
582 #[track_caller]
584 pub fn assert_not_sent(&self, check: impl Fn(&SentRequest) -> bool) {
585 assert!(
586 !self.sent().iter().any(check),
587 "a matching HTTP request was sent"
588 );
589 }
590
591 #[track_caller]
593 pub fn assert_sent_count(&self, expected: usize) {
594 assert_eq!(self.sent().len(), expected, "HTTP requests sent");
595 }
596}
597
598fn fake_send(fake: &Mutex<FakeState>, request: &Request, url: &str) -> Result<Response> {
599 let mut state = fake.lock().unwrap_or_else(|e| e.into_inner());
600 let mut headers = request.headers.clone();
601 if let Some((content_type, _)) = &request.body {
602 headers.push(("content-type".into(), content_type.clone()));
603 }
604 state.sent.push(SentRequest {
605 method: request.method.to_string(),
606 url: url.to_owned(),
607 headers,
608 body: request
609 .body
610 .as_ref()
611 .map(|(_, body)| String::from_utf8_lossy(body).into_owned())
612 .unwrap_or_default(),
613 });
614 let method = request.method.as_str();
615 let answers = state
616 .routes
617 .iter_mut()
618 .find(|(pattern, _)| matches(pattern, method, url))
619 .map(|(_, answers)| answers)
620 .ok_or_else(|| {
621 anyhow::anyhow!(
622 "no fake for {method} {url}: add one with `fake_http().on(\"{url}\", …)`"
623 )
624 })?;
625 let answer = if answers.len() > 1 {
626 answers.remove(0)
627 } else {
628 answers[0].clone()
629 };
630 if answer.fails {
631 return Err(anyhow::anyhow!("{method} {url}: connection refused (fake)").into());
632 }
633 Ok(Response {
634 status: answer.status,
635 headers: answer.headers,
636 body: answer.body,
637 url: url.to_owned(),
638 })
639}
640
641fn matches(pattern: &str, method: &str, url: &str) -> bool {
643 let (want_method, pattern) = match pattern.split_once(' ') {
644 Some((m, rest)) if m.chars().all(|c| c.is_ascii_uppercase()) => (Some(m), rest),
645 _ => (None, pattern),
646 };
647 if want_method.is_some_and(|m| m != method) {
648 return false;
649 }
650 glob(pattern.as_bytes(), url.as_bytes())
651}
652
653fn glob(pattern: &[u8], text: &[u8]) -> bool {
654 match pattern.split_first() {
655 None => text.is_empty(),
656 Some((b'*', rest)) => (0..=text.len()).any(|i| glob(rest, &text[i..])),
657 Some((c, rest)) => text.first() == Some(c) && glob(rest, &text[1..]),
658 }
659}
660
661#[cfg(test)]
662mod tests {
663 use super::*;
664
665 #[cfg(feature = "http")]
666 #[test]
667 fn the_client_builds_with_the_ring_provider() {
668 let _ = client();
670 }
671
672 #[test]
673 fn patterns() {
674 assert!(matches("https://a.test/*", "GET", "https://a.test/x?y=1"));
675 assert!(matches("POST https://a.test/o", "POST", "https://a.test/o"));
676 assert!(!matches("POST https://a.test/o", "GET", "https://a.test/o"));
677 assert!(!matches("https://a.test/o", "GET", "https://a.test/o/1"));
678 assert!(matches("*", "DELETE", "https://b.test"));
679 assert!(matches("https://*.test/*/x", "GET", "https://b.test/1/2/x"));
680 }
681
682 #[tokio::test]
683 async fn fakes_answer_in_turn_and_retries_follow() {
684 let http = Http::default();
685 let fake = http.fake();
686 fake.on("POST https://a.test/pay", FakeResponse::connection_error())
687 .on("POST https://a.test/pay", FakeResponse::status(503))
688 .on(
689 "POST https://a.test/pay",
690 FakeResponse::json(201, serde_json::json!({"id": 7})),
691 );
692 let response = http
693 .post("https://a.test/pay")
694 .json(&serde_json::json!({"total": 5}))
695 .retry(2, Duration::ZERO)
696 .send()
697 .await
698 .unwrap();
699 assert_eq!(response.status(), StatusCode::CREATED);
700 assert_eq!(response.json::<serde_json::Value>().unwrap()["id"], 7);
701 fake.assert_sent_count(3);
702 assert_eq!(fake.sent()[0].json()["total"], 5);
703 assert_eq!(
704 fake.sent()[0].header("Content-Type"),
705 Some("application/json")
706 );
707
708 fake.on("https://a.test/flaky", FakeResponse::status(500));
710 let res = http.get("https://a.test/flaky").send().await.unwrap();
711 assert!(res.clone().error_for_status().is_err());
712 assert!(!res.ok());
713 assert!(
714 http.get("https://a.test/none").send().await.is_err(),
715 "no fake"
716 );
717 }
718
719 #[tokio::test]
720 async fn sign_adds_verifiable_standard_webhooks_headers() {
721 let secret = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
722 let http = Http::default();
723 let fake = http.fake();
724 fake.on("POST https://a.test/hook", FakeResponse::status(200));
725 http.post("https://a.test/hook")
726 .json(&serde_json::json!({"a": 1}))
727 .sign("billing", secret)
728 .send()
729 .await
730 .unwrap();
731 let sent = &fake.sent()[0];
732 assert_eq!(sent.header("webhook-key-id"), Some("billing"));
733 assert!(sent.header("webhook-id").unwrap().starts_with("msg_"));
734 assert!(crate::webhook::signing::verify(
735 secret,
736 sent.header("webhook-id").unwrap(),
737 sent.header("webhook-timestamp").unwrap(),
738 sent.header("webhook-signature").unwrap(),
739 sent.body.as_bytes(),
740 Duration::from_secs(300),
741 ));
742
743 assert!(
745 http.post("https://a.test/hook")
746 .sign("billing", "whsec_***")
747 .send()
748 .await
749 .is_err()
750 );
751 }
752
753 #[tokio::test]
754 async fn builds_urls_and_headers() {
755 let http = Http::default();
756 let fake = http.fake();
757 fake.on("*", FakeResponse::text(200, "ok"));
758 http.get("https://a.test/r?x=1")
759 .query(&[("q", "iced coffee"), ("n", "2")])
760 .bearer("t0k")
761 .send()
762 .await
763 .unwrap();
764 http.post("https://a.test/f")
765 .basic_auth("u", "p")
766 .form(&[("a", "1 2")])
767 .send()
768 .await
769 .unwrap();
770 let sent = fake.sent();
771 assert_eq!(sent[0].url, "https://a.test/r?x=1&q=iced+coffee&n=2");
772 assert_eq!(sent[0].header("authorization"), Some("Bearer t0k"));
773 assert_eq!(sent[1].header("authorization"), Some("Basic dTpw"));
774 assert_eq!(sent[1].body, "a=1+2");
775 fake.assert_sent(|r| r.method == "POST");
776 fake.assert_not_sent(|r| r.method == "DELETE");
777 }
778
779 #[tokio::test]
782 async fn put_patch_raw_bodies_and_response_helpers() {
783 let http = Http::default();
784 let fake = http.fake();
785 fake.on(
786 "PUT https://api.test/items/1",
787 FakeResponse::text(200, "not json").header("x-request-id", "r1"),
788 );
789 fake.on("PATCH https://api.test/items/1", FakeResponse::status(204));
790 let res = http
791 .put("https://api.test/items/1")
792 .body("text/csv", "a,b\n1,2")
793 .send()
794 .await
795 .unwrap();
796 assert_eq!(res.header("X-Request-Id"), Some("r1"));
797 assert_eq!(res.bytes(), b"not json");
798 let err = res.json::<serde_json::Value>().unwrap_err();
799 assert!(
800 format!("{err:?}")
801 .contains("the response of https://api.test/items/1 is not the expected JSON"),
802 "{err:?}"
803 );
804 http.patch("https://api.test/items/1").send().await.unwrap();
805 let sent = fake.sent();
806 assert_eq!(sent[0].method, "PUT");
807 assert_eq!(sent[0].body, "a,b\n1,2");
808 assert!(
809 sent[0]
810 .headers
811 .iter()
812 .any(|(k, v)| k == "content-type" && v == "text/csv")
813 );
814 assert_eq!(sent[1].method, "PATCH");
815 assert_eq!(format!("{http:?}"), "Http");
817 }
818
819 #[tokio::test]
820 async fn bodies_that_cant_be_encoded_fail_at_send() {
821 let http = Http::default();
822 let fake = http.fake();
823 let mut odd = std::collections::HashMap::new();
824 odd.insert((1, 2), 3);
825 assert!(
826 http.post("https://api.test/a")
827 .json(&odd)
828 .send()
829 .await
830 .is_err()
831 );
832 let nested = [("a", vec![1, 2])];
833 assert!(
834 http.post("https://api.test/b")
835 .form(&nested)
836 .send()
837 .await
838 .is_err()
839 );
840 assert!(fake.sent().is_empty(), "nothing was sent");
841 }
842
843 #[tokio::test]
844 #[should_panic(
845 expected = "no matching HTTP request was sent; sent: [\n \"GET https://api.test/x\",\n]"
846 )]
847 async fn assert_sent_lists_what_was_sent() {
848 let http = Http::default();
849 let fake = http.fake();
850 fake.on("https://api.test/*", FakeResponse::status(200));
851 http.get("https://api.test/x").send().await.unwrap();
852 fake.assert_sent(|r| r.method == "POST");
853 }
854}