-
Notifications
You must be signed in to change notification settings - Fork 0
fix: #129 harden GraphQL API & PostgreSQL pool, fix review/cursor bugs, and deduplicate server helpers #136
Conversation
There was a problem hiding this 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:largeuse the same pool, so they now get the 10 sstatement_timeouttoo. Default to0for 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.
|
Thanks for the thorough review, @evenkkl! All review items have been addressed in
Additional notes:
Stacked PR #139 ( |
There was a problem hiding this 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.
Closes #129
What was done
GraphQL & HTTP API hardening (
server/src/security.ts,server/src/app.ts,server/src/index.ts)<= 8), alias count (<= 10), and complexity/selection limits (<= 200, including blocking fragment expansion bombs and nestedAlbum.reviewsN+1 amplification insidesearchAlbums/myCrate).GRAPHQL_MAX_BODY_BYTES) rejecting both oversizedContent-Lengthand chunked payloads with413 Payload Too Large.RATE_LIMIT_WINDOW_MS,RATE_LIMIT_MAX_REQUESTS) on/graphql, trustingX-Forwarded-For(rightmost proxy-appended hop) only whenremoteAddressis loopback (127.0.0.1/::1/::ffff:127.0.0.1), returning429+Retry-After.cors: false) with optionalCORS_ORIGINcomma-separated allowlist (credentials: false); untrustedOriginheaders are never reflected.__schema/__typeintrospection whenNODE_ENV=productionwhile keeping{ __typename }working for CI smoke checks and client caches.Cache-Control: no-storeandX-Content-Type-Options: nosniffon all/graphqlresponses (including error responses).SIGTERM/SIGINTgraceful shutdown closing the HTTP server and callingpool.end().PostgreSQL pool hardening (
server/src/db/poolConfig.ts,server/src/db/client.ts)statement_timeout(10s default, env-overridable viaPG_STATEMENT_TIMEOUT_MSincluding0for CLI scripts),connectionTimeoutMillis(5s),idle_in_transaction_session_timeout(15s), andmax(10).pool.on('error', ...)so idle backend disconnects log instead of crashing Node.Bug fixes,
int4validation & 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)removeReviewto validate review IDs with'Invalid review id.'instead of'Invalid album id.'.findAlbum/findAlbumById/AlbumRecordnow selectmusicBrainzReleaseGroupId.myReviewByAlbum,reviewCountByAlbum,averageRatingByAlbum,albumById) inupsertReviewanddeleteReview.int4bounds (1..2_147_483_647for IDs/cursor IDs,0..2_147_483_647for decades) and rejected empty/whitespace strings on all ID, genre, decade, and cursor validators.decodeReviewCursorto strict microsecond UTC timestamp validation and switchedreviewsForAlbumto tuple keyset comparison("review"."created_at", "review"."id") < ($2::timestamptz, $3).MAX_SEARCH_QUERY_LENGTH, album lookup, and base64url timestamp cursor helpers; hoistedIntl.DisplayNamesto module scope; removed stale comment inresolvers.ts; splitsearchAlbums,reviewsForAlbum, andcrateForUserinto domain modules.What was tested
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→ succeededpnpm --filter @t19/server exec vitest run→ 16/16 test files, 203/203 tests passednode server/scripts/assert-postgres-tests.mjs→ all 6 database-backed suites executedNew/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, andserver/src/search/search.test.ts.