From 883c4793c9481679c37863277390958cdee840c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 16:35:54 +0100 Subject: [PATCH 1/5] feat(api): limit requests, query size and recipe creation; batch inserts - Per-client GraphQL request limit (300/min, keyed like the auth limiter behind Apache): 429 with Retry-After and code RATE_LIMITED. - Validation rule rejecting operations with more than 10 aliases, 3 top-level fields, 300 fields after fragment expansion or 8 levels (QUERY_TOO_COMPLEX) before any resolver runs. Introspection is not counted, so GraphiQL keeps working. Bodies over 1 MB are refused (413). - Recipe creation quota per user: 30 per hour (RATE_LIMITED with retryAfterSeconds) and 1000 in total (QUOTA_EXCEEDED), checked under a per-user advisory lock so parallel creates are counted one by one. - Ingredients, instructions and tags are written with one INSERT per table (unnest WITH ORDINALITY) instead of one per row. - Limits are injectable through createApp; the browser test server raises the request limit since all scenarios share 127.0.0.1. - The web client explains RATE_LIMITED (also HTTP 429) and QUOTA_EXCEEDED. Closes #119 --- apps/api/src/apiLimits.test.ts | 160 ++++++++++++++++++ apps/api/src/apiLimits.ts | 156 +++++++++++++++++ apps/api/src/app.ts | 93 ++++++++-- .../src/features/recipes/recipeRepository.ts | 89 +++++++--- .../src/features/recipes/recipeApi.test.ts | 39 +++++ apps/web/src/features/recipes/recipeApi.ts | 3 + apps/web/src/lib/graphqlClient.ts | 6 + docs/recipe-api.md | 27 ++- e2e/recipe-api.spec.ts | 4 + scripts/test-recipe-api.ts | 130 ++++++++++++++ 10 files changed, 666 insertions(+), 41 deletions(-) create mode 100644 apps/api/src/apiLimits.test.ts create mode 100644 apps/api/src/apiLimits.ts create mode 100644 apps/web/src/features/recipes/recipeApi.test.ts diff --git a/apps/api/src/apiLimits.test.ts b/apps/api/src/apiLimits.test.ts new file mode 100644 index 0000000..5d94115 --- /dev/null +++ b/apps/api/src/apiLimits.test.ts @@ -0,0 +1,160 @@ +// @vitest-environment node +import { readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { + buildSchema, + getIntrospectionQuery, + parse, + specifiedRules, + validate, +} from 'graphql'; +import { describe, expect, it } from 'vitest'; +import { + createRequestRateLimiter, + DEFAULT_API_LIMITS, + queryLimitsRule, + type QueryLimits, +} from './apiLimits.js'; +import { createApp } from './app.js'; + +const schema = buildSchema( + readFileSync(new URL('./schema.graphql', import.meta.url), 'utf8'), +); +function errors(query: string, limits: QueryLimits = DEFAULT_API_LIMITS.query) { + return validate(schema, parse(query), [ + ...specifiedRules, + queryLimitsRule(limits), + ]).map((error) => error.message); +} + +describe('query limits', () => { + it('accept every operation the web app sends', () => { + expect( + errors( + readFileSync( + new URL('../../../contracts/operations.graphql', import.meta.url), + 'utf8', + ), + ), + ).toEqual([]); + }); + + it("accept GraphiQL's introspection query", () => { + expect(errors(getIntrospectionQuery())).toEqual([]); + }); + + it('reject repeating a list query through aliases', () => { + const aliases = Array.from( + { length: 11 }, + (_, index) => + `a${index}: recipes(input: { pageSize: 50 }) { totalCount }`, + ); + expect(errors(`{ ${aliases.join(' ')} }`)).toEqual([ + 'The query is too large: more than 10 aliases, more than 3 top-level fields.', + ]); + }); + + it('reject more than three top-level fields', () => { + expect( + errors('{ a: health b: health c: health d: health }', { + ...DEFAULT_API_LIMITS.query, + maxAliases: 100, + }), + ).toEqual(['The query is too large: more than 3 top-level fields.']); + }); + + it('reject nesting deeper than the limit', () => { + const query = '{ recipe(id: "1") { ingredients { name } author { id } } }'; + expect(errors(query, { ...DEFAULT_API_LIMITS.query, maxDepth: 3 })).toEqual( + [], + ); + expect(errors(query, { ...DEFAULT_API_LIMITS.query, maxDepth: 2 })).toEqual( + ['The query is too large: nesting is deeper than 2 levels.'], + ); + }); + + it('stop counting early when fragments multiply the fields', () => { + // Each fragment spreads the next twice: 2^20 fields once expanded. + const fragments = Array.from( + { length: 20 }, + (_, index) => + `fragment F${index} on Recipe { ${index === 19 ? 'id title' : `...F${index + 1} ...F${index + 1}`} }`, + ); + const document = parse( + `{ recipe(id: "1") { ...F0 } } ${fragments.join(' ')}`, + ); + const started = performance.now(); + const result = validate(schema, document, [ + queryLimitsRule(DEFAULT_API_LIMITS.query), + ]); + expect(result.map((error) => error.message)).toEqual([ + 'The query is too large: more than 300 fields.', + ]); + expect(performance.now() - started).toBeLessThan(500); + }); +}); + +describe('request rate limiter', () => { + it('limits each client per window and resets after it', () => { + let time = 0; + const limiter = createRequestRateLimiter(2, 60_000, () => time); + expect(limiter.take('a')).toBeNull(); + expect(limiter.take('a')).toBeNull(); + expect(limiter.take('a')).toBe(60); + // Another client has its own budget. + expect(limiter.take('b')).toBeNull(); + time = 45_000; + expect(limiter.take('a')).toBe(15); + time = 60_000; + expect(limiter.take('a')).toBeNull(); + }); +}); + +describe('API limits over HTTP', () => { + const post = ( + app: ReturnType, + query: string, + headers: Record = {}, + ) => + app.fetch('http://localhost/graphql', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Requested-With': 'recipe-platform', + ...headers, + }, + body: JSON.stringify({ query }), + }); + const app = (limits = {}) => + createApp(undefined, false, false, {}, tmpdir(), false, limits); + + it('answers 429 with Retry-After once a client sends too many requests', async () => { + const api = app({ requestsPerMinute: 2 }); + expect((await post(api, '{ health }')).status).toBe(200); + expect((await post(api, '{ health }')).status).toBe(200); + const limited = await post(api, '{ health }'); + expect(limited.status).toBe(429); + expect(Number(limited.headers.get('retry-after'))).toBeGreaterThan(0); + expect(await limited.json()).toMatchObject({ + errors: [{ extensions: { code: 'RATE_LIMITED' } }], + }); + }); + + it('rejects an alias-repeated query before any resolver runs', async () => { + const aliases = Array.from( + { length: 11 }, + (_, index) => `a${index}: health`, + ); + const response = await post(app(), `{ ${aliases.join(' ')} }`); + expect(await response.json()).toMatchObject({ + errors: [{ extensions: { code: 'QUERY_TOO_COMPLEX' } }], + }); + }); + + it('refuses a request body larger than 1 MB', async () => { + const response = await post(app(), '{ health }', { + 'Content-Length': '1000001', + }); + expect(response.status).toBe(413); + }); +}); diff --git a/apps/api/src/apiLimits.ts b/apps/api/src/apiLimits.ts new file mode 100644 index 0000000..9fe3650 --- /dev/null +++ b/apps/api/src/apiLimits.ts @@ -0,0 +1,156 @@ +import { + GraphQLError, + Kind, + type ASTVisitor, + type FragmentDefinitionNode, + type SelectionSetNode, + type ValidationContext, +} from 'graphql'; + +/* + * Resource limits for the GraphQL API. Authentication attempts and image + * uploads have their own limits (authRateLimit.ts, imageStore.ts); these + * bound what any single client or request can make the server do. + */ +export type QueryLimits = { + /** Nesting of fields, e.g. recipes { items { ingredients { name } } } is 4. */ + maxDepth: number; + /** Aliased fields, the usual way to repeat an expensive field. */ + maxAliases: number; + /** Field selections after expanding fragments. */ + maxFields: number; + /** Top-level fields, each of which is at least one database query. */ + maxRootFields: number; +}; + +export type ApiLimits = { + /** GraphQL requests per client (IP address) per minute. */ + requestsPerMinute: number; + /** Recipes one user may create per hour, and in total. */ + recipesPerHour: number; + recipesPerUser: number; + query: QueryLimits; +}; + +// Every operation the web app sends stays well inside these (see +// apiLimits.test.ts); a page load makes a handful of requests. +export const DEFAULT_API_LIMITS: ApiLimits = { + requestsPerMinute: 300, + recipesPerHour: 30, + recipesPerUser: 1000, + query: { maxDepth: 8, maxAliases: 10, maxFields: 300, maxRootFields: 3 }, +}; + +/** Bodies above this are refused before parsing (a recipe is far smaller). */ +export const MAX_REQUEST_BYTES = 1_000_000; + +/** + * Rejects operations that are too deep, too wide or repeat fields through + * aliases, before any resolver runs. Introspection (__schema, __type) is + * not counted: GraphiQL's schema query is deep but reads no data. + */ +export function queryLimitsRule(limits: QueryLimits) { + return (context: ValidationContext): ASTVisitor => { + const fragments = new Map(); + for (const definition of context.getDocument().definitions) + if (definition.kind === Kind.FRAGMENT_DEFINITION) + fragments.set(definition.name.value, definition); + + return { + OperationDefinition(operation) { + const usage = { fields: 0, aliases: 0, depth: 0, root: 0 }; + // Stops early once over the field limit, so fragments that spread + // each other many times cannot make this check itself expensive. + function measure( + selections: SelectionSetNode, + depth: number, + spreading: Set, + ) { + for (const selection of selections.selections) { + if (usage.fields > limits.maxFields) return; + if (selection.kind === Kind.FIELD) { + const name = selection.name.value; + if (name === '__schema' || name === '__type') continue; + if (name === '__typename') continue; + usage.fields += 1; + if (depth === 1) usage.root += 1; + if (selection.alias) usage.aliases += 1; + usage.depth = Math.max(usage.depth, depth); + if (selection.selectionSet) + measure(selection.selectionSet, depth + 1, spreading); + } else if (selection.kind === Kind.INLINE_FRAGMENT) { + measure(selection.selectionSet, depth, spreading); + } else { + const name = selection.name.value; + const fragment = fragments.get(name); + // Unknown or cyclic fragments are reported by the standard rules. + if (!fragment || spreading.has(name)) continue; + spreading.add(name); + measure(fragment.selectionSet, depth, spreading); + spreading.delete(name); + } + } + } + measure(operation.selectionSet, 1, new Set()); + + const exceeded = [ + usage.depth > limits.maxDepth && + `nesting is deeper than ${limits.maxDepth} levels`, + usage.aliases > limits.maxAliases && + `more than ${limits.maxAliases} aliases`, + usage.fields > limits.maxFields && + `more than ${limits.maxFields} fields`, + usage.root > limits.maxRootFields && + `more than ${limits.maxRootFields} top-level fields`, + ].filter(Boolean); + if (exceeded.length) + context.reportError( + new GraphQLError( + `The query is too large: ${exceeded.join(', ')}.`, + { + nodes: operation, + extensions: { code: 'QUERY_TOO_COMPLEX' }, + }, + ), + ); + }, + }; + }; +} + +/** + * Fixed-window request counter per client. Returns null when the request + * is allowed, otherwise the seconds until the client may try again. + * Memory is bounded: expired entries are swept (at most once a second), + * and when 10 000 clients are already tracked a new one is let through + * rather than locking out every new visitor. + */ +export function createRequestRateLimiter( + limit: number, + windowMs = 60_000, + now = Date.now, +) { + const clients = new Map(); + let nextSweep = 0; + return { + take(client: string): number | null { + const time = now(); + if (time >= nextSweep) { + for (const [key, entry] of clients) + if (entry.resetAt <= time) clients.delete(key); + nextSweep = time + 1000; + } + const entry = clients.get(client); + if (!entry || entry.resetAt <= time) { + clients.delete(client); + if (clients.size < 10_000) + clients.set(client, { count: 1, resetAt: time + windowMs }); + return null; + } + if (entry.count >= limit) + return Math.max(1, Math.ceil((entry.resetAt - time) / 1000)); + entry.count += 1; + return null; + }, + }; +} diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 8148c00..a25b062 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -7,6 +7,7 @@ import { createRecipeRepository } from './features/recipes/recipeRepository.js'; import { createRecipeResolvers } from './features/recipes/recipeResolvers.js'; import { readFileSync } from 'node:fs'; import { createSchema, createYoga } from 'graphql-yoga'; +import type { ValidationRule } from 'graphql'; import type { Resolvers } from './generated.js'; import type { IncomingMessage } from 'node:http'; @@ -15,6 +16,14 @@ import { type AuthContext, } from './features/auth/authResolvers.js'; import { authClientKey } from './features/auth/authRateLimit.js'; +import { + createRequestRateLimiter, + DEFAULT_API_LIMITS, + MAX_REQUEST_BYTES, + queryLimitsRule, + type ApiLimits, + type QueryLimits, +} from './apiLimits.js'; import { authService, type AuthService } from './features/auth/authService.js'; import { readSessionCookie, @@ -34,7 +43,18 @@ export function createApp( // resolver enforces authentication and ownership and POSTs need the CSRF // header. Set API_GRAPHIQL=false to turn it off. enableGraphiql = process.env.API_GRAPHIQL !== 'false', + // Request, query and recipe-creation limits (apiLimits.ts); tests that + // send many requests from one address raise them. + limitOverrides: Partial> & { + query?: Partial; + } = {}, ) { + const limits: ApiLimits = { + ...DEFAULT_API_LIMITS, + ...limitOverrides, + query: { ...DEFAULT_API_LIMITS.query, ...limitOverrides.query }, + }; + const requestLimiter = createRequestRateLimiter(limits.requestsPerMinute); const images = createImageStore( database.pool ?? db, database.schema ?? 'project2', @@ -42,7 +62,11 @@ export function createApp( ); const authResolvers = createAuthResolvers(service); const recipes = createRecipeResolvers( - createRecipeRepository(database.pool ?? db, database.schema ?? 'project2'), + createRecipeRepository( + database.pool ?? db, + database.schema ?? 'project2', + limits, + ), ); const cookies = new WeakMap(); return createYoga<{ req?: IncomingMessage }, AuthContext>({ @@ -53,7 +77,29 @@ export function createApp( }, plugins: [ { - async onRequest({ request, fetchAPI, endResponse }) { + onValidate({ + addValidationRule, + }: { + addValidationRule: (rule: ValidationRule) => void; + }) { + addValidationRule(queryLimitsRule(limits.query)); + }, + async onRequest({ request, serverContext, fetchAPI, endResponse }) { + const blocked = ( + status: number, + message: string, + extensions: Record, + headers: Record = {}, + ) => + endResponse( + new fetchAPI.Response( + JSON.stringify({ errors: [{ message, extensions }] }), + { + status, + headers: { 'Content-Type': 'application/json', ...headers }, + }, + ), + ); const imageResponse = await handleImageRequest( request, service, @@ -63,28 +109,39 @@ export function createApp( endResponse(imageResponse); return; } + // Refuse oversized bodies before they are parsed. + if ( + Number(request.headers.get('content-length') ?? 0) > + MAX_REQUEST_BYTES + ) { + blocked(413, 'Request too large.', { code: 'PAYLOAD_TOO_LARGE' }); + return; + } + const retryAfterSeconds = requestLimiter.take( + authClientKey( + request, + // Node's request, as in the context below. + (serverContext as { req?: IncomingMessage } | undefined)?.req + ?.socket.remoteAddress, + trustProxy, + ), + ); + if (retryAfterSeconds !== null) { + blocked( + 429, + 'Too many requests. Please try again shortly.', + { code: 'RATE_LIMITED', retryAfterSeconds }, + { 'Retry-After': String(retryAfterSeconds) }, + ); + return; + } if ( request.method === 'POST' && (request.headers.get('x-requested-with') !== 'recipe-platform' || request.headers.get('content-type')?.split(';')[0]?.trim() !== 'application/json') ) { - endResponse( - new fetchAPI.Response( - JSON.stringify({ - errors: [ - { - message: 'Request blocked.', - extensions: { code: 'FORBIDDEN' }, - }, - ], - }), - { - status: 403, - headers: { 'Content-Type': 'application/json' }, - }, - ), - ); + blocked(403, 'Request blocked.', { code: 'FORBIDDEN' }); } }, onResponse({ request, response }) { diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts index ffd4316..455b0b6 100644 --- a/apps/api/src/features/recipes/recipeRepository.ts +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -4,8 +4,16 @@ import { db } from '../../db/client.js'; import type { CookbookScope, Recipe } from '../../generated.js'; import type { RecipeInput, ListInput } from './recipeValidation.js'; import { validateImageReference, lockImages } from './imageRepository.js'; +import { DEFAULT_API_LIMITS, type ApiLimits } from '../../apiLimits.js'; -export function createRecipeRepository(pool: Pool = db, schema = 'project2') { +export function createRecipeRepository( + pool: Pool = db, + schema = 'project2', + limits: Pick< + ApiLimits, + 'recipesPerHour' | 'recipesPerUser' + > = DEFAULT_API_LIMITS, +) { if (!/^[a-z_][a-z0-9_]*$/.test(schema)) throw new Error('Invalid database schema.'); const t = (name: string) => `"${schema}"."${name}"`; @@ -99,29 +107,69 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { extensions: { code: 'NOT_FOUND' }, }); } + // One INSERT per child table, whatever the recipe's size: the arrays are + // unnested in order, and WITH ORDINALITY numbers the positions from 1. async function children(client: PoolClient, id: string, input: RecipeInput) { - for (const [index, ingredient] of input.ingredients.entries()) { + await client.query( + `INSERT INTO ${t('recipe_ingredients')} (recipe_id,name,amount,unit,note,position) + SELECT $1, i.name, i.amount, i.unit, i.note, i.position + FROM unnest($2::text[], $3::numeric[], $4::text[], $5::text[]) WITH ORDINALITY AS i(name, amount, unit, note, position)`, + [ + id, + input.ingredients.map((ingredient) => ingredient.name), + input.ingredients.map((ingredient) => String(ingredient.amount)), + input.ingredients.map((ingredient) => ingredient.unit), + input.ingredients.map((ingredient) => ingredient.note), + ], + ); + await client.query( + `INSERT INTO ${t('recipe_instructions')} (recipe_id,text,position) + SELECT $1, i.text, i.position + FROM unnest($2::text[]) WITH ORDINALITY AS i(text, position)`, + [id, input.instructions], + ); + if (input.tags.length) await client.query( - `INSERT INTO ${t('recipe_ingredients')} (recipe_id,name,amount,unit,note,position) VALUES ($1,$2,$3,$4,$5,$6)`, - [ - id, - ingredient.name, - ingredient.amount, - ingredient.unit, - ingredient.note, - index + 1, - ], + `INSERT INTO ${t('recipe_tags')} (recipe_id,tag) SELECT $1, unnest($2::text[])`, + [id, input.tags], ); - } - for (const [index, instruction] of input.instructions.entries()) - await client.query( - `INSERT INTO ${t('recipe_instructions')} (recipe_id,text,position) VALUES ($1,$2,$3)`, - [id, instruction, index + 1], + } + /* + * Recipe creation quota per user. A per-user lock makes parallel creates + * by the same user count one after another, so they cannot all pass the + * check together. Recipes created directly in the database (seed, tests) + * are not limited. + */ + async function checkCreateQuota(client: PoolClient, userId: string) { + await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [ + `${schema}:recipe-create:${userId}`, + ]); + const usage = await client.query<{ + total: number; + recent: number; + retryAfter: number | null; + }>( + `SELECT count(*)::int AS total, + count(*) FILTER (WHERE created_at > now()-interval '1 hour')::int AS recent, + ceil(extract(epoch FROM min(created_at) FILTER (WHERE created_at > now()-interval '1 hour') + interval '1 hour' - now()))::int AS "retryAfter" + FROM ${t('recipes')} WHERE author_id=$1`, + [userId], + ); + const { total, recent, retryAfter } = usage.rows[0]!; + if (total >= limits.recipesPerUser) + throw new GraphQLError( + `You can have at most ${limits.recipesPerUser} recipes. Delete one to add another.`, + { extensions: { code: 'QUOTA_EXCEEDED' } }, ); - for (const tag of input.tags) - await client.query( - `INSERT INTO ${t('recipe_tags')} (recipe_id,tag) VALUES ($1,$2)`, - [id, tag], + if (recent >= limits.recipesPerHour) + throw new GraphQLError( + 'You have created many recipes in the last hour. Please try again later.', + { + extensions: { + code: 'RATE_LIMITED', + retryAfterSeconds: Math.max(1, retryAfter ?? 3600), + }, + }, ); } const values = (input: RecipeInput) => [ @@ -182,6 +230,7 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') { }, async create(input: RecipeInput, userId: string) { return transaction(async (client) => { + await checkCreateQuota(client, userId); await validateImageReference(client, schema, input.imageUrl, userId); const result = await client.query<{ id: string }>( `INSERT INTO ${t('recipes')} (title,description,image_url,category,cuisine,difficulty,visibility,prep_minutes,cook_minutes,servings,author_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) RETURNING id`, diff --git a/apps/web/src/features/recipes/recipeApi.test.ts b/apps/web/src/features/recipes/recipeApi.test.ts new file mode 100644 index 0000000..c61ba24 --- /dev/null +++ b/apps/web/src/features/recipes/recipeApi.test.ts @@ -0,0 +1,39 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { listRecipes, recipeErrorMessage } from './recipeApi'; + +afterEach(() => vi.unstubAllGlobals()); + +describe('recipe API limits', () => { + it('explains the per-client request limit (HTTP 429)', async () => { + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValue( + Response.json( + { errors: [{ extensions: { code: 'RATE_LIMITED' } }] }, + { status: 429, headers: { 'Retry-After': '30' } }, + ), + ), + ); + const error = await listRecipes({}).catch((caught: unknown) => caught); + expect(recipeErrorMessage(error)).toBe( + 'You are doing that too often. Please try again later.', + ); + }); + + it('explains the recipe creation quota', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + Response.json({ + errors: [{ extensions: { code: 'QUOTA_EXCEEDED' } }], + }), + ), + ); + const error = await listRecipes({}).catch((caught: unknown) => caught); + expect(recipeErrorMessage(error)).toBe( + 'You have reached the maximum number of recipes. Delete one to add another.', + ); + }); +}); diff --git a/apps/web/src/features/recipes/recipeApi.ts b/apps/web/src/features/recipes/recipeApi.ts index dad8b9d..7a435f0 100644 --- a/apps/web/src/features/recipes/recipeApi.ts +++ b/apps/web/src/features/recipes/recipeApi.ts @@ -97,6 +97,9 @@ export function recipeErrorMessage(error: unknown) { FORBIDDEN: 'You do not have permission to perform this action.', NOT_FOUND: 'This recipe is unavailable or you no longer have access.', BAD_USER_INPUT: 'Check the recipe fields and try again.', + RATE_LIMITED: 'You are doing that too often. Please try again later.', + QUOTA_EXCEEDED: + 'You have reached the maximum number of recipes. Delete one to add another.', }; return messages[error.code] ?? error.message; } diff --git a/apps/web/src/lib/graphqlClient.ts b/apps/web/src/lib/graphqlClient.ts index b28a7ed..c53b541 100644 --- a/apps/web/src/lib/graphqlClient.ts +++ b/apps/web/src/lib/graphqlClient.ts @@ -44,6 +44,12 @@ export async function graphqlRequest( 'Unable to connect. Check your connection and try again.', ); } + // The API's per-client request limit (apps/api/src/apiLimits.ts). + if (response.status === 429) + throw new ApiError( + 'RATE_LIMITED', + 'Too many requests. Please wait a moment and try again.', + ); if (!response.ok) throw new ApiError( 'API_ERROR', diff --git a/docs/recipe-api.md b/docs/recipe-api.md index 613a879..31a3df3 100644 --- a/docs/recipe-api.md +++ b/docs/recipe-api.md @@ -169,11 +169,32 @@ Frontend er koblet ved de eksisterende data-grensene. Integrasjonen følger diss - `cuisine` er nullable; en frontend-mapper må håndtere manglende verdi. - Bruk eksisterende pending/error/not-found-mønstre og behold formdata ved feil. -Feilkoder: `BAD_USER_INPUT`, `UNAUTHENTICATED`, `NOT_FOUND` og `FORBIDDEN`. +Feilkoder: `BAD_USER_INPUT`, `UNAUTHENTICATED`, `NOT_FOUND`, `FORBIDDEN`, +`RATE_LIMITED`, `QUOTA_EXCEEDED` og `QUERY_TOO_COMPLEX`. Ugyldige enumverdier avvises av GraphQL før resolveren kjøres; klienten må også håndtere GraphQL-valideringsfeil uten disse domenekodene. -Uventede databasefeil maskeres av Yoga. Oppdatering/sletting av andres eller -ukjente oppskrifter gir samme feil og avslører ikke private data. + +### Ressursgrenser + +Grensene ligger i `apps/api/src/apiLimits.ts` og kan overstyres i `createApp` +(tester som sender mange forespørsler fra én adresse, gjør det). + +- **Forespørsler:** 300 GraphQL-forespørsler per klient (IP-adresse, samme + nøkkel som auth-begrensningen bak Apache) per minutt. Deretter svarer API-et + `429` med `Retry-After` og koden `RATE_LIMITED`. Grensen holdes i minnet og + nullstilles ved omstart. +- **Spørringer:** høyst 10 alias, 3 toppnivåfelt, 300 felt etter at fragmenter + er utvidet og 8 nivåer. Større spørringer avvises med `QUERY_TOO_COMPLEX` før + noen resolver kjører. Introspeksjon (GraphiQL) telles ikke. +- **Størrelse:** forespørsler over 1 MB (`Content-Length`) avvises med `413`. +- **Nye oppskrifter:** høyst 30 per bruker per time (`RATE_LIMITED` med + `retryAfterSeconds`) og 1000 totalt (`QUOTA_EXCEEDED`). En lås per bruker + gjør at parallelle forespørsler telles etter hverandre. Seed og direkte + databaseskriving begrenses ikke. Slettede oppskrifter teller ikke. +- **Lagring:** ingredienser, steg og tagger skrives med én `INSERT` per tabell + (`unnest … WITH ORDINALITY`), uansett hvor stor oppskriften er. + Uventede databasefeil maskeres av Yoga. Oppdatering/sletting av andres eller + ukjente oppskrifter gir samme feil og avslører ikke private data. ### Avtale for frontendintegrasjon og videre arbeid diff --git a/e2e/recipe-api.spec.ts b/e2e/recipe-api.spec.ts index e1d8d54..c48ace7 100644 --- a/e2e/recipe-api.spec.ts +++ b/e2e/recipe-api.spec.ts @@ -56,6 +56,10 @@ test.beforeAll(async () => { false, { pool, schema }, imageDirectory, + false, + // Every scenario's browser requests come from 127.0.0.1, so the + // per-client request limit would count them all together. + { requestsPerMinute: 10_000 }, ), ); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts index ecb053c..1991b01 100644 --- a/scripts/test-recipe-api.ts +++ b/scripts/test-recipe-api.ts @@ -741,6 +741,136 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { } }, ); + await t.test( + 'stores ingredients, steps and tags in order with one insert each', + async () => { + const ingredients = [ + { name: 'Flour', amount: 1234.5678, unit: 'g', note: 'sifted' }, + { name: 'Salt', amount: 0.1, unit: 'tsp', note: null }, + ...Array.from({ length: 98 }, (_, index) => ({ + name: `Spice ${index + 3}`, + amount: index + 3, + unit: 'g', + note: null, + })), + ]; + const { createRecipe } = await ok( + CreateRecipeDocument, + { + input: { + ...input, + title: 'Hundred ingredient bake', + ingredients, + instructions: ['Mix', 'Bake', 'Cool'], + tags: ['Baking', 'big'], + }, + }, + owner.cookie, + ); + try { + assert.deepEqual( + createRecipe.ingredients.map(({ name, amount, note }) => ({ + name, + amount, + note, + })), + ingredients.map(({ name, amount, note }) => ({ + name, + amount, + note, + })), + ); + assert.deepEqual(createRecipe.instructions, [ + { step: 1, text: 'Mix' }, + { step: 2, text: 'Bake' }, + { step: 3, text: 'Cool' }, + ]); + assert.deepEqual(createRecipe.tags, ['baking', 'big']); + // A recipe without tags writes no tag row. + const { updateRecipe } = await ok( + UpdateRecipeDocument, + { id: createRecipe.id, input: { ...input, tags: [] } }, + owner.cookie, + ); + assert.deepEqual(updateRecipe.tags, []); + assert.equal(updateRecipe.ingredients.length, 2); + } finally { + await ok(DeleteRecipeDocument, { id: createRecipe.id }, owner.cookie); + } + }, + ); + await t.test( + 'limits recipe creation per user, also for parallel requests', + async () => { + const limited = createApp( + createAuthService(createAuthRepository(pool, pool, schema)), + false, + false, + { pool, schema }, + imageDirectory, + false, + { recipesPerHour: 2, recipesPerUser: 3 }, + ); + const { user, sessionToken } = await createAuthRepository( + pool, + pool, + schema, + ).createUserWithSession( + 'Busy cook', + 'busy-cook@example.com', + 'not-a-real-hash', + new Date(Date.now() + 3_600_000), + ); + const cookie = `${owner.cookie.split('=')[0]}=${sessionToken}`; + const create = async (title: string) => { + const response = await limited.fetch('http://localhost/graphql', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Requested-With': 'recipe-platform', + Cookie: cookie, + }, + body: JSON.stringify({ + query: CreateRecipeDocument.toString(), + variables: { input: { ...input, title } }, + }), + }); + return (await response.json()) as { + errors?: { + extensions: { code: string; retryAfterSeconds?: number }; + }[]; + }; + }; + // Four at once with room for two: exactly two are created. + const results = await Promise.all( + ['One', 'Two', 'Three', 'Four'].map((title) => create(title)), + ); + const codes = results.map( + (result) => result.errors?.[0]?.extensions.code ?? 'ok', + ); + assert.deepEqual(codes.toSorted(), [ + 'RATE_LIMITED', + 'RATE_LIMITED', + 'ok', + 'ok', + ]); + const retry = results.find((result) => result.errors)!.errors![0]!; + assert.ok(retry.extensions.retryAfterSeconds! > 3500); + // An hour later the hourly limit allows more, up to the total. + await pool.query( + `UPDATE "${schema}".recipes SET created_at=now()-interval '2 hours' WHERE author_id=$1`, + [user.id], + ); + assert.equal((await create('Five')).errors, undefined); + assert.equal( + (await create('Six')).errors?.[0]?.extensions.code, + 'QUOTA_EXCEEDED', + ); + await pool.query(`DELETE FROM "${schema}".recipes WHERE author_id=$1`, [ + user.id, + ]); + }, + ); await t.test('only the owner can update or delete', async () => { await fails( UpdateRecipeDocument, From fa62a10d979f00d3e5820c5773495ee3f2ae970d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 18:27:33 +0100 Subject: [PATCH 2/5] fix(api): apply alias and root-field limits to introspection queries Introspection fields (__schema, __type) were skipped entirely by the query limits, so a large aliased introspection query could repeat the whole schema without limit. They now count like any other field for aliases, top-level fields and total size, which also bounds fragment expansion inside them. Only depth is exempt, because GraphiQL's standard introspection query is 15 levels deep (about 230 fields, no aliases) and still passes. Tests: the standard getIntrospectionQuery() is accepted; aliased __schema/__type at the top level, aliases below __schema and a very large nested introspection query are rejected. --- apps/api/src/apiLimits.test.ts | 23 +++++++++++++++++++++++ apps/api/src/apiLimits.ts | 23 ++++++++++++++++------- docs/recipe-api.md | 4 +++- 3 files changed, 42 insertions(+), 8 deletions(-) diff --git a/apps/api/src/apiLimits.test.ts b/apps/api/src/apiLimits.test.ts index 5d94115..e70fbbd 100644 --- a/apps/api/src/apiLimits.test.ts +++ b/apps/api/src/apiLimits.test.ts @@ -43,6 +43,29 @@ describe('query limits', () => { expect(errors(getIntrospectionQuery())).toEqual([]); }); + it('reject heavily aliased introspection like any other field', () => { + const copies = (count: number, field: string) => + Array.from({ length: count }, (_, index) => `a${index}: ${field}`); + // Repeating the whole schema through aliases at the top level. + expect( + errors(`{ ${copies(11, '__schema { types { name } }').join(' ')} }`), + ).toEqual([ + 'The query is too large: more than 10 aliases, more than 3 top-level fields.', + ]); + expect( + errors(`{ ${copies(5, '__type(name: "Recipe") { name }').join(' ')} }`), + ).toEqual(['The query is too large: more than 3 top-level fields.']); + // Aliases below the introspection field count too. + expect( + errors(`{ __schema { ${copies(11, 'types { name }').join(' ')} } }`), + ).toEqual(['The query is too large: more than 10 aliases.']); + // And so does its total size, however deeply it is nested. + const deep = `{ __schema { types ${'{ ofType '.repeat(300)}{ name }${' }'.repeat(300)} } }`; + expect(errors(deep)).toEqual([ + 'The query is too large: more than 300 fields.', + ]); + }); + it('reject repeating a list query through aliases', () => { const aliases = Array.from( { length: 11 }, diff --git a/apps/api/src/apiLimits.ts b/apps/api/src/apiLimits.ts index 9fe3650..5007b96 100644 --- a/apps/api/src/apiLimits.ts +++ b/apps/api/src/apiLimits.ts @@ -47,7 +47,9 @@ export const MAX_REQUEST_BYTES = 1_000_000; /** * Rejects operations that are too deep, too wide or repeat fields through * aliases, before any resolver runs. Introspection (__schema, __type) is - * not counted: GraphiQL's schema query is deep but reads no data. + * counted like any other field, so aliases, top-level fields and the total + * size stay limited, but its depth is not: GraphiQL's schema query is 15 + * levels deep and reads no data. */ export function queryLimitsRule(limits: QueryLimits) { return (context: ValidationContext): ASTVisitor => { @@ -65,33 +67,40 @@ export function queryLimitsRule(limits: QueryLimits) { selections: SelectionSetNode, depth: number, spreading: Set, + introspection: boolean, ) { for (const selection of selections.selections) { if (usage.fields > limits.maxFields) return; if (selection.kind === Kind.FIELD) { const name = selection.name.value; - if (name === '__schema' || name === '__type') continue; if (name === '__typename') continue; + const inIntrospection = + introspection || name === '__schema' || name === '__type'; usage.fields += 1; if (depth === 1) usage.root += 1; if (selection.alias) usage.aliases += 1; - usage.depth = Math.max(usage.depth, depth); + if (!inIntrospection) usage.depth = Math.max(usage.depth, depth); if (selection.selectionSet) - measure(selection.selectionSet, depth + 1, spreading); + measure( + selection.selectionSet, + depth + 1, + spreading, + inIntrospection, + ); } else if (selection.kind === Kind.INLINE_FRAGMENT) { - measure(selection.selectionSet, depth, spreading); + measure(selection.selectionSet, depth, spreading, introspection); } else { const name = selection.name.value; const fragment = fragments.get(name); // Unknown or cyclic fragments are reported by the standard rules. if (!fragment || spreading.has(name)) continue; spreading.add(name); - measure(fragment.selectionSet, depth, spreading); + measure(fragment.selectionSet, depth, spreading, introspection); spreading.delete(name); } } } - measure(operation.selectionSet, 1, new Set()); + measure(operation.selectionSet, 1, new Set(), false); const exceeded = [ usage.depth > limits.maxDepth && diff --git a/docs/recipe-api.md b/docs/recipe-api.md index 7cec3c2..b729db8 100644 --- a/docs/recipe-api.md +++ b/docs/recipe-api.md @@ -185,7 +185,9 @@ Grensene ligger i `apps/api/src/apiLimits.ts` og kan overstyres i `createApp` nullstilles ved omstart. - **Spørringer:** høyst 10 alias, 3 toppnivåfelt, 300 felt etter at fragmenter er utvidet og 8 nivåer. Større spørringer avvises med `QUERY_TOO_COMPLEX` før - noen resolver kjører. Introspeksjon (GraphiQL) telles ikke. + noen resolver kjører. Introspeksjon (`__schema`, `__type`) teller som andre + felt for alias, toppnivåfelt og totalt antall felt, men ikke for dybde, slik + at GraphiQLs standardspørring (15 nivåer, ca. 230 felt) går gjennom. - **Størrelse:** forespørsler over 1 MB (`Content-Length`) avvises med `413`. - **Nye oppskrifter:** høyst 30 per bruker per time (`RATE_LIMITED` med `retryAfterSeconds`) og 1000 totalt (`QUOTA_EXCEEDED`). En lås per bruker From 41d936ce2715fb54a091c4e4578b2e0f087e75f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 18:27:49 +0100 Subject: [PATCH 3/5] fix(api): enforce the body limit on bytes received, not just Content-Length The 1 MB limit only looked at the Content-Length header, so a chunked request without it (or one that sent more than it stated) was parsed at any size. The request body is now read through a stream that counts the bytes actually received and fails once over the limit; the request is then answered with 413 and PAYLOAD_TOO_LARGE. The quick Content-Length rejection stays, so honest oversized requests are still refused before any reading. Test: a chunked POST without Content-Length over 1 MB gets 413, and a small chunked POST still succeeds. --- apps/api/src/apiLimits.test.ts | 32 ++++++++++++++++++++++++++++++ apps/api/src/apiLimits.ts | 36 ++++++++++++++++++++++++++++++++++ apps/api/src/app.ts | 29 +++++++++++++++++++++++++-- docs/recipe-api.md | 4 +++- 4 files changed, 98 insertions(+), 3 deletions(-) diff --git a/apps/api/src/apiLimits.test.ts b/apps/api/src/apiLimits.test.ts index e70fbbd..988e3d4 100644 --- a/apps/api/src/apiLimits.test.ts +++ b/apps/api/src/apiLimits.test.ts @@ -180,4 +180,36 @@ describe('API limits over HTTP', () => { }); expect(response.status).toBe(413); }); + + it('counts the bytes of a chunked body that has no Content-Length', async () => { + const chunk = new TextEncoder().encode(' '.repeat(100_000)); + const chunked = (chunks: number) => + app().fetch('http://localhost/graphql', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Requested-With': 'recipe-platform', + }, + body: new ReadableStream({ + start(controller) { + for (let index = 0; index < chunks; index++) + controller.enqueue(chunk); + controller.enqueue( + new TextEncoder().encode('{"query":"{ health }"}'), + ); + controller.close(); + }, + }), + duplex: 'half', + } as RequestInit); + const large = await chunked(11); + expect(large.status).toBe(413); + expect(await large.json()).toMatchObject({ + errors: [{ extensions: { code: 'PAYLOAD_TOO_LARGE' } }], + }); + // The same kind of request under the limit still works. + const small = await chunked(2); + expect(small.status).toBe(200); + expect(await small.json()).toEqual({ data: { health: 'ok' } }); + }); }); diff --git a/apps/api/src/apiLimits.ts b/apps/api/src/apiLimits.ts index 5007b96..0919068 100644 --- a/apps/api/src/apiLimits.ts +++ b/apps/api/src/apiLimits.ts @@ -44,6 +44,42 @@ export const DEFAULT_API_LIMITS: ApiLimits = { /** Bodies above this are refused before parsing (a recipe is far smaller). */ export const MAX_REQUEST_BYTES = 1_000_000; +/** + * Passes the request's body through while counting the bytes actually read, + * and fails the stream once more than maxBytes arrive. Content-Length is + * only a claim by the client: chunked requests have none, and others can + * send more than they state. exceeded() tells the caller that a failed read + * was caused by the limit. + */ +export function limitRequestBody(request: Request, maxBytes: number) { + let exceeded = false; + if (!request.body) return { request, exceeded: () => exceeded }; + const reader = request.body.getReader(); + let received = 0; + const body = new ReadableStream({ + async pull(controller) { + const { done, value } = await reader.read(); + if (done) return controller.close(); + received += value.byteLength; + if (received > maxBytes) { + exceeded = true; + controller.error(new Error('Request body too large.')); + reader.cancel().catch(() => undefined); + } else controller.enqueue(value); + }, + cancel: (reason) => reader.cancel(reason), + }); + return { + request: new Request(request.url, { + method: request.method, + headers: request.headers, + body, + duplex: 'half', + } as RequestInit), + exceeded: () => exceeded, + }; +} + /** * Rejects operations that are too deep, too wide or repeat fields through * aliases, before any resolver runs. Introspection (__schema, __type) is diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index a25b062..4e08029 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -7,7 +7,7 @@ import { createRecipeRepository } from './features/recipes/recipeRepository.js'; import { createRecipeResolvers } from './features/recipes/recipeResolvers.js'; import { readFileSync } from 'node:fs'; import { createSchema, createYoga } from 'graphql-yoga'; -import type { ValidationRule } from 'graphql'; +import { GraphQLError, type ValidationRule } from 'graphql'; import type { Resolvers } from './generated.js'; import type { IncomingMessage } from 'node:http'; @@ -19,6 +19,7 @@ import { authClientKey } from './features/auth/authRateLimit.js'; import { createRequestRateLimiter, DEFAULT_API_LIMITS, + limitRequestBody, MAX_REQUEST_BYTES, queryLimitsRule, type ApiLimits, @@ -84,6 +85,29 @@ export function createApp( }) { addValidationRule(queryLimitsRule(limits.query)); }, + // The body limit also covers requests that give no Content-Length + // (chunked) or send more than they state: the bytes read are counted. + onRequestParse({ request, requestParser, setRequestParser }) { + if (request.method !== 'POST' || !requestParser) return; + const parse = requestParser; + setRequestParser(async (received) => { + const limited = limitRequestBody(received, MAX_REQUEST_BYTES); + try { + // Awaited so a failed read can be told from a bad body; the + // cast is only because Yoga does not export its parser type. + return (await parse(limited.request)) as never; + } catch (error) { + if (limited.exceeded()) + throw new GraphQLError('Request too large.', { + extensions: { + code: 'PAYLOAD_TOO_LARGE', + http: { status: 413 }, + }, + }); + throw error; + } + }); + }, async onRequest({ request, serverContext, fetchAPI, endResponse }) { const blocked = ( status: number, @@ -109,7 +133,8 @@ export function createApp( endResponse(imageResponse); return; } - // Refuse oversized bodies before they are parsed. + // Refuse bodies that announce an oversized length before reading + // them; onRequestParse counts the bytes of the rest. if ( Number(request.headers.get('content-length') ?? 0) > MAX_REQUEST_BYTES diff --git a/docs/recipe-api.md b/docs/recipe-api.md index b729db8..6e16bfc 100644 --- a/docs/recipe-api.md +++ b/docs/recipe-api.md @@ -188,7 +188,9 @@ Grensene ligger i `apps/api/src/apiLimits.ts` og kan overstyres i `createApp` noen resolver kjører. Introspeksjon (`__schema`, `__type`) teller som andre felt for alias, toppnivåfelt og totalt antall felt, men ikke for dybde, slik at GraphiQLs standardspørring (15 nivåer, ca. 230 felt) går gjennom. -- **Størrelse:** forespørsler over 1 MB (`Content-Length`) avvises med `413`. +- **Størrelse:** forespørsler over 1 MB avvises med `413`. `Content-Length` + avviser raskt; i tillegg telles bytene som faktisk leses, slik at chunked + forespørsler uten `Content-Length` også stoppes. - **Nye oppskrifter:** høyst 30 per bruker per time (`RATE_LIMITED` med `retryAfterSeconds`) og 1000 totalt (`QUOTA_EXCEEDED`). En lås per bruker gjør at parallelle forespørsler telles etter hverandre. Seed og direkte From 2bbc4c4e33e2e00e285f4e920f0a78442efebbec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 18:27:49 +0100 Subject: [PATCH 4/5] fix(api): count a request toward the rate limit only after CSRF checks pass Requests were counted before the CSRF header and content-type checks, so a stream of requests that were refused anyway (403) could use up a client's whole per-minute budget and lock them out. The checks now run first and the request is counted only when they pass, so refused requests cost the client nothing. Test: repeated requests with a wrong header, a wrong content-type or an oversized Content-Length are refused, and the client's full budget is still available afterwards. --- apps/api/src/apiLimits.test.ts | 15 +++++++++++++++ apps/api/src/app.ts | 19 +++++++++++-------- docs/recipe-api.md | 4 +++- 3 files changed, 29 insertions(+), 9 deletions(-) diff --git a/apps/api/src/apiLimits.test.ts b/apps/api/src/apiLimits.test.ts index 988e3d4..2c6dd40 100644 --- a/apps/api/src/apiLimits.test.ts +++ b/apps/api/src/apiLimits.test.ts @@ -174,6 +174,21 @@ describe('API limits over HTTP', () => { }); }); + it('does not count rejected requests toward the request limit', async () => { + const api = app({ requestsPerMinute: 2 }); + const bad = (headers: Record) => + post(api, '{ health }', headers); + for (let attempt = 0; attempt < 5; attempt++) { + expect((await bad({ 'X-Requested-With': 'other' })).status).toBe(403); + expect((await bad({ 'Content-Type': 'text/plain' })).status).toBe(403); + expect((await bad({ 'Content-Length': '1000001' })).status).toBe(413); + } + // The client's whole budget is still there. + expect((await post(api, '{ health }')).status).toBe(200); + expect((await post(api, '{ health }')).status).toBe(200); + expect((await post(api, '{ health }')).status).toBe(429); + }); + it('refuses a request body larger than 1 MB', async () => { const response = await post(app(), '{ health }', { 'Content-Length': '1000001', diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 4e08029..925d679 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -142,6 +142,17 @@ export function createApp( blocked(413, 'Request too large.', { code: 'PAYLOAD_TOO_LARGE' }); return; } + if ( + request.method === 'POST' && + (request.headers.get('x-requested-with') !== 'recipe-platform' || + request.headers.get('content-type')?.split(';')[0]?.trim() !== + 'application/json') + ) { + blocked(403, 'Request blocked.', { code: 'FORBIDDEN' }); + return; + } + // Counted only now: requests refused above cost the server almost + // nothing and must not use up a client's budget. const retryAfterSeconds = requestLimiter.take( authClientKey( request, @@ -160,14 +171,6 @@ export function createApp( ); return; } - if ( - request.method === 'POST' && - (request.headers.get('x-requested-with') !== 'recipe-platform' || - request.headers.get('content-type')?.split(';')[0]?.trim() !== - 'application/json') - ) { - blocked(403, 'Request blocked.', { code: 'FORBIDDEN' }); - } }, onResponse({ request, response }) { const cookie = cookies.get(request); diff --git a/docs/recipe-api.md b/docs/recipe-api.md index 6e16bfc..2ff26c1 100644 --- a/docs/recipe-api.md +++ b/docs/recipe-api.md @@ -182,7 +182,9 @@ Grensene ligger i `apps/api/src/apiLimits.ts` og kan overstyres i `createApp` - **Forespørsler:** 300 GraphQL-forespørsler per klient (IP-adresse, samme nøkkel som auth-begrensningen bak Apache) per minutt. Deretter svarer API-et `429` med `Retry-After` og koden `RATE_LIMITED`. Grensen holdes i minnet og - nullstilles ved omstart. + nullstilles ved omstart. En forespørsel telles først etter at CSRF-header og + `Content-Type` er godkjent, så avviste forespørsler (`403`, `413`) bruker + ikke opp klientens kvote. - **Spørringer:** høyst 10 alias, 3 toppnivåfelt, 300 felt etter at fragmenter er utvidet og 8 nivåer. Større spørringer avvises med `QUERY_TOO_COMPLEX` før noen resolver kjører. Introspeksjon (`__schema`, `__type`) teller som andre From 2afca64892dc15060482d0a32d5bda735de0b0b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 19:09:15 +0100 Subject: [PATCH 5/5] fix(api): count __typename in query limits; validate GET queries before rate limiting - __typename now counts toward the total field and alias limits, so a fragment chain of __typename cannot expand to 2^n fields unchecked. It still does not count as a top-level field or as nesting. - A GET that carries a query needs the same X-Requested-With header as a POST. Only requests that run an operation are counted toward the request limit, so malformed or cross-site GETs cannot use up a visitor's quota. --- apps/api/src/apiLimits.test.ts | 51 ++++++++++++++++++++++++++++++++++ apps/api/src/apiLimits.ts | 8 ++++-- apps/api/src/app.ts | 22 +++++++++++---- docs/recipe-api.md | 11 ++++++-- 4 files changed, 82 insertions(+), 10 deletions(-) diff --git a/apps/api/src/apiLimits.test.ts b/apps/api/src/apiLimits.test.ts index 2c6dd40..a4fa786 100644 --- a/apps/api/src/apiLimits.test.ts +++ b/apps/api/src/apiLimits.test.ts @@ -117,6 +117,38 @@ describe('query limits', () => { }); }); +describe('__typename in query limits', () => { + it('counts __typename toward the field limit, so fragment chains of it are rejected', () => { + // Each fragment spreads the next twice: 2^20 __typename fields expanded. + const fragments = Array.from( + { length: 20 }, + (_, index) => + `fragment F${index} on Recipe { ${index === 19 ? '__typename' : `...F${index + 1} ...F${index + 1}`} }`, + ); + const started = performance.now(); + expect( + errors(`{ recipe(id: "1") { ...F0 } } ${fragments.join(' ')}`), + ).toEqual(['The query is too large: more than 300 fields.']); + expect(performance.now() - started).toBeLessThan(500); + }); + + it('counts aliased __typename toward the alias limit', () => { + const aliases = Array.from( + { length: 11 }, + (_, index) => `t${index}: __typename`, + ); + expect(errors(`{ ${aliases.join(' ')} }`)).toEqual([ + 'The query is too large: more than 10 aliases.', + ]); + }); + + it('still accepts the __typename a client adds to a selection', () => { + expect( + errors('{ recipes { __typename items { __typename id } } }'), + ).toEqual([]); + }); +}); + describe('request rate limiter', () => { it('limits each client per window and resets after it', () => { let time = 0; @@ -189,6 +221,25 @@ describe('API limits over HTTP', () => { expect((await post(api, '{ health }')).status).toBe(429); }); + it('does not let GET requests use up the limit, and gives GET queries the same header check', async () => { + const api = app({ requestsPerMinute: 2 }); + const get = (path: string, headers: Record = {}) => + api.fetch(`http://localhost/graphql${path}`, { headers }); + const query = '?query=%7B%20health%20%7D'; + for (let attempt = 0; attempt < 5; attempt++) { + // A query without the custom header (as from another site): refused. + expect((await get(query)).status).toBe(403); + // Malformed or operation-less GETs run nothing and are not counted. + expect((await get('')).status).toBeLessThan(500); + expect((await get('', { Accept: 'text/html' })).status).toBeLessThan(500); + } + // The whole budget is still there; a GET query with the header is counted. + const allowed = { 'X-Requested-With': 'recipe-platform' }; + expect((await get(query, allowed)).status).toBe(200); + expect((await get(query, allowed)).status).toBe(200); + expect((await get(query, allowed)).status).toBe(429); + }); + it('refuses a request body larger than 1 MB', async () => { const response = await post(app(), '{ health }', { 'Content-Length': '1000001', diff --git a/apps/api/src/apiLimits.ts b/apps/api/src/apiLimits.ts index 0919068..d7f2a47 100644 --- a/apps/api/src/apiLimits.ts +++ b/apps/api/src/apiLimits.ts @@ -109,12 +109,16 @@ export function queryLimitsRule(limits: QueryLimits) { if (usage.fields > limits.maxFields) return; if (selection.kind === Kind.FIELD) { const name = selection.name.value; + usage.fields += 1; + if (selection.alias) usage.aliases += 1; + // __typename reads no data: it counts toward the total and + // alias limits (so a fragment chain of __typename cannot make + // the server expand 2^n fields), but not as a top-level field + // or as nesting. if (name === '__typename') continue; const inIntrospection = introspection || name === '__schema' || name === '__type'; - usage.fields += 1; if (depth === 1) usage.root += 1; - if (selection.alias) usage.aliases += 1; if (!inIntrospection) usage.depth = Math.max(usage.depth, depth); if (selection.selectionSet) measure( diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 925d679..335948e 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -142,17 +142,29 @@ export function createApp( blocked(413, 'Request too large.', { code: 'PAYLOAD_TOO_LARGE' }); return; } + // A request runs an operation if it is a POST or a GET with a + // query (the GraphiQL page and malformed GETs run nothing). Both + // need the custom header, which a page on another site cannot add + // without a CORS preflight; POST also needs a JSON body. + const runsOperation = + request.method === 'POST' || + (request.method === 'GET' && + new URL(request.url).searchParams.has('query')); if ( - request.method === 'POST' && + runsOperation && (request.headers.get('x-requested-with') !== 'recipe-platform' || - request.headers.get('content-type')?.split(';')[0]?.trim() !== - 'application/json') + (request.method === 'POST' && + request.headers.get('content-type')?.split(';')[0]?.trim() !== + 'application/json')) ) { blocked(403, 'Request blocked.', { code: 'FORBIDDEN' }); return; } - // Counted only now: requests refused above cost the server almost - // nothing and must not use up a client's budget. + // Only requests that run an operation are counted, and only now: + // refused or operation-less requests cost the server almost nothing + // and must not use up a client's budget (a page on another site + // could otherwise send them from a visitor's browser). + if (!runsOperation) return; const retryAfterSeconds = requestLimiter.take( authClientKey( request, diff --git a/docs/recipe-api.md b/docs/recipe-api.md index 2ff26c1..04567f6 100644 --- a/docs/recipe-api.md +++ b/docs/recipe-api.md @@ -182,14 +182,19 @@ Grensene ligger i `apps/api/src/apiLimits.ts` og kan overstyres i `createApp` - **Forespørsler:** 300 GraphQL-forespørsler per klient (IP-adresse, samme nøkkel som auth-begrensningen bak Apache) per minutt. Deretter svarer API-et `429` med `Retry-After` og koden `RATE_LIMITED`. Grensen holdes i minnet og - nullstilles ved omstart. En forespørsel telles først etter at CSRF-header og - `Content-Type` er godkjent, så avviste forespørsler (`403`, `413`) bruker - ikke opp klientens kvote. + nullstilles ved omstart. Bare forespørsler som kjører en operasjon telles + (POST, og GET med `query`), og først etter at CSRF-headeren + `X-Requested-With` (og for POST `Content-Type`) er godkjent. GET med `query` + uten headeren får `403`. Avviste eller operasjonsløse forespørsler (`403`, + `413`, GraphiQL-siden) bruker ikke opp klientens kvote, så en side på et annet + nettsted kan ikke tømme kvoten til en besøkende. - **Spørringer:** høyst 10 alias, 3 toppnivåfelt, 300 felt etter at fragmenter er utvidet og 8 nivåer. Større spørringer avvises med `QUERY_TOO_COMPLEX` før noen resolver kjører. Introspeksjon (`__schema`, `__type`) teller som andre felt for alias, toppnivåfelt og totalt antall felt, men ikke for dybde, slik at GraphiQLs standardspørring (15 nivåer, ca. 230 felt) går gjennom. + `__typename` teller som felt og alias (så en fragmentkjede av `__typename` + stoppes), men ikke som toppnivåfelt eller dybde. - **Størrelse:** forespørsler over 1 MB avvises med `413`. `Content-Length` avviser raskt; i tillegg telles bytene som faktisk leses, slik at chunked forespørsler uten `Content-Length` også stoppes.