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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! This module provides the same functions as the root module, but which don't operate
//! directly on the browser's cookie string, so it can be used outside a browser.
//!
//! Instead of reading the browser's cookie string, functions in this module take it as an
//! argument. Instead of writing to the browser's cookie string, they return it.

#[cfg(not(target_arch = "wasm32"))]
use chrono::offset::Utc;
#[cfg(not(target_arch = "wasm32"))]
use chrono::NaiveDateTime;
#[cfg(target_arch = "wasm32")]
use js_sys::Date;
use std::borrow::Cow;
use std::collections::HashMap;
use std::time::Duration;
use urlencoding::FromUrlEncodingError;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsValue;

/// URI decoding error on a key or a value, when calling `wasm_cookie::all`.
#[derive(Debug)]
pub enum AllDecodeError {
    /// URI decoding error on a key.
    ///
    /// - The first field is the raw key.
    /// - The second field is the URI decoding error.
    Key(String, FromUrlEncodingError),

    /// URI decoding error on a value.
    ///
    /// - The first field is the URI decoded key corresponding to the value.
    /// - The second field is the URI decoding error.
    Value(String, FromUrlEncodingError),
}

fn process_key_value_str(key_value_str: &str) -> Result<(&str, &str), ()> {
    match key_value_str.split_once('=') {
        Some((key, value)) => Ok((key.trim(), value.trim())),
        None => Err(()),
    }
}

/// Returns all cookies as key-value pairs, with undecoded keys and values.
pub fn all_iter_raw(cookie_string: &str) -> impl Iterator<Item = (&str, &str)> {
    cookie_string.split(';').filter_map(|key_value_str| {
        match process_key_value_str(key_value_str) {
            Ok((key, value)) => Some((key, value)),
            Err(_) => None,
        }
    })
}

/// Returns all cookies as key-value pairs, with URI decoded keys and values
/// (with the [urlencoding crate](https://crates.io/crates/urlencoding)),
/// or an error if URI decoding fails on a key or a value.
pub fn all_iter(
    cookie_string: &str,
) -> impl Iterator<Item = Result<(String, String), AllDecodeError>> + '_ {
    all_iter_raw(cookie_string).map(|(key, value)| match urlencoding::decode(key) {
        Ok(key) => match urlencoding::decode(value) {
            Ok(value) => Ok((key, value)),
            Err(error) => Err(AllDecodeError::Value(key, error)),
        },

        Err(error) => Err(AllDecodeError::Key(key.to_owned(), error)),
    })
}

/// Returns all cookies, with undecoded keys and values.
pub fn all_raw(cookie_string: &str) -> HashMap<String, String> {
    all_iter_raw(cookie_string)
        .map(|(key, value)| (key.to_owned(), value.to_owned()))
        .collect()
}

/// Returns all cookies, with URI decoded keys and values
/// (with the [urlencoding crate](https://crates.io/crates/urlencoding)),
/// or an error if URI decoding fails on a key or a value.
pub fn all(cookie_string: &str) -> Result<HashMap<String, String>, AllDecodeError> {
    all_iter(cookie_string).collect()
}

/// Returns undecoded cookie if it exists.
pub fn get_raw(cookie_string: &str, name: &str) -> Option<String> {
    cookie_string
        .split(';')
        .find_map(|key_value_str| match process_key_value_str(key_value_str) {
            Ok((key, value)) => {
                if key == name {
                    Some(value.to_owned())
                } else {
                    None
                }
            }

            Err(_) => None,
        })
}

/// If it exists, returns URI decoded cookie
/// (with the [urlencoding crate](https://crates.io/crates/urlencoding))
/// or an error if the value's URI decoding fails.
pub fn get(cookie_string: &str, name: &str) -> Option<Result<String, FromUrlEncodingError>> {
    let name = urlencoding::encode(name);

    cookie_string
        .split(';')
        .find_map(|key_value_str| match process_key_value_str(key_value_str) {
            Ok((key, value)) => {
                if key == name {
                    Some(urlencoding::decode(value))
                } else {
                    None
                }
            }

            Err(_) => None,
        })
}

