net/
cookie_storage.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Implementation of cookie storage as specified in
6//! <http://tools.ietf.org/html/rfc6265>
7
8use std::cmp::Ordering;
9use std::collections::HashMap;
10use std::collections::hash_map::Entry;
11use std::time::SystemTime;
12
13use cookie::Cookie;
14use itertools::Itertools;
15use log::info;
16use net_traits::CookieSource;
17use net_traits::pub_domains::reg_suffix;
18use serde::{Deserialize, Serialize};
19use servo_url::ServoUrl;
20
21use crate::cookie::ServoCookie;
22
23#[derive(Clone, Debug, Deserialize, Serialize)]
24pub struct CookieStorage {
25    version: u32,
26    cookies_map: HashMap<String, Vec<ServoCookie>>,
27    max_per_host: usize,
28}
29
30#[derive(Debug)]
31pub enum RemoveCookieError {
32    Overlapping,
33    NonHTTP,
34}
35
36impl CookieStorage {
37    pub fn new(max_cookies: usize) -> CookieStorage {
38        CookieStorage {
39            version: 1,
40            cookies_map: HashMap::new(),
41            max_per_host: max_cookies,
42        }
43    }
44
45    // http://tools.ietf.org/html/rfc6265#section-5.3
46    pub fn remove(
47        &mut self,
48        cookie: &ServoCookie,
49        url: &ServoUrl,
50        source: CookieSource,
51    ) -> Result<Option<ServoCookie>, RemoveCookieError> {
52        let domain = reg_host(cookie.cookie.domain().as_ref().unwrap_or(&""));
53        let cookies = self.cookies_map.entry(domain).or_default();
54
55        // https://www.ietf.org/id/draft-ietf-httpbis-cookie-alone-01.txt Step 2
56        if !cookie.cookie.secure().unwrap_or(false) && !url.is_secure_scheme() {
57            let new_domain = cookie.cookie.domain().as_ref().unwrap().to_owned();
58            let new_path = cookie.cookie.path().as_ref().unwrap().to_owned();
59
60            let any_overlapping = cookies.iter().any(|c| {
61                let existing_domain = c.cookie.domain().as_ref().unwrap().to_owned();
62                let existing_path = c.cookie.path().as_ref().unwrap().to_owned();
63
64                c.cookie.name() == cookie.cookie.name() &&
65                    c.cookie.secure().unwrap_or(false) &&
66                    (ServoCookie::domain_match(new_domain, existing_domain) ||
67                        ServoCookie::domain_match(existing_domain, new_domain)) &&
68                    ServoCookie::path_match(new_path, existing_path)
69            });
70
71            if any_overlapping {
72                return Err(RemoveCookieError::Overlapping);
73            }
74        }
75
76        // Step 11.1
77        let position = cookies.iter().position(|c| {
78            c.cookie.domain() == cookie.cookie.domain() &&
79                c.cookie.path() == cookie.cookie.path() &&
80                c.cookie.name() == cookie.cookie.name()
81        });
82
83        if let Some(ind) = position {
84            // Step 11.4
85            let c = cookies.remove(ind);
86
87            // http://tools.ietf.org/html/rfc6265#section-5.3 step 11.2
88            if c.cookie.http_only().unwrap_or(false) && source == CookieSource::NonHTTP {
89                // Undo the removal.
90                cookies.push(c);
91                Err(RemoveCookieError::NonHTTP)
92            } else {
93                Ok(Some(c))
94            }
95        } else {
96            Ok(None)
97        }
98    }
99
100    pub fn clear_storage(&mut self, url: &ServoUrl) {
101        let domain = reg_host(url.host_str().unwrap_or(""));
102        let cookies = self.cookies_map.entry(domain).or_default();
103        for cookie in cookies.iter_mut() {
104            cookie.set_expiry_time_in_past();
105        }
106    }
107
108    pub fn delete_cookie_with_name(&mut self, url: &ServoUrl, name: String) {
109        let domain = reg_host(url.host_str().unwrap_or(""));
110        let cookies = self.cookies_map.entry(domain).or_default();
111        for cookie in cookies.iter_mut() {
112            if cookie.cookie.name() == name {
113                cookie.set_expiry_time_in_past();
114            }
115        }
116    }
117
118    // http://tools.ietf.org/html/rfc6265#section-5.3
119    pub fn push(&mut self, mut cookie: ServoCookie, url: &ServoUrl, source: CookieSource) {
120        // https://www.ietf.org/id/draft-ietf-httpbis-cookie-alone-01.txt Step 1
121        if cookie.cookie.secure().unwrap_or(false) && !url.is_secure_scheme() {
122            return;
123        }
124
125        let old_cookie = self.remove(&cookie, url, source);
126        if old_cookie.is_err() {
127            // This new cookie is not allowed to overwrite an existing one.
128            return;
129        }
130
131        // Step 11
132        if let Some(old_cookie) = old_cookie.unwrap() {
133            // Step 11.3
134            cookie.creation_time = old_cookie.creation_time;
135        }
136
137        // Step 12
138        let domain = reg_host(cookie.cookie.domain().as_ref().unwrap_or(&""));
139        let cookies = self.cookies_map.entry(domain).or_default();
140
141        if cookies.len() == self.max_per_host {
142            let old_len = cookies.len();
143            cookies.retain(|c| !is_cookie_expired(c));
144            let new_len = cookies.len();
145
146            // https://www.ietf.org/id/draft-ietf-httpbis-cookie-alone-01.txt
147            if new_len == old_len &&
148                !evict_one_cookie(cookie.cookie.secure().unwrap_or(false), cookies)
149            {
150                return;
151            }
152        }
153        cookies.push(cookie);
154    }
155
156    pub fn cookie_comparator(a: &ServoCookie, b: &ServoCookie) -> Ordering {
157        let a_path_len = a.cookie.path().as_ref().map_or(0, |p| p.len());
158        let b_path_len = b.cookie.path().as_ref().map_or(0, |p| p.len());
159        match a_path_len.cmp(&b_path_len) {
160            Ordering::Equal => a.creation_time.cmp(&b.creation_time),
161            // Ensure that longer paths are sorted earlier than shorter paths
162            Ordering::Greater => Ordering::Less,
163            Ordering::Less => Ordering::Greater,
164        }
165    }
166
167    pub fn remove_expired_cookies_for_url(&mut self, url: &ServoUrl) {
168        let domain = reg_host(url.host_str().unwrap_or(""));
169        if let Entry::Occupied(mut entry) = self.cookies_map.entry(domain) {
170            let cookies = entry.get_mut();
171            cookies.retain(|c| !is_cookie_expired(c));
172            if cookies.is_empty() {
173                entry.remove_entry();
174            }
175        }
176    }
177
178    // http://tools.ietf.org/html/rfc6265#section-5.4
179    pub fn cookies_for_url(&mut self, url: &ServoUrl, source: CookieSource) -> Option<String> {
180        // Let cookie-list be the set of cookies from the cookie store
181        let cookie_list = self.cookies_data_for_url(url, source);
182
183        let reducer = |acc: String, cookie: Cookie<'static>| -> String {
184            // Serialize the cookie-list into a cookie-string by processing each cookie in the cookie-list in order:
185            // If the cookies' name is not empty, output the cookie's name followed by the %x3D ("=") character.
186            // If the cookies' value is not empty, output the cookie's value.
187            // If there is an unprocessed cookie in the cookie-list, output the characters %x3B and %x20 ("; ").
188            // Security: the above steps allow for "nameless" cookies which have proved to be a security footgun
189            // especially with the new cookie name prefix proposals
190            (match acc.len() {
191                0 => acc,
192                _ => acc + "; ",
193            }) + cookie.name() +
194                "=" +
195                cookie.value()
196        };
197
198        // Serialize the cookie-list into a cookie-string by processing each cookie in the cookie-list in order
199        let result = cookie_list.fold("".to_owned(), reducer);
200
201        info!(" === COOKIES SENT: {}", result);
202        match result.len() {
203            0 => None,
204            _ => Some(result),
205        }
206    }
207
208    /// <https://cookiestore.spec.whatwg.org/#query-cookies>
209    pub fn query_cookies(&mut self, url: &ServoUrl, name: Option<String>) -> Vec<Cookie<'static>> {
210        // 1. Retrieve cookie-list given request-uri and "non-HTTP" source
211        let cookie_list = self.cookies_data_for_url(url, CookieSource::NonHTTP);
212
213        // 3. For each cookie in cookie-list, run these steps:
214        // 3.2. If name is given, then run these steps:
215        if let Some(name) = name {
216            // Let cookieName be the result of running UTF-8 decode without BOM on cookie’s name.
217            // If cookieName does not equal name, then continue.
218            cookie_list.filter(|cookie| cookie.name() == name).collect()
219        } else {
220            cookie_list.collect()
221        }
222
223        // Note: we do not convert the list into CookieListItem's here, we do that in script to not not have to define
224        // the binding types in net.
225
226        // Return list
227    }
228
229    pub fn cookies_data_for_url<'a>(
230        &'a mut self,
231        url: &'a ServoUrl,
232        source: CookieSource,
233    ) -> impl Iterator<Item = cookie::Cookie<'static>> + 'a {
234        let domain = reg_host(url.host_str().unwrap_or(""));
235        let cookies = self.cookies_map.entry(domain).or_default();
236
237        cookies
238            .iter_mut()
239            .filter(move |c| c.appropriate_for_url(url, source))
240            .sorted_by(|a: &&mut ServoCookie, b: &&mut ServoCookie| {
241                // The user agent SHOULD sort the cookie-list
242                CookieStorage::cookie_comparator(a, b)
243            })
244            .map(|c| {
245                // Update the last-access-time of each cookie in the cookie-list to the current date and time
246                c.touch();
247                c.cookie.clone()
248            })
249    }
250}
251
252fn reg_host(url: &str) -> String {
253    reg_suffix(url).to_lowercase()
254}
255
256fn is_cookie_expired(cookie: &ServoCookie) -> bool {
257    matches!(cookie.expiry_time, Some(date_time) if date_time <= SystemTime::now())
258}
259
260fn evict_one_cookie(is_secure_cookie: bool, cookies: &mut Vec<ServoCookie>) -> bool {
261    // Remove non-secure cookie with oldest access time
262    let oldest_accessed = get_oldest_accessed(false, cookies);
263
264    if let Some((index, _)) = oldest_accessed {
265        cookies.remove(index);
266    } else {
267        // All secure cookies were found
268        if !is_secure_cookie {
269            return false;
270        }
271        let oldest_accessed = get_oldest_accessed(true, cookies);
272        if let Some((index, _)) = oldest_accessed {
273            cookies.remove(index);
274        }
275    }
276    true
277}
278
279fn get_oldest_accessed(
280    is_secure_cookie: bool,
281    cookies: &mut [ServoCookie],
282) -> Option<(usize, SystemTime)> {
283    let mut oldest_accessed = None;
284    for (i, c) in cookies.iter().enumerate() {
285        if (c.cookie.secure().unwrap_or(false) == is_secure_cookie) &&
286            oldest_accessed
287                .as_ref()
288                .is_none_or(|(_, current_oldest_time)| c.last_access < *current_oldest_time)
289        {
290            oldest_accessed = Some((i, c.last_access));
291        }
292    }
293    oldest_accessed
294}