Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,24 @@ cookies, so the next request tries again:
| gets a 2xx with no session, or one that fails verification | 502 `upstream_unavailable` |
| waits on another request's rotation for it and times out | 502 `upstream_unavailable` |

### Several instances

Refresh sharing lives in one process. With several adapter instances (several workers, pods or
hosts) behind one site, two of them can present the same refresh token at once. This needs the
auth API release that ships the refresh replay window
([seamless-auth-api#613](https://github.com/fells-code/seamless-auth-api/pull/613)). Within the
window, 5 seconds by default (`REFRESH_REPLAY_WINDOW_SECONDS` on the API, 0 disables it, capped
at 60), and for at most 3 replays, the API answers every caller with the same successor: the same
refresh token, session id, `refreshTtl`, `sub`, `roles` and `organizationId`. The access token is
minted per call, so it differs but carries the same `sid`. Each instance therefore writes the same
refresh cookie and no user is logged out, and no shared lock, cache or sticky routing is needed.
That holds while the requests reach the API, and your clocks agree, within the window.

A token presented after the window or past the replay count, or an older ancestor, is answered
401 `refresh_token_reused` and the API revokes the session chain. The adapter treats any 401 as
terminal: it clears the cookies and never retries. Against an API without the window, concurrent
refreshes from separate instances still log the user out.

## The manifest

On its first request the adapter fetches `/.well-known/seamless-adapter.json` from the auth API
Expand Down
113 changes: 113 additions & 0 deletions tests/test_refresh_replay.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
"""Concurrent refreshes across adapter instances. The auth API answers every caller
presenting a refresh token inside its replay window with the same successor, so each
instance succeeds and writes the same refresh cookie."""

from __future__ import annotations

import threading
from typing import Any

import httpx2
import pytest
from conftest import (
TEST_SECRET,
FakeApi,
api_token,
call,
respond,
signed_cookie,
)

from seamless_auth._jwt import verify_hs256

REFRESH = signed_cookie("seamless-refresh", {"sub": "u1", "refreshToken": "r1"})


class ReplayingApi:
"""Answers every caller holding r1 with the one successor r2 and a freshly
minted access token, as the auth API's replay window does."""

def __init__(self, callers: int) -> None:
self.lock = threading.Lock()
self.minted = 0
self.arrived = threading.Barrier(callers)

def refresh(self, _req: httpx2.Request) -> httpx2.Response:
self.arrived.wait(timeout=10)
with self.lock:
self.minted += 1
jti = f"access-{self.minted}"
return httpx2.Response(
200,
json={
"message": "Success",
"sub": "u1",
"token": api_token("u1", "access", sid="s-1", jti=jti),
"refreshToken": "r2",
"sessionId": "s-1",
"ttl": 900,
"refreshTtl": 3600,
"roles": ["user"],
"organizationId": "org-1",
},
)


def _claims(value: str) -> dict[str, Any]:
claims = verify_hs256(value, TEST_SECRET)
assert claims is not None
return claims


@pytest.mark.parametrize(
"route", [("POST", "/refresh"), ("GET", "/users/me")], ids=["post", "silent"]
)
def test_two_instances_refreshing_one_token_both_write_the_same_successor(
route: tuple[str, str],
) -> None:
contract = ReplayingApi(callers=2)
apis = [FakeApi(), FakeApi()]
for api in apis:
api.on("POST", "/refresh", contract.refresh)
api.on("GET", "/users/me", respond(200, {"user": {"id": "u1"}}))
adapters = [api.adapter() for api in apis]
replies: list[Any] = [None, None]

def run(i: int) -> None:
replies[i] = call(adapters[i], *route, cookie=REFRESH)

threads = [threading.Thread(target=run, args=(i,)) for i in range(2)]
for t in threads:
t.start()
for t in threads:
t.join(timeout=20)

assert contract.minted == 2
for api in apis:
assert len(api.calls_to("POST", "/refresh")) == 1
for r in replies:
assert r.status == 200, r.text
assert "refreshToken" not in r.text
refresh = [_claims(r.cookies["seamless-refresh"].value) for r in replies]
assert [c["refreshToken"] for c in refresh] == ["r2", "r2"]
access = [_claims(r.cookies["seamless-access"].value) for r in replies]
assert [a["sessionId"] for a in access] == ["s-1", "s-1"]
assert access[0]["token"] != access[1]["token"]


@pytest.mark.parametrize(
"route", [("POST", "/refresh"), ("GET", "/users/me")], ids=["post", "silent"]
)
def test_refresh_token_reused_clears_the_cookies_and_is_not_retried(
api: FakeApi, route: tuple[str, str]
) -> None:
api.on("POST", "/refresh", respond(401, {"error": "refresh_token_reused"}))
api.on("GET", "/users/me", respond(200, {"user": {"id": "u1"}}))

r = call(api.adapter(), *route, cookie=REFRESH)

assert r.status == 401, r.text
assert r.cleared("seamless-access")
assert r.cleared("seamless-refresh")
assert len(api.calls_to("POST", "/refresh")) == 1
assert api.calls_to("GET", "/users/me") == []
Loading