Testing Refresh Token Rotation and Expiry Edge Cases
Refresh tokens are the most powerful tokens in your auth system. An access token lasts 15 minutes. A refresh token can last weeks. If a refresh token is stolen and never tested for rotation or revocation, an attacker has persistent access until you manually intervene.
Most teams test "does refresh work." Almost nobody tests "does refresh rotation work correctly under concurrent requests" or "does logout actually invalidate the refresh token family." This is where the real bugs hide.
How Refresh Token Rotation Works
Standard OAuth refresh: you send a refresh token, you get a new access token. The refresh token stays the same. Simple—and dangerous, because a stolen refresh token never expires.
Refresh token rotation changes this: every time you use a refresh token, you get a new refresh token, and the old one is immediately invalidated. This means:
- Stolen tokens are detected when the attacker uses them after the victim's client has already rotated
- Each refresh is single-use
- Token families can be tracked and entirely revoked if abuse is detected
The catch: rotation introduces edge cases. What happens when two tabs refresh simultaneously? What if the network request succeeds but the response is lost? These scenarios need tests.
Basic Rotation Testing
Single-Use Enforcement
def test_refresh_token_is_single_use():
tokens = authenticate("user", "password")
refresh_token = tokens["refresh_token"]
# First use succeeds
response1 = use_refresh_token(refresh_token)
assert response1.status_code == 200
new_tokens = response1.json()
assert new_tokens["refresh_token"] != refresh_token # New token issued
# Original refresh token is now invalid
response2 = use_refresh_token(refresh_token)
assert response2.status_code == 400
assert response2.json()["error"] == "invalid_grant"
def test_new_refresh_token_issued_on_rotation():
tokens = authenticate("user", "password")
refreshed = use_refresh_token(tokens["refresh_token"])
assert refreshed.status_code == 200
result = refreshed.json()
# New tokens should be different
assert result["access_token"] != tokens["access_token"]
assert result["refresh_token"] != tokens["refresh_token"]
# New access token should be valid
response = client.get(
"/api/profile",
headers={"Authorization": f"Bearer {result['access_token']}"}
)
assert response.status_code == 200Token Family Invalidation (Reuse Detection)
The security property of rotation is that reuse of an old token should invalidate the entire family. If an attacker steals a refresh token and uses it after the legitimate client has already rotated, the server detects the reuse and kills all tokens in the family.
def test_refresh_token_reuse_invalidates_family():
tokens = authenticate("user", "password")
original_refresh = tokens["refresh_token"]
# Legitimate rotation
rotated = use_refresh_token(original_refresh)
new_refresh = rotated.json()["refresh_token"]
new_access = rotated.json()["access_token"]
# Verify new tokens work
assert client.get("/api/me", headers=auth(new_access)).status_code == 200
# Simulate attacker reusing the original (now-invalidated) refresh token
attack_response = use_refresh_token(original_refresh)
assert attack_response.status_code == 400
# Now the ENTIRE FAMILY should be invalidated—new tokens too
time.sleep(0.5) # Allow revocation to propagate
family_check = client.get("/api/me", headers=auth(new_access))
assert family_check.status_code == 401 # Family was killed
def test_new_refresh_token_works_without_reuse():
tokens = authenticate("user", "password")
# Normal rotation chain: original → A → B → C
a = use_refresh_token(tokens["refresh_token"]).json()
b = use_refresh_token(a["refresh_token"]).json()
c = use_refresh_token(b["refresh_token"]).json()
# C should work
assert client.get("/api/me", headers=auth(c["access_token"])).status_code == 200Testing Concurrent Refresh Requests
This is the #1 edge case that breaks rotation implementations. SPAs sometimes send multiple requests simultaneously, all with expired access tokens. Each tries to refresh.
import threading
def test_concurrent_refresh_same_token():
tokens = authenticate("user", "password")
refresh_token = tokens["refresh_token"]
results = []
errors = []
def do_refresh():
try:
r = use_refresh_token(refresh_token)
results.append(r.status_code)
except Exception as e:
errors.append(str(e))
# Fire 5 concurrent refresh requests with the same token
threads = [threading.Thread(target=do_refresh) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
# Exactly one should succeed
successes = [s for s in results if s == 200]
failures = [s for s in results if s in [400, 401, 429]]
assert len(successes) == 1, f"Expected 1 success, got {len(successes)}"
assert len(failures) == 4, f"Expected 4 failures, got {len(failures)}"
def test_concurrent_refresh_doesnt_lose_session():
# More realistic: two tabs, access token expired, both try to refresh
tokens = authenticate("user", "password")
refresh_token = tokens["refresh_token"]
success_tokens = []
lock = threading.Lock()
def refresh_and_collect():
r = use_refresh_token(refresh_token)
if r.status_code == 200:
with lock:
success_tokens.append(r.json())
threads = [threading.Thread(target=refresh_and_collect) for _ in range(2)]
for t in threads:
t.start()
for t in threads:
t.join()
# Exactly one succeeded—the winning tab has a valid session
assert len(success_tokens) == 1
# The winning token should work
winner = success_tokens[0]
assert client.get("/api/me", headers=auth(winner["access_token"])).status_code == 200What you're testing here: Your server's behavior when two clients race to use the same refresh token. One should win. The other should get a clean error. The user shouldn't be logged out unless you implement family invalidation on reuse.
Testing Refresh Token Expiry
Refresh tokens have their own expiry—separate from access tokens. This is the absolute maximum session lifetime.
def test_expired_refresh_token_rejected():
# Create a refresh token that's already expired
expired_refresh = create_refresh_token_with_expiry(
user_id="user123",
expires_at=datetime.utcnow() - timedelta(days=1)
)
response = use_refresh_token(expired_refresh)
assert response.status_code == 400
error = response.json()
assert error["error"] == "invalid_grant"
# Optional: check error description
assert "expired" in error.get("error_description", "").lower() \
or "invalid_grant" == error["error"]
def test_refresh_token_expiry_is_absolute():
# Even if you keep refreshing, the refresh token should eventually expire
# (max session lifetime)
tokens = authenticate("user", "password")
# Keep rotating—each rotation should reset nothing if absolute expiry is set
for _ in range(3):
rotated = use_refresh_token(tokens["refresh_token"])
assert rotated.status_code == 200
tokens = rotated.json()
# Access token is fresh—good
# If absolute session expiry is 1 day, a token issued 1 day ago should fail
# (This requires time manipulation or a very short absolute timeout for testing)
old_refresh = create_refresh_token_at_time(
user_id="user123",
issued_at=datetime.utcnow() - timedelta(days=31), # Older than max session
expires_in_days=30 # 30-day absolute max
)
response = use_refresh_token(old_refresh)
assert response.status_code == 400Testing Logout and Revocation
Logout must invalidate refresh tokens. This is often implemented wrong.
def test_logout_invalidates_refresh_token():
tokens = authenticate("user", "password")
access_token = tokens["access_token"]
refresh_token = tokens["refresh_token"]
# Verify both work
assert client.get("/api/me", headers=auth(access_token)).status_code == 200
# Log out
logout_response = client.post(
"/api/logout",
headers=auth(access_token)
)
assert logout_response.status_code in [200, 204]
# Refresh token must be invalidated
refresh_response = use_refresh_token(refresh_token)
assert refresh_response.status_code == 400
def test_revoke_refresh_token_directly():
tokens = authenticate("user", "password")
# RFC 7009 — OAuth 2.0 Token Revocation
revoke_response = requests.post(
"/oauth/revoke",
data={
"token": tokens["refresh_token"],
"token_type_hint": "refresh_token",
"client_id": "my-app",
"client_secret": "client-secret"
}
)
# Should succeed (or at minimum not error)
assert revoke_response.status_code in [200, 204]
# Token must not work after revocation
refresh_response = use_refresh_token(tokens["refresh_token"])
assert refresh_response.status_code == 400
def test_revoke_all_sessions_for_user():
# Admin revokes all tokens for a compromised account
user_tokens_a = authenticate("user", "password") # Session A
user_tokens_b = authenticate("user", "password") # Session B (different device)
# Admin action: revoke all
admin_revoke_all("user")
# Both sessions should be dead
assert use_refresh_token(user_tokens_a["refresh_token"]).status_code == 400
assert use_refresh_token(user_tokens_b["refresh_token"]).status_code == 400Testing Silent Renewal in SPAs
Single-page applications use a hidden iframe or service worker to silently refresh tokens before they expire. This is a common failure point.
def test_silent_renewal_succeeds_before_expiry(browser):
browser.login("user", "password")
# App's access token expires in 60 seconds
# Silent renewal should kick in at ~45 seconds
initial_access_token = browser.get_local_storage("access_token")
# Wait for silent renewal
time.sleep(50)
# Token should have been refreshed
renewed_access_token = browser.get_local_storage("access_token")
assert renewed_access_token != initial_access_token
# App should still be functional
assert browser.is_visible("#user-menu")
def test_silent_renewal_fails_gracefully_when_session_expired(browser):
browser.login("user", "password")
# Revoke the refresh token server-side (e.g., forced logout)
revoke_all_user_sessions("user")
# Wait for silent renewal attempt
time.sleep(access_token_lifetime + 5)
# App should redirect to login or show session expired message
assert browser.current_url.endswith("/login") or \
browser.is_visible("[data-testid='session-expired-message']")Testing Refresh Token Theft Scenarios
def test_stolen_refresh_token_from_different_ip():
# Issue token from IP 1
tokens = authenticate_from_ip("user", "password", ip="192.168.1.1")
# Attacker uses it from IP 2 (if IP binding is enabled)
response = use_refresh_token_from_ip(tokens["refresh_token"], ip="10.0.0.1")
if ip_binding_enabled():
assert response.status_code == 400
else:
# No IP binding—this will succeed (document the decision)
assert response.status_code == 200
def test_refresh_token_not_returned_in_logs():
tokens = authenticate("user", "password")
refresh_token = tokens["refresh_token"]
# Verify refresh token doesn't appear in application logs
log_entries = get_recent_log_entries()
for entry in log_entries:
assert refresh_token not in str(entry), \
"Refresh token found in logs—token leakage risk"Testing Edge Cases
Lost Response Scenario
The server issued a new refresh token, but the client never received it (network error). The client retries with the old refresh token.
def test_lost_response_handling():
tokens = authenticate("user", "password")
original_refresh = tokens["refresh_token"]
# First rotation happened server-side, but response was "lost"
# Client didn't get the new token
server_did_rotate(original_refresh) # Simulate server-side rotation
# Client retries with the old token
retry_response = use_refresh_token(original_refresh)
# This is implementation-dependent:
# Option A: Reject (strict security—user must log in again)
# Option B: Accept within a grace window (better UX, slightly less secure)
# Test that your implementation matches your documented policy
if strict_rotation_policy():
assert retry_response.status_code == 400
else:
assert retry_response.status_code == 200Empty or Missing Refresh Token
def test_empty_refresh_token_rejected():
response = use_refresh_token("")
assert response.status_code == 400
def test_missing_refresh_token_rejected():
response = requests.post("/oauth/token", data={
"grant_type": "refresh_token",
"client_id": "my-app",
"client_secret": "secret"
# No refresh_token field
})
assert response.status_code == 400
def test_refresh_token_from_different_client_rejected():
# Token issued to client-A can't be used by client-B
tokens = authenticate_as_client("user", "password", client_id="client-A")
response = requests.post("/oauth/token", data={
"grant_type": "refresh_token",
"refresh_token": tokens["refresh_token"],
"client_id": "client-B",
"client_secret": "client-b-secret"
})
assert response.status_code in [400, 401]Testing Checklist
- Refresh token is single-use
- New refresh token issued on every rotation
- Old refresh token immediately invalidated after rotation
- Reuse of old token triggers family invalidation
- Concurrent refresh requests: exactly one succeeds
- Expired refresh token rejected
- Absolute session expiry enforced
- Logout invalidates refresh token
- Token revocation endpoint works (RFC 7009)
- Revoke-all for compromised account works
- Silent renewal works in SPA
- Silent renewal failure redirects to login
- Refresh tokens not logged
Refresh token edge cases are subtle. Most teams discover them in production. Write these tests now.