/// Cookies options (see [https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie)).
///
/// You can create it by calling `CookieOptions::default()`.
#[derive(Default, Clone, Debug)]
pub struct CookieOptions<'a> {
    /// If `None`, defaults to the current path of the current document location.
    pub path: Option<&'a str>,

    /// If `None`, defaults to the host portion of the current document location.
    pub domain: Option<&'a str>,

    /// Expiration date in GMT string format.
    /// If `None`, the cookie will expire at the end of session.
    pub expires: Option<Cow<'a, str>>,

    /// If true, the cookie will only be transmitted over secure protocol as HTTPS.
    /// The default value is false.
    pub secure: bool,

    /// SameSite prevents the browser from sending the cookie along with cross-site requests
    /// (see [https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#SameSite_attribute](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#SameSite_attribute)).
    pub same_site: SameSite,
}

impl<'a> CookieOptions<'a> {
    /// Set the path.
    /// The default value is the current path of the current document location.
    pub fn with_path(mut self, path: &'a str) -> Self {
        self.path = Some(path);
        self
    }

    /// Set the domain.
    /// The default value is the host portion of the current document location.
    pub fn with_domain(mut self, domain: &'a str) -> Self {
        self.domain = Some(domain);
        self
    }

    /// Expires the cookie at a specific date.
    ///
    /// `date` must be a GMT string (see <https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString>).
    ///
    /// The default behavior of the cookie is to expire at the end of session.
    pub fn expires_at_date(mut self, date: &'a str) -> Self {
        self.expires = Some(Cow::Borrowed(date));
        self
    }

    /// Expires the cookie at a specific timestamp (in milliseconds, UTC, with leap seconds ignored).
    /// The default behavior of the cookie is to expire at the end of session.
    pub fn expires_at_timestamp(mut self, timestamp: i64) -> Self {
        #[cfg(target_arch = "wasm32")]
        let date: String = Date::new(&JsValue::from_f64(timestamp as f64))
            .to_utc_string()
            .into();

        #[cfg(not(target_arch = "wasm32"))]
        let date = NaiveDateTime::from_timestamp_millis(timestamp)
            .unwrap()
            .format("%a, %d %b %Y %T GMT")
            .to_string();

        self.expires = Some(Cow::Owned(date));
        self
    }

    /// Expires the cookie after a certain duration.
    /// The default behavior of the cookie is to expire at the end of session.
    pub fn expires_after(self, duration: Duration) -> Self {
        #[cfg(target_arch = "wasm32")]
        let now = Date::now() as i64;
        #[cfg(not(target_arch = "wasm32"))]
        let now = Utc::now().timestamp_millis();
        self.expires_at_timestamp(now + duration.as_millis() as i64)
    }

    /// Set the cookie to be only transmitted over secure protocol as HTTPS.
    pub fn secure(mut self) -> Self {
        self.secure = true;
        self
    }

    /// Set the SameSite value.
    /// SameSite prevents the browser from sending the cookie along with cross-site requests
    /// (see [https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#SameSite_attribute](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#SameSite_attribute)).
    pub fn with_same_site(mut self, same_site: SameSite) -> Self {
        self.same_site = same_site;
        self
    }
}

/// SameSite value for [CookieOptions](struct.CookieOptions.html).
///
/// SameSite prevents the browser from sending the cookie along with cross-site requests
/// (see [https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#SameSite_attribute](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#SameSite_attribute)).
#[derive(Clone, Debug)]
pub enum SameSite {
    /// The `Lax` value value will send the cookie for all same-site requests and top-level navigation GET requests.
    /// This is sufficient for user tracking, but it will prevent many CSRF attacks.
    /// This is the default value when calling `SameSite::default()`.
    Lax,

    /// The `Strict` value will prevent the cookie from being sent by the browser to the
    /// target site in all cross-site browsing contexts, even when following a regular link.
    Strict,

    /// The `None` value explicitly states no restrictions will be applied.
    /// The cookie will be sent in all requests - both cross-site and same-site.
    None,
}

impl Default for SameSite {
    fn default() -> Self {
        Self::Lax
    }
}

impl SameSite {
    fn cookie_string_value(&self) -> &'static str {
        match self {
            SameSite::Lax => "lax",
            SameSite::Strict => "strict",
            SameSite::None => "none",
        }
    }
}

