Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Renew the rate limit session and log the limits as JSON lines (#5836)
Olga Bulat74566aa41b8a
diff --git a/documentation/projects/proposals/proxy_frontend_api_requests/20241202-implementation_plan_proxy_frontend_api_requests_ip.md b/documentation/projects/proposals/proxy_frontend_api_requests/20241202-implementation_plan_proxy_frontend_api_requests_ip.mdindex 7d52929d5..da4595f38 100644--- a/documentation/projects/proposals/proxy_frontend_api_requests/20241202-implementation_plan_proxy_frontend_api_requests_ip.md+++ b/documentation/projects/proposals/proxy_frontend_api_requests/20241202-implementation_plan_proxy_frontend_api_requests_ip.md@@ -229,6 +229,11 @@ should:and `SameSite=Lax`, and have a short maximum age. With `SameSite=Strict`,users arriving from an external link wouldn't send the cookie and would get anew session.+- be replaced with a new session once it is older than half its maximum age, by+ any SSR page or rate-limited request, so that people who keep a tab open for+ longer than the maximum age keep a session. A `/api` request without a valid+ session also starts one. h3 checks a session's age from its creation time, so+ renewing it means starting a new one.### Add the server plugin to initialize the Openverse API client and add it to the event context@@ -353,11 +358,14 @@ Add the [counters](#counters) to the `/api` routes and to the pages that callthe API, using a server middleware. Use a `runtimeConfig` setting to switchbetween logging and enforcing, and start with logging.-- Read the client IP from the `X-Forwarded-For` entry added by our load- balancer. Earlier entries come from the client and can be faked.+- Read the client IP from the `CF-Connecting-IP` header. The load balancer only+ accepts HTTPS from Cloudflare, so clients can't set it themselves.- Identify in-process SSR calls in a way that a client can't fake.- Do not log session values or IP addresses. Log which counter a request hit and- whether it would have been limited.+ whether it would have been limited, as one JSON line, so that CloudWatch Logs+ Insights can query the fields. When a window that went over its limit ends,+ log how many requests it counted and, for the per-IP ceiling, how many+ sessions shared the address.- When enforcing, return a 429 with a `Retry-After` header. The frontend mustshow a clear message for this response, including on SSR pages.diff --git a/frontend/server/middleware/rate-limit.ts b/frontend/server/middleware/rate-limit.tsindex b79fa2213..ccf9ed0d5 100644--- a/frontend/server/middleware/rate-limit.ts+++ b/frontend/server/middleware/rate-limit.ts@@ -2,14 +2,10 @@ import { useRuntimeConfig } from "nitropack/runtime"import {createError,defineEventHandler,- getCookie,+ getRequestHeader,getRequestURL,setResponseHeader,- unsealSession,- type H3Event,- type SessionConfig,} from "h3"-import { logger } from "~~/server/utils/logger"import { isInternalRequest } from "~~/server/utils/proxy"import {getClientIp,@@ -20,26 +16,20 @@ import {type RateLimitConfig,} from "~~/server/utils/rate-limit"-import { getSessionConfig } from "#shared/utils/session"+import { ensureSession, getSessionConfig } from "#shared/utils/session"let limiter: RateLimiter | null = null-let nextSummaryAt = 0-const readSessionId = async (event: H3Event, config: SessionConfig | null) => {- if (!config?.name) {- return null- }- const sealed = getCookie(event, config.name)- if (!sealed) {- return null- }- try {- const session = await unsealSession(event, config, sealed)- return typeof session.id === "string" && session.id ? session.id : null- } catch {- // An expired or forged session is the same as no session.- return null- }+/**+ * Writes one JSON line, so that CloudWatch Logs Insights reads its fields.+ * The logger formats objects over several lines, and each line becomes a+ * separate CloudWatch event. Writing to stdout directly also skips the+ * prefixes that a wrapped `console` adds.+ */+const logRateLimit = (event: string, fields: Record<string, unknown>) => {+ process.stdout.write(+ `${JSON.stringify({ log: "rate-limit", event, ...fields })}\n`+ )}const toRateLimitConfig = (@@ -55,7 +45,8 @@ const toRateLimitConfig = (/*** Limits the proxy routes and the pages that call the API during SSR.* In `log` mode, it only logs the requests that would be limited. Session- * values and IP addresses are never logged.+ * values and IP addresses are never logged, only short hashes that change+ * with every Nuxt process.** In-process SSR requests to the proxy routes are not counted, because their* page load is already counted.@@ -68,38 +59,39 @@ export default defineEventHandler(async (event) => {const runtimeConfig = useRuntimeConfig(event)const config = toRateLimitConfig(runtimeConfig.rateLimit)- limiter ??= new RateLimiter(config.windowSeconds * 1000)+ const enforce = config.mode === "enforce"+ limiter ??= new RateLimiter(config.windowSeconds * 1000, Date.now, (window) =>+ logRateLimit("window", { ...window, enforced: enforce })+ )- const sessionId = await readSessionId(- event,- getSessionConfig(- runtimeConfig.hmacSigningSecret,- runtimeConfig.public.deploymentEnv- )+ const sessionConfig = getSessionConfig(+ runtimeConfig.hmacSigningSecret,+ runtimeConfig.public.deploymentEnv)+ // Before the limits, so that a limited response also renews the session.+ const session = sessionConfig+ ? await ensureSession(event, sessionConfig)+ : { id: null, state: "none" as const }+const ip = getIpRateLimitKey(getClientIp(event))const result = limiter.hit(- getRateLimitChecks({ kind, sessionId, ip, config })+ getRateLimitChecks({ kind, sessionId: session.id, ip, config }))-- const now = Date.now()- if (now >= nextSummaryAt) {- nextSummaryAt = now + config.windowSeconds * 1000- const counts = limiter.takeLimitedCounts()- if (Object.values(counts).some(Boolean)) {- logger.info("Rate limited requests by counter", counts)- }- }-if (!result) {return}- const enforce = config.mode === "enforce"if (result.isFirstExceeded) {- logger.warn("Rate limit exceeded", {+ logRateLimit("exceeded", {counter: result.counter,+ keyHash: result.keyHash,+ limit: result.limit,+ windowSeconds: config.windowSeconds,requestKind: kind,+ session: session.state,+ // Without any cookie, the browser may block cookies.+ hasCookies: Boolean(getRequestHeader(event, "cookie")),+ country: getRequestHeader(event, "cf-ipcountry") ?? null,enforced: enforce,})}diff --git a/frontend/server/utils/rate-limit.ts b/frontend/server/utils/rate-limit.tsindex 01436b612..bcd509b09 100644--- a/frontend/server/utils/rate-limit.ts+++ b/frontend/server/utils/rate-limit.ts@@ -18,15 +18,41 @@ export interface RateLimitCheck {counter: RateLimitCounterkey: stringlimit: number+ /**+ * The session that made the request, for the per-IP ceiling. The window+ * counts how many sessions it saw, to tell a shared address apart from a+ * single client.+ */+ sessionId?: string | null}export interface RateLimitResult {counter: RateLimitCounter+ /**+ * A short hash of the session ID or IP address, which is the same for all+ * the log lines of one key in this process.+ */+ keyHash: string+ limit: numberretryAfterSeconds: number/** Whether this is the first request over the limit in the window. */isFirstExceeded: boolean}+/** A window that went over its limit, reported when it ends. */+export interface ExceededWindow {+ counter: RateLimitCounter+ keyHash: string+ limit: number+ windowSeconds: number+ requests: number+ limitedRequests: number+ /** Only for the per-IP ceiling. */+ sessions?: number+ /** Only for the per-IP ceiling: requests that had no valid session. */+ noSessionRequests?: number+}+const PROXY_ROUTE_PATTERN =/^\/api\/(?:search\/[^/]+|[^/]+\/related\/[^/]+|[^/]+\/[^/]+)\/?$//**@@ -106,9 +132,20 @@ export const getIpRateLimitKey = (ip: string) => {.join(":")}::/64`}+/**+ * The most sessions a window keeps track of, so that a client that sends many+ * session cookies can't use up the memory.+ */+const MAX_TRACKED_SESSIONS = 10_000+interface Window {+ counter: RateLimitCounter+ keyHash: string+ limit: numbercount: numberresetAt: number+ sessions?: Set<string>+ noSessionRequests?: number}/**@@ -117,23 +154,26 @@ interface Window {* 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.+ *+ * Each window that went over its limit is passed to `onExceededWindow` when+ * it ends: when the key's next window starts, or when it's removed.*/export class RateLimiter {private windows = new Map<string, Window>()- private limited: Record<RateLimitCounter, number> = {- session: 0,- "no-session": 0,- ip: 0,- }private nextPruneAt = 0private hashKey = randomBytes(32)constructor(private windowMs: number,- private now: () => number = Date.now+ private now: () => number = Date.now,+ private onExceededWindow: (window: ExceededWindow) => void = () => {}) {}+ private hash(value: string) {+ return createHmac("sha256", this.hashKey).update(value).digest("base64url")+ }+/*** Counts the request in every check and returns the first exceeded limit,* or `null` if the request is under all the limits.@@ -143,20 +183,39 @@ export class RateLimiter {this.prune(now)let result: RateLimitResult | null = null- for (const { counter, key, limit } of checks) {- const windowKey = createHmac("sha256", this.hashKey)- .update(`${counter}:${key}`)- .digest("base64url")+ for (const { counter, key, limit, sessionId } of checks) {+ const keyHash = this.hash(key)+ const windowKey = `${counter}:${keyHash}`let window = this.windows.get(windowKey)if (!window || window.resetAt <= now) {- window = { count: 0, resetAt: now + this.windowMs }+ if (window) {+ this.report(window)+ }+ window = {+ counter,+ keyHash: keyHash.slice(0, 12),+ limit,+ count: 0,+ resetAt: now + this.windowMs,+ }this.windows.set(windowKey, window)}window.count += 1+ if (sessionId !== undefined) {+ if (!sessionId) {+ window.noSessionRequests = (window.noSessionRequests ?? 0) + 1+ } else {+ window.sessions ??= new Set()+ if (window.sessions.size < MAX_TRACKED_SESSIONS) {+ window.sessions.add(this.hash(sessionId))+ }+ }+ }if (!result && window.count > limit) {- this.limited[counter] += 1result = {counter,+ keyHash: window.keyHash,+ limit,retryAfterSeconds: Math.max(Math.ceil((window.resetAt - now) / 1000),1@@ -168,26 +227,36 @@ export class RateLimiter {return result}- /**- * Returns the number of limited requests by counter since the last call,- * and resets them.- */- takeLimitedCounts() {- const counts = { ...this.limited }- this.limited = { session: 0, "no-session": 0, ip: 0 }- return counts- }-get size() {return this.windows.size}+ private report(window: Window) {+ if (window.count <= window.limit) {+ return+ }+ const trackedSessions = window.counter === "ip"+ this.onExceededWindow({+ counter: window.counter,+ keyHash: window.keyHash,+ limit: window.limit,+ windowSeconds: this.windowMs / 1000,+ requests: window.count,+ limitedRequests: window.count - window.limit,+ ...(trackedSessions && {+ sessions: window.sessions?.size ?? 0,+ noSessionRequests: window.noSessionRequests ?? 0,+ }),+ })+ }+private prune(now: number) {if (now < this.nextPruneAt) {return}for (const [key, window] of this.windows) {if (window.resetAt <= now) {+ this.report(window)this.windows.delete(key)}}@@ -228,6 +297,6 @@ export const getRateLimitChecks = ({limit: config.noSessionLimit,})}- checks.push({ counter: "ip", key: ip, limit: config.ipLimit })+ checks.push({ counter: "ip", key: ip, limit: config.ipLimit, sessionId })return checks}diff --git a/frontend/shared/utils/session.ts b/frontend/shared/utils/session.tsindex d3d4de2ed..3602d8d0e 100644--- a/frontend/shared/utils/session.ts+++ b/frontend/shared/utils/session.ts@@ -1,9 +1,20 @@-import { LOCAL, type DeployEnv } from "#shared/constants/deploy-env"+import {+ getCookie,+ unsealSession,+ updateSession,+ type H3Event,+ type SessionConfig,+} from "h3"-import type { SessionConfig } from "h3"+import { LOCAL, type DeployEnv } from "#shared/constants/deploy-env"export const SESSION_NAME = "ovSession"export const SESSION_MAX_AGE_SECONDS = 60 * 60 * 24+/**+ * A session older than this is replaced with a new one, so that people who+ * keep using a tab for longer than the session lifetime keep a session.+ */+export const SESSION_RENEW_AFTER_SECONDS = SESSION_MAX_AGE_SECONDS / 2/*** Used only in the local environment, so that the session works without@@ -40,3 +51,81 @@ export const getSessionConfig = (},}}++/**+ * `none`: the request has no session cookie.+ * `invalid`: the cookie is expired, forged or sealed with another secret.+ */+export type RequestSessionState = "none" | "invalid" | "valid"++export interface RequestSession {+ /** The ID of the valid session that the request came with. */+ id: string | null+ state: RequestSessionState+}++const readRequestSession = async (+ event: H3Event,+ config: SessionConfig+): Promise<{ state: RequestSessionState; id?: string; createdAt?: number }> => {+ const sealed = getCookie(event, SESSION_NAME)+ if (!sealed) {+ return { state: "none" }+ }+ try {+ // Checks the seal and that the session is younger than `maxAge`.+ const { id, createdAt } = await unsealSession(event, config, sealed)+ if (typeof id === "string" && id && typeof createdAt === "number") {+ return { state: "valid", id, createdAt }+ }+ } catch {+ // An expired or forged session is the same as no session.+ }+ return { state: "invalid" }+}++/**+ * Sets a new session cookie on the response. h3 checks a session's age from+ * its creation time, which `updateSession` keeps, so renewing a session means+ * starting a new one with a new ID.+ */+const startSession = async (event: H3Event, config: SessionConfig) => {+ event.context.sessions ??= Object.create(null)+ event.context.sessions![SESSION_NAME] = {+ id: crypto.randomUUID(),+ createdAt: Date.now(),+ data: {},+ }+ await updateSession(event, config)+}++const requestSessions = new WeakMap<H3Event, Promise<RequestSession>>()++/**+ * Returns the session that the request came with, and starts a new one in the+ * response if the request has no valid session, or if its session is older+ * than `SESSION_RENEW_AFTER_SECONDS`.+ *+ * The rate limits count the request by the session it came with, so dropping+ * the cookie to get a new session doesn't help a client avoid them. A client+ * can already get a new session by loading a page; the per-IP ceiling limits+ * all of them together.+ *+ * The result is cached for each request, so the rate limit middleware and the+ * SSR plugin set the cookie at most once.+ */+export const ensureSession = (event: H3Event, config: SessionConfig) => {+ let result = requestSessions.get(event)+ if (!result) {+ result = (async () => {+ const { state, id, createdAt } = await readRequestSession(event, config)+ const renewAt = (createdAt ?? 0) + SESSION_RENEW_AFTER_SECONDS * 1000+ if (state !== "valid" || Date.now() >= renewAt) {+ await startSession(event, config)+ }+ return { id: id ?? null, state }+ })()+ requestSessions.set(event, result)+ }+ return result+}diff --git a/frontend/src/plugins/02.init.server.ts b/frontend/src/plugins/02.init.server.tsindex 320b820de..fb71aa0ae 100644--- a/frontend/src/plugins/02.init.server.ts+++ b/frontend/src/plugins/02.init.server.ts@@ -1,8 +1,6 @@import { defineNuxtPlugin, useCookie, useRuntimeConfig } from "#imports"-import { getSession } from "h3"--import { getSessionConfig } from "#shared/utils/session"+import { ensureSession, getSessionConfig } from "#shared/utils/session"import type { OpenverseCookieState } from "#shared/types/cookies"import { useFeatureFlagStore } from "~/stores/feature-flag"import { useUiStore } from "~/stores/ui"@@ -33,8 +31,8 @@ export default defineNuxtPlugin(async (nuxtApp) => {/* Session */// The anonymous session lets the Nitro rate limits count the requests of- // people who share an IP address separately. `getSession` creates the- // session and sets the cookie if the request doesn't have a valid one.+ // people who share an IP address separately. `ensureSession` sets a new+ // session cookie if the request has no valid session, or an old one.const event = nuxtApp.ssrContext?.eventconst config = useRuntimeConfig()const sessionConfig = getSessionConfig(@@ -42,6 +40,6 @@ export default defineNuxtPlugin(async (nuxtApp) => {config.public.deploymentEnv)if (event && sessionConfig) {- await getSession(event, sessionConfig)+ await ensureSession(event, sessionConfig)}})diff --git a/frontend/test/unit/specs/server/rate-limit.spec.ts b/frontend/test/unit/specs/server/rate-limit.spec.tsindex d134b2adb..924253f92 100644--- a/frontend/test/unit/specs/server/rate-limit.spec.ts+++ b/frontend/test/unit/specs/server/rate-limit.spec.ts@@ -5,6 +5,7 @@ import {getRateLimitChecks,getRateLimitedRequestKind,RateLimiter,+ type ExceededWindow,type RateLimitConfig,} from "~~/server/utils/rate-limit"@@ -114,6 +115,8 @@ describe("RateLimiter", () => {}expect(limiter.hit(checks)).toEqual({counter: "session",+ keyHash: expect.any(String),+ limit: config.sessionLimit,retryAfterSeconds: 60,isFirstExceeded: true,})@@ -146,25 +149,96 @@ describe("RateLimiter", () => {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(),- ])+ const stored = JSON.stringify(+ [...(limiter as unknown as { windows: Map<string, unknown> }).windows],+ (_, value) => (value instanceof Set ? [...value] : value)+ )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)+ it("reports each exceeded window once, when it ends", () => {+ let now = 0+ const reported: ExceededWindow[] = []+ const limiter = new RateLimiter(+ 60_000,+ () => now,+ (window) => reported.push(window)+ )for (let i = 0; i < config.sessionLimit + 2; i++) {limiter.hit(checks)}- expect(limiter.takeLimitedCounts()).toEqual({- session: 2,- "no-session": 0,- ip: 0,+ expect(reported).toEqual([])++ now = 60_000+ limiter.hit(checks)+ expect(reported).toEqual([+ {+ counter: "session",+ keyHash: expect.any(String),+ limit: config.sessionLimit,+ windowSeconds: 60,+ requests: config.sessionLimit + 2,+ limitedRequests: 2,+ },+ ])+ })++ it("does not report windows under the limit", () => {+ let now = 0+ const reported: ExceededWindow[] = []+ const limiter = new RateLimiter(+ 60_000,+ () => now,+ (window) => reported.push(window)+ )+ limiter.hit(checks)+ now = 120_000+ limiter.hit(checks)+ expect(reported).toEqual([])+ })++ it("reports how many sessions shared an exceeded IP window", () => {+ let now = 0+ const reported: ExceededWindow[] = []+ const limiter = new RateLimiter(+ 60_000,+ () => now,+ (window) => reported.push(window)+ )+ const hitAs = (sessionId: string | null) =>+ limiter.hit(+ getRateLimitChecks({ kind: "page", sessionId, ip: "1.1.1.1", config })+ )+ for (const sessionId of ["a", "a", "b", "c", null, null]) {+ hitAs(sessionId)+ }+ now = 60_000+ hitAs("a")+ expect(reported).toEqual([+ expect.objectContaining({+ counter: "ip",+ requests: 6,+ limitedRequests: 1,+ sessions: 3,+ noSessionRequests: 2,+ }),+ ])+ })++ it("uses the same key hash for the counters of one IP address", () => {+ const limiter = new RateLimiter(60_000, () => 0)+ const noSessionChecks = getRateLimitChecks({+ kind: "api",+ sessionId: null,+ ip: "1.1.1.1",+ config: { ...config, ipLimit: 0 },})- expect(limiter.takeLimitedCounts().session).toEqual(0)+ const ipResult = limiter.hit(noSessionChecks)+ expect(ipResult?.counter).toEqual("ip")+ const noSessionResult = limiter.hit(noSessionChecks)+ expect(noSessionResult?.counter).toEqual("no-session")+ expect(noSessionResult?.keyHash).toEqual(ipResult?.keyHash)+ expect(ipResult?.keyHash).not.toContain("1.1.1.1")})})diff --git a/frontend/test/unit/specs/server/session.spec.ts b/frontend/test/unit/specs/server/session.spec.tsnew file mode 100644index 000000000..4edd38448--- /dev/null+++ b/frontend/test/unit/specs/server/session.spec.ts@@ -0,0 +1,107 @@+import { IncomingMessage, ServerResponse } from "node:http"+import { Socket } from "node:net"++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { createEvent, sealSession, type H3Event, type SessionConfig } from "h3"++import {+ ensureSession,+ getSessionConfig,+ SESSION_MAX_AGE_SECONDS,+ SESSION_NAME,+ SESSION_RENEW_AFTER_SECONDS,+} from "#shared/utils/session"++const config = getSessionConfig(+ "a-test-secret-that-is-at-least-32-characters-long",+ "production"+) as SessionConfig++const makeEvent = (cookie?: string) => {+ const req = new IncomingMessage(new Socket())+ if (cookie) {+ req.headers.cookie = cookie+ }+ return createEvent(req, new ServerResponse(req))+}++const getSetCookies = (event: H3Event) =>+ [event.node.res.getHeader("set-cookie") ?? []].flat().map(String)++/** Returns a cookie header with a session sealed `ageSeconds` ago. */+const sessionCookie = async (ageSeconds: number, id = "existing") => {+ const event = makeEvent()+ event.context.sessions = {+ [SESSION_NAME]: {+ id,+ createdAt: Date.now() - ageSeconds * 1000,+ data: {},+ },+ }+ return `${SESSION_NAME}=${await sealSession(event, config)}`+}++describe("ensureSession", () => {+ beforeEach(() => {+ vi.useFakeTimers({ now: new Date("2026-11-19T12:00:00Z") })+ })+ afterEach(() => {+ vi.useRealTimers()+ })++ it("starts a session when the request has none", async () => {+ const event = makeEvent()+ expect(await ensureSession(event, config)).toEqual({+ id: null,+ state: "none",+ })+ const [cookie] = getSetCookies(event)+ expect(cookie).toMatch(new RegExp(`^${SESSION_NAME}=`))+ expect(cookie).toContain("HttpOnly")+ expect(cookie).toContain("Secure")+ })++ it("keeps a session younger than the renewal age", async () => {+ const event = makeEvent(await sessionCookie(60))+ expect(await ensureSession(event, config)).toEqual({+ id: "existing",+ state: "valid",+ })+ expect(getSetCookies(event)).toEqual([])+ })++ it("counts an old session and replaces it with a new one", async () => {+ const event = makeEvent(+ await sessionCookie(SESSION_RENEW_AFTER_SECONDS + 1)+ )+ expect(await ensureSession(event, config)).toEqual({+ id: "existing",+ state: "valid",+ })+ expect(getSetCookies(event)).toHaveLength(1)+ expect(event.context.sessions?.[SESSION_NAME].id).not.toEqual("existing")+ })++ it.each`+ name | cookie+ ${"expired"} | ${() => sessionCookie(SESSION_MAX_AGE_SECONDS + 1)}+ ${"forged"} | ${() => Promise.resolve(`${SESSION_NAME}=forged`)}+ `(+ "treats an $name session as invalid and starts a new one",+ async ({ cookie }) => {+ const event = makeEvent(await cookie())+ expect(await ensureSession(event, config)).toEqual({+ id: null,+ state: "invalid",+ })+ expect(getSetCookies(event)).toHaveLength(1)+ }+ )++ it("sets the cookie only once for a request", async () => {+ const event = makeEvent()+ await ensureSession(event, config)+ await ensureSession(event, config)+ expect(getSetCookies(event)).toHaveLength(1)+ })+})