diff --git a/README.md b/README.md index 3a37762..7367361 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,7 @@ The API reads `server/.env` (when present) and process environment variables: | `GRAPHQL_MAX_DEPTH` | `8` | Maximum GraphQL selection depth | | `GRAPHQL_MAX_ALIASES` | `10` | Maximum aliased fields per GraphQL operation | | `GRAPHQL_MAX_COMPLEXITY` | `200` | Maximum weighted complexity score per GraphQL operation | +| `GRAPHQL_MAX_FRAGMENT_SPREADS` | `20` | Maximum total fragment spreads per GraphQL document (short-circuited before validation) | | `GRAPHQL_MAX_BODY_BYTES` | `65536` | Maximum HTTP request body size in bytes (returns `413` when exceeded) | | `PG_POOL_MAX` | `10` | Maximum PostgreSQL pool connections | | `PG_CONNECTION_TIMEOUT_MS` | `5000` | PostgreSQL connection acquisition timeout in milliseconds | diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index bff44ed..708e6da 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -180,6 +180,7 @@ the part that matters most. | 2026-11-25 | erikhfj | Antigravity (`Gemini 4 Neon (High)`) | #132 (PR #140): fixed accessibility gaps, added CSP-safe manual Dark/Light theme toggle (`ThemeToggle`, `useTheme`, external `theme-init.js`), two-step inline review delete confirmation, and UI/UX polish across Discover, Album detail, and Your crate. Verified with unit tests, axe checks, and independent verifier review. | | 2026-11-25 | erikhfj | Antigravity (`Gemini 4 Neon (High)`) | #133 (PR #141): optimized Discover hero WebP assets (`39.16 kB` desktop / `13.39 kB` mobile, responsive ``, `fetchPriority="high"`), improved mobile hero spacing with a `Browse catalog` jump link, added `no-referrer` policy for external artwork, and documented Apache `mod_deflate`, immutable asset caching, CSP/security headers, and VM hardening in `docs/VM-setup.md`. | | 2026-11-25 | erikhfj | Antigravity (`Gemini 4 Neon (High)`) | #135 (PR #142): added AI reflection, model version notes, and prompt-to-revision examples; fixed `AI-USAGE.md` defects and missing `#74` row; re-ran Lighthouse 13.6.0 across Discover, Album detail, and Your crate (desktop/mobile, light/dark) and Playwright axe + 200%/400% zoom reflow checks; synced build sizes and fixed all 10 technical doc discrepancies; recaptured all 9 UI screenshots against the 2,000-album catalog. | +| 2026-11-26 | erikhfj | Antigravity (`Gemini 4 Neon (High)`) | #143: capped total GraphQL `FragmentSpread` nodes in `securityPlugin.onValidate` (`DEFAULT_MAX_FRAGMENT_SPREADS = 20`, configurable via `GRAPHQL_MAX_FRAGMENT_SPREADS`) before `graphql-js` validation runs to stop cyclic `__Schema` fragment-spread DoS in milliseconds in both dev and prod, with unit and HTTP regression tests. Verified with `pnpm format:check`, `pnpm lint`, `pnpm typecheck`, `pnpm test`, and `pnpm build`. | ## Notes diff --git a/server/src/app.ts b/server/src/app.ts index 1505b8d..c75535f 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -12,10 +12,12 @@ import { DEFAULT_MAX_BODY_BYTES, DEFAULT_MAX_ALIASES, DEFAULT_MAX_COMPLEXITY, + DEFAULT_MAX_FRAGMENT_SPREADS, DEFAULT_MAX_QUERY_DEPTH, DEFAULT_RATE_LIMIT_MAX_REQUESTS, DEFAULT_RATE_LIMIT_WINDOW_MS, GRAPHQL_SECURITY_HEADERS, + checkFragmentSpreadLimit, createCorsConfig, createQueryLimitsRule, createRateLimiter, @@ -34,6 +36,7 @@ export type ServerConfig = { maxQueryDepth?: number; maxAliases?: number; maxComplexity?: number; + maxFragmentSpreads?: number; rateLimitWindowMs?: number; rateLimitMaxRequests?: number; now?: () => number; @@ -70,6 +73,11 @@ export function configFromEnv( maxComplexity: parseOptionalInt(env.GRAPHQL_MAX_COMPLEXITY, DEFAULT_MAX_COMPLEXITY, { min: 1, }), + maxFragmentSpreads: parseOptionalInt( + env.GRAPHQL_MAX_FRAGMENT_SPREADS, + DEFAULT_MAX_FRAGMENT_SPREADS, + { min: 1 }, + ), rateLimitWindowMs: parseOptionalInt( env.RATE_LIMIT_WINDOW_MS, DEFAULT_RATE_LIMIT_WINDOW_MS, @@ -165,6 +173,7 @@ function readBoundedBody(req: IncomingMessage, maxBytes: number): Promise = { - onValidate({ addValidationRule }) { + onValidate({ params, addValidationRule, setResult }) { + const spreadLimitError = checkFragmentSpreadLimit( + params.documentAST, + maxFragmentSpreads, + ); + if (spreadLimitError) { + setResult([spreadLimitError]); + return; + } addValidationRule(queryLimitsRule); if (isProduction) { addValidationRule(noIntrospectionRule); diff --git a/server/src/security.test.ts b/server/src/security.test.ts index df74645..c582fe3 100644 --- a/server/src/security.test.ts +++ b/server/src/security.test.ts @@ -19,6 +19,8 @@ import { } from './app.js'; import type { Db } from './db/client.js'; import { + DEFAULT_MAX_FRAGMENT_SPREADS, + checkFragmentSpreadLimit, createQueryLimitsRule, createRateLimiter, getClientIp, @@ -31,6 +33,20 @@ const schema = buildSchema(typeDefs); const stubDb = {} as unknown as Db; +function buildSchemaFragmentBomb(count = 11): string { + const names = Array.from({ length: count }, (_, i) => `S${i}`); + const fragments = names + .map((name) => { + const spreads = names + .filter((other) => other !== name) + .map((other) => `...${other}`) + .join(' '); + return `fragment ${name} on __Schema { ${spreads} }`; + }) + .join('\n'); + return `query { __schema { ...S0 } }\n${fragments}`; +} + function validateQuery(query: string, extraRules = [createQueryLimitsRule()]) { return validate(schema, parse(query), [...specifiedRules, ...extraRules]); } @@ -293,6 +309,33 @@ describe('GraphQL validation limits', () => { ); }); + it('caps total fragment spreads in checkFragmentSpreadLimit while allowing introspection and queries within the cap', () => { + expect(checkFragmentSpreadLimit(parse(getIntrospectionQuery()))).toBeNull(); + + const atCap = ` + query { ${Array.from({ length: DEFAULT_MAX_FRAGMENT_SPREADS }, () => '...Q').join(' ')} } + fragment Q on Query { __typename } + `; + expect(checkFragmentSpreadLimit(parse(atCap))).toBeNull(); + + const overCap = ` + query { ${Array.from({ length: DEFAULT_MAX_FRAGMENT_SPREADS + 1 }, () => '...Q').join(' ')} } + fragment Q on Query { __typename } + `; + const overCapError = checkFragmentSpreadLimit(parse(overCap)); + expect(overCapError?.message).toContain( + `maximum allowed fragment spread count of ${DEFAULT_MAX_FRAGMENT_SPREADS}`, + ); + + const start = performance.now(); + const bombError = checkFragmentSpreadLimit(parse(buildSchemaFragmentBomb(11))); + const elapsedMs = performance.now() - start; + expect(bombError?.message).toContain( + `maximum allowed fragment spread count of ${DEFAULT_MAX_FRAGMENT_SPREADS}`, + ); + expect(elapsedMs).toBeLessThan(100); + }); + it('blocks __schema and __type with noIntrospectionRule while allowing __typename', () => { expect(validateQuery('{ __typename }', [noIntrospectionRule])).toEqual([]); @@ -328,11 +371,13 @@ describe('client IP & CORS helpers', () => { NODE_ENV: 'production', CORS_ORIGIN: 'https://crate.example', GRAPHQL_MAX_BODY_BYTES: '81920', + GRAPHQL_MAX_FRAGMENT_SPREADS: '15', RATE_LIMIT_MAX_REQUESTS: '50', }); expect(cfg.isProduction).toBe(true); expect(cfg.corsOrigins).toEqual(['https://crate.example']); expect(cfg.maxBodyBytes).toBe(81_920); + expect(cfg.maxFragmentSpreads).toBe(15); expect(cfg.rateLimitMaxRequests).toBe(50); }); @@ -520,6 +565,70 @@ describe('HTTP server hardening', () => { expect(prodBody.errors?.[0]?.message).toContain('introspection is disabled'); }); + it('rejects cyclic __Schema fragment-spread bombs before validation in both dev and prod', async () => { + const bomb = buildSchemaFragmentBomb(11); + + for (const isProduction of [false, true]) { + const instance = await startTestServer({ isProduction }); + servers.push(instance.server); + + const start = performance.now(); + const res = await fetch(instance.url, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ query: bomb }), + }); + const elapsedMs = performance.now() - start; + + const body = (await res.json()) as { + data?: unknown; + errors?: { message: string }[]; + }; + expect(body.data).toBeUndefined(); + expect(body.errors).toHaveLength(1); + expect(body.errors?.[0]?.message).toContain( + `maximum allowed fragment spread count of ${DEFAULT_MAX_FRAGMENT_SPREADS}`, + ); + expect(elapsedMs).toBeLessThan(100); + } + }); + + it('enforces the fragment spread cap over HTTP while allowing valid queries within the cap', async () => { + const instance = await startTestServer({ isProduction: false }); + servers.push(instance.server); + + const allowedQuery = ` + query { ${Array.from({ length: DEFAULT_MAX_FRAGMENT_SPREADS }, () => '...Q').join(' ')} } + fragment Q on Query { __typename } + `; + const allowedRes = await fetch(instance.url, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ query: allowedQuery }), + }); + expect(allowedRes.status).toBe(200); + expect(await allowedRes.json()).toEqual({ data: { __typename: 'Query' } }); + + const rejectedQuery = ` + query { ${Array.from({ length: DEFAULT_MAX_FRAGMENT_SPREADS + 1 }, () => '...Q').join(' ')} } + fragment Q on Query { __typename } + `; + const rejectedRes = await fetch(instance.url, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ query: rejectedQuery }), + }); + const rejectedBody = (await rejectedRes.json()) as { + data?: unknown; + errors?: { message: string }[]; + }; + expect(rejectedBody.data).toBeUndefined(); + expect(rejectedBody.errors).toHaveLength(1); + expect(rejectedBody.errors?.[0]?.message).toContain( + `maximum allowed fragment spread count of ${DEFAULT_MAX_FRAGMENT_SPREADS}`, + ); + }); + it('rejects non-/graphql paths with 404 before Yoga and prevents rate-limit bypass', async () => { expect(buildInternalGraphqlUrl('/graphql')).toBe('http://localhost/graphql'); expect(buildInternalGraphqlUrl('/graphql?query=%7B__typename%7D')).toBe( diff --git a/server/src/security.ts b/server/src/security.ts index 174627d..29327c8 100644 --- a/server/src/security.ts +++ b/server/src/security.ts @@ -1,6 +1,7 @@ import { GraphQLError, Kind, + type DocumentNode, type FieldNode, type FragmentDefinitionNode, type FragmentSpreadNode, @@ -23,6 +24,7 @@ export type CorsConfig = export const DEFAULT_MAX_QUERY_DEPTH = 8; export const DEFAULT_MAX_ALIASES = 10; export const DEFAULT_MAX_COMPLEXITY = 200; +export const DEFAULT_MAX_FRAGMENT_SPREADS = 20; export const DEFAULT_MAX_BODY_BYTES = 65_536; // 64 KiB export const DEFAULT_RATE_LIMIT_WINDOW_MS = 60_000; export const DEFAULT_RATE_LIMIT_MAX_REQUESTS = 180; @@ -64,6 +66,57 @@ function readFirstArgument(field: FieldNode): number { return MAX_CONNECTION_PAGE_SIZE; } +/** + * Counts `FragmentSpread` AST nodes across the document without expanding + * fragments and returns a `GraphQLError` as soon as the total exceeds + * `maxFragmentSpreads`. Running this in `onValidate` before `graphql-js` + * executes its built-in validation rules prevents exponential validation + * blow-ups from mutually-spreading fragments (including on `__Schema`). + */ +export function checkFragmentSpreadLimit( + document: DocumentNode, + maxFragmentSpreads = DEFAULT_MAX_FRAGMENT_SPREADS, +): GraphQLError | null { + let spreadCount = 0; + const stack: SelectionSetNode[] = []; + + for (let i = document.definitions.length - 1; i >= 0; i -= 1) { + const definition = document.definitions[i]; + if ( + definition && + (definition.kind === Kind.OPERATION_DEFINITION || + definition.kind === Kind.FRAGMENT_DEFINITION) + ) { + stack.push(definition.selectionSet); + } + } + + while (stack.length > 0) { + const selectionSet = stack.pop()!; + const childSelectionSets: SelectionSetNode[] = []; + for (const selection of selectionSet.selections) { + if (selection.kind === Kind.FRAGMENT_SPREAD) { + spreadCount += 1; + if (spreadCount > maxFragmentSpreads) { + return new GraphQLError( + `Query exceeds maximum allowed fragment spread count of ${maxFragmentSpreads}.`, + { nodes: selection }, + ); + } + } else if (selection.kind === Kind.FIELD && selection.selectionSet) { + childSelectionSets.push(selection.selectionSet); + } else if (selection.kind === Kind.INLINE_FRAGMENT) { + childSelectionSets.push(selection.selectionSet); + } + } + for (let i = childSelectionSets.length - 1; i >= 0; i -= 1) { + stack.push(childSelectionSets[i]!); + } + } + + return null; +} + /** * GraphQL validation rule enforcing bounded query depth, alias count, and * selection/nesting complexity (including blocking nested Album.reviews