typed-session 0.9.0

Async typed session middleware
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
use chrono::{Duration, Utc};
use std::collections::BTreeSet;
use typed_session::{
    DebugSessionCookieGenerator, Error, MemoryStore, Operation, Session, SessionCookieCommand,
    SessionCookieGenerator, SessionExpiry, SessionId, SessionRenewalStrategy, SessionStore,
};

/// If a new session is created but never mutated, then no cookie is set and the session is not stored in the session store.
#[async_std::test]
async fn test_dont_store_default_session() {
    let mut connection = MemoryStore::new_with_logger();
    let store: SessionStore<(), _, _> = SessionStore::new_with_cookie_generator(
        DebugSessionCookieGenerator::default(),
        SessionRenewalStrategy::Ignore,
    );
    let session = Session::new();
    matches!(
        store.store_session(session, &mut connection).await.unwrap(),
        SessionCookieCommand::DoNothing
    );
    assert_eq!(connection.into_logger().into_inner().as_slice(), &[]);
}

/// If a new session is created but only its expiry is mutated and not its data, then no cookie is set and the session is not stored in the session store.
#[async_std::test]
async fn test_dont_store_default_session_with_expiry_change() {
    let mut connection = MemoryStore::new_with_logger();
    let store: SessionStore<(), _, _> = SessionStore::new_with_cookie_generator(
        DebugSessionCookieGenerator::default(),
        SessionRenewalStrategy::Ignore,
    );
    let mut session = Session::new();
    session.set_expiry(Utc::now() + Duration::days(1));

    matches!(
        store.store_session(session, &mut connection).await.unwrap(),
        SessionCookieCommand::DoNothing
    );
    assert_eq!(connection.into_logger().into_inner().as_slice(), &[]);
}

/// If a new session is created and mutated, then a cookie is set and the session is stored in the session store.
#[async_std::test]
async fn test_store_updated_default_session() {
    let mut connection = MemoryStore::new_with_logger();
    let cookie_generator = DebugSessionCookieGenerator::default();
    let cookie_0 = cookie_generator.generate_cookie();

    let store: SessionStore<i32, _, _> = SessionStore::new_with_cookie_generator(
        DebugSessionCookieGenerator::default(),
        SessionRenewalStrategy::Ignore,
    );
    let mut session = Session::new();
    *session.data_mut() = 1;
    let SessionCookieCommand::Set {
        expiry: SessionExpiry::Never,
        cookie_value,
    } = store.store_session(session, &mut connection).await.unwrap()
    else {
        panic!()
    };
    assert_eq!(cookie_value, cookie_0);
    // Also check if memory store works correctly here. That is not the main thing we test, but why not.
    let mut data_expiry_pairs = BTreeSet::new();
    connection.for_each(|session| {
        data_expiry_pairs.insert(session.into_data_expiry_pair());
    });
    assert_eq!(
        data_expiry_pairs,
        BTreeSet::from([(Some(1), Some(SessionExpiry::Never))])
    );
    assert_eq!(
        connection.into_logger().into_inner().as_slice(),
        &[Operation::CreateSession {
            id: SessionId::from_cookie_value(&cookie_0),
            expiry: SessionExpiry::Never,
            data: 1,
        }]
    );
}

/// If a session is loaded from the store and stored without change, then the cookie is not updated and the session is not updated in the session store.
#[async_std::test]
async fn test_dont_update_unchanged_session() {
    let mut connection = MemoryStore::new_with_logger();
    let cookie_generator = DebugSessionCookieGenerator::default();
    let cookie_0 = cookie_generator.generate_cookie();

    let store: SessionStore<i32, _, _> = SessionStore::new_with_cookie_generator(
        DebugSessionCookieGenerator::default(),
        SessionRenewalStrategy::Ignore,
    );
    let mut session = Session::new();
    *session.data_mut() = 1;
    let SessionCookieCommand::Set {
        cookie_value,
        expiry: SessionExpiry::Never,
    } = store.store_session(session, &mut connection).await.unwrap()
    else {
        panic!()
    };
    assert_eq!(cookie_value, cookie_0);
    let session = store
        .load_session(cookie_value, &mut connection)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(
        store.store_session(session, &mut connection).await.unwrap(),
        SessionCookieCommand::DoNothing
    );
    assert_eq!(
        connection.into_logger().into_inner().as_slice(),
        &[
            Operation::CreateSession {
                id: SessionId::from_cookie_value(&cookie_0),
                expiry: SessionExpiry::Never,
                data: 1,
            },
            Operation::ReadSession {
                id: SessionId::from_cookie_value(&cookie_0)
            }
        ]
    );
}

