feat: proactive Bearer token refresh with unified fallback
- Parse JWT 'exp' claim to track token expiry (token_expires_at) - Proactively refresh Bearer tokens 1 hour before expiry in ensure_authenticated() - Refresh response without expires_in now falls back to JWT exp for expiry derivation - Support custom refresh_path via bearer auth_config whitelist - Unify 401 fallback: all bearer types (including Sub2API) now go through _refresh_bearer_token() instead of separate old path - Remove dead _is_sub2api_bearer() / _refresh_sub2api_bearer_token() - Add 2 new tests: refresh_path override + JWT exp backfill Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
5a20e792fe
commit
2262b6a564
@@ -1,5 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
@@ -36,6 +40,17 @@ def _response(request: httpx.Request, status_code: int, payload=None) -> httpx.R
|
||||
return httpx.Response(status_code, json=payload, request=request)
|
||||
|
||||
|
||||
def _jwt_token(exp_timestamp: int) -> str:
|
||||
"""Build a fake JWT with the given exp claim."""
|
||||
payload_b64 = base64.urlsafe_b64encode(
|
||||
json.dumps({"exp": exp_timestamp}).encode()
|
||||
).rstrip(b"=").decode()
|
||||
return f"header.{payload_b64}.sig"
|
||||
|
||||
|
||||
# ── Existing Sub2API bearer tests (unchanged) ─────────────────────────────
|
||||
|
||||
|
||||
def test_sub2api_bearer_refreshes_on_401_and_retries(monkeypatch):
|
||||
updates: list[dict] = []
|
||||
|
||||
@@ -98,7 +113,51 @@ def test_sub2api_bearer_without_refresh_token_does_not_refresh(monkeypatch):
|
||||
]
|
||||
|
||||
|
||||
def test_non_sub2api_bearer_does_not_refresh(monkeypatch):
|
||||
# ── Updated: non-Sub2API bearer now refreshes with refresh_token ──────────
|
||||
|
||||
|
||||
def test_bearer_refreshes_on_401_with_default_refresh_path(monkeypatch):
|
||||
"""Non-sub2api bearer with refresh_token refreshes on 401 (new behaviour)."""
|
||||
updates: list[dict] = []
|
||||
|
||||
def handler(request: httpx.Request, kwargs):
|
||||
if request.url.path == "/groups/available":
|
||||
auth = kwargs["headers"].get("Authorization")
|
||||
if auth == "Bearer old-access":
|
||||
return _response(request, 401, {"detail": "expired"})
|
||||
assert auth == "Bearer new-access"
|
||||
return _response(request, 200, [{"id": "g1", "name": "G1"}])
|
||||
if request.url.path == "/api/user/refresh":
|
||||
assert kwargs["json"] == {"refresh_token": "old-refresh"}
|
||||
return _response(request, 200, {
|
||||
"access_token": "new-access",
|
||||
"refresh_token": "new-refresh",
|
||||
"expires_in": 3600,
|
||||
})
|
||||
raise AssertionError(f"unexpected: {request.method} {request.url}")
|
||||
|
||||
fake = _install_fake_client(monkeypatch, handler)
|
||||
client = UpstreamClient(
|
||||
base_url="http://plain-bearer.local",
|
||||
api_prefix="",
|
||||
auth_type="bearer",
|
||||
auth_config={"token": "old-access", "refresh_token": "old-refresh"},
|
||||
on_auth_config_update=updates.append,
|
||||
)
|
||||
|
||||
groups = client.get_available_groups("/groups/available")
|
||||
|
||||
assert groups == [{"id": "g1", "name": "G1"}]
|
||||
assert [(c["method"], c["path"]) for c in fake.calls] == [
|
||||
("GET", "/groups/available"),
|
||||
("POST", "/api/user/refresh"),
|
||||
("GET", "/groups/available"),
|
||||
]
|
||||
assert updates[-1]["token"] == "new-access"
|
||||
|
||||
|
||||
def test_bearer_without_refresh_token_still_fails_on_401(monkeypatch):
|
||||
"""Bearer without refresh_token does NOT retry on 401."""
|
||||
def handler(request: httpx.Request, kwargs):
|
||||
assert request.url.path == "/groups/available"
|
||||
return _response(request, 401, {"detail": "expired"})
|
||||
@@ -108,7 +167,7 @@ def test_non_sub2api_bearer_does_not_refresh(monkeypatch):
|
||||
base_url="http://plain-bearer.local",
|
||||
api_prefix="",
|
||||
auth_type="bearer",
|
||||
auth_config={"token": "old-access", "refresh_token": "old-refresh"},
|
||||
auth_config={"token": "old-access"},
|
||||
)
|
||||
|
||||
with pytest.raises(httpx.HTTPStatusError):
|
||||
@@ -119,6 +178,188 @@ def test_non_sub2api_bearer_does_not_refresh(monkeypatch):
|
||||
]
|
||||
|
||||
|
||||
# ── New: proactive refresh tests ─────────────────────────────────────────
|
||||
|
||||
|
||||
def test_bearer_proactive_refresh_when_expiry_approaching(monkeypatch):
|
||||
"""ensure_authenticated proactively refreshes token expiring within 1 h."""
|
||||
updates: list[dict] = []
|
||||
|
||||
def handler(request: httpx.Request, kwargs):
|
||||
if request.url.path == "/api/user/refresh":
|
||||
assert kwargs["json"] == {"refresh_token": "the-refresh"}
|
||||
return _response(request, 200, {
|
||||
"access_token": "new-token",
|
||||
"refresh_token": "new-refresh",
|
||||
"expires_in": 7200,
|
||||
})
|
||||
raise AssertionError(f"unexpected: {request.method} {request.url}")
|
||||
|
||||
_install_fake_client(monkeypatch, handler)
|
||||
client = UpstreamClient(
|
||||
base_url="http://bearer.local",
|
||||
api_prefix="",
|
||||
auth_type="bearer",
|
||||
auth_config={
|
||||
"token": "old-token",
|
||||
"refresh_token": "the-refresh",
|
||||
"token_expires_at": int(time.time()) + 1800, # 30 min left
|
||||
},
|
||||
on_auth_config_update=updates.append,
|
||||
)
|
||||
|
||||
client.ensure_authenticated()
|
||||
|
||||
assert updates[-1]["token"] == "new-token"
|
||||
assert updates[-1]["refresh_token"] == "new-refresh"
|
||||
|
||||
|
||||
def test_bearer_proactive_skips_when_token_fresh(monkeypatch):
|
||||
"""ensure_authenticated does NOT refresh token that is far from expiry."""
|
||||
|
||||
def handler(request: httpx.Request, kwargs):
|
||||
raise AssertionError(f"unexpected request: {request.method} {request.url}")
|
||||
|
||||
_install_fake_client(monkeypatch, handler)
|
||||
client = UpstreamClient(
|
||||
base_url="http://bearer.local",
|
||||
api_prefix="",
|
||||
auth_type="bearer",
|
||||
auth_config={
|
||||
"token": "still-fresh",
|
||||
"refresh_token": "the-refresh",
|
||||
"token_expires_at": int(time.time()) + 86400 * 7, # 7 days
|
||||
},
|
||||
)
|
||||
|
||||
# Should not make any HTTP request
|
||||
client.ensure_authenticated()
|
||||
|
||||
|
||||
def test_bearer_proactive_parses_jwt_exp_when_missing(monkeypatch):
|
||||
"""Missing token_expires_at is derived from JWT exp claim."""
|
||||
future_exp = int(time.time()) + 86400 * 7 # 7 days → far away, no refresh
|
||||
fake_jwt = _jwt_token(future_exp)
|
||||
|
||||
def handler(request: httpx.Request, kwargs):
|
||||
raise AssertionError(f"unexpected request: {request.method} {request.url}")
|
||||
|
||||
_install_fake_client(monkeypatch, handler)
|
||||
client = UpstreamClient(
|
||||
base_url="http://bearer.local",
|
||||
api_prefix="",
|
||||
auth_type="bearer",
|
||||
auth_config={"token": fake_jwt, "refresh_token": "the-refresh"},
|
||||
)
|
||||
|
||||
client.ensure_authenticated()
|
||||
|
||||
assert client.auth_config.get("token_expires_at") == future_exp
|
||||
|
||||
|
||||
def test_bearer_proactive_refresh_from_jwt_exp(monkeypatch):
|
||||
"""When token_expires_at is missing but JWT exp is within 1h, refresh."""
|
||||
updates: list[dict] = []
|
||||
|
||||
def handler(request: httpx.Request, kwargs):
|
||||
if request.url.path == "/api/user/refresh":
|
||||
return _response(request, 200, {
|
||||
"access_token": "refreshed-token",
|
||||
"expires_in": 7200,
|
||||
})
|
||||
raise AssertionError(f"unexpected: {request.method} {request.url}")
|
||||
|
||||
_install_fake_client(monkeypatch, handler)
|
||||
near_exp = int(time.time()) + 600 # 10 min left
|
||||
client = UpstreamClient(
|
||||
base_url="http://bearer.local",
|
||||
api_prefix="",
|
||||
auth_type="bearer",
|
||||
auth_config={"token": _jwt_token(near_exp), "refresh_token": "the-refresh"},
|
||||
on_auth_config_update=updates.append,
|
||||
)
|
||||
|
||||
client.ensure_authenticated()
|
||||
|
||||
assert updates[-1]["token"] == "refreshed-token"
|
||||
|
||||
|
||||
def test_bearer_refresh_uses_custom_refresh_path(monkeypatch):
|
||||
"""refresh_path in auth_config overrides the default refresh endpoint."""
|
||||
updates: list[dict] = []
|
||||
|
||||
def handler(request: httpx.Request, kwargs):
|
||||
if request.url.path == "/custom/refresh/endpoint":
|
||||
assert kwargs["json"] == {"refresh_token": "my-refresh"}
|
||||
return _response(request, 200, {
|
||||
"access_token": "custom-refreshed",
|
||||
"expires_in": 7200,
|
||||
})
|
||||
raise AssertionError(f"unexpected: {request.method} {request.url}")
|
||||
|
||||
_install_fake_client(monkeypatch, handler)
|
||||
# Token is within 1h → triggers proactive refresh
|
||||
near_exp = int(time.time()) + 1800
|
||||
client = UpstreamClient(
|
||||
base_url="http://bearer.local",
|
||||
api_prefix="", # default would be /api/user/refresh
|
||||
auth_type="bearer",
|
||||
auth_config={
|
||||
"token": "stale-token",
|
||||
"refresh_token": "my-refresh",
|
||||
"refresh_path": "/custom/refresh/endpoint",
|
||||
"token_expires_at": near_exp,
|
||||
},
|
||||
on_auth_config_update=updates.append,
|
||||
)
|
||||
|
||||
client.ensure_authenticated()
|
||||
|
||||
assert updates[-1]["token"] == "custom-refreshed"
|
||||
|
||||
|
||||
def test_bearer_refresh_backfills_token_expires_at_from_jwt(monkeypatch):
|
||||
"""When refresh response has no expires_in, derive token_expires_at from JWT exp."""
|
||||
updates: list[dict] = []
|
||||
future_exp = int(time.time()) + 3600 # 1 h from now
|
||||
new_access_token = _jwt_token(future_exp)
|
||||
|
||||
def handler(request: httpx.Request, kwargs):
|
||||
if request.url.path == "/api/user/refresh":
|
||||
assert kwargs["json"] == {"refresh_token": "my-refresh"}
|
||||
# Response deliberately omits expires_in
|
||||
return _response(request, 200, {
|
||||
"access_token": new_access_token,
|
||||
"refresh_token": "new-refresh",
|
||||
})
|
||||
raise AssertionError(f"unexpected: {request.method} {request.url}")
|
||||
|
||||
_install_fake_client(monkeypatch, handler)
|
||||
# Token is within 1h → triggers proactive refresh
|
||||
near_exp = int(time.time()) + 1800
|
||||
client = UpstreamClient(
|
||||
base_url="http://bearer.local",
|
||||
api_prefix="",
|
||||
auth_type="bearer",
|
||||
auth_config={
|
||||
"token": "stale-token",
|
||||
"refresh_token": "my-refresh",
|
||||
"token_expires_at": near_exp,
|
||||
},
|
||||
on_auth_config_update=updates.append,
|
||||
)
|
||||
|
||||
client.ensure_authenticated()
|
||||
|
||||
assert updates[-1]["token"] == new_access_token
|
||||
assert updates[-1]["token_expires_at"] == future_exp
|
||||
# expires_in was NOT in the response → should not appear in the update
|
||||
assert "expires_in" not in updates[-1]
|
||||
|
||||
|
||||
# ── Existing login_password tests (unchanged) ─────────────────────────────
|
||||
|
||||
|
||||
def test_login_password_saves_sub2api_refresh_token(monkeypatch):
|
||||
updates: list[dict] = []
|
||||
|
||||
|
||||
Reference in New Issue
Block a user