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]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
15b5c6258d
commit
97c62f21f0
@@ -1241,6 +1241,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
|
||||
| Roles count only for accounts of a staff collection, in every predicate and access function | — | `access.staffCollections` |
|
||||
| `enabled: false` keeps the schema | — | — (no endpoints, `onInit` or admin components; no DROP TABLE in `migrate:create`) |
|
||||
| No client IP = one shared `unknown-ip` bucket at 20× the limit | `setUnknownIpFactor(0)` (only with a limiter in front) | `setUnknownIpFactor(n)`; `UNKNOWN_IP_FACTOR` |
|
||||
| IPv6 counted per /64 in every plugin limiter (1.17.2): one /64 = one client, `::ffff:a.b.c.d` = its IPv4; no /48 counter by default. **Verify:** 50 requests with `X-Real-IP: 2001:db8:1:1::<n>` → `429` after the limit | `setIpv6Grouping({ prefix: 128 })` (per address, as before) | `setIpv6Grouping({ prefix, wide: 48, wideFactor })`; `ipRateKey(ip)` for your own limiter (forms.md "IPv6 is counted per network") |
|
||||
| Turnstile token domain not checked | (default) | `createSubmitAction({ turnstileHostnames })`, `verifyTurnstile({ hostnames })` — leave empty in dev |
|
||||
| Consent Mode `advanced` | `consentMode: 'basic'` | your own `<Analytics>` props (`SiteProviders analytics={false}`) |
|
||||
| Locale cookie: consent read under its own stored version | — | `createProxy(config, { policyVersion })` / `createLocaleMiddleware({ policyVersion })` |
|
||||
|
||||
@@ -746,6 +746,7 @@ Most routes and metadata are already ready in `createContentHelpers` (`generateP
|
||||
| `setRateLimitStore(store \| null)` | `@intecion/ipal-kit` | Shared store (e.g. Redis) for all plugin limiters (forms, consents, MCP…); `null` = process memory. Call once at startup when several instances run. |
|
||||
| `setUnknownIpFactor(n)` | `@intecion/ipal-kit` | Requests with no client IP share one `unknown-ip` bucket with `n` × the limit (every plugin limiter). Call once at startup; `0` = unlimited (only with a limiter in front, e.g. Cloudflare). |
|
||||
| `UNKNOWN_IP_FACTOR` | `@intecion/ipal-kit` | `20` — the default factor of the no-IP bucket. |
|
||||
| `setIpv6Grouping({ prefix?, wide?, wideFactor? })`, `ipRateKey(ip)`, type `Ipv6Grouping` | `@intecion/ipal-kit` | 1.17.2: how every plugin limiter counts IPv6 — default one client per /64 (`prefix: 64`), no wide counter; `wide: 48` adds a counter per /48 at `wideFactor` (10) × the limit; `prefix: 128` = per address. Out-of-range values throw. `ipRateKey`: an IPv4 as it is, `::ffff:a.b.c.d` as the IPv4, an IPv6 as its network (`2001:db8:1:2:0:0:0:0/64`), anything else unchanged. |
|
||||
|
||||
**Types:** `ClientIpOptions` — `clientIp` options; `RateLimitStore` — store contract (`hit(id, cost, windowMs)` → `{ count, resetAt }`).
|
||||
|
||||
|
||||
@@ -436,6 +436,18 @@ A missing IP (the proxy strips the header, a wrong `IAPL_IP_HEADER`) does **not*
|
||||
share one `unknown-ip` bucket with a ×20 limit (`UNKNOWN_IP_FACTOR`) — real
|
||||
visitors get through, a flood without the header does not. `setUnknownIpFactor(n)` (root, once at startup)
|
||||
changes the multiplier; `setUnknownIpFactor(0)` = the old behaviour (no limit), when a limiter sits in front.
|
||||
|
||||
**IPv6 is counted per network (1.17.2).** A host with IPv6 holds a whole /64 — 2^64 addresses, every home
|
||||
connection and every server — so counting per address gave one visitor as many budgets as it had addresses. Every
|
||||
limiter of the plugin (forms, the file upload endpoint, search, MCP, the consent log, stats, the doctor status, the
|
||||
mail service's confirm route and account-mail limit) counts a **/64 as one client**; an IPv4-mapped address
|
||||
(`::ffff:1.2.3.4`) counts as its IPv4. One home network shares the budget, as an IPv4 home behind one router always
|
||||
did. Change it once at start (root export): `setIpv6Grouping({ prefix: 128 })` = per address (as before);
|
||||
`setIpv6Grouping({ prefix: 56 })` another network size; `setIpv6Grouping({ wide: 48, wideFactor: 10 })` adds a
|
||||
second counter per /48 at 10× the limit (a hosting customer often holds a /48 — off by default, because a mobile
|
||||
carrier can put many phones in one /48). A value out of range throws. `ipRateKey(ip)` gives the key a limiter of
|
||||
your own should count by (`consumeRateLimit` already applies it to a key that is an IP address).
|
||||
**Check:** fifty requests to a limited route with `X-Real-IP: 2001:db8:1:1::1` … `::32` → `429` after the limit.
|
||||
Without a pinned header the order
|
||||
`cf-connecting-ip` → `x-real-ip` → XFF stays (switching to XFF-only, from the right, would put every visitor
|
||||
behind Cloudflare into the bucket of the edge node) — that is why `IAPL_IP_HEADER` is mandatory in production
|
||||
|
||||
+2
-1
@@ -570,7 +570,8 @@ export { applyCollectionOverride } from './modules/shared/collectionOverride.js'
|
||||
export type { CollectionOverride } from './modules/shared/collectionOverride.js'
|
||||
// Development addresses by pattern (no env): the built-in list and the matcher behind `developmentHosts`.
|
||||
export { assertDevelopmentHosts, DEFAULT_DEVELOPMENT_HOSTS, isDevelopmentHost, matchDevelopmentHost } from './modules/shared/developmentHosts.js'
|
||||
export { clientIp, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js'
|
||||
export { clientIp, ipRateKey, setIpv6Grouping, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js'
|
||||
export type { Ipv6Grouping } from './modules/shared/rateLimit.js'
|
||||
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
|
||||
export { buildSlugField, toSlug } from './modules/slug/index.js'
|
||||
export { STATS_SLUG } from './modules/stats/index.js'
|
||||
|
||||
@@ -4,7 +4,7 @@ import { createHash, randomBytes } from 'node:crypto'
|
||||
|
||||
import type { ResolvedRelayOptions } from './options.js'
|
||||
|
||||
import { consumeRateLimit } from '../../shared/rateLimit.js'
|
||||
import { consumeRateLimit, ipRateKey } from '../../shared/rateLimit.js'
|
||||
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
|
||||
import { RELAY_DEFAULTS, type RelayStatusCode, relayStatusFor } from './constants.js'
|
||||
import { currentMailKind, type MailKind, mailKindOf, takeExpectedMail } from './kinds.js'
|
||||
@@ -136,7 +136,7 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
const windowMs = (own.windowMinutes ?? RELAY_DEFAULTS.accountMail.windowMinutes) * 60_000
|
||||
const perAddress = own.perAddress ?? RELAY_DEFAULTS.accountMail.perAddress
|
||||
const checks = [
|
||||
...(marked?.visitor ? [{ key: `visitor:${marked.visitor}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []),
|
||||
...(marked?.visitor ? [{ key: `visitor:${ipRateKey(marked.visitor)}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []),
|
||||
...[...(request.to ?? []), ...(request.cc ?? []), ...(request.bcc ?? [])].map((address) => ({ key: `to:${sha256Hex(address.toLowerCase())}`, max: perAddress })),
|
||||
]
|
||||
for (const check of checks) {
|
||||
|
||||
@@ -3,9 +3,11 @@ export {
|
||||
checkRateLimit,
|
||||
clientIp,
|
||||
consumeRateLimit,
|
||||
ipRateKey,
|
||||
retryAfterSeconds,
|
||||
setIpv6Grouping,
|
||||
setRateLimitStore,
|
||||
setUnknownIpFactor,
|
||||
tooManyRequests,
|
||||
} from '../shared/rateLimit.js'
|
||||
export type { ClientIpOptions, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js'
|
||||
export type { ClientIpOptions, Ipv6Grouping, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js'
|
||||
|
||||
+112
-13
@@ -1,3 +1,5 @@
|
||||
import { isIPv4, isIPv6 } from 'node:net'
|
||||
|
||||
import { readEnv } from './envName.js'
|
||||
|
||||
type Bucket = { count: number; resetAt: number }
|
||||
@@ -94,8 +96,95 @@ export function setUnknownIpFactor(factor: number): void {
|
||||
unknownIpFactor = Math.max(0, factor)
|
||||
}
|
||||
|
||||
/**
|
||||
* IPv6 is counted per network, not per address (1.17.2, IAWL idea 9). A host with IPv6 gets a whole /64
|
||||
* (2^64 addresses) — every home connection and every server does — so counting per address gave one visitor
|
||||
* as many budgets as it has addresses. Every limiter of the plugin (forms, search, MCP, consent log, stats,
|
||||
* doctor, the mail service's confirm route and account-mail limit) counts a /64 as one client. One home network
|
||||
* shares the budget then, as an IPv4 home behind one router always did.
|
||||
*
|
||||
* Optionally a second, roomier counter per wider network (`wide: 48`, `wideFactor` × the limit): one hosting
|
||||
* customer often holds a /48 (65,536 /64s). Off by default — mobile carriers can put many phones in one /48.
|
||||
*/
|
||||
export type Ipv6Grouping = {
|
||||
/** Prefix length one client is counted by. Default 64; 128 = per address (as before 1.17.2). 1–128. */
|
||||
prefix?: number
|
||||
/** A second counter per this wider prefix (e.g. 48), at `wideFactor` × the limit. Default: none. */
|
||||
wide?: false | number
|
||||
/** Multiplier for the wide counter's limit. Default 10. */
|
||||
wideFactor?: number
|
||||
}
|
||||
|
||||
let ipv6 = { prefix: 64, wide: 0, wideFactor: 10 }
|
||||
|
||||
/** How every limiter of the plugin counts IPv6 clients (call once at start). `setIpv6Grouping({ prefix: 128 })` = per address. */
|
||||
export function setIpv6Grouping(next: Ipv6Grouping = {}): void {
|
||||
const prefix = next.prefix ?? 64
|
||||
const wide = next.wide === false || next.wide === undefined ? 0 : next.wide
|
||||
const wideFactor = next.wideFactor ?? 10
|
||||
for (const [name, value, min] of [['prefix', prefix, 1], ['wide', wide, 0], ['wideFactor', wideFactor, 1]] as const) {
|
||||
if (!Number.isInteger(value) || value < min || value > (name === 'wideFactor' ? 1e6 : 128)) {
|
||||
throw new Error(`[iapl] setIpv6Grouping: ${name} must be a whole number from ${min}${name === 'wideFactor' ? '' : ' to 128'} (received ${JSON.stringify(value)}).`)
|
||||
}
|
||||
}
|
||||
if (wide && wide >= prefix) {throw new Error(`[iapl] setIpv6Grouping: wide (${wide}) must be a shorter prefix than prefix (${prefix}).`)}
|
||||
ipv6 = { prefix, wide, wideFactor }
|
||||
}
|
||||
|
||||
/** The 8 groups of an IPv6 address as numbers, or null. */
|
||||
function ipv6Groups(address: string): null | number[] {
|
||||
const bare = address.replace(/^\[|\]$/g, '').split('%')[0]
|
||||
if (!isIPv6(bare)) {return null}
|
||||
let text = bare
|
||||
const v4 = /(\d+\.\d+\.\d+\.\d+)$/.exec(text)
|
||||
if (v4) {
|
||||
const [a, b, c, d] = v4[1].split('.').map(Number)
|
||||
text = text.slice(0, -v4[1].length) + `${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`
|
||||
}
|
||||
const [head, tail] = text.includes('::') ? text.split('::') : [text, undefined]
|
||||
const left = head ? head.split(':') : []
|
||||
const right = tail ? tail.split(':') : []
|
||||
const fill = tail === undefined ? [] : Array(8 - left.length - right.length).fill('0')
|
||||
const groups = [...left, ...fill, ...right].map((g) => parseInt(g, 16))
|
||||
return groups.length === 8 && groups.every((g) => Number.isInteger(g) && g >= 0 && g <= 0xffff) ? groups : null
|
||||
}
|
||||
|
||||
/** `2001:db8:1:2::/64` for any address of that network (`bits` = prefix length). */
|
||||
function ipv6Network(groups: number[], bits: number): string {
|
||||
const out = groups.map((g, i) => {
|
||||
const start = i * 16
|
||||
if (start >= bits) {return 0}
|
||||
const keep = Math.min(16, bits - start)
|
||||
return keep === 16 ? g : g & ((0xffff << (16 - keep)) & 0xffff)
|
||||
})
|
||||
return `${out.map((g) => g.toString(16)).join(':')}/${bits}`
|
||||
}
|
||||
|
||||
/**
|
||||
* The key one client is counted by: an IPv4 address as it is, an IPv4-mapped IPv6 address (`::ffff:1.2.3.4`) as
|
||||
* its IPv4, an IPv6 address as its network (`setIpv6Grouping`, default /64). Anything else is returned unchanged.
|
||||
* Use it for a limiter of your own keyed by `clientIp()`.
|
||||
*/
|
||||
export function ipRateKey(ip: string): string {
|
||||
const value = ip.trim()
|
||||
if (!value || isIPv4(value)) {return value}
|
||||
const groups = ipv6Groups(value)
|
||||
if (!groups) {return value}
|
||||
const mapped = groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff
|
||||
if (mapped) {return `${groups[6] >> 8}.${groups[6] & 0xff}.${groups[7] >> 8}.${groups[7] & 0xff}`}
|
||||
return ipv6Network(groups, ipv6.prefix)
|
||||
}
|
||||
|
||||
/** The wide network of an IPv6 key, when the wide counter is on; null otherwise. */
|
||||
function wideKeyOf(ip: string): null | string {
|
||||
if (!ipv6.wide) {return null}
|
||||
const groups = ipv6Groups(ip.trim())
|
||||
if (!groups || (groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff)) {return null}
|
||||
return ipv6Network(groups, ipv6.wide)
|
||||
}
|
||||
|
||||
function resolveKey(key: string, max: number): { key: string; max: number } | null {
|
||||
if (key) {return { key, max }}
|
||||
if (key) {return { key: ipRateKey(key), max }}
|
||||
return unknownIpFactor > 0 ? { key: UNKNOWN_IP_KEY, max: max * unknownIpFactor } : null
|
||||
}
|
||||
|
||||
@@ -125,10 +214,16 @@ export function checkRateLimit({ cost = 1, key: rawKey, max: rawMax = 5, scope =
|
||||
if (!resolved) {return true}
|
||||
const { key, max } = resolved
|
||||
const id = `${scope}:${key}`
|
||||
const current = buckets.get(id)
|
||||
const used = current && current.resetAt > Date.now() ? current.count : 0
|
||||
if (used + cost > max) {return false}
|
||||
const wide = wideKeyOf(rawKey)
|
||||
const wideId = wide ? `${scope}:${wide}` : null
|
||||
const used = (bucketId: string) => {
|
||||
const current = buckets.get(bucketId)
|
||||
return current && current.resetAt > Date.now() ? current.count : 0
|
||||
}
|
||||
if (used(id) + cost > max) {return false}
|
||||
if (wideId && used(wideId) + cost > max * ipv6.wideFactor) {return false}
|
||||
hitMemory(id, cost, windowMs)
|
||||
if (wideId) {hitMemory(wideId, cost, windowMs)}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -149,26 +244,30 @@ export async function consumeRateLimit({
|
||||
if (!resolved) {return { ok: true, retryAfter: 0 }}
|
||||
const { key, max } = resolved
|
||||
const id = `${scope}:${key}`
|
||||
const wide = wideKeyOf(rawKey)
|
||||
|
||||
let bucket: Bucket
|
||||
if (store) {
|
||||
const hit = async (bucketId: string): Promise<Bucket | null> => {
|
||||
if (!store) {return hitMemory(bucketId, cost, windowMs)}
|
||||
try {
|
||||
bucket = await store.hit(id, cost, windowMs)
|
||||
return await store.hit(bucketId, cost, windowMs)
|
||||
} catch (err) {
|
||||
console.warn('[iapl] rate limit store failed, allowing request:', err instanceof Error ? err.message : err)
|
||||
return { ok: true, retryAfter: 0 }
|
||||
return null
|
||||
}
|
||||
} else {
|
||||
bucket = hitMemory(id, cost, windowMs)
|
||||
}
|
||||
const bucket = await hit(id)
|
||||
if (!bucket) {return { ok: true, retryAfter: 0 }}
|
||||
const wideBucket = wide ? await hit(`${scope}:${wide}`) : null
|
||||
|
||||
const retryAfter = Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000))
|
||||
return { ok: bucket.count <= max, retryAfter }
|
||||
const over = [bucket.count > max ? bucket : null, wideBucket && wideBucket.count > max * ipv6.wideFactor ? wideBucket : null].filter((b): b is Bucket => b !== null)
|
||||
const later = over.reduce((at, b) => Math.max(at, b.resetAt), bucket.resetAt)
|
||||
const retryAfter = Math.max(1, Math.ceil(((over.length ? later : bucket.resetAt) - Date.now()) / 1000))
|
||||
return { ok: over.length === 0, retryAfter }
|
||||
}
|
||||
|
||||
/** Seconds until the key's IN-MEMORY window resets — for a Retry-After header. */
|
||||
export function retryAfterSeconds(key: string, scope = 'form'): number {
|
||||
const bucket = buckets.get(`${scope}:${key}`)
|
||||
const bucket = buckets.get(`${scope}:${key ? ipRateKey(key) : UNKNOWN_IP_KEY}`)
|
||||
return bucket ? Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000)) : 1
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* 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])
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user