1use std::sync::OnceLock;
2
3use miette::Diagnostic;
4use reqwest::{header::AUTHORIZATION, Client, RequestBuilder};
5use thiserror::Error;
6use url::Url;
7
8use crate::config::{access_tokens::Kind, Config};
9
10const SOURCEHUT_HOST: &str = "git.sr.ht";
11
12static HTTPS_CLIENT: OnceLock<Client> = OnceLock::new();
13static HTTP_CLIENT: OnceLock<Client> = OnceLock::new();
14
15#[derive(Error, Debug, Diagnostic)]
17#[non_exhaustive]
18pub enum Error {
19 #[error("request refused")]
20 RequestRefused {
21 #[help]
22 help: String,
23 source: reqwest::Error,
24 },
25 #[error("resource not found")]
26 #[diagnostic(help("the resource could not be found. verify that it exists on the server."))]
27 NotFound(#[source] reqwest::Error),
28 #[error("request failed")]
29 #[diagnostic(help("check your network connection."))]
30 Other(#[source] reqwest::Error),
31}
32
33impl From<reqwest::Error> for Error {
34 fn from(err: reqwest::Error) -> Self {
35 if err.status() == Some(reqwest::StatusCode::NOT_FOUND) {
36 Self::NotFound(err)
37 } else if err.status().is_some_and(|status| status.is_client_error()) {
38 let for_host_str = match (err.url(), err.url().and_then(Url::host_str)) {
39 (_, Some(host)) => format!(" for {host}"),
40 (Some(url), None) => format!(" for the host of {url}"),
41 (None, None) => "".to_string(),
42 };
43 Self::RequestRefused {
44 help: format!(
45 r#"this could be an access-token issue. consider adding an access token{for_host_str}
46 in the `[access_tokens]` section of your Lux config,
47 or via the `LUX_ACCESS_TOKENS` environment variable."#
48 ),
49 source: err,
50 }
51 } else {
52 Self::Other(err)
53 }
54 }
55}
56
57pub(crate) trait RequestBuilderExt: private::Sealed {
61 fn apply_access_token(self, config: &Config, url: &Url) -> RequestBuilder;
62}
63
64impl RequestBuilderExt for reqwest::RequestBuilder {
65 fn apply_access_token(self, config: &Config, url: &Url) -> RequestBuilder {
66 if let Some(host) = url.host_str() {
67 if let Some(token) = config.access_token(host) {
68 let password = unsafe { token.password() };
69 return match (token.kind(), host) {
70 (Kind::GitLabPAT, _) => self.header("PRIVATE-TOKEN", password),
71 (Kind::GitLabOAuth2, _) | (Kind::Plain, SOURCEHUT_HOST) => {
72 self.header(AUTHORIZATION, format!("Bearer {password}"))
73 }
74 (Kind::Plain, _) => self.header(AUTHORIZATION, format!("token {password}")),
75 };
76 }
77 }
78 self
79 }
80}
81
82fn client(https_only: bool, config: &Config) -> Result<&Client, reqwest::Error> {
83 let enforce_https = https_only && !cfg!(test);
85
86 let cache = if enforce_https {
87 &HTTPS_CLIENT
88 } else {
89 &HTTP_CLIENT
90 };
91 if let Some(client) = cache.get() {
92 Ok(client)
93 } else {
94 let mut builder = Client::builder();
95 if enforce_https {
96 builder = builder.https_only(true);
97 }
98 let client = builder.user_agent(config.user_agent()).build()?;
99 Ok(cache.get_or_init(|| client))
101 }
102}
103
104pub fn https_client(config: &Config) -> Result<&Client, reqwest::Error> {
106 client(true, config)
107}
108
109pub(crate) fn http_client(config: &Config) -> Result<&Client, reqwest::Error> {
112 client(false, config)
113}
114
115mod private {
116 pub trait Sealed {}
117 impl Sealed for reqwest::RequestBuilder {}
118}
119
120#[cfg(test)]
121mod tests {
122 use httptest::{
123 matchers::{contains, request},
124 responders::status_code,
125 Expectation, Server,
126 };
127
128 use super::*;
129
130 fn config_with_token(host: &str, raw_token: &str) -> crate::config::Config {
131 let config: crate::config::Builder =
132 toml::from_str(&format!("[access_tokens]\n\"{host}\" = {raw_token:?}\n")).unwrap();
133 config.build().unwrap()
134 }
135
136 #[tokio::test]
137 async fn test_plain_token_uses_token_header() {
138 let server = Server::run();
139 server.expect(
140 Expectation::matching(request::headers(contains(("authorization", "token abc"))))
141 .respond_with(status_code(200)),
142 );
143 let url = Url::parse(&server.url("/").to_string()).unwrap();
144 let config = config_with_token(url.host_str().unwrap(), "abc");
145 let response = Client::new()
146 .get(url.clone())
147 .apply_access_token(&config, &url)
148 .send()
149 .await
150 .unwrap();
151 assert!(response.status().is_success());
152 }
153
154 #[test]
155 fn test_sourcehut_plain_token_uses_bearer_header() {
156 let url = Url::parse("https://git.sr.ht/~user/repo/archive/ref.tar.gz").unwrap();
157 let config = config_with_token("git.sr.ht", "abc");
158 let request = Client::new()
159 .get(url.clone())
160 .apply_access_token(&config, &url)
161 .build()
162 .unwrap();
163 assert_eq!(
164 request.headers().get("authorization").unwrap(),
165 "Bearer abc"
166 );
167 }
168
169 #[tokio::test]
170 async fn test_oauth2_token_uses_bearer_header() {
171 let server = Server::run();
172 server.expect(
173 Expectation::matching(request::headers(contains(("authorization", "Bearer abc"))))
174 .respond_with(status_code(200)),
175 );
176 let url = Url::parse(&server.url("/").to_string()).unwrap();
177 let config = config_with_token(url.host_str().unwrap(), "OAuth2:abc");
178 let response = Client::new()
179 .get(url.clone())
180 .apply_access_token(&config, &url)
181 .send()
182 .await
183 .unwrap();
184 assert!(response.status().is_success());
185 }
186
187 #[tokio::test]
188 async fn test_pat_token_uses_private_token_header() {
189 let server = Server::run();
190 server.expect(
191 Expectation::matching(request::headers(contains(("private-token", "abc"))))
192 .respond_with(status_code(200)),
193 );
194 let url = Url::parse(&server.url("/").to_string()).unwrap();
195 let config = config_with_token(url.host_str().unwrap(), "PAT:abc");
196 let response = Client::new()
197 .get(url.clone())
198 .apply_access_token(&config, &url)
199 .send()
200 .await
201 .unwrap();
202 assert!(response.status().is_success());
203 }
204}