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