pas-external 0.7.0

Ppoppo Accounts System (PAS) external SDK — OAuth2 PKCE, JWT verification port, Axum middleware, session liveness
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! S-L6 boundary tests for `SessionValidator::validate` (the async
//! integration tier above the sync `SvCore` state machine in
//! `src/middleware/sv/core_tests.rs`).
//!
//! Pins the S-L6 fail-CLOSED invariant: every PasFailure variant
//! (Rejected / ServerError / Transport) yields `Expired`; every
//! cipher decrypt failure yields `Expired`; access-token anomaly
//! (post-Phase-10.13.B: `sv` claim missing from the just-issued
//! access_token on a Human session) yields `Expired`; update_sv DB
//! failure yields `Expired` *without* updating the cache (so cache +
//! store cannot diverge); ciphertext-lookup DB failure yields
//! `Expired`; mid-refresh logout race yields `Expired` after update_sv
//! + record have already landed; happy-path returns `Authenticated`
//! with the new sv.

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented)]

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use async_trait::async_trait;
use axum_extra::extract::PrivateCookieJar;
use axum_extra::extract::cookie::{Cookie, Key};
use base64::{Engine, engine::general_purpose::STANDARD};
use pas_external::middleware::{
    NewSession, SessionResolution, SessionResolver, SessionStore, SvAware, SessionValidator,
    SvCachePort,
};
use pas_external::oauth::TokenResponse;
use pas_external::pas_port::{MemoryPasAuth, PasFailure};
use pas_external::session_liveness::{EncryptedRefreshToken, TokenCipher};
use pas_external::types::SessionId;

// ── Fakes ────────────────────────────────────────────────────────

#[derive(Debug, thiserror::Error)]
#[error("fake error: {0}")]
struct FakeError(String);

#[derive(Clone, Debug)]
struct FakeAuthContext {
    ppnum_id: String,
    sv: Option<i64>,
}

impl SvAware for FakeAuthContext {
    fn ppnum_id(&self) -> &str {
        &self.ppnum_id
    }
    fn sv(&self) -> Option<i64> {
        self.sv
    }
}

#[derive(Default)]
struct FakeStore {
    contexts: Mutex<HashMap<String, FakeAuthContext>>,
    ciphertexts: Mutex<HashMap<String, EncryptedRefreshToken>>,
    update_sv_should_fail: Mutex<bool>,
    update_sv_calls: Mutex<u32>,
    ciphertext_lookup_should_fail: Mutex<bool>,
    /// When true, the *second* (and later) call to `find()` returns
    /// `Ok(None)` — simulates a logout race between `update_sv` and the
    /// post-refresh re-fetch.
    drop_session_on_refetch: Mutex<bool>,
    find_calls: Mutex<u32>,
}

impl FakeStore {
    fn put(&self, id: &str, ctx: FakeAuthContext) {
        self.contexts.lock().unwrap().insert(id.to_string(), ctx);
    }
    fn put_ciphertext(&self, id: &str, ct: EncryptedRefreshToken) {
        self.ciphertexts.lock().unwrap().insert(id.to_string(), ct);
    }
    fn fail_update_sv(&self) {
        *self.update_sv_should_fail.lock().unwrap() = true;
    }
    fn fail_ciphertext_lookup(&self) {
        *self.ciphertext_lookup_should_fail.lock().unwrap() = true;
    }
    fn drop_session_on_refetch(&self) {
        *self.drop_session_on_refetch.lock().unwrap() = true;
    }
    fn update_sv_call_count(&self) -> u32 {
        *self.update_sv_calls.lock().unwrap()
    }
}

impl SessionStore for FakeStore {
    type Error = FakeError;
    type AuthContext = FakeAuthContext;

    async fn create(&self, _session: NewSession) -> Result<SessionId, FakeError> {
        unimplemented!("not used by these tests")
    }

    async fn find(&self, id: &SessionId) -> Result<Option<FakeAuthContext>, FakeError> {
        let mut calls = self.find_calls.lock().unwrap();
        *calls += 1;
        let n = *calls;
        drop(calls);
        if n >= 2 && *self.drop_session_on_refetch.lock().unwrap() {
            return Ok(None);
        }
        Ok(self.contexts.lock().unwrap().get(&id.0).cloned())
    }

    async fn delete(&self, _id: &SessionId) -> Result<(), FakeError> {
        Ok(())
    }

