**Priority:** High (Final sprint before 27 Nov) **Source:** Peer feedback + pre-submission code & security audit ## Problem 1. **Unbounded GraphQL query & HTTP execution (`server/src/index.ts:13-25`, `server/src/resolvers.ts:178-215,362-363`):** - `createYoga` enforces no query depth, alias, or selection complexity limits, and `createServer(yoga)` enforces no HTTP body size limit (verified accepting 100 aliased fields and 2 MiB JSON bodies). - `Album.reviews` (`resolvers.ts:362-363`) is not DataLoader-backed, so combining nested `reviews` with GraphQL aliases amplifies a single HTTP request into hundreds of SQL queries. - No per-IP rate limiting exists on `/graphql`, allowing write-table spam (`app_user`, `review`, `crate_item`, `search_history`) or repeated expensive facet queries. 2. **Permissive default CORS & unconditionally exposed GraphiQL/introspection (`server/src/index.ts:13-20`):** - Yoga's default CORS reflects any `Origin` with `Access-Control-Allow-Credentials: true`, even though both Apache (`/graphql`) and Vite proxy same-origin. - GraphiQL (`GET /graphql`) and `__schema`/`__type` introspection remain enabled in production, and `/graphql` responses lack `Cache-Control: no-store` and `X-Content-Type-Options: nosniff`. 3. **PostgreSQL pool timeouts, error handling, and graceful shutdown (`server/src/db/client.ts:12`, `server/src/index.ts:24-26`):** - `new pg.Pool({ connectionString: url })` configures no `statement_timeout`, `connectionTimeoutMillis`, or `idle_in_transaction_session_timeout`, and attaches no `pool.on('error', ...)` listener (an idle backend disconnect crashes Node). - `server/src/index.ts` has no `SIGTERM`/`SIGINT` graceful shutdown handler to drain HTTP requests and call `pool.end()` on `systemctl restart crate-api`. 4. **Review/crate/cursor bugs & incomplete `int4` input validation (`server/src/reviews.ts:18,28-32,46-54,94`, `server/src/crate.ts:8,16-30`, `server/src/resolvers.ts:44-111,185-190,384-387`, `server/src/search/search.ts:52-57,75-79,308`, `server/src/db/schema.ts:172`):** - `removeReview` (`reviews.ts:94`) calls `parseAlbumId(reviewId)` and throws `'Invalid album id.'` for an invalid review ID. - `findAlbum` in `reviews.ts:48` and `crate.ts:24` omits `musicBrainzReleaseGroupId`, returning `null` if a mutation selects it. - `upsertReview` / `deleteReview` (`resolvers.ts:384-387`) do not clear `ctx.loaders.myReviewByAlbum`, `reviewCountByAlbum`, or `averageRatingByAlbum` (unlike crate mutations at `:388-401`). - `parseNumericId`, `parseAlbumId`, `parseGenreId` (which treats `""` as `0`), `parseDecade`, and cursor `id` checks do not enforce PostgreSQL 32-bit `int4` bounds (`1..2_147_483_647`). - `decodeReviewCursor` (`resolvers.ts:61-67`) relies on loose `Date.parse`, letting non-ISO strings like `"1"` reach PostgreSQL and cause `22007` internal errors; `reviewsForAlbum` (`resolvers.ts:185-190`) uses `or(lt, and(eq, lt))` without tuple keyset comparison. 5. **Backend helper duplication (`server/src/reviews.ts`, `server/src/crate.ts`, `server/src/resolvers.ts:44-111,313,327-328`, `server/src/search/search.ts:29,291-313`, `server/src/searchHistory.ts:9`):** - `AlbumRecord`, `parseAlbumId`/`parseNumericId`, `findAlbum`, `MAX_SEARCH_QUERY_LENGTH`, and base64url cursor codecs are duplicated across files; `new Intl.DisplayNames(['en'], { type: 'region' })` is recreated per row inside `.map()` (`resolvers.ts:313`); stale comment remains at `resolvers.ts:327-328`. ## Suggested solution - Add GraphQL validation rules in `server/src/index.ts` (or a dedicated `server/src/security.ts` helper) enforcing bounded depth (`<= 8`), max aliases (`<= 10`), and complexity/selection limits, plus an HTTP request body size limit (`64–100 KiB` returning `413`) and lightweight env-configurable per-IP rate limiting (trusting `X-Forwarded-For` only when `remoteAddress` is `127.0.0.1`/`::1`, returning `429` + `Retry-After`). - Disable CORS by default (or allow explicit `CORS_ORIGIN` allowlist with `credentials: false`), disable GraphiQL and `__schema`/`__type` introspection when `NODE_ENV === 'production'` (keeping `{ __typename }` working for CI smoke checks), and set `Cache-Control: no-store` and `X-Content-Type-Options: nosniff` on `/graphql`. - Configure `pg.Pool` timeouts (`statement_timeout` e.g. `10_000` ms overridable via env for CLI scripts, `connectionTimeoutMillis` `5_000` ms, `idle_in_transaction_session_timeout` `15_000` ms, explicit `max`), attach `pool.on('error', ...)`, and add `SIGTERM`/`SIGINT` graceful shutdown. - Extract shared server helpers (`parseNumericId` with `int4` bounds, `findAlbum` selecting `musicBrainzReleaseGroupId`, `MAX_SEARCH_QUERY_LENGTH`, strict UTC timestamp/base64url cursor codec), hoist `Intl.DisplayNames`, fix `removeReview` error text, clear review DataLoaders on mutations, and switch `reviewsForAlbum` to tuple keyset comparison `(review.created_at, review.id) < (...)`. ## Acceptance criteria - [ ] Oversized HTTP bodies (`413`), excessive GraphQL aliases, overly deep/complex queries, and rate-limited bursts (`429` + `Retry-After`) are rejected while all legitimate client queries/mutations pass. - [ ] Cross-origin requests with untrusted `Origin` headers are not reflected; GraphiQL and `__schema`/`__type` introspection are disabled when `NODE_ENV=production` while `{ __typename }` continues to succeed; `/graphql` returns `Cache-Control: no-store` and `X-Content-Type-Options: nosniff`. - [ ] `pg.Pool` configures explicit `statement_timeout`, `connectionTimeoutMillis`, `idle_in_transaction_session_timeout`, `max`, and `pool.on('error', ...)`, and `server/src/index.ts` handles `SIGTERM`/`SIGINT` gracefully (`db:migrate` and `db:import:musicbrainz` still succeed). - [ ] `removeReview` throws `'Invalid review id.'`; `findAlbum` selects `musicBrainzReleaseGroupId`; review mutations clear affected per-request DataLoaders; ID/genre/decade/cursor validators enforce 32-bit `int4` bounds and reject empty strings; `decodeReviewCursor` strictly validates timestamps and `reviewsForAlbum` uses tuple keyset comparison. - [ ] Shared server helpers are deduplicated, `Intl.DisplayNames` is hoisted to module scope, stale comment at `resolvers.ts:327-328` is removed, and unit tests cover all new validation/security behaviors. ### Optional stretch (if time permits) - [ ] Split query helper functions out of `server/src/resolvers.ts` into domain modules (`search/`, `crate.ts`, `reviews.ts`).