rwf 0.2.1

Framework for building web applications in the Rust programming language
Documentation
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! HTTP cookies.
//!
//! This module handles decoding the `Cookie` header,
//! and generating `Set-Cookie` headers.
use std::collections::HashMap;
use time::{Duration, OffsetDateTime};

use super::url::urldecode;
use super::Error;
use crate::config::get_config;
use crate::controller::Session;
use crate::crypto::{decrypt, encrypt};

/// Cookies storage.
///
/// Supports both plain text and encrypted (private) cookies.
#[derive(Debug, Clone, Default)]
pub struct Cookies {
    cookies: HashMap<String, Cookie>,
}

impl Cookies {
    /// Create new empty cookies storage.
    pub fn new() -> Self {
        Self {
            cookies: HashMap::new(),
        }
    }

    /// Parse cookies from the `Cookie` header.
    ///
    /// # Example
    ///
    /// ```
    /// # use rwf::http::Cookies;
    /// let cookies = Cookies::parse("rwf_aid=1234; rwf_session=foo");
    /// assert_eq!(
    ///     cookies
    ///         .get("rwf_aid")
    ///         .unwrap()
    ///         .value(),
    ///     "1234"
    /// );
    /// ```
    pub fn parse(value: &str) -> Cookies {
        let parts = value.split(";");
        let mut cookies = HashMap::new();

        for part in parts {
            if let Some(cookie) = Cookie::parse(part.trim()) {
                cookies.insert(cookie.name.to_string(), cookie);
            }
        }

        Cookies { cookies }
    }

    /// Add an encrypted cookie.
    ///
    /// If this is set on the [`crate::http::Response`], this cookie will be sent
    /// to the client.
    pub fn add_private(&mut self, cookie: impl ToCookie) -> Result<(), Error> {
        let mut cookie = cookie.to_cookie();
        cookie.value = encrypt(cookie.value.as_bytes())?;
        self.cookies.insert(cookie.name.clone(), cookie);

        Ok(())
    }

    /// Get an encrypted cookie received from the client. The value is decrypted automatically.
    ///
    /// If the decryption fails, `None` is returned. This indicates the encrypted cookie has been modified,
    /// or has been encrypted with a different secret key.
    ///
    /// If the cookie isn't valid UTF-8, like the HTTP specification requires, an error is returned.
    pub fn get_private(&self, name: &str) -> Result<Option<Cookie>, Error> {
        if let Some(cookie) = self.cookies.get(name) {
            let mut cookie = cookie.clone();
            cookie.value = String::from_utf8(match decrypt(&cookie.value) {
                Ok(value) => value,
                Err(_) => return Ok(None),
            })?;
            Ok(Some(cookie))
        } else {
            Ok(None)
        }
    }

    /// Add a cookie.
    ///
    /// If this is done to the response, the cookie will be sent it to the client,
    /// using the `Set-Cookie` header.
    pub fn add(&mut self, cookie: impl ToCookie) {
        let cookie = cookie.to_cookie();
        self.cookies.insert(cookie.name.clone(), cookie);
    }

    /// Get a cookie sent by the client.
    pub fn get(&self, name: &str) -> Option<&Cookie> {
        self.cookies.get(name)
    }

    /// Get the session cookie, if one is set. If no session is set,
    /// `None` is returned. While all requests should have a session, there is
    /// no guarantee the browser respects cookie settings we send over (e.g. cURL won't).
    ///
    /// If the session is not valid UTF-8, an error is returned.
    pub fn get_session(&self) -> Result<Option<Session>, Error> {
        let cookie = self.get_private("rwf_session")?;

        if let Some(cookie) = cookie {
            Ok(serde_json::from_str(cookie.value())?)
        } else {
            Ok(None)
        }
    }

    /// Set a sessionn cookie and send it to the client. The cookie expires
    /// when the session does.
    pub fn add_session(&mut self, session: &Session) -> Result<(), Error> {
        let value = serde_json::to_string(session)?;
        self.add_private(
            CookieBuilder::new()
                .name("rwf_session")
                .value(value)
                .expiration(OffsetDateTime::from_unix_timestamp(session.expiration)?)
                .build(),
        )
    }

    /// Convert cookies to `Set-Cookie` headers which will be sent to the client.
    pub fn to_headers(&self) -> Vec<u8> {
        let mut headers = vec![];
        for (_, cookie) in &self.cookies {
            headers.extend_from_slice(format!("set-cookie: {}\r\n", cookie).as_bytes());
        }
        headers
    }
}