    async fn update_sv(&self, id: &SessionId, new_sv: i64) -> Result<(), FakeError> {
        *self.update_sv_calls.lock().unwrap() += 1;
        if *self.update_sv_should_fail.lock().unwrap() {
            return Err(FakeError("update_sv DB failure".into()));
        }
        let mut inner = self.contexts.lock().unwrap();
        if let Some(ctx) = inner.get_mut(&id.0) {
            ctx.sv = Some(new_sv);
        }
        Ok(())
    }

    async fn get_refresh_ciphertext(
        &self,
        id: &SessionId,
    ) -> Result<Option<EncryptedRefreshToken>, FakeError> {
        if *self.ciphertext_lookup_should_fail.lock().unwrap() {
            return Err(FakeError("ciphertext lookup DB failure".into()));
        }
        Ok(self.ciphertexts.lock().unwrap().get(&id.0).cloned())
    }
}

// Cheap-Clone wrapper (Arc-shared inner state) so tests can hand one
// handle to the policy and keep a second for assertions — same pattern
// as a real Redis client.
#[derive(Clone, Default)]
struct FakeBackend {
    inner: Arc<FakeBackendInner>,
}

#[derive(Default)]
struct FakeBackendInner {
    map: Mutex<HashMap<String, i64>>,
    store_calls: Mutex<u32>,
    last_ttl: Mutex<Option<Duration>>,
}

impl FakeBackend {
    fn store_call_count(&self) -> u32 {
        *self.inner.store_calls.lock().unwrap()
    }
    fn last_ttl(&self) -> Option<Duration> {
        *self.inner.last_ttl.lock().unwrap()
    }
}

#[async_trait]
impl SvCachePort for FakeBackend {
    async fn load(&self, key: &str) -> Option<i64> {
        self.inner.map.lock().unwrap().get(key).copied()
    }
    async fn store(&self, key: &str, sv: i64, ttl: Duration) {
        *self.inner.store_calls.lock().unwrap() += 1;
        *self.inner.last_ttl.lock().unwrap() = Some(ttl);
        self.inner.map.lock().unwrap().insert(key.to_string(), sv);
    }
}

// ── Test wiring helpers ──────────────────────────────────────────

const COOKIE_NAME: &str = "test_session";
const SESSION_ID: &str = "01HXYZTESTSESSION0000000000";
const PPNUM_ID: &str = "01HXYZPPPN00000000000000PP";
const PLAINTEXT_RT: &str = "rt_plain_xyz";

fn cipher() -> TokenCipher {
    let key_b64 = STANDARD.encode([0u8; 32]);
    TokenCipher::from_base64_key(&key_b64).unwrap()
}

fn other_cipher() -> TokenCipher {
    // Different key — ciphertext under cipher() will fail to decrypt here.
    let mut key = [0u8; 32];
    key[0] = 1;
    let key_b64 = STANDARD.encode(key);
    TokenCipher::from_base64_key(&key_b64).unwrap()
}

fn jar_with_session() -> PrivateCookieJar {
    let key = Key::generate();
    let mut jar = PrivateCookieJar::new(key);
    jar = jar.add(Cookie::new(COOKIE_NAME, SESSION_ID));
    jar
}

/// Build a JWS-Compact-shaped access_token whose payload carries the
/// requested `sv` claim (or no `sv` at all when `sv` is `None`). The
/// adapter trust-extracts `sv` *without* signature verification, so a
/// synthetic token with arbitrary header / signature segments suffices.
///
/// Header: `{"alg":"none"}` (read but not validated by `peek_session_version`).
/// Payload: `{"sv": <value>}` or `{}`.
/// Signature: literal `"sig"` placeholder.
fn token_response_with_sv(sv: Option<i64>) -> TokenResponse {
    use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
    let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"none"}"#);
    let payload_json = match sv {
        Some(v) => serde_json::json!({ "sv": v }),
        None => serde_json::json!({}),
    };
    let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload_json).unwrap());
    let access_token = format!("{header}.{payload}.sig");
    let body = serde_json::json!({
        "access_token": access_token,
        "token_type": "Bearer",
        "expires_in": 3600,
        "refresh_token": null,
    });
    serde_json::from_value(body).unwrap()
}

/// Standard test wiring: store with one session @ sv=1, ciphertext keyed
/// by `cipher`, cache empty (forces refresh path).
fn standard_setup(cipher_for_ct: &TokenCipher) -> Arc<FakeStore> {
    let store = Arc::new(FakeStore::default());
    store.put(
        SESSION_ID,
        FakeAuthContext {
            ppnum_id: PPNUM_ID.into(),
            sv: Some(1),
        },
    );
    store.put_ciphertext(
        SESSION_ID,
        cipher_for_ct.encrypt_to_token(PLAINTEXT_RT).unwrap(),
    );
    store
}

