-
Notifications
You must be signed in to change notification settings - Fork 452
chore(backend): Cache invalid opaque OAuth tokens locally #8519
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
Closed
wobsoriano
wants to merge
17
commits into
main
from
rob/aisec-24-unauthenticated-attacker-prevents-customer-backend-from
Closed
Changes from 11 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
a7358cd
feat(backend): add CfConnectingIp, ForwardedFor, and RealIp header co…
wobsoriano c0558cc
feat(backend): add MachineTokenRateLimit to AuthErrorReason
wobsoriano af973b7
feat(backend): add per-IP token-bucket rate limiter for machine auth
wobsoriano 7df1869
test(backend): add failing integration tests for machine token rate l…
wobsoriano c67bca3
feat(backend): gate verifyMachineAuthToken behind per-IP token-bucket…
wobsoriano 9530d3a
fix(backend): exempt JWT-format OAuth and M2M tokens from IP rate lim…
wobsoriano ef15a10
chore: add integration tests
wobsoriano 8f7dabf
Merge branch 'main' into rob/aisec-24-unauthenticated-attacker-preven…
wobsoriano 88413ea
chore: revert e2e
wobsoriano 2a1b3a8
chore: address coderabbit comments
wobsoriano eca73d4
chore: limit solution to oauth opaque tokens
wobsoriano 0ed7f13
chore: improve tests
wobsoriano 16a9834
Merge branch 'main' into rob/aisec-24-unauthenticated-attacker-preven…
wobsoriano a0ace65
chore: remove unused added constants
wobsoriano e90b4d4
chore: only cache oauth tokens
wobsoriano 21a2f11
chore: remove useless e2e test
wobsoriano 5a74cb4
chore: use 'any' as mocked option for authenticateRequest
wobsoriano 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
79 changes: 79 additions & 0 deletions
79
packages/backend/src/tokens/__tests__/oauthTokenRateLimiter.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,79 @@ | ||
| import { afterEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import { checkOAuthTokenRateLimit, resetOAuthTokenRateLimiter } from '../oauthTokenRateLimiter'; | ||
|
|
||
| afterEach(() => { | ||
| resetOAuthTokenRateLimiter(); | ||
| vi.useRealTimers(); | ||
| }); | ||
|
|
||
| describe('checkOAuthTokenRateLimit', () => { | ||
| it('allows the first request from an IP', () => { | ||
| expect(checkOAuthTokenRateLimit('1.2.3.4')).toBe(true); | ||
| }); | ||
|
|
||
| it('allows up to MAX_BURST requests in a burst', () => { | ||
| const ip = '10.0.0.1'; | ||
| for (let i = 0; i < 20; i++) { | ||
| expect(checkOAuthTokenRateLimit(ip), `request ${i + 1} should be allowed`).toBe(true); | ||
| } | ||
| }); | ||
|
|
||
| it('blocks requests that exceed MAX_BURST', () => { | ||
| const ip = '10.0.0.2'; | ||
| for (let i = 0; i < 20; i++) { | ||
| checkOAuthTokenRateLimit(ip); | ||
| } | ||
| expect(checkOAuthTokenRateLimit(ip)).toBe(false); | ||
| }); | ||
|
|
||
| it('allows requests again after tokens refill', () => { | ||
| vi.useFakeTimers(); | ||
| const ip = '10.0.0.3'; | ||
| for (let i = 0; i < 20; i++) { | ||
| checkOAuthTokenRateLimit(ip); | ||
| } | ||
| expect(checkOAuthTokenRateLimit(ip)).toBe(false); | ||
|
|
||
| // Advance 2 seconds: at 10 tokens/s, 20 new tokens should be available | ||
| vi.advanceTimersByTime(2000); | ||
| expect(checkOAuthTokenRateLimit(ip)).toBe(true); | ||
| }); | ||
|
|
||
| it('tracks different IPs independently', () => { | ||
| const ipA = '192.168.1.1'; | ||
| const ipB = '192.168.1.2'; | ||
| for (let i = 0; i < 20; i++) { | ||
| checkOAuthTokenRateLimit(ipA); | ||
| } | ||
| expect(checkOAuthTokenRateLimit(ipA)).toBe(false); | ||
| expect(checkOAuthTokenRateLimit(ipB)).toBe(true); | ||
| }); | ||
|
|
||
| it('treats the unknown sentinel as a single IP', () => { | ||
| for (let i = 0; i < 20; i++) { | ||
| checkOAuthTokenRateLimit('unknown'); | ||
| } | ||
| expect(checkOAuthTokenRateLimit('unknown')).toBe(false); | ||
| }); | ||
|
|
||
| it('evicts the oldest bucket and allows a new IP when MAX_BUCKETS is reached', () => { | ||
| // Fill up to MAX_BUCKETS (10 000) unique IPs | ||
| for (let i = 0; i < 10_000; i++) { | ||
| checkOAuthTokenRateLimit(`10.${Math.floor(i / 65536)}.${Math.floor((i % 65536) / 256)}.${i % 256}`); | ||
| } | ||
| // The 10 001st IP triggers eviction of the oldest entry; the new IP gets a fresh bucket | ||
| const freshIp = '172.16.0.1'; | ||
| expect(checkOAuthTokenRateLimit(freshIp)).toBe(true); | ||
| }); | ||
|
|
||
| it('allows a previously blocked IP after resetOAuthTokenRateLimiter', () => { | ||
| const ip = '5.5.5.5'; | ||
| for (let i = 0; i < 21; i++) { | ||
| checkOAuthTokenRateLimit(ip); | ||
| } | ||
| expect(checkOAuthTokenRateLimit(ip)).toBe(false); | ||
| resetOAuthTokenRateLimiter(); | ||
| expect(checkOAuthTokenRateLimit(ip)).toBe(true); | ||
| }); | ||
| }); |
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
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
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
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,32 @@ | ||
| const MAX_BURST = 20; | ||
| const REFILL_RATE = 10; // tokens per second | ||
| const MAX_BUCKETS = 10_000; | ||
|
|
||
| type Bucket = { tokens: number; lastRefill: number }; | ||
| const buckets = new Map<string, Bucket>(); | ||
|
|
||
| export function checkOAuthTokenRateLimit(ip: string): boolean { | ||
| if (buckets.size >= MAX_BUCKETS) { | ||
| // Evict the oldest entry rather than clearing all buckets to prevent an attacker | ||
| // from neutralizing rate limits by forcing key churn across many distinct IPs. | ||
| const oldest = buckets.keys().next().value; | ||
| if (oldest !== undefined) { | ||
| buckets.delete(oldest); | ||
| } | ||
| } | ||
| const now = Date.now(); | ||
| const existing = buckets.get(ip); | ||
| const bucket: Bucket = existing ?? { tokens: MAX_BURST, lastRefill: now }; | ||
| const elapsed = (now - bucket.lastRefill) / 1000; | ||
| const refilled = Math.min(MAX_BURST, bucket.tokens + elapsed * REFILL_RATE); | ||
| if (refilled < 1) { | ||
| buckets.set(ip, { tokens: refilled, lastRefill: now }); | ||
| return false; | ||
| } | ||
| buckets.set(ip, { tokens: refilled - 1, lastRefill: now }); | ||
| return true; | ||
| } | ||
|
|
||
| export function resetOAuthTokenRateLimiter(): void { | ||
| buckets.clear(); | ||
| } | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Eviction is triggered for existing IPs at capacity, which weakens throttling.
At Line 9, eviction runs before checking whether
ipalready has a bucket. Whenbuckets.size === MAX_BUCKETS, even requests from existing IPs evict other clients’ buckets, causing unintended rate-limit resets and reducing protection under load.Suggested fix
export function checkMachineTokenRateLimit(ip: string): boolean { - if (buckets.size >= MAX_BUCKETS) { + const existing = buckets.get(ip); + if (existing === undefined && buckets.size >= MAX_BUCKETS) { // Evict the oldest entry rather than clearing all buckets to prevent an attacker // from neutralizing rate limits by forcing key churn across many distinct IPs. const oldest = buckets.keys().next().value; if (oldest !== undefined) { buckets.delete(oldest); } } const now = Date.now(); - const existing = buckets.get(ip); const bucket: Bucket = existing ?? { tokens: MAX_BURST, lastRefill: now };🤖 Prompt for AI Agents