1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
use std::{fmt, str::FromStr};

use parse_display::Display;
use serde::{Deserialize, Serialize};
use thiserror::Error;
pub use url::ParseError;
use url::Url;

// `url::Url::scheme()` returns lower-cased ASCII string without `:`
const SCHEMES: [&str; 2] = ["http", "https"];

#[derive(Debug, Error, PartialEq, Eq)]
pub enum Error {
    #[error("Invalid scheme '{0}', only 'http' & 'https' are allowed")]
    InvalidScheme(String),
    #[error("The Url has to be a base, i.e. `data:`, `mailto:` etc. are not allowed")]
    ShouldBeABase,
    #[error("Having a fragment (i.e. `#fragment`) is not allowed")]
    HasFragment,
    #[error("Having a query parameters (i.e. `?query_param=value`) is not allowed")]
    HasQuery,
    #[error("Parsing the url: {0}")]
    Parsing(#[from] url::ParseError),
}

/// A safe Url to use in REST API calls.
///
/// It makes sure to always end the Url with `/`,
/// however it doesn't check for the existence of a file, e.g. `/path/a-file.html`
///
/// Underneath it uses [`url::Url`], so all the validation from there is enforced,
/// with additional validation which doesn't allow having:
/// - `Scheme` different that `http` & `https`
/// - Non-base `url`s like `data:` & `mailto:`
/// - `Fragment`, e.g. `#fragment`
/// - `Query`, e.g. `?query_param=value`, `?query_param`, `?query=value&....`, etc.
///
/// [`url::Url`]: url::Url
#[derive(Clone, Hash, Display, Ord, PartialOrd, Eq, PartialEq, Deserialize, Serialize)]
#[serde(try_from = "Url", into = "Url")]
pub struct ApiUrl(Url);

impl ApiUrl {
    pub fn parse(input: &str) -> Result<Self, Error> {
        Self::from_str(input)
    }

    /// The Endpoint of which we want to get an url to (strips prefixed `/` from the endpoint),
    /// which can can include:
    ///
    /// - path
    /// - query
    /// - fragments - usually should not be used for requesting API resources from server
    ///
    /// This method does **not** check if a file is present
    ///
    /// This method strips the starting `/` of the endpoint, if there is one
    pub fn join(&self, endpoint: &str) -> Result<Url, ParseError> {
        let stripped = endpoint.strip_prefix('/').unwrap_or(endpoint);
        // this join is safe, since we always prefix the Url with `/`
        self.0.join(stripped)
    }

    pub fn to_url(&self) -> Url {
        self.0.clone()
    }

    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl fmt::Debug for ApiUrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Url({})", self)
    }
}

impl TryFrom<Url> for ApiUrl {
    type Error = Error;

    fn try_from(mut url: Url) -> Result<Self, Self::Error> {
        if url.cannot_be_a_base() {
            return Err(Error::ShouldBeABase);
        }

        if url.fragment().is_some() {
            return Err(Error::HasFragment);
        }

        if !SCHEMES.contains(&url.scheme()) {
            return Err(Error::InvalidScheme(url.scheme().to_string()));
        }

        if url.query().is_some() {
            return Err(Error::HasQuery);
        }

        let url_path = url.path();

        let mut stripped_path = url_path.strip_suffix('/').unwrap_or(url_path).to_string();
        // Make sure to always end the path with `/`!
        stripped_path.push('/');

        url.set_path(&stripped_path);

        Ok(Self(url))
    }
}

impl From<ApiUrl> for Url {
    fn from(api_url: ApiUrl) -> Self {
        api_url.0
    }
}

impl FromStr for ApiUrl {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(s.parse::<Url>()?)
    }
}

#[cfg(test)]
mod test {
    use url::ParseError;

    use super::*;

    #[test]
    fn api_url() {
        let allowed = vec![
            // Http
            (
                "http://127.0.0.1/",
                ApiUrl::from_str("http://127.0.0.1/").unwrap(),
            ),
            (
                "http://127.0.0.1",
                ApiUrl::from_str("http://127.0.0.1/").unwrap(),
            ),
            // Https
            (
                "https://127.0.0.1/",
                ApiUrl::from_str("https://127.0.0.1/").unwrap(),
            ),
            (
                "https://127.0.0.1",
                ApiUrl::from_str("https://127.0.0.1/").unwrap(),
            ),
            // Domain `/` suffixed
            (
                "https://jerry.adex.network/",
                ApiUrl::from_str("https://jerry.adex.network/").unwrap(),
            ),
            (
                "https://tom.adex.network",
                ApiUrl::from_str("https://tom.adex.network/").unwrap(),
            ),
            // With Port
            (
                "https://localhost:3335",
                ApiUrl::from_str("https://localhost:3335/").unwrap(),
            ),
            // With Path non `/` suffixed
            (
                "https://localhost/leader",
                ApiUrl::from_str("https://localhost/leader/").unwrap(),
            ),
            // With Path `/` suffixed
            (
                "https://localhost/leader/",
                ApiUrl::from_str("https://localhost/leader/").unwrap(),
            ),
            // with authority
            (
                "https://username:password@localhost",
                ApiUrl::from_str("https://username:password@localhost/").unwrap(),
            ),
            // HTTPS, authority, domain, port and path
            (
                "https://username:password@jerry.adex.network:3335/leader",
                ApiUrl::from_str("https://username:password@jerry.adex.network:3335/leader")
                    .unwrap(),
            ),
        ];

        let failing = vec![
            // Unix socket
            (
                "unix:/run/foo.socket",
                Error::InvalidScheme("unix".to_string()),
            ),
            // A file URL
            (
                "file://127.0.0.1/",
                Error::InvalidScheme("file".to_string()),
            ),
            // relative path
            (
                "/relative/path",
                Error::Parsing(ParseError::RelativeUrlWithoutBase),
            ),
            (
                "/relative/path/",
                Error::Parsing(ParseError::RelativeUrlWithoutBase),
            ),
            // blob
            ("data:text/plain,Stuff", Error::ShouldBeABase),
        ];

        for (case, expected) in allowed {
            let url = case.parse::<ApiUrl>();
            assert_eq!(url, Ok(expected))
        }

        for (case, error) in failing {
            assert_eq!(case.parse::<ApiUrl>(), Err(error))
        }
    }

    #[test]
    fn api_endpoint() {
        let api_url = ApiUrl::parse("http://127.0.0.1/leader").expect("It is a valid API URL");

        let expected = url::Url::parse("http://127.0.0.1/leader/endpoint?query=query value")
            .expect("it is a valid Url");
        let expected_url_encoded = "http://127.0.0.1/leader/endpoint?query=query%20value";

        let actual = api_url
            .join("endpoint?query=query value")
            .expect("Should join endpoint");
        let actual_should_strip_suffix = api_url
            .join("/endpoint?query=query value")
            .expect("Should join endpoint and strip `/` suffix and preserve the original ApiUrl");
        assert_eq!(&expected, &actual);
        assert_eq!(&expected, &actual_should_strip_suffix);

        assert_eq!(expected_url_encoded, &actual.to_string());
        assert_eq!(
            expected_url_encoded,
            &actual_should_strip_suffix.to_string()
        );
    }
}