Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Bound the session seals and correct the rate limit window logs (#5844)
Olga Bulate4e81cd417ce
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 da4595f38..0e546387c 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@@ -232,8 +232,10 @@ should:- be replaced with a new session once it is older than half its maximum age, byany SSR page or rate-limited request, so that people who keep a tab open forlonger 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.+ session also starts one, unless the limits reject it. h3 checks a session's+ age from its creation time, so renewing it means starting a new one. The new+ session's ID is derived from the old one, so that requests sent together renew+ it to the same session.### Add the server plugin to initialize the Openverse API client and add it to the event context@@ -363,9 +365,9 @@ between logging and enforcing, and start with logging.- 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 andwhether 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.+ Insights can query the fields. After a window that went over its limit ends,+ log when it ended, how many requests it counted, how many of them this counter+ limited 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 ccf9ed0d5..6ec0a789b 100644--- a/frontend/server/middleware/rate-limit.ts+++ b/frontend/server/middleware/rate-limit.ts@@ -1,4 +1,4 @@-import { useRuntimeConfig } from "nitropack/runtime"+import { useNitroApp, useRuntimeConfig } from "nitropack/runtime"import {createError,defineEventHandler,@@ -16,7 +16,11 @@ import {type RateLimitConfig,} from "~~/server/utils/rate-limit"-import { ensureSession, getSessionConfig } from "#shared/utils/session"+import {+ getRequestSession,+ getSessionConfig,+ renewSession,+} from "#shared/utils/session"let limiter: RateLimiter | null = null@@ -32,6 +36,24 @@ const logRateLimit = (event: string, fields: Record<string, unknown>) => {)}+/**+ * The exceeded windows are logged after they end. The timer logs them within+ * one more window on a task that gets no more requests, and the `close` hook+ * logs the open ones before the task stops.+ */+const createLimiter = (windowMs: number, enforced: boolean) => {+ const created = new RateLimiter(windowMs, Date.now, (window) =>+ logRateLimit("window", { ...window, enforced })+ )+ const timer = setInterval(() => created.prune(), windowMs)+ timer.unref()+ useNitroApp().hooks.hookOnce("close", () => {+ clearInterval(timer)+ created.flush()+ })+ return created+}+const toRateLimitConfig = (config: Record<string, unknown>): RateLimitConfig => ({@@ -60,23 +82,26 @@ export default defineEventHandler(async (event) => {const runtimeConfig = useRuntimeConfig(event)const config = toRateLimitConfig(runtimeConfig.rateLimit)const enforce = config.mode === "enforce"- limiter ??= new RateLimiter(config.windowSeconds * 1000, Date.now, (window) =>- logRateLimit("window", { ...window, enforced: enforce })- )+ limiter ??= createLimiter(config.windowSeconds * 1000, enforce)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)+ ? await getRequestSession(event, sessionConfig): { id: null, state: "none" as const }const ip = getIpRateLimitKey(getClientIp(event))const result = limiter.hit(getRateLimitChecks({ kind, sessionId: session.id, ip, config }))+ const isRejected = Boolean(result) && enforce+ // A rejected request doesn't start a session, so that a flood of requests+ // without a session costs nothing more than counting them.+ if (sessionConfig && !isRejected) {+ await renewSession(event, sessionConfig)+ }if (!result) {return}diff --git a/frontend/server/utils/rate-limit.ts b/frontend/server/utils/rate-limit.tsindex bcd509b09..7abc51567 100644--- a/frontend/server/utils/rate-limit.ts+++ b/frontend/server/utils/rate-limit.ts@@ -45,7 +45,14 @@ export interface ExceededWindow {keyHash: stringlimit: numberwindowSeconds: number+ /** When the window ended, because it is reported later than that. */+ windowEnd: stringrequests: number+ /**+ * The requests that this counter limited. A request over several limits is+ * counted only by the first one, so the sum over the windows is the number+ * of limited requests.+ */limitedRequests: number/** Only for the per-IP ceiling. */sessions?: number@@ -143,6 +150,7 @@ interface Window {keyHash: stringlimit: numbercount: number+ limited: numberresetAt: numbersessions?: Set<string>noSessionRequests?: number@@ -155,8 +163,9 @@ interface Window {* 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.+ * Each window that went over its limit is passed to `onExceededWindow` after+ * it ends: when the key's next window starts, or when it's removed by `prune`+ * or `flush`.*/export class RateLimiter {private windows = new Map<string, Window>()@@ -180,7 +189,9 @@ export class RateLimiter {*/hit(checks: RateLimitCheck[]): RateLimitResult | null {const now = this.now()- this.prune(now)+ if (now >= this.nextPruneAt) {+ this.prune()+ }let result: RateLimitResult | null = nullfor (const { counter, key, limit, sessionId } of checks) {@@ -196,6 +207,7 @@ export class RateLimiter {keyHash: keyHash.slice(0, 12),limit,count: 0,+ limited: 0,resetAt: now + this.windowMs,}this.windows.set(windowKey, window)@@ -212,6 +224,7 @@ export class RateLimiter {}}if (!result && window.count > limit) {+ window.limited += 1result = {counter,keyHash: window.keyHash,@@ -241,8 +254,9 @@ export class RateLimiter {keyHash: window.keyHash,limit: window.limit,windowSeconds: this.windowMs / 1000,+ windowEnd: new Date(window.resetAt).toISOString(),requests: window.count,- limitedRequests: window.count - window.limit,+ limitedRequests: window.limited,...(trackedSessions && {sessions: window.sessions?.size ?? 0,noSessionRequests: window.noSessionRequests ?? 0,@@ -250,10 +264,13 @@ export class RateLimiter {})}- private prune(now: number) {- if (now < this.nextPruneAt) {- return- }+ /**+ * Removes the windows that ended. `hit` does this at most once per window;+ * calling it on a timer reports the exceeded windows of a task that gets no+ * more requests.+ */+ prune() {+ const now = this.now()for (const [key, window] of this.windows) {if (window.resetAt <= now) {this.report(window)@@ -262,6 +279,17 @@ export class RateLimiter {}this.nextPruneAt = now + this.windowMs}++ /**+ * Removes all the windows, including the ones that have not ended, so that+ * the exceeded ones are reported before the process stops.+ */+ flush() {+ for (const window of this.windows.values()) {+ this.report(window)+ }+ this.windows.clear()+ }}/**diff --git a/frontend/shared/utils/session.ts b/frontend/shared/utils/session.tsindex 3602d8d0e..67569a76f 100644--- a/frontend/shared/utils/session.ts+++ b/frontend/shared/utils/session.ts@@ -64,24 +64,67 @@ export interface RequestSession {state: RequestSessionState}-const readRequestSession = async (+interface ReadSession extends RequestSession {+ createdAt?: number+}++const requestSessions = new WeakMap<H3Event, Promise<ReadSession>>()+const sessionRenewals = new WeakMap<H3Event, Promise<void>>()++const unsealRequestSession = async (event: H3Event,config: SessionConfig-): Promise<{ state: RequestSessionState; id?: string; createdAt?: number }> => {+): Promise<ReadSession> => {const sealed = getCookie(event, SESSION_NAME)if (!sealed) {- return { state: "none" }+ return { id: null, 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 }+ return { id, state: "valid", createdAt }}} catch {// An expired or forged session is the same as no session.}- return { state: "invalid" }+ return { id: null, state: "invalid" }+}++const readSession = (event: H3Event, config: SessionConfig) => {+ let session = requestSessions.get(event)+ if (!session) {+ session = unsealRequestSession(event, config)+ requestSessions.set(event, session)+ }+ return session+}++/**+ * Returns the session that the request came with, without changing it. The+ * result is cached for each request.+ */+export const getRequestSession = async (+ event: H3Event,+ config: SessionConfig+): Promise<RequestSession> => {+ const { id, state } = await readSession(event, config)+ return { id, state }+}++/**+ * Returns the ID of the session that replaces `id`. Requests that a tab sends+ * together with one old session each renew it, and the browser keeps only one+ * of their cookies. Deriving the ID gives them all the same new session.+ */+const getRenewedSessionId = async (id: string) => {+ const digest = await crypto.subtle.digest(+ "SHA-256",+ new TextEncoder().encode(id)+ )+ return Array.from(new Uint8Array(digest), (byte) =>+ byte.toString(16).padStart(2, "0")+ ).join("")}/**@@ -89,43 +132,54 @@ const readRequestSession = async (* 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) => {+const startSession = async (+ event: H3Event,+ config: SessionConfig,+ id: string+) => {event.context.sessions ??= Object.create(null)event.context.sessions![SESSION_NAME] = {- id: crypto.randomUUID(),+ id,createdAt: Date.now(),data: {},}await updateSession(event, config)}-const requestSessions = new WeakMap<H3Event, Promise<RequestSession>>()+/**+ * Starts a new session in the response if the request has no valid session,+ * or if its session is older than `SESSION_RENEW_AFTER_SECONDS`. It sets the+ * cookie at most once for each request.+ */+export const renewSession = (event: H3Event, config: SessionConfig) => {+ let renewal = sessionRenewals.get(event)+ if (!renewal) {+ renewal = (async () => {+ const { id, createdAt } = await readSession(event, config)+ if (!id) {+ await startSession(event, config, crypto.randomUUID())+ } else if (+ Date.now() >=+ (createdAt ?? 0) + SESSION_RENEW_AFTER_SECONDS * 1000+ ) {+ await startSession(event, config, await getRenewedSessionId(id))+ }+ })()+ sessionRenewals.set(event, renewal)+ }+ return renewal+}/**- * 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`.+ * Returns the session that the request came with, and renews it.** 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+export const ensureSession = async (event: H3Event, config: SessionConfig) => {+ const session = await getRequestSession(event, config)+ await renewSession(event, config)+ return session}diff --git a/frontend/test/unit/specs/server/rate-limit.spec.ts b/frontend/test/unit/specs/server/rate-limit.spec.tsindex 924253f92..368109b6c 100644--- a/frontend/test/unit/specs/server/rate-limit.spec.ts+++ b/frontend/test/unit/specs/server/rate-limit.spec.ts@@ -178,6 +178,7 @@ describe("RateLimiter", () => {keyHash: expect.any(String),limit: config.sessionLimit,windowSeconds: 60,+ windowEnd: "1970-01-01T00:01:00.000Z",requests: config.sessionLimit + 2,limitedRequests: 2,},@@ -226,6 +227,68 @@ describe("RateLimiter", () => {])})+ it("counts a request over several limits as limited by the first one", () => {+ let now = 0+ const reported: ExceededWindow[] = []+ const limiter = new RateLimiter(+ 60_000,+ () => now,+ (window) => reported.push(window)+ )+ for (let i = 0; i < config.ipLimit + 2; i++) {+ limiter.hit(checks)+ }+ now = 60_000+ limiter.hit(checks)+ expect(reported).toEqual([+ expect.objectContaining({+ counter: "session",+ requests: config.ipLimit + 2,+ limitedRequests: config.ipLimit + 2 - config.sessionLimit,+ }),+ expect.objectContaining({+ counter: "ip",+ requests: config.ipLimit + 2,+ limitedRequests: 0,+ }),+ ])+ })++ it("reports the ended windows when pruned without a request", () => {+ let now = 0+ const reported: ExceededWindow[] = []+ const limiter = new RateLimiter(+ 60_000,+ () => now,+ (window) => reported.push(window)+ )+ for (let i = 0; i <= config.sessionLimit; i++) {+ limiter.hit(checks)+ }+ limiter.prune()+ expect(reported).toEqual([])++ now = 60_000+ limiter.prune()+ expect(reported.map(({ counter }) => counter)).toEqual(["session"])+ expect(limiter.size).toEqual(0)+ })++ it("reports the open exceeded windows when flushed", () => {+ const reported: ExceededWindow[] = []+ const limiter = new RateLimiter(+ 60_000,+ () => 0,+ (window) => reported.push(window)+ )+ for (let i = 0; i <= config.sessionLimit; i++) {+ limiter.hit(checks)+ }+ limiter.flush()+ expect(reported.map(({ counter }) => counter)).toEqual(["session"])+ expect(limiter.size).toEqual(0)+ })+it("uses the same key hash for the counters of one IP address", () => {const limiter = new RateLimiter(60_000, () => 0)const noSessionChecks = getRateLimitChecks({diff --git a/frontend/test/unit/specs/server/session.spec.ts b/frontend/test/unit/specs/server/session.spec.tsindex 4edd38448..bc275e6dc 100644--- a/frontend/test/unit/specs/server/session.spec.ts+++ b/frontend/test/unit/specs/server/session.spec.ts@@ -6,7 +6,9 @@ import { createEvent, sealSession, type H3Event, type SessionConfig } from "h3"import {ensureSession,+ getRequestSession,getSessionConfig,+ renewSession,SESSION_MAX_AGE_SECONDS,SESSION_NAME,SESSION_RENEW_AFTER_SECONDS,@@ -82,6 +84,29 @@ describe("ensureSession", () => {expect(event.context.sessions?.[SESSION_NAME].id).not.toEqual("existing")})+ it("gives requests that renew the same session the same new one", async () => {+ const cookie = await sessionCookie(SESSION_RENEW_AFTER_SECONDS + 1)+ const events = [makeEvent(cookie), makeEvent(cookie)]+ await Promise.all(events.map((event) => ensureSession(event, config)))+ const [first, second] = events.map(+ (event) => event.context.sessions?.[SESSION_NAME].id+ )+ expect(first).toEqual(second)+ })++ it("renews different sessions to different ones", async () => {+ const ids = await Promise.all(+ ["one", "two"].map(async (id) => {+ const event = makeEvent(+ await sessionCookie(SESSION_RENEW_AFTER_SECONDS + 1, id)+ )+ await ensureSession(event, config)+ return event.context.sessions?.[SESSION_NAME].id+ })+ )+ expect(ids[0]).not.toEqual(ids[1])+ })+it.each`name | cookie${"expired"} | ${() => sessionCookie(SESSION_MAX_AGE_SECONDS + 1)}@@ -105,3 +130,17 @@ describe("ensureSession", () => {expect(getSetCookies(event)).toHaveLength(1)})})++describe("getRequestSession", () => {+ it("reads the session without starting one", async () => {+ const event = makeEvent()+ expect(await getRequestSession(event, config)).toEqual({+ id: null,+ state: "none",+ })+ expect(getSetCookies(event)).toEqual([])++ await renewSession(event, config)+ expect(getSetCookies(event)).toHaveLength(1)+ })+})