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
//! Backend server.

use std::str::FromStr;

/// The maximum length in characters of a backend name.
const MAX_BACKEND_NAME_LEN: usize = 255;

/// A named backend.
///
/// This represents a backend associated with a service that we can send requests to, potentially
/// caching the responses received.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Backend {
    name: String,
}

impl Backend {
    /// Get a backend by its name.
    ///
    /// This function will return a [`BackendError`] if an invalid name was given.
    ///
    /// Backend names:
    ///   * cannot be empty
    ///   * cannot be longer than 255 characters
    ///   * cannot ASCII control characters such as `'\n'` or `DELETE`.
    ///   * cannot contain special Unicode characters
    ///   * should only contain visible ASCII characters or spaces
    ///
    /// Future versions of this function may return an error if your service does not have a backend
    /// with this name.
    pub fn from_name(s: &str) -> Result<Self, BackendError> {
        s.parse()
    }

    /// Get the name of this backend.
    pub fn name(&self) -> &str {
        self.name.as_str()
    }

    /// Turn the backend into its name as a string.
    pub fn into_string(self) -> String {
        self.name
    }
}

/// [`Backend`]-related errors.
#[derive(Copy, Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum BackendError {
    /// The backend name was empty.
    #[error("an empty string is not a valid backend")]
    EmptyName,
    /// The backend name was too long.
    #[error("backend names must be <= 255 characters")]
    TooLong,
    /// The backend name contained invalid characters.
    #[error("backend names must only contain visible ASCII characters or spaces")]
    InvalidName,
}

impl FromStr for Backend {
    type Err = BackendError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        validate_backend(s)?;
        Ok(Self { name: s.to_owned() })
    }
}

impl std::fmt::Display for Backend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.name.as_str())
    }
}

/// Validate that a string looks like an acceptable [`Backend`] value.
///
/// Note that this is *not* meant to be a filter for things that could cause security issues, it is
/// only meant to catch errors before the hostcalls do in order to yield friendlier error messages.
///
/// This function will return a [`BackendError`] if an invalid name was given.
///
/// Backend names:
///   * cannot be empty
///   * cannot be longer than 255 characters
///   * cannot ASCII control characters such as `'\n'` or `DELETE`.
///   * cannot contain special Unicode characters
///   * should only contain visible ASCII characters or spaces
//
// TODO KTM 2020-03-10: We should not allow VCL keywords like `if`, `now`, `true`, `urldecode`, and
// so on. Once we have better errors, let's make sure that these are caught in a pleasant manner.
pub fn validate_backend(backend: &str) -> Result<(), BackendError> {
    if backend.is_empty() {
        Err(BackendError::EmptyName)
    } else if backend.len() > MAX_BACKEND_NAME_LEN {
        Err(BackendError::TooLong)
    } else if backend.chars().any(is_invalid_char) {
        Err(BackendError::InvalidName)
    } else {
        Ok(())
    }
}

/// Return true if a character is not allowed in a [`Backend`] name.
///
/// This is used to enforce the rules described in the documentation of [`Backend::from_name()`]. A
/// backend name should only contain visible ASCII characters, or spaces.
#[inline]
fn is_invalid_char(c: char) -> bool {
    c != ' ' && !c.is_ascii_graphic()
}

#[cfg(test)]
mod validate_backend_tests {
    use super::*;

    #[test]
    fn valid_backend_names_are_accepted() {
        let valid_backend_names = [
            "valid_backend_1",
            "1_backend_with_leading_integer",
            "backend-with-kebab-case",
            "backend with spaces",
            "backend.with.periods",
            "123_456_789_000",
            "123.456.789.000",
            "tilde~backend",
            "(parens-backend)",
        ];
        for backend in valid_backend_names.iter() {
            match validate_backend(backend) {
                Ok(_) => {}
                x => panic!(
                    "backend string \"{}\" yielded unexpected result: {:?}",
                    backend, x
                ),
            }
        }
    }

    #[test]
    fn empty_str_is_not_accepted() {
        let invalid_backend = "";
        match validate_backend(invalid_backend) {
            Err(BackendError::EmptyName) => {}
            x => panic!("unexpected result: {:?}", x),
        }
    }

    #[test]
    fn name_equal_to_character_limit_is_accepted() {
        use std::iter::FromIterator;
        let invalid_backend: String = String::from_iter(vec!['a'; 255]);
        match validate_backend(&invalid_backend) {
            Ok(_) => {}
            x => panic!("unexpected result: {:?}", x),
        }
    }

    #[test]
    fn name_longer_than_character_limit_are_not_accepted() {
        use std::iter::FromIterator;
        let invalid_backend: String = String::from_iter(vec!['a'; 256]);
        match validate_backend(&invalid_backend) {
            Err(BackendError::TooLong) => {}
            x => panic!("unexpected result: {:?}", x),
        }
    }

    #[test]
    fn unprintable_characters_are_not_accepted() {
        let invalid_backend = "\n";
        match validate_backend(invalid_backend) {
            Err(BackendError::InvalidName) => {}
            x => panic!("unexpected result: {:?}", x),
        }
    }

    #[test]
    fn unicode_is_not_accepted() {
        let invalid_backend = "♓";
        match validate_backend(invalid_backend) {
            Err(BackendError::InvalidName) => {}
            x => panic!("unexpected result: {:?}", x),
        }
    }
}