/// Return the cookie string that sets a cookie, with non encoded name and value.
pub fn set_raw(name: &str, value: &str, options: &CookieOptions) -> String {
    let mut cookie_string = name.to_owned();
    cookie_string.push('=');
    cookie_string.push_str(value);

    if let Some(path) = options.path {
        cookie_string.push_str(";path=");
        cookie_string.push_str(path);
    }

    if let Some(domain) = options.domain {
        cookie_string.push_str(";domain=");
        cookie_string.push_str(domain);
    }

    if let Some(expires_str) = &options.expires {
        cookie_string.push_str(";expires=");
        cookie_string.push_str(expires_str);
    }

    if options.secure {
        cookie_string.push_str(";secure");
    }

    cookie_string.push_str(";samesite=");
    cookie_string.push_str(options.same_site.cookie_string_value());

    cookie_string
}

/// Return the cookie string that sets a cookie, with URI encoded name and value
/// (with the [urlencoding crate](https://crates.io/crates/urlencoding)).
pub fn set(name: &str, value: &str, options: &CookieOptions) -> String {
    set_raw(
        &urlencoding::encode(name),
        &urlencoding::encode(value),
        options,
    )
}

/// Return the cookie string that deletes a cookie without encoding its name.
pub fn delete_raw(name: &str) -> String {
    format!("{}=;expires=Thu, 01 Jan 1970 00:00:00 GMT", name)
}

/// Return the cookie string that deletes a cookie, URI encoding its name.
pub fn delete(name: &str) -> String {
    delete_raw(&urlencoding::encode(name))
}

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

    #[test]
    fn test_all_raw() {
        let cookies = all_raw(" key1=value1;key2=value2 ; key3  = value3");
        assert_eq!(cookies.len(), 3);
        assert_eq!(cookies["key1"], "value1");
        assert_eq!(cookies["key2"], "value2");
        assert_eq!(cookies["key3"], "value3");

        let cookies = all_raw("");
        assert!(cookies.is_empty());
    }

    #[test]
    fn test_all() {
        let cookies =
            all("key%20%251=value%20%251  ;key%20%252=value%20%252;key%20%253  = value%20%253")
                .unwrap();
        assert_eq!(cookies.len(), 3);
        assert_eq!(cookies["key %1"], "value %1");
        assert_eq!(cookies["key %2"], "value %2");
        assert_eq!(cookies["key %3"], "value %3");

        let cookies = all("").unwrap();
        assert!(cookies.is_empty());

        let error = all("key1=value1;key2%AA=value2").unwrap_err();

        match error {
            AllDecodeError::Key(raw_key, _) => assert_eq!(raw_key, "key2%AA"),
            _ => panic!(),
        }

        let error = all("key1=value1;key%202=value2%AA").unwrap_err();

        match error {
            AllDecodeError::Value(key, _) => assert_eq!(key, "key 2"),
            _ => panic!(),
        }
    }

    #[test]
    fn test_get_raw() {
        assert_eq!(
            get_raw("key1=value1 ; key2= value2;key3=value3", "key2"),
            Some("value2".to_owned())
        );

        assert_eq!(
            get_raw("key1=value1 ; key2= value2;key3=value3", "key4"),
            None
        );
    }

    #[test]
    fn test_get() {
        assert_eq!(
            get("key1=value1 ; key%202= value%202=;key3=value3", "key 2")
                .map(|result| result.unwrap()),
            Some("value 2=".to_owned())
        );

        assert!(get("key1=value1 ; key2= value2;key3=value3", "key4").is_none());
        assert!(get("key1=value1 ; key2= value2%AA;key3=value3", "key2")
            .unwrap()
            .is_err());
    }

    #[test]
    fn test_set_raw() {
        assert_eq!(
            set_raw("key", "value", &CookieOptions::default()),
            "key=value;samesite=lax"
        );

        assert_eq!(
            set_raw("key", "value", &CookieOptions::default().with_path("/path")),
            "key=value;path=/path;samesite=lax"
        );

        assert_eq!(
            set_raw(
                "key",
                "value",
                &CookieOptions::default()
                    .with_path("/path")
                    .with_domain("example.com")
            ),
            "key=value;path=/path;domain=example.com;samesite=lax"
        );

        assert_eq!(
            set_raw(
                "key",
                "value",
                &CookieOptions::default()
                    .with_path("/path")
                    .with_domain("example.com")
                    .secure()
            ),
            "key=value;path=/path;domain=example.com;secure;samesite=lax"
        );

        assert_eq!(
            set_raw(
                "key",
                "value",
                &CookieOptions::default().expires_at_timestamp(1100000000000),
            ),
            "key=value;expires=Tue, 09 Nov 2004 11:33:20 GMT;samesite=lax",
        );
    }
}