Files
ipal-kit/test/rateLimitIpv6.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 97c62f21f0 Every plugin limiter counts IPv6 per /64 (setIpv6Grouping)
clientIp() returns the whole IPv6 address and every limiter keyed on it, so
one host with a /64 had 2^64 budgets: 50 addresses of one /64 against a
limit of 5 all passed (IAWL idea 9, owner's Q4). consumeRateLimit and
checkRateLimit now count an IPv6 key by its /64 (an IPv4-mapped address by
its IPv4); the mail service's per-visitor account-mail key too. A second
counter per /48 at 10x the limit is available and off by default
(setIpv6Grouping({ wide: 48 })); setIpv6Grouping({ prefix: 128 }) counts
per address as before. ipRateKey(ip) is exported for own limiters.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 10:42:02 +01:00

106 lines
4.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* IPv6 is counted per network (1.17.2, IAWL idea 9): a /64 is one client in every limiter of the plugin; a second
* counter per /48 when a project turns it on (`setIpv6Grouping({ wide: 48 })`).
*/
import { afterEach, describe, expect, test, vi } from 'vitest'
import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js'
import { passRateLimit } from '../src/modules/forms/submitForm.js'
import { checkRateLimit, clientIp, consumeRateLimit, ipRateKey, setIpv6Grouping } from '../src/modules/shared/rateLimit.js'
vi.mock('server-only', () => ({}))
let scope = 0
const nextScope = () => `ipv6-test-${++scope}`
const hex = (n: number) => n.toString(16)
afterEach(() => setIpv6Grouping())
describe('ipRateKey', () => {
test('one key for every address of a /64, whatever the spelling', () => {
const key = ipRateKey('2001:db8:1:2::1')
expect(key).toBe('2001:db8:1:2:0:0:0:0/64')
for (const a of ['2001:db8:1:2:ffff:ffff:ffff:ffff', '2001:0DB8:0001:0002:0000:0000:0000:0042', '[2001:db8:1:2::9]', '2001:db8:1:2::9%eth0']) {
expect([a, ipRateKey(a)]).toEqual([a, key])
}
expect(ipRateKey('2001:db8:1:3::1')).not.toBe(key)
})
test('IPv4 as it is; an IPv4-mapped IPv6 address is its IPv4; anything else unchanged', () => {
expect(ipRateKey('198.51.100.7')).toBe('198.51.100.7')
expect(ipRateKey('::ffff:198.51.100.7')).toBe('198.51.100.7')
expect(ipRateKey('::ffff:c633:6407')).toBe('198.51.100.7')
expect(ipRateKey('')).toBe('')
expect(ipRateKey('not-an-ip')).toBe('not-an-ip')
})
test('setIpv6Grouping: per address again, another prefix; nonsense is refused', () => {
setIpv6Grouping({ prefix: 128 })
expect(ipRateKey('2001:db8::1')).not.toBe(ipRateKey('2001:db8::2'))
setIpv6Grouping({ prefix: 56 })
expect(ipRateKey('2001:db8:0:ff::1')).toBe(ipRateKey('2001:db8:0:1::1'))
expect(() => setIpv6Grouping({ prefix: 0 })).toThrow(/prefix must be/)
expect(() => setIpv6Grouping({ prefix: '64' as never })).toThrow(/prefix must be/)
expect(() => setIpv6Grouping({ prefix: 48, wide: 56 })).toThrow(/shorter prefix/)
})
})
describe('the limiters count a /64 as one client', () => {
test('consumeRateLimit: fifty addresses of one /64 get five requests, not fifty', async () => {
const s = nextScope()
let allowed = 0
for (let i = 1; i <= 50; i++) {
if ((await consumeRateLimit({ key: clientIp(new Headers({ 'x-real-ip': `2001:db8:1:1::${hex(i)}` })), max: 5, scope: s })).ok) {allowed++}
}
expect(allowed).toBe(5)
// another /64 of the same /48 is another client (the wide counter is off by default)
expect((await consumeRateLimit({ key: '2001:db8:1:2::1', max: 5, scope: s })).ok).toBe(true)
})
test('checkRateLimit (the synchronous one) too', () => {
const s = nextScope()
const results = Array.from({ length: 8 }, (_, i) => checkRateLimit({ key: `2001:db8:9:9::${hex(i + 1)}`, max: 3, scope: s }))
expect(results.filter(Boolean)).toHaveLength(3)
})
test('the forms gate (passRateLimit)', async () => {
const results = []
for (let i = 1; i <= 8; i++) {results.push(await passRateLimit({ ip: `2001:db8:abcd:1::${hex(i)}`, maxPerMinute: 5 }))}
expect(results.filter((r) => r === null)).toHaveLength(5)
expect(results[7]).toMatchObject({ reason: 'rate_limited' })
})
test('a plugin endpoint (the consent log, 20 a minute): the 21st address of one /64 gets 429', async () => {
const { handler } = buildConsentLogEndpoint()
const statuses: number[] = []
for (let i = 1; i <= 21; i++) {
const req = { headers: new Headers({ 'x-real-ip': `2001:db8:feed:1::${hex(i)}` }), text: () => Promise.resolve('{') }
statuses.push((await (handler as (r: never) => Promise<Response>)(req as never)).status)
}
expect(statuses.slice(0, 20)).not.toContain(429)
expect(statuses[20]).toBe(429)
})
})
describe('the wide counter (setIpv6Grouping({ wide: 48 }))', () => {
test('three hundred /64s of one /48: at most wideFactor × max requests', async () => {
setIpv6Grouping({ wide: 48, wideFactor: 10 })
const s = nextScope()
let allowed = 0
for (let i = 1; i <= 300; i++) {
if ((await consumeRateLimit({ key: `2001:db8:7:${hex(i)}::1`, max: 5, scope: s })).ok) {allowed++}
}
expect(allowed).toBe(50)
// another /48 is untouched
expect((await consumeRateLimit({ key: '2001:db8:8:1::1', max: 5, scope: s })).ok).toBe(true)
})
test('IPv4 is not affected by it', async () => {
setIpv6Grouping({ wide: 48 })
const s = nextScope()
const ok = []
for (let i = 1; i <= 6; i++) {ok.push((await consumeRateLimit({ key: `198.51.100.${i}`, max: 1, scope: s })).ok)}
expect(ok).toEqual([true, true, true, true, true, true])
})
})