impl std::fmt::Display for Cookies {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let mut result = Vec::new();
        for (_name, cookie) in &self.cookies {
            result.push(cookie.to_string());
        }
        write!(f, "{}", result.join("; "))
    }
}

/// Convert a value to a cookie.
///
/// This is syntax sugar to help create cookies more easily. Most use cases would
/// want to use the [`CookieBuilder`] instead.
pub trait ToCookie {
    fn to_cookie(self) -> Cookie;
}

impl ToCookie for (&str, &str) {
    fn to_cookie(self) -> Cookie {
        let builder = CookieBuilder::new();
        builder.name(self.0).value(self.1).build()
    }
}

impl ToCookie for (String, String) {
    fn to_cookie(self) -> Cookie {
        let builder = CookieBuilder::new();
        builder.name(self.0).value(self.1).build()
    }
}

impl ToCookie for Cookie {
    fn to_cookie(self) -> Cookie {
        self
    }
}

/// A browser cookie.
#[derive(Debug, Clone, Default)]
pub struct Cookie {
    name: String,
    value: String,
    expiration: Option<OffsetDateTime>,
    max_age: Option<Duration>,
    path: Option<String>,
    domain: Option<String>,
    http_only: bool,
    secure: bool,
    same_site: Option<String>,
}

impl Cookie {
    /// Parse a single cookie from the `Cookie` header.
    fn parse(value: &str) -> Option<Self> {
        let mut parts = value.split(";");
        let mut builder = CookieBuilder::new();
        let _cookie = if let Some(cookie) = parts.next() {
            match Self::key_value(cookie) {
                (Some(key), Some(value)) => builder = builder.name(&key).value(urldecode(&value)),
                (Some(key), None) => builder = builder.name(&key),
                _ => return None,
            }
        } else {
            return None;
        };

        for part in parts {
            match Self::key_value(part) {
                (Some(key), value) => match key.as_str().trim() {
                    "Domain" => {
                        if let Some(value) = value {
                            builder = builder.domain(value);
                        }
                    }
                    "HttpOnly" => {
                        builder = builder.http_only();
                    }
                    "Secure" => {
                        builder = builder.secure();
                    }
                    "Max-Age" => {
                        if let Some(value) = value {
                            match value.parse::<i64>() {
                                Ok(value) => {
                                    builder = builder.max_age(Duration::seconds(value));
                                }
                                Err(_) => continue,
                            }
                        }
                    }
                    _ => continue,
                },

                _ => continue,
            };
        }

        Some(builder.build())
    }

    fn key_value(s: &str) -> (Option<String>, Option<String>) {
        let mut parts = s.split("=");
        if let Some(key) = parts.next() {
            if let Some(value) = parts.next() {
                (Some(key.to_owned()), Some(value.to_owned()))
            } else {
                (Some(key.to_owned()), None)
            }
        } else {
            (None, None)
        }
    }

    /// Create new cookie with the name.
    fn new(name: impl ToString) -> Self {
        Cookie {
            name: name.to_string(),
            max_age: Some(get_config().general.cookie_max_age()),
            ..Default::default()
        }
    }

    /// Get cookie value.
    pub fn value(&self) -> &str {
        &self.value
    }

    /// Get cookie name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Check if the cookie is secure.
    fn secure(&self) -> bool {
        self.secure
    }

    /// Check if the cookie is HTTP-only.
    fn http_only(&self) -> bool {
        self.http_only
    }

    /// Get the cookie's `MaxAge` attribute if any is set.
    fn max_age(&self) -> Option<Duration> {
        self.max_age
    }
}

impl std::fmt::Display for Cookie {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}={}", self.name, self.value)?;

        if let Some(ref max_age) = self.max_age {
            write!(f, "; Max-Age: {}", max_age.whole_seconds())?;
        }

        if self.secure {
            write!(f, "; Secure")?;
        }

        if self.http_only {
            write!(f, "; HttpOnly")?;
        }

        if let Some(ref path) = self.path {
            write!(f, "; Path={}", path)?;
        } else {
            write!(f, "; Path=/")?;
        }

        if let Some(ref domain) = self.domain {
            write!(f, "; Domain={}", domain)?;
        }

        if let Some(ref same_site) = self.same_site {
            write!(f, "; SameSite={}", same_site)?;
        } else {
            write!(f, "; SameSite=Lax")?;
        }

        if let Some(ref expiration) = self.expiration {
            write!(
                f,
                "; Expires={}",
                expiration
                    .format(&time::format_description::well_known::Rfc2822)
                    .unwrap()
            )?;
        }

        Ok(())
    }
}

