Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Proxy API requests in production and limit page loads by session (#5883)
Olga Bulat8f7d19b105d4
diff --git a/frontend/feat/feature-flags.json b/frontend/feat/feature-flags.jsonindex 0d0c74f22..da4bc1b60 100644--- a/frontend/feat/feature-flags.json+++ b/frontend/feat/feature-flags.json@@ -43,7 +43,7 @@"proxy_requests": {"status": {"staging": "switchable",- "production": "disabled"+ "production": "enabled"},"description": "Proxy frontend requests through Nuxt server","defaultState": "off",diff --git a/frontend/nuxt.config.ts b/frontend/nuxt.config.tsindex 7c6ccbbfb..a2bdc20d4 100644--- a/frontend/nuxt.config.ts+++ b/frontend/nuxt.config.ts@@ -71,6 +71,12 @@ export default defineNuxtConfig({sessionLimit: 120,noSessionLimit: 30,ipLimit: 1200,+ // Server-rendered page loads per session. After the first page, people+ // navigate in the browser, so few of their pages load from the server.+ sessionPageLimit: 20,+ // Page loads without a session that one Nuxt task renders per window,+ // from all clients together. Every new visitor's first page counts here.+ noSessionPageLimit: 600,},public: {deploymentEnv: "local",diff --git a/frontend/server/middleware/rate-limit.ts b/frontend/server/middleware/rate-limit.tsindex 6ec0a789b..75c30d743 100644--- a/frontend/server/middleware/rate-limit.ts+++ b/frontend/server/middleware/rate-limit.ts@@ -62,10 +62,15 @@ const toRateLimitConfig = (sessionLimit: Number(config.sessionLimit),noSessionLimit: Number(config.noSessionLimit),ipLimit: Number(config.ipLimit),+ sessionPageLimit: Number(config.sessionPageLimit),+ noSessionPageLimit: Number(config.noSessionPageLimit),})/*** Limits the proxy routes and the pages that call the API during SSR.+ * Page loads without a session share one budget per Nuxt task, so that a+ * crawler spread over many IP addresses can't make SSR call the API without+ * a bound. Past it, they get a 503 before SSR starts.* In `log` mode, it only logs the requests that would be limited. Session* values and IP addresses are never logged, only short hashes that change* with every Nuxt process.@@ -125,9 +130,12 @@ export default defineEventHandler(async (event) => {}setResponseHeader(event, "Retry-After", result.retryAfterSeconds)+ // The shared budget limits the server, not the client, so it answers like+ // an overloaded server. It rejects the request before SSR calls the API.+ const overloaded = result.counter === "no-session-page"throw createError({- statusCode: 429,- statusMessage: "Too Many Requests",+ statusCode: overloaded ? 503 : 429,+ statusMessage: overloaded ? "Service Unavailable" : "Too Many Requests",data: { retryAfter: result.retryAfterSeconds },})})diff --git a/frontend/server/utils/rate-limit.ts b/frontend/server/utils/rate-limit.tsindex 7abc51567..54ec02b5b 100644--- a/frontend/server/utils/rate-limit.ts+++ b/frontend/server/utils/rate-limit.ts@@ -3,7 +3,12 @@ import { isIPv6 } from "node:net"import { getRequestHeader, getRequestIP, type H3Event } from "h3"-export type RateLimitCounter = "session" | "no-session" | "ip"+export type RateLimitCounter =+ | "session"+ | "session-page"+ | "no-session"+ | "no-session-page"+ | "ip"export type RateLimitedRequestKind = "api" | "page"export interface RateLimitConfig {@@ -12,6 +17,13 @@ export interface RateLimitConfig {sessionLimit: numbernoSessionLimit: numberipLimit: number+ /** Server-rendered page loads per session. */+ sessionPageLimit: number+ /**+ * Page loads without a session that one Nuxt task renders in a window,+ * from all clients together.+ */+ noSessionPageLimit: number}export interface RateLimitCheck {@@ -292,12 +304,22 @@ export class RateLimiter {}}+/**+ * The key of the counter that all the page loads without a session share.+ */+const NO_SESSION_PAGE_KEY = "all"+/*** Returns the counters that a request is counted by.* - A request with a session counts toward its session limit.+ * - A page load with a session also counts toward its low page limit, because+ * after the first page, people navigate without loading pages from the+ * server.* - An `/api` request without a session counts toward the low per-IP limit.- * - A page load without a session counts only toward the per-IP ceiling,- * because every new visitor arrives this way.+ * - A page load without a session counts toward a budget that all such page+ * loads share, because every new visitor arrives this way, and a crawler+ * that spreads its requests over many IP addresses stays under any per-IP+ * limit.* - Every request counts toward the per-IP ceiling.*/export const getRateLimitChecks = ({@@ -318,12 +340,25 @@ export const getRateLimitChecks = ({key: sessionId,limit: config.sessionLimit,})+ if (kind === "page") {+ checks.push({+ counter: "session-page",+ key: sessionId,+ limit: config.sessionPageLimit,+ })+ }} else if (kind === "api") {checks.push({counter: "no-session",key: ip,limit: config.noSessionLimit,})+ } else {+ checks.push({+ counter: "no-session-page",+ key: NO_SESSION_PAGE_KEY,+ limit: config.noSessionPageLimit,+ })}checks.push({ counter: "ip", key: ip, limit: config.ipLimit, sessionId })return checksdiff --git a/frontend/test/unit/specs/server/rate-limit.spec.ts b/frontend/test/unit/specs/server/rate-limit.spec.tsindex 368109b6c..64bd3d9a6 100644--- a/frontend/test/unit/specs/server/rate-limit.spec.ts+++ b/frontend/test/unit/specs/server/rate-limit.spec.ts@@ -17,6 +17,8 @@ const config: RateLimitConfig = {sessionLimit: 3,noSessionLimit: 1,ipLimit: 5,+ sessionPageLimit: 2,+ noSessionPageLimit: 3,}const eventWithHeaders = (headers: Record<string, string>) =>@@ -84,8 +86,8 @@ describe("getRateLimitChecks", () => {kind | sessionId | expected${"api"} | ${"s1"} | ${["session", "ip"]}${"api"} | ${null} | ${["no-session", "ip"]}- ${"page"} | ${"s1"} | ${["session", "ip"]}- ${"page"} | ${null} | ${["ip"]}+ ${"page"} | ${"s1"} | ${["session", "session-page", "ip"]}+ ${"page"} | ${null} | ${["no-session-page", "ip"]}`("counts $kind requests with session $sessionId by $expected",({ kind, sessionId, expected }) => {