-
-
Notifications
You must be signed in to change notification settings - Fork 274
fix: centralize rate limiting and CF IP #42
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
Open
regenrek
wants to merge
2
commits into
openclaw:main
Choose a base branch
from
regenrek:fix/rate-limit-helper-cf-ip
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+149
−89
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
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,35 @@ | ||
| /* @vitest-environment node */ | ||
| import { describe, expect, it } from 'vitest' | ||
| import { getClientIp } from './httpRateLimit' | ||
|
|
||
| describe('getClientIp', () => { | ||
| it('returns null when cf-connecting-ip missing', () => { | ||
| const request = new Request('https://example.com', { | ||
| headers: { | ||
| 'x-forwarded-for': '203.0.113.9', | ||
| }, | ||
| }) | ||
| process.env.TRUST_FORWARDED_IPS = '' | ||
| expect(getClientIp(request)).toBeNull() | ||
| }) | ||
|
|
||
| it('returns first ip from cf-connecting-ip', () => { | ||
| const request = new Request('https://example.com', { | ||
| headers: { | ||
| 'cf-connecting-ip': '203.0.113.1, 198.51.100.2', | ||
| }, | ||
| }) | ||
| expect(getClientIp(request)).toBe('203.0.113.1') | ||
| }) | ||
|
|
||
| it('uses forwarded headers when opt-in enabled', () => { | ||
| const request = new Request('https://example.com', { | ||
| headers: { | ||
| 'x-forwarded-for': '203.0.113.9, 198.51.100.2', | ||
| }, | ||
| }) | ||
| process.env.TRUST_FORWARDED_IPS = 'true' | ||
| expect(getClientIp(request)).toBe('203.0.113.9') | ||
| process.env.TRUST_FORWARDED_IPS = '' | ||
| }) | ||
| }) |
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,112 @@ | ||
| import { internal } from '../_generated/api' | ||
| import type { ActionCtx } from '../_generated/server' | ||
| import { hashToken } from './tokens' | ||
|
|
||
| const RATE_LIMIT_WINDOW_MS = 60_000 | ||
| export const RATE_LIMITS = { | ||
| read: { ip: 120, key: 600 }, | ||
| write: { ip: 30, key: 120 }, | ||
| } as const | ||
|
|
||
| type RateLimitResult = { | ||
| allowed: boolean | ||
| remaining: number | ||
| limit: number | ||
| resetAt: number | ||
| } | ||
|
|
||
| export async function applyRateLimit( | ||
| ctx: ActionCtx, | ||
| request: Request, | ||
| kind: keyof typeof RATE_LIMITS, | ||
| ): Promise<{ ok: true; headers: HeadersInit } | { ok: false; response: Response }> { | ||
| const ip = getClientIp(request) ?? 'unknown' | ||
| const ipResult = await checkRateLimit(ctx, `ip:${ip}`, RATE_LIMITS[kind].ip) | ||
| const token = parseBearerToken(request) | ||
| const keyResult = token | ||
| ? await checkRateLimit(ctx, `key:${await hashToken(token)}`, RATE_LIMITS[kind].key) | ||
| : null | ||
|
|
||
| const chosen = pickMostRestrictive(ipResult, keyResult) | ||
| const headers = rateHeaders(chosen) | ||
|
|
||
| if (!ipResult.allowed || (keyResult && !keyResult.allowed)) { | ||
| return { | ||
| ok: false, | ||
| response: new Response('Rate limit exceeded', { | ||
| status: 429, | ||
| headers: mergeHeaders( | ||
| { | ||
| 'Content-Type': 'text/plain; charset=utf-8', | ||
| 'Cache-Control': 'no-store', | ||
| }, | ||
| headers, | ||
| ), | ||
| }), | ||
| } | ||
| } | ||
|
|
||
| return { ok: true, headers } | ||
| } | ||
|
|
||
| export function getClientIp(request: Request) { | ||
| const header = request.headers.get('cf-connecting-ip') | ||
| if (!header) { | ||
| if (!shouldTrustForwardedIps()) return null | ||
| const forwarded = | ||
| request.headers.get('x-real-ip') ?? | ||
| request.headers.get('x-forwarded-for') ?? | ||
| request.headers.get('fly-client-ip') | ||
| if (!forwarded) return null | ||
| if (forwarded.includes(',')) return forwarded.split(',')[0]?.trim() || null | ||
| return forwarded.trim() | ||
| } | ||
| if (header.includes(',')) return header.split(',')[0]?.trim() || null | ||
| return header.trim() | ||
| } | ||
|
|
||
| async function checkRateLimit( | ||
| ctx: ActionCtx, | ||
| key: string, | ||
| limit: number, | ||
| ): Promise<RateLimitResult> { | ||
| return (await ctx.runMutation(internal.rateLimits.checkRateLimitInternal, { | ||
| key, | ||
| limit, | ||
| windowMs: RATE_LIMIT_WINDOW_MS, | ||
| })) as RateLimitResult | ||
| } | ||
|
|
||
| function pickMostRestrictive(primary: RateLimitResult, secondary: RateLimitResult | null) { | ||
| if (!secondary) return primary | ||
| if (!primary.allowed) return primary | ||
| if (!secondary.allowed) return secondary | ||
| return secondary.remaining < primary.remaining ? secondary : primary | ||
| } | ||
|
|
||
| function rateHeaders(result: RateLimitResult): HeadersInit { | ||
| const resetSeconds = Math.ceil(result.resetAt / 1000) | ||
| return { | ||
| 'X-RateLimit-Limit': String(result.limit), | ||
| 'X-RateLimit-Remaining': String(result.remaining), | ||
| 'X-RateLimit-Reset': String(resetSeconds), | ||
| ...(result.allowed ? {} : { 'Retry-After': String(resetSeconds) }), | ||
| } | ||
| } | ||
|
|
||
| export function parseBearerToken(request: Request) { | ||
| const header = request.headers.get('authorization') ?? request.headers.get('Authorization') | ||
| if (!header) return null | ||
| const trimmed = header.trim() | ||
| if (!trimmed.toLowerCase().startsWith('bearer ')) return null | ||
| const token = trimmed.slice(7).trim() | ||
| return token || null | ||
| } | ||
|
|
||
| function mergeHeaders(base: HeadersInit, extra?: HeadersInit) { | ||
| return { ...(base as Record<string, string>), ...(extra as Record<string, string>) } | ||
| } | ||
|
|
||
| function shouldTrustForwardedIps() { | ||
| return String(process.env.TRUST_FORWARDED_IPS ?? '').toLowerCase() === 'true' | ||
| } | ||
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.