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
use crate::headers::{HeaderName, HeaderValue, Headers, ToHeaderValues, ETAG};
use crate::{Error, StatusCode};

use std::fmt::{self, Debug, Display};
use std::option;

/// HTTP Entity Tags.

///

/// ETags provide an ID for a particular resource, enabling clients and servers

/// to reason about caches and make conditional requests.

///

/// # Specifications

///

/// - [RFC 7232, section 2.3: ETag](https://tools.ietf.org/html/rfc7232#section-2.3)

///

/// # Examples

///

/// ```

/// # fn main() -> http_types::Result<()> {

/// #

/// use http_types::Response;

/// use http_types::conditional::ETag;

///

/// let etag = ETag::new("0xcafebeef".to_string());

///

/// let mut res = Response::new(200);

/// etag.apply(&mut res);

///

/// let etag = ETag::from_headers(res)?.unwrap();

/// assert_eq!(etag, ETag::Strong(String::from("0xcafebeef")));

/// #

/// # Ok(()) }

/// ```

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ETag {
    /// An ETag using strong validation.

    Strong(String),
    /// An ETag using weak validation.

    Weak(String),
}

impl ETag {
    /// Create a new ETag that uses strong validation.

    pub fn new(s: String) -> Self {
        debug_assert!(!s.contains('\\'), "ETags ought to avoid backslash chars");
        Self::Strong(s)
    }

    /// Create a new ETag that uses weak validation.

    pub fn new_weak(s: String) -> Self {
        debug_assert!(!s.contains('\\'), "ETags ought to avoid backslash chars");
        Self::Weak(s)
    }

    /// Create a new instance from headers.

    ///

    /// Only a single ETag per resource is assumed to exist. If multiple ETag

    /// headers are found the last one is used.

    pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> {
        let headers = match headers.as_ref().get(ETAG) {
            Some(headers) => headers,
            None => return Ok(None),
        };

        // If a header is returned we can assume at least one exists.

        let s = headers.iter().last().unwrap().as_str();
        Self::from_str(s).map(Some)
    }

    /// Sets the `ETag` header.

    pub fn apply(&self, mut headers: impl AsMut<Headers>) {
        headers.as_mut().insert(ETAG, self.value());
    }

    /// Get the `HeaderName`.

    pub fn name(&self) -> HeaderName {
        ETAG
    }

    /// Get the `HeaderValue`.

    pub fn value(&self) -> HeaderValue {
        let s = self.to_string();
        // SAFETY: the internal string is validated to be ASCII.

        unsafe { HeaderValue::from_bytes_unchecked(s.into()) }
    }

    /// Returns `true` if the ETag is a `Strong` value.

    pub fn is_strong(&self) -> bool {
        matches!(self, Self::Strong(_))
    }

    /// Returns `true` if the ETag is a `Weak` value.

    pub fn is_weak(&self) -> bool {
        matches!(self, Self::Weak(_))
    }

    /// Create an Etag from a string.

    pub(crate) fn from_str(s: &str) -> crate::Result<Self> {
        let mut weak = false;
        let s = match s.strip_prefix("W/") {
            Some(s) => {
                weak = true;
                s
            }
            None => s,
        };

        let s = match s.strip_prefix('"').and_then(|s| s.strip_suffix('"')) {
            Some(s) => s.to_owned(),
            None => {
                return Err(Error::from_str(
                    StatusCode::BadRequest,
                    "Invalid ETag header",
                ))
            }
        };

        if !s
            .bytes()
            .all(|c| c == 0x21 || (c >= 0x23 && c <= 0x7E) || c >= 0x80)
        {
            return Err(Error::from_str(
                StatusCode::BadRequest,
                "Invalid ETag header",
            ));
        }

        let etag = if weak { Self::Weak(s) } else { Self::Strong(s) };
        Ok(etag)
    }
}

impl Display for ETag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Strong(s) => write!(f, r#""{}""#, s),
            Self::Weak(s) => write!(f, r#"W/"{}""#, s),
        }
    }
}

impl ToHeaderValues for ETag {
    type Iter = option::IntoIter<HeaderValue>;
    fn to_header_values(&self) -> crate::Result<Self::Iter> {
        // A HeaderValue will always convert into itself.

        Ok(self.value().to_header_values().unwrap())
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::headers::Headers;

    #[test]
    fn smoke() -> crate::Result<()> {
        let etag = ETag::new("0xcafebeef".to_string());

        let mut headers = Headers::new();
        etag.apply(&mut headers);

        let etag = ETag::from_headers(headers)?.unwrap();
        assert_eq!(etag, ETag::Strong(String::from("0xcafebeef")));
        Ok(())
    }

    #[test]
    fn smoke_weak() -> crate::Result<()> {
        let etag = ETag::new_weak("0xcafebeef".to_string());

        let mut headers = Headers::new();
        etag.apply(&mut headers);

        let etag = ETag::from_headers(headers)?.unwrap();
        assert_eq!(etag, ETag::Weak(String::from("0xcafebeef")));
        Ok(())
    }

    #[test]
    fn bad_request_on_parse_error() -> crate::Result<()> {
        let mut headers = Headers::new();
        headers.insert(ETAG, "<nori ate the tag. yum.>");
        let err = ETag::from_headers(headers).unwrap_err();
        assert_eq!(err.status(), 400);
        Ok(())
    }

    #[test]
    fn validate_quotes() -> crate::Result<()> {
        assert_entry_err(r#""hello"#, "Invalid ETag header");
        assert_entry_err(r#"hello""#, "Invalid ETag header");
        assert_entry_err(r#"/O"valid content""#, "Invalid ETag header");
        assert_entry_err(r#"/Wvalid content""#, "Invalid ETag header");
        Ok(())
    }

    fn assert_entry_err(s: &str, msg: &str) {
        let mut headers = Headers::new();
        headers.insert(ETAG, s);
        let err = ETag::from_headers(headers).unwrap_err();
        assert_eq!(format!("{}", err), msg);
    }

    #[test]
    fn validate_characters() -> crate::Result<()> {
        assert_entry_err(r#"""hello""#, "Invalid ETag header");
        assert_entry_err("\"hello\x7F\"", "Invalid ETag header");
        Ok(())
    }
}