fn build_resolver(
    store: Arc<FakeStore>,
    backend: FakeBackend,
    pas: Arc<MemoryPasAuth>,
    cipher: Option<Arc<TokenCipher>>,
) -> SessionValidator<FakeStore, MemoryPasAuth, FakeBackend> {
    let cookie_name: Arc<str> = Arc::from(COOKIE_NAME);
    let base = SessionResolver::new(Arc::clone(&store), cookie_name);
    SessionValidator::new(base, store, pas, Arc::new(backend), cipher)
}

// ── Tests ────────────────────────────────────────────────────────

#[tokio::test]
async fn sv_cipher_failure_yields_expired() {
    // Ciphertext stored under cipher A; resolver configured with cipher B.
    // pas_refresh returns Err(CipherFailure). S-L6: Expired, no PAS call.
    let cipher_for_ct = cipher();
    let cipher_for_resolver = other_cipher();
    let store = standard_setup(&cipher_for_ct);
    let backend = FakeBackend::default();
    // No expectations on the port — a call to refresh() would panic.
    let pas = Arc::new(MemoryPasAuth::new());
    let resolver = build_resolver(
        Arc::clone(&store),
        backend.clone(),
        Arc::clone(&pas),
        Some(Arc::new(cipher_for_resolver)),
    );

    let res = resolver.validate(&jar_with_session()).await.unwrap();
    assert!(matches!(res, SessionResolution::Expired));
    assert_eq!(backend.store_call_count(), 0);
    assert_eq!(store.update_sv_call_count(), 0);
}

#[tokio::test]
async fn sv_pas_4xx_on_refresh_yields_expired() {
    let cipher_arc = Arc::new(cipher());
    let store = standard_setup(&cipher_arc);
    let backend = FakeBackend::default();
    let pas = Arc::new(MemoryPasAuth::new().expect_refresh(
        PLAINTEXT_RT,
        Err(PasFailure::Rejected {
            status: 400,
            detail: "invalid_grant".into(),
        }),
    ));
    let resolver = build_resolver(
        Arc::clone(&store),
        backend.clone(),
        Arc::clone(&pas),
        Some(Arc::clone(&cipher_arc)),
    );

    let res = resolver.validate(&jar_with_session()).await.unwrap();
    assert!(matches!(res, SessionResolution::Expired));
    assert_eq!(backend.store_call_count(), 0, "cache must not be touched");
    assert_eq!(
        store.update_sv_call_count(),
        0,
        "update_sv must not be called"
    );
}

#[tokio::test]
async fn sv_pas_5xx_on_refresh_yields_expired_fail_closed() {
    // S-L6 invariant: 5xx must NOT serve cache here. (Compare with
    // S-L3, where 5xx serves cache.)
    let cipher_arc = Arc::new(cipher());
    let store = standard_setup(&cipher_arc);
    let backend = FakeBackend::default();
    let pas = Arc::new(MemoryPasAuth::new().expect_refresh(
        PLAINTEXT_RT,
        Err(PasFailure::ServerError {
            status: 503,
            detail: "upstream".into(),
        }),
    ));
    let resolver = build_resolver(
        Arc::clone(&store),
        backend.clone(),
        Arc::clone(&pas),
        Some(Arc::clone(&cipher_arc)),
    );

    let res = resolver.validate(&jar_with_session()).await.unwrap();
    assert!(matches!(res, SessionResolution::Expired));
    assert_eq!(backend.store_call_count(), 0);
    assert_eq!(store.update_sv_call_count(), 0);
}

#[tokio::test]
async fn sv_pas_transport_on_refresh_yields_expired() {
    // S-L6 invariant: transport-class failures fail-CLOSED.
    let cipher_arc = Arc::new(cipher());
    let store = standard_setup(&cipher_arc);
    let backend = FakeBackend::default();
    let pas = Arc::new(MemoryPasAuth::new().expect_refresh(
        PLAINTEXT_RT,
        Err(PasFailure::Transport {
            detail: "connection reset".into(),
        }),
    ));
    let resolver = build_resolver(
        Arc::clone(&store),
        backend.clone(),
        Arc::clone(&pas),
        Some(Arc::clone(&cipher_arc)),
    );

    let res = resolver.validate(&jar_with_session()).await.unwrap();
    assert!(matches!(res, SessionResolution::Expired));
}

