topcoat-cookie 0.2.0

A modular, batteries-included Rust web framework for server-rendered apps.
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
use std::{borrow::Cow, marker::PhantomData};

use serde::{Serialize, de::DeserializeOwned};

use crate::{Cookie, Cookies};

/// A typed value backed by a single cookie.
///
/// A `CookieStore` holds a deserialized `T` in memory and writes it back to its
/// cookie as JSON on [`commit`](Self::commit). It is built from any [`Cookies`]
/// jar, so signing, encryption, prefixes, and default attributes all compose
/// through the jar it wraps.
///
/// Reads and mutations operate on the in-memory value only. **Nothing is written
/// to the response until [`commit`](Self::commit) is called**; dropping the store
/// (or calling [`rollback`](Self::rollback)) discards any pending changes. This
/// makes it easy to update a cookie only once some other work has succeeded:
/// just hold off on `commit` until then.
///
/// Obtain one by reading the incoming cookie through [`cookie_store`]:
///
/// ```rust
/// use serde::{Deserialize, Serialize};
/// use topcoat::{
///     Result,
///     context::Cx,
///     cookie::{cookie_store, private_cookies},
///     router::route,
/// };
///
/// #[derive(Default, Serialize, Deserialize)]
/// struct Cart {
///     items: Vec<String>,
/// }
///
/// #[route(POST "/api/cart")]
/// async fn add_item(cx: &Cx) -> Result<String> {
///     // `commit` writes the cookie and hands the value back; without it the
///     // change is discarded.
///     let cart = cookie_store::<Cart, _>(private_cookies(cx), "cart")
///         .parse_or_default()
///         .update(|cart| cart.items.push("widget".to_owned()))
///         .commit()?;
///
///     Ok(format!("{} items in cart", cart.items.len()))
/// }
/// ```
pub struct CookieStore<T, J> {
    jar: J,
    key: Cow<'static, str>,
    value: T,
}

impl<T, J> CookieStore<T, J>
where
    T: Serialize + DeserializeOwned,
    J: Cookies,
{
    /// Builds a store around an already-known `value`.
    ///
    /// Most code instead goes through [`cookie_store`] and one of the `parse*`
    /// methods, which read the existing cookie first.
    pub fn new(jar: J, key: impl Into<Cow<'static, str>>, value: T) -> Self {
        Self {
            jar,
            key: key.into(),
            value,
        }
    }

    /// Returns a reference to the in-memory value.
    pub fn read(&self) -> &T {
        &self.value
    }

    /// Returns a clone of the in-memory value.
    pub fn get(&self) -> T
    where
        T: Clone,
    {
        self.value.clone()
    }

    /// Replaces the in-memory value, returning the store so calls can be chained.
    ///
    /// Like every mutation, this is not persisted until [`commit`](Self::commit).
    #[must_use]
    pub fn set(mut self, value: T) -> Self {
        self.value = value;
        self
    }

    /// Mutates the in-memory value in place, returning the store so calls can be
    /// chained.
    ///
    /// Like every mutation, this is not persisted until [`commit`](Self::commit).
    ///
    /// ```rust
    /// # use serde::{Deserialize, Serialize};
    /// # use topcoat::{
    /// #     Result,
    /// #     context::Cx,
    /// #     cookie::{cookie_store, private_cookies},
    /// # };
    /// # #[derive(Default, Serialize, Deserialize)]
    /// # struct Cart {
    /// #     items: Vec<String>,
    /// # }
    /// # fn example(cx: &Cx) -> Result<(), topcoat::Error> {
    /// let cart = cookie_store::<Cart, _>(private_cookies(cx), "cart")
    ///     .parse_or_default()
    ///     .update(|cart| cart.items.push("widget".to_owned()))
    ///     .commit()?;
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn update<F>(mut self, f: F) -> Self
    where
        F: FnOnce(&mut T),
    {
        f(&mut self.value);
        self
    }

    /// Serializes the current value, queues it on the backing jar as a
    /// `Set-Cookie`, and returns the value.
    ///
    /// This is the only method that writes anything: until it is called, the
    /// store's value lives only in memory. Returns an error if the value cannot
    /// be serialized.
    ///
    /// # Errors
    ///
    /// Returns `Err` if serializing `T` to JSON fails.
    pub fn commit(self) -> Result<T, serde_json::Error> {
        let serialized = serde_json::to_string(&self.value)?;
        self.jar.add(Cookie::new(self.key, serialized));
        Ok(self.value)
    }

    /// Discards the store along with any uncommitted changes.
    ///
    /// Equivalent to dropping the store without calling [`commit`](Self::commit);
    /// it exists to make that intent explicit at the call site.
    pub fn rollback(self) {}

    /// Queues a removal of the backing cookie, expiring it on the client.
    ///
    /// Writes to the response like [`commit`](Self::commit), but deletes the
    /// cookie instead of saving a value; the in-memory value is dropped. The
    /// removal goes through the jar, so the `Path`/`Domain` and prefix attributes
    /// the cookie was written with are reapplied and the browser can match it.
    pub fn remove(self) {
        self.jar.remove(Cookie::new(self.key, ""));
    }
}

