Skip to content

Conversation

erikhfj
Copy link
Member

@erikhfj erikhfj commented Nov 24, 2026

Closes #129

What was done

GraphQL & HTTP API hardening (server/src/security.ts, server/src/app.ts, server/src/index.ts)

  • Added GraphQL validation rules enforcing bounded query depth (<= 8), alias count (<= 10), and complexity/selection limits (<= 200, including blocking fragment expansion bombs and nested Album.reviews N+1 amplification inside searchAlbums / myCrate).
  • Added an HTTP request body size cap (default 64 KiB, overridable via GRAPHQL_MAX_BODY_BYTES) rejecting both oversized Content-Length and chunked payloads with 413 Payload Too Large.
  • Added lightweight env-configurable per-IP rate limiting (RATE_LIMIT_WINDOW_MS, RATE_LIMIT_MAX_REQUESTS) on /graphql, trusting X-Forwarded-For (rightmost proxy-appended hop) only when remoteAddress is loopback (127.0.0.1 / ::1 / ::ffff:127.0.0.1), returning 429 + Retry-After.
  • Disabled CORS by default (cors: false) with optional CORS_ORIGIN comma-separated allowlist (credentials: false); untrusted Origin headers are never reflected.
  • Disabled GraphiQL and __schema / __type introspection when NODE_ENV=production while keeping { __typename } working for CI smoke checks and client caches.
  • Set Cache-Control: no-store and X-Content-Type-Options: nosniff on all /graphql responses (including error responses).
  • Added SIGTERM / SIGINT graceful shutdown closing the HTTP server and calling pool.end().

PostgreSQL pool hardening (server/src/db/poolConfig.ts, server/src/db/client.ts)

  • Configured explicit statement_timeout (10s default, env-overridable via PG_STATEMENT_TIMEOUT_MS including 0 for CLI scripts), connectionTimeoutMillis (5s), idle_in_transaction_session_timeout (15s), and max (10).
  • Attached pool.on('error', ...) so idle backend disconnects log instead of crashing Node.

Bug fixes, int4 validation & helper deduplication (server/src/validation.ts, server/src/albums.ts, server/src/search/queries.ts, server/src/reviews.ts, server/src/crate.ts, server/src/search/search.ts, server/src/searchHistory.ts, server/src/resolvers.ts)

  • Fixed removeReview to validate review IDs with 'Invalid review id.' instead of 'Invalid album id.'.
  • Shared findAlbum / findAlbumById / AlbumRecord now select musicBrainzReleaseGroupId.
  • Cleared and primed affected per-request DataLoaders (myReviewByAlbum, reviewCountByAlbum, averageRatingByAlbum, albumById) in upsertReview and deleteReview.
  • Enforced PostgreSQL 32-bit int4 bounds (1..2_147_483_647 for IDs/cursor IDs, 0..2_147_483_647 for decades) and rejected empty/whitespace strings on all ID, genre, decade, and cursor validators.
  • Tightened decodeReviewCursor to strict microsecond UTC timestamp validation and switched reviewsForAlbum to tuple keyset comparison ("review"."created_at", "review"."id") < ($2::timestamptz, $3).
  • Deduplicated shared numeric ID, MAX_SEARCH_QUERY_LENGTH, album lookup, and base64url timestamp cursor helpers; hoisted Intl.DisplayNames to module scope; removed stale comment in resolvers.ts; split searchAlbums, reviewsForAlbum, and crateForUser into domain modules.

What was tested

pnpm format:check && pnpm lint && pnpm typecheck && pnpm test && pnpm build
# All passed with 0 lint warnings and clean build.

Verified against a local throwaway PostgreSQL cluster:

  • DATABASE_URL="$TEST_DATABASE_URL" pnpm --filter @t19/server db:migrate → Migrations applied.
  • DATABASE_URL="$TEST_DATABASE_URL" pnpm --filter @t19/server db:import:musicbrainz → succeeded
  • pnpm --filter @t19/server exec vitest run → 16/16 test files, 203/203 tests passed
  • node server/scripts/assert-postgres-tests.mjs → all 6 database-backed suites executed

New/expanded unit tests in server/src/security.test.ts, server/src/db/poolConfig.test.ts, server/src/reviews.test.ts, server/src/crate.test.ts, and server/src/search/search.test.ts.

Copy link
Member

@evenkkl evenkkl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work overall. All 203 tests pass for me against a real Postgres, and the cursor, body cap, CORS, X-Forwarded-For and int4 changes hold up. Two things should be fixed before merge, plus a few smaller ones.

1. A small fragment query can block the server (request changes)
createQueryLimitsRule only charges cost for fields, so fragments that only spread each other walk every path without ever hitting the limit. The rule runs before graphql-js rejects the cycle. A 1 KB document with 11 fragments, each spreading all the others, blocked the event loop for ~2.9 s. With a few more fragments it's minutes. Fix: count each fragment spread / inline fragment toward complexity (and error on a spread already in visitedFragments).