/// If a session is loaded from the store and stored with change, then the cookie is updated and the session is updated in the session store.
#[async_std::test]
async fn test_update_changed_session() {
    let mut connection = MemoryStore::new_with_logger();
    let cookie_generator = DebugSessionCookieGenerator::default();
    let cookie_0 = cookie_generator.generate_cookie();
    let cookie_1 = cookie_generator.generate_cookie();
    let store: SessionStore<i32, _, _> = SessionStore::new_with_cookie_generator(
        DebugSessionCookieGenerator::default(),
        SessionRenewalStrategy::Ignore,
    );
    let mut session = Session::new();
    *session.data_mut() = 1;
    let SessionCookieCommand::Set {
        cookie_value,
        expiry: SessionExpiry::Never,
    } = store.store_session(session, &mut connection).await.unwrap()
    else {
        panic!()
    };
    assert_eq!(cookie_value, cookie_0);
    let mut session = store
        .load_session(cookie_value, &mut connection)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(*session.data(), 1);
    *session.data_mut() = 2;
    assert_eq!(
        store.store_session(session, &mut connection).await.unwrap(),
        SessionCookieCommand::Set {
            cookie_value: cookie_1.clone(),
            expiry: SessionExpiry::Never
        }
    );
    assert_eq!(
        connection.into_logger().into_inner().as_slice(),
        &[
            Operation::CreateSession {
                id: SessionId::from_cookie_value(&cookie_0),
                expiry: SessionExpiry::Never,
                data: 1,
            },
            Operation::ReadSession {
                id: SessionId::from_cookie_value(&cookie_0)
            },
            Operation::UpdateSession {
                current_id: SessionId::from_cookie_value(&cookie_1),
                previous_id: SessionId::from_cookie_value(&cookie_0),
                expiry: SessionExpiry::Never,
                data: 2,
            }
        ]
    );
}

/// If a session is deleted, then the cookie is deleted and the session is deleted from the session store.
#[async_std::test]
async fn test_delete_deleted_session() {
    let mut connection = MemoryStore::new_with_logger();
    let cookie_generator = DebugSessionCookieGenerator::default();
    let cookie_0 = cookie_generator.generate_cookie();
    let store: SessionStore<i32, _, _> = SessionStore::new_with_cookie_generator(
        DebugSessionCookieGenerator::default(),
        SessionRenewalStrategy::Ignore,
    );
    let mut session = Session::new();
    *session.data_mut() = 1;
    let SessionCookieCommand::Set {
        cookie_value,
        expiry: SessionExpiry::Never,
    } = store.store_session(session, &mut connection).await.unwrap()
    else {
        panic!()
    };
    assert_eq!(cookie_value, cookie_0);
    let mut session = store
        .load_session(cookie_value, &mut connection)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(*session.data(), 1);
    session.delete();
    assert_eq!(
        store.store_session(session, &mut connection).await.unwrap(),
        SessionCookieCommand::Delete,
    );
    assert_eq!(
        connection.into_logger().into_inner().as_slice(),
        &[
            Operation::CreateSession {
                id: SessionId::from_cookie_value(&cookie_0),
                expiry: SessionExpiry::Never,
                data: 1,
            },
            Operation::ReadSession {
                id: SessionId::from_cookie_value(&cookie_0)
            },
            Operation::DeleteSession {
                current_id: SessionId::from_cookie_value(&cookie_0),
            }
        ]
    );
}

