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
//! Utilities for working with URLs

use log::warn;

/// Make sure a URL is safe to use
///
/// ## Usage
/// ```
/// use revelio::url::sanitize;
///
/// // Insert HTTPS and trailing slash:
/// assert_eq!(sanitize("example.com"), "https://example.com/");
///
/// // Convert HTTP to HTTPS (and insert trailing slash)
/// assert_eq!(sanitize("http://example.com"), "https://example.com/");
///
/// // Convert HTTP to HTTPS
/// assert_eq!(sanitize("http://example.com/"), "https://example.com/");
///
/// // Insert trailing slash:
/// assert_eq!(sanitize("https://example.com"), "https://example.com/");
///
/// // Already sanitized is a no-op:
/// assert_eq!(sanitize("https://example.com/"), "https://example.com/");
/// ```
/// Resulting URL will be HTTPS and end with a trailing slash.
pub fn sanitize(url: &str) -> String {
  let url = match url.ends_with("/") {
    true => String::from(url),
    false => String::from(url) + "/",
  };
  // Insert protocol if needed
  let url = match url {
    _ if url.starts_with("https://") => url,
    _ if url.starts_with("http://") => {
      warn!("HTTPS is required, rewriting URL.");
      url.replace("http://", "https://")
    }
    _ => format!("https://{}", url),
  };
  url
}

#[test]
fn sanitize_domain_name() {
  let received = sanitize("example.com");
  let expected = "https://example.com/";
  assert_eq!(received, expected);
}

#[test]
fn sanitize_trailing_slash() {
  let received = sanitize("https://example.com");
  let expected = "https://example.com/";
  assert_eq!(received, expected);
}

#[test]
fn sanitize_https() {
  let received = sanitize("http://example.com/");
  let expected = "https://example.com/";
  assert_eq!(received, expected);
}

#[test]
fn sanitize_no_op() {
  let received = sanitize("https://example.com/");
  let expected = "https://example.com/";
  assert_eq!(received, expected);
}