/// Cookie builder which helps with creating cookies with multiple attributes.
///
/// # Example
///
/// ```
/// # use rwf::http::CookieBuilder;
/// use time::Duration;
///
/// let cookie = CookieBuilder::new()
///     .name("rwf_aid")
///     .value("1234")
///     .max_age(Duration::days(4))
///     .secure()
///     .http_only()
///     .build();
/// ```
///
/// The resulting cookie can be set on a response, which will send it to the client.
#[derive(Clone, Debug)]
pub struct CookieBuilder {
    cookie: Cookie,
}

impl CookieBuilder {
    /// Create new cookie builder.
    pub fn new() -> Self {
        Self {
            cookie: Cookie::default(),
        }
    }

    /// Set cookie name.
    pub fn name(mut self, name: impl ToString) -> Self {
        self.cookie.name = name.to_string();
        self
    }

    /// Set cookie value. The value is stored in plain text.
    pub fn value(mut self, value: impl ToString) -> Self {
        self.cookie.value = value.to_string();
        self
    }

    /// Set cookie `Expiration` attribute.
    pub fn expiration(mut self, expiration: OffsetDateTime) -> Self {
        self.cookie.expiration = Some(expiration);
        self
    }

    /// Set cookie `MaxAge` attribute.
    pub fn max_age(mut self, max_age: Duration) -> Self {
        self.cookie.max_age = Some(max_age);
        self
    }

    /// Set cookie `Path` attribute.
    pub fn path(mut self, path: impl ToString) -> Self {
        self.cookie.path = Some(path.to_string());
        self
    }

    /// Set cookie `Domain` attribute.
    pub fn domain(mut self, domain: impl ToString) -> Self {
        self.cookie.domain = Some(domain.to_string());
        self
    }

    /// Set the cookie to be only sent via plain HTTP requests (no AJAX).
    /// This is the `HttpOnly` attribute.
    pub fn http_only(mut self) -> Self {
        self.cookie.http_only = true;
        self
    }

    /// Make sure the cookie is sent only via HTTPS connections.
    /// This is the `Secure` attribute.
    pub fn secure(mut self) -> Self {
        self.cookie.secure = true;
        self
    }

    /// Set cookie `SameSite` attribute to `Lax`.
    ///
    /// This setting is desirable if you want
    /// the cookie set on redirects from external sites.
    pub fn lax(mut self) -> Self {
        self.cookie.same_site = Some("Lax".to_string());
        self
    }

    /// Set cookie `SameSite` attribute to `Strict`.
    ///
    /// This cookie won't be set on redirects from external links, breaking
    /// authentication.
    pub fn strict(mut self) -> Self {
        self.cookie.same_site = Some("Strict".to_string());
        self
    }

    /// Build the cookie.
    ///
    /// This consumes the builder.
    pub fn build(self) -> Cookie {
        self.cookie
    }
}

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

    #[test]
    fn test_parsing_cookies() {
        let value = "name=some_value; Max-Age=55; Secure";
        let cookie = Cookie::parse(value).expect("cookie parse");
        assert_eq!(cookie.name(), "name");
        assert_eq!(cookie.value(), "some_value");
        assert!(cookie.secure());
        assert_eq!(cookie.max_age(), Some(Duration::seconds(55)));

        let value = "random=hello_world";
        let cookie = Cookie::parse(value).expect("cookie parse");
        assert_eq!(cookie.name(), "random");
        assert_eq!(cookie.value(), "hello_world");
    }

    #[test]
    fn test_creating_cookies() {
        let mut cookies = Cookies::new();
        cookies.add(("hello", "world"));
        cookies
            .add_private(("session", "super_secret_key"))
            .expect("private");
        let s = cookies.to_string();

        let cookies = Cookies::parse(&s);
        assert!(cookies.get("hello").is_some());
        assert_eq!(cookies.get("hello").unwrap().value(), "world");
        assert_eq!(
            cookies
                .get_private("session")
                .expect("decrypt")
                .expect("session cookie")
                .value(),
            "super_secret_key"
        );
    }
}