1#![allow(
23 clippy::missing_panics_doc,
24 reason = "each check panics on a contract violation, documented above"
25)]
26
27use std::net::{IpAddr, Ipv4Addr};
28
29use chrono::{DateTime, TimeDelta, Utc};
30use uuid::Uuid;
31
32use crate::{
33 checks::Check,
34 event::{ClientSummary, EventKind, SessionEvent, SessionOrigin},
35 fingerprint::{Baseline, Fingerprint},
36 intel::Anonymity,
37 store::{ClaimScope, Rotation, SessionRecord, SessionStore, SessionUpdate, Supersede},
38 token::{SessionToken, TokenHash},
39};
40
41#[macro_export]
44macro_rules! store_conformance {
45 ($make:expr) => {
46 $crate::store_conformance!(@tests $make;
47 insert_and_find,
48 unknown_token_is_none,
49 records_round_trip,
50 session_without_origin,
51 exact_rotation_happens_once,
52 concurrent_rotation_has_one_winner,
53 rotation_if_issued_before,
54 current_rotation,
55 newer_token_used_is_tracked,
56 newer_used_tokens_are_listed,
57 mark_used_sets_once,
58 mark_used_reaches_the_rotated_token,
59 none_fields_are_preserved,
60 prune_superseded_tokens,
61 delete_session_removes_tokens,
62 delete_subject_sessions,
63 list_subject_sessions,
64 delete_expired_absolute_and_idle,
65 events_record_and_purge,
66 event_claims_dedupe_within_window,
67 subject_claims_dedupe_within_window,
68 apply_to_missing_session,
69 );
70 };
71 (@tests $make:expr; $($name:ident),* $(,)?) => {
72 $(
73 #[::tokio::test(flavor = "multi_thread")]
74 async fn $name() {
75 $crate::testing::$name(($make)().await).await;
76 }
77 )*
78 };
79}
80
81pub fn now_secs() -> DateTime<Utc> {
83 let now = Utc::now();
84 DateTime::from_timestamp(now.timestamp(), 0).unwrap_or(now)
85}
86
87pub fn random_hash() -> TokenHash {
94 let mut bytes = *SessionToken::generate().expect("OS RNG").hash().as_bytes();
95 bytes[0] = 0;
96 TokenHash::from_bytes(bytes)
97}
98
99fn aligned_session_id() -> Uuid {
101 let mut bytes = *Uuid::new_v4().as_bytes();
102 bytes[15] = 0;
103 Uuid::from_bytes(bytes)
104}
105
106pub fn sample_session(now: DateTime<Utc>) -> SessionRecord {
108 sample_session_for(&format!("\"conformance-{}\"", Uuid::new_v4()), now)
109}
110
111pub fn sample_session_for(subject: &str, now: DateTime<Utc>) -> SessionRecord {
113 SessionRecord {
114 id: aligned_session_id(),
115 subject: subject.to_owned(),
116 created_at: now,
117 authenticated_at: now,
118 last_seen_at: now,
119 expires_at: now + TimeDelta::days(1),
120 step_up_required: false,
121 baseline: Baseline::new(Fingerprint {
122 ip_prefix: "203.0.113.0/24".into(),
123 ..Fingerprint::default()
124 }),
125 origin: Some(SessionOrigin {
126 at: now,
127 ip_prefix: IpAddr::V4(Ipv4Addr::new(203, 0, 113, 0)),
128 ip: None,
129 user_agent: None,
130 client: ClientSummary {
131 country: Some("BE".into()),
132 browser: Some("Firefox".into()),
133 ..ClientSummary::default()
134 },
135 }),
136 }
137}
138
139fn secs(n: i64) -> TimeDelta {
140 TimeDelta::seconds(n)
141}
142
143fn rotation(new_token: TokenHash, supersede: Supersede, prune_before: DateTime<Utc>) -> Rotation {
144 Rotation {
145 new_token,
146 supersede,
147 prune_superseded_before: prune_before,
148 }
149}
150
151fn rotate(id: Uuid, now: DateTime<Utc>, rotation: Rotation) -> SessionUpdate {
152 SessionUpdate {
153 rotation: Some(rotation),
154 ..SessionUpdate::touch(id, now)
155 }
156}
157
158pub async fn insert_and_find<St: SessionStore>(store: St) {
160 let now = now_secs();
161 let session = sample_session(now);
162 let token = random_hash();
163 store.insert_session(&session, &token).await.unwrap();
164
165 let found = store
166 .find_by_token(&token)
167 .await
168 .unwrap()
169 .expect("inserted token is found");
170 assert_eq!(found.session, session);
171 assert_eq!(found.token.hash, token);
172 assert_eq!(found.token.issued_at, now);
173 assert_eq!(found.token.first_used_at, None);
174 assert_eq!(found.token.superseded_at, None);
175 assert!(!found.newer_token_used);
176}
177
178pub async fn unknown_token_is_none<St: SessionStore>(store: St) {
180 assert!(store.find_by_token(&random_hash()).await.unwrap().is_none());
181}
182
183pub async fn records_round_trip<St: SessionStore>(store: St) {
185 let now = now_secs();
186 let mut session = sample_session_for(
187 &format!("{{\"tenant\":\"zürich-🦀\",\"user\":\"{}\"}}", Uuid::new_v4()),
188 now,
189 );
190 session.step_up_required = true;
191 session.authenticated_at = now - secs(30);
192 session.last_seen_at = now - secs(5);
193 session.baseline = Baseline {
194 fingerprint: Fingerprint {
195 ip_prefix: "2001:db8:1::/48".into(),
196 country: Some("BE".into()),
197 asn: Some(64_496),
198 browser: Some("Firefox".into()),
199 browser_major: Some(131),
200 os: Some("Linux".into()),
201 ch_platform: Some("Linux".into()),
202 ch_mobile: Some(false),
203 accept_language: Some("nl-be,nl,en".into()),
204 tls: Some("t13d1516h2_8daaf6152771_02713d6af862".into()),
205 anonymity: Some(Anonymity::Vpn),
206 },
207 previous_ip_prefix: Some("198.51.100.0/24".into()),
208 ip_changed_at: Some(now - secs(60)),
209 ipv4_prefix: Some("192.0.2.0/24".into()),
210 ipv6_prefix: Some("2001:db8:1::/48".into()),
211 };
212 session.origin = Some(SessionOrigin {
213 at: now - secs(30),
214 ip_prefix: "2001:db8:1::".parse().unwrap(),
215 ip: Some("2001:db8:1::7".parse().unwrap()),
216 user_agent: Some("Mozilla/5.0 🦀".into()),
217 client: ClientSummary {
218 country: Some("BE".into()),
219 city: Some("Zürich".into()),
220 asn: Some(64_496),
221 network: Some("Example Net".into()),
222 anonymity: Some(Anonymity::Vpn),
223 browser: Some("Firefox".into()),
224 os: Some("Linux".into()),
225 },
226 });
227 let token = random_hash();
228 store.insert_session(&session, &token).await.unwrap();
229 let found = store.find_by_token(&token).await.unwrap().unwrap();
230 assert_eq!(found.session, session);
231 assert_eq!(
232 store.list_subject_sessions(&session.subject).await.unwrap(),
233 vec![session]
234 );
235}
236
237pub async fn session_without_origin<St: SessionStore>(store: St) {
239 let now = now_secs();
240 let session = SessionRecord {
241 origin: None,
242 ..sample_session(now)
243 };
244 let token = random_hash();
245 store.insert_session(&session, &token).await.unwrap();
246 let found = store.find_by_token(&token).await.unwrap().unwrap();
247 assert_eq!(found.session, session);
248 store
249 .apply(&SessionUpdate::touch(session.id, now + secs(1)))
250 .await
251 .unwrap();
252 let listed = store.list_subject_sessions(&session.subject).await.unwrap();
253 assert_eq!(listed.len(), 1);
254 assert_eq!(listed[0].origin, None);
255}
256
257pub async fn exact_rotation_happens_once<St: SessionStore>(store: St) {
259 let now = now_secs();
260 let session = sample_session(now);
261 let first = random_hash();
262 store.insert_session(&session, &first).await.unwrap();
263
264 let later = now + secs(60);
265 let second = random_hash();
266 let rotated = store
267 .apply(&rotate(
268 session.id,
269 later,
270 rotation(second, Supersede::Exact(first), now),
271 ))
272 .await
273 .unwrap();
274 assert!(rotated);
275
276 let third = random_hash();
277 let again = store
278 .apply(&rotate(
279 session.id,
280 later,
281 rotation(third, Supersede::Exact(first), now),
282 ))
283 .await
284 .unwrap();
285 assert!(!again, "a superseded token must not rotate again");
286 assert!(store.find_by_token(&third).await.unwrap().is_none());
287
288 let old = store.find_by_token(&first).await.unwrap().unwrap();
289 assert_eq!(old.token.superseded_at, Some(later));
290 let new = store.find_by_token(&second).await.unwrap().unwrap();
291 assert_eq!(new.token.issued_at, later);
292 assert_eq!(new.token.superseded_at, None);
293 assert_eq!(new.session.last_seen_at, later);
294}
295
296pub async fn concurrent_rotation_has_one_winner<St: SessionStore>(store: St) {
299 let now = now_secs();
300 let session = sample_session(now);
301 let first = random_hash();
302 store.insert_session(&session, &first).await.unwrap();
303
304 let candidates: Vec<TokenHash> = (0..16).map(|_| random_hash()).collect();
305 let attempts = candidates.iter().map(|&candidate| {
306 let update = rotate(
307 session.id,
308 now + secs(1),
309 rotation(candidate, Supersede::Exact(first), now),
310 );
311 let store = &store;
312 async move { store.apply(&update).await.unwrap() }
313 });
314 let results = join_all(attempts).await;
315 assert_eq!(results.iter().filter(|r| **r).count(), 1, "exactly one rotation wins");
316
317 let mut current = 0;
318 for (candidate, won) in candidates.iter().zip(&results) {
319 let found = store.find_by_token(candidate).await.unwrap();
320 assert_eq!(found.is_some(), *won);
321 if found.is_some_and(|f| f.token.superseded_at.is_none()) {
322 current += 1;
323 }
324 }
325 assert_eq!(current, 1, "exactly one current token");
326}
327
328pub async fn rotation_if_issued_before<St: SessionStore>(store: St) {
330 let now = now_secs();
331 let session = sample_session(now);
332 let first = random_hash();
333 store.insert_session(&session, &first).await.unwrap();
334
335 let too_new = random_hash();
336 let rotated = store
337 .apply(&rotate(
338 session.id,
339 now + secs(5),
340 rotation(too_new, Supersede::CurrentIssuedBefore(now), now),
341 ))
342 .await
343 .unwrap();
344 assert!(!rotated, "issued_at == cutoff is not strictly before");
345 assert!(store.find_by_token(&too_new).await.unwrap().is_none());
346
347 let second = random_hash();
348 let rotated = store
349 .apply(&rotate(
350 session.id,
351 now + secs(5),
352 rotation(second, Supersede::CurrentIssuedBefore(now + secs(1)), now),
353 ))
354 .await
355 .unwrap();
356 assert!(rotated);
357 let old = store.find_by_token(&first).await.unwrap().unwrap();
358 assert_eq!(old.token.superseded_at, Some(now + secs(5)));
359}
360
361pub async fn current_rotation<St: SessionStore>(store: St) {
363 let now = now_secs();
364 let session = sample_session(now);
365 let first = random_hash();
366 store.insert_session(&session, &first).await.unwrap();
367 let second = random_hash();
368 store
369 .apply(&rotate(
370 session.id,
371 now + secs(1),
372 rotation(second, Supersede::Exact(first), now),
373 ))
374 .await
375 .unwrap();
376
377 let third = random_hash();
378 let rotated = store
379 .apply(&rotate(
380 session.id,
381 now + secs(2),
382 rotation(third, Supersede::Current, now),
383 ))
384 .await
385 .unwrap();
386 assert!(rotated);
387 let second_found = store.find_by_token(&second).await.unwrap().unwrap();
388 assert_eq!(second_found.token.superseded_at, Some(now + secs(2)));
389 let third_found = store.find_by_token(&third).await.unwrap().unwrap();
390 assert_eq!(third_found.token.superseded_at, None);
391}
392
393pub async fn newer_token_used_is_tracked<St: SessionStore>(store: St) {
395 let now = now_secs();
396 let session = sample_session(now);
397 let first = random_hash();
398 store.insert_session(&session, &first).await.unwrap();
399 let second = random_hash();
400 store
401 .apply(&rotate(
402 session.id,
403 now + secs(1),
404 rotation(second, Supersede::Exact(first), now),
405 ))
406 .await
407 .unwrap();
408 assert!(!store.find_by_token(&first).await.unwrap().unwrap().newer_token_used);
409
410 store
411 .apply(&SessionUpdate {
412 mark_used: Some(second),
413 ..SessionUpdate::touch(session.id, now + secs(2))
414 })
415 .await
416 .unwrap();
417 assert!(store.find_by_token(&first).await.unwrap().unwrap().newer_token_used);
418 assert!(!store.find_by_token(&second).await.unwrap().unwrap().newer_token_used);
419}
420
421pub async fn newer_used_tokens_are_listed<St: SessionStore>(store: St) {
425 let now = now_secs();
426 let session = sample_session(now);
427 let first = random_hash();
428 store.insert_session(&session, &first).await.unwrap();
429 let Some(listed) = store.newer_used_tokens(&first).await.unwrap() else {
430 return;
431 };
432 assert_eq!(listed, Vec::new());
433 assert_eq!(store.newer_used_tokens(&random_hash()).await.unwrap(), Some(Vec::new()));
434
435 let second = random_hash();
436 let third = random_hash();
437 let fourth = random_hash();
438 for (offset, (old, new)) in [(1, (first, second)), (2, (second, third)), (3, (third, fourth))] {
439 store
440 .apply(&rotate(
441 session.id,
442 now + secs(offset),
443 rotation(new, Supersede::Exact(old), now),
444 ))
445 .await
446 .unwrap();
447 }
448 for (offset, token) in [(4, fourth), (5, second)] {
449 store
450 .apply(&SessionUpdate {
451 mark_used: Some(token),
452 ..SessionUpdate::touch(session.id, now + secs(offset))
453 })
454 .await
455 .unwrap();
456 }
457
458 let listed = store.newer_used_tokens(&first).await.unwrap().unwrap();
459 let summary: Vec<_> = listed
460 .iter()
461 .map(|t| (t.hash, t.issued_at, t.first_used_at, t.superseded_at))
462 .collect();
463 assert_eq!(
464 summary,
465 vec![
466 (second, now + secs(1), Some(now + secs(5)), Some(now + secs(2))),
467 (fourth, now + secs(3), Some(now + secs(4)), None),
468 ]
469 );
470 let listed = store.newer_used_tokens(&third).await.unwrap().unwrap();
471 assert_eq!(listed.iter().map(|t| t.hash).collect::<Vec<_>>(), vec![fourth]);
472 assert_eq!(store.newer_used_tokens(&fourth).await.unwrap(), Some(Vec::new()));
473}
474
475pub async fn newer_used_tokens_are_supported<St: SessionStore>(store: St) {
477 let now = now_secs();
478 let session = sample_session(now);
479 let token = random_hash();
480 store.insert_session(&session, &token).await.unwrap();
481 assert_eq!(store.newer_used_tokens(&token).await.unwrap(), Some(Vec::new()));
482}
483
484pub async fn mark_used_sets_once<St: SessionStore>(store: St) {
486 let now = now_secs();
487 let session = sample_session(now);
488 let token = random_hash();
489 store.insert_session(&session, &token).await.unwrap();
490
491 for offset in [3, 9] {
492 store
493 .apply(&SessionUpdate {
494 mark_used: Some(token),
495 ..SessionUpdate::touch(session.id, now + secs(offset))
496 })
497 .await
498 .unwrap();
499 }
500 let found = store.find_by_token(&token).await.unwrap().unwrap();
501 assert_eq!(found.token.first_used_at, Some(now + secs(3)));
502 assert_eq!(found.session.last_seen_at, now + secs(9));
503}
504
505pub async fn mark_used_reaches_the_rotated_token<St: SessionStore>(store: St) {
507 let now = now_secs();
508 let session = sample_session(now);
509 let first = random_hash();
510 store.insert_session(&session, &first).await.unwrap();
511 let second = random_hash();
512 let rotated = store
513 .apply(&SessionUpdate {
514 mark_used: Some(second),
515 ..rotate(
516 session.id,
517 now + secs(1),
518 rotation(second, Supersede::Exact(first), now),
519 )
520 })
521 .await
522 .unwrap();
523 assert!(rotated);
524 let found = store.find_by_token(&second).await.unwrap().unwrap();
525 assert_eq!(found.token.first_used_at, Some(now + secs(1)));
526 assert!(store.find_by_token(&first).await.unwrap().unwrap().newer_token_used);
527}
528
529pub async fn none_fields_are_preserved<St: SessionStore>(store: St) {
531 let now = now_secs();
532 let session = sample_session(now);
533 let token = random_hash();
534 store.insert_session(&session, &token).await.unwrap();
535
536 let mut baseline = session.baseline.clone();
537 baseline.fingerprint.country = Some("NL".into());
538 store
539 .apply(&SessionUpdate {
540 baseline: Some(baseline.clone()),
541 step_up_required: Some(true),
542 authenticated_at: Some(now + secs(4)),
543 ..SessionUpdate::touch(session.id, now + secs(4))
544 })
545 .await
546 .unwrap();
547 store
548 .apply(&SessionUpdate::touch(session.id, now + secs(8)))
549 .await
550 .unwrap();
551
552 let found = store.find_by_token(&token).await.unwrap().unwrap().session;
553 assert_eq!(found.baseline, baseline);
554 assert!(found.step_up_required);
555 assert_eq!(found.authenticated_at, now + secs(4));
556 assert_eq!(found.last_seen_at, now + secs(8));
557 assert_eq!(found.created_at, session.created_at);
558 assert_eq!(found.expires_at, session.expires_at);
559 assert_eq!(found.subject, session.subject);
560 assert_eq!(found.origin, session.origin);
561
562 store
563 .apply(&SessionUpdate {
564 step_up_required: Some(false),
565 ..SessionUpdate::touch(session.id, now + secs(9))
566 })
567 .await
568 .unwrap();
569 assert!(
570 !store
571 .find_by_token(&token)
572 .await
573 .unwrap()
574 .unwrap()
575 .session
576 .step_up_required
577 );
578}
579
580pub async fn prune_superseded_tokens<St: SessionStore>(store: St) {
582 let now = now_secs();
583 let session = sample_session(now);
584 let t1 = random_hash();
585 store.insert_session(&session, &t1).await.unwrap();
586 let t2 = random_hash();
587 store
588 .apply(&rotate(
589 session.id,
590 now + secs(10),
591 rotation(t2, Supersede::Exact(t1), now),
592 ))
593 .await
594 .unwrap();
595 let t3 = random_hash();
596 store
597 .apply(&rotate(
598 session.id,
599 now + secs(20),
600 rotation(t3, Supersede::Exact(t2), now),
601 ))
602 .await
603 .unwrap();
604
605 let t4 = random_hash();
607 store
608 .apply(&rotate(
609 session.id,
610 now + secs(30),
611 rotation(t4, Supersede::Exact(t3), now + secs(15)),
612 ))
613 .await
614 .unwrap();
615 assert!(
616 store.find_by_token(&t1).await.unwrap().is_none(),
617 "superseded before cutoff is pruned"
618 );
619 assert!(store.find_by_token(&t2).await.unwrap().is_some());
620 assert!(store.find_by_token(&t3).await.unwrap().is_some());
621 assert!(store.find_by_token(&t4).await.unwrap().is_some());
622}
623
624pub async fn delete_session_removes_tokens<St: SessionStore>(store: St) {
626 let now = now_secs();
627 let session = sample_session(now);
628 let t1 = random_hash();
629 store.insert_session(&session, &t1).await.unwrap();
630 let t2 = random_hash();
631 store
632 .apply(&rotate(
633 session.id,
634 now + secs(1),
635 rotation(t2, Supersede::Exact(t1), now),
636 ))
637 .await
638 .unwrap();
639
640 assert!(store.delete_session(session.id).await.unwrap());
641 assert!(!store.delete_session(session.id).await.unwrap());
642 assert!(store.find_by_token(&t1).await.unwrap().is_none());
643 assert!(store.find_by_token(&t2).await.unwrap().is_none());
644}
645
646pub async fn delete_subject_sessions<St: SessionStore>(store: St) {
648 let now = now_secs();
649 let subject = format!("\"conformance-{}\"", Uuid::new_v4());
650 let mut tokens = Vec::new();
651 let mut ids = Vec::new();
652 for _ in 0..3 {
653 let token = random_hash();
654 let session = sample_session_for(&subject, now);
655 store.insert_session(&session, &token).await.unwrap();
656 tokens.push(token);
657 ids.push(session.id);
658 }
659 let other = random_hash();
660 store.insert_session(&sample_session(now), &other).await.unwrap();
661
662 let mut deleted = store.delete_subject_sessions(&subject).await.unwrap();
663 deleted.sort();
664 ids.sort();
665 assert_eq!(deleted, ids);
666 assert_eq!(
667 store.delete_subject_sessions(&subject).await.unwrap(),
668 Vec::<Uuid>::new()
669 );
670 for token in &tokens {
671 assert!(store.find_by_token(token).await.unwrap().is_none());
672 }
673 assert!(store.find_by_token(&other).await.unwrap().is_some());
674}
675
676pub async fn list_subject_sessions<St: SessionStore>(store: St) {
678 let now = now_secs();
679 let subject = format!("\"conformance-{}\"", Uuid::new_v4());
680 let a = sample_session_for(&subject, now);
681 let b = sample_session_for(&subject, now - secs(60));
682 store.insert_session(&a, &random_hash()).await.unwrap();
683 store.insert_session(&b, &random_hash()).await.unwrap();
684 store
685 .insert_session(&sample_session(now), &random_hash())
686 .await
687 .unwrap();
688
689 let mut listed = store.list_subject_sessions(&subject).await.unwrap();
690 listed.sort_by_key(|s| s.created_at);
691 assert_eq!(listed, vec![b, a]);
692 assert_eq!(store.list_subject_sessions("\"nobody\"").await.unwrap(), vec![]);
693}
694
695pub async fn delete_expired_absolute_and_idle<St: SessionStore>(store: St) {
697 let base = far_past();
702 let later = Utc::now() + TimeDelta::days(1);
703 let mut expired = sample_session(base);
704 expired.expires_at = base;
705 let mut idle = sample_session(base);
706 idle.last_seen_at = base - secs(100);
707 idle.expires_at = later;
708 let mut live = sample_session(base);
709 live.expires_at = later;
710 live.last_seen_at = base - secs(99);
711
712 let (te, ti, tl) = (random_hash(), random_hash(), random_hash());
713 store.insert_session(&expired, &te).await.unwrap();
714 store.insert_session(&idle, &ti).await.unwrap();
715 store.insert_session(&live, &tl).await.unwrap();
716
717 let deleted = store.delete_expired(base, base - secs(100)).await.unwrap();
718 assert!(deleted >= 1);
719 assert!(store.find_by_token(&te).await.unwrap().is_none());
720 assert!(store.find_by_token(&ti).await.unwrap().is_none());
721 assert!(store.find_by_token(&tl).await.unwrap().is_some());
722 store.delete_session(live.id).await.unwrap();
723}
724
725pub async fn events_record_and_purge<St: SessionStore>(store: St) {
727 let at = far_past();
728 let event = SessionEvent {
729 session_id: Uuid::new_v4(),
730 subject: "\"conformance\"".into(),
731 kind: EventKind::RiskRevoked,
732 enforced: false,
733 score: Some(95),
734 signals: vec![Check::OsChanged, Check::CountryChanged],
735 ip: IpAddr::V4(Ipv4Addr::new(203, 0, 113, 0)),
736 user_agent: Some("Mozilla/5.0 🦀".into()),
737 client: ClientSummary {
738 country: Some("BE".into()),
739 asn: Some(64500),
740 browser: Some("Firefox".into()),
741 ..ClientSummary::default()
742 },
743 at,
744 };
745 store.record_event(&event).await.unwrap();
746 store
747 .record_event(&SessionEvent {
748 user_agent: None,
749 score: None,
750 signals: vec![],
751 client: ClientSummary::default(),
752 ..event.clone()
753 })
754 .await
755 .unwrap();
756 store.delete_events_before(at).await.unwrap();
757 assert!(store.delete_events_before(at + secs(1)).await.unwrap() >= 2);
758}
759
760pub async fn event_claims_dedupe_within_window<St: SessionStore>(store: St) {
762 let now = now_secs();
763 let window = secs(600);
764 let session = Uuid::new_v4();
765 let claim = |kind, at| store.claim_event(ClaimScope::Session(session), kind, at, window);
766 assert!(claim(EventKind::RiskRevoked, now).await.unwrap());
767 assert!(!claim(EventKind::RiskRevoked, now + secs(1)).await.unwrap());
768 assert!(!claim(EventKind::RiskRevoked, now + secs(599)).await.unwrap());
769 assert!(
770 claim(EventKind::StepUpRequired, now).await.unwrap(),
771 "kinds are independent"
772 );
773 assert!(
774 store
775 .claim_event(ClaimScope::Session(Uuid::new_v4()), EventKind::RiskRevoked, now, window)
776 .await
777 .unwrap(),
778 "sessions are independent"
779 );
780 assert!(
781 claim(EventKind::RiskRevoked, now + secs(600)).await.unwrap(),
782 "the window elapsed"
783 );
784 assert!(
785 !claim(EventKind::RiskRevoked, now + secs(601)).await.unwrap(),
786 "the new claim holds"
787 );
788}
789
790pub async fn subject_claims_dedupe_within_window<St: SessionStore>(store: St) {
793 let now = now_secs();
794 let window = secs(600);
795 let subject = format!("\"conformance-{}\"", Uuid::new_v4());
796 let claim = |kind, at| store.claim_event(ClaimScope::Subject(&subject), kind, at, window);
797 assert!(claim(EventKind::RiskRevoked, now).await.unwrap());
798 assert!(!claim(EventKind::RiskRevoked, now + secs(1)).await.unwrap());
799 assert!(!claim(EventKind::RiskRevoked, now + secs(599)).await.unwrap());
800 assert!(
801 claim(EventKind::TokenReuse, now).await.unwrap(),
802 "kinds are independent"
803 );
804 let other = format!("\"conformance-{}\"", Uuid::new_v4());
805 assert!(
806 store
807 .claim_event(ClaimScope::Subject(&other), EventKind::RiskRevoked, now, window)
808 .await
809 .unwrap(),
810 "subjects are independent"
811 );
812 let session = Uuid::new_v4();
813 let session_claim = |at| store.claim_event(ClaimScope::Session(session), EventKind::RiskRevoked, at, window);
814 assert!(session_claim(now).await.unwrap(), "session claims are independent");
815 assert!(!session_claim(now + secs(1)).await.unwrap());
816 assert!(
817 claim(EventKind::RiskRevoked, now + secs(600)).await.unwrap(),
818 "the window elapsed"
819 );
820 assert!(
821 !claim(EventKind::RiskRevoked, now + secs(601)).await.unwrap(),
822 "the new claim holds"
823 );
824
825 let at = far_past();
826 let old = format!("\"conformance-{}\"", Uuid::new_v4());
827 let claim_old = |at| store.claim_event(ClaimScope::Subject(&old), EventKind::RiskRevoked, at, window);
828 assert!(claim_old(at).await.unwrap());
829 assert!(!claim_old(at + secs(2)).await.unwrap());
830 store.delete_events_before(at + secs(1)).await.unwrap();
831 assert!(claim_old(at + secs(2)).await.unwrap(), "the purge removed the claim");
832}
833
834pub async fn apply_to_missing_session<St: SessionStore>(store: St) {
836 let now = now_secs();
837 let update = rotate(
838 aligned_session_id(),
839 now,
840 rotation(random_hash(), Supersede::Current, now),
841 );
842 assert!(!store.apply(&update).await.unwrap());
843}
844
845fn far_past() -> DateTime<Utc> {
847 let bytes = Uuid::new_v4().into_bytes();
848 let minutes = i64::from(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], 0]));
849 DateTime::from_timestamp(-2_208_988_800 + minutes * 60, 0).unwrap_or_default()
850}
851
852async fn join_all<F: std::future::Future>(futures: impl IntoIterator<Item = F>) -> Vec<F::Output> {
854 use std::{
855 pin::Pin,
856 task::{Context, Poll},
857 };
858
859 struct JoinAll<F: std::future::Future> {
860 futures: Vec<Option<Pin<Box<F>>>>,
861 outputs: Vec<Option<F::Output>>,
862 }
863
864 impl<F: std::future::Future> Unpin for JoinAll<F> {}
866
867 impl<F: std::future::Future> std::future::Future for JoinAll<F> {
868 type Output = Vec<F::Output>;
869
870 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
871 let this = self.get_mut();
872 let mut pending = false;
873 for (slot, out) in this.futures.iter_mut().zip(this.outputs.iter_mut()) {
874 if let Some(fut) = slot {
875 match fut.as_mut().poll(cx) {
876 Poll::Ready(v) => {
877 *out = Some(v);
878 *slot = None;
879 }
880 Poll::Pending => pending = true,
881 }
882 }
883 }
884 if pending {
885 Poll::Pending
886 } else {
887 Poll::Ready(this.outputs.iter_mut().filter_map(Option::take).collect())
888 }
889 }
890 }
891
892 let futures: Vec<_> = futures.into_iter().map(|f| Some(Box::pin(f))).collect();
893 let outputs = futures.iter().map(|_| None).collect();
894 JoinAll { futures, outputs }.await
895}