Skip to content
281 changes: 281 additions & 0 deletions apps/api/src/apiLimits.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof createApp>,
query: string,
headers: Record<string, string> = {},
) =>
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<string, string>) =>
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<string, string> = {}) =>
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' } });
});
});
Loading