/// Phase 10.13.B replacement for the legacy
/// `sv_userinfo_session_version_none_yields_expired`: a Human session
/// whose newly-issued access_token lacks the `sv` claim must fail
/// closed via `ExpiryCause::AccessTokenMissingSv`. Verifies that the
/// driver's trust-extract step is the actual gate, not a downstream
/// userinfo round-trip (which no longer exists in this path).
#[tokio::test]
async fn sv_access_token_missing_sv_yields_expired() {
    let cipher_arc = Arc::new(cipher());
    let store = standard_setup(&cipher_arc);
    let backend = FakeBackend::default();
    let pas = Arc::new(
        MemoryPasAuth::new()
            .expect_refresh(PLAINTEXT_RT, Ok(token_response_with_sv(None))),
    );
    let resolver = build_resolver(
        Arc::clone(&store),
        backend.clone(),
        Arc::clone(&pas),
        Some(Arc::clone(&cipher_arc)),
    );

    let res = resolver.validate(&jar_with_session()).await.unwrap();
    assert!(matches!(res, SessionResolution::Expired));
    assert_eq!(backend.store_call_count(), 0);
    assert_eq!(store.update_sv_call_count(), 0);
}

#[tokio::test]
async fn sv_update_sv_db_failure_yields_expired_does_not_update_cache() {
    // Critical invariant: cache must not diverge from durable store.
    let cipher_arc = Arc::new(cipher());
    let store = standard_setup(&cipher_arc);
    store.fail_update_sv();
    let backend = FakeBackend::default();
    let pas = Arc::new(
        MemoryPasAuth::new()
            .expect_refresh(PLAINTEXT_RT, Ok(token_response_with_sv(Some(2)))),
    );
    let resolver = build_resolver(
        Arc::clone(&store),
        backend.clone(),
        Arc::clone(&pas),
        Some(Arc::clone(&cipher_arc)),
    );

    let res = resolver.validate(&jar_with_session()).await.unwrap();
    assert!(matches!(res, SessionResolution::Expired));
    assert_eq!(store.update_sv_call_count(), 1);
    assert_eq!(
        backend.store_call_count(),
        0,
        "cache must not be touched after store failure"
    );
}

#[tokio::test]
async fn sv_happy_path_returns_authenticated_with_updated_sv() {
    let cipher_arc = Arc::new(cipher());
    let store = standard_setup(&cipher_arc);
    let backend = FakeBackend::default();
    let pas = Arc::new(
        MemoryPasAuth::new()
            .expect_refresh(PLAINTEXT_RT, Ok(token_response_with_sv(Some(2)))),
    );
    let resolver = build_resolver(
        Arc::clone(&store),
        backend.clone(),
        Arc::clone(&pas),
        Some(Arc::clone(&cipher_arc)),
    );

    let res = resolver.validate(&jar_with_session()).await.unwrap();
    let ctx = match res {
        SessionResolution::Authenticated(ctx) => ctx,
        other => panic!("expected Authenticated, got {other:?}"),
    };
    assert_eq!(ctx.sv(), Some(2));
    assert_eq!(store.update_sv_call_count(), 1);
    assert_eq!(backend.store_call_count(), 1);
    // Policy must pass the spec-fixed 60 s TTL to the backend on
    // record() (regression guard for the previously lying-trait bug).
    assert_eq!(backend.last_ttl(), Some(Duration::from_secs(60)));
}

#[tokio::test]
async fn sv_no_ciphertext_yields_expired() {
    // No ciphertext stored → can't refresh → Expired (no PAS call).
    let cipher_arc = Arc::new(cipher());
    let store = Arc::new(FakeStore::default());
    store.put(
        SESSION_ID,
        FakeAuthContext {
            ppnum_id: PPNUM_ID.into(),
            sv: Some(1),
        },
    );
    // Note: no put_ciphertext call.
    let backend = FakeBackend::default();
    let pas = Arc::new(MemoryPasAuth::new());
    let resolver = build_resolver(
        Arc::clone(&store),
        backend.clone(),
        Arc::clone(&pas),
        Some(Arc::clone(&cipher_arc)),
    );

    let res = resolver.validate(&jar_with_session()).await.unwrap();
    assert!(matches!(res, SessionResolution::Expired));
}

