-
-
Notifications
You must be signed in to change notification settings - Fork 256
feat: add rate limit (429) handling to AuthenticationController
#6993
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
mathieuartu
merged 11 commits into
main
from
feat/authentication-controller-429-throttling
Nov 17, 2025
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
402f1e8
feat: (wip) add 429 handling and request throttling to authentication…
mathieuartu 182fffe
fix: only manage 429
mathieuartu 86706ff
fix: lint issues
mathieuartu 269027e
fix: update changelog
mathieuartu cd3e038
Merge branch 'main' into feat/authentication-controller-429-throttling
mathieuartu cb71a05
fix: re-throw bug
mathieuartu 77cba42
fix: update getUserProfileLineage to use RL management
mathieuartu 2e99d46
fix: past-date bug
mathieuartu ee982eb
fix: better types in test file
mathieuartu 20c6074
fix: address pr feedbacks
mathieuartu fb123d2
Merge branch 'main' into feat/authentication-controller-429-throttling
mathieuartu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
174 changes: 174 additions & 0 deletions
174
packages/profile-sync-controller/src/sdk/authentication-jwt-bearer/flow-srp.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| import { SRPJwtBearerAuth } from './flow-srp'; | ||
| import { | ||
| AuthType, | ||
| type AuthConfig, | ||
| type LoginResponse, | ||
| type UserProfile, | ||
| } from './types'; | ||
| import * as timeUtils from './utils/time'; | ||
| import { Env, Platform } from '../../shared/env'; | ||
| import { RateLimitedError } from '../errors'; | ||
|
|
||
| jest.setTimeout(15000); | ||
|
|
||
| // Mock the time utilities to avoid real delays in tests | ||
| jest.mock('./utils/time', () => ({ | ||
| delay: jest.fn(), | ||
| })); | ||
|
|
||
| const mockDelay = timeUtils.delay as jest.MockedFunction< | ||
| typeof timeUtils.delay | ||
| >; | ||
|
|
||
| // Mock services | ||
| const mockGetNonce = jest.fn(); | ||
| const mockAuthenticate = jest.fn(); | ||
| const mockAuthorizeOIDC = jest.fn(); | ||
|
|
||
| jest.mock('./services', () => ({ | ||
| authenticate: (...args: unknown[]) => mockAuthenticate(...args), | ||
| authorizeOIDC: (...args: unknown[]) => mockAuthorizeOIDC(...args), | ||
| getNonce: (...args: unknown[]) => mockGetNonce(...args), | ||
| getUserProfileLineage: jest.fn(), | ||
| })); | ||
|
|
||
| describe('SRPJwtBearerAuth rate limit handling', () => { | ||
| const config: AuthConfig & { type: AuthType.SRP } = { | ||
| type: AuthType.SRP, | ||
| env: Env.DEV, | ||
| platform: Platform.EXTENSION, | ||
| }; | ||
|
|
||
| // Mock data constants | ||
| const MOCK_PROFILE: UserProfile = { | ||
| profileId: 'p1', | ||
| metaMetricsId: 'm1', | ||
| identifierId: 'i1', | ||
| }; | ||
|
|
||
| const MOCK_NONCE_RESPONSE = { | ||
| nonce: 'nonce-1', | ||
| identifier: 'identifier-1', | ||
| expiresIn: 60, | ||
| }; | ||
|
|
||
| const MOCK_AUTH_RESPONSE = { | ||
| token: 'jwt-token', | ||
| expiresIn: 60, | ||
| profile: MOCK_PROFILE, | ||
| }; | ||
|
|
||
| const MOCK_OIDC_RESPONSE = { | ||
| accessToken: 'access', | ||
| expiresIn: 60, | ||
| obtainedAt: Date.now(), | ||
| }; | ||
|
|
||
| // Helper to create a rate limit error | ||
| const createRateLimitError = (retryAfterMs?: number) => | ||
| new RateLimitedError('rate limited', retryAfterMs); | ||
|
|
||
| const createAuth = (overrides?: { | ||
| cooldownDefaultMs?: number; | ||
| maxLoginRetries?: number; | ||
| }) => { | ||
| const store: { value: LoginResponse | null } = { value: null }; | ||
|
|
||
| const auth = new SRPJwtBearerAuth(config, { | ||
| storage: { | ||
| getLoginResponse: async () => store.value, | ||
| setLoginResponse: async (val) => { | ||
| store.value = val; | ||
| }, | ||
| }, | ||
| signing: { | ||
| getIdentifier: async () => 'identifier-1', | ||
| signMessage: async () => 'signature-1', | ||
| }, | ||
| rateLimitRetry: overrides, | ||
| }); | ||
|
|
||
| return { auth, store }; | ||
| }; | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| mockGetNonce.mockResolvedValue(MOCK_NONCE_RESPONSE); | ||
| mockAuthenticate.mockResolvedValue(MOCK_AUTH_RESPONSE); | ||
| mockAuthorizeOIDC.mockResolvedValue(MOCK_OIDC_RESPONSE); | ||
| }); | ||
|
|
||
| it('coalesces concurrent calls into a single login attempt', async () => { | ||
| const { auth } = createAuth(); | ||
|
|
||
| const p1 = auth.getAccessToken(); | ||
| const p2 = auth.getAccessToken(); | ||
| const p3 = auth.getAccessToken(); | ||
|
|
||
| const [t1, t2, t3] = await Promise.all([p1, p2, p3]); | ||
|
|
||
| expect(t1).toBe('access'); | ||
| expect(t2).toBe('access'); | ||
| expect(t3).toBe('access'); | ||
|
|
||
| // single sequence of service calls | ||
| expect(mockGetNonce).toHaveBeenCalledTimes(1); | ||
| expect(mockAuthenticate).toHaveBeenCalledTimes(1); | ||
| expect(mockAuthorizeOIDC).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it('applies cooldown and retries once on 429 with Retry-After', async () => { | ||
| const cooldownDefaultMs = 20; | ||
| const maxLoginRetries = 1; | ||
| const { auth } = createAuth({ cooldownDefaultMs, maxLoginRetries }); | ||
|
|
||
| mockAuthenticate | ||
| .mockRejectedValueOnce(createRateLimitError(cooldownDefaultMs)) | ||
| .mockResolvedValueOnce(MOCK_AUTH_RESPONSE); | ||
|
|
||
| const p1 = auth.getAccessToken(); | ||
| const p2 = auth.getAccessToken(); | ||
|
|
||
| const [t1, t2] = await Promise.all([p1, p2]); | ||
| expect(t1).toBe('access'); | ||
| expect(t2).toBe('access'); | ||
|
|
||
| // Should retry after rate limit error | ||
| expect(mockAuthenticate).toHaveBeenCalledTimes(maxLoginRetries + 1); | ||
| // Should apply cooldown delay | ||
| expect(mockDelay).toHaveBeenCalledWith(cooldownDefaultMs); | ||
| }); | ||
|
|
||
| it('throws 429 after exhausting all retries', async () => { | ||
| const cooldownDefaultMs = 20; | ||
| const maxLoginRetries = 1; | ||
| const { auth } = createAuth({ cooldownDefaultMs, maxLoginRetries }); | ||
|
|
||
| mockAuthenticate.mockRejectedValue(createRateLimitError(cooldownDefaultMs)); | ||
| await expect(auth.getAccessToken()).rejects.toThrow('rate limited'); | ||
|
|
||
| // Should attempt initial + maxLoginRetries | ||
| expect(mockAuthenticate).toHaveBeenCalledTimes(1 + maxLoginRetries); | ||
| // Should apply cooldown delay | ||
| expect(mockDelay).toHaveBeenCalledTimes(maxLoginRetries); | ||
| }); | ||
|
|
||
| it('throws transient errors immediately without retry', async () => { | ||
| const { auth, store } = createAuth(); | ||
|
|
||
| // Force a login by clearing session | ||
| store.value = null; | ||
|
|
||
| const transientError = new Error('transient network error'); | ||
| mockAuthenticate.mockRejectedValue(transientError); | ||
|
|
||
| await expect(auth.getAccessToken()).rejects.toThrow( | ||
| 'transient network error', | ||
| ); | ||
|
|
||
| // Should NOT retry on transient errors | ||
| expect(mockAuthenticate).toHaveBeenCalledTimes(1); | ||
| // Should NOT apply any delay | ||
| expect(mockDelay).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.