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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

//! An implementation of the [CORS preflight cache](https://fetch.spec.whatwg.org/#cors-preflight-cache)
//! For now this library is XHR-specific.
//! For stuff involving `<img>`, `<iframe>`, `<form>`, etc please check what
//! the request mode should be and compare with the fetch spec
//! This library will eventually become the core of the Fetch crate
//! with CORSRequest being expanded into FetchRequest (etc)

use std::time::{Duration, Instant};

use http::header::HeaderName;
use http::Method;
use net_traits::request::{CredentialsMode, Origin, Request};
use servo_url::ServoUrl;

/// Union type for CORS cache entries
///
/// Each entry might pertain to a header or method
#[derive(Clone, Debug)]
pub enum HeaderOrMethod {
    HeaderData(HeaderName),
    MethodData(Method),
}

impl HeaderOrMethod {
    fn match_header(&self, header_name: &HeaderName) -> bool {
        match *self {
            HeaderOrMethod::HeaderData(ref n) => n == header_name,
            _ => false,
        }
    }

    fn match_method(&self, method: &Method) -> bool {
        match *self {
            HeaderOrMethod::MethodData(ref m) => m == method,
            _ => false,
        }
    }
}

/// An entry in the CORS cache
#[derive(Clone, Debug)]
pub struct CorsCacheEntry {
    pub origin: Origin,
    pub url: ServoUrl,
    pub max_age: Duration,
    pub credentials: bool,
    pub header_or_method: HeaderOrMethod,
    created: Instant,
}

impl CorsCacheEntry {
    fn new(
        origin: Origin,
        url: ServoUrl,
        max_age: Duration,
        credentials: bool,
        header_or_method: HeaderOrMethod,
    ) -> CorsCacheEntry {
        CorsCacheEntry {
            origin,
            url,
            max_age,
            credentials,
            header_or_method,
            created: Instant::now(),
        }
    }
}

fn match_headers(cors_cache: &CorsCacheEntry, cors_req: &Request) -> bool {
    cors_cache.origin == cors_req.origin &&
        cors_cache.url == cors_req.current_url() &&
        (cors_cache.credentials || cors_req.credentials_mode != CredentialsMode::Include)
}

/// A simple, vector-based CORS Cache
#[derive(Clone, Default)]
pub struct CorsCache(Vec<CorsCacheEntry>);

impl CorsCache {
    fn find_entry_by_header<'a>(
        &'a mut self,
        request: &Request,
        header_name: &HeaderName,
    ) -> Option<&'a mut CorsCacheEntry> {
        self.cleanup();
        self.0
            .iter_mut()
            .find(|e| match_headers(e, request) && e.header_or_method.match_header(header_name))
    }

    fn find_entry_by_method<'a>(
        &'a mut self,
        request: &Request,
        method: Method,
    ) -> Option<&'a mut CorsCacheEntry> {
        // we can take the method from CorSRequest itself
        self.cleanup();
        self.0
            .iter_mut()
            .find(|e| match_headers(e, request) && e.header_or_method.match_method(&method))
    }

    /// Remove old entries
    pub fn cleanup(&mut self) {
        let CorsCache(buf) = self.clone();
        let now = Instant::now();
        let new_buf: Vec<CorsCacheEntry> = buf
            .into_iter()
            .filter(|e| now < e.created + e.max_age)
            .collect();
        *self = CorsCache(new_buf);
    }

    /// Returns true if an entry with a
    /// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found
    pub fn match_header(&mut self, request: &Request, header_name: &HeaderName) -> bool {
        self.find_entry_by_header(request, header_name).is_some()
    }

    /// Updates max age if an entry for a
    /// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found.
    ///
    /// If not, it will insert an equivalent entry
    pub fn match_header_and_update(
        &mut self,
        request: &Request,
        header_name: &HeaderName,
        new_max_age: Duration,
    ) -> bool {
        match self
            .find_entry_by_header(request, header_name)
            .map(|e| e.max_age = new_max_age)
        {
            Some(_) => true,
            None => {
                self.insert(CorsCacheEntry::new(
                    request.origin.clone(),
                    request.current_url(),
                    new_max_age,
                    request.credentials_mode == CredentialsMode::Include,
                    HeaderOrMethod::HeaderData(header_name.clone()),
                ));
                false
            },
        }
    }

    /// Returns true if an entry with a
    /// [matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found
    pub fn match_method(&mut self, request: &Request, method: Method) -> bool {
        self.find_entry_by_method(request, method).is_some()
    }

    /// Updates max age if an entry for
    /// [a matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found.
    ///
    /// If not, it will insert an equivalent entry
    pub fn match_method_and_update(
        &mut self,
        request: &Request,
        method: Method,
        new_max_age: Duration,
    ) -> bool {
        match self
            .find_entry_by_method(request, method.clone())
            .map(|e| e.max_age = new_max_age)
        {
            Some(_) => true,
            None => {
                self.insert(CorsCacheEntry::new(
                    request.origin.clone(),
                    request.current_url(),
                    new_max_age,
                    request.credentials_mode == CredentialsMode::Include,
                    HeaderOrMethod::MethodData(method),
                ));
                false
            },
        }
    }

    /// Insert an entry
    pub fn insert(&mut self, entry: CorsCacheEntry) {
        self.cleanup();
        self.0.push(entry);
    }
}