/// A [`CookieStore`] that has not yet read its backing cookie.
///
/// Created by [`cookie_store`]. Call one of the `parse*` methods to read and
/// deserialize the cookie, yielding a [`CookieStore`] you can read and mutate.
pub struct UnparsedCookieStore<T, J> {
    jar: J,
    key: Cow<'static, str>,
    _marker: PhantomData<fn() -> T>,
}

impl<T, J> UnparsedCookieStore<T, J>
where
    T: Serialize + DeserializeOwned,
    J: Cookies,
{
    /// Builds an unparsed store for the cookie named `key`, backed by `jar`.
    ///
    /// Usually called through [`cookie_store`].
    pub fn new(jar: J, key: impl Into<Cow<'static, str>>) -> Self {
        Self {
            jar,
            key: key.into(),
            _marker: PhantomData,
        }
    }

    /// Seeds a [`CookieStore`] with `value` without reading the existing cookie.
    ///
    /// Use this to overwrite the cookie outright when you don't need its current
    /// contents. The value is not written until the returned store is
    /// [`commit`](CookieStore::commit)ted.
    ///
    /// ```rust
    /// # use serde::{Deserialize, Serialize};
    /// # use topcoat::{
    /// #     Result,
    /// #     context::Cx,
    /// #     cookie::{cookie_store, private_cookies},
    /// # };
    /// # #[derive(Default, Serialize, Deserialize)]
    /// # struct Cart {
    /// #     items: Vec<String>,
    /// # }
    /// # fn example(cx: &Cx) -> Result<(), topcoat::Error> {
    /// cookie_store::<Cart, _>(private_cookies(cx), "cart")
    ///     .set(Cart::default())
    ///     .commit()?;
    /// #     Ok(())
    /// # }
    /// ```
    pub fn set(self, value: T) -> CookieStore<T, J> {
        CookieStore::new(self.jar, self.key, value)
    }

    /// Queues a removal of the backing cookie without reading it first.
    ///
    /// Use this to delete the cookie regardless of its current contents.
    pub fn remove(self) {
        self.jar.remove(Cookie::new(self.key, ""));
    }

    /// Reads and deserializes the backing cookie.
    ///
    /// Returns `Ok(None)` when the cookie is absent, and `Err` when it is
    /// present but cannot be deserialized.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the cookie is present but its value cannot be
    /// deserialized into `T`.
    pub fn parse(self) -> Result<Option<CookieStore<T, J>>, serde_json::Error> {
        match self.jar.get(&self.key) {
            Some(cookie) => {
                let value = serde_json::from_str(cookie.value())?;
                Ok(Some(CookieStore::new(self.jar, self.key, value)))
            }
            None => Ok(None),
        }
    }

    /// Parses the backing cookie, falling back to `default` when it is absent or
    /// malformed.
    pub fn parse_or(self, default: T) -> CookieStore<T, J> {
        self.parse_or_else(move || default)
    }

    /// Parses the backing cookie, falling back to `f()` when it is absent or
    /// malformed.
    pub fn parse_or_else<F>(self, f: F) -> CookieStore<T, J>
    where
        F: FnOnce() -> T,
    {
        let value = match self.jar.get(&self.key) {
            Some(cookie) => serde_json::from_str(cookie.value()).unwrap_or_else(|_| f()),
            None => f(),
        };
        CookieStore::new(self.jar, self.key, value)
    }

    /// Parses the backing cookie, falling back to `T::default()` when it is
    /// absent or malformed.
    pub fn parse_or_default(self) -> CookieStore<T, J>
    where
        T: Default,
    {
        self.parse_or_else(T::default)
    }
}

