Skip to main content

git_remote_refs/
http.rs

1use crate::Error;
2use alloc::{string::String, vec, vec::Vec};
3
4pub(crate) const ADVERTISEMENT: &str = "application/x-git-upload-pack-advertisement";
5pub(crate) const REQUEST: &str = "application/x-git-upload-pack-request";
6pub(crate) const RESULT: &str = "application/x-git-upload-pack-result";
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum Method {
10    Get,
11    Post,
12}
13
14impl Method {
15    pub const fn as_str(self) -> &'static str {
16        match self {
17            Self::Get => "GET",
18            Self::Post => "POST",
19        }
20    }
21}
22
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct Request {
25    pub method: Method,
26    pub url: String,
27    pub headers: Vec<(&'static str, &'static str)>,
28    pub body: Vec<u8>,
29}
30
31#[derive(Clone, Copy, Debug)]
32pub struct Response<'a> {
33    pub status: u16,
34    pub content_type: Option<&'a str>,
35    pub body: &'a [u8],
36}
37
38#[derive(Clone, Debug, PartialEq, Eq)]
39pub struct Remote {
40    url: String,
41}
42
43impl Remote {
44    pub fn new(url: &str) -> Result<Self, Error> {
45        let rest = strip_scheme(url, "https://")
46            .or_else(|| strip_scheme(url, "http://"))
47            .ok_or(Error::InvalidUrl)?;
48        let invalid = |byte: u8| byte <= b' ' || byte == 0x7f || byte == b'?' || byte == b'#';
49        if rest.is_empty() || rest.starts_with('/') || url.bytes().any(invalid) {
50            return Err(Error::InvalidUrl);
51        }
52        Ok(Self {
53            url: url.trim_end_matches('/').into(),
54        })
55    }
56
57    pub fn url(&self) -> &str {
58        &self.url
59    }
60
61    pub fn discovery_request(&self) -> Request {
62        Request {
63            method: Method::Get,
64            url: alloc::format!("{}/info/refs?service=git-upload-pack", self.url),
65            headers: vec![("Accept", ADVERTISEMENT), ("Git-Protocol", "version=2")],
66            body: Vec::new(),
67        }
68    }
69
70    pub(crate) fn post(&self, body: Vec<u8>) -> Request {
71        Request {
72            method: Method::Post,
73            url: alloc::format!("{}/git-upload-pack", self.url),
74            headers: vec![
75                ("Content-Type", REQUEST),
76                ("Accept", RESULT),
77                ("Git-Protocol", "version=2"),
78            ],
79            body,
80        }
81    }
82}
83
84fn strip_scheme<'a>(url: &'a str, scheme: &str) -> Option<&'a str> {
85    let head = url.get(..scheme.len())?;
86    head.eq_ignore_ascii_case(scheme)
87        .then(|| &url[scheme.len()..])
88}
89
90pub(crate) fn body<'a>(response: &Response<'a>, content_type: &str) -> Result<&'a [u8], Error> {
91    match response.status {
92        200..=299 => {}
93        401 | 403 => return Err(Error::AuthRequired(response.status)),
94        404 => return Err(Error::NotFound),
95        status => return Err(Error::Http(status)),
96    }
97    let media_type = response
98        .content_type
99        .and_then(|value| value.split(';').next())
100        .map(str::trim);
101    if !media_type.is_some_and(|value| value.eq_ignore_ascii_case(content_type)) {
102        return Err(Error::NotSmartHttp);
103    }
104    Ok(response.body)
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    #[test]
112    fn accepts_http_urls_and_trims_trailing_slashes() {
113        let remote = Remote::new("HTTPS://github.com/denoland/setup-deno.git/").unwrap();
114        assert_eq!(remote.url(), "HTTPS://github.com/denoland/setup-deno.git");
115        assert_eq!(
116            remote.discovery_request().url,
117            "HTTPS://github.com/denoland/setup-deno.git/info/refs?service=git-upload-pack"
118        );
119        assert_eq!(
120            Remote::new("http://localhost:8080/repo")
121                .unwrap()
122                .post(Vec::new())
123                .url,
124            "http://localhost:8080/repo/git-upload-pack"
125        );
126    }
127
128    #[test]
129    fn rejects_other_schemes_queries_fragments_and_whitespace() {
130        for url in [
131            "ssh://github.com/a/b",
132            "https://",
133            "https:///path",
134            "https://host/a?b",
135            "https://host/a#b",
136            "https://host/a b",
137            "github.com/a/b",
138        ] {
139            assert_eq!(Remote::new(url), Err(Error::InvalidUrl), "{url}");
140        }
141    }
142
143    #[test]
144    fn maps_status_and_content_type() {
145        let response = |status, content_type| Response {
146            status,
147            content_type,
148            body: b"x",
149        };
150        assert_eq!(
151            body(
152                &response(200, Some("application/x-git-upload-pack-result; charset=x")),
153                RESULT
154            ),
155            Ok(&b"x"[..])
156        );
157        assert_eq!(
158            body(&response(401, None), RESULT),
159            Err(Error::AuthRequired(401))
160        );
161        assert_eq!(
162            body(&response(403, None), RESULT),
163            Err(Error::AuthRequired(403))
164        );
165        assert_eq!(body(&response(404, None), RESULT), Err(Error::NotFound));
166        assert_eq!(body(&response(500, None), RESULT), Err(Error::Http(500)));
167        assert_eq!(
168            body(&response(200, Some("text/plain")), RESULT),
169            Err(Error::NotSmartHttp)
170        );
171        assert_eq!(body(&response(200, None), RESULT), Err(Error::NotSmartHttp));
172    }
173}