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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Copyright (c) 2018 Weihang Lo
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::{
    error::SaphirError,
    file::etag::{EntityTag, SystemTimeExt},
    request::Request,
};
//use chrono::{DateTime, FixedOffset, Utc};
use hyper::Method;
use std::time::SystemTime;
use time::{
    format_description::{well_known::Rfc2822, FormatItem},
    macros::format_description,
    OffsetDateTime,
};

const DEPRECATED_HEADER_DATE_FORMAT: &[FormatItem<'static>] =
    format_description!("[weekday], [day]-[month repr:short]-[year repr:last_two] [hour]:[minute]:[second] [offset_hour][offset_minute]");
const DEPRECATED_HEADER_DATE_FORMAT2: &[FormatItem<'static>] =
    format_description!("[weekday repr:short] [month repr:short] [day] [hour]:[minute]:[second] [year]");

/// Validate precondition of `If-Match` header.
///
/// Note that an origin server MUST use the strong comparison function when
/// comparing entity-tags for `If-Match`.
///
/// [RFC7232: If-Match](https://tools.ietf.org/html/rfc7232#section-3.1)
fn check_if_match(etag: &EntityTag, if_match: &str) -> bool {
    if_match.trim() == "*" || if_match.split(',').any(|string| etag.strong_eq(EntityTag::parse(string.trim())))
}

/// Validate precondition of `If-None-Match` header.
///
/// Note that a recipient MUST use the weak comparison function when comparing
/// entity-tags for `If-None-Match`.
///
/// [RFC7232: If-None-Match](https://tools.ietf.org/html/rfc7232#section-3.2)
fn check_if_none_match(etag: &EntityTag, if_none_match: &str) -> bool {
    if_none_match.trim() != "*" && if_none_match.split(',').all(|string| !etag.weak_eq(EntityTag::parse(string.trim())))
}

/// Validate precondition of `If-Unmodified-Since` header.
fn check_if_unmodified_since(last_modified: &SystemTime, if_unmodified_since: &SystemTime) -> bool {
    last_modified.timestamp() <= if_unmodified_since.timestamp()
}

/// Validate precondition of `If-Modified-Since` header.
fn check_if_modified_since(last_modified: &SystemTime, if_modified_since: &SystemTime) -> bool {
    !check_if_unmodified_since(last_modified, if_modified_since)
}

fn is_method_get_head(method: &Method) -> bool {
    match *method {
        Method::GET | Method::HEAD => true,
        _ => false,
    }
}

/// Indicates that conditions given in the request header evaluted to false.
/// Return true if any preconditions fail.
///
/// Note that this method is only implemented partial precedence of
/// conditions defined in [RFC7232][1] which is only related to precondition
/// (Status Code 412) but not caching response (Status Code 304). Caller must
/// handle caching responses by themselves.
///
/// [1]: https://tools.ietf.org/html/rfc7232#section-6
pub fn is_precondition_failed(req: &Request, etag: &EntityTag, last_modified: &SystemTime) -> bool {
    // 1. Evaluate If-Match
    if let Some(if_match) = req.headers().get(http::header::IF_MATCH) {
        if check_if_match(etag, if_match.to_str().unwrap_or_default()) {
            // 3. Evaluate If-None-Match
            if req.headers().get(http::header::IF_NONE_MATCH).is_some() && !is_method_get_head(req.method()) {
                return true;
            }
        } else {
            return true;
        }
    }

    // 2. Evaluate If-Unmodified-Since
    if let Some(if_unmodified_since) = req
        .headers()
        .get(http::header::IF_UNMODIFIED_SINCE)
        .and_then(|header| header.to_str().ok())
        .and_then(|s| date_from_http_str(s).ok())
        .map(|time| time.into())
    {
        if check_if_unmodified_since(last_modified, &if_unmodified_since) {
            // 3. Evaluate If-None-Match
            if req.headers().get(http::header::IF_NONE_MATCH).is_some() && !is_method_get_head(req.method()) {
                return true;
            }
        } else {
            return true;
        }
    }

    // 3. Evaluate If-None-Match
    if req.headers().get(http::header::IF_NONE_MATCH).is_some() && !is_method_get_head(req.method()) {
        return true;
    }

    false
}

/// Determine freshness of requested resource by validate `If-None-Match`
/// and `If-Modified-Since` precondition header fields containing validators.
///
/// See more on [RFC7234, 4.3.2. Handling a Received Validation Request][1].
///
/// [1]: https://tools.ietf.org/html/rfc7234#section-4.3.2
pub fn is_fresh(req: &Request, etag: &EntityTag, last_modified: &SystemTime) -> bool {
    // `If-None-Match` takes presedence over `If-Modified-Since`.
    if let Some(Ok(if_none_match)) = req.headers().get(http::header::IF_NONE_MATCH).map(|header| header.to_str()) {
        !check_if_none_match(etag, if_none_match)
    } else if let Some(since) = req
        .headers()
        .get(http::header::IF_UNMODIFIED_SINCE)
        .and_then(|header| header.to_str().ok())
        .and_then(|s| date_from_http_str(s).ok())
        .map(|time| time.into())
    {
        !check_if_modified_since(last_modified, &since)
    } else {
        false
    }
}

pub fn format_systemtime(time: SystemTime) -> String {
    OffsetDateTime::from(time).format(&Rfc2822).unwrap_or_default()
}

pub fn date_from_http_str(http: &str) -> Result<OffsetDateTime, SaphirError> {
    match OffsetDateTime::parse(http, &Rfc2822)
        .or_else(|_| OffsetDateTime::parse(http, &DEPRECATED_HEADER_DATE_FORMAT))
        .or_else(|_| OffsetDateTime::parse(http, &DEPRECATED_HEADER_DATE_FORMAT2))
    {
        Ok(t) => Ok(t),
        Err(_) => Err(SaphirError::Other("Cannot parse date from header".to_owned())),
    }
}

#[cfg(test)]
mod t {
    use super::*;
    use crate::{file::etag::EntityTag, prelude::Body};
    use http::request::Builder;
    use std::time::Duration;

    mod match_none_match {
        use super::*;

        #[test]
        fn any() {
            let etag = EntityTag::Strong("".to_owned());
            assert!(check_if_match(&etag, "*"));
            assert!(!check_if_none_match(&etag, "*"));
        }

        #[test]
        fn one() {
            let etag = EntityTag::Strong("2".to_owned());
            let tags = format!(
                "{},{},{}",
                EntityTag::Strong("0".to_owned()).get_tag(),
                EntityTag::Strong("1".to_owned()).get_tag(),
                EntityTag::Strong("2".to_owned()).get_tag(),
            );
            assert!(check_if_match(&etag, &tags));
            assert!(!check_if_none_match(&etag, &tags));
        }

        #[test]
        fn none() {
            let etag = EntityTag::Strong("0".to_owned());
            let tags = EntityTag::Strong("1".to_owned()).get_tag();
            assert!(!check_if_match(&etag, &tags));
            assert!(check_if_none_match(&etag, &tags));
        }
    }

    mod modified_unmodified_since {
        use super::*;

        fn init_since() -> (SystemTime, SystemTime) {
            let now = SystemTime::now();
            (now, now)
        }

        #[test]
        fn now() {
            let (now, last_modified) = init_since();
            assert!(!check_if_modified_since(&last_modified, &now));
            assert!(check_if_unmodified_since(&last_modified, &now));
        }

        #[test]
        fn after_one_sec() {
            let (now, last_modified) = init_since();
            let modified = now + Duration::from_secs(1);
            assert!(!check_if_modified_since(&last_modified, &modified));
            assert!(check_if_unmodified_since(&last_modified, &modified));
        }

        #[test]
        fn one_sec_ago() {
            let (now, last_modified) = init_since();
            let modified = now - Duration::from_secs(1);
            assert!(check_if_modified_since(&last_modified, &modified));
            assert!(!check_if_unmodified_since(&last_modified, &modified));
        }
    }

    fn init_request() -> (Builder, EntityTag, SystemTime) {
        (
            http::request::Request::builder().method("GET"),
            EntityTag::Strong("hello".to_owned()),
            SystemTime::now(),
        )
    }

    mod fresh {
        use super::*;

        #[test]
        fn no_precondition_header_fields() {
            let (req, etag, date) = init_request();
            let req = Request::new(req.body(Body::empty()).unwrap(), None);
            assert!(!is_fresh(&req, &etag, &date));
        }

        #[test]
        fn if_none_match_precedes_if_modified_since() {
            let (req, etag, date) = init_request();
            let if_none_match = etag.get_tag();
            let if_modified_since = format_systemtime(date + Duration::from_secs(1));
            let req = Request::new(
                req.header(http::header::IF_NONE_MATCH, if_none_match)
                    .header(http::header::IF_MODIFIED_SINCE, if_modified_since)
                    .body(Body::empty())
                    .unwrap(),
                None,
            );
            assert!(is_fresh(&req, &etag, &date));
        }
    }

    mod precondition {
        use super::*;

        #[test]
        fn ok_without_any_precondition() {
            let (req, etag, date) = init_request();
            let req = Request::new(req.body(Body::empty()).unwrap(), None);
            assert!(!is_precondition_failed(&req, &etag, &date));
        }

        #[test]
        fn failed_with_if_match_not_passes() {
            let (req, etag, date) = init_request();
            let if_match = EntityTag::Strong("".to_owned()).get_tag();
            let req = Request::new(req.header(http::header::IF_MATCH, if_match).body(Body::empty()).unwrap(), None);
            assert!(is_precondition_failed(&req, &etag, &date));
        }

        #[test]
        fn with_if_match_passes_get() {
            let (req, etag, date) = init_request();
            let if_match = EntityTag::Strong("hello".to_owned()).get_tag();
            let if_none_match = EntityTag::Strong("world".to_owned()).get_tag();
            let req = Request::new(
                req.header(http::header::IF_MATCH, if_match)
                    .header(http::header::IF_NONE_MATCH, if_none_match)
                    .body(Body::empty())
                    .unwrap(),
                None,
            );
            assert!(!is_precondition_failed(&req, &etag, &date));
        }

        #[test]
        fn with_if_match_fails_post() {
            let (req, etag, date) = init_request();
            let if_match = EntityTag::Strong("hello".to_owned()).get_tag();
            let if_none_match = EntityTag::Strong("world".to_owned()).get_tag();
            let req = Request::new(
                req.method(Method::POST)
                    .header(http::header::IF_MATCH, if_match)
                    .header(http::header::IF_NONE_MATCH, if_none_match)
                    .body(Body::empty())
                    .unwrap(),
                None,
            );
            assert!(is_precondition_failed(&req, &etag, &date));
        }

        #[test]
        fn failed_with_if_unmodified_since_not_passes() {
            let (req, etag, date) = init_request();
            let if_unmodified_since = date - Duration::from_secs(1);
            let req = Request::new(
                req.header(http::header::IF_UNMODIFIED_SINCE, self::format_systemtime(if_unmodified_since))
                    .body(Body::empty())
                    .unwrap(),
                None,
            );
            assert!(is_precondition_failed(&req, &etag, &date));
        }

        #[test]
        fn with_if_unmodified_since_passes_get() {
            let (req, etag, if_unmodified_since) = init_request();
            let if_none_match = EntityTag::Strong("nonematch".to_owned()).get_tag();
            let req = Request::new(
                req.header(http::header::IF_UNMODIFIED_SINCE, self::format_systemtime(if_unmodified_since))
                    .header(http::header::IF_NONE_MATCH, if_none_match)
                    .body(Body::empty())
                    .unwrap(),
                None,
            );
            assert!(!is_precondition_failed(&req, &etag, &if_unmodified_since));
        }

        #[test]
        fn with_if_unmodified_since_fails_post() {
            let (req, etag, if_unmodified_since) = init_request();
            let if_none_match = EntityTag::Strong("nonematch".to_owned()).get_tag();
            let req = Request::new(
                req.method(Method::POST)
                    .header(http::header::IF_UNMODIFIED_SINCE, self::format_systemtime(if_unmodified_since))
                    .header(http::header::IF_NONE_MATCH, if_none_match)
                    .body(Body::empty())
                    .unwrap(),
                None,
            );
            assert!(is_precondition_failed(&req, &etag, &if_unmodified_since));
        }
    }
}