#[tokio::test]
async fn sv_stale_branch_drives_refresh_and_records_new_sv() {
    // Pre-seed the backend with sv=5 (higher than the token's sv=1) so
    // the policy returns CheckResult::Stale rather than Unknown. This
    // exercises the break-glass-converged-across-pods path that the
    // RFC justifies as the reason for keeping Stale and Unknown
    // distinct. Without this test the resolver could silently treat
    // them identically and a future refactor that conflates them would
    // not fail the suite.
    let cipher_arc = Arc::new(cipher());
    let store = standard_setup(&cipher_arc);
    let backend = FakeBackend::default();
    backend
        .store(&format!("sv:{PPNUM_ID}"), 5, Duration::from_secs(60))
        .await;
    let pas = Arc::new(
        MemoryPasAuth::new()
            .expect_refresh(PLAINTEXT_RT, Ok(token_response_with_sv(Some(7)))),
    );
    let resolver = build_resolver(
        Arc::clone(&store),
        backend.clone(),
        Arc::clone(&pas),
        Some(Arc::clone(&cipher_arc)),
    );

    let res = resolver.validate(&jar_with_session()).await.unwrap();
    let ctx = match res {
        SessionResolution::Authenticated(ctx) => ctx,
        other => panic!("expected Authenticated, got {other:?}"),
    };
    assert_eq!(ctx.sv(), Some(7));
    assert_eq!(store.update_sv_call_count(), 1);
    // Two stores total: the pre-seed plus the post-refresh record().
    assert_eq!(backend.store_call_count(), 2);
}

#[tokio::test]
async fn sv_no_cipher_configured_with_ciphertext_yields_expired() {
    // Misconfiguration: ciphertext stored, but resolver has no cipher.
    // Soft fail: log error + return Expired.
    let cipher_for_ct = cipher();
    let store = standard_setup(&cipher_for_ct);
    let backend = FakeBackend::default();
    let pas = Arc::new(MemoryPasAuth::new());
    let resolver = build_resolver(
        Arc::clone(&store),
        backend.clone(),
        Arc::clone(&pas),
        None, // ← no cipher
    );

    let res = resolver.validate(&jar_with_session()).await.unwrap();
    assert!(matches!(res, SessionResolution::Expired));
}

#[tokio::test]
async fn sv_ciphertext_lookup_db_failure_yields_expired() {
    // Closes the test gap flagged in PR review: `get_refresh_ciphertext`
    // returning `Err` is the only `ExpiryCause` arm previously without
    // an integration test. A regression where the driver `?`-propagates
    // the store error (instead of folding to `CiphertextFeed::LookupFailed`)
    // would break fail-closed semantics and the unit test alone would
    // not catch it because the bug lives in the driver, not the core.
    let cipher_arc = Arc::new(cipher());
    let store = standard_setup(&cipher_arc);
    store.fail_ciphertext_lookup();
    let backend = FakeBackend::default();
    let pas = Arc::new(MemoryPasAuth::new());
    let resolver = build_resolver(
        Arc::clone(&store),
        backend.clone(),
        Arc::clone(&pas),
        Some(Arc::clone(&cipher_arc)),
    );

    let res = resolver.validate(&jar_with_session()).await.unwrap();
    assert!(matches!(res, SessionResolution::Expired));
    assert_eq!(store.update_sv_call_count(), 0);
    assert_eq!(backend.store_call_count(), 0);
}

#[tokio::test]
async fn sv_session_vanishes_between_update_and_refetch_yields_expired() {
    // Race scenario: `update_sv` succeeded, `policy.record` ran, but
    // the post-refresh `find()` returns None (e.g. concurrent logout).
    // Verifies the `RefetchFeed::Missing` → `ExpiryCause::ReFetchMissing`
    // path is reachable via the real driver, not just the state machine
    // unit test. Asserts ordering: `update_sv` MUST have run AND the
    // cache MUST have recorded BEFORE the missing re-fetch — proves
    // the operational bug class "session vanished mid-refresh" is
    // observable and lands in the expected fail-closed branch.
    let cipher_arc = Arc::new(cipher());
    let store = standard_setup(&cipher_arc);
    store.drop_session_on_refetch();
    let backend = FakeBackend::default();
    let pas = Arc::new(
        MemoryPasAuth::new()
            .expect_refresh(PLAINTEXT_RT, Ok(token_response_with_sv(Some(7)))),
    );
    let resolver = build_resolver(
        Arc::clone(&store),
        backend.clone(),
        Arc::clone(&pas),
        Some(Arc::clone(&cipher_arc)),
    );

    let res = resolver.validate(&jar_with_session()).await.unwrap();
    assert!(matches!(res, SessionResolution::Expired));
    assert_eq!(
        store.update_sv_call_count(),
        1,
        "update_sv must have landed before the refetch raced",
    );
    assert_eq!(
        backend.store_call_count(),
        1,
        "policy.record must have landed before the refetch raced",
    );
}