Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Rate limit by CF-Connecting-IP and store only HMACs of the keys (#5796)
Olga Bulat6b810063fac0
diff --git a/frontend/nuxt.config.ts b/frontend/nuxt.config.tsindex 5fc23e71c..7a6b9366e 100644--- a/frontend/nuxt.config.ts+++ b/frontend/nuxt.config.ts@@ -71,8 +71,6 @@ export default defineNuxtConfig({sessionLimit: 120,noSessionLimit: 30,ipLimit: 1200,- // The number of proxies that append to `X-Forwarded-For`.- trustedProxies: 1,},public: {deploymentEnv: "local",diff --git a/frontend/server/middleware/rate-limit.ts b/frontend/server/middleware/rate-limit.tsindex 48834b275..b79fa2213 100644--- a/frontend/server/middleware/rate-limit.ts+++ b/frontend/server/middleware/rate-limit.ts@@ -13,6 +13,7 @@ import { logger } from "~~/server/utils/logger"import { isInternalRequest } from "~~/server/utils/proxy"import {getClientIp,+ getIpRateLimitKey,getRateLimitChecks,getRateLimitedRequestKind,RateLimiter,@@ -49,7 +50,6 @@ const toRateLimitConfig = (sessionLimit: Number(config.sessionLimit),noSessionLimit: Number(config.noSessionLimit),ipLimit: Number(config.ipLimit),- trustedProxies: Number(config.trustedProxies),})/**@@ -77,7 +77,7 @@ export default defineEventHandler(async (event) => {runtimeConfig.public.deploymentEnv))- const ip = getClientIp(event, config.trustedProxies)+ const ip = getIpRateLimitKey(getClientIp(event))const result = limiter.hit(getRateLimitChecks({ kind, sessionId, ip, config }))diff --git a/frontend/server/utils/rate-limit.ts b/frontend/server/utils/rate-limit.tsindex b7a4ac5eb..01436b612 100644--- a/frontend/server/utils/rate-limit.ts+++ b/frontend/server/utils/rate-limit.ts@@ -1,3 +1,6 @@+import { createHmac, randomBytes } from "node:crypto"+import { isIPv6 } from "node:net"+import { getRequestHeader, getRequestIP, type H3Event } from "h3"export type RateLimitCounter = "session" | "no-session" | "ip"@@ -9,7 +12,6 @@ export interface RateLimitConfig {sessionLimit: numbernoSessionLimit: numberipLimit: number- trustedProxies: number}export interface RateLimitCheck {@@ -51,23 +53,57 @@ export const getRateLimitedRequestKind = (}/**- * Returns the client IP address from the `X-Forwarded-For` entry added by the- * closest trusted proxy, our load balancer. The earlier entries come from the- * client and can be faked.+ * Returns the client IP address that Cloudflare sets in `CF-Connecting-IP`.+ * The load balancer only accepts requests from Cloudflare, so clients cannot+ * set this header themselves. Without Cloudflare, for example locally, it+ * falls back to the socket address.*/-export const getClientIp = (event: H3Event, trustedProxies: number) => {- const forwardedFor = getRequestHeader(event, "x-forwarded-for")- if (forwardedFor && trustedProxies > 0) {- const entries = forwardedFor- .split(",")- .map((entry) => entry.trim())- .filter(Boolean)- const entry = entries[Math.max(entries.length - trustedProxies, 0)]- if (entry) {- return entry- }+export const getClientIp = (event: H3Event) =>+ getRequestHeader(event, "cf-connecting-ip")?.trim() ||+ getRequestIP(event) ||+ "unknown"++const expandIpv6 = (address: string) => {+ const toGroups = (part: string) =>+ part+ ? part.split(":").flatMap((group) => {+ if (!group.includes(".")) {+ return [parseInt(group, 16)]+ }+ const [a, b, c, d] = group.split(".").map(Number)+ return [(a << 8) | b, (c << 8) | d]+ })+ : []+ const [head, tail] = address.split("::")+ const headGroups = toGroups(head)+ if (tail === undefined) {+ return headGroups}- return getRequestIP(event) ?? "unknown"+ const tailGroups = toGroups(tail)+ const zeros = Array(8 - headGroups.length - tailGroups.length).fill(0)+ return [...headGroups, ...zeros, ...tailGroups]+}++/**+ * Returns the address that the per-IP limits count by. An IPv6 client usually+ * gets a whole /64 network, so it is counted by its /64 prefix and cannot get+ * around the limits by changing addresses inside it.+ */+export const getIpRateLimitKey = (ip: string) => {+ const address = ip.split("%")[0]+ if (!isIPv6(address)) {+ return ip+ }+ const groups = expandIpv6(address)+ if (+ groups.slice(0, 6).every((group, i) => group === (i === 5 ? 0xffff : 0))+ ) {+ return `${groups[6] >> 8}.${groups[6] & 0xff}.${groups[7] >> 8}.${groups[7] & 0xff}`+ }+ return `${groups+ .slice(0, 4)+ .map((group) => group.toString(16))+ .join(":")}::/64`}interface Window {@@ -77,7 +113,10 @@ interface Window {/*** In-memory fixed-window counters. They are per Nuxt task, so the limits are- * approximate. Keys are kept only until their window ends.+ * approximate. Session IDs and IP addresses are never stored: the counters+ * are keyed by their HMAC with a random key that is generated for each+ * limiter and never leaves the process. Expired counters are removed at the+ * first request after the end of the next window.*/export class RateLimiter {private windows = new Map<string, Window>()@@ -88,6 +127,8 @@ export class RateLimiter {}private nextPruneAt = 0+ private hashKey = randomBytes(32)+constructor(private windowMs: number,private now: () => number = Date.now@@ -103,7 +144,9 @@ export class RateLimiter {let result: RateLimitResult | null = nullfor (const { counter, key, limit } of checks) {- const windowKey = `${counter}:${key}`+ const windowKey = createHmac("sha256", this.hashKey)+ .update(`${counter}:${key}`)+ .digest("base64url")let window = this.windows.get(windowKey)if (!window || window.resetAt <= now) {window = { count: 0, resetAt: now + this.windowMs }diff --git a/frontend/test/unit/specs/server/rate-limit.spec.ts b/frontend/test/unit/specs/server/rate-limit.spec.tsindex 75e34a524..d134b2adb 100644--- a/frontend/test/unit/specs/server/rate-limit.spec.ts+++ b/frontend/test/unit/specs/server/rate-limit.spec.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest"import {getClientIp,+ getIpRateLimitKey,getRateLimitChecks,getRateLimitedRequestKind,RateLimiter,@@ -15,7 +16,6 @@ const config: RateLimitConfig = {sessionLimit: 3,noSessionLimit: 1,ipLimit: 5,- trustedProxies: 1,}const eventWithHeaders = (headers: Record<string, string>) =>@@ -47,21 +47,34 @@ describe("getRateLimitedRequestKind", () => {})describe("getClientIp", () => {- it("uses the entry added by the trusted proxy", () => {+ it("uses the address that Cloudflare sets", () => {const event = eventWithHeaders({- "x-forwarded-for": "1.1.1.1, 2.2.2.2, 3.3.3.3",+ "cf-connecting-ip": "1.1.1.1",+ "x-forwarded-for": "2.2.2.2, 1.1.1.1, 3.3.3.3",})- expect(getClientIp(event, 1)).toEqual("3.3.3.3")- expect(getClientIp(event, 2)).toEqual("2.2.2.2")+ expect(getClientIp(event)).toEqual("1.1.1.1")})- it("does not go past the first entry", () => {- const event = eventWithHeaders({ "x-forwarded-for": "1.1.1.1" })- expect(getClientIp(event, 3)).toEqual("1.1.1.1")+ it("ignores X-Forwarded-For without the Cloudflare header", () => {+ const event = eventWithHeaders({ "x-forwarded-for": "2.2.2.2" })+ expect(getClientIp(event)).toEqual("10.0.0.1")})+})- it("falls back to the socket address without the header", () => {- expect(getClientIp(eventWithHeaders({}), 1)).toEqual("10.0.0.1")+describe("getIpRateLimitKey", () => {+ it.each`+ ip | expected+ ${"203.0.113.7"} | ${"203.0.113.7"}+ ${"2001:db8:85a3:12:8a2e:370:7334:1"} | ${"2001:db8:85a3:12::/64"}+ ${"2001:DB8:85A3:0012::1"} | ${"2001:db8:85a3:12::/64"}+ ${"2001:db8::1"} | ${"2001:db8:0:0::/64"}+ ${"1::2:3:4:5:6:7"} | ${"1:0:2:3::/64"}+ ${"fe80::1%eth0"} | ${"fe80:0:0:0::/64"}+ ${"::ffff:203.0.113.7"} | ${"203.0.113.7"}+ ${"64:ff9b::203.0.113.7"} | ${"64:ff9b:0:0::/64"}+ ${"unknown"} | ${"unknown"}+ `("counts $ip as $expected", ({ ip, expected }) => {+ expect(getIpRateLimitKey(ip)).toEqual(expected)})})@@ -130,6 +143,18 @@ describe("RateLimiter", () => {expect(limiter.size).toEqual(2)})+ it("does not store session IDs or IP addresses", () => {+ const limiter = new RateLimiter(60_000, () => 0)+ limiter.hit(checks)+ const stored = JSON.stringify([+ ...(+ limiter as unknown as { windows: Map<string, unknown> }+ ).windows.keys(),+ ])+ expect(stored).not.toContain("s1")+ expect(stored).not.toContain("1.1.1.1")+ })+it("reports the limited requests by counter", () => {const limiter = new RateLimiter(60_000, () => 0)for (let i = 0; i < config.sessionLimit + 2; i++) {