/// If a session is changed, the old session id becomes invalid.
#[async_std::test]
async fn test_prevent_using_old_session_id() {
    let mut connection = MemoryStore::new_with_logger();
    let cookie_generator = DebugSessionCookieGenerator::default();
    let cookie_0 = cookie_generator.generate_cookie();
    let cookie_1 = cookie_generator.generate_cookie();
    // true represents being logged in
    let store: SessionStore<bool, _, _> = SessionStore::new_with_cookie_generator(
        DebugSessionCookieGenerator::default(),
        SessionRenewalStrategy::Ignore,
    );
    let mut session = Session::new();
    *session.data_mut() = false;
    let SessionCookieCommand::Set {
        cookie_value,
        expiry: SessionExpiry::Never,
    } = store.store_session(session, &mut connection).await.unwrap()
    else {
        panic!()
    };
    assert_eq!(cookie_value, cookie_0);
    let mut session = store
        .load_session(cookie_value, &mut connection)
        .await
        .unwrap()
        .unwrap();
    assert!(!*session.data());
    *session.data_mut() = true;
    assert_eq!(
        store.store_session(session, &mut connection).await.unwrap(),
        SessionCookieCommand::Set {
            cookie_value: cookie_1.clone(),
            expiry: SessionExpiry::Never
        }
    );

    // Check if we can upgrade the old session.
    assert!(store
        .load_session(&cookie_0, &mut connection)
        .await
        .unwrap()
        .is_none());

    assert_eq!(
        connection.into_logger().into_inner().as_slice(),
        &[
            Operation::CreateSession {
                id: SessionId::from_cookie_value(&cookie_0),
                expiry: SessionExpiry::Never,
                data: false,
            },
            Operation::ReadSession {
                id: SessionId::from_cookie_value(&cookie_0)
            },
            Operation::UpdateSession {
                current_id: SessionId::from_cookie_value(&cookie_1),
                previous_id: SessionId::from_cookie_value(&cookie_0),
                expiry: SessionExpiry::Never,
                data: true,
            },
            Operation::ReadSession {
                id: SessionId::from_cookie_value(&cookie_0)
            },
        ]
    );
}

/// If a session is changed concurrently, then only the first modification is successful.
#[async_std::test]
async fn test_concurrent_modification() {
    let mut connection = MemoryStore::new_with_logger();
    let cookie_generator = DebugSessionCookieGenerator::default();
    let cookie_0 = cookie_generator.generate_cookie();
    let cookie_1 = cookie_generator.generate_cookie();
    let cookie_2 = cookie_generator.generate_cookie();
    let store: SessionStore<i32, _, _> = SessionStore::new_with_cookie_generator(
        DebugSessionCookieGenerator::default(),
        SessionRenewalStrategy::Ignore,
    );
    let mut session = Session::new();
    *session.data_mut() = 1;
    let SessionCookieCommand::Set {
        cookie_value,
        expiry: SessionExpiry::Never,
    } = store.store_session(session, &mut connection).await.unwrap()
    else {
        panic!()
    };
    assert_eq!(cookie_value, cookie_0);
    let mut session1 = store
        .load_session(&cookie_value, &mut connection)
        .await
        .unwrap()
        .unwrap();
    let mut session2 = store
        .load_session(&cookie_value, &mut connection)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(*session1.data(), 1);
    assert_eq!(*session2.data(), 1);
    *session1.data_mut() = 2;
    *session2.data_mut() = 3;
    assert_eq!(
        store
            .store_session(session1, &mut connection)
            .await
            .unwrap(),
        SessionCookieCommand::Set {
            cookie_value: cookie_1.clone(),
            expiry: SessionExpiry::Never
        }
    );
    let actual = store.store_session(session2, &mut connection).await;
    assert!(
        matches!(actual, Err(Error::UpdatedSessionDoesNotExist)),
        "{actual:?}",
    );

    // Check if we can upgrade the old session.
    assert!(store
        .load_session(&cookie_0, &mut connection)
        .await
        .unwrap()
        .is_none());

    let actual = connection.into_logger().into_inner();
    let actual = actual.as_slice();
    let expected = &[
        Operation::CreateSession {
            id: SessionId::from_cookie_value(&cookie_0),
            expiry: SessionExpiry::Never,
            data: 1,
        },
        Operation::ReadSession {
            id: SessionId::from_cookie_value(&cookie_0),
        },
        Operation::ReadSession {
            id: SessionId::from_cookie_value(&cookie_0),
        },
        Operation::UpdateSession {
            current_id: SessionId::from_cookie_value(&cookie_1),
            previous_id: SessionId::from_cookie_value(&cookie_0),
            expiry: SessionExpiry::Never,
            data: 2,
        },
        Operation::UpdateSession {
            current_id: SessionId::from_cookie_value(&cookie_2),
            previous_id: SessionId::from_cookie_value(&cookie_0),
            expiry: SessionExpiry::Never,
            data: 3,
        },
        Operation::ReadSession {
            id: SessionId::from_cookie_value(&cookie_0),
        },
    ];
    assert_eq!(actual, expected, "{actual:#?}\n!=\n{expected:#?}",);
}

