diff --git a/.changeset/concurrent-refresh-replay.md b/.changeset/concurrent-refresh-replay.md new file mode 100644 index 0000000..5e6f97a --- /dev/null +++ b/.changeset/concurrent-refresh-replay.md @@ -0,0 +1,5 @@ +--- +"@seamless-auth/core": patch +--- + +Document multi-instance deployment and test that two adapter instances refreshing the same cookie at once both succeed with the same refresh cookie, and that `refresh_token_reused` clears the cookies without a retry. Needs the auth API release that ships the refresh replay window (fells-code/seamless-auth-api#613). diff --git a/README.md b/README.md index 2e2f3c1..1977b03 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,19 @@ packages/nextjs --- +## Running Multiple Instances + +Cookie sessions refresh themselves: when the access cookie is missing or expired, the adapter rotates the refresh cookie at the auth API and sets the new cookies. With several adapter instances behind a load balancer, two instances can receive a refresh from the same browser at nearly the same time, each presenting the same refresh token. + +The auth API covers this with a short replay window. Callers that present a refresh token inside the window after it rotated each get a normal `200` response carrying the same successor refresh token, session id and refresh TTL. The access token is minted per call, so it differs between callers but carries the same session id. Every instance then sets the same refresh cookie value, and the browser ends up with one session. + +- The window defaults to 5 seconds, allows at most 3 replays, and is set on the auth API with `REFRESH_REPLAY_WINDOW_SECONDS` (0 disables it, the maximum is 60). It matches the 5 second completed-refresh cache the core keeps for a refresh cookie presented twice to one instance, so keep them aligned. +- No shared lock or cache between adapter instances is needed while the spread between concurrent requests and any clock skew between the instances and the auth API stay under the window. +- A token presented outside the window, past the replay count, or an older ancestor of the current token is a reuse. The auth API answers `401` with `refresh_token_reused` and revokes the session chain. The adapters treat that as terminal: they clear the session cookies and never retry it. Retrying a reused token cannot succeed and only deepens the revocation. +- Unknown, revoked or expired tokens answer `401` with `invalid_refresh_token`, as before. + +This needs the auth API release that ships fells-code/seamless-auth-api#613. Against an API without it, two instances racing the same refresh token still trip reuse detection and sign the user out, so run a single instance or route a browser's requests to one instance until the API is upgraded. + ## OAuth Login OAuth support is intentionally split across the same trust boundary as the rest of Seamless Auth: diff --git a/packages/core/tests/refreshMultiInstance.test.js b/packages/core/tests/refreshMultiInstance.test.js new file mode 100644 index 0000000..ae076c8 --- /dev/null +++ b/packages/core/tests/refreshMultiInstance.test.js @@ -0,0 +1,134 @@ +// Two adapter instances refreshing the same cookie at once (fells-code/seamless-auth-server#285). +// The auth API holds a short replay window: concurrent callers presenting the +// same refresh token R1 each get 200 with the same successor R2, and a minted +// access token that carries the same sid. Each instance has its own in-process +// state, so nothing here may assume one winner. +import { jest } from "@jest/globals"; + +const verifyRefreshCookieMock = jest.fn(); +const authFetchMock = jest.fn(); +const verifySignedAuthResponseMock = jest.fn(); + +jest.unstable_mockModule("../dist/verifyRefreshCookie.js", () => ({ + verifyRefreshCookie: verifyRefreshCookieMock, +})); +jest.unstable_mockModule("../dist/authFetch.js", () => ({ + authFetch: authFetchMock, + UPSTREAM_UNAVAILABLE_ERROR_CODE: "upstream_unavailable", +})); +jest.unstable_mockModule("../dist/verifySignedAuthResponse.js", () => ({ + verifySignedAuthResponse: verifySignedAuthResponseMock, +})); + +const OPTS = { + authServerUrl: "https://auth.example.com", + cookieDomain: "example.com", + accessCookieName: "access", + registrationCookieName: "registration", + refreshCookieName: "refresh", + preAuthCookieName: "preauth", + cookieSecret: "cookie-secret-cookie-secret-cookie-secret", + serviceSecret: "service-secret-service-secret-service-secret", + issuer: "https://frontend.example.com", + audience: "https://auth.example.com", + keyId: "dev-main", +}; + +const jwt = (payload) => + `e30.${Buffer.from(JSON.stringify(payload)).toString("base64url")}.sig`; + +const json = (status, body) => ({ ok: status < 400, status, json: async () => body }); + +// A fresh module graph is a separate adapter process as far as the in-flight +// and completed-refresh state is concerned. +async function newInstance() { + jest.resetModules(); + const { ensureCookies } = await import("../dist/ensureCookies.js"); + return ensureCookies; +} + +const request = { path: "/users/me", cookies: { refresh: "r1.signed.cookie" } }; + +describe("concurrent refresh across adapter instances", () => { + beforeEach(() => { + authFetchMock.mockReset(); + verifyRefreshCookieMock.mockReset(); + verifySignedAuthResponseMock.mockReset(); + verifyRefreshCookieMock.mockReturnValue({ sub: "user-1", refreshToken: "R1" }); + verifySignedAuthResponseMock.mockImplementation(async (token) => + JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString()), + ); + }); + + it("gives both instances the same successor refresh token and session id", async () => { + let call = 0; + // The API contract: the token is minted per call, everything else is the + // one successor, including for the caller that lost the rotation race. + authFetchMock.mockImplementation(async () => { + call += 1; + return json(200, { + sub: "user-1", + sessionId: "sid-1", + token: jwt({ typ: "access", sub: "user-1", sid: "sid-1", jti: `jti-${call}` }), + refreshToken: "R2", + refreshTtl: 3600, + roles: ["user"], + organizationId: "org-1", + ttl: 300, + }); + }); + + const instanceA = await newInstance(); + const instanceB = await newInstance(); + expect(instanceB).not.toBe(instanceA); + + const [a, b] = await Promise.all([ + instanceA(request, OPTS), + instanceB(request, OPTS), + ]); + + // Each instance went to the API: there is no shared state to deduplicate on. + expect(authFetchMock).toHaveBeenCalledTimes(2); + + for (const result of [a, b]) { + expect(result.type).toBe("ok"); + expect(result.user).toMatchObject({ sub: "user-1", sessionId: "sid-1", refreshed: true }); + } + + const [accessA, refreshA] = a.setCookies; + const [accessB, refreshB] = b.setCookies; + + expect(refreshA.name).toBe("refresh"); + expect(refreshA.value).toEqual(refreshB.value); + expect(refreshA.value.refreshToken).toBe("R2"); + expect(refreshA.ttl).toBe(refreshB.ttl); + expect(accessA.value.sessionId).toBe("sid-1"); + expect(accessB.value.sessionId).toBe("sid-1"); + expect(accessA.value.token).not.toBe(accessB.value.token); + }); + + it("clears the cookies and does not retry when the API answers refresh_token_reused", async () => { + authFetchMock.mockImplementation(async () => + json(401, { error: "refresh_token_reused" }), + ); + + const instance = await newInstance(); + const result = await instance(request, OPTS); + + expect(result.type).toBe("error"); + expect(result.status).toBe(401); + expect(result.clearCookies).toEqual( + expect.arrayContaining(["access", "registration", "refresh"]), + ); + expect(result.setCookies).toBeUndefined(); + expect(authFetchMock).toHaveBeenCalledTimes(1); + + // The refusal is not remembered as a session, so a later request is judged + // by the API again rather than handed anything. + authFetchMock.mockClear(); + const again = await instance(request, OPTS); + expect(again.status).toBe(401); + expect(again.clearCookies).toContain("refresh"); + expect(authFetchMock).toHaveBeenCalledTimes(1); + }); +});