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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
use std::fmt;
use std::str::FromStr;

use url::Url;

use auth::{auth_from_dsn_and_client, Auth};
use project_id::{ProjectId, ProjectIdParseError};

/// Represents a dsn url parsing error.
#[derive(Debug, Fail)]
pub enum DsnParseError {
    /// raised on completely invalid urls
    #[fail(display = "no valid url provided")]
    InvalidUrl,
    /// raised the scheme is invalid / unsupported.
    #[fail(display = "no valid scheme")]
    InvalidScheme,
    /// raised if the username (public key) portion is missing.
    #[fail(display = "username is empty")]
    NoUsername,
    /// raised the project is is missing (first path component)
    #[fail(display = "empty path")]
    NoProjectId,
    /// raised the project id is invalid.
    #[fail(display = "invalid project id")]
    InvalidProjectId(#[cause] ProjectIdParseError),
}

/// Represents the scheme of an url http/https.
///
/// This holds schemes that are supported by sentry and relays.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum Scheme {
    /// unencrypted HTTP scheme (should not be used)
    Http,
    /// encrypted HTTPS scheme
    Https,
}

impl Scheme {
    /// Returns the default port for this scheme.
    pub fn default_port(&self) -> u16 {
        match *self {
            Scheme::Http => 80,
            Scheme::Https => 443,
        }
    }
}

impl fmt::Display for Scheme {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            match *self {
                Scheme::Https => "https",
                Scheme::Http => "http",
            }
        )
    }
}

/// Represents a Sentry dsn.
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct Dsn {
    scheme: Scheme,
    public_key: String,
    secret_key: Option<String>,
    host: String,
    port: Option<u16>,
    project_id: ProjectId,
}

impl Dsn {
    /// Converts the dsn into an auth object.
    ///
    /// This always attaches the latest and greatest protocol
    /// version to the auth header.
    pub fn to_auth(&self, client_agent: Option<&str>) -> Auth {
        auth_from_dsn_and_client(self, client_agent)
    }

    /// Returns the submission API URL.
    pub fn store_api_url(&self) -> Url {
        use std::fmt::Write;
        let mut buf = format!("{}://{}", self.scheme(), self.host());
        if self.port() != self.scheme.default_port() {
            write!(&mut buf, ":{}", self.port()).unwrap();
        }
        write!(&mut buf, "/api/{}/store/", self.project_id()).unwrap();
        Url::parse(&buf).unwrap()
    }

    /// Returns the scheme
    pub fn scheme(&self) -> Scheme {
        self.scheme
    }

    /// Returns the public_key
    pub fn public_key(&self) -> &str {
        &self.public_key
    }

    /// Returns secret_key
    pub fn secret_key(&self) -> Option<&str> {
        self.secret_key.as_ref().map(|x| x.as_str())
    }

    /// Returns the host
    pub fn host(&self) -> &str {
        &self.host
    }

    /// Returns the port
    pub fn port(&self) -> u16 {
        self.port.unwrap_or_else(|| self.scheme.default_port())
    }

    /// Returns the project_id
    pub fn project_id(&self) -> ProjectId {
        self.project_id
    }
}

impl fmt::Display for Dsn {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}://{}", self.scheme, self.public_key)?;
        if let Some(ref secret_key) = self.secret_key {
            write!(f, ":{}", secret_key)?;
        }
        write!(f, "@{}", self.host)?;
        if let Some(ref port) = self.port {
            write!(f, ":{}", port)?;
        }
        write!(f, "/{}", self.project_id)?;
        Ok(())
    }
}

impl FromStr for Dsn {
    type Err = DsnParseError;