/// Builds an [`UnparsedCookieStore`] for the cookie named `key`, backed by `jar`.
///
/// `jar` is any [`Cookies`] jar, so signing, encryption, prefixes, and default
/// attributes compose through it. Specify the stored type as `T`:
///
/// ```rust
/// # use serde::{Deserialize, Serialize};
/// # use topcoat::{
/// #     Result,
/// #     context::Cx,
/// #     cookie::{cookie_store, private_cookies},
/// # };
/// # #[derive(Default, Serialize, Deserialize)]
/// # struct Cart {
/// #     items: Vec<String>,
/// # }
/// # fn example(cx: &Cx) -> Result<(), topcoat::Error> {
/// let cart = cookie_store::<Cart, _>(private_cookies(cx), "cart").parse_or_default();
/// #     Ok(())
/// # }
/// ```
pub fn cookie_store<T, J>(jar: J, key: impl Into<Cow<'static, str>>) -> UnparsedCookieStore<T, J>
where
    T: Serialize + DeserializeOwned,
    J: Cookies,
{
    UnparsedCookieStore::new(jar, key)
}

#[cfg(test)]
mod tests {
    use std::{cell::RefCell, collections::HashMap};

    use http::{HeaderMap, Request, header};
    use serde::{Deserialize, Serialize};
    use topcoat_core::context::{Cx, CxTestBuilder};

    use super::*;
    use crate::{CookieJarCell, Key, cookies, write_cookies};

    #[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
    struct Cart {
        items: Vec<String>,
    }

    /// A minimal [`Cookies`] jar for testing the store in isolation: it serves
    /// preset incoming cookies and records the cookies written through it.
    #[derive(Default)]
    struct MockJar {
        incoming: HashMap<String, String>,
        added: RefCell<Vec<Cookie<'static>>>,
        removed: RefCell<Vec<Cookie<'static>>>,
    }

    impl MockJar {
        fn with(pairs: &[(&str, &str)]) -> Self {
            Self {
                incoming: pairs
                    .iter()
                    .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
                    .collect(),
                ..Self::default()
            }
        }

        fn added(&self) -> Vec<Cookie<'static>> {
            self.added.borrow().clone()
        }

        fn removed(&self) -> Vec<Cookie<'static>> {
            self.removed.borrow().clone()
        }
    }

    impl Cookies for &MockJar {
        fn get(&self, name: &str) -> Option<Cookie<'static>> {
            self.incoming
                .get(name)
                .map(|value| Cookie::new(name.to_owned(), value.clone()))
        }

        fn add<C: Into<Cookie<'static>>>(&self, cookie: C) {
            self.added.borrow_mut().push(cookie.into());
        }

        fn remove<C: Into<Cookie<'static>>>(&self, cookie: C) {
            self.removed.borrow_mut().push(cookie.into());
        }
    }

    #[test]
    fn parse_reads_existing_value() {
        let jar = MockJar::with(&[("cart", r#"{"items":["a","b"]}"#)]);
        let store = cookie_store::<Cart, _>(&jar, "cart")
            .parse()
            .unwrap()
            .expect("cookie is present");

        assert_eq!(store.read().items, ["a", "b"]);
    }

    #[test]
    fn parse_returns_none_when_absent() {
        let jar = MockJar::with(&[]);
        assert!(
            cookie_store::<Cart, _>(&jar, "cart")
                .parse()
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn parse_errors_on_malformed() {
        let jar = MockJar::with(&[("cart", "not json")]);
        assert!(cookie_store::<Cart, _>(&jar, "cart").parse().is_err());
    }

    #[test]
    fn parse_or_default_falls_back_when_absent_or_malformed() {
        let absent = MockJar::with(&[]);
        assert_eq!(
            cookie_store::<Cart, _>(&absent, "cart")
                .parse_or_default()
                .get(),
            Cart::default()
        );

        // A malformed cookie is treated like a missing one, not an error.
        let malformed = MockJar::with(&[("cart", "not json")]);
        assert_eq!(
            cookie_store::<Cart, _>(&malformed, "cart")
                .parse_or_default()
                .get(),
            Cart::default()
        );
    }

    #[test]
    fn parse_or_and_parse_or_else_use_their_fallbacks() {
        let jar = MockJar::with(&[]);
        let from_value = cookie_store::<Cart, _>(&jar, "cart").parse_or(Cart {
            items: vec!["x".to_owned()],
        });
        assert_eq!(from_value.read().items, ["x"]);

        let from_closure = cookie_store::<Cart, _>(&jar, "cart").parse_or_else(|| Cart {
            items: vec!["y".to_owned()],
        });
        assert_eq!(from_closure.read().items, ["y"]);
    }

    #[test]
    fn commit_writes_serialized_cookie_and_returns_value() {
        let jar = MockJar::with(&[]);
        let cart = cookie_store::<Cart, _>(&jar, "cart")
            .parse_or_default()
            .update(|cart| cart.items.push("widget".to_owned()))
            .commit()
            .unwrap();

        // The value is handed back.
        assert_eq!(cart.items, ["widget"]);

        // And serialized into the jar under the right name.
        let added = jar.added();
        assert_eq!(added.len(), 1);
        assert_eq!(added[0].name(), "cart");
        assert_eq!(added[0].value(), r#"{"items":["widget"]}"#);
    }

    #[test]
    fn get_clones_and_read_borrows() {
        let jar = MockJar::with(&[("cart", r#"{"items":["a"]}"#)]);
        let store = cookie_store::<Cart, _>(&jar, "cart").parse_or_default();

        assert_eq!(store.read().items, ["a"]);
        assert_eq!(store.get(), *store.read());
    }

    #[test]
    fn nothing_is_written_without_commit() {
        let jar = MockJar::with(&[]);
        let _ = cookie_store::<Cart, _>(&jar, "cart")
            .parse_or_default()
            .update(|cart| cart.items.push("z".to_owned()));

        assert!(jar.added().is_empty());
    }

    #[test]
    fn rollback_writes_nothing() {
        let jar = MockJar::with(&[]);
        cookie_store::<Cart, _>(&jar, "cart")
            .parse_or_default()
            .update(|cart| cart.items.push("z".to_owned()))
            .rollback();

        assert!(jar.added().is_empty());
    }

    #[test]
    fn unparsed_set_overwrites_without_reading() {
        let jar = MockJar::with(&[("cart", r#"{"items":["old"]}"#)]);
        cookie_store::<Cart, _>(&jar, "cart")
            .set(Cart {
                items: vec!["new".to_owned()],
            })
            .commit()
            .unwrap();

        assert_eq!(jar.added()[0].value(), r#"{"items":["new"]}"#);
    }

    #[test]
    fn remove_queues_a_removal() {
        // On a parsed store.
        let parsed = MockJar::with(&[("cart", r#"{"items":[]}"#)]);
        cookie_store::<Cart, _>(&parsed, "cart")
            .parse_or_default()
            .remove();
        let removed = parsed.removed();
        assert_eq!(removed.len(), 1);
        assert_eq!(removed[0].name(), "cart");
        assert!(parsed.added().is_empty());

        // And directly on the unparsed store.
        let unparsed = MockJar::with(&[]);
        cookie_store::<Cart, _>(&unparsed, "cart").remove();
        assert_eq!(unparsed.removed()[0].name(), "cart");
    }

    /// Builds a `Cx` whose request carries the given raw `Cookie` header values.
    fn cx_with(cookie_headers: &[&str]) -> Cx {
        let mut builder = Request::builder();
        for value in cookie_headers {
            builder = builder.header(header::COOKIE, *value);
        }
        let (parts, ()) = builder.body(()).unwrap().into_parts();

        CxTestBuilder::new()
            .request_context(parts)
            .request_context(CookieJarCell::new())
            .build()
    }

    /// The leading `name=value` pair of the request's first `Set-Cookie` value.
    fn echoed_pair(cx: &Cx) -> String {
        let mut headers = HeaderMap::new();
        write_cookies(cx, &mut headers);
        let set = headers
            .get(header::SET_COOKIE)
            .unwrap()
            .to_str()
            .unwrap()
            .to_owned();
        set.split(';').next().unwrap().to_owned()
    }

    #[test]
    fn round_trips_through_a_signed_jar() {
        // Proves the store's serialization composes with the jar's layers: write
        // through a signed jar, then read the echoed cookie back through one.
        let key = Key::generate();

        let writer = cx_with(&[]);
        cookie_store::<Cart, _>(cookies(&writer).signed(&key), "cart")
            .set(Cart {
                items: vec!["widget".to_owned()],
            })
            .commit()
            .unwrap();
        let echoed = echoed_pair(&writer);

        let reader = cx_with(&[&echoed]);
        let cart = cookie_store::<Cart, _>(cookies(&reader).signed(&key), "cart")
            .parse()
            .unwrap()
            .expect("the signed cookie should verify and deserialize");

        assert_eq!(cart.read().items, ["widget"]);
    }
}