Skip to main content

lux_lib/
reqwest.rs

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