1use std::collections::BTreeMap;
9
10use crate::{Error, Result};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Method {
14 Get,
15 Post,
16 Put,
17 Patch,
18 Delete,
19}
20
21impl Method {
22 pub fn as_str(self) -> &'static str {
23 match self {
24 Self::Get => "GET",
25 Self::Post => "POST",
26 Self::Put => "PUT",
27 Self::Patch => "PATCH",
28 Self::Delete => "DELETE",
29 }
30 }
31}
32
33#[derive(Debug, Clone)]
34pub struct HttpRequest {
35 pub method: Method,
36 pub url: String,
37 pub headers: Vec<(String, String)>,
38 pub body: Option<String>,
40}
41
42impl HttpRequest {
43 pub fn get(url: impl Into<String>) -> Self {
44 Self {
45 method: Method::Get,
46 url: url.into(),
47 headers: Vec::new(),
48 body: None,
49 }
50 }
51
52 pub fn delete(url: impl Into<String>) -> Self {
53 Self {
54 method: Method::Delete,
55 url: url.into(),
56 headers: Vec::new(),
57 body: None,
58 }
59 }
60
61 pub fn post_json(url: impl Into<String>, body: &serde_json::Value) -> Self {
62 Self {
63 method: Method::Post,
64 url: url.into(),
65 headers: vec![("Content-Type".into(), "application/json".into())],
66 body: Some(body.to_string()),
67 }
68 }
69
70 pub fn put_json(url: impl Into<String>, body: &serde_json::Value) -> Self {
71 Self {
72 method: Method::Put,
73 ..Self::post_json(url, body)
74 }
75 }
76
77 pub fn patch_json(url: impl Into<String>, body: &serde_json::Value) -> Self {
78 Self {
79 method: Method::Patch,
80 ..Self::post_json(url, body)
81 }
82 }
83
84 pub fn delete_json(url: impl Into<String>, body: &serde_json::Value) -> Self {
86 Self {
87 method: Method::Delete,
88 ..Self::post_json(url, body)
89 }
90 }
91
92 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
93 self.headers.push((name.into(), value.into()));
94 self
95 }
96}
97
98#[derive(Debug, Clone)]
99pub struct HttpResponse {
100 pub status: u16,
101 pub headers: BTreeMap<String, String>,
102 pub body: String,
103}
104
105impl HttpResponse {
106 pub fn is_success(&self) -> bool {
107 (200..300).contains(&self.status)
108 }
109
110 pub fn error_for_status(&self, what: &str) -> Result<()> {
115 if self.is_success() {
116 return Ok(());
117 }
118 if crate::conditional::is_rate_limited(self) {
119 let now = std::time::SystemTime::now()
120 .duration_since(std::time::UNIX_EPOCH)
121 .map(|d| d.as_secs())
122 .unwrap_or(0);
123 let wait = crate::conditional::rate_state(self, now)
124 .map(|(_, reset)| reset.saturating_sub(now))
125 .unwrap_or(60);
126 return Err(Error::RateLimited {
127 host: what.to_string(),
128 retry_in_secs: wait.max(1),
129 });
130 }
131 let detail = host_message(&self.body).unwrap_or_else(|| self.body.trim().to_string());
132 let detail = truncate(&detail, 300);
133 Err(match self.status {
134 401 => Error::Unauthorized {
135 what: what.to_string(),
136 detail,
137 },
138 403 => Error::Forbidden {
139 what: what.to_string(),
140 detail,
141 },
142 status => Error::Api {
143 what: what.to_string(),
144 status,
145 detail,
146 },
147 })
148 }
149
150 pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T> {
151 serde_json::from_str(&self.body).map_err(|e| Error::Decode(e.to_string()))
152 }
153}
154
155#[derive(Debug, Clone)]
158pub struct HttpBytes {
159 pub status: u16,
160 pub headers: BTreeMap<String, String>,
161 pub body: Vec<u8>,
162}
163
164fn host_message(body: &str) -> Option<String> {
169 let value: serde_json::Value = serde_json::from_str(body).ok()?;
170 for key in ["message", "error", "error_description"] {
171 match value.get(key) {
172 Some(serde_json::Value::String(text)) => {
173 let extra: Vec<String> = value
175 .get("errors")
176 .and_then(|e| e.as_array())
177 .map(|rows| {
178 rows.iter()
179 .map(|row| match row {
180 serde_json::Value::String(s) => s.clone(),
181 other => other
182 .get("message")
183 .and_then(|m| m.as_str())
184 .map(str::to_string)
185 .unwrap_or_else(|| {
186 let field = other
187 .get("field")
188 .and_then(|f| f.as_str())
189 .unwrap_or("?");
190 let code = other
191 .get("code")
192 .and_then(|c| c.as_str())
193 .unwrap_or("invalid");
194 format!("{field}: {code}")
195 }),
196 })
197 .collect()
198 })
199 .unwrap_or_default();
200 return Some(if extra.is_empty() {
201 text.clone()
202 } else {
203 format!("{text} ({})", extra.join("; "))
204 });
205 }
206 Some(obj @ serde_json::Value::Object(_)) => return Some(obj.to_string()),
208 _ => {}
209 }
210 }
211 None
212}
213
214fn truncate(text: &str, max: usize) -> String {
215 let text = text.trim();
216 if text.chars().count() <= max {
217 return text.to_string();
218 }
219 let cut: String = text.chars().take(max).collect();
220 format!("{cut}...")
221}
222
223#[async_trait::async_trait]
224pub trait HttpTransport: Send + Sync {
225 async fn send(&self, request: HttpRequest) -> Result<HttpResponse>;
226
227 async fn download(&self, request: HttpRequest, progress: &Progress<'_>) -> Result<Vec<u8>> {
231 let _ = (request, progress);
232 Err(Error::Http("this transport cannot download files".into()))
233 }
234
235 async fn fetch_bytes(&self, request: HttpRequest) -> Result<HttpBytes> {
240 let _ = request;
241 Err(Error::Http(
242 "this transport cannot fetch binary bodies".into(),
243 ))
244 }
245}
246
247pub type Progress<'a> = dyn Fn(u64, Option<u64>) -> bool + Send + Sync + 'a;
250
251#[derive(Default)]
257pub struct RecordedTransport {
258 responses: std::sync::Mutex<Vec<(String, HttpResponse)>>,
259 files: std::sync::Mutex<Vec<(String, Vec<u8>)>>,
260 seen: std::sync::Mutex<Vec<HttpRequest>>,
261}
262
263impl RecordedTransport {
264 pub fn new() -> Self {
265 Self::default()
266 }
267
268 pub fn on(self, url_fragment: &str, status: u16, body: &str) -> Self {
272 self.responses.lock().unwrap().push((
273 url_fragment.to_string(),
274 HttpResponse {
275 status,
276 headers: BTreeMap::new(),
277 body: body.to_string(),
278 },
279 ));
280 self
281 }
282
283 pub fn on_with_headers(
286 self,
287 url_fragment: &str,
288 status: u16,
289 body: &str,
290 headers: &[(&str, &str)],
291 ) -> Self {
292 self.responses.lock().unwrap().push((
293 url_fragment.to_string(),
294 HttpResponse {
295 status,
296 headers: headers
297 .iter()
298 .map(|(k, v)| (k.to_string(), v.to_string()))
299 .collect(),
300 body: body.to_string(),
301 },
302 ));
303 self
304 }
305
306 pub fn on_file(self, url_fragment: &str, bytes: Vec<u8>) -> Self {
309 self.files
310 .lock()
311 .unwrap()
312 .push((url_fragment.to_string(), bytes));
313 self
314 }
315
316 pub fn requests(&self) -> Vec<HttpRequest> {
317 self.seen.lock().unwrap().clone()
318 }
319}
320
321#[async_trait::async_trait]
322impl HttpTransport for RecordedTransport {
323 async fn download(&self, request: HttpRequest, progress: &Progress<'_>) -> Result<Vec<u8>> {
324 self.seen.lock().unwrap().push(request.clone());
325 let bytes = {
326 let files = self.files.lock().unwrap();
327 files
328 .iter()
329 .find(|(fragment, _)| request.url.contains(fragment.as_str()))
330 .map(|(_, bytes)| bytes.clone())
331 };
332 let Some(bytes) = bytes else {
333 return Err(Error::Http(format!(
334 "RecordedTransport has no file for {}",
335 request.url
336 )));
337 };
338 let total = bytes.len() as u64;
339 let mut received = 0u64;
340 for chunk in bytes.chunks(64 * 1024) {
341 received += chunk.len() as u64;
342 if !progress(received, Some(total)) {
343 return Err(Error::Http("download canceled".into()));
344 }
345 }
346 Ok(bytes)
347 }
348
349 async fn fetch_bytes(&self, request: HttpRequest) -> Result<HttpBytes> {
352 self.seen.lock().unwrap().push(request.clone());
353 let file = {
354 let files = self.files.lock().unwrap();
355 files
356 .iter()
357 .find(|(fragment, _)| request.url.contains(fragment.as_str()))
358 .map(|(_, bytes)| bytes.clone())
359 };
360 if let Some(body) = file {
361 return Ok(HttpBytes {
362 status: 200,
363 headers: BTreeMap::new(),
364 body,
365 });
366 }
367 let responses = self.responses.lock().unwrap();
368 match responses
369 .iter()
370 .find(|(fragment, _)| request.url.contains(fragment.as_str()))
371 {
372 Some((_, response)) => Ok(HttpBytes {
373 status: response.status,
374 headers: response.headers.clone(),
375 body: response.body.clone().into_bytes(),
376 }),
377 None => Err(Error::Http(format!(
378 "RecordedTransport has no response for {}",
379 request.url
380 ))),
381 }
382 }
383
384 async fn send(&self, request: HttpRequest) -> Result<HttpResponse> {
385 self.seen.lock().unwrap().push(request.clone());
386 let responses = self.responses.lock().unwrap();
387 let position = responses
391 .iter()
392 .position(|(fragment, _)| request.url.contains(fragment.as_str()));
393 match position {
394 Some(i) => Ok(responses[i].1.clone()),
395 None => Err(Error::Http(format!(
396 "RecordedTransport has no response for {} {}",
397 request.method.as_str(),
398 request.url
399 ))),
400 }
401 }
402}
403
404pub const BLOCK_EXTERNAL_ENV: &str = "GITPOULPI_BLOCK_EXTERNAL_HOSTS";
408pub const LIVE_TESTS_ENV: &str = "GITPOULPI_LIVE_TESTS";
410
411pub fn external_host_refusal(url: &str) -> Option<String> {
416 let on = |name: &str| matches!(std::env::var(name).as_deref(), Ok("1") | Ok("true"));
417 refusal(
418 url,
419 cfg!(test) || on(BLOCK_EXTERNAL_ENV),
420 on(LIVE_TESTS_ENV),
421 )
422}
423
424fn refusal(url: &str, blocking: bool, live: bool) -> Option<String> {
425 if !blocking || live {
426 return None;
427 }
428 let host = url_host(url)?;
429 if is_loopback_host(&host) {
430 return None;
431 }
432 Some(format!(
433 "refusing to connect to {host} from a test: tests only reach loopback; \
434 set {LIVE_TESTS_ENV}=1 for a live run"
435 ))
436}
437
438fn url_host(url: &str) -> Option<String> {
439 let rest = url.split_once("://").map_or(url, |(_, r)| r);
440 let authority = rest.split(['/', '?', '#']).next()?;
441 let hostport = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
442 let host = if let Some(v6) = hostport.strip_prefix('[') {
443 v6.split(']').next()?
444 } else {
445 hostport.split(':').next()?
446 };
447 Some(host.to_ascii_lowercase())
448}
449
450fn is_loopback_host(host: &str) -> bool {
451 host == "localhost" || host.ends_with(".localhost") || host == "::1" || host.starts_with("127.")
452}
453
454#[cfg(feature = "network")]
456fn same_origin_redirects() -> reqwest::redirect::Policy {
457 reqwest::redirect::Policy::custom(|attempt| {
458 let same = attempt.previous().last().is_some_and(|prev| {
459 prev.scheme() == attempt.url().scheme()
460 && prev.host_str() == attempt.url().host_str()
461 && prev.port_or_known_default() == attempt.url().port_or_known_default()
462 });
463 if attempt.previous().len() >= 5 {
464 attempt.error("too many redirects")
465 } else if same {
466 attempt.follow()
467 } else {
468 attempt.stop()
469 }
470 })
471}
472
473#[cfg(feature = "network")]
477fn send_error(error: &reqwest::Error, url: &str) -> Error {
478 use std::error::Error as _;
479 let mut text = error.to_string();
480 let mut source = error.source();
481 while let Some(s) = source {
482 text.push(' ');
483 text.push_str(&s.to_string());
484 source = s.source();
485 }
486 if text.to_ascii_lowercase().contains("certificate") {
487 if let Some(problem) =
488 crate::trust::origin::host_of(url).and_then(|h| crate::trust::tls::problem_for(&h))
489 {
490 return Error::Trust(problem);
491 }
492 }
493 Error::Http(error.to_string())
494}
495
496#[cfg(feature = "network")]
499pub struct ReqwestTransport {
500 client: reqwest::Client,
501 download_hosts: std::sync::Arc<Vec<String>>,
504}
505
506#[cfg(feature = "network")]
507impl ReqwestTransport {
508 pub fn new() -> Result<Self> {
509 Self::with_timeout(std::time::Duration::from_secs(30))
510 }
511
512 pub fn with_timeout(timeout: std::time::Duration) -> Result<Self> {
516 let client = reqwest::Client::builder()
517 .user_agent(concat!("gitpoulpi/", env!("CARGO_PKG_VERSION")))
518 .use_preconfigured_tls(crate::trust::tls::client_config().map_err(Error::Http)?)
521 .redirect(same_origin_redirects())
525 .timeout(timeout)
527 .pool_max_idle_per_host(0)
533 .build()
534 .map_err(|e| Error::Http(e.to_string()))?;
535 Ok(Self {
536 client,
537 download_hosts: std::sync::Arc::default(),
538 })
539 }
540
541 #[must_use]
545 pub fn with_download_hosts(mut self, hosts: Vec<String>) -> Self {
546 self.download_hosts = std::sync::Arc::new(hosts);
547 self
548 }
549}
550
551#[cfg(feature = "network")]
552#[async_trait::async_trait]
553impl HttpTransport for ReqwestTransport {
554 async fn send(&self, request: HttpRequest) -> Result<HttpResponse> {
555 let method = match request.method {
556 Method::Get => reqwest::Method::GET,
557 Method::Post => reqwest::Method::POST,
558 Method::Put => reqwest::Method::PUT,
559 Method::Patch => reqwest::Method::PATCH,
560 Method::Delete => reqwest::Method::DELETE,
561 };
562 if let Some(why) = external_host_refusal(&request.url) {
563 return Err(Error::Http(why));
564 }
565 let request_url = request.url.clone();
566 let mut builder = self.client.request(method, &request.url);
567 for (name, value) in &request.headers {
568 builder = builder.header(name, value);
569 }
570 if let Some(body) = request.body {
571 builder = builder.body(body);
572 }
573 let response = builder
574 .send()
575 .await
576 .map_err(|e| send_error(&e, &request_url))?;
577 let status = response.status().as_u16();
578 let headers = response
579 .headers()
580 .iter()
581 .filter_map(|(k, v)| Some((k.as_str().to_string(), v.to_str().ok()?.to_string())))
582 .collect();
583 let body = response
584 .text()
585 .await
586 .map_err(|e| Error::Http(e.to_string()))?;
587 Ok(HttpResponse {
588 status,
589 headers,
590 body,
591 })
592 }
593
594 async fn fetch_bytes(&self, request: HttpRequest) -> Result<HttpBytes> {
599 if let Some(why) = external_host_refusal(&request.url) {
600 return Err(Error::Http(why));
601 }
602 let client = reqwest::Client::builder()
603 .user_agent(concat!("gitpoulpi/", env!("CARGO_PKG_VERSION")))
604 .use_preconfigured_tls(crate::trust::tls::client_config().map_err(Error::Http)?)
605 .redirect(reqwest::redirect::Policy::limited(5))
606 .timeout(std::time::Duration::from_secs(5))
607 .pool_max_idle_per_host(0)
608 .build()
609 .map_err(|e| Error::Http(e.to_string()))?;
610 let url = request.url.clone();
611 let mut builder = client.get(&request.url);
612 for (name, value) in &request.headers {
613 builder = builder.header(name, value);
614 }
615 let response = builder.send().await.map_err(|e| send_error(&e, &url))?;
616 let status = response.status().as_u16();
617 let headers = response
618 .headers()
619 .iter()
620 .filter_map(|(k, v)| Some((k.as_str().to_string(), v.to_str().ok()?.to_string())))
621 .collect();
622 let body = response
623 .bytes()
624 .await
625 .map_err(|e| Error::Http(e.to_string()))?
626 .to_vec();
627 Ok(HttpBytes {
628 status,
629 headers,
630 body,
631 })
632 }
633
634 async fn download(&self, request: HttpRequest, progress: &Progress<'_>) -> Result<Vec<u8>> {
638 if !crate::updates::download_host_allowed_with(&request.url, &self.download_hosts) {
639 return Err(Error::Http(format!(
640 "refusing to download from {}: not a GitHub release host",
641 request.url
642 )));
643 }
644 if let Some(why) = external_host_refusal(&request.url) {
645 return Err(Error::Http(why));
646 }
647 let hosts = self.download_hosts.clone();
648 let policy = reqwest::redirect::Policy::custom(move |attempt| {
649 if attempt.previous().len() >= 5 {
650 attempt.error("too many redirects")
651 } else if crate::updates::download_host_allowed_with(attempt.url().as_str(), &hosts) {
652 attempt.follow()
653 } else {
654 let host = attempt.url().host_str().unwrap_or("?").to_string();
655 attempt.error(format!(
656 "redirect to {host} refused: not a GitHub release host"
657 ))
658 }
659 });
660 let client = reqwest::Client::builder()
661 .user_agent(concat!("gitpoulpi/", env!("CARGO_PKG_VERSION")))
662 .use_preconfigured_tls(crate::trust::tls::client_config().map_err(Error::Http)?)
663 .redirect(policy)
664 .read_timeout(std::time::Duration::from_secs(30))
666 .connect_timeout(std::time::Duration::from_secs(15))
667 .pool_max_idle_per_host(0)
668 .build()
669 .map_err(|e| Error::Http(e.to_string()))?;
670 let mut builder = client.get(&request.url);
671 for (name, value) in &request.headers {
672 builder = builder.header(name, value);
673 }
674 let url = request.url.clone();
675 let mut response = builder.send().await.map_err(|e| send_error(&e, &url))?;
676 let status = response.status();
677 if !status.is_success() {
678 return Err(Error::Http(format!(
679 "the download answered HTTP {}",
680 status.as_u16()
681 )));
682 }
683 let total = response.content_length();
684 let mut out = Vec::with_capacity(total.unwrap_or(0).min(256 << 20) as usize);
685 while let Some(chunk) = response
686 .chunk()
687 .await
688 .map_err(|e| Error::Http(e.to_string()))?
689 {
690 out.extend_from_slice(&chunk);
691 if !progress(out.len() as u64, total) {
692 return Err(Error::Http("download canceled".into()));
693 }
694 }
695 Ok(out)
696 }
697}
698
699#[cfg(test)]
700mod tests {
701 use super::*;
702
703 #[test]
704 fn a_hosts_own_error_message_survives_into_the_error() {
705 let response = HttpResponse {
706 status: 401,
707 headers: BTreeMap::new(),
708 body: r#"{"message":"Bad credentials"}"#.into(),
709 };
710 let err = response.error_for_status("listing projects").unwrap_err();
711 let text = err.to_string();
712 assert!(text.contains("Bad credentials"), "{text}");
713 assert!(text.contains("listing projects"), "{text}");
714 assert!(matches!(err, Error::Unauthorized { .. }));
715 }
716
717 #[test]
721 fn a_non_json_error_body_is_truncated_rather_than_dumped() {
722 let response = HttpResponse {
723 status: 500,
724 headers: BTreeMap::new(),
725 body: "x".repeat(5000),
726 };
727 let text = response
728 .error_for_status("listing projects")
729 .unwrap_err()
730 .to_string();
731 assert!(text.len() < 400, "error was {} chars", text.len());
732 assert!(text.ends_with("..."));
733 }
734
735 #[test]
736 fn a_success_is_not_an_error() {
737 let response = HttpResponse {
738 status: 204,
739 headers: BTreeMap::new(),
740 body: String::new(),
741 };
742 assert!(response.error_for_status("anything").is_ok());
743 }
744
745 #[cfg(feature = "network")]
752 #[test]
753 fn a_request_never_picks_up_a_connection_frozen_on_another_runtime() {
754 use std::io::{Read, Write};
755 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
756 let url = format!("http://{}/x", listener.local_addr().unwrap());
757 std::thread::spawn(move || {
758 for stream in listener.incoming().flatten() {
759 std::thread::spawn(move || {
760 let mut stream = stream;
761 let mut seen = Vec::new();
762 let mut buf = [0u8; 1024];
763 while let Ok(n) = stream.read(&mut buf) {
765 if n == 0 {
766 return;
767 }
768 seen.extend_from_slice(&buf[..n]);
769 while let Some(end) = seen.windows(4).position(|w| w == b"\r\n\r\n") {
770 seen.drain(..end + 4);
771 let _ =
772 stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok");
773 }
774 }
775 });
776 }
777 });
778 let transport = ReqwestTransport::with_timeout(std::time::Duration::from_secs(3)).unwrap();
779 let mut parked = Vec::new();
780 for _ in 0..3 {
781 let rt = tokio::runtime::Builder::new_current_thread()
782 .enable_all()
783 .build()
784 .unwrap();
785 let request = HttpRequest {
786 method: Method::Get,
787 url: url.clone(),
788 headers: Vec::new(),
789 body: None,
790 };
791 let response = rt.block_on(transport.send(request)).unwrap();
792 assert_eq!(response.body, "ok");
793 parked.push(rt);
794 }
795 }
796
797 #[test]
798 fn a_blocked_build_refuses_external_hosts_but_not_loopback() {
799 for url in [
800 "http://127.0.0.1:3000/api",
801 "http://localhost:8081/",
802 "http://[::1]:80/x",
803 "http://user:pw@127.0.0.1/",
804 ] {
805 assert_eq!(refusal(url, true, false), None, "{url}");
806 }
807 for url in [
808 "https://api.github.com/user",
809 "https://gitlab.com/api/v4",
810 "http://user@example.org:80/x",
811 ] {
812 assert!(refusal(url, true, false).is_some(), "{url}");
813 assert_eq!(refusal(url, true, true), None, "live switch lifts it");
814 assert_eq!(refusal(url, false, false), None, "production never refuses");
815 }
816 }
817}