diff --git a/apps/api/src/apiLimits.test.ts b/apps/api/src/apiLimits.test.ts new file mode 100644 index 0000000..a4fa786 --- /dev/null +++ b/apps/api/src/apiLimits.test.ts @@ -0,0 +1,281 @@ +// @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 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 }, + (_, 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('__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; + 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('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('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', + }); + 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 new file mode 100644 index 0000000..d7f2a47 --- /dev/null +++ b/apps/api/src/apiLimits.ts @@ -0,0 +1,205 @@ +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; + +/** + * 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 + * 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 => { + 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, + introspection: boolean, + ) { + for (const selection of selections.selections) { + 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'; + if (depth === 1) usage.root += 1; + if (!inIntrospection) usage.depth = Math.max(usage.depth, depth); + if (selection.selectionSet) + measure( + selection.selectionSet, + depth + 1, + spreading, + inIntrospection, + ); + } else if (selection.kind === Kind.INLINE_FRAGMENT) { + 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, introspection); + spreading.delete(name); + } + } + } + measure(operation.selectionSet, 1, new Set(), false); + + 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..335948e 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 { GraphQLError, type ValidationRule } from 'graphql'; import type { Resolvers } from './generated.js'; import type { IncomingMessage } from 'node:http'; @@ -15,6 +16,15 @@ import { type AuthContext, } from './features/auth/authResolvers.js'; import { authClientKey } from './features/auth/authRateLimit.js'; +import { + createRequestRateLimiter, + DEFAULT_API_LIMITS, + limitRequestBody, + MAX_REQUEST_BYTES, + queryLimitsRule, + type ApiLimits, + type QueryLimits, +} from './apiLimits.js'; import { authService, type AuthService } from './features/auth/authService.js'; import { readSessionCookie, @@ -34,7 +44,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 +63,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 +78,52 @@ export function createApp( }, plugins: [ { - async onRequest({ request, fetchAPI, endResponse }) { + onValidate({ + addValidationRule, + }: { + addValidationRule: (rule: ValidationRule) => void; + }) { + 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, + 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 +133,55 @@ export function createApp( endResponse(imageResponse); return; } + // 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 + ) { + 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')) ) { - 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' }); + return; + } + // 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, + // 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; } }, onResponse({ request, response }) { diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts index 8aac90e..018c1a6 100644 --- a/apps/api/src/features/recipes/recipeRepository.ts +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -4,6 +4,7 @@ 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'; /** * Turns the user's search text into a PostgreSQL tsquery that matches @@ -19,7 +20,14 @@ export function toSearchQuery(search: string) { return [...new Set(words)].map((word) => `${word}:*`).join(' & '); } -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}"`; @@ -137,29 +145,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) => [ @@ -227,6 +275,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 2af7982..ae6e0ca 100644 --- a/apps/web/src/features/recipes/recipeApi.ts +++ b/apps/web/src/features/recipes/recipeApi.ts @@ -107,6 +107,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.', CONFLICT: 'This recipe was changed in another tab or session after you opened it, so your version was not saved. Your changes are still in the form: save a draft, reload the page to see the latest version, then restore the draft if you want to keep your changes.', }; 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 378d1fb..04567f6 100644 --- a/docs/recipe-api.md +++ b/docs/recipe-api.md @@ -169,11 +169,43 @@ 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. 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. +- **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 c34d95a..ac596d0 100644 --- a/scripts/test-recipe-api.ts +++ b/scripts/test-recipe-api.ts @@ -741,6 +741,64 @@ 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( 'refuses an update based on an outdated version (CONFLICT)', async () => { @@ -928,6 +986,78 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { } }, ); + 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( 'cached ratings and search words stay correct under concurrent writes', async () => {