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
101 changes: 99 additions & 2 deletions api/_lib/rateLimit.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { isRateLimited, clientIp } from './rateLimit'
import {
isRateLimited,
isChallengeRateLimited,
isActionRateLimited,
clientIp,
} from './rateLimit'

describe('isRateLimited', () => {
// ---------------------------------------------------------------------------
// Shared helper — all three exported limit functions use the same in-memory
// fallback when KV is not configured, so the core bucket behaviour is covered
// once for the legacy shim and verified for both new functions.
// ---------------------------------------------------------------------------

describe('isRateLimited (legacy shim — delegates to isActionRateLimited)', () => {
afterEach(() => {
vi.useRealTimers()
})
Expand Down Expand Up @@ -41,6 +52,92 @@ describe('isRateLimited', () => {
})
})

// ---------------------------------------------------------------------------
// Issue #1162 — split rate-limit buckets
// ---------------------------------------------------------------------------

describe('split rate-limit buckets (issue #1162)', () => {
afterEach(() => {
vi.useRealTimers()
})

it('isChallengeRateLimited and isActionRateLimited use independent buckets for the same identifier', async () => {
// Use the same string as both an "IP" (challenge) and an "address" (action)
// so we can confirm the two counters are separate KV namespaces.
const shared = `addr-${Math.random()}`

// Exhaust the challenge-issuance bucket for `shared`
// CHALLENGE_MAX_PER_WINDOW defaults to 20; we drive it to the limit.
for (let i = 0; i < 20; i++) {
await isChallengeRateLimited(shared)
}
expect(await isChallengeRateLimited(shared)).toBe(true)

// The action bucket for the same string is untouched — 10 requests must
// all be allowed (ACTION_MAX_PER_WINDOW defaults to 10).
for (let i = 0; i < 10; i++) {
expect(await isActionRateLimited(shared)).toBe(false)
}
})

it('exhausting the action bucket for address A does not affect address A\'s challenge bucket', async () => {
const addr = `addr-${Math.random()}`

// Exhaust the action bucket
for (let i = 0; i < 10; i++) {
await isActionRateLimited(addr)
}
expect(await isActionRateLimited(addr)).toBe(true)

// The challenge bucket for the same string (treated as an IP here) is
// fully independent — first request must still be allowed.
expect(await isChallengeRateLimited(addr)).toBe(false)
})

it('exhausting the action bucket for address A does not block address A from obtaining a challenge (griefing scenario)', async () => {
// Simulate the griefing scenario from issue #1162 in reverse:
// an attacker floods the action bucket for address A. The victim (address
// A) must still be able to obtain a challenge because challenge issuance is
// limited by IP, not by address.
const victimAddress = `GVICTIM${Math.random()}`
const victimIp = `10.0.0.${Math.floor(Math.random() * 255)}`

// Exhaust the action bucket for the victim's address
for (let i = 0; i < 11; i++) {
await isActionRateLimited(victimAddress)
}
expect(await isActionRateLimited(victimAddress)).toBe(true)

// The victim's own IP can still get a challenge
expect(await isChallengeRateLimited(victimIp)).toBe(false)
})

it('attacker flooding challenge endpoint with victim address does NOT exhaust victim action bucket', async () => {
// The core griefing scenario from issue #1162:
// An attacker calls GET /api/auth/challenge?address=<victim> many times.
// With the old shared bucket this exhausted the victim's action quota too.
// After the fix the challenge bucket is keyed on IP; the victim's action
// bucket (keyed on address) must remain untouched.
const attackerIp = `203.0.113.${Math.floor(Math.random() * 255)}`
const victimAddress = `GVICTIM${Math.random()}`

// Attacker exhausts challenge-issuance limit from their IP
for (let i = 0; i < 20; i++) {
await isChallengeRateLimited(attackerIp)
}
expect(await isChallengeRateLimited(attackerIp)).toBe(true)

// Victim's authenticated-action quota is completely unaffected
for (let i = 0; i < 10; i++) {
expect(await isActionRateLimited(victimAddress)).toBe(false)
}
})
})

// ---------------------------------------------------------------------------
// clientIp
// ---------------------------------------------------------------------------

describe('clientIp', () => {
it('reads the rightmost (most trusted) address from x-forwarded-for', () => {
const req = {
Expand Down
106 changes: 84 additions & 22 deletions api/_lib/rateLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,97 @@ import type { VercelRequest } from '@vercel/node'
import { isKvConfigured, kvGet, kvSet } from './kv'

const WINDOW_MS = 15 * 60 * 1000 // 15 minutes
const MAX_REQUESTS_PER_WINDOW = parseInt(process.env.RATE_LIMIT_WINDOW ?? '10', 10)
const MAX_REQUESTS_PER_DAY = parseInt(process.env.RATE_LIMIT_DAY ?? '100', 10)

/**
* Check if a wallet address has exceeded rate limits (window or daily).
* Uses Vercel KV for durable, cross-instance limits.
* Falls back to in-memory tracking if KV is unavailable.
* Challenge-issuance limits (unauthenticated — GET /api/auth/challenge).
*
* The KV REST helpers moved to `./kv` when the challenge store (issue #1091)
* needed the same durable path. Two behavioural notes from that move, both of
* which make this function match the intent its own comment already stated
* ("On error, deny the request (fail closed)"):
* These are intentionally tighter than authenticated-action limits and are
* keyed on the *requester IP*, not the target address, so an attacker who
* knows a victim's public address cannot exhaust the victim's login budget by
* flooding the challenge endpoint (issue #1162).
*
* - A non-2xx read used to be indistinguishable from an empty bucket, so a
* KV outage silently reset every counter and let traffic through. It now
* throws and is caught below.
* - A failed write used to be ignored, leaving the limiter running against
* counters that were never incremented. It now throws too.
* The per-IP window limit is kept low to prevent one host from spamming
* challenges at a high rate. The daily limit is generous enough that
* legitimate multi-device users are never affected.
*/
const CHALLENGE_MAX_PER_WINDOW = parseInt(process.env.CHALLENGE_RATE_LIMIT_WINDOW ?? '20', 10)
const CHALLENGE_MAX_PER_DAY = parseInt(process.env.CHALLENGE_RATE_LIMIT_DAY ?? '200', 10)

/**
* Authenticated-action limits (upload-file, upload-json, unpin).
*
* These are keyed on the wallet address, which is safe because the caller
* has already proved possession of the corresponding private key via the
* challenge→signature flow before reaching these endpoints.
*/
const ACTION_MAX_PER_WINDOW = parseInt(process.env.RATE_LIMIT_WINDOW ?? '10', 10)
const ACTION_MAX_PER_DAY = parseInt(process.env.RATE_LIMIT_DAY ?? '100', 10)

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/**
* Rate-limit check for **challenge issuance** (GET /api/auth/challenge).
*
* Keyed on the requester's IP address so that an attacker who knows a
* victim's Stellar address (a public value) cannot lock the victim out of
* the system by flooding the unauthenticated challenge endpoint (issue #1162).
*
* @param ip Trusted client IP, e.g. from `clientIp(req)`.
*/
export async function isChallengeRateLimited(ip: string): Promise<boolean> {
return _isRateLimited(
`ratelimit:challenge:${ip}`,
CHALLENGE_MAX_PER_WINDOW,
CHALLENGE_MAX_PER_DAY,
)
}

/**
* Rate-limit check for **authenticated actions** (upload-file, upload-json,
* unpin). Keyed on the wallet address, which is safe because possession of
* the corresponding private key has already been proved via the
* challenge→signature flow (issue #1162).
*
* @param address The verified wallet address extracted from the JWT.
*/
export async function isActionRateLimited(address: string): Promise<boolean> {
return _isRateLimited(
`ratelimit:action:${address}`,
ACTION_MAX_PER_WINDOW,
ACTION_MAX_PER_DAY,
)
}

/**
* @deprecated Use `isChallengeRateLimited` or `isActionRateLimited` instead.
*
* Left in place so any external callers that were importing `isRateLimited`
* directly keep compiling. All internal call sites have been migrated to the
* split functions above (issue #1162).
*/
export async function isRateLimited(address: string): Promise<boolean> {
return isActionRateLimited(address)
}

// ---------------------------------------------------------------------------
// Shared implementation
// ---------------------------------------------------------------------------

async function _isRateLimited(
bucketPrefix: string,
maxPerWindow: number,
maxPerDay: number,
): Promise<boolean> {
if (!isKvConfigured()) {
// Fallback: use in-memory (not production-safe)
return isRateLimitedInMemory(address)
return _isRateLimitedInMemory(bucketPrefix, maxPerWindow)
}

try {
const now = Date.now()
const windowKey = `ratelimit:${address}:window`
const dayKey = `ratelimit:${address}:day`
const windowKey = `${bucketPrefix}:window`
const dayKey = `${bucketPrefix}:day`

// Window bucket (15 min rolling)
const windowData = await kvGet(windowKey)
Expand All @@ -41,7 +103,7 @@ export async function isRateLimited(address: string): Promise<boolean> {
await kvSet(windowKey, JSON.stringify({ count: 1, windowStart: now }), 900)
} else {
// Window still active
if (count >= MAX_REQUESTS_PER_WINDOW) return true
if (count >= maxPerWindow) return true
await kvSet(windowKey, JSON.stringify({ count: count + 1, windowStart }), 900)
}
} else {
Expand All @@ -53,7 +115,7 @@ export async function isRateLimited(address: string): Promise<boolean> {
const dayData = await kvGet(dayKey)
if (dayData) {
const { count } = JSON.parse(dayData)
if (count >= MAX_REQUESTS_PER_DAY) return true
if (count >= maxPerDay) return true
await kvSet(dayKey, JSON.stringify({ count: count + 1 }), 86400)
} else {
// First request in this day
Expand All @@ -76,7 +138,7 @@ interface Bucket {

const buckets = new Map<string, Bucket>()

function isRateLimitedInMemory(key: string): Promise<boolean> {
function _isRateLimitedInMemory(key: string, maxPerWindow: number): Promise<boolean> {
const now = Date.now()
const bucket = buckets.get(key)

Expand All @@ -86,7 +148,7 @@ function isRateLimitedInMemory(key: string): Promise<boolean> {
}

bucket.count += 1
return Promise.resolve(bucket.count > MAX_REQUESTS_PER_WINDOW)
return Promise.resolve(bucket.count > maxPerWindow)
}

/**
Expand Down
17 changes: 11 additions & 6 deletions api/auth/challenge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { VercelRequest, VercelResponse } from '@vercel/node'
import { randomBytes } from 'crypto'
import { issueToken, verifyToken } from '../_lib/jwt'
import { deleteChallenge, getChallenge, putChallenge } from '../_lib/challengeStore'
import { isRateLimited } from '../_lib/rateLimit'
import { clientIp, isChallengeRateLimited, isActionRateLimited } from '../_lib/rateLimit'

// Challenge storage — TTL, one-time use and the durable/dev-fallback split all
// live in `../_lib/challengeStore` (issue #1091). It used to be a Map in this
Expand Down Expand Up @@ -36,9 +36,11 @@ async function handleGetChallenge(req: VercelRequest, res: VercelResponse) {
return
}

// Rate limit per address to prevent abuse (challenge issuance has no
// proof-of-possession, so it gets a tighter window than upload endpoints)
if (await isRateLimited(address)) {
// Rate limit by requester IP — not by target address — so an attacker who
// knows a victim's public Stellar address cannot exhaust the victim's login
// budget by flooding this unauthenticated endpoint (issue #1162).
const ip = clientIp(req)
if (await isChallengeRateLimited(ip)) {
res.status(429).json({ error: 'Too many challenge requests. Please try again later.' })
return
}
Expand Down Expand Up @@ -74,8 +76,11 @@ async function handleVerifyChallenge(req: VercelRequest, res: VercelResponse) {
}

// Rate limit per address to prevent brute-force probing of the
// signature-verification path
if (await isRateLimited(address)) {
// signature-verification path. This is keyed on address (proof of
// possession already required to reach here meaningfully) and uses the
// authenticated-action bucket so it is independent of the challenge-issuance
// IP bucket (issue #1162).
if (await isActionRateLimited(address)) {
res.status(429).json({ error: 'Too many verification attempts. Please try again later.' })
return
}
Expand Down
4 changes: 2 additions & 2 deletions api/ipfs/unpin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { VercelRequest, VercelResponse } from '@vercel/node'
import { isRateLimited } from '../_lib/rateLimit'
import { isActionRateLimited } from '../_lib/rateLimit'
import { PINATA_API_URL, pinataHeaders } from '../_lib/pinata'
import { isValidCid } from '../_lib/schemaValidation'
import { verifyToken } from '../_lib/jwt'
Expand Down Expand Up @@ -37,7 +37,7 @@ export default async function handler(req: VercelRequest, res: VercelResponse) {
}

// Check rate limits (per wallet address, durable across instances)
if (await isRateLimited(walletAddress)) {
if (await isActionRateLimited(walletAddress)) {
res.status(429).json({ error: 'Too many requests. Please try again later.' })
return
}
Expand Down
4 changes: 2 additions & 2 deletions api/ipfs/upload-file.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { VercelRequest, VercelResponse } from '@vercel/node'
import Busboy from 'busboy'
import { isRateLimited } from '../_lib/rateLimit'
import { isActionRateLimited } from '../_lib/rateLimit'
import { PINATA_API_URL, pinataHeaders } from '../_lib/pinata'
import { validateFileMagicBytes } from '../_lib/fileValidation'
import { verifyToken } from '../_lib/jwt'
Expand Down Expand Up @@ -87,7 +87,7 @@ export default async function handler(req: VercelRequest, res: VercelResponse) {
}

// Check rate limits (per wallet address, durable across instances)
if (await isRateLimited(walletAddress)) {
if (await isActionRateLimited(walletAddress)) {
res.status(429).json({ error: 'Too many upload requests. Please try again later.' })
return
}
Expand Down
4 changes: 2 additions & 2 deletions api/ipfs/upload-json.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { VercelRequest, VercelResponse } from '@vercel/node'
import { isRateLimited } from '../_lib/rateLimit'
import { isActionRateLimited } from '../_lib/rateLimit'
import { PINATA_API_URL, pinataHeaders } from '../_lib/pinata'
import { validateTokenMetadata } from '../_lib/schemaValidation'
import { verifyToken } from '../_lib/jwt'
Expand Down Expand Up @@ -38,7 +38,7 @@ export default async function handler(req: VercelRequest, res: VercelResponse) {
}

// Check rate limits (per wallet address, durable across instances)
if (await isRateLimited(walletAddress)) {
if (await isActionRateLimited(walletAddress)) {
res.status(429).json({ error: 'Too many upload requests. Please try again later.' })
return
}
Expand Down
Loading
Loading