/// Ensure that creating a session store with default parameters results in long enough session tokens.
#[async_std::test]
async fn test_default_cookie_length() {
    let mut connection = MemoryStore::new_with_logger();
    let session_store: SessionStore<bool, _, _> = SessionStore::new(SessionRenewalStrategy::Ignore);
    let mut session = Session::new();
    *session.data_mut() = true;
    if let SessionCookieCommand::Set { cookie_value, .. } = session_store
        .store_session(session, &mut connection)
        .await
        .unwrap()
    {
        assert!(cookie_value.len() >= 32);
    } else {
        panic!("Unexpected session cookie command.");
    }
}

/// Ensure that the expiry of sessions that expire automatically is set correctly.
#[async_std::test]
async fn test_automatic_setting_of_session_expiry() {
    let mut connection = MemoryStore::new_with_logger();
    let ttl = Duration::hours(24);
    let mut session_store: SessionStore<bool, _, _> =
        SessionStore::new(SessionRenewalStrategy::AutomaticRenewal {
            time_to_live: ttl,
            maximum_remaining_time_to_live_for_renewal: Duration::hours(12),
        });
    let mut session = Session::new();
    *session.data_mut() = true;

    let now = Utc::now();
    let now_lower = now - Duration::minutes(1);
    let now_upper = now + Duration::minutes(1);

    if let SessionCookieCommand::Set { expiry, .. } = session_store
        .store_session(session, &mut connection)
        .await
        .unwrap()
    {
        if let SessionExpiry::DateTime(expiry) = expiry {
            assert!(expiry >= now_lower + ttl && expiry <= now_upper + ttl);
        } else {
            panic!("Expiry not set");
        }
    } else {
        panic!("Unexpected session cookie command.");
    }

    let ttl = Duration::hours(12);
    *session_store.session_renewal_strategy_mut() = SessionRenewalStrategy::AutomaticRenewal {
        time_to_live: ttl,
        maximum_remaining_time_to_live_for_renewal: Duration::hours(6),
    };
    let mut session = Session::new();
    *session.data_mut() = true;

    let now = Utc::now();
    let now_lower = now - Duration::minutes(1);
    let now_upper = now + Duration::minutes(1);

    if let SessionCookieCommand::Set { expiry, .. } = session_store
        .store_session(session, &mut connection)
        .await
        .unwrap()
    {
        if let SessionExpiry::DateTime(expiry) = expiry {
            assert!(expiry >= now_lower + ttl && expiry <= now_upper + ttl);
        } else {
            panic!("Expiry not set");
        }
    } else {
        panic!("Unexpected session cookie command.");
    }
}