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
155fn host_message(body: &str) -> Option<String> {
160 let value: serde_json::Value = serde_json::from_str(body).ok()?;
161 for key in ["message", "error", "error_description"] {
162 match value.get(key) {
163 Some(serde_json::Value::String(text)) => {
164 let extra: Vec<String> = value
166 .get("errors")
167 .and_then(|e| e.as_array())
168 .map(|rows| {
169 rows.iter()
170 .map(|row| match row {
171 serde_json::Value::String(s) => s.clone(),
172 other => other
173 .get("message")
174 .and_then(|m| m.as_str())
175 .map(str::to_string)
176 .unwrap_or_else(|| {
177 let field = other
178 .get("field")
179 .and_then(|f| f.as_str())
180 .unwrap_or("?");
181 let code = other
182 .get("code")
183 .and_then(|c| c.as_str())
184 .unwrap_or("invalid");
185 format!("{field}: {code}")
186 }),
187 })
188 .collect()
189 })
190 .unwrap_or_default();
191 return Some(if extra.is_empty() {
192 text.clone()
193 } else {
194 format!("{text} ({})", extra.join("; "))
195 });
196 }
197 Some(obj @ serde_json::Value::Object(_)) => return Some(obj.to_string()),
199 _ => {}
200 }
201 }
202 None
203}
204
205fn truncate(text: &str, max: usize) -> String {
206 let text = text.trim();
207 if text.chars().count() <= max {
208 return text.to_string();
209 }
210 let cut: String = text.chars().take(max).collect();
211 format!("{cut}...")
212}
213
214#[async_trait::async_trait]
215pub trait HttpTransport: Send + Sync {
216 async fn send(&self, request: HttpRequest) -> Result<HttpResponse>;
217
218 async fn download(&self, request: HttpRequest, progress: &Progress<'_>) -> Result<Vec<u8>> {
222 let _ = (request, progress);
223 Err(Error::Http("this transport cannot download files".into()))
224 }
225}
226
227pub type Progress<'a> = dyn Fn(u64, Option<u64>) -> bool + Send + Sync + 'a;
230
231#[derive(Default)]
237pub struct RecordedTransport {
238 responses: std::sync::Mutex<Vec<(String, HttpResponse)>>,
239 files: std::sync::Mutex<Vec<(String, Vec<u8>)>>,
240 seen: std::sync::Mutex<Vec<HttpRequest>>,
241}
242
243impl RecordedTransport {
244 pub fn new() -> Self {
245 Self::default()
246 }
247
248 pub fn on(self, url_fragment: &str, status: u16, body: &str) -> Self {
252 self.responses.lock().unwrap().push((
253 url_fragment.to_string(),
254 HttpResponse {
255 status,
256 headers: BTreeMap::new(),
257 body: body.to_string(),
258 },
259 ));
260 self
261 }
262
263 pub fn on_with_headers(
266 self,
267 url_fragment: &str,
268 status: u16,
269 body: &str,
270 headers: &[(&str, &str)],
271 ) -> Self {
272 self.responses.lock().unwrap().push((
273 url_fragment.to_string(),
274 HttpResponse {
275 status,
276 headers: headers
277 .iter()
278 .map(|(k, v)| (k.to_string(), v.to_string()))
279 .collect(),
280 body: body.to_string(),
281 },
282 ));
283 self
284 }
285
286 pub fn on_file(self, url_fragment: &str, bytes: Vec<u8>) -> Self {
289 self.files
290 .lock()
291 .unwrap()
292 .push((url_fragment.to_string(), bytes));
293 self
294 }
295
296 pub fn requests(&self) -> Vec<HttpRequest> {
297 self.seen.lock().unwrap().clone()
298 }
299}
300
301#[async_trait::async_trait]
302impl HttpTransport for RecordedTransport {
303 async fn download(&self, request: HttpRequest, progress: &Progress<'_>) -> Result<Vec<u8>> {
304 self.seen.lock().unwrap().push(request.clone());
305 let bytes = {
306 let files = self.files.lock().unwrap();
307 files
308 .iter()
309 .find(|(fragment, _)| request.url.contains(fragment.as_str()))
310 .map(|(_, bytes)| bytes.clone())
311 };
312 let Some(bytes) = bytes else {
313 return Err(Error::Http(format!(
314 "RecordedTransport has no file for {}",
315 request.url
316 )));
317 };
318 let total = bytes.len() as u64;
319 let mut received = 0u64;
320 for chunk in bytes.chunks(64 * 1024) {
321 received += chunk.len() as u64;
322 if !progress(received, Some(total)) {
323 return Err(Error::Http("download canceled".into()));
324 }
325 }
326 Ok(bytes)
327 }
328
329 async fn send(&self, request: HttpRequest) -> Result<HttpResponse> {
330 self.seen.lock().unwrap().push(request.clone());
331 let responses = self.responses.lock().unwrap();
332 let position = responses
336 .iter()
337 .position(|(fragment, _)| request.url.contains(fragment.as_str()));
338 match position {
339 Some(i) => Ok(responses[i].1.clone()),
340 None => Err(Error::Http(format!(
341 "RecordedTransport has no response for {} {}",
342 request.method.as_str(),
343 request.url
344 ))),
345 }
346 }
347}
348
349pub const BLOCK_EXTERNAL_ENV: &str = "GITPOULPI_BLOCK_EXTERNAL_HOSTS";
353pub const LIVE_TESTS_ENV: &str = "GITPOULPI_LIVE_TESTS";
355
356pub fn external_host_refusal(url: &str) -> Option<String> {
361 let on = |name: &str| matches!(std::env::var(name).as_deref(), Ok("1") | Ok("true"));
362 refusal(
363 url,
364 cfg!(test) || on(BLOCK_EXTERNAL_ENV),
365 on(LIVE_TESTS_ENV),
366 )
367}
368
369fn refusal(url: &str, blocking: bool, live: bool) -> Option<String> {
370 if !blocking || live {
371 return None;
372 }
373 let host = url_host(url)?;
374 if is_loopback_host(&host) {
375 return None;
376 }
377 Some(format!(
378 "refusing to connect to {host} from a test: tests only reach loopback; \
379 set {LIVE_TESTS_ENV}=1 for a live run"
380 ))
381}
382
383fn url_host(url: &str) -> Option<String> {
384 let rest = url.split_once("://").map_or(url, |(_, r)| r);
385 let authority = rest.split(['/', '?', '#']).next()?;
386 let hostport = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
387 let host = if let Some(v6) = hostport.strip_prefix('[') {
388 v6.split(']').next()?
389 } else {
390 hostport.split(':').next()?
391 };
392 Some(host.to_ascii_lowercase())
393}
394
395fn is_loopback_host(host: &str) -> bool {
396 host == "localhost" || host.ends_with(".localhost") || host == "::1" || host.starts_with("127.")
397}
398
399#[cfg(feature = "network")]
401fn same_origin_redirects() -> reqwest::redirect::Policy {
402 reqwest::redirect::Policy::custom(|attempt| {
403 let same = attempt.previous().last().is_some_and(|prev| {
404 prev.scheme() == attempt.url().scheme()
405 && prev.host_str() == attempt.url().host_str()
406 && prev.port_or_known_default() == attempt.url().port_or_known_default()
407 });
408 if attempt.previous().len() >= 5 {
409 attempt.error("too many redirects")
410 } else if same {
411 attempt.follow()
412 } else {
413 attempt.stop()
414 }
415 })
416}
417
418#[cfg(feature = "network")]
422fn send_error(error: &reqwest::Error, url: &str) -> Error {
423 use std::error::Error as _;
424 let mut text = error.to_string();
425 let mut source = error.source();
426 while let Some(s) = source {
427 text.push(' ');
428 text.push_str(&s.to_string());
429 source = s.source();
430 }
431 if text.to_ascii_lowercase().contains("certificate") {
432 if let Some(problem) =
433 crate::trust::origin::host_of(url).and_then(|h| crate::trust::tls::problem_for(&h))
434 {
435 return Error::Trust(problem);
436 }
437 }
438 Error::Http(error.to_string())
439}
440
441#[cfg(feature = "network")]
444pub struct ReqwestTransport {
445 client: reqwest::Client,
446 download_hosts: std::sync::Arc<Vec<String>>,
449}
450
451#[cfg(feature = "network")]
452impl ReqwestTransport {
453 pub fn new() -> Result<Self> {
454 Self::with_timeout(std::time::Duration::from_secs(30))
455 }
456
457 pub fn with_timeout(timeout: std::time::Duration) -> Result<Self> {
461 let client = reqwest::Client::builder()
462 .user_agent(concat!("gitpoulpi/", env!("CARGO_PKG_VERSION")))
463 .use_preconfigured_tls(crate::trust::tls::client_config().map_err(Error::Http)?)
466 .redirect(same_origin_redirects())
470 .timeout(timeout)
472 .pool_max_idle_per_host(0)
478 .build()
479 .map_err(|e| Error::Http(e.to_string()))?;
480 Ok(Self {
481 client,
482 download_hosts: std::sync::Arc::default(),
483 })
484 }
485
486 #[must_use]
490 pub fn with_download_hosts(mut self, hosts: Vec<String>) -> Self {
491 self.download_hosts = std::sync::Arc::new(hosts);
492 self
493 }
494}
495
496#[cfg(feature = "network")]
497#[async_trait::async_trait]
498impl HttpTransport for ReqwestTransport {
499 async fn send(&self, request: HttpRequest) -> Result<HttpResponse> {
500 let method = match request.method {
501 Method::Get => reqwest::Method::GET,
502 Method::Post => reqwest::Method::POST,
503 Method::Put => reqwest::Method::PUT,
504 Method::Patch => reqwest::Method::PATCH,
505 Method::Delete => reqwest::Method::DELETE,
506 };
507 if let Some(why) = external_host_refusal(&request.url) {
508 return Err(Error::Http(why));
509 }
510 let request_url = request.url.clone();
511 let mut builder = self.client.request(method, &request.url);
512 for (name, value) in &request.headers {
513 builder = builder.header(name, value);
514 }
515 if let Some(body) = request.body {
516 builder = builder.body(body);
517 }
518 let response = builder
519 .send()
520 .await
521 .map_err(|e| send_error(&e, &request_url))?;
522 let status = response.status().as_u16();
523 let headers = response
524 .headers()
525 .iter()
526 .filter_map(|(k, v)| Some((k.as_str().to_string(), v.to_str().ok()?.to_string())))
527 .collect();
528 let body = response
529 .text()
530 .await
531 .map_err(|e| Error::Http(e.to_string()))?;
532 Ok(HttpResponse {
533 status,
534 headers,
535 body,
536 })
537 }
538
539 async fn download(&self, request: HttpRequest, progress: &Progress<'_>) -> Result<Vec<u8>> {
543 if !crate::updates::download_host_allowed_with(&request.url, &self.download_hosts) {
544 return Err(Error::Http(format!(
545 "refusing to download from {}: not a GitHub release host",
546 request.url
547 )));
548 }
549 if let Some(why) = external_host_refusal(&request.url) {
550 return Err(Error::Http(why));
551 }
552 let hosts = self.download_hosts.clone();
553 let policy = reqwest::redirect::Policy::custom(move |attempt| {
554 if attempt.previous().len() >= 5 {
555 attempt.error("too many redirects")
556 } else if crate::updates::download_host_allowed_with(attempt.url().as_str(), &hosts) {
557 attempt.follow()
558 } else {
559 let host = attempt.url().host_str().unwrap_or("?").to_string();
560 attempt.error(format!(
561 "redirect to {host} refused: not a GitHub release host"
562 ))
563 }
564 });
565 let client = reqwest::Client::builder()
566 .user_agent(concat!("gitpoulpi/", env!("CARGO_PKG_VERSION")))
567 .use_preconfigured_tls(crate::trust::tls::client_config().map_err(Error::Http)?)
568 .redirect(policy)
569 .read_timeout(std::time::Duration::from_secs(30))
571 .connect_timeout(std::time::Duration::from_secs(15))
572 .pool_max_idle_per_host(0)
573 .build()
574 .map_err(|e| Error::Http(e.to_string()))?;
575 let mut builder = client.get(&request.url);
576 for (name, value) in &request.headers {
577 builder = builder.header(name, value);
578 }
579 let url = request.url.clone();
580 let mut response = builder.send().await.map_err(|e| send_error(&e, &url))?;
581 let status = response.status();
582 if !status.is_success() {
583 return Err(Error::Http(format!(
584 "the download answered HTTP {}",
585 status.as_u16()
586 )));
587 }
588 let total = response.content_length();
589 let mut out = Vec::with_capacity(total.unwrap_or(0).min(256 << 20) as usize);
590 while let Some(chunk) = response
591 .chunk()
592 .await
593 .map_err(|e| Error::Http(e.to_string()))?
594 {
595 out.extend_from_slice(&chunk);
596 if !progress(out.len() as u64, total) {
597 return Err(Error::Http("download canceled".into()));
598 }
599 }
600 Ok(out)
601 }
602}
603
604#[cfg(test)]
605mod tests {
606 use super::*;
607
608 #[test]
609 fn a_hosts_own_error_message_survives_into_the_error() {
610 let response = HttpResponse {
611 status: 401,
612 headers: BTreeMap::new(),
613 body: r#"{"message":"Bad credentials"}"#.into(),
614 };
615 let err = response.error_for_status("listing projects").unwrap_err();
616 let text = err.to_string();
617 assert!(text.contains("Bad credentials"), "{text}");
618 assert!(text.contains("listing projects"), "{text}");
619 assert!(matches!(err, Error::Unauthorized { .. }));
620 }
621
622 #[test]
626 fn a_non_json_error_body_is_truncated_rather_than_dumped() {
627 let response = HttpResponse {
628 status: 500,
629 headers: BTreeMap::new(),
630 body: "x".repeat(5000),
631 };
632 let text = response
633 .error_for_status("listing projects")
634 .unwrap_err()
635 .to_string();
636 assert!(text.len() < 400, "error was {} chars", text.len());
637 assert!(text.ends_with("..."));
638 }
639
640 #[test]
641 fn a_success_is_not_an_error() {
642 let response = HttpResponse {
643 status: 204,
644 headers: BTreeMap::new(),
645 body: String::new(),
646 };
647 assert!(response.error_for_status("anything").is_ok());
648 }
649
650 #[cfg(feature = "network")]
657 #[test]
658 fn a_request_never_picks_up_a_connection_frozen_on_another_runtime() {
659 use std::io::{Read, Write};
660 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
661 let url = format!("http://{}/x", listener.local_addr().unwrap());
662 std::thread::spawn(move || {
663 for stream in listener.incoming().flatten() {
664 std::thread::spawn(move || {
665 let mut stream = stream;
666 let mut seen = Vec::new();
667 let mut buf = [0u8; 1024];
668 while let Ok(n) = stream.read(&mut buf) {
670 if n == 0 {
671 return;
672 }
673 seen.extend_from_slice(&buf[..n]);
674 while let Some(end) = seen.windows(4).position(|w| w == b"\r\n\r\n") {
675 seen.drain(..end + 4);
676 let _ =
677 stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok");
678 }
679 }
680 });
681 }
682 });
683 let transport = ReqwestTransport::with_timeout(std::time::Duration::from_secs(3)).unwrap();
684 let mut parked = Vec::new();
685 for _ in 0..3 {
686 let rt = tokio::runtime::Builder::new_current_thread()
687 .enable_all()
688 .build()
689 .unwrap();
690 let request = HttpRequest {
691 method: Method::Get,
692 url: url.clone(),
693 headers: Vec::new(),
694 body: None,
695 };
696 let response = rt.block_on(transport.send(request)).unwrap();
697 assert_eq!(response.body, "ok");
698 parked.push(rt);
699 }
700 }
701
702 #[test]
703 fn a_blocked_build_refuses_external_hosts_but_not_loopback() {
704 for url in [
705 "http://127.0.0.1:3000/api",
706 "http://localhost:8081/",
707 "http://[::1]:80/x",
708 "http://user:pw@127.0.0.1/",
709 ] {
710 assert_eq!(refusal(url, true, false), None, "{url}");
711 }
712 for url in [
713 "https://api.github.com/user",
714 "https://gitlab.com/api/v4",
715 "http://user@example.org:80/x",
716 ] {
717 assert!(refusal(url, true, false).is_some(), "{url}");
718 assert_eq!(refusal(url, true, true), None, "live switch lifts it");
719 assert_eq!(refusal(url, false, false), None, "production never refuses");
720 }
721 }
722}