2. The rate limit can be bypassed (request changes)
isGraphqlPath only matches /graphql exactly, but Yoga serves any path ending in /graphql. With the limit hit, POST /graphql gives 429 while /graphql/foo/graphql and /graphql//graphql still give 200. Apache's ProxyPass /graphql matches by prefix, so these should get through on the VM too. Fix: return 404 for non-/graphql paths before calling Yoga, and build the yoga.fetch URL from a fixed origin instead of the Host header.

Smaller

  • The depth limit (8) also applies to the introspection query, so GraphiQL can't load the schema in dev. Skip the rule for __schema/__type, since prod already blocks them.
  • Nothing in the repo sets NODE_ENV=production. Is it set on the VM? If not, introspection and GraphiQL stay on in prod.
  • db:migrate/db:import:musicbrainz/db:seed:large use the same pool, so they now get the 10 s statement_timeout too. Default to 0 for scripts, or set it in the deploy step.
  • The new env vars (CORS_ORIGIN, RATE_LIMIT_*, GRAPHQL_MAX_*, PG_*) should be documented in the README.
  • Nit: there's no (album_id, created_at, id) index on reviews, so the tuple keyset is a filter, not a seek. It's fine at this size.

@erikhfj
Copy link
Member Author

erikhfj commented Nov 26, 2026

Thanks for the thorough review, @evenkkl! All review items have been addressed in 6eab778:

  1. Fragment-cycle / spread DoS (server/src/security.ts, server/src/security.test.ts): createQueryLimitsRule now charges complexity (1) for every FragmentSpread and InlineFragment, immediately reports an error and aborts traversal when a spread is already in visitedFragments, and stops walking once any depth/alias/complexity limit is exceeded. Added regression tests including an 11-fragment mutually spreading cyclic document (rejects cleanly in <10 ms).
  2. Path-suffix rate-limit bypass & Host header URL construction (server/src/app.ts, server/src/security.test.ts): Requests to any path other than exact /graphql (with optional query string) are rejected with HTTP 404 before calling Yoga, and yoga.fetch always receives a canonical internal URL built from http://localhost rather than req.headers.host. Added tests covering /graphql/foo/graphql, /graphql//graphql, /graphql/, /, /health, and spoofed/malformed Host headers.
  3. Dev GraphiQL introspection (server/src/security.ts, server/src/security.test.ts): createQueryLimitsRule skips depth/complexity traversal inside __schema and __type subtrees so GraphiQL's full introspection query works in development, while NODE_ENV=production still rejects __schema and __type via noIntrospectionRule. Added unit and HTTP tests for both dev and prod.
  4. CLI DB script timeouts (server/src/db/poolConfig.ts, server/src/db/client.ts, migrate.ts, seed.ts, seedLarge.ts, importMusicBrainz.ts): Exported createDb({ defaultStatementTimeoutMs: 0 }) so the CLI DB scripts default to statement_timeout = 0 (unless PG_STATEMENT_TIMEOUT_MS is explicitly set in the environment) while the API server keeps its 10 s default. Updated server/src/db/poolConfig.test.ts.
  5. Env var documentation (README.md): Added a Server environment variables table covering DATABASE_URL, HOST, PORT, NODE_ENV, CORS_ORIGIN, RATE_LIMIT_*, GRAPHQL_MAX_*, and PG_*.

Additional notes:

Stacked PR #139 (feat/130-unaccent-search) is also being rebased onto this commit. Ready for re-review!

Copy link
Member

@evenkkl evenkkl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, re-reviewed 6eab778. All checks pass, and all five items are fixed. I re-ran both the fragment bomb and the path bypass, and they're now rejected.

One small remaining case: fragments on __Schema are still slow, this time inside graphql-js's own validation (so main has it too). In production, a 1 KB query like query { __schema { ...S0 } }, with S0..S10 each spreading all the others, takes ~2.4 s, and a few more fragments push it to minutes. Suggested fix: count fragment spreads in securityPlugin.onValidate and setResult([...error]) above ~20. The client uses no spreads, so nothing legitimate is affected.

Happy to approve once that's in, or with a follow-up issue for it.

@erikhfj erikhfj merged commit 2a92b9f into main Nov 26, 2026
3 checks passed
@erikhfj erikhfj deleted the fix/129-server-hardening-and-cleanup branch November 26, 2026 19:22
@erikhfj
Copy link
Member Author

erikhfj commented Nov 26, 2026

Thanks again for the approval and catching the __Schema fragment-spread case, @evenkkl! Tracked in follow-up issue #143 (#143).

Sign in to join this conversation on GitHub.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Harden GraphQL API & PostgreSQL pool, fix review/cursor bugs, and deduplicate server helpers
2 participants