Skip to main content

rocket/
cookies.rs

1use std::fmt;
2
3use parking_lot::Mutex;
4
5use crate::Config;
6use crate::http::private::cookie;
7
8#[doc(inline)]
9pub use self::cookie::{Cookie, SameSite, Iter};
10
11/// Collection of one or more HTTP cookies.
12///
13/// `CookieJar` allows for retrieval of cookies from an incoming request. It
14/// also tracks modifications (additions and removals) and marks them as
15/// pending.
16///
17/// # Pending
18///
19/// Changes to a `CookieJar` are _not_ visible via the normal [`get()`] and
20/// [`get_private()`] methods. This is typically the desired effect as a
21/// `CookieJar` always reflects the cookies in an incoming request. In cases
22/// where this is not desired, the [`get_pending()`] method is available, which
23/// always returns the latest changes.
24///
25/// ```rust
26/// # #[macro_use] extern crate rocket;
27/// use rocket::http::{CookieJar, Cookie};
28///
29/// #[get("/message")]
30/// fn message(jar: &CookieJar<'_>) {
31///     jar.add(("message", "hello!"));
32///     jar.add(Cookie::build(("session", "bye!")).expires(None));
33///
34///     // `get()` does not reflect changes.
35///     assert!(jar.get("session").is_none());
36///     assert_eq!(jar.get("message").map(|c| c.value()), Some("hi"));
37///
38///     // `get_pending()` does.
39///     let session_pending = jar.get_pending("session");
40///     let message_pending = jar.get_pending("message");
41///     assert_eq!(session_pending.as_ref().map(|c| c.value()), Some("bye!"));
42///     assert_eq!(message_pending.as_ref().map(|c| c.value()), Some("hello!"));
43///     # jar.remove("message");
44///     # assert_eq!(jar.get("message").map(|c| c.value()), Some("hi"));
45///     # assert!(jar.get_pending("message").is_none());
46/// }
47/// # fn main() {
48/// #     use rocket::local::blocking::Client;
49/// #     let client = Client::debug_with(routes![message]).unwrap();
50/// #     let response = client.get("/message")
51/// #         .cookie(("message", "hi"))
52/// #         .dispatch();
53/// #
54/// #     assert!(response.status().class().is_success());
55/// # }
56/// ```
57///
58/// # Usage
59///
60/// A type of `&CookieJar` can be retrieved via its `FromRequest` implementation
61/// as a request guard or via the [`Request::cookies()`] method. Individual
62/// cookies can be retrieved via the [`get()`] and [`get_private()`] methods.
63/// Pending changes can be observed via the [`get_pending()`] method. Cookies
64/// can be added or removed via the [`add()`], [`add_private()`], [`remove()`],
65/// and [`remove_private()`] methods.
66///
67/// [`Request::cookies()`]: crate::Request::cookies()
68/// [`get()`]: #method.get
69/// [`get_private()`]: #method.get_private
70/// [`get_pending()`]: #method.get_pending
71/// [`add()`]: #method.add
72/// [`add_private()`]: #method.add_private
73/// [`remove()`]: #method.remove
74/// [`remove_private()`]: #method.remove_private
75///
76/// ## Examples
77///
78/// The following example shows `&CookieJar` being used as a request guard in a
79/// handler to retrieve the value of a "message" cookie.
80///
81/// ```rust
82/// # #[macro_use] extern crate rocket;
83/// use rocket::http::CookieJar;
84///
85/// #[get("/message")]
86/// fn message<'a>(jar: &'a CookieJar<'_>) -> Option<&'a str> {
87///     jar.get("message").map(|cookie| cookie.value())
88/// }
89/// # fn main() {  }
90/// ```
91///
92/// The following snippet shows `&CookieJar` being retrieved from a `Request` in
93/// a custom request guard implementation for `User`. A [private cookie]
94/// containing a user's ID is retrieved. If the cookie exists and the ID parses
95/// as an integer, a `User` structure is validated. Otherwise, the guard
96/// forwards.
97///
98/// [private cookie]: #method.add_private
99///
100/// ```rust
101/// # #[macro_use] extern crate rocket;
102/// # #[cfg(feature = "secrets")] {
103/// use rocket::http::Status;
104/// use rocket::request::{self, Request, FromRequest};
105/// use rocket::outcome::IntoOutcome;
106///
107/// // In practice, we'd probably fetch the user from the database.
108/// struct User(usize);
109///
110/// #[rocket::async_trait]
111/// impl<'r> FromRequest<'r> for User {
112///     type Error = std::convert::Infallible;
113///
114///     async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
115///         request.cookies()
116///             .get_private("user_id")
117///             .and_then(|c| c.value().parse().ok())
118///             .map(|id| User(id))
119///             .or_forward(Status::Unauthorized)
120///     }
121/// }
122/// # }
123/// ```
124///
125/// # Private Cookies
126///
127/// _Private_ cookies are just like regular cookies except that they are
128/// encrypted using authenticated encryption, a form of encryption which
129/// simultaneously provides confidentiality, integrity, and authenticity. This
130/// means that private cookies cannot be inspected, tampered with, or
131/// manufactured by clients. If you prefer, you can think of private cookies as
132/// being signed and encrypted.
133///
134/// Private cookies can be retrieved, added, and removed from a `CookieJar`
135/// collection via the [`get_private()`], [`add_private()`], and
136/// [`remove_private()`] methods.
137///
138/// ## Encryption Key
139///
140/// To encrypt private cookies, Rocket uses the 256-bit key specified in the
141/// `secret_key` configuration parameter. If one is not specified, Rocket will
142/// automatically generate a fresh key. Note, however, that a private cookie can
143/// only be decrypted with the same key with which it was encrypted. As such, it
144/// is important to set a `secret_key` configuration parameter when using
145/// private cookies so that cookies decrypt properly after an application
146/// restart. Rocket will emit a warning if an application is run in production
147/// mode without a configured `secret_key`.
148///
149/// Generating a string suitable for use as a `secret_key` configuration value
150/// is usually done through tools like `openssl`. Using `openssl`, for instance,
151/// a 256-bit base64 key can be generated with the command `openssl rand -base64
152/// 32`.
153pub struct CookieJar<'a> {
154    jar: cookie::CookieJar,
155    ops: Mutex<Vec<Op>>,
156    config: &'a Config,
157}
158
159impl<'a> Clone for CookieJar<'a> {
160    fn clone(&self) -> Self {
161        CookieJar {
162            jar: self.jar.clone(),
163            ops: Mutex::new(self.ops.lock().clone()),
164            config: self.config,
165        }
166    }
167}
168
169#[derive(Clone)]
170enum Op {
171    Add(Cookie<'static>, bool),
172    Remove(Cookie<'static>),
173}
174
175impl Op {
176    fn cookie(&self) -> &Cookie<'static> {
177        match self {
178            Op::Add(c, _) | Op::Remove(c) => c
179        }
180    }
181}
182
183impl<'a> CookieJar<'a> {
184    #[inline(always)]
185    pub(crate) fn new(config: &'a Config) -> Self {
186        CookieJar::from(cookie::CookieJar::new(), config)
187    }
188
189    pub(crate) fn from(jar: cookie::CookieJar, config: &'a Config) -> Self {
190        CookieJar { jar, config, ops: Mutex::new(Vec::new()) }
191    }
192
193    /// Returns a reference to the _original_ `Cookie` inside this container
194    /// with the name `name`. If no such cookie exists, returns `None`.
195    ///
196    /// **Note:** This method _does not_ observe changes made via additions and
197    /// removals to the cookie jar. To observe those changes, use
198    /// [`CookieJar::get_pending()`].
199    ///
200    /// # Example
201    ///
202    /// ```rust
203    /// # #[macro_use] extern crate rocket;
204    /// use rocket::http::CookieJar;
205    ///
206    /// #[get("/")]
207    /// fn handler(jar: &CookieJar<'_>) {
208    ///     let cookie = jar.get("name");
209    /// }
210    /// ```
211    pub fn get(&self, name: &str) -> Option<&Cookie<'static>> {
212        self.jar.get(name)
213    }
214
215    /// Retrieves the _original_ `Cookie` inside this collection with the name
216    /// `name` and authenticates and decrypts the cookie's value. If the cookie
217    /// cannot be found, or the cookie fails to authenticate or decrypt, `None`
218    /// is returned.
219    ///
220    /// **Note:** This method _does not_ observe changes made via additions and
221    /// removals to the cookie jar. To observe those changes, use
222    /// [`CookieJar::get_pending()`].
223    ///
224    /// # Example
225    ///
226    /// ```rust
227    /// # #[macro_use] extern crate rocket;
228    /// use rocket::http::CookieJar;
229    ///
230    /// #[get("/")]
231    /// fn handler(jar: &CookieJar<'_>) {
232    ///     let cookie = jar.get_private("name");
233    /// }
234    /// ```
235    #[cfg(feature = "secrets")]
236    #[cfg_attr(nightly, doc(cfg(feature = "secrets")))]
237    pub fn get_private(&self, name: &str) -> Option<Cookie<'static>> {
238        self.jar.private(&self.config.secret_key.key).get(name)
239    }
240
241    /// Returns a reference to the _original or pending_ `Cookie` inside this
242    /// container with the name `name`, irrespective of whether the cookie was
243    /// private or not. If no such cookie exists, returns `None`.
244    ///
245    /// In general, due to performance overhead, calling this method should be
246    /// avoided if it is known that a cookie called `name` is not pending.
247    /// Instead, prefer to use [`CookieJar::get()`] or
248    /// [`CookieJar::get_private()`].
249    ///
250    /// # Example
251    ///
252    /// ```rust
253    /// # #[macro_use] extern crate rocket;
254    /// use rocket::http::CookieJar;
255    ///
256    /// #[get("/")]
257    /// fn handler(jar: &CookieJar<'_>) {
258    ///     let pending_cookie = jar.get_pending("name");
259    /// }
260    /// ```
261    pub fn get_pending(&self, name: &str) -> Option<Cookie<'static>> {
262        let ops = self.ops.lock();
263        for op in ops.iter().rev().filter(|op| op.cookie().name() == name) {
264            match op {
265                Op::Add(c, _) => return Some(c.clone()),
266                Op::Remove(_) => return None,
267            }
268        }
269
270        drop(ops);
271
272        #[cfg(feature = "secrets")] {
273            self.get_private(name).or_else(|| self.get(name).cloned())
274        }
275
276        #[cfg(not(feature = "secrets"))] {
277            self.get(name).cloned()
278        }
279    }
280
281    /// Adds `cookie` to this collection.
282    ///
283    /// Unless a value is set for the given property, the following defaults are
284    /// set on `cookie` before being added to `self`:
285    ///
286    ///    * `path`: `"/"`
287    ///    * `SameSite`: `Strict`
288    ///
289    /// Furthermore, if TLS is enabled, the `Secure` cookie flag is set.
290    ///
291    /// # Example
292    ///
293    /// ```rust
294    /// # #[macro_use] extern crate rocket;
295    /// use rocket::http::{Cookie, SameSite, CookieJar};
296    ///
297    /// #[get("/")]
298    /// fn handler(jar: &CookieJar<'_>) {
299    ///     jar.add(("first", "value"));
300    ///
301    ///     let cookie = Cookie::build(("other", "value_two"))
302    ///         .path("/")
303    ///         .secure(true)
304    ///         .same_site(SameSite::Lax);
305    ///
306    ///     jar.add(cookie);
307    /// }
308    /// ```
309    pub fn add<C: Into<Cookie<'static>>>(&self, cookie: C) {
310        let mut cookie = cookie.into();
311        Self::set_defaults(self.config, &mut cookie);
312        self.ops.lock().push(Op::Add(cookie, false));
313    }
314
315    /// Adds `cookie` to the collection. The cookie's value is encrypted with
316    /// authenticated encryption assuring confidentiality, integrity, and
317    /// authenticity. The cookie can later be retrieved using
318    /// [`get_private`](#method.get_private) and removed using
319    /// [`remove_private`](#method.remove_private).
320    ///
321    /// Unless a value is set for the given property, the following defaults are
322    /// set on `cookie` before being added to `self`:
323    ///
324    ///    * `path`: `"/"`
325    ///    * `SameSite`: `Strict`
326    ///    * `HttpOnly`: `true`
327    ///    * `Expires`: 1 week from now
328    ///
329    /// Furthermore, if TLS is enabled, the `Secure` cookie flag is set. These
330    /// defaults ensure maximum usability and security. For additional security,
331    /// you may wish to set the `secure` flag.
332    ///
333    /// # Example
334    ///
335    /// ```rust
336    /// # #[macro_use] extern crate rocket;
337    /// use rocket::http::CookieJar;
338    ///
339    /// #[get("/")]
340    /// fn handler(jar: &CookieJar<'_>) {
341    ///     jar.add_private(("name", "value"));
342    /// }
343    /// ```
344    #[cfg(feature = "secrets")]
345    #[cfg_attr(nightly, doc(cfg(feature = "secrets")))]
346    pub fn add_private<C: Into<Cookie<'static>>>(&self, cookie: C) {
347        let mut cookie = cookie.into();
348        Self::set_private_defaults(self.config, &mut cookie);
349        self.ops.lock().push(Op::Add(cookie, true));
350    }
351
352    /// Removes `cookie` from this collection and generates a "removal" cookie
353    /// to send to the client on response. A "removal" cookie is a cookie that
354    /// has the same name as the original cookie but has an empty value, a
355    /// max-age of 0, and an expiration date far in the past.
356    ///
357    /// **For successful removal, `cookie` must contain the same `path` and
358    /// `domain` as the cookie that was originally set. The cookie will fail to
359    /// be deleted if any other `path` and `domain` are provided. For
360    /// convenience, a path of `"/"` is automatically set when one is not
361    /// specified.** The full list of defaults when corresponding values aren't
362    /// specified is:
363    ///
364    ///    * `path`: `"/"`
365    ///    * `SameSite`: `Lax`
366    ///
367    /// <small>Note: a default setting of `Lax` for `SameSite` carries no
368    /// security implications: the removal cookie has expired, so it is never
369    /// transferred to any origin.</small>
370    ///
371    /// # Example
372    ///
373    /// ```rust
374    /// # #[macro_use] extern crate rocket;
375    /// use rocket::http::{Cookie, CookieJar};
376    ///
377    /// #[get("/")]
378    /// fn handler(jar: &CookieJar<'_>) {
379    ///     // `path` and `SameSite` are set to defaults (`/` and `Lax`)
380    ///     jar.remove("name");
381    ///
382    ///     // Use a custom-built cookie to set a custom path.
383    ///     jar.remove(Cookie::build("name").path("/login"));
384    ///
385    ///     // Use a custom-built cookie to set a custom path and domain.
386    ///     jar.remove(Cookie::build("id").path("/guide").domain("rocket.rs"));
387    /// }
388    /// ```
389    pub fn remove<C: Into<Cookie<'static>>>(&self, cookie: C) {
390        let mut cookie = cookie.into();
391        Self::set_removal_defaults(&mut cookie);
392        self.ops.lock().push(Op::Remove(cookie));
393    }
394
395    /// Removes the private `cookie` from the collection.
396    ///
397    /// **For successful removal, `cookie` must contain the same `path` and
398    /// `domain` as the cookie that was originally set. The cookie will fail to
399    /// be deleted if any other `path` and `domain` are provided. For
400    /// convenience, a path of `"/"` is automatically set when one is not
401    /// specified.** The full list of defaults when corresponding values aren't
402    /// specified is:
403    ///
404    ///    * `path`: `"/"`
405    ///    * `SameSite`: `Lax`
406    ///
407    /// <small>Note: a default setting of `Lax` for `SameSite` carries no
408    /// security implications: the removal cookie has expired, so it is never
409    /// transferred to any origin.</small>
410    ///
411    /// # Example
412    ///
413    /// ```rust
414    /// # #[macro_use] extern crate rocket;
415    /// use rocket::http::{CookieJar, Cookie};
416    ///
417    /// #[get("/")]
418    /// fn handler(jar: &CookieJar<'_>) {
419    ///     // `path` and `SameSite` are set to defaults (`/` and `Lax`)
420    ///     jar.remove_private("name");
421    ///
422    ///     // Use a custom-built cookie to set a custom path.
423    ///     jar.remove_private(Cookie::build("name").path("/login"));
424    ///
425    ///     // Use a custom-built cookie to set a custom path and domain.
426    ///     let cookie = Cookie::build("id").path("/guide").domain("rocket.rs");
427    ///     jar.remove_private(cookie);
428    /// }
429    /// ```
430    #[cfg(feature = "secrets")]
431    #[cfg_attr(nightly, doc(cfg(feature = "secrets")))]
432    pub fn remove_private<C: Into<Cookie<'static>>>(&self, cookie: C) {
433        let mut cookie = cookie.into();
434        Self::set_removal_defaults(&mut cookie);
435        self.ops.lock().push(Op::Remove(cookie));
436    }
437
438    /// Returns an iterator over all of the _original_ cookies present in this
439    /// collection.
440    ///
441    /// **Note:** This method _does not_ observe changes made via additions and
442    /// removals to the cookie jar.
443    ///
444    /// # Example
445    ///
446    /// ```rust
447    /// # #[macro_use] extern crate rocket;
448    /// use rocket::http::CookieJar;
449    ///
450    /// #[get("/")]
451    /// fn handler(jar: &CookieJar<'_>) {
452    ///     for c in jar.iter() {
453    ///         println!("Name: {:?}, Value: {:?}", c.name(), c.value());
454    ///     }
455    /// }
456    /// ```
457    pub fn iter(&self) -> impl Iterator<Item=&Cookie<'static>> {
458        self.jar.iter()
459    }
460
461    /// Removes all delta cookies.
462    #[inline(always)]
463    pub(crate) fn reset_delta(&self) {
464        self.ops.lock().clear();
465    }
466
467    /// TODO: This could be faster by just returning the cookies directly via
468    /// an ordered hash-set of sorts.
469    pub(crate) fn take_delta_jar(&self) -> cookie::CookieJar {
470        let ops = std::mem::take(&mut *self.ops.lock());
471        let mut jar = cookie::CookieJar::new();
472
473        for op in ops {
474            match op {
475                Op::Add(c, false) => jar.add(c),
476                #[cfg(feature = "secrets")]
477                Op::Add(c, true) => {
478                    jar.private_mut(&self.config.secret_key.key).add(c);
479                }
480                Op::Remove(mut c) => {
481                    if self.jar.get(c.name()).is_some() {
482                        c.make_removal();
483                        jar.add(c);
484                    } else {
485                        jar.remove(c);
486                    }
487                }
488                #[allow(unreachable_patterns)]
489                _ => unreachable!()
490            }
491        }
492
493        jar
494    }
495
496    /// Adds an original `cookie` to this collection.
497    #[inline(always)]
498    pub(crate) fn add_original(&mut self, cookie: Cookie<'static>) {
499        self.jar.add_original(cookie)
500    }
501
502    /// Adds an original, private `cookie` to the collection.
503    #[cfg(feature = "secrets")]
504    #[cfg_attr(nightly, doc(cfg(feature = "secrets")))]
505    #[inline(always)]
506    pub(crate) fn add_original_private(&mut self, cookie: Cookie<'static>) {
507        self.jar.private_mut(&self.config.secret_key.key).add_original(cookie);
508    }
509
510    /// For each property mentioned below, this method checks if there is a
511    /// provided value and if there is none, sets a default value. Default
512    /// values are:
513    ///
514    ///    * `path`: `"/"`
515    ///    * `SameSite`: `Strict`
516    ///
517    /// Furthermore, if TLS is enabled, the `Secure` cookie flag is set.
518    fn set_defaults(config: &Config, cookie: &mut Cookie<'static>) {
519        if cookie.path().is_none() {
520            cookie.set_path("/");
521        }
522
523        if cookie.same_site().is_none() {
524            cookie.set_same_site(SameSite::Strict);
525        }
526
527        if cookie.secure().is_none() && config.tls_enabled() {
528            cookie.set_secure(true);
529        }
530    }
531
532    /// For each property below, this method checks if there is a provided value
533    /// and if there is none, sets a default value. Default values are:
534    ///
535    ///    * `path`: `"/"`
536    ///    * `SameSite`: `Lax`
537    fn set_removal_defaults(cookie: &mut Cookie<'static>) {
538        if cookie.path().is_none() {
539            cookie.set_path("/");
540        }
541
542        if cookie.same_site().is_none() {
543            cookie.set_same_site(SameSite::Lax);
544        }
545    }
546
547    /// For each property mentioned below, this method checks if there is a
548    /// provided value and if there is none, sets a default value. Default
549    /// values are:
550    ///
551    ///    * `path`: `"/"`
552    ///    * `SameSite`: `Strict`
553    ///    * `HttpOnly`: `true`
554    ///    * `Expires`: 1 week from now
555    ///
556    /// Furthermore, if TLS is enabled, the `Secure` cookie flag is set.
557    #[cfg(feature = "secrets")]
558    #[cfg_attr(nightly, doc(cfg(feature = "secrets")))]
559    fn set_private_defaults(config: &Config, cookie: &mut Cookie<'static>) {
560        if cookie.path().is_none() {
561            cookie.set_path("/");
562        }
563
564        if cookie.same_site().is_none() {
565            cookie.set_same_site(SameSite::Strict);
566        }
567
568        if cookie.http_only().is_none() {
569            cookie.set_http_only(true);
570        }
571
572        if cookie.expires().is_none() {
573            cookie.set_expires(time::OffsetDateTime::now_utc() + time::Duration::weeks(1));
574        }
575
576        if cookie.secure().is_none() && config.tls_enabled() {
577            cookie.set_secure(true);
578        }
579    }
580}
581
582impl fmt::Debug for CookieJar<'_> {
583    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
584        let pending: Vec<_> = self.ops.lock()
585            .iter()
586            .map(|c| c.cookie())
587            .cloned()
588            .collect();
589
590        f.debug_struct("CookieJar")
591            .field("original", &self.jar)
592            .field("pending", &pending)
593            .finish()
594    }
595
596}