    fn from_str(s: &str) -> Result<Dsn, DsnParseError> {
        let url = Url::parse(s).map_err(|_| DsnParseError::InvalidUrl)?;

        if url.path() == "/" {
            return Err(DsnParseError::NoProjectId);
        }

        let path_segments = url.path_segments()
            .ok_or_else(|| DsnParseError::NoProjectId)?;
        if path_segments.count() > 1 {
            return Err(DsnParseError::InvalidUrl);
        }

        let public_key = match url.username() {
            "" => return Err(DsnParseError::NoUsername),
            username => username.to_string(),
        };

        let scheme = match url.scheme() {
            "http" => Scheme::Http,
            "https" => Scheme::Https,
            _ => return Err(DsnParseError::InvalidScheme),
        };

        let secret_key = url.password().map(|s| s.into());
        let port = url.port();
        let host = match url.host_str() {
            Some(host) => host.into(),
            None => return Err(DsnParseError::InvalidUrl),
        };
        let project_id = url.path()
            .trim_matches('/')
            .parse()
            .map_err(DsnParseError::InvalidProjectId)?;

        Ok(Dsn {
            scheme,
            public_key,
            secret_key,
            port,
            host,
            project_id,
        })
    }
}

impl_str_serialization!(Dsn);

#[cfg(test)]
mod test {

    use super::*;
    use serde_json;

    #[test]
    fn test_dsn_serialize_deserialize() {
        let dsn = Dsn::from_str("https://username@domain/42").unwrap();
        let serialized = serde_json::to_string(&dsn).unwrap();
        assert_eq!(serialized, "\"https://username@domain/42\"");
        let deserialized: Dsn = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized.to_string(), "https://username@domain/42");
    }

    #[test]
    fn test_dsn_parsing() {
        let url = "https://username:password@domain:8888/23";
        let dsn = url.parse::<Dsn>().unwrap();
        assert_eq!(dsn.scheme(), Scheme::Https);
        assert_eq!(dsn.public_key(), "username");
        assert_eq!(dsn.secret_key(), Some("password"));
        assert_eq!(dsn.host(), "domain");
        assert_eq!(dsn.port(), 8888);
        assert_eq!(dsn.project_id(), ProjectId::from(23));
        assert_eq!(url, dsn.to_string());
    }

    #[test]
    fn test_dsn_no_port() {
        let url = "https://username@domain/42";
        let dsn = Dsn::from_str(url).unwrap();
        assert_eq!(dsn.port(), 443);
        assert_eq!(url, dsn.to_string());
        assert_eq!(
            dsn.store_api_url().to_string(),
            "https://domain/api/42/store/"
        );
    }

    #[test]
    fn test_insecure_dsn_no_port() {
        let url = "http://username@domain/42";
        let dsn = Dsn::from_str(url).unwrap();
        assert_eq!(dsn.port(), 80);
        assert_eq!(url, dsn.to_string());
        assert_eq!(
            dsn.store_api_url().to_string(),
            "http://domain/api/42/store/"
        );
    }

    #[test]
    fn test_dsn_no_password() {
        let url = "https://username@domain:8888/42";
        let dsn = Dsn::from_str(url).unwrap();
        assert_eq!(url, dsn.to_string());
        assert_eq!(
            dsn.store_api_url().to_string(),
            "https://domain:8888/api/42/store/"
        );
    }

    #[test]
    fn test_dsn_http_url() {
        let url = "http://username@domain:8888/42";
        let dsn = Dsn::from_str(url).unwrap();
        assert_eq!(url, dsn.to_string());
    }

    #[test]
    #[should_panic(expected = "InvalidUrl")]
    fn test_dsn_more_than_one_non_integer_path() {
        Dsn::from_str("http://username@domain:8888/path/path2").unwrap();
    }

    #[test]
    #[should_panic(expected = "NoUsername")]
    fn test_dsn_no_username() {
        Dsn::from_str("https://:password@domain:8888/23").unwrap();
    }

    #[test]
    #[should_panic(expected = "InvalidUrl")]
    fn test_dsn_invalid_url() {
        Dsn::from_str("random string").unwrap();
    }

    #[test]
    #[should_panic(expected = "InvalidUrl")]
    fn test_dsn_no_host() {
        Dsn::from_str("https://username:password@:8888/42").unwrap();
    }

    #[test]
    #[should_panic(expected = "NoProjectId")]
    fn test_dsn_no_project_id() {
        Dsn::from_str("https://username:password@domain:8888/").unwrap();
    }

    #[test]
    #[should_panic(expected = "InvalidScheme")]
    fn test_dsn_invalid_scheme() {
        Dsn::from_str("ftp://username:password@domain:8888/1").unwrap();
    }
}