use super::*;
use crate::clock::FixedClock;
use crate::test_support::{FAR_FUTURE, TempDir, seed_expired_token, temp_dir, write_token};
use std::os::unix::fs::PermissionsExt as _;
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
fn token_path(dir: &Path) -> PathBuf {
TokenStore::new(dir.to_path_buf()).token_path()
}
fn lock_path(dir: &Path) -> PathBuf {
TokenStore::new(dir.to_path_buf()).lock_path()
}
fn disk_json(dir: &Path) -> serde_json::Value {
let raw = std::fs::read_to_string(token_path(dir)).expect("read token file");
serde_json::from_str(&raw).expect("token file must be json")
}
#[track_caller]
fn assert_owner_only(path: &Path, what: &str) {
let mode = std::fs::metadata(path)
.expect("must exist")
.permissions()
.mode()
& 0o777;
assert_eq!(
mode & 0o077,
0,
"{what}: permission bits beyond the owner are still set (mode {mode:o})"
);
}
fn writes_are_denied(dir: &Path) -> bool {
let probe = dir.join(".write-probe");
match std::fs::File::create(&probe) {
Ok(_) => {
let _ = std::fs::remove_file(&probe);
false
}
Err(_) => true,
}
}
fn wait_until(what: &str, mut cond: impl FnMut() -> bool) {
let started = std::time::Instant::now();
while !cond() {
assert!(
started.elapsed() < Duration::from_secs(30),
"condition was never met: {what}"
);
std::thread::sleep(Duration::from_millis(1));
}
}
struct CountingRefresher {
calls: AtomicUsize,
new_access: String,
delay: Duration,
}
impl CountingRefresher {
fn new(new_access: &str) -> Self {
Self::with_delay(new_access, Duration::from_millis(50))
}
fn with_delay(new_access: &str, delay: Duration) -> Self {
Self {
calls: AtomicUsize::new(0),
new_access: new_access.to_owned(),
delay,
}
}
fn call_count(&self) -> usize {
self.calls.load(Ordering::SeqCst)
}
}
impl TokenRefresher for CountingRefresher {
fn refresh(&self, _refresh_token: &str) -> Result<Refreshed, Error> {
self.calls.fetch_add(1, Ordering::SeqCst);
std::thread::sleep(self.delay);
Ok(Refreshed::new(
self.new_access.clone(),
"NA_ROTATED".to_owned(),
28_800,
))
}
}
struct FailingRefresher {
calls: AtomicUsize,
}
impl FailingRefresher {
fn new() -> Self {
Self {
calls: AtomicUsize::new(0),
}
}
fn call_count(&self) -> usize {
self.calls.load(Ordering::SeqCst)
}
}
impl TokenRefresher for FailingRefresher {
fn refresh(&self, _refresh_token: &str) -> Result<Refreshed, Error> {
self.calls.fetch_add(1, Ordering::SeqCst);
Err(Error::Auth {
message: "upstream refused".to_owned(),
pricing: None,
})
}
}
struct LifetimeRefresher {
calls: AtomicUsize,
expires_in_secs: u64,
}
impl LifetimeRefresher {
fn new(expires_in_secs: u64) -> Self {
Self {
calls: AtomicUsize::new(0),
expires_in_secs,
}
}
fn call_count(&self) -> usize {
self.calls.load(Ordering::SeqCst)
}
}
impl TokenRefresher for LifetimeRefresher {
fn refresh(&self, _refresh_token: &str) -> Result<Refreshed, Error> {
self.calls.fetch_add(1, Ordering::SeqCst);
Ok(Refreshed {
access_token: "NEW".to_owned(),
refresh_token: "NA_ROTATED".to_owned(),
expires_in_secs: self.expires_in_secs,
})
}
}
const T0: u64 = 1_700_000_000;
fn interval_manager(
tag: &str,
expires_in: u64,
) -> (
TokenManager,
Arc<LifetimeRefresher>,
Arc<FixedClock>,
TempDir,
) {
let dir = temp_dir(tag);
seed_expired_token(&dir);
let refresher = Arc::new(LifetimeRefresher::new(expires_in));
let clock = Arc::new(FixedClock::new(T0));
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_clock(Arc::clone(&clock) as Arc<_>)
.with_lock_deadline(Duration::from_secs(3));
(mgr, refresher, clock, dir)
}
const SHORT_BUT_USABLE: u64 = 100;
struct SlowStaleRefresher {
calls: AtomicUsize,
delay: Duration,
}
impl SlowStaleRefresher {
fn new(delay: Duration) -> Self {
Self {
calls: AtomicUsize::new(0),
delay,
}
}
fn call_count(&self) -> usize {
self.calls.load(Ordering::SeqCst)
}
}
impl TokenRefresher for SlowStaleRefresher {
fn refresh(&self, _refresh_token: &str) -> Result<Refreshed, Error> {
self.calls.fetch_add(1, Ordering::SeqCst);
std::thread::sleep(self.delay);
Ok(Refreshed::new("NEW".to_owned(), "NA_ROTATED".to_owned(), 0))
}
}
#[test]
fn the_min_refresh_interval_is_the_expiry_skew_and_is_sixty_seconds() {
assert_eq!(MIN_REFRESH_INTERVAL, EXPIRY_SKEW);
assert_eq!(MIN_REFRESH_INTERVAL, Duration::from_secs(60));
}
#[test]
fn refresh_within_min_interval_errors_and_sends_nothing() {
let (mgr, refresher, _clock, _dir) = interval_manager("gen-interval", 0);
assert_eq!(mgr.access_token().expect("first"), "NEW");
let after_first = refresher.call_count();
assert_eq!(after_first, 1, "the first call should rotate normally");
let err = mgr
.access_token()
.expect_err("inside the interval it should be an error, not the cache");
assert_eq!(
refresher.call_count(),
after_first,
"one more refresh POST was fired inside the interval"
);
let msg = err.to_string();
assert!(msg.contains("refresh"), "should name the cause: {msg}");
assert!(
msg.contains("rotation interval"),
"a failure for another reason (lock, persist, ...) is mistaken for the interval: {msg}"
);
}
#[test]
fn min_interval_error_is_not_billed() {
let (mgr, _refresher, _clock, _dir) = interval_manager("gen-notbilled", 0);
let _first = mgr.access_token().expect("first");
let err = mgr
.access_token()
.expect_err("should be blocked by the interval");
assert!(
matches!(&err, Error::Auth { pricing: None, .. }),
"actual: {err:?}"
);
assert_eq!(err.billing(), crate::pricing::Billing::NotBilled);
}
#[test]
fn clock_going_backwards_counts_as_interval_not_met() {
let (mgr, refresher, clock, _dir) = interval_manager("gen-backwards", 0);
assert_eq!(mgr.access_token().expect("first"), "NEW");
let after_first = refresher.call_count();
clock.set(T0 - 30);
let err = mgr
.access_token()
.expect_err("a clock going backwards should count as interval not met");
assert!(
err.to_string().contains("rotation interval"),
"the backwards clock was caught somewhere other than the gate (the test is vacuous): {err}"
);
assert_eq!(
refresher.call_count(),
after_first,
"a clock going backwards defeated the rotation suppression"
);
}
#[test]
fn the_minimum_interval_boundary_admits_exactly_sixty_seconds() {
let (mgr, refresher, clock, _dir) = interval_manager("gen-boundary", SHORT_BUT_USABLE);
let (g1, _tok) = mgr.access_token_with_generation().expect("first");
assert_eq!(refresher.call_count(), 1);
mgr.invalidate_generation(g1).expect("invalidate");
clock.advance(MIN_REFRESH_INTERVAL.as_secs() - 1);
let err = mgr
.access_token()
.expect_err("59 seconds should be blocked");
assert!(err.to_string().contains("rotation interval"), "{err}");
assert_eq!(refresher.call_count(), 1, "rotated at 59 seconds");
clock.advance(1);
assert_eq!(
mgr.access_token()
.expect("exactly 60 seconds should be allowed"),
"NEW"
);
assert_eq!(
refresher.call_count(),
2,
"the interval was met but no rotation happened โ the gate is off by one at the boundary"
);
}
#[test]
fn generation_increases_on_each_refresh() {
let (mgr, refresher, clock, _dir) = interval_manager("gen-increases", SHORT_BUT_USABLE);
let (g1, _t1) = mgr.access_token_with_generation().expect("first");
assert_eq!(refresher.call_count(), 1);
mgr.invalidate_generation(g1).expect("invalidate");
clock.advance(MIN_REFRESH_INTERVAL.as_secs() + 1);
let (g2, _t2) = mgr.access_token_with_generation().expect("second");
assert_eq!(
refresher.call_count(),
2,
"if the second call was not a rotation, this test does not live up to its name"
);
assert!(g2 > g1, "g1={g1} g2={g2}");
}
#[test]
fn generation_increases_when_a_siblings_rotation_is_adopted() {
let (mgr, refresher, _clock, dir) = interval_manager("gen-adopt", SHORT_BUT_USABLE);
let (g1, t1) = mgr.access_token_with_generation().expect("first");
assert_eq!(refresher.call_count(), 1);
mgr.invalidate_generation(g1).expect("invalidate");
write_token(&dir, "FROM_SIBLING", "NA_SIBLING", FAR_FUTURE);
let (g2, t2) = mgr.access_token_with_generation().expect("adopt");
assert_eq!(t2, "FROM_SIBLING", "the sibling's token was not adopted");
assert_ne!(t2, t1);
assert_eq!(
refresher.call_count(),
1,
"a rotation POST was fired on the adoption path"
);
assert!(
g2 > g1,
"the cache was replaced but the generation did not change โ a stale 401 can kill this \
token (g1={g1} g2={g2})"
);
}
#[test]
fn stale_generation_cannot_invalidate_newer_token() {
let (mgr, refresher, clock, _dir) = interval_manager("gen-stale", SHORT_BUT_USABLE);
let (g1, _t1) = mgr.access_token_with_generation().expect("first");
mgr.invalidate_generation(g1).expect("invalidate g1");
clock.advance(MIN_REFRESH_INTERVAL.as_secs() + 1);
let (g2, t2) = mgr.access_token_with_generation().expect("second");
let calls_after_g2 = refresher.call_count();
let locks_after_g2 = mgr.lock_attempts();
assert_eq!(calls_after_g2, 2);
mgr.invalidate_generation(g1)
.expect("invalidating a stale generation is a no-op, not an error");
let (g3, t3) = mgr.access_token_with_generation().expect("third");
assert_eq!(
g3, g2,
"an invalidation with a stale generation took effect"
);
assert_eq!(t3, t2, "a perfectly good token was discarded");
assert_eq!(
refresher.call_count(),
calls_after_g2,
"the invalidation took effect and one more rotation happened"
);
assert_eq!(
mgr.lock_attempts(),
locks_after_g2,
"the cache was emptied and the third call went as far as the file lock"
);
}
#[test]
fn a_blocked_second_caller_gets_the_interval_error_not_a_file_lock_timeout() {
let dir = temp_dir("relock-order");
seed_expired_token(&dir);
let refresher = Arc::new(SlowStaleRefresher::new(Duration::from_millis(300)));
let mgr = Arc::new(
TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_clock(Arc::new(FixedClock::new(T0)))
.with_lock_deadline(Duration::from_millis(800)),
);
let winner = {
let m = Arc::clone(&mgr);
std::thread::spawn(move || m.access_token())
};
wait_until("the winner has entered refresh", || {
refresher.call_count() >= 1
});
let loser = {
let m = Arc::clone(&mgr);
std::thread::spawn(move || m.access_token())
};
assert_eq!(winner.join().expect("join").expect("winner"), "NEW");
let err = loser
.join()
.expect("join")
.expect_err("the loser should be blocked by the interval");
let msg = err.to_string();
assert!(
msg.contains("rotation interval"),
"failed for a reason other than the interval: {msg}"
);
assert!(
!msg.contains("token lock:"),
"the loser starved on the file lock โ this means the winner released the state mutex \
before the flock, which is a side effect of an implementation that reads the \
generation outside the critical section: {msg}"
);
assert_eq!(
refresher.call_count(),
1,
"a second rotation was fired inside the interval"
);
}
#[test]
fn invalidating_the_current_generation_clears_the_cache() {
let (mgr, refresher, clock, _dir) = interval_manager("gen-clears", SHORT_BUT_USABLE);
let (g1, _t1) = mgr.access_token_with_generation().expect("first");
let locks_after_g1 = mgr.lock_attempts();
mgr.invalidate_generation(g1).expect("invalidate");
clock.advance(MIN_REFRESH_INTERVAL.as_secs() + 1);
let (g2, _t2) = mgr.access_token_with_generation().expect("second");
assert!(g2 > g1, "the cache was not emptied (g1={g1} g2={g2})");
assert_eq!(refresher.call_count(), 2);
assert!(
mgr.lock_attempts() > locks_after_g1,
"the cache was left as is, so the file lock was never tried โ the invalidation is a no-op"
);
}
struct RotatingRefresher {
calls: AtomicUsize,
}
impl RotatingRefresher {
fn new() -> Self {
Self {
calls: AtomicUsize::new(0),
}
}
fn call_count(&self) -> usize {
self.calls.load(Ordering::SeqCst)
}
}
impl TokenRefresher for RotatingRefresher {
fn refresh(&self, _refresh_token: &str) -> Result<Refreshed, Error> {
let n = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
Ok(Refreshed {
access_token: format!("ROT{n}"),
refresh_token: format!("NA_ROT{n}"),
expires_in_secs: 28_800,
})
}
}
fn rotating_manager(
tag: &str,
) -> (
TokenManager,
Arc<RotatingRefresher>,
Arc<FixedClock>,
TempDir,
) {
let dir = temp_dir(tag);
seed_expired_token(&dir);
let refresher = Arc::new(RotatingRefresher::new());
let clock = Arc::new(FixedClock::new(T0));
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_clock(Arc::clone(&clock) as Arc<_>)
.with_lock_deadline(Duration::from_secs(3));
(mgr, refresher, clock, dir)
}
#[test]
fn rejecting_the_current_generation_forces_exactly_one_rotation_past_a_fresh_token() {
let (mgr, refresher, clock, _dir) = rotating_manager("gen-reject-forces");
let (g1, t1) = mgr.access_token_with_generation().expect("first");
assert_eq!(refresher.call_count(), 1);
assert_eq!(t1, "ROT1");
mgr.reject_generation(g1).expect("reject");
clock.advance(MIN_REFRESH_INTERVAL.as_secs() + 1);
let (g2, t2) = mgr.access_token_with_generation().expect("second");
assert_eq!(
refresher.call_count(),
2,
"the rejection was stopped by the freshness check and forced no rotation โ this means \
the retry resends, unchanged, the token that was just rejected"
);
assert_ne!(t2, t1, "the same token came out again");
assert!(g2 > g1, "g1={g1} g2={g2}");
let locks_after_g2 = mgr.lock_attempts();
clock.advance(MIN_REFRESH_INTERVAL.as_secs() + 1);
let (g3, t3) = mgr.access_token_with_generation().expect("third");
assert_eq!(
refresher.call_count(),
2,
"the rejection mark lingered and fired another rotation โ the forcing must happen once"
);
assert_eq!((g3, t3.as_str()), (g2, t2.as_str()));
assert_eq!(
mgr.lock_attempts(),
locks_after_g2,
"it was not a cache hit; it went as far as the file lock"
);
}
#[test]
fn a_rejected_token_still_yields_to_a_siblings_newer_token() {
let (mgr, refresher, _clock, dir) = rotating_manager("gen-reject-adopt");
let (g1, t1) = mgr.access_token_with_generation().expect("first");
assert_eq!(refresher.call_count(), 1);
mgr.reject_generation(g1).expect("reject");
write_token(&dir, "FROM_SIBLING", "NA_SIBLING", FAR_FUTURE);
let (g2, t2) = mgr.access_token_with_generation().expect("adopt");
assert_eq!(
t2, "FROM_SIBLING",
"the sibling's new token was not adopted"
);
assert_ne!(t2, t1);
assert_eq!(
refresher.call_count(),
1,
"a rotation POST was fired although a different, adoptable token was there"
);
assert!(
g2 > g1,
"the cache was replaced but the generation did not change (g1={g1} g2={g2})"
);
}
#[test]
fn a_stale_generation_cannot_reject_a_newer_token() {
let (mgr, refresher, clock, _dir) = rotating_manager("gen-reject-stale");
let (g1, _t1) = mgr.access_token_with_generation().expect("first");
mgr.reject_generation(g1).expect("reject g1");
clock.advance(MIN_REFRESH_INTERVAL.as_secs() + 1);
let (g2, t2) = mgr.access_token_with_generation().expect("second");
assert_eq!(refresher.call_count(), 2);
let locks_after_g2 = mgr.lock_attempts();
mgr.reject_generation(g1)
.expect("rejecting a stale generation is a no-op, not an error");
clock.advance(MIN_REFRESH_INTERVAL.as_secs() + 1);
let (g3, t3) = mgr.access_token_with_generation().expect("third");
assert_eq!(g3, g2, "a rejection with a stale generation took effect");
assert_eq!(t3, t2, "a perfectly good token was discarded");
assert_eq!(
refresher.call_count(),
2,
"the stale rejection fired one more rotation"
);
assert_eq!(
mgr.lock_attempts(),
locks_after_g2,
"the cache was discarded and the file lock was tried โ the stale rejection was not a no-op"
);
}
#[test]
fn a_rejected_token_is_never_adopted_again_even_after_a_later_rotation() {
let (mgr, refresher, clock, dir) = rotating_manager("gen-reject-sticky");
let (g1, t1) = mgr.access_token_with_generation().expect("first");
mgr.reject_generation(g1).expect("reject");
clock.advance(MIN_REFRESH_INTERVAL.as_secs() + 1);
let (g2, t2) = mgr.access_token_with_generation().expect("rotated");
assert_eq!(refresher.call_count(), 2);
assert_ne!(t2, t1);
write_token(&dir, &t1, "NA_RESURRECTED", FAR_FUTURE);
mgr.invalidate_generation(g2).expect("invalidate");
clock.advance(MIN_REFRESH_INTERVAL.as_secs() + 1);
let (_g3, t3) = mgr.access_token_with_generation().expect("third");
assert_ne!(
t3, t1,
"a token the server already rejected was revived from disk and handed out"
);
assert_eq!(
refresher.call_count(),
3,
"it should have rotated instead of adopting the dead token"
);
}
#[test]
fn a_rejection_does_not_bypass_the_minimum_rotation_interval() {
let (mgr, refresher, clock, _dir) = rotating_manager("gen-reject-interval");
let (g1, t1) = mgr.access_token_with_generation().expect("first");
assert_eq!(refresher.call_count(), 1);
mgr.reject_generation(g1).expect("reject");
let err = mgr
.access_token()
.expect_err("a forced rotation inside the interval should be refused");
assert!(
err.to_string().contains("rotation interval"),
"failed for a reason other than the gate: {err}"
);
assert_eq!(
refresher.call_count(),
1,
"the rejection bypassed the rotation suppression gate"
);
clock.advance(MIN_REFRESH_INTERVAL.as_secs() + 1);
let (_g2, t2) = mgr.access_token_with_generation().expect("second");
assert_eq!(
refresher.call_count(),
2,
"the interval was met but it did not rotate"
);
assert_ne!(
t2, t1,
"the rejection mark was cleared and it went back to the dead token"
);
}
#[test]
fn concurrent_callers_collapse_into_exactly_one_refresh() {
let dir = temp_dir("singleflight");
seed_expired_token(&dir);
let refresher = Arc::new(CountingRefresher::with_delay(
"NEW",
Duration::from_millis(100),
));
let mgr = Arc::new(
TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_state_deadline(Duration::from_secs(20)),
);
let started = std::time::Instant::now();
let mut handles = Vec::new();
for _ in 0..16 {
let m = Arc::clone(&mgr);
handles.push(std::thread::spawn(move || m.access_token()));
}
for h in handles {
assert_eq!(h.join().expect("join").expect("access_token"), "NEW");
}
assert_eq!(
refresher.call_count(),
1,
"the refreshes did not collapse into a single flight"
);
assert!(
started.elapsed() < Duration::from_secs(10),
"waiters slept until the state deadline instead of being woken: {:?}",
started.elapsed()
);
}
#[test]
fn concurrent_callers_are_served_from_memory_rather_than_each_taking_the_file_lock() {
let dir = temp_dir("memoryserved");
seed_expired_token(&dir);
let refresher = Arc::new(CountingRefresher::new("NEW"));
let mgr = Arc::new(
TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_lock_deadline(Duration::ZERO)
.with_state_deadline(Duration::from_secs(60)),
);
let mut handles = Vec::new();
for _ in 0..16 {
let m = Arc::clone(&mgr);
handles.push(std::thread::spawn(move || m.access_token()));
}
for h in handles {
assert_eq!(
h.join()
.expect("join")
.expect("every caller should get its answer from memory"),
"NEW"
);
}
assert_eq!(refresher.call_count(), 1);
assert_eq!(
mgr.lock_attempts(),
1,
"late callers got their answer through the file lock, not from memory"
);
}
#[test]
fn two_managers_sharing_a_directory_collapse_into_one_refresh() {
let dir = temp_dir("twomanagers");
seed_expired_token(&dir);
let refresher = Arc::new(CountingRefresher::new("NEW"));
let winner = Arc::new(TokenManager::new(
dir.to_path_buf(),
Arc::clone(&refresher) as Arc<_>,
));
let loser = Arc::new(TokenManager::new(
dir.to_path_buf(),
Arc::clone(&refresher) as Arc<_>,
));
let w = Arc::clone(&winner);
let first = std::thread::spawn(move || w.access_token());
wait_until("the winner has entered refresh", || {
refresher.call_count() >= 1
});
let l = Arc::clone(&loser);
let second = std::thread::spawn(move || l.access_token());
assert_eq!(first.join().expect("join").expect("winner"), "NEW");
assert_eq!(
second.join().expect("join").expect("loser"),
"NEW",
"the loser did not get the sibling's new token"
);
assert_eq!(
refresher.call_count(),
1,
"the two managers each rotated โ the cross-process single-flight is broken, and the \
second rotation is reuse of an already invalidated chain"
);
assert_eq!(
winner.lock_attempts(),
1,
"the winner did not take the lock"
);
assert_eq!(
loser.lock_attempts(),
1,
"the loser never went for the file lock"
);
let v = disk_json(&dir);
assert_eq!(v["access_token"], serde_json::json!("NEW"));
assert_eq!(v["refresh_token"], serde_json::json!("NA_ROTATED"));
}
#[test]
fn a_contended_in_process_mutex_times_out_with_a_message_distinct_from_the_file_lock() {
let dir = temp_dir("statedeadline");
seed_expired_token(&dir);
let refresher = Arc::new(CountingRefresher::with_delay("NEW", Duration::from_secs(1)));
let mgr = Arc::new(
TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_state_deadline(Duration::from_millis(50)),
);
let holder = {
let m = Arc::clone(&mgr);
std::thread::spawn(move || m.access_token())
};
wait_until("the holder has entered refresh", || {
refresher.call_count() >= 1
});
let err = mgr
.access_token()
.expect_err("the mutex wait must not be unbounded");
let msg = err.to_string();
assert!(msg.contains("token state lock"), "{msg}");
assert!(
!msg.contains("token lock:"),
"the in-process mutex wait arrives with the same wording as the file lock wait: {msg}"
);
assert_eq!(
refresher.call_count(),
1,
"refreshed without having obtained the mutex"
);
assert_eq!(holder.join().expect("join").expect("holder"), "NEW");
}
#[test]
fn refreshed_debug_never_prints_token_material() {
let r = Refreshed::new(
"AT_LEAKED_ACCESS".to_owned(),
"NA_LEAKED_REFRESH".to_owned(),
28_800,
);
let rendered = format!("{r:?}");
assert!(
!rendered.contains("AT_LEAKED_ACCESS"),
"access token leaked: {rendered}"
);
assert!(
!rendered.contains("NA_LEAKED_REFRESH"),
"refresh token leaked: {rendered}"
);
assert!(
rendered.contains(crate::redaction::REDACTED),
"marker diverged from redaction::REDACTED: {rendered}"
);
assert!(
rendered.contains("28800"),
"even expires_in_secs was redacted: {rendered}"
);
}
#[test]
fn refreshed_new_assigns_the_fields_in_the_documented_order() {
let r = Refreshed::new("ACCESS".to_owned(), "REFRESH".to_owned(), 7);
assert_eq!(r.access_token, "ACCESS");
assert_eq!(r.refresh_token, "REFRESH");
assert_eq!(r.expires_in_secs, 7);
}
#[test]
fn a_fresh_token_on_disk_is_used_without_calling_refresh() {
let dir = temp_dir("nofresh");
write_token(&dir, "STILLGOOD", "NA_X", FAR_FUTURE);
let refresher = Arc::new(CountingRefresher::new("UNUSED"));
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>);
assert_eq!(mgr.access_token().expect("token"), "STILLGOOD");
assert_eq!(
refresher.call_count(),
0,
"refresh was called although the token is valid"
);
}
#[test]
fn a_cached_fresh_token_is_returned_without_touching_the_file_lock() {
let dir = temp_dir("fastpath");
write_token(&dir, "STILLGOOD", "NA_X", FAR_FUTURE);
let refresher = Arc::new(CountingRefresher::new("UNUSED"));
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_lock_deadline(Duration::from_secs(3));
assert_eq!(mgr.access_token().expect("first"), "STILLGOOD");
assert_eq!(
mgr.lock_attempts(),
1,
"the first call should take the lock"
);
let held = lock::acquire(&lock_path(&dir), lock::LOCK_DEADLINE).expect("hold the lock");
assert_eq!(mgr.access_token().expect("cached"), "STILLGOOD");
assert_eq!(
mgr.lock_attempts(),
1,
"went for the file lock again although the cache is valid"
);
assert_eq!(refresher.call_count(), 0);
drop(held);
}
#[test]
fn the_rotated_refresh_token_is_persisted_before_the_new_access_token_is_returned() {
let dir = temp_dir("rotation");
seed_expired_token(&dir);
let mgr = TokenManager::new(dir.to_path_buf(), Arc::new(CountingRefresher::new("NEW")));
assert_eq!(mgr.access_token().expect("token"), "NEW");
let v = disk_json(&dir);
assert_eq!(v["refresh_token"], serde_json::json!("NA_ROTATED"));
assert_eq!(v["access_token"], serde_json::json!("NEW"));
let rendered = format!("{mgr:?}");
assert!(!rendered.contains("NEW"), "access token leaked: {rendered}");
assert!(
!rendered.contains("NA_ROTATED"),
"refresh token leaked: {rendered}"
);
}
#[test]
fn expires_at_is_the_refresh_time_plus_the_reported_lifetime() {
let dir = temp_dir("expiry");
seed_expired_token(&dir);
let mgr = TokenManager::new(dir.to_path_buf(), Arc::new(CountingRefresher::new("NEW")))
.with_clock(Arc::new(FixedClock::new(1_000_000)));
assert_eq!(mgr.access_token().expect("token"), "NEW");
assert_eq!(
disk_json(&dir)["expires_at"],
serde_json::json!(1_028_800_u64),
"expires_at is not now + expires_in"
);
}
#[test]
fn a_lock_timeout_never_refreshes() {
let dir = temp_dir("locktimeout");
seed_expired_token(&dir);
let held = lock::acquire(&lock_path(&dir), lock::LOCK_DEADLINE).expect("hold the lock");
let refresher = Arc::new(CountingRefresher::new("NEW"));
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_lock_deadline(Duration::from_millis(200));
let err = mgr.access_token().expect_err("should time out");
assert!(err.to_string().contains("token lock"), "{err}");
assert_eq!(
refresher.call_count(),
0,
"refreshed without having obtained the lock โ the concurrent refresh path"
);
assert_eq!(
disk_json(&dir)["refresh_token"],
serde_json::json!("NA_OLD"),
"the disk was updated without the lock"
);
drop(held);
}
#[test]
fn a_missing_token_directory_is_created_owner_only_instead_of_only_being_checked() {
let base = temp_dir("mkdir");
let dir = base.join("nested").join("deep");
let refresher = Arc::new(CountingRefresher::new("UNUSED"));
let mgr = TokenManager::new(dir.clone(), Arc::clone(&refresher) as Arc<_>)
.with_lock_deadline(Duration::from_millis(200));
let err = mgr.access_token().expect_err("there is no token");
assert!(err.to_string().contains("token store"), "{err}");
assert!(
dir.is_dir(),
"the directory was not created โ this is check-only, not create-then-check"
);
assert_owner_only(&base.join("nested"), "token dir (ancestor)");
assert_owner_only(&dir, "token dir");
assert_eq!(refresher.call_count(), 0);
}
#[test]
fn an_over_permissive_directory_is_rejected_before_the_lock_is_acquired() {
let dir = temp_dir("baddir");
seed_expired_token(&dir);
let held = lock::acquire(&lock_path(&dir), lock::LOCK_DEADLINE).expect("hold the lock");
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o777)).expect("chmod");
let refresher = Arc::new(CountingRefresher::new("NEW"));
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_lock_deadline(Duration::from_secs(3));
let err = mgr
.access_token()
.expect_err("an over-permissive directory should be refused");
assert!(
err.to_string().contains("token directory permissions"),
"failed for a reason other than directory permissions: {err}"
);
assert_eq!(
mgr.lock_attempts(),
0,
"the lock came before the directory check"
);
assert_eq!(refresher.call_count(), 0);
drop(held);
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).expect("restore");
}
#[test]
fn a_broken_clock_is_diagnosed_instead_of_timing_out_on_a_sibling_s_lock() {
let dir = temp_dir("clock-before-lock");
seed_expired_token(&dir);
let held = lock::acquire(&lock_path(&dir), lock::LOCK_DEADLINE).expect("hold the lock");
let pre_epoch = std::time::UNIX_EPOCH - Duration::from_secs(1);
let refresher = Arc::new(CountingRefresher::new("NEW"));
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_lock_deadline(Duration::from_secs(3))
.with_clock(Arc::new(FixedClock::new(crate::clock::secs_since_epoch(
pre_epoch,
))));
let err = mgr.access_token().expect_err("should be refused");
assert!(
err.to_string().contains("unix epoch"),
"reported lock contention instead of the clock: {err}"
);
assert_eq!(
mgr.lock_attempts(),
0,
"the lock came before the clock check"
);
assert_eq!(refresher.call_count(), 0);
drop(held);
}
#[test]
fn a_pre_epoch_clock_refuses_to_refresh_rather_than_minting_an_immortal_token() {
let dir = temp_dir("preepoch");
seed_expired_token(&dir);
let pre_epoch = std::time::UNIX_EPOCH - Duration::from_secs(1);
let refresher = Arc::new(CountingRefresher::new("NEW"));
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>).with_clock(
Arc::new(FixedClock::new(crate::clock::secs_since_epoch(pre_epoch))),
);
let err = mgr.access_token().expect_err("should be refused");
assert!(err.to_string().contains("unix epoch"), "{err}");
assert_eq!(
refresher.call_count(),
0,
"a rotation was fired although the expiry time cannot be computed"
);
let v = disk_json(&dir);
assert_eq!(v["refresh_token"], serde_json::json!("NA_OLD"));
assert_eq!(v["expires_at"], serde_json::json!(1_u64));
}
#[test]
fn an_unrepresentable_expiry_is_recorded_as_expired_not_immortal() {
let dir = temp_dir("nearmax");
seed_expired_token(&dir);
let now = u64::MAX - 5;
let refresher = Arc::new(CountingRefresher::new("NEW"));
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_clock(Arc::new(FixedClock::new(now)));
assert_eq!(mgr.access_token().expect("token"), "NEW");
assert_eq!(refresher.call_count(), 1);
let v = disk_json(&dir);
assert_eq!(v["refresh_token"], serde_json::json!("NA_ROTATED"));
assert_ne!(
v["expires_at"],
serde_json::json!(u64::MAX),
"a token that never expires was stamped onto disk"
);
assert_eq!(v["expires_at"], serde_json::json!(now));
}
#[test]
fn a_failed_persist_forbids_a_second_refresh_but_still_adopts_a_good_disk_token() {
let dir = temp_dir("persistfail");
seed_expired_token(&dir);
drop(lock::acquire(&lock_path(&dir), lock::LOCK_DEADLINE).expect("pre-create the lock file"));
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o500)).expect("chmod");
if !writes_are_denied(&dir) {
eprintln!(
"skipped a_failed_persist_forbids_a_second_refresh_but_still_adopts_a_good_disk_token: \
running as root โ writes succeed even in a read-only directory"
);
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).expect("restore");
return;
}
let refresher = Arc::new(CountingRefresher::new("NEW"));
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_lock_deadline(Duration::from_millis(500));
let err = mgr.access_token().expect_err("the persist should fail");
assert!(err.to_string().contains("persist"), "{err}");
for leaked in ["NA_OLD", "NA_ROTATED", "NEW"] {
assert!(
!err.to_string().contains(leaked),
"a token was carried in the error message: {err}"
);
}
assert_eq!(refresher.call_count(), 1);
let err2 = mgr.access_token().expect_err("should be forbidden");
assert!(err2.to_string().contains("token chain"), "{err2}");
assert!(
err2.to_string().contains("could not be persisted"),
"{err2}"
);
assert_eq!(
refresher.call_count(),
1,
"retried with the old refresh token after a rotation that could not be persisted"
);
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).expect("restore");
write_token(&dir, "FROM_DISK", "NA_SIBLING", FAR_FUTURE);
assert_eq!(mgr.access_token().expect("adopt"), "FROM_DISK");
assert_eq!(refresher.call_count(), 1);
}
#[test]
fn a_missing_token_file_is_reported_without_calling_refresh() {
let dir = temp_dir("notokenfile");
let refresher = Arc::new(CountingRefresher::new("NEW"));
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_lock_deadline(Duration::from_millis(200));
let err = mgr.access_token().expect_err("there is no token");
assert!(err.to_string().contains("token store"), "{err}");
assert_eq!(refresher.call_count(), 0);
}
#[test]
fn a_failing_refresh_leaves_the_cache_the_disk_and_the_poison_flag_untouched() {
let dir = temp_dir("failrefresh");
seed_expired_token(&dir);
let refresher = Arc::new(FailingRefresher::new());
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_lock_deadline(Duration::from_millis(200));
let err = mgr
.access_token()
.expect_err("the failure should be propagated");
assert!(err.to_string().contains("upstream refused"), "{err}");
assert_eq!(refresher.call_count(), 1);
let v = disk_json(&dir);
assert_eq!(v["access_token"], serde_json::json!("OLD"));
assert_eq!(v["refresh_token"], serde_json::json!("NA_OLD"));
assert_eq!(v["expires_at"], serde_json::json!(1_u64));
let err2 = mgr.access_token().expect_err("should still fail");
assert!(err2.to_string().contains("upstream refused"), "{err2}");
assert!(
!err2.to_string().contains("token chain"),
"a network failure was poisoned like a persist failure: {err2}"
);
assert_eq!(
refresher.call_count(),
2,
"a retry was blocked after a transient refresh failure โ treated like a persist failure"
);
}
#[test]
fn an_absurd_reported_lifetime_is_clamped_instead_of_collapsing_to_expired() {
let dir = temp_dir("absurdlifetime");
seed_expired_token(&dir);
let now = 1_000_000_u64;
let refresher = Arc::new(LifetimeRefresher::new(u64::MAX));
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_clock(Arc::new(FixedClock::new(now)));
assert_eq!(mgr.access_token().expect("token"), "NEW");
let expires_at = disk_json(&dir)["expires_at"].clone();
assert_ne!(
expires_at,
serde_json::json!(now),
"the absurd lifetime collapsed to 'already expired' โ every call rotates the chain"
);
assert_ne!(
expires_at,
serde_json::json!(u64::MAX),
"a token that never expires was stamped onto disk"
);
assert_eq!(
expires_at,
serde_json::json!(now + MAX_TOKEN_LIFETIME.as_secs()),
"it was cut down to some value other than the cap"
);
assert_eq!(mgr.access_token().expect("second"), "NEW");
assert_eq!(
refresher.call_count(),
1,
"the second call rotated again โ the cap did not stop the storm"
);
}
#[test]
fn the_lifetime_cap_is_thirty_days() {
assert_eq!(MAX_TOKEN_LIFETIME, Duration::from_secs(2_592_000));
}
#[test]
fn a_reported_lifetime_inside_the_skew_window_is_stale_on_arrival() {
let now = 1_000_000_u64;
{
let dir = temp_dir("skewfloor-above");
seed_expired_token(&dir);
let refresher = Arc::new(LifetimeRefresher::new(EXPIRY_SKEW.as_secs() + 1));
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_clock(Arc::new(FixedClock::new(now)));
assert_eq!(mgr.access_token().expect("first"), "NEW");
assert_eq!(mgr.access_token().expect("second"), "NEW");
assert_eq!(
refresher.call_count(),
1,
"the second call rotated again although it is outside the skew (61 seconds)"
);
}
for expires_in in [0, EXPIRY_SKEW.as_secs()] {
let dir = temp_dir(&format!("skewfloor-{expires_in}"));
seed_expired_token(&dir);
let refresher = Arc::new(LifetimeRefresher::new(expires_in));
let mgr = TokenManager::new(dir.to_path_buf(), Arc::clone(&refresher) as Arc<_>)
.with_clock(Arc::new(FixedClock::new(now)));
assert_eq!(mgr.access_token().expect("first"), "NEW");
let v = disk_json(&dir);
assert_eq!(v["refresh_token"], serde_json::json!("NA_ROTATED"));
assert_eq!(
v["expires_at"],
serde_json::json!(now + expires_in),
"expires_in={expires_in}: reported lifetime should be recorded as is (no lower bound)"
);
let err = mgr
.access_token()
.expect_err("expires_in={expires_in}: the interval gate should block it");
assert!(
err.to_string().contains("rotation interval"),
"expires_in={expires_in}: failed for a reason other than the interval: {err}"
);
assert_eq!(
refresher.call_count(),
1,
"expires_in={expires_in}: the chain was rotated once more inside the interval โ \
the storm A2 handed to A3 is still there"
);
}
}
#[test]
fn a_normal_reported_lifetime_is_recorded_verbatim() {
let dir = temp_dir("normallifetime");
seed_expired_token(&dir);
let now = 1_000_000_u64;
let mgr = TokenManager::new(dir.to_path_buf(), Arc::new(LifetimeRefresher::new(28_800)))
.with_clock(Arc::new(FixedClock::new(now)));
assert_eq!(mgr.access_token().expect("token"), "NEW");
assert_eq!(
disk_json(&dir)["expires_at"],
serde_json::json!(now + 28_800),
"a normal lifetime was changed to the cap or some other value"
);
}
#[test]
fn the_lock_file_survives_every_path_through_access_token() {
use std::os::unix::fs::MetadataExt as _;
let ino_of = |p: &Path| std::fs::metadata(p).expect("lock file must exist").ino();
let dir = temp_dir("lockimmortal");
let path = lock_path(&dir);
seed_expired_token(&dir);
let mgr = TokenManager::new(dir.to_path_buf(), Arc::new(CountingRefresher::new("NEW")));
mgr.access_token().expect("success path");
let ino = ino_of(&path);
seed_expired_token(&dir);
let mgr = TokenManager::new(dir.to_path_buf(), Arc::new(FailingRefresher::new()));
mgr.access_token().expect_err("the refresh should fail");
assert_eq!(
ino_of(&path),
ino,
"the refresh failure path replaced the lock file"
);
std::fs::remove_file(token_path(&dir)).expect("remove token file");
mgr.access_token().expect_err("there is no token");
assert_eq!(
ino_of(&path),
ino,
"the read failure path replaced the lock file"
);
}
struct PanickingRefresher;
impl TokenRefresher for PanickingRefresher {
fn refresh(&self, _refresh_token: &str) -> Result<Refreshed, Error> {
panic!("refresher blew up mid-rotation");
}
}
#[test]
fn a_panicking_refresher_forbids_refresh_and_does_not_block_others() {
let dir = temp_dir("panicking-refresher");
seed_expired_token(&dir);
let before = disk_json(&dir);
let mgr = TokenManager::new(dir.to_path_buf(), Arc::new(PanickingRefresher) as Arc<_>)
.with_clock(Arc::new(FixedClock::new(T0)) as Arc<_>)
.with_lock_deadline(Duration::from_secs(3))
.with_state_deadline(Duration::from_secs(2));
let first = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| mgr.access_token()));
assert!(
first.is_err(),
"the refresher's panic should propagate to its caller"
);
let started = std::time::Instant::now();
let second = mgr.access_token();
assert!(
started.elapsed() < Duration::from_secs(2),
"second caller waited out the state deadline: {:?}",
started.elapsed()
);
let msg = second.expect_err("refresh must stay forbidden").to_string();
assert!(msg.contains("was interrupted"), "actual: {msg}");
assert!(!msg.contains("could not be persisted"), "actual: {msg}");
assert_eq!(disk_json(&dir), before, "the token file must be untouched");
}