diff --git a/README.md b/README.md index fac2443..07457cb 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,28 @@ The default frontend GraphQL endpoint is `/graphql`. To use a different endpoint **Note:** `db:import:musicbrainz` adds or updates the real catalog without deleting albums, reviews or crate items. `db:seed` and `db:seed:large` are reset commands: they replace the catalog and delete associated tracks, reviews and crate items. Do not use either seed command on a database containing data you want to keep. See [VM setup](docs/VM-setup.md) for deployment instructions. +### Server environment variables + +The API reads `server/.env` (when present) and process environment variables: + +| Variable | Default | Description | +| ----------------------------------- | ------------ | -------------------------------------------------------------------------------------------------------- | +| `DATABASE_URL` | _(required)_ | PostgreSQL connection string | +| `HOST` | `127.0.0.1` | Interface the HTTP server binds to | +| `PORT` | `3001` | HTTP server port | +| `NODE_ENV` | _(unset)_ | Set to `production` to disable GraphiQL and schema introspection (`__schema` / `__type`) | +| `CORS_ORIGIN` | _(unset)_ | Comma-separated allowlist of allowed browser origins; unset disables CORS | +| `RATE_LIMIT_MAX_REQUESTS` | `180` | Max requests per client IP per rate-limit window (`0` disables rate limiting) | +| `RATE_LIMIT_WINDOW_MS` | `60000` | Rate-limit window duration in milliseconds | +| `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_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 | +| `PG_STATEMENT_TIMEOUT_MS` | `10000` | PostgreSQL `statement_timeout` in ms (`0` disables; CLI DB scripts default to `0` unless set explicitly) | +| `PG_IDLE_IN_TRANSACTION_TIMEOUT_MS` | `15000` | PostgreSQL `idle_in_transaction_session_timeout` in milliseconds (`0` disables) | + ### Checks and useful commands Before opening a PR, run: diff --git a/server/src/albums.ts b/server/src/albums.ts new file mode 100644 index 0000000..6bc4ee3 --- /dev/null +++ b/server/src/albums.ts @@ -0,0 +1,34 @@ +import { eq } from 'drizzle-orm'; +import { GraphQLError } from 'graphql'; + +import type { Db } from './db/client.js'; +import { album } from './db/schema.js'; + +export type AlbumRecord = { + id: number; + title: string; + releaseYear: number | null; + musicBrainzReleaseGroupId: string | null; +}; + +const albumColumns = { + id: album.id, + title: album.title, + releaseYear: album.releaseYear, + musicBrainzReleaseGroupId: album.musicBrainzReleaseGroupId, +}; + +export async function findAlbumById(db: Db, id: number): Promise { + const [found] = await db + .select(albumColumns) + .from(album) + .where(eq(album.id, id)) + .limit(1); + return found ?? null; +} + +export async function findAlbum(db: Db, id: number): Promise { + const found = await findAlbumById(db, id); + if (!found) throw new GraphQLError('Album not found.'); + return found; +} diff --git a/server/src/app.ts b/server/src/app.ts new file mode 100644 index 0000000..1505b8d --- /dev/null +++ b/server/src/app.ts @@ -0,0 +1,338 @@ +import { + createServer, + type IncomingMessage, + type Server, + type ServerResponse, +} from 'node:http'; +import { createSchema, createYoga, type Plugin } from 'graphql-yoga'; +import type { Db } from './db/client.js'; +import { createLoaders } from './loaders/index.js'; +import { resolvers, type Context } from './resolvers.js'; +import { + DEFAULT_MAX_BODY_BYTES, + DEFAULT_MAX_ALIASES, + DEFAULT_MAX_COMPLEXITY, + DEFAULT_MAX_QUERY_DEPTH, + DEFAULT_RATE_LIMIT_MAX_REQUESTS, + DEFAULT_RATE_LIMIT_WINDOW_MS, + GRAPHQL_SECURITY_HEADERS, + createCorsConfig, + createQueryLimitsRule, + createRateLimiter, + getClientIp, + noIntrospectionRule, + parseCorsOrigins, +} from './security.js'; +import { parseUserId } from './userIdentity.js'; + +export type ServerConfig = { + db: Db; + typeDefs: string; + isProduction?: boolean; + corsOrigins?: readonly string[]; + maxBodyBytes?: number; + maxQueryDepth?: number; + maxAliases?: number; + maxComplexity?: number; + rateLimitWindowMs?: number; + rateLimitMaxRequests?: number; + now?: () => number; + plugins?: Plugin[]; +}; + +function parseOptionalInt( + raw: string | undefined, + fallback: number, + { min }: { min: number }, +): number { + if (raw === undefined || raw.trim() === '') return fallback; + const trimmed = raw.trim(); + if (!/^\d+$/.test(trimmed)) return fallback; + const parsed = Number(trimmed); + return Number.isSafeInteger(parsed) && parsed >= min ? parsed : fallback; +} + +export function configFromEnv( + env: Record, +): Omit { + return { + isProduction: env.NODE_ENV === 'production', + corsOrigins: parseCorsOrigins(env.CORS_ORIGIN), + maxBodyBytes: parseOptionalInt(env.GRAPHQL_MAX_BODY_BYTES, DEFAULT_MAX_BODY_BYTES, { + min: 1024, + }), + maxQueryDepth: parseOptionalInt(env.GRAPHQL_MAX_DEPTH, DEFAULT_MAX_QUERY_DEPTH, { + min: 1, + }), + maxAliases: parseOptionalInt(env.GRAPHQL_MAX_ALIASES, DEFAULT_MAX_ALIASES, { + min: 1, + }), + maxComplexity: parseOptionalInt(env.GRAPHQL_MAX_COMPLEXITY, DEFAULT_MAX_COMPLEXITY, { + min: 1, + }), + rateLimitWindowMs: parseOptionalInt( + env.RATE_LIMIT_WINDOW_MS, + DEFAULT_RATE_LIMIT_WINDOW_MS, + { min: 1000 }, + ), + rateLimitMaxRequests: parseOptionalInt( + env.RATE_LIMIT_MAX_REQUESTS, + DEFAULT_RATE_LIMIT_MAX_REQUESTS, + { min: 0 }, + ), + }; +} + +function sendJsonError( + res: ServerResponse, + statusCode: number, + message: string, + extraHeaders: Record = {}, +): void { + res.writeHead(statusCode, { + 'content-type': 'application/json; charset=utf-8', + ...GRAPHQL_SECURITY_HEADERS, + ...extraHeaders, + }); + res.end(JSON.stringify({ errors: [{ message }] })); +} + +function toWebHeaders(req: IncomingMessage): Headers { + const headers = new Headers(); + for (const [key, value] of Object.entries(req.headers)) { + if (value === undefined) continue; + if (Array.isArray(value)) { + for (const item of value) headers.append(key, item); + } else { + headers.set(key, value); + } + } + return headers; +} + +const INTERNAL_ORIGIN = 'http://localhost'; + +/** + * Validates that the request targets exact `/graphql` (with optional query + * string) and returns a canonical internal URL without trusting the `Host` + * header. Returns null for any other path so Yoga's suffix matching cannot + * bypass rate limiting or serve unintended paths. + */ +export function buildInternalGraphqlUrl(rawUrl: string | undefined): string | null { + if (!rawUrl || !rawUrl.startsWith('/')) return null; + const queryIndex = rawUrl.indexOf('?'); + const pathname = queryIndex === -1 ? rawUrl : rawUrl.slice(0, queryIndex); + if (pathname !== '/graphql') return null; + const search = queryIndex === -1 ? '' : rawUrl.slice(queryIndex); + try { + const parsed = new URL(`/graphql${search}`, INTERNAL_ORIGIN); + if (parsed.origin !== INTERNAL_ORIGIN || parsed.pathname !== '/graphql') { + return null; + } + return parsed.toString(); + } catch { + return null; + } +} + +function readBoundedBody(req: IncomingMessage, maxBytes: number): Promise { + return new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + let totalBytes = 0; + let exceeded = false; + + req.on('data', (chunk: Buffer | string) => { + if (exceeded) return; + const buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk; + totalBytes += buffer.length; + if (totalBytes > maxBytes) { + exceeded = true; + resolve(null); + return; + } + chunks.push(buffer); + }); + + req.on('end', () => { + if (!exceeded) resolve(Buffer.concat(chunks)); + }); + + req.on('error', (error) => { + if (!exceeded) reject(error); + }); + }); +} + +export function createGraphQLYoga(config: ServerConfig) { + const isProduction = config.isProduction ?? false; + const queryLimitsRule = createQueryLimitsRule({ + maxDepth: config.maxQueryDepth, + maxAliases: config.maxAliases, + maxComplexity: config.maxComplexity, + }); + + const securityPlugin: Plugin = { + onValidate({ addValidationRule }) { + addValidationRule(queryLimitsRule); + if (isProduction) { + addValidationRule(noIntrospectionRule); + } + }, + onResponse({ request, response }) { + const pathname = new URL(request.url).pathname; + if (pathname === '/graphql') { + for (const [name, value] of Object.entries(GRAPHQL_SECURITY_HEADERS)) { + response.headers.set(name, value); + } + } + }, + }; + + return createYoga({ + schema: createSchema({ typeDefs: config.typeDefs, resolvers }), + cors: createCorsConfig(config.corsOrigins ?? []), + graphiql: !isProduction, + landingPage: !isProduction, + plugins: [securityPlugin, ...(config.plugins ?? [])], + // New loaders per request, so batching never leaks between requests. + context: ({ request }) => { + const userId = parseUserId(request.headers.get('x-user-id')); + return { db: config.db, userId, loaders: createLoaders(config.db, userId) }; + }, + }); +} + +export function createAppServer(config: ServerConfig): { + server: Server; + yoga: ReturnType; + rateLimiter: ReturnType; +} { + const maxBodyBytes = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES; + const yoga = createGraphQLYoga(config); + const rateLimiter = createRateLimiter({ + windowMs: config.rateLimitWindowMs, + maxRequests: config.rateLimitMaxRequests, + now: config.now, + }); + + const server = createServer(async (req, res) => { + try { + const internalUrl = buildInternalGraphqlUrl(req.url); + if (internalUrl === null) { + sendJsonError(res, 404, 'Not found.'); + return; + } + + const method = (req.method ?? 'GET').toUpperCase(); + if (method !== 'OPTIONS') { + const clientIp = getClientIp( + req.socket.remoteAddress, + req.headers['x-forwarded-for'], + ); + const decision = rateLimiter.check(clientIp); + if (!decision.allowed) { + sendJsonError(res, 429, 'Too many requests. Please try again later.', { + 'retry-after': String(decision.retryAfterSeconds), + }); + return; + } + } + + const hasBody = method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS'; + let body: Uint8Array | undefined; + + if (hasBody) { + const contentLengthHeader = req.headers['content-length']; + if (contentLengthHeader !== undefined) { + const declaredBytes = Number(contentLengthHeader); + if (Number.isFinite(declaredBytes) && declaredBytes > maxBodyBytes) { + sendJsonError(res, 413, 'Request body too large.', { connection: 'close' }); + req.resume(); + return; + } + } + + const rawBody = await readBoundedBody(req, maxBodyBytes); + if (rawBody === null) { + res.writeHead(413, { + 'content-type': 'application/json; charset=utf-8', + connection: 'close', + ...GRAPHQL_SECURITY_HEADERS, + }); + res.end( + JSON.stringify({ errors: [{ message: 'Request body too large.' }] }), + () => { + req.destroy(); + }, + ); + return; + } + body = new Uint8Array(rawBody); + } + + const headers = toWebHeaders(req); + const response = await yoga.fetch(internalUrl, { + method, + headers, + ...(body !== undefined ? { body } : {}), + }); + + const responseHeaders: Record = {}; + response.headers.forEach((value, key) => { + responseHeaders[key] = value; + }); + Object.assign(responseHeaders, GRAPHQL_SECURITY_HEADERS); + + const responseBody = Buffer.from(await response.arrayBuffer()); + res.writeHead(response.status, responseHeaders); + res.end(responseBody); + } catch (error) { + console.error('Unhandled HTTP request error:', error); + if (!res.headersSent) { + sendJsonError(res, 500, 'Internal server error.'); + } else { + res.end(); + } + } + }); + + return { server, yoga, rateLimiter }; +} + +export function registerGracefulShutdown( + server: Server, + closePool: () => Promise, + { + timeoutMs = 10_000, + onExit = (code: number) => process.exit(code), + }: { timeoutMs?: number; onExit?: (code: number) => void } = {}, +) { + let shuttingDown = false; + + return (signal: NodeJS.Signals) => { + if (shuttingDown) return; + shuttingDown = true; + console.log(`Received ${signal}, shutting down gracefully...`); + + const forceTimer = setTimeout(() => { + console.error('Graceful shutdown timed out; forcing exit.'); + onExit(1); + }, timeoutMs); + forceTimer.unref(); + + server.close(async (closeError) => { + if (closeError) { + console.error('Error closing HTTP server:', closeError); + } + try { + await closePool(); + clearTimeout(forceTimer); + onExit(closeError ? 1 : 0); + } catch (poolError) { + console.error('Error closing PostgreSQL pool:', poolError); + clearTimeout(forceTimer); + onExit(1); + } + }); + }; +} diff --git a/server/src/crate.test.ts b/server/src/crate.test.ts index a61246f..1cc7dae 100644 --- a/server/src/crate.test.ts +++ b/server/src/crate.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { addToCrate, removeFromCrate } from './crate.js'; +import { addToCrate, decodeCrateCursor, removeFromCrate } from './crate.js'; const userId = '550e8400-e29b-41d4-a716-446655440000'; @@ -13,10 +13,25 @@ describe('crate mutation validation', () => { await expect(removeFromCrate({} as never, null, '1')).rejects.toThrow('X-User-Id'); }); - it.each(['0', '-1', 'not-an-id', '1.5'])('rejects invalid album id %s', async (id) => { - await expect(addToCrate({} as never, userId, id)).rejects.toThrow('Invalid album id'); - await expect(removeFromCrate({} as never, userId, id)).rejects.toThrow( - 'Invalid album id', - ); - }); + it.each(['', ' ', '0', '-1', 'not-an-id', '1.5', ' 1 ', '2147483648'])( + 'rejects invalid album id %j', + async (id) => { + await expect(addToCrate({} as never, userId, id)).rejects.toThrow( + 'Invalid album id.', + ); + await expect(removeFromCrate({} as never, userId, id)).rejects.toThrow( + 'Invalid album id.', + ); + }, + ); + + it.each([0, -1, 2_147_483_648])( + 'rejects out-of-range int4 id %s in crate cursor', + (id) => { + const forged = Buffer.from( + JSON.stringify(['2026-01-02T10:00:00.000000Z', id]), + ).toString('base64url'); + expect(() => decodeCrateCursor(forged)).toThrow('Invalid crate cursor.'); + }, + ); }); diff --git a/server/src/crate.ts b/server/src/crate.ts index ccfa42e..56f3fb4 100644 --- a/server/src/crate.ts +++ b/server/src/crate.ts @@ -1,11 +1,18 @@ -import { and, eq } from 'drizzle-orm'; +import { and, count, desc, eq, sql } from 'drizzle-orm'; import { GraphQLError } from 'graphql'; +import { findAlbum, type AlbumRecord } from './albums.js'; import type { Db } from './db/client.js'; -import { album, crateItem } from './db/schema.js'; +import { crateItem } from './db/schema.js'; +import { pageSize } from './search/search.js'; import { ensureUser, requireUserId } from './userIdentity.js'; +import { + decodeTimestampCursor, + encodeTimestampCursor, + parseNumericId, +} from './validation.js'; -export type AlbumRecord = { id: number; title: string; releaseYear: number | null }; +export type { AlbumRecord }; export type CrateItemRecord = { id: number; userId: string; @@ -13,20 +20,83 @@ export type CrateItemRecord = { addedAt: Date; }; -function parseAlbumId(value: string): number { - const id = Number(value); - if (!Number.isSafeInteger(id) || id < 1) throw new GraphQLError('Invalid album id.'); - return id; +export type CrateArgs = { first: number; after?: string | null }; + +export function encodeCrateCursor(row: { addedAtCursor: string; id: number }): string { + return encodeTimestampCursor({ timestamp: row.addedAtCursor, id: row.id }); +} + +export function decodeCrateCursor(value: string): { addedAt: string; id: number } { + const { timestamp, id } = decodeTimestampCursor(value, 'crate'); + return { addedAt: timestamp, id }; } -async function findAlbum(db: Db, id: number): Promise { - const [found] = await db - .select({ id: album.id, title: album.title, releaseYear: album.releaseYear }) - .from(album) - .where(eq(album.id, id)); +/** + * The user's crate, newest first, paged by `(added_at, id)` at microsecond + * precision, so a page boundary inside a run of albums saved close together is + * still stable. The `crate_item_user_added_at_idx` index matches the ordering. + * + * An anonymous request gets an empty crate rather than an error: `CrateConnection` + * is non-null, and reads are supposed to degrade instead of failing + * (architecture decision 5). Nothing about another user's crate is reachable + * from here, because the user id comes from the request context. + */ +export async function crateForUser( + db: Db, + userId: string | null, + { first, after }: CrateArgs, +) { + if (!userId) { + return { + edges: [], + pageInfo: { hasNextPage: false, endCursor: null }, + totalCount: 0, + }; + } + + const limit = pageSize(first); + const cursor = after ? decodeCrateCursor(after) : null; + // A row comparison rather than an OR, so PostgreSQL seeks to the cursor in the + // index instead of filtering every item the user has already seen. + const afterCondition = cursor + ? sql`(${crateItem.addedAt}, ${crateItem.id}) < (${cursor.addedAt}::timestamptz, ${cursor.id})` + : undefined; + + const [rows, total] = await Promise.all([ + db + .select({ + id: crateItem.id, + albumId: crateItem.albumId, + addedAt: crateItem.addedAt, + // The Date above keeps milliseconds. This keeps the stored microseconds + // so the next page compares the same instant. + addedAtCursor: sql`to_char(${crateItem.addedAt} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`, + }) + .from(crateItem) + .where( + afterCondition + ? and(eq(crateItem.userId, userId), afterCondition) + : eq(crateItem.userId, userId), + ) + .orderBy(desc(crateItem.addedAt), desc(crateItem.id)) + .limit(limit + 1), + db.select({ count: count() }).from(crateItem).where(eq(crateItem.userId, userId)), + ]); + + const page = rows.slice(0, limit); + const edges = page.map(({ addedAtCursor, ...node }) => ({ + cursor: encodeCrateCursor({ addedAtCursor, id: node.id }), + node, + })); - if (!found) throw new GraphQLError('Album not found.'); - return found; + return { + edges, + pageInfo: { + hasNextPage: rows.length > limit, + endCursor: edges.at(-1)?.cursor ?? null, + }, + totalCount: Number(total[0]?.count ?? 0), + }; } export async function addToCrate( @@ -35,7 +105,7 @@ export async function addToCrate( albumIdValue: string, ): Promise<{ item: CrateItemRecord; album: AlbumRecord }> { const ownerId = requireUserId(userId); - const albumId = parseAlbumId(albumIdValue); + const albumId = parseNumericId(albumIdValue, 'album'); const albumRecord = await findAlbum(db, albumId); await ensureUser(db, ownerId); @@ -61,7 +131,7 @@ export async function removeFromCrate( albumIdValue: string, ): Promise<{ removedAlbumId: string; album: AlbumRecord }> { const ownerId = requireUserId(userId); - const albumId = parseAlbumId(albumIdValue); + const albumId = parseNumericId(albumIdValue, 'album'); const albumRecord = await findAlbum(db, albumId); await db diff --git a/server/src/db/client.ts b/server/src/db/client.ts index a05e69d..83b234a 100644 --- a/server/src/db/client.ts +++ b/server/src/db/client.ts @@ -1,15 +1,19 @@ import { drizzle } from 'drizzle-orm/node-postgres'; import pg from 'pg'; +import { createPoolConfig, type PoolConfigOptions } from './poolConfig.js'; -const url = process.env.DATABASE_URL; -if (!url) { - throw new Error( - 'DATABASE_URL is not set, e.g. postgres://t19:@127.0.0.1:5432/crate', - ); -} +export type CreateDbOptions = PoolConfigOptions & { + env?: Record; +}; -// One pool for the whole process. Every request borrows a connection from it. -export const pool = new pg.Pool({ connectionString: url }); -export const db = drizzle(pool); +export function createDb(options: CreateDbOptions = {}) { + const { env = process.env, ...poolOptions } = options; + const pool = new pg.Pool(createPoolConfig(env, poolOptions)); + pool.on('error', (error) => { + console.error('Unexpected PostgreSQL pool error:', error); + }); + const db = drizzle(pool); + return { db, pool }; +} -export type Db = typeof db; +export type Db = ReturnType['db']; diff --git a/server/src/db/importMusicBrainz.ts b/server/src/db/importMusicBrainz.ts index 252557c..a71cafa 100644 --- a/server/src/db/importMusicBrainz.ts +++ b/server/src/db/importMusicBrainz.ts @@ -1,11 +1,13 @@ import { readFile } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; -import { db, pool } from './client.js'; +import { createDb } from './client.js'; import { importMusicBrainzAlbums, parseMusicBrainzCatalog, } from './musicBrainzCatalog.js'; +const { db, pool } = createDb({ defaultStatementTimeoutMs: 0 }); + const snapshotPath = fileURLToPath( new URL('../../data/musicbrainz-albums.json', import.meta.url), ); diff --git a/server/src/db/migrate.ts b/server/src/db/migrate.ts index be21037..1a885b5 100644 --- a/server/src/db/migrate.ts +++ b/server/src/db/migrate.ts @@ -1,6 +1,8 @@ import { fileURLToPath } from 'node:url'; import { migrate } from 'drizzle-orm/node-postgres/migrator'; -import { db, pool } from './client.js'; +import { createDb } from './client.js'; + +const { db, pool } = createDb({ defaultStatementTimeoutMs: 0 }); // Applies every migration in server/drizzle/ that the database has not seen yet. await migrate(db, { diff --git a/server/src/db/poolConfig.test.ts b/server/src/db/poolConfig.test.ts new file mode 100644 index 0000000..daffc65 --- /dev/null +++ b/server/src/db/poolConfig.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest'; +import { + DEFAULT_CONNECTION_TIMEOUT_MS, + DEFAULT_IDLE_IN_TRANSACTION_TIMEOUT_MS, + DEFAULT_POOL_MAX, + DEFAULT_STATEMENT_TIMEOUT_MS, + createPoolConfig, +} from './poolConfig.js'; + +describe('createPoolConfig', () => { + const url = 'postgres://t19:secret@127.0.0.1:5432/crate'; + + it('applies explicit safe defaults for timeouts and pool size', () => { + expect(createPoolConfig({ DATABASE_URL: url })).toEqual({ + connectionString: url, + max: DEFAULT_POOL_MAX, + connectionTimeoutMillis: DEFAULT_CONNECTION_TIMEOUT_MS, + statement_timeout: DEFAULT_STATEMENT_TIMEOUT_MS, + idle_in_transaction_session_timeout: DEFAULT_IDLE_IN_TRANSACTION_TIMEOUT_MS, + }); + }); + + it('allows overriding timeouts and pool max via environment variables (including 0)', () => { + expect( + createPoolConfig({ + DATABASE_URL: url, + PG_POOL_MAX: '20', + PG_CONNECTION_TIMEOUT_MS: '8000', + PG_STATEMENT_TIMEOUT_MS: '0', + PG_IDLE_IN_TRANSACTION_TIMEOUT_MS: '30000', + }), + ).toEqual({ + connectionString: url, + max: 20, + connectionTimeoutMillis: 8000, + statement_timeout: 0, + idle_in_transaction_session_timeout: 30000, + }); + }); + + it('supports overriding the default statement timeout for CLI scripts while honoring PG_STATEMENT_TIMEOUT_MS', () => { + expect( + createPoolConfig({ DATABASE_URL: url }, { defaultStatementTimeoutMs: 0 }), + ).toEqual({ + connectionString: url, + max: DEFAULT_POOL_MAX, + connectionTimeoutMillis: DEFAULT_CONNECTION_TIMEOUT_MS, + statement_timeout: 0, + idle_in_transaction_session_timeout: DEFAULT_IDLE_IN_TRANSACTION_TIMEOUT_MS, + }); + + expect( + createPoolConfig( + { DATABASE_URL: url, PG_STATEMENT_TIMEOUT_MS: '30000' }, + { defaultStatementTimeoutMs: 0 }, + ).statement_timeout, + ).toBe(30_000); + }); + + it('throws when DATABASE_URL is missing or pool settings are invalid', () => { + expect(() => createPoolConfig({})).toThrow('DATABASE_URL is not set'); + expect(() => createPoolConfig({ DATABASE_URL: url, PG_POOL_MAX: '0' })).toThrow( + 'PG_POOL_MAX', + ); + expect(() => + createPoolConfig({ DATABASE_URL: url, PG_STATEMENT_TIMEOUT_MS: '-1' }), + ).toThrow('PG_STATEMENT_TIMEOUT_MS'); + }); +}); diff --git a/server/src/db/poolConfig.ts b/server/src/db/poolConfig.ts new file mode 100644 index 0000000..25cff64 --- /dev/null +++ b/server/src/db/poolConfig.ts @@ -0,0 +1,65 @@ +import type pg from 'pg'; + +export const DEFAULT_STATEMENT_TIMEOUT_MS = 10_000; +export const DEFAULT_CONNECTION_TIMEOUT_MS = 5_000; +export const DEFAULT_IDLE_IN_TRANSACTION_TIMEOUT_MS = 15_000; +export const DEFAULT_POOL_MAX = 10; + +function parseEnvInt( + raw: string | undefined, + name: string, + fallback: number, + { min }: { min: number }, +): number { + if (raw === undefined || raw.trim() === '') return fallback; + if (!/^\d+$/.test(raw.trim())) { + throw new Error(`${name} must be an integer >= ${min}.`); + } + const parsed = Number(raw.trim()); + if (!Number.isSafeInteger(parsed) || parsed < min) { + throw new Error(`${name} must be an integer >= ${min}.`); + } + return parsed; +} + +export type PoolConfigOptions = { + defaultStatementTimeoutMs?: number; +}; + +export function createPoolConfig( + env: Record, + options: PoolConfigOptions = {}, +): pg.PoolConfig { + const url = env.DATABASE_URL; + if (!url) { + throw new Error( + 'DATABASE_URL is not set, e.g. postgres://t19:@127.0.0.1:5432/crate', + ); + } + + const defaultStatementTimeoutMs = + options.defaultStatementTimeoutMs ?? DEFAULT_STATEMENT_TIMEOUT_MS; + + return { + connectionString: url, + max: parseEnvInt(env.PG_POOL_MAX, 'PG_POOL_MAX', DEFAULT_POOL_MAX, { min: 1 }), + connectionTimeoutMillis: parseEnvInt( + env.PG_CONNECTION_TIMEOUT_MS, + 'PG_CONNECTION_TIMEOUT_MS', + DEFAULT_CONNECTION_TIMEOUT_MS, + { min: 1 }, + ), + statement_timeout: parseEnvInt( + env.PG_STATEMENT_TIMEOUT_MS, + 'PG_STATEMENT_TIMEOUT_MS', + defaultStatementTimeoutMs, + { min: 0 }, + ), + idle_in_transaction_session_timeout: parseEnvInt( + env.PG_IDLE_IN_TRANSACTION_TIMEOUT_MS, + 'PG_IDLE_IN_TRANSACTION_TIMEOUT_MS', + DEFAULT_IDLE_IN_TRANSACTION_TIMEOUT_MS, + { min: 0 }, + ), + }; +} diff --git a/server/src/db/seed.ts b/server/src/db/seed.ts index 13ddabb..1a32a0d 100644 --- a/server/src/db/seed.ts +++ b/server/src/db/seed.ts @@ -1,7 +1,9 @@ import { sql } from 'drizzle-orm'; -import { db, pool } from './client.js'; +import { createDb } from './client.js'; import { album, albumArtist, albumGenre, artist, genre } from './schema.js'; +const { db, pool } = createDb({ defaultStatementTimeoutMs: 0 }); + /** * A small hand-written catalog, enough to exercise search, filters, facets and * paging. Development/reset only: the cascading truncate also deletes reviews diff --git a/server/src/db/seedLarge.ts b/server/src/db/seedLarge.ts index fe0f495..33ddfc4 100644 --- a/server/src/db/seedLarge.ts +++ b/server/src/db/seedLarge.ts @@ -1,5 +1,5 @@ import { sql } from 'drizzle-orm'; -import { db, pool } from './client.js'; +import { createDb } from './client.js'; import { createLargeCatalogAlbum, largeCatalogArtistNames, @@ -10,6 +10,7 @@ import { import { album, albumArtist, albumGenre, artist, genre } from './schema.js'; const albumCount = parseAlbumCount(process.env.ALBUM_COUNT); +const { db, pool } = createDb({ defaultStatementTimeoutMs: 0 }); try { const { artistIds, genreIds } = await db.transaction(async (tx) => { diff --git a/server/src/index.ts b/server/src/index.ts index b417b26..0d0c9dd 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -1,26 +1,26 @@ import { readFileSync } from 'node:fs'; -import { createServer } from 'node:http'; -import { createSchema, createYoga } from 'graphql-yoga'; -import { db } from './db/client.js'; -import { createLoaders } from './loaders/index.js'; -import { resolvers, type Context } from './resolvers.js'; -import { parseUserId } from './userIdentity.js'; +import { configFromEnv, createAppServer, registerGracefulShutdown } from './app.js'; +import { createDb } from './db/client.js'; + +// One pool for the whole process. Every request borrows a connection from it. +const { db, pool } = createDb(); // The API contract is the schema.graphql at the repository root, shared with // the client. The path is the same from src/ (dev) and dist/ (production). const typeDefs = readFileSync(new URL('../../schema.graphql', import.meta.url), 'utf8'); -const yoga = createYoga({ - schema: createSchema({ typeDefs, resolvers }), - // New loaders per request, so batching never leaks between requests. - context: ({ request }) => { - const userId = parseUserId(request.headers.get('x-user-id')); - return { db, userId, loaders: createLoaders(db, userId) }; - }, +const { server } = createAppServer({ + db, + typeDefs, + ...configFromEnv(process.env), }); +const shutdown = registerGracefulShutdown(server, () => pool.end()); +process.on('SIGTERM', shutdown); +process.on('SIGINT', shutdown); + const host = process.env.HOST ?? '127.0.0.1'; const port = Number(process.env.PORT ?? 3001); -createServer(yoga).listen(port, host, () => { +server.listen(port, host, () => { console.log(`Crate API listening on http://${host}:${port}/graphql`); }); diff --git a/server/src/resolvers.ts b/server/src/resolvers.ts index 5e3a32b..d5cb583 100644 --- a/server/src/resolvers.ts +++ b/server/src/resolvers.ts @@ -1,366 +1,64 @@ -import { and, count, desc, eq, lt, or, sql, type SQL } from 'drizzle-orm'; import { GraphQLError } from 'graphql'; +import { findAlbumById, type AlbumRecord } from './albums.js'; +import { addToCrate, crateForUser, removeFromCrate, type CrateArgs } from './crate.js'; import type { Db } from './db/client.js'; -import { album, crateItem, review } from './db/schema.js'; import type { Loaders } from './loaders/index.js'; import { - afterNullValues, - afterCursor, - decodeCursor, - encodeCursor, - countryFacetQuery, - genreFacetQuery, - orderBy, - pageSize, - searchFilter, - sortKey, - withSelectedDecades, - type AlbumSearchInput, -} from './search/search.js'; -import { removeReview, saveReview, type UpsertReviewInput } from './reviews.js'; -import { addToCrate, removeFromCrate } from './crate.js'; -import { publicDisplayName } from './userIdentity.js'; + removeReview, + reviewsForAlbum, + saveReview, + type ReviewArgs, + type UpsertReviewInput, +} from './reviews.js'; +import { + albumConnectionAggregates, + searchAlbums, + type SearchArgs, +} from './search/queries.js'; import { clearSearchHistory, historyForUser, recordSearch } from './searchHistory.js'; +import { publicDisplayName } from './userIdentity.js'; +import { parseNumericId } from './validation.js'; export type Context = { db: Db; loaders: Loaders; userId: string | null }; -type AlbumRow = { id: number; title: string; releaseYear: number | null }; - -type SearchArgs = { input: AlbumSearchInput; first: number; after?: string | null }; type AlbumArgs = { id: string }; -type ReviewArgs = { first: number; after?: string | null }; -type CrateArgs = { first: number; after?: string | null }; - -type ReviewRow = { - id: number; - userId: string; - albumId: number; - rating: number; - comment: string; - createdAt: string; - updatedAt: Date; -}; - -function parseNumericId(value: string, label: string): number { - const id = Number(value); - if (!Number.isSafeInteger(id) || id < 1) throw new GraphQLError(`Invalid ${label} id.`); - return id; -} - -type ReviewCursor = { createdAt: string; id: number }; - -function encodeReviewCursor(row: ReviewRow): string { - return Buffer.from(JSON.stringify([row.createdAt, row.id])).toString('base64url'); -} - -function decodeReviewCursor(value: string): ReviewCursor { - try { - const parsed: unknown = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')); - if (!Array.isArray(parsed) || parsed.length !== 2) throw new Error(); - const [createdAt, id] = parsed; - if ( - typeof createdAt !== 'string' || - Number.isNaN(Date.parse(createdAt)) || - !Number.isInteger(id) - ) { - throw new Error(); - } - return { createdAt, id }; - } catch { - throw new GraphQLError('Invalid review cursor.'); - } -} - -type CrateCursor = { addedAt: string; id: number }; - -// The text encodeCrateCursor writes: UTC with six fractional digits, as the -// database stores them. A JS Date would keep only milliseconds, so the cursor -// carries the database text instead, and the shape is checked before SQL sees it. -const EXACT_UTC_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/; - -function isExactUtcTimestamp(text: string): boolean { - if (!EXACT_UTC_TIMESTAMP.test(text)) return false; - const milliseconds = Date.parse(text); - // Date.parse rolls 30 February over to 2 March; a real date survives the round trip. - return ( - !Number.isNaN(milliseconds) && - new Date(milliseconds).toISOString().startsWith(text.slice(0, 19)) - ); -} - -function encodeCrateCursor(row: { addedAtCursor: string; id: number }): string { - return Buffer.from(JSON.stringify([row.addedAtCursor, row.id])).toString('base64url'); -} - -function decodeCrateCursor(value: string): CrateCursor { - try { - const parsed: unknown = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')); - if (!Array.isArray(parsed) || parsed.length !== 2) throw new Error(); - const [addedAt, id] = parsed; - if ( - typeof addedAt !== 'string' || - !isExactUtcTimestamp(addedAt) || - !Number.isInteger(id) - ) { - throw new Error(); - } - return { addedAt, id }; - } catch { - throw new GraphQLError('Invalid crate cursor.'); - } -} - -/** - * The user's crate, newest first, paged by `(added_at, id)` at microsecond - * precision, so a page boundary inside a run of albums saved close together is - * still stable. The `crate_item_user_added_at_idx` index matches the ordering. - * - * An anonymous request gets an empty crate rather than an error: `CrateConnection` - * is non-null, and reads are supposed to degrade instead of failing - * (architecture decision 5). Nothing about another user's crate is reachable - * from here, because the user id comes from the request context. - */ -async function crateForUser(ctx: Context, { first, after }: CrateArgs) { - if (!ctx.userId) { - return { - edges: [], - pageInfo: { hasNextPage: false, endCursor: null }, - totalCount: 0, - }; - } - - const userId = ctx.userId; - const limit = pageSize(first); - const cursor = after ? decodeCrateCursor(after) : null; - // A row comparison rather than an OR, so PostgreSQL seeks to the cursor in the - // index instead of filtering every item the user has already seen. - const afterCondition = cursor - ? sql`(${crateItem.addedAt}, ${crateItem.id}) < (${cursor.addedAt}::timestamptz, ${cursor.id})` - : undefined; - - const [rows, total] = await Promise.all([ - ctx.db - .select({ - id: crateItem.id, - albumId: crateItem.albumId, - addedAt: crateItem.addedAt, - // The Date above keeps milliseconds. This keeps the stored microseconds - // so the next page compares the same instant. - addedAtCursor: sql`to_char(${crateItem.addedAt} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`, - }) - .from(crateItem) - .where( - afterCondition - ? and(eq(crateItem.userId, userId), afterCondition) - : eq(crateItem.userId, userId), - ) - .orderBy(desc(crateItem.addedAt), desc(crateItem.id)) - .limit(limit + 1), - ctx.db.select({ count: count() }).from(crateItem).where(eq(crateItem.userId, userId)), - ]); - - const page = rows.slice(0, limit); - const edges = page.map(({ addedAtCursor, ...node }) => ({ - cursor: encodeCrateCursor({ addedAtCursor, id: node.id }), - node, - })); - - return { - edges, - pageInfo: { - hasNextPage: rows.length > limit, - endCursor: edges.at(-1)?.cursor ?? null, - }, - totalCount: Number(total[0]?.count ?? 0), - }; -} - -async function reviewsForAlbum( - ctx: Context, - albumId: number, - { first, after }: ReviewArgs, -) { - const limit = pageSize(first); - const cursor = after ? decodeReviewCursor(after) : null; - const afterCondition = cursor - ? or( - lt(review.createdAt, cursor.createdAt), - and(eq(review.createdAt, cursor.createdAt), lt(review.id, cursor.id)), - ) - : undefined; - const [rows, totalCount] = await Promise.all([ - ctx.db - .select() - .from(review) - .where( - afterCondition - ? and(eq(review.albumId, albumId), afterCondition) - : eq(review.albumId, albumId), - ) - .orderBy(desc(review.createdAt), desc(review.id)) - .limit(limit + 1), - ctx.loaders.reviewCountByAlbum.load(albumId), - ]); - const page = rows.slice(0, limit) as ReviewRow[]; - const edges = page.map((node) => ({ cursor: encodeReviewCursor(node), node })); - return { - edges, - pageInfo: { - hasNextPage: rows.length > limit, - endCursor: edges.at(-1)?.cursor ?? null, - }, - totalCount, - }; -} - -/** - * searchAlbums runs one query: a page of albums, filtered and sorted in SQL so - * it covers the whole result set. Album artists and genres are then fetched by - * the loaders, one query each for the whole page. - * - * The total count, the three facet lists and the reviewed count are resolved - * by `AlbumConnection` below, only when the operation selects them. They cover - * the whole result set and do not change between pages, so the client asks for - * them with the first page and leaves them out of Load more (#96). At 1M rows - * they cost far more than an indexed cursor page (docs/scalability.md). - */ -async function searchAlbums(db: Db, { input, first, after }: SearchArgs) { - const limit = pageSize(first); - const filter = searchFilter(input); - const key = sortKey(input); - const cursor = after ? decodeCursor(after, input.sort) : null; - const afterSql = cursor ? afterCursor(key, cursor) : sql`TRUE`; - const pageSizeWithLookahead = limit + 1; - const pageSelect = (predicate: SQL) => sql` - SELECT album.id, album.title, album.release_year AS "releaseYear", - album.musicbrainz_release_group_id AS "musicBrainzReleaseGroupId", - ${key.expr} AS "sortValue" - FROM album - WHERE ${filter} AND ${predicate} - ORDER BY ${orderBy(key)} - LIMIT ${pageSizeWithLookahead} - `; - const pageQuery = - key.nullable && cursor && cursor.value !== null - ? sql` - SELECT * FROM ( - (${pageSelect(sql`(${afterSql} AND ${key.expr} IS NOT NULL)`)}) - UNION ALL - (${pageSelect(afterNullValues(key, cursor))}) - ) AS page_rows - ORDER BY "sortValue" ${sql.raw(key.direction)} NULLS LAST, - id ${sql.raw(key.direction)} NULLS LAST - LIMIT ${pageSizeWithLookahead} - ` - : pageSelect(afterSql); - - // One extra row tells us whether there is a next page. - const page = await db.execute( - pageQuery, - ); - - const rows = page.rows.slice(0, limit); - const edges = rows.map(({ sortValue, ...node }) => ({ - cursor: encodeCursor({ sort: input.sort, value: sortValue, id: node.id }), - node, - })); - - return { - edges, - pageInfo: { - hasNextPage: page.rows.length > limit, - endCursor: edges.at(-1)?.cursor ?? null, - }, - // Not a schema field: the AlbumConnection resolvers read it. - input, - }; -} - -type SearchConnection = Awaited>; - -// Whole-result-set aggregates of a search, each run only if its field is selected. -const albumConnectionAggregates = { - totalCount: async ({ input }: SearchConnection, _: unknown, ctx: Context) => { - const total = await ctx.db.execute<{ count: number }>(sql` - SELECT count(*)::int AS count FROM album WHERE ${searchFilter(input)} - `); - return total.rows[0]?.count ?? 0; - }, - genreFacets: async ({ input }: SearchConnection, _: unknown, ctx: Context) => { - const facets = await ctx.db.execute<{ id: number; name: string; count: number }>( - genreFacetQuery(input), - ); - return facets.rows.map(({ count, ...g }) => ({ genre: g, count })); - }, - decadeFacets: async ({ input }: SearchConnection, _: unknown, ctx: Context) => { - const facets = await ctx.db.execute<{ decade: number; count: number }>(sql` - SELECT (album.release_year / 10) * 10 AS decade, count(*)::int AS count - FROM album - WHERE ${searchFilter(input, 'decades')} AND album.release_year IS NOT NULL - GROUP BY 1 - ORDER BY 1 - `); - return withSelectedDecades(facets.rows, input); - }, - countryFacets: async ({ input }: SearchConnection, _: unknown, ctx: Context) => { - const facets = await ctx.db.execute<{ country_code: string; count: number }>( - countryFacetQuery(input), - ); - return facets.rows.map(({ country_code: countryCode, count }) => ({ - countryCode, - countryName: - new Intl.DisplayNames(['en'], { type: 'region' }).of(countryCode) ?? countryCode, - count, - })); - }, - reviewedCount: async ({ input }: SearchConnection, _: unknown, ctx: Context) => { - const reviewed = await ctx.db.execute<{ count: number }>(sql` - SELECT count(*)::int AS count FROM album - WHERE ${searchFilter(input, 'hasReviews')} - AND EXISTS (SELECT 1 FROM review WHERE review.album_id = album.id) - `); - return reviewed.rows[0]?.count ?? 0; - }, -}; - -// Fields not listed here (tracks, ratings, reviews, crate) arrive with their -// own issues. export const resolvers = { Query: { mySearchHistory: (_: unknown, __: unknown, ctx: Context) => historyForUser(ctx.db, ctx.userId), searchAlbums: (_: unknown, args: SearchArgs, ctx: Context) => searchAlbums(ctx.db, args), - myCrate: (_: unknown, args: CrateArgs, ctx: Context) => crateForUser(ctx, args), + myCrate: (_: unknown, args: CrateArgs, ctx: Context) => + crateForUser(ctx.db, ctx.userId, args), album: async (_: unknown, { id }: AlbumArgs, ctx: Context) => { const albumId = parseNumericId(id, 'album'); - const [found] = await ctx.db - .select() - .from(album) - .where(eq(album.id, albumId)) - .limit(1); - return found ?? null; + return findAlbumById(ctx.db, albumId); }, }, AlbumConnection: albumConnectionAggregates, Album: { - artists: (album: AlbumRow, _: unknown, ctx: Context) => + artists: (album: AlbumRecord, _: unknown, ctx: Context) => ctx.loaders.artistsByAlbum.load(album.id), - genres: (album: AlbumRow, _: unknown, ctx: Context) => + genres: (album: AlbumRecord, _: unknown, ctx: Context) => ctx.loaders.genresByAlbum.load(album.id), - tracks: (album: AlbumRow, _: unknown, ctx: Context) => + tracks: (album: AlbumRecord, _: unknown, ctx: Context) => ctx.loaders.tracksByAlbum.load(album.id), - reviewCount: (album: AlbumRow, _: unknown, ctx: Context) => + reviewCount: (album: AlbumRecord, _: unknown, ctx: Context) => ctx.loaders.reviewCountByAlbum.load(album.id), - averageRating: (album: AlbumRow, _: unknown, ctx: Context) => + averageRating: (album: AlbumRecord, _: unknown, ctx: Context) => ctx.loaders.averageRatingByAlbum.load(album.id), - myReview: (album: AlbumRow, _: unknown, ctx: Context) => + myReview: (album: AlbumRecord, _: unknown, ctx: Context) => ctx.loaders.myReviewByAlbum.load(album.id), - isInCrate: (album: AlbumRow, _: unknown, ctx: Context) => + isInCrate: (album: AlbumRecord, _: unknown, ctx: Context) => ctx.loaders.isInCrateByAlbum.load(album.id), - reviews: (album: AlbumRow, args: ReviewArgs, ctx: Context) => - reviewsForAlbum(ctx, album.id, args), + reviews: (album: AlbumRecord, args: ReviewArgs, ctx: Context) => + reviewsForAlbum( + ctx.db, + (id) => ctx.loaders.reviewCountByAlbum.load(id), + album.id, + args, + ), }, CrateItem: { album: async (item: { albumId: number }, _: unknown, ctx: Context) => { @@ -381,10 +79,28 @@ export const resolvers = { recordSearch(ctx.db, ctx.userId, query), clearSearchHistory: (_: unknown, __: unknown, ctx: Context) => clearSearchHistory(ctx.db, ctx.userId), - upsertReview: (_: unknown, { input }: { input: UpsertReviewInput }, ctx: Context) => - saveReview(ctx.db, ctx.userId, input), - deleteReview: (_: unknown, { id }: { id: string }, ctx: Context) => - removeReview(ctx.db, ctx.userId, id), + upsertReview: async ( + _: unknown, + { input }: { input: UpsertReviewInput }, + ctx: Context, + ) => { + const result = await saveReview(ctx.db, ctx.userId, input); + const albumId = result.album.id; + ctx.loaders.myReviewByAlbum.clear(albumId).prime(albumId, result.review); + ctx.loaders.reviewCountByAlbum.clear(albumId); + ctx.loaders.averageRatingByAlbum.clear(albumId); + ctx.loaders.albumById.clear(albumId); + return result; + }, + deleteReview: async (_: unknown, { id }: { id: string }, ctx: Context) => { + const result = await removeReview(ctx.db, ctx.userId, id); + const albumId = result.album.id; + ctx.loaders.myReviewByAlbum.clear(albumId).prime(albumId, null); + ctx.loaders.reviewCountByAlbum.clear(albumId); + ctx.loaders.averageRatingByAlbum.clear(albumId); + ctx.loaders.albumById.clear(albumId); + return result; + }, addToCrate: async (_: unknown, { albumId }: { albumId: string }, ctx: Context) => { const result = await addToCrate(ctx.db, ctx.userId, albumId); ctx.loaders.isInCrateByAlbum.clear(result.album.id).prime(result.album.id, true); diff --git a/server/src/reviews.test.ts b/server/src/reviews.test.ts index 2fa16cc..b9df7be 100644 --- a/server/src/reviews.test.ts +++ b/server/src/reviews.test.ts @@ -1,9 +1,17 @@ import { readFileSync } from 'node:fs'; -import { buildSchema, validate, parse } from 'graphql'; -import { describe, expect, it } from 'vitest'; +import { PgDialect } from 'drizzle-orm/pg-core'; +import type { SQL } from 'drizzle-orm'; +import { buildSchema, parse, validate } from 'graphql'; +import { describe, expect, it, vi } from 'vitest'; import { resolvers, type Context } from './resolvers.js'; -import { removeReview, saveReview } from './reviews.js'; +import { + decodeReviewCursor, + encodeReviewCursor, + removeReview, + reviewsForAlbum, + saveReview, +} from './reviews.js'; import { displayNameFor } from './userIdentity.js'; const userId = '550e8400-e29b-41d4-a716-446655440000'; @@ -18,6 +26,24 @@ describe('review input validation', () => { ).rejects.toThrow('Rating must be an integer between 1 and 5'); }); + it.each(['', ' ', '0', '-1', 'not-an-id', '1.5', ' 1 ', '2147483648'])( + 'rejects invalid album id %j on saveReview', + async (albumId) => { + await expect( + saveReview({} as never, userId, { albumId, rating: 4, comment: '' }), + ).rejects.toThrow('Invalid album id.'); + }, + ); + + it.each(['', ' ', '0', '-1', 'not-an-id', '1.5', ' 1 ', '2147483648'])( + 'rejects invalid review id %j with Invalid review id. on removeReview', + async (reviewId) => { + await expect(removeReview({} as never, userId, reviewId)).rejects.toThrow( + 'Invalid review id.', + ); + }, + ); + it('rejects a missing user before deleting a review', async () => { await expect(removeReview({} as never, null, '1')).rejects.toThrow('X-User-Id'); }); @@ -33,6 +59,186 @@ describe('review input validation', () => { }); }); +describe('review cursors', () => { + it('round-trips a microsecond UTC timestamp and positive int4 id', () => { + const encoded = encodeReviewCursor({ + createdAtCursor: '2026-01-02T10:00:00.123456Z', + id: 42, + }); + expect(decodeReviewCursor(encoded)).toEqual({ + createdAt: '2026-01-02T10:00:00.123456Z', + id: 42, + }); + }); + + it.each([ + ['1', 1], + ['2026-02-30T10:00:00.000000Z', 1], + ['2026-01-02T10:00:00.123Z', 1], + ['2026-01-02 10:00:00.123456+00', 1], + ['2026-01-02T10:00:00.123456Z', 0], + ['2026-01-02T10:00:00.123456Z', -5], + ['2026-01-02T10:00:00.123456Z', 2_147_483_648], + ])('rejects malformed cursor payload [%j, %j]', (createdAt, id) => { + const forged = Buffer.from(JSON.stringify([createdAt, id])).toString('base64url'); + expect(() => decodeReviewCursor(forged)).toThrow('Invalid review cursor.'); + }); + + it('uses tuple keyset comparison in reviewsForAlbum when after cursor is supplied', async () => { + const dialect = new PgDialect(); + let capturedWhere: SQL | undefined; + const db = { + select: vi.fn(() => ({ + from: vi.fn(() => ({ + where: vi.fn((condition: SQL) => { + capturedWhere = condition; + return { + orderBy: vi.fn(() => ({ + limit: vi.fn(async () => []), + })), + }; + }), + })), + })), + }; + const after = encodeReviewCursor({ + createdAtCursor: '2026-01-02T10:00:00.123456Z', + id: 17, + }); + + await reviewsForAlbum(db as never, async () => 0, 5, { first: 10, after }); + + expect(capturedWhere).toBeDefined(); + const rendered = dialect.sqlToQuery(capturedWhere!); + expect(rendered.sql).toContain( + '("review"."created_at", "review"."id") < ($2::timestamptz, $3)', + ); + expect(rendered.params).toEqual([5, '2026-01-02T10:00:00.123456Z', 17]); + }); +}); + +describe('review mutation loader invalidation', () => { + function mockLoader() { + const loader = { + clear: vi.fn(), + prime: vi.fn(), + }; + loader.clear.mockReturnValue(loader); + loader.prime.mockReturnValue(loader); + return loader as unknown as { + clear: ReturnType; + prime: ReturnType; + _phantom?: T; + }; + } + + it('clears and primes affected album loaders on upsertReview and preserves musicBrainzReleaseGroupId', async () => { + const albumRow = { + id: 7, + title: 'Kind of Blue', + releaseYear: 1959, + musicBrainzReleaseGroupId: '8e7a8c50-7b65-3f71-8d0a-99f3f89a0001', + }; + const savedReview = { + id: 99, + userId, + albumId: 7, + rating: 5, + comment: 'Classic', + createdAt: '2026-01-02T10:00:00.000000Z', + updatedAt: new Date('2026-01-02T10:00:00.000Z'), + }; + let selectCall = 0; + const db = { + select: vi.fn(() => ({ + from: vi.fn(() => ({ + where: vi.fn(() => { + selectCall += 1; + if (selectCall === 1) { + return { limit: vi.fn(async () => [albumRow]) }; + } + return Promise.resolve([{ id: userId, displayName: 'Amber Groove' }]); + }), + })), + })), + insert: vi.fn(() => ({ + values: vi.fn(() => ({ + onConflictDoNothing: vi.fn(async () => undefined), + onConflictDoUpdate: vi.fn(() => ({ + returning: vi.fn(async () => [savedReview]), + })), + })), + })), + }; + const loaders = { + myReviewByAlbum: mockLoader(), + reviewCountByAlbum: mockLoader(), + averageRatingByAlbum: mockLoader(), + albumById: mockLoader(), + }; + + const result = await resolvers.Mutation.upsertReview( + {}, + { input: { albumId: '7', rating: 5, comment: 'Classic' } }, + { db, userId, loaders } as unknown as Context, + ); + + expect(result.album.musicBrainzReleaseGroupId).toBe( + albumRow.musicBrainzReleaseGroupId, + ); + expect(loaders.myReviewByAlbum.clear).toHaveBeenCalledWith(7); + expect(loaders.myReviewByAlbum.prime).toHaveBeenCalledWith(7, savedReview); + expect(loaders.reviewCountByAlbum.clear).toHaveBeenCalledWith(7); + expect(loaders.averageRatingByAlbum.clear).toHaveBeenCalledWith(7); + expect(loaders.albumById.clear).toHaveBeenCalledWith(7); + }); + + it('clears and primes affected album loaders on deleteReview', async () => { + const albumRow = { + id: 7, + title: 'Kind of Blue', + releaseYear: 1959, + musicBrainzReleaseGroupId: '8e7a8c50-7b65-3f71-8d0a-99f3f89a0001', + }; + const db = { + delete: vi.fn(() => ({ + where: vi.fn(() => ({ + returning: vi.fn(async () => [{ id: 99, albumId: 7 }]), + })), + })), + select: vi.fn(() => ({ + from: vi.fn(() => ({ + where: vi.fn(() => ({ + limit: vi.fn(async () => [albumRow]), + })), + })), + })), + }; + const loaders = { + myReviewByAlbum: mockLoader(), + reviewCountByAlbum: mockLoader(), + averageRatingByAlbum: mockLoader(), + albumById: mockLoader(), + }; + + const result = await resolvers.Mutation.deleteReview({}, { id: '99' }, { + db, + userId, + loaders, + } as unknown as Context); + + expect(result.deletedReviewId).toBe('99'); + expect(result.album.musicBrainzReleaseGroupId).toBe( + albumRow.musicBrainzReleaseGroupId, + ); + expect(loaders.myReviewByAlbum.clear).toHaveBeenCalledWith(7); + expect(loaders.myReviewByAlbum.prime).toHaveBeenCalledWith(7, null); + expect(loaders.reviewCountByAlbum.clear).toHaveBeenCalledWith(7); + expect(loaders.averageRatingByAlbum.clear).toHaveBeenCalledWith(7); + expect(loaders.albumById.clear).toHaveBeenCalledWith(7); + }); +}); + describe('public review author privacy', () => { it('does not expose User.id in the GraphQL schema', () => { const errors = validate( diff --git a/server/src/reviews.ts b/server/src/reviews.ts index 78a4b5f..bc9ca26 100644 --- a/server/src/reviews.ts +++ b/server/src/reviews.ts @@ -1,9 +1,18 @@ -import { and, eq } from 'drizzle-orm'; +import { and, desc, eq, sql } from 'drizzle-orm'; import { GraphQLError } from 'graphql'; +import { findAlbum, type AlbumRecord } from './albums.js'; import type { Db } from './db/client.js'; -import { album, review } from './db/schema.js'; +import { review } from './db/schema.js'; +import { pageSize } from './search/search.js'; import { ensureUser, requireUserId } from './userIdentity.js'; +import { + decodeTimestampCursor, + encodeTimestampCursor, + parseNumericId, +} from './validation.js'; + +export type { AlbumRecord }; export type ReviewRecord = { id: number; @@ -15,20 +24,23 @@ export type ReviewRecord = { updatedAt: Date; }; -export type AlbumRecord = { id: number; title: string; releaseYear: number | null }; - export type UpsertReviewInput = { albumId: string; rating: number; comment: string; }; +export type ReviewArgs = { first: number; after?: string | null }; + const MAX_COMMENT_LENGTH = 2000; -function parseAlbumId(value: string): number { - const id = Number(value); - if (!Number.isSafeInteger(id) || id < 1) throw new GraphQLError('Invalid album id.'); - return id; +export function encodeReviewCursor(row: { createdAtCursor: string; id: number }): string { + return encodeTimestampCursor({ timestamp: row.createdAtCursor, id: row.id }); +} + +export function decodeReviewCursor(value: string): { createdAt: string; id: number } { + const { timestamp, id } = decodeTimestampCursor(value, 'review'); + return { createdAt: timestamp, id }; } function validateRating(rating: number): void { @@ -43,14 +55,57 @@ function validateComment(comment: string): void { } } -async function findAlbum(db: Db, id: number): Promise { - const [found] = await db - .select({ id: album.id, title: album.title, releaseYear: album.releaseYear }) - .from(album) - .where(eq(album.id, id)); +export async function reviewsForAlbum( + db: Db, + loadReviewCount: (albumId: number) => Promise, + albumId: number, + { first, after }: ReviewArgs, +) { + const limit = pageSize(first); + const cursor = after ? decodeReviewCursor(after) : null; + const afterCondition = cursor + ? sql`(${review.createdAt}, ${review.id}) < (${cursor.createdAt}::timestamptz, ${cursor.id})` + : undefined; + + const [rows, totalCount] = await Promise.all([ + db + .select({ + id: review.id, + userId: review.userId, + albumId: review.albumId, + rating: review.rating, + comment: review.comment, + createdAt: review.createdAt, + updatedAt: review.updatedAt, + // Format at microsecond UTC precision so cursor comparisons round-trip + // cleanly against PostgreSQL timestamptz. + createdAtCursor: sql`to_char(${review.createdAt} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`, + }) + .from(review) + .where( + afterCondition + ? and(eq(review.albumId, albumId), afterCondition) + : eq(review.albumId, albumId), + ) + .orderBy(desc(review.createdAt), desc(review.id)) + .limit(limit + 1), + loadReviewCount(albumId), + ]); + + const page = rows.slice(0, limit); + const edges = page.map(({ createdAtCursor, ...node }) => ({ + cursor: encodeReviewCursor({ createdAtCursor, id: node.id }), + node, + })); - if (!found) throw new GraphQLError('Album not found.'); - return found; + return { + edges, + pageInfo: { + hasNextPage: rows.length > limit, + endCursor: edges.at(-1)?.cursor ?? null, + }, + totalCount, + }; } export async function saveReview( @@ -59,7 +114,7 @@ export async function saveReview( input: UpsertReviewInput, ): Promise<{ review: ReviewRecord; album: AlbumRecord }> { const ownerId = requireUserId(userId); - const albumId = parseAlbumId(input.albumId); + const albumId = parseNumericId(input.albumId, 'album'); validateRating(input.rating); const comment = input.comment.trim(); validateComment(comment); @@ -91,7 +146,7 @@ export async function removeReview( reviewId: string, ): Promise<{ deletedReviewId: string; album: AlbumRecord }> { const ownerId = requireUserId(userId); - const id = parseAlbumId(reviewId); + const id = parseNumericId(reviewId, 'review'); const [deleted] = await db .delete(review) diff --git a/server/src/search/queries.ts b/server/src/search/queries.ts new file mode 100644 index 0000000..5e56238 --- /dev/null +++ b/server/src/search/queries.ts @@ -0,0 +1,135 @@ +import { sql, type SQL } from 'drizzle-orm'; +import type { AlbumRecord } from '../albums.js'; +import type { Db } from '../db/client.js'; +import { + afterCursor, + afterNullValues, + countryFacetQuery, + decodeCursor, + encodeCursor, + genreFacetQuery, + orderBy, + pageSize, + searchFilter, + sortKey, + withSelectedDecades, + type AlbumSearchInput, +} from './search.js'; + +export type SearchArgs = { + input: AlbumSearchInput; + first: number; + after?: string | null; +}; + +const regionDisplayNames = new Intl.DisplayNames(['en'], { type: 'region' }); + +/** + * searchAlbums runs one query: a page of albums, filtered and sorted in SQL so + * it covers the whole result set. Album artists and genres are then fetched by + * the loaders, one query each for the whole page. + * + * The total count, the three facet lists and the reviewed count are resolved + * by `albumConnectionAggregates` below, only when the operation selects them. + * They cover the whole result set and do not change between pages, so the + * client asks for them with the first page and leaves them out of Load more + * (#96). At 1M rows they cost far more than an indexed cursor page + * (docs/scalability.md). + */ +export async function searchAlbums(db: Db, { input, first, after }: SearchArgs) { + const limit = pageSize(first); + const filter = searchFilter(input); + const key = sortKey(input); + const cursor = after ? decodeCursor(after, input.sort) : null; + const afterSql = cursor ? afterCursor(key, cursor) : sql`TRUE`; + const pageSizeWithLookahead = limit + 1; + const pageSelect = (predicate: SQL) => sql` + SELECT album.id, album.title, album.release_year AS "releaseYear", + album.musicbrainz_release_group_id AS "musicBrainzReleaseGroupId", + ${key.expr} AS "sortValue" + FROM album + WHERE ${filter} AND ${predicate} + ORDER BY ${orderBy(key)} + LIMIT ${pageSizeWithLookahead} + `; + const pageQuery = + key.nullable && cursor && cursor.value !== null + ? sql` + SELECT * FROM ( + (${pageSelect(sql`(${afterSql} AND ${key.expr} IS NOT NULL)`)}) + UNION ALL + (${pageSelect(afterNullValues(key, cursor))}) + ) AS page_rows + ORDER BY "sortValue" ${sql.raw(key.direction)} NULLS LAST, + id ${sql.raw(key.direction)} NULLS LAST + LIMIT ${pageSizeWithLookahead} + ` + : pageSelect(afterSql); + + // One extra row tells us whether there is a next page. + const page = await db.execute( + pageQuery, + ); + + const rows = page.rows.slice(0, limit); + const edges = rows.map(({ sortValue, ...node }) => ({ + cursor: encodeCursor({ sort: input.sort, value: sortValue, id: node.id }), + node, + })); + + return { + edges, + pageInfo: { + hasNextPage: page.rows.length > limit, + endCursor: edges.at(-1)?.cursor ?? null, + }, + // Not a schema field: the AlbumConnection resolvers read it. + input, + }; +} + +export type SearchConnection = Awaited>; + +// Whole-result-set aggregates of a search, each run only if its field is selected. +export const albumConnectionAggregates = { + totalCount: async ({ input }: SearchConnection, _: unknown, ctx: { db: Db }) => { + const total = await ctx.db.execute<{ count: number }>(sql` + SELECT count(*)::int AS count FROM album WHERE ${searchFilter(input)} + `); + return total.rows[0]?.count ?? 0; + }, + genreFacets: async ({ input }: SearchConnection, _: unknown, ctx: { db: Db }) => { + const facets = await ctx.db.execute<{ id: number; name: string; count: number }>( + genreFacetQuery(input), + ); + return facets.rows.map(({ count, ...g }) => ({ genre: g, count })); + }, + decadeFacets: async ({ input }: SearchConnection, _: unknown, ctx: { db: Db }) => { + const facets = await ctx.db.execute<{ decade: number; count: number }>(sql` + SELECT (album.release_year / 10) * 10 AS decade, count(*)::int AS count + FROM album + WHERE ${searchFilter(input, 'decades')} AND album.release_year IS NOT NULL + GROUP BY 1 + ORDER BY 1 + `); + return withSelectedDecades(facets.rows, input); + }, + countryFacets: async ({ input }: SearchConnection, _: unknown, ctx: { db: Db }) => { + const facets = await ctx.db.execute<{ country_code: string; count: number }>( + countryFacetQuery(input), + ); + return facets.rows.map(({ country_code: countryCode, count }) => ({ + countryCode, + countryName: regionDisplayNames.of(countryCode) ?? countryCode, + count, + })); + }, + reviewedCount: async ({ input }: SearchConnection, _: unknown, ctx: { db: Db }) => { + const reviewed = await ctx.db.execute<{ count: number }>(sql` + SELECT count(*)::int AS count FROM album + WHERE ${searchFilter(input, 'hasReviews')} + AND EXISTS (SELECT 1 FROM review WHERE review.album_id = album.id) + `); + return reviewed.rows[0]?.count ?? 0; + }, +}; diff --git a/server/src/search/search.test.ts b/server/src/search/search.test.ts index 3978100..5ae59aa 100644 --- a/server/src/search/search.test.ts +++ b/server/src/search/search.test.ts @@ -36,10 +36,22 @@ describe('cursors', () => { expect(decodeCursor(encodeCursor(cursor), 'RELEASE_YEAR_DESC')).toEqual(cursor); }); - it('rejects garbage and cursors from another sort', () => { + it('rejects garbage, out-of-range int4 ids, and cursors from another sort', () => { expect(() => decodeCursor('not a cursor', 'TITLE_ASC')).toThrow('Invalid cursor'); const cursor = encodeCursor({ sort: 'TITLE_ASC', value: 'abbey road', id: 1 }); expect(() => decodeCursor(cursor, 'RELEASE_YEAR_DESC')).toThrow('different sort'); + + for (const badId of [0, -1, 2_147_483_648]) { + const forged = Buffer.from(JSON.stringify(['TITLE_ASC', 'blue', badId])).toString( + 'base64url', + ); + expect(() => decodeCursor(forged, 'TITLE_ASC')).toThrow('Invalid cursor'); + } + + const forgedYear = Buffer.from( + JSON.stringify(['RELEASE_YEAR_DESC', 2_147_483_648, 1]), + ).toString('base64url'); + expect(() => decodeCursor(forgedYear, 'RELEASE_YEAR_DESC')).toThrow('Invalid cursor'); }); }); @@ -268,11 +280,16 @@ describe('searchFilter', () => { expect(params).toEqual([3, 4]); }); - it('rejects a non-numeric genre id', () => { - expect(() => searchFilter(input({ genreIds: ['rock'] }))).toThrow('Invalid genre id'); - }); + it.each(['', ' ', '0', '-1', 'rock', '1.5', ' 1 ', '2147483648'])( + 'rejects invalid genre id %j', + (genreId) => { + expect(() => searchFilter(input({ genreIds: [genreId] }))).toThrow( + 'Invalid genre id', + ); + }, + ); - it('rejects oversized queries, oversized filter lists, and non-integer decades', () => { + it('rejects oversized queries, oversized filter lists, and invalid/out-of-range decades', () => { const tooLong = 'a'.repeat(201); expect(() => searchFilter(input({ query: tooLong }))).toThrow( 'Search query must be at most 200 characters', @@ -281,7 +298,9 @@ describe('searchFilter', () => { 'Search query must be at most 200 characters', ); expect(() => - searchFilter(input({ genreIds: Array.from({ length: 51 }, (_, i) => String(i)) })), + searchFilter( + input({ genreIds: Array.from({ length: 51 }, (_, i) => String(i + 1)) }), + ), ).toThrow('At most 50 genre filters are allowed'); expect(() => searchFilter(input({ countries: Array.from({ length: 51 }, () => 'NO') })), @@ -290,6 +309,10 @@ describe('searchFilter', () => { searchFilter(input({ decades: Array.from({ length: 51 }, () => 1990) })), ).toThrow('At most 50 decade filters are allowed'); expect(() => searchFilter(input({ decades: [1990.5] }))).toThrow('Invalid decade'); + expect(() => searchFilter(input({ decades: [-10] }))).toThrow('Invalid decade'); + expect(() => searchFilter(input({ decades: [2_147_483_648] }))).toThrow( + 'Invalid decade', + ); }); }); diff --git a/server/src/search/search.ts b/server/src/search/search.ts index 0398b0e..0eeb4a8 100644 --- a/server/src/search/search.ts +++ b/server/src/search/search.ts @@ -1,5 +1,16 @@ import { sql, type SQL } from 'drizzle-orm'; import { GraphQLError } from 'graphql'; +import { + MAX_SEARCH_QUERY_LENGTH, + POSTGRES_INT4_MAX, + decodeBase64UrlJson, + encodeBase64UrlJson, + isPositiveInt4, + isValidInt4, + parsePositiveInt4, +} from '../validation.js'; + +export { MAX_SEARCH_QUERY_LENGTH }; /** * Pure building blocks for searchAlbums: the WHERE clause, the sort order and @@ -26,7 +37,6 @@ export type AlbumSearchInput = { }; const MAX_PAGE_SIZE = 50; -export const MAX_SEARCH_QUERY_LENGTH = 200; const MAX_FILTER_VALUES = 50; export function pageSize(first: number): number { @@ -50,7 +60,7 @@ function assertFilterLimit(values: readonly unknown[], label: string): void { } function parseDecade(value: number): number { - if (!Number.isInteger(value)) { + if (!Number.isInteger(value) || value < 0 || value > POSTGRES_INT4_MAX) { throw new GraphQLError(`Invalid decade: ${value}`); } return value; @@ -73,9 +83,7 @@ function tsQuery(query: string): SQL { } function parseGenreId(id: string): number { - const n = Number(id); - if (!Number.isInteger(n)) throw new GraphQLError(`Invalid genre id: ${id}`); - return n; + return parsePositiveInt4(id, `Invalid genre id: ${id}`); } function parseCountryCode(value: string): string { @@ -289,27 +297,31 @@ export function orderBy(key: SortKey): SQL { export type Cursor = { sort: AlbumSort; value: string | number | null; id: number }; export function encodeCursor(cursor: Cursor): string { - return Buffer.from(JSON.stringify([cursor.sort, cursor.value, cursor.id])).toString( - 'base64url', - ); + return encodeBase64UrlJson([cursor.sort, cursor.value, cursor.id]); } export function decodeCursor(encoded: string, sort: AlbumSort): Cursor { - let parsed: unknown; - try { - parsed = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')); - } catch { + const parsed = decodeBase64UrlJson(encoded, 'Invalid cursor'); + if (!Array.isArray(parsed) || parsed.length !== 3) { throw new GraphQLError('Invalid cursor'); } - if (!Array.isArray(parsed) || parsed.length !== 3) - throw new GraphQLError('Invalid cursor'); const [cursorSort, value, id] = parsed as unknown[]; if (cursorSort !== sort) throw new GraphQLError('Cursor belongs to a different sort'); - if (!Number.isInteger(id)) throw new GraphQLError('Invalid cursor'); + if (!isPositiveInt4(id)) throw new GraphQLError('Invalid cursor'); if (value !== null && typeof value !== 'string' && typeof value !== 'number') { throw new GraphQLError('Invalid cursor'); } - return { sort, value, id: id as number }; + if (typeof value === 'number' && !Number.isFinite(value)) { + throw new GraphQLError('Invalid cursor'); + } + if ( + (sort === 'RELEASE_YEAR_ASC' || sort === 'RELEASE_YEAR_DESC') && + value !== null && + !isValidInt4(value) + ) { + throw new GraphQLError('Invalid cursor'); + } + return { sort, value, id }; } /** "Comes after the cursor" in the order given by orderBy(key). */ diff --git a/server/src/searchHistory.ts b/server/src/searchHistory.ts index 00c17ac..82a4e59 100644 --- a/server/src/searchHistory.ts +++ b/server/src/searchHistory.ts @@ -4,9 +4,9 @@ import { GraphQLError } from 'graphql'; import type { Db } from './db/client.js'; import { appUser, searchHistory } from './db/schema.js'; import { ensureUser, requireUserId } from './userIdentity.js'; +import { MAX_SEARCH_QUERY_LENGTH } from './validation.js'; const HISTORY_LIMIT = 10; -const MAX_SEARCH_QUERY_LENGTH = 200; export async function historyForUser(db: Db, userId: string | null) { if (!userId) return []; diff --git a/server/src/security.test.ts b/server/src/security.test.ts new file mode 100644 index 0000000..df74645 --- /dev/null +++ b/server/src/security.test.ts @@ -0,0 +1,706 @@ +import { readFileSync } from 'node:fs'; +import { request as httpRequest, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { performance } from 'node:perf_hooks'; +import { + buildSchema, + getIntrospectionQuery, + parse, + specifiedRules, + validate, +} from 'graphql'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { + buildInternalGraphqlUrl, + configFromEnv, + createAppServer, + registerGracefulShutdown, +} from './app.js'; +import type { Db } from './db/client.js'; +import { + createQueryLimitsRule, + createRateLimiter, + getClientIp, + noIntrospectionRule, + parseCorsOrigins, +} from './security.js'; + +const typeDefs = readFileSync(new URL('../../schema.graphql', import.meta.url), 'utf8'); +const schema = buildSchema(typeDefs); + +const stubDb = {} as unknown as Db; + +function validateQuery(query: string, extraRules = [createQueryLimitsRule()]) { + return validate(schema, parse(query), [...specifiedRules, ...extraRules]); +} + +async function startTestServer( + options: Omit[0], 'db' | 'typeDefs'> = {}, +) { + const { server, yoga, rateLimiter } = createAppServer({ + db: stubDb, + typeDefs, + ...options, + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve())); + const { port } = server.address() as AddressInfo; + return { + server, + yoga, + rateLimiter, + url: `http://127.0.0.1:${port}/graphql`, + port, + }; +} + +function closeServer(server: Server): Promise { + return new Promise((resolve, reject) => + server.close((err) => (err ? reject(err) : resolve())), + ); +} + +describe('GraphQL validation limits', () => { + it('allows all legitimate client queries and mutations', () => { + const operations = [ + '{ __typename }', + `query SearchAlbums($input: AlbumSearchInput!, $first: Int!, $after: String) { + searchAlbums(input: $input, first: $first, after: $after) { + __typename + edges { + __typename + cursor + node { + __typename + id + title + releaseYear + musicBrainzReleaseGroupId + artists { __typename id name } + genres { __typename id name } + averageRating + reviewCount + isInCrate + } + } + pageInfo { __typename hasNextPage endCursor } + totalCount + genreFacets { __typename genre { __typename id name } count } + decadeFacets { __typename decade count } + countryFacets { __typename countryCode countryName count } + reviewedCount + } + }`, + `query AlbumDetail($id: ID!, $reviewFirst: Int!, $reviewAfter: String) { + album(id: $id) { + __typename + id + title + releaseYear + musicBrainzReleaseGroupId + artists { __typename id name } + genres { __typename id name } + tracks { __typename id title trackNumber durationSeconds } + averageRating + reviewCount + isInCrate + myReview { __typename id rating comment } + reviews(first: $reviewFirst, after: $reviewAfter) { + __typename + edges { + __typename + cursor + node { + __typename + id + rating + comment + createdAt + updatedAt + user { __typename displayName } + } + } + pageInfo { __typename hasNextPage endCursor } + totalCount + } + } + }`, + `query MyCrate($first: Int!, $after: String) { + myCrate(first: $first, after: $after) { + __typename + edges { + __typename + cursor + node { + __typename + id + addedAt + album { + __typename + id + title + releaseYear + musicBrainzReleaseGroupId + averageRating + reviewCount + isInCrate + artists { __typename id name } + genres { __typename id name } + } + } + } + pageInfo { __typename hasNextPage endCursor } + totalCount + } + }`, + `mutation UpsertReview($input: UpsertReviewInput!) { + upsertReview(input: $input) { + review { id rating comment } + album { id averageRating reviewCount myReview { id } } + } + }`, + ]; + + for (const op of operations) { + expect(validateQuery(op)).toEqual([]); + } + }); + + it('rejects queries exceeding maximum depth (8)', () => { + // Depth 9: myCrate(1) -> edges(2) -> node(3) -> album(4) -> reviews(5) -> edges(6) -> node(7) -> user(8) -> displayName(9) + const tooDeep = ` + query { + myCrate(first: 1) { + edges { + node { + album { + reviews(first: 1) { + edges { + node { + user { + displayName + } + } + } + } + } + } + } + } + } + `; + const errors = validateQuery(tooDeep); + expect(errors.some((e) => e.message.includes('maximum allowed depth of 8'))).toBe( + true, + ); + }); + + it('rejects queries exceeding maximum alias count (10)', () => { + const aliases = Array.from({ length: 11 }, (_, i) => `a${i}: __typename`).join(' '); + const errors = validateQuery(`query { ${aliases} }`); + expect( + errors.some((e) => e.message.includes('maximum allowed alias count of 10')), + ).toBe(true); + }); + + it('rejects nested Album.reviews amplification inside searchAlbums', () => { + const amplified = ` + query { + searchAlbums(input: { query: "", sort: TITLE_ASC }, first: 20) { + edges { + node { + id + reviews(first: 10) { + edges { + node { id } + } + } + } + } + } + } + `; + const errors = validateQuery(amplified); + expect(errors.some((e) => e.message.includes('maximum allowed complexity'))).toBe( + true, + ); + }); + + it('rejects fragment expansion bombs exceeding complexity limit', () => { + const bomb = ` + query { + album(id: "1") { + ...F1 + ...F1 + ...F1 + } + } + fragment F1 on Album { ...F2 ...F2 ...F2 ...F2 } + fragment F2 on Album { ...F3 ...F3 ...F3 ...F3 } + fragment F3 on Album { id title releaseYear averageRating reviewCount isInCrate } + `; + const errors = validateQuery(bomb); + expect(errors.some((e) => e.message.includes('maximum allowed complexity'))).toBe( + true, + ); + }); + + it('rejects 11 mutually spreading cyclic fragments cleanly and quickly', () => { + const names = Array.from({ length: 11 }, (_, i) => `F${i + 1}`); + const fragments = names + .map((name) => { + const spreads = names + .filter((other) => other !== name) + .map((other) => `...${other}`) + .join(' '); + return `fragment ${name} on Album { ${spreads} }`; + }) + .join('\n'); + const doc = `query { album(id: "1") { ...F1 } }\n${fragments}`; + + const start = performance.now(); + const errors = validateQuery(doc); + const elapsedMs = performance.now() - start; + + expect(errors.length).toBeGreaterThan(0); + expect(errors.some((e) => e.message.includes('Cannot spread fragment'))).toBe(true); + expect(elapsedMs).toBeLessThan(100); + }); + + it('counts inline fragments toward complexity limit', () => { + const inlineNest = + 'query { album(id: "1") { ' + + '... on Album { '.repeat(210) + + 'id' + + ' }'.repeat(210) + + ' } }'; + const errors = validateQuery(inlineNest); + expect(errors.some((e) => e.message.includes('maximum allowed complexity'))).toBe( + true, + ); + }); + + it('allows deep GraphiQL introspection queries under query limits when introspection is enabled', () => { + const introspection = getIntrospectionQuery(); + expect(validateQuery(introspection)).toEqual([]); + + const prodErrors = validateQuery(introspection, [ + createQueryLimitsRule(), + noIntrospectionRule, + ]); + expect(prodErrors.some((e) => e.message.includes('introspection is disabled'))).toBe( + true, + ); + }); + + it('blocks __schema and __type with noIntrospectionRule while allowing __typename', () => { + expect(validateQuery('{ __typename }', [noIntrospectionRule])).toEqual([]); + + const schemaErrors = validateQuery('{ __schema { types { name } } }', [ + noIntrospectionRule, + ]); + expect(schemaErrors[0]?.message).toContain('introspection is disabled'); + + const typeErrors = validateQuery('{ __type(name: "Album") { name } }', [ + noIntrospectionRule, + ]); + expect(typeErrors[0]?.message).toContain('introspection is disabled'); + }); +}); + +describe('client IP & CORS helpers', () => { + it('trusts X-Forwarded-For only from loopback and takes the proxy-appended hop', () => { + expect(getClientIp('127.0.0.1', '203.0.113.10')).toBe('203.0.113.10'); + expect(getClientIp('::1', '198.51.100.1, 203.0.113.20')).toBe('203.0.113.20'); + expect(getClientIp('::ffff:127.0.0.1', '203.0.113.30')).toBe('203.0.113.30'); + // Untrusted non-loopback peer cannot spoof X-Forwarded-For. + expect(getClientIp('198.51.100.5', '203.0.113.99')).toBe('198.51.100.5'); + expect(getClientIp('127.0.0.1', undefined)).toBe('127.0.0.1'); + }); + + it('parses CORS_ORIGIN allowlist and env config', () => { + expect(parseCorsOrigins(undefined)).toEqual([]); + expect(parseCorsOrigins(' https://a.test , https://b.test , ')).toEqual([ + 'https://a.test', + 'https://b.test', + ]); + const cfg = configFromEnv({ + NODE_ENV: 'production', + CORS_ORIGIN: 'https://crate.example', + GRAPHQL_MAX_BODY_BYTES: '81920', + 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.rateLimitMaxRequests).toBe(50); + }); + + it('enforces per-IP rate limits with Retry-After and window reset', () => { + let time = 1_000; + const limiter = createRateLimiter({ + windowMs: 10_000, + maxRequests: 2, + now: () => time, + }); + + expect(limiter.check('1.1.1.1')).toEqual({ allowed: true, remaining: 1 }); + expect(limiter.check('1.1.1.1')).toEqual({ allowed: true, remaining: 0 }); + expect(limiter.check('1.1.1.1')).toEqual({ allowed: false, retryAfterSeconds: 10 }); + expect(limiter.check('2.2.2.2')).toEqual({ allowed: true, remaining: 1 }); + + time += 10_000; + expect(limiter.check('1.1.1.1')).toEqual({ allowed: true, remaining: 1 }); + }); +}); + +describe('HTTP server hardening', () => { + const servers: Server[] = []; + + afterEach(async () => { + while (servers.length) { + await closeServer(servers.pop()!); + } + }); + + it('rejects oversized bodies with 413 (both Content-Length and chunked) and sets security headers', async () => { + const instance = await startTestServer({ maxBodyBytes: 1024 }); + servers.push(instance.server); + + const largePayload = JSON.stringify({ + query: '{ __typename }', + pad: 'x'.repeat(2048), + }); + const res = await fetch(instance.url, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: largePayload, + }); + expect(res.status).toBe(413); + expect(res.headers.get('cache-control')).toBe('no-store'); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + + // Chunked transfer without Content-Length header + const chunkedStatus = await new Promise((resolve, reject) => { + const req = httpRequest( + { + hostname: '127.0.0.1', + port: instance.port, + path: '/graphql', + method: 'POST', + headers: { + 'content-type': 'application/json', + 'transfer-encoding': 'chunked', + }, + }, + (response) => { + response.resume(); + resolve(response.statusCode ?? 0); + }, + ); + req.on('error', reject); + req.write('{"query":"{ __typename }","pad":"'); + req.write('y'.repeat(1500)); + req.end('"}'); + }); + expect(chunkedStatus).toBe(413); + }); + + it('disables CORS by default and never reflects untrusted origins', async () => { + const instance = await startTestServer({ corsOrigins: [] }); + servers.push(instance.server); + + const res = await fetch(instance.url, { + method: 'POST', + headers: { + 'content-type': 'application/json', + origin: 'https://evil.example', + }, + body: JSON.stringify({ query: '{ __typename }' }), + }); + expect(res.status).toBe(200); + expect(res.headers.get('access-control-allow-origin')).toBeNull(); + expect(res.headers.get('access-control-allow-credentials')).toBeNull(); + expect(res.headers.get('cache-control')).toBe('no-store'); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + }); + + it('allows only listed CORS_ORIGIN values with credentials disabled', async () => { + const instance = await startTestServer({ + corsOrigins: ['https://allowed.example'], + }); + servers.push(instance.server); + + const allowed = await fetch(instance.url, { + method: 'POST', + headers: { + 'content-type': 'application/json', + origin: 'https://allowed.example', + }, + body: JSON.stringify({ query: '{ __typename }' }), + }); + expect(allowed.status).toBe(200); + expect(allowed.headers.get('access-control-allow-origin')).toBe( + 'https://allowed.example', + ); + expect(allowed.headers.get('access-control-allow-credentials')).toBeNull(); + + const rejected = await fetch(instance.url, { + method: 'POST', + headers: { + 'content-type': 'application/json', + origin: 'https://evil.example', + }, + body: JSON.stringify({ query: '{ __typename }' }), + }); + expect(rejected.status).toBe(200); + expect(rejected.headers.get('access-control-allow-origin')).toBeNull(); + }); + + it('disables GraphiQL and introspection in production while keeping { __typename } working', async () => { + const instance = await startTestServer({ isProduction: true }); + servers.push(instance.server); + + const graphiql = await fetch(instance.url, { + method: 'GET', + headers: { accept: 'text/html' }, + }); + const html = await graphiql.text(); + expect(html.toLowerCase()).not.toContain('graphiql'); + + const introspection = await fetch(instance.url, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ query: '{ __schema { types { name } } }' }), + }); + const introspectionBody = (await introspection.json()) as { + errors?: { message: string }[]; + }; + expect(introspectionBody.errors?.[0]?.message).toContain('introspection is disabled'); + + const smoke = await fetch(instance.url, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ query: '{ __typename }' }), + }); + expect(smoke.status).toBe(200); + expect(smoke.headers.get('cache-control')).toBe('no-store'); + expect(smoke.headers.get('x-content-type-options')).toBe('nosniff'); + expect(await smoke.json()).toEqual({ data: { __typename: 'Query' } }); + }); + + it('allows full GraphiQL introspection in development and blocks it in production', async () => { + const introspection = getIntrospectionQuery(); + + const dev = await startTestServer({ isProduction: false }); + servers.push(dev.server); + + const devRes = await fetch(dev.url, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ query: introspection }), + }); + expect(devRes.status).toBe(200); + const devBody = (await devRes.json()) as { + data?: { __schema?: { types?: unknown[] } }; + errors?: unknown[]; + }; + expect(devBody.errors).toBeUndefined(); + expect(devBody.data?.__schema?.types?.length).toBeGreaterThan(0); + + const prod = await startTestServer({ isProduction: true }); + servers.push(prod.server); + + const prodRes = await fetch(prod.url, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ query: introspection }), + }); + const prodBody = (await prodRes.json()) as { errors?: { message: string }[] }; + expect(prodBody.errors?.[0]?.message).toContain('introspection is disabled'); + }); + + 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( + 'http://localhost/graphql?query=%7B__typename%7D', + ); + expect(buildInternalGraphqlUrl('/graphql/foo/graphql')).toBeNull(); + expect(buildInternalGraphqlUrl('/graphql//graphql')).toBeNull(); + expect(buildInternalGraphqlUrl('/graphql/')).toBeNull(); + expect(buildInternalGraphqlUrl('/')).toBeNull(); + expect(buildInternalGraphqlUrl('//evil.example/graphql')).toBeNull(); + + const seenUrls: string[] = []; + const instance = await startTestServer({ + rateLimitWindowMs: 30_000, + rateLimitMaxRequests: 1, + plugins: [ + { + onRequest({ request }) { + seenUrls.push(request.url); + }, + }, + ], + }); + servers.push(instance.server); + + // Exhaust rate limit on /graphql for this client IP. + const ok = await fetch(instance.url, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-forwarded-for': '203.0.113.50', + }, + body: JSON.stringify({ query: '{ __typename }' }), + }); + expect(ok.status).toBe(200); + expect(seenUrls).toEqual(['http://localhost/graphql']); + + const limited = await fetch(instance.url, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-forwarded-for': '203.0.113.50', + }, + body: JSON.stringify({ query: '{ __typename }' }), + }); + expect(limited.status).toBe(429); + + // Suffix paths and other paths must return 404 and never reach Yoga. + for (const badPath of [ + '/graphql/foo/graphql', + '/graphql//graphql', + '/graphql/', + '/', + '/health', + ]) { + const res = await fetch(`http://127.0.0.1:${instance.port}${badPath}`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-forwarded-for': '203.0.113.50', + }, + body: JSON.stringify({ query: '{ __typename }' }), + }); + expect(res.status).toBe(404); + expect(res.headers.get('cache-control')).toBe('no-store'); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + } + expect(seenUrls).toEqual(['http://localhost/graphql']); + + // Exact /graphql with query string is allowed for a fresh IP. + const getRes = await fetch( + `http://127.0.0.1:${instance.port}/graphql?query=%7B__typename%7D`, + { + method: 'GET', + headers: { 'x-forwarded-for': '203.0.113.51' }, + }, + ); + expect(getRes.status).toBe(200); + expect(await getRes.json()).toEqual({ data: { __typename: 'Query' } }); + expect(seenUrls).toEqual([ + 'http://localhost/graphql', + 'http://localhost/graphql?query=%7B__typename%7D', + ]); + }); + + it('builds yoga.fetch URL from fixed internal origin regardless of Host header', async () => { + const seenUrls: string[] = []; + const instance = await startTestServer({ + plugins: [ + { + onRequest({ request }) { + seenUrls.push(request.url); + }, + }, + ], + }); + servers.push(instance.server); + + const sendWithHost = (hostHeader: string) => + new Promise<{ status: number; body: string }>((resolve, reject) => { + const payload = JSON.stringify({ query: '{ __typename }' }); + const req = httpRequest( + { + hostname: '127.0.0.1', + port: instance.port, + path: '/graphql', + method: 'POST', + headers: { + host: hostHeader, + 'content-type': 'application/json', + 'content-length': Buffer.byteLength(payload), + }, + }, + (response) => { + const chunks: Buffer[] = []; + response.on('data', (chunk: Buffer) => chunks.push(chunk)); + response.on('end', () => { + resolve({ + status: response.statusCode ?? 0, + body: Buffer.concat(chunks).toString('utf8'), + }); + }); + }, + ); + req.on('error', reject); + req.end(payload); + }); + + for (const spoofedHost of ['evil.example:9999', '[invalid-host']) { + const result = await sendWithHost(spoofedHost); + expect(result.status).toBe(200); + expect(JSON.parse(result.body)).toEqual({ data: { __typename: 'Query' } }); + } + + expect(seenUrls).toEqual(['http://localhost/graphql', 'http://localhost/graphql']); + }); + + it('returns 429 with Retry-After when rate limit is exceeded', async () => { + const instance = await startTestServer({ + rateLimitWindowMs: 30_000, + rateLimitMaxRequests: 2, + }); + servers.push(instance.server); + + const post = (forwardedFor: string) => + fetch(instance.url, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-forwarded-for': forwardedFor, + }, + body: JSON.stringify({ query: '{ __typename }' }), + }); + + expect((await post('203.0.113.5')).status).toBe(200); + expect((await post('203.0.113.5')).status).toBe(200); + + const limited = await post('203.0.113.5'); + expect(limited.status).toBe(429); + expect(Number(limited.headers.get('retry-after'))).toBeGreaterThanOrEqual(1); + expect(limited.headers.get('cache-control')).toBe('no-store'); + expect(limited.headers.get('x-content-type-options')).toBe('nosniff'); + + // Different forwarded client IP is unaffected + expect((await post('203.0.113.6')).status).toBe(200); + }); +}); + +describe('graceful shutdown', () => { + it('closes the HTTP server and PostgreSQL pool once on signal', async () => { + const serverClose = vi.fn((cb: (err?: Error) => void) => cb()); + const poolEnd = vi.fn(async () => undefined); + const onExit = vi.fn(); + const server = { close: serverClose } as unknown as Server; + + const handler = registerGracefulShutdown(server, poolEnd, { onExit }); + handler('SIGTERM'); + handler('SIGINT'); // duplicate signal is ignored + + await vi.waitFor(() => expect(onExit).toHaveBeenCalledWith(0)); + expect(serverClose).toHaveBeenCalledTimes(1); + expect(poolEnd).toHaveBeenCalledTimes(1); + }); +}); diff --git a/server/src/security.ts b/server/src/security.ts new file mode 100644 index 0000000..174627d --- /dev/null +++ b/server/src/security.ts @@ -0,0 +1,338 @@ +import { + GraphQLError, + Kind, + type FieldNode, + type FragmentDefinitionNode, + type FragmentSpreadNode, + type InlineFragmentNode, + type SelectionSetNode, + type ValidationRule, +} from 'graphql'; + +export type CorsConfig = + | false + | { + origin?: string[] | string; + methods?: string[]; + allowedHeaders?: string[]; + exposedHeaders?: string[]; + credentials?: boolean; + maxAge?: number; + }; + +export const DEFAULT_MAX_QUERY_DEPTH = 8; +export const DEFAULT_MAX_ALIASES = 10; +export const DEFAULT_MAX_COMPLEXITY = 200; +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; + +export const GRAPHQL_SECURITY_HEADERS: Readonly> = { + 'cache-control': 'no-store', + 'x-content-type-options': 'nosniff', +}; + +const FIELD_COSTS: Readonly> = { + searchAlbums: 10, + myCrate: 10, + reviews: 20, + genreFacets: 10, + decadeFacets: 10, + countryFacets: 10, + totalCount: 5, + reviewedCount: 5, +}; + +const ALBUM_CONNECTION_FIELDS = new Set(['searchAlbums', 'myCrate']); +const MAX_CONNECTION_PAGE_SIZE = 50; + +export type QueryLimitOptions = { + maxDepth?: number; + maxAliases?: number; + maxComplexity?: number; +}; + +function readFirstArgument(field: FieldNode): number { + const firstArg = field.arguments?.find((arg) => arg.name.value === 'first'); + if (firstArg?.value.kind === Kind.INT) { + const parsed = Number(firstArg.value.value); + if (Number.isInteger(parsed)) { + return Math.min(Math.max(parsed, 1), MAX_CONNECTION_PAGE_SIZE); + } + } + // When `first` is a variable or omitted, assume worst-case page size. + return MAX_CONNECTION_PAGE_SIZE; +} + +/** + * GraphQL validation rule enforcing bounded query depth, alias count, and + * selection/nesting complexity (including blocking nested Album.reviews + * amplification inside album connections). + */ +export function createQueryLimitsRule(options: QueryLimitOptions = {}): ValidationRule { + const maxDepth = options.maxDepth ?? DEFAULT_MAX_QUERY_DEPTH; + const maxAliases = options.maxAliases ?? DEFAULT_MAX_ALIASES; + const maxComplexity = options.maxComplexity ?? DEFAULT_MAX_COMPLEXITY; + + return (context) => ({ + Document(document) { + const fragments = new Map(); + for (const definition of document.definitions) { + if (definition.kind === Kind.FRAGMENT_DEFINITION) { + fragments.set(definition.name.value, definition); + } + } + + for (const definition of document.definitions) { + if (definition.kind !== Kind.OPERATION_DEFINITION) continue; + + const state = { + aliases: 0, + complexity: 0, + aborted: false, + }; + + const chargeComplexity = ( + cost: number, + node: FieldNode | InlineFragmentNode | FragmentSpreadNode, + ): boolean => { + state.complexity += cost; + if (state.complexity > maxComplexity) { + context.reportError( + new GraphQLError( + `Query complexity exceeds maximum allowed complexity of ${maxComplexity}.`, + { nodes: node }, + ), + ); + state.aborted = true; + return false; + } + return true; + }; + + const visitSelectionSet = ( + selectionSet: SelectionSetNode, + depth: number, + visitedFragments: ReadonlySet, + outerConnectionMultiplier: number, + ): void => { + for (const selection of selectionSet.selections) { + if (state.aborted) return; + + if (selection.kind === Kind.FIELD) { + const nextDepth = depth + 1; + if (nextDepth > maxDepth) { + context.reportError( + new GraphQLError( + `Query depth exceeds maximum allowed depth of ${maxDepth}.`, + { nodes: selection }, + ), + ); + state.aborted = true; + return; + } + + if (selection.alias) { + state.aliases += 1; + if (state.aliases > maxAliases) { + context.reportError( + new GraphQLError( + `Query exceeds maximum allowed alias count of ${maxAliases}.`, + { nodes: selection }, + ), + ); + state.aborted = true; + return; + } + } + + const fieldName = selection.name.value; + const baseCost = FIELD_COSTS[fieldName] ?? 1; + // Album.reviews is not DataLoader-backed, so nesting it inside an + // album connection multiplies SQL queries by the outer page size. + const multiplier = + fieldName === 'reviews' && outerConnectionMultiplier > 1 + ? outerConnectionMultiplier + : 1; + if (!chargeComplexity(baseCost * multiplier, selection)) return; + + // Skip depth and complexity traversal inside introspection subtrees + // so dev GraphiQL can load the schema; production still rejects + // __schema and __type via noIntrospectionRule. + const isIntrospectionRoot = + fieldName === '__schema' || fieldName === '__type'; + if (selection.selectionSet && !isIntrospectionRoot) { + const nextMultiplier = ALBUM_CONNECTION_FIELDS.has(fieldName) + ? Math.max(outerConnectionMultiplier, readFirstArgument(selection)) + : outerConnectionMultiplier; + visitSelectionSet( + selection.selectionSet, + nextDepth, + visitedFragments, + nextMultiplier, + ); + } + } else if (selection.kind === Kind.INLINE_FRAGMENT) { + if (!chargeComplexity(1, selection)) return; + visitSelectionSet( + selection.selectionSet, + depth, + visitedFragments, + outerConnectionMultiplier, + ); + } else if (selection.kind === Kind.FRAGMENT_SPREAD) { + if (!chargeComplexity(1, selection)) return; + const name = selection.name.value; + if (visitedFragments.has(name)) { + context.reportError( + new GraphQLError(`Cannot spread fragment "${name}" within itself.`, { + nodes: selection, + }), + ); + state.aborted = true; + return; + } + const fragment = fragments.get(name); + if (!fragment) continue; + const nextVisited = new Set(visitedFragments); + nextVisited.add(name); + visitSelectionSet( + fragment.selectionSet, + depth, + nextVisited, + outerConnectionMultiplier, + ); + } + } + }; + + visitSelectionSet(definition.selectionSet, 0, new Set(), 1); + } + }, + }); +} + +/** + * Blocks schema introspection (`__schema` and `__type`) in production while + * keeping `{ __typename }` enabled for client caches and CI smoke checks. + */ +export const noIntrospectionRule: ValidationRule = (context) => ({ + Field(node) { + if (node.name.value === '__schema' || node.name.value === '__type') { + context.reportError( + new GraphQLError('GraphQL introspection is disabled in production.', { + nodes: node, + }), + ); + } + }, +}); + +export function parseCorsOrigins(raw: string | undefined): string[] { + if (!raw) return []; + return raw + .split(',') + .map((origin) => origin.trim()) + .filter((origin) => origin.length > 0); +} + +export function createCorsConfig( + allowedOrigins: readonly string[], +): false | ((request: Request) => CorsConfig) { + if (allowedOrigins.length === 0) return false; + const allowlist = new Set(allowedOrigins); + return (request: Request): CorsConfig => { + const origin = request.headers.get('origin'); + if (!origin || !allowlist.has(origin)) { + return false; + } + return { + origin: [origin], + credentials: false, + methods: ['POST', 'OPTIONS'], + allowedHeaders: ['Content-Type', 'X-User-Id'], + }; + }; +} + +export function isLoopbackAddress(address: string | undefined): boolean { + return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'; +} + +/** + * Resolves the client IP for rate limiting. Only trusts X-Forwarded-For when + * the direct peer is loopback (the local Apache reverse proxy), taking the + * rightmost hop appended by that proxy so spoofed leading entries are ignored. + */ +export function getClientIp( + remoteAddress: string | undefined, + forwardedFor: string | string[] | undefined, +): string { + if (isLoopbackAddress(remoteAddress) && forwardedFor) { + const raw = Array.isArray(forwardedFor) ? forwardedFor.join(',') : forwardedFor; + const hops = raw + .split(',') + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0); + const proxyAppended = hops.at(-1); + if (proxyAppended) return proxyAppended; + } + return remoteAddress || 'unknown'; +} + +export type RateLimitResult = + { allowed: true; remaining: number } | { allowed: false; retryAfterSeconds: number }; + +export type RateLimiterOptions = { + windowMs?: number; + maxRequests?: number; + now?: () => number; +}; + +export function createRateLimiter(options: RateLimiterOptions = {}) { + const windowMs = options.windowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS; + const maxRequests = options.maxRequests ?? DEFAULT_RATE_LIMIT_MAX_REQUESTS; + const now = options.now ?? Date.now; + const buckets = new Map(); + + function prune(currentTime: number): void { + for (const [key, bucket] of buckets) { + if (bucket.resetAt <= currentTime) { + buckets.delete(key); + } + } + } + + return { + check(ip: string): RateLimitResult { + if (maxRequests <= 0) { + return { allowed: true, remaining: Number.POSITIVE_INFINITY }; + } + + const currentTime = now(); + if (buckets.size > 1000) { + prune(currentTime); + } + + const existing = buckets.get(ip); + if (!existing || existing.resetAt <= currentTime) { + buckets.set(ip, { count: 1, resetAt: currentTime + windowMs }); + return { allowed: true, remaining: Math.max(0, maxRequests - 1) }; + } + + if (existing.count >= maxRequests) { + const retryAfterSeconds = Math.max( + 1, + Math.ceil((existing.resetAt - currentTime) / 1000), + ); + return { allowed: false, retryAfterSeconds }; + } + + existing.count += 1; + return { allowed: true, remaining: Math.max(0, maxRequests - existing.count) }; + }, + reset(): void { + buckets.clear(); + }, + }; +} diff --git a/server/src/validation.ts b/server/src/validation.ts new file mode 100644 index 0000000..2e39be4 --- /dev/null +++ b/server/src/validation.ts @@ -0,0 +1,90 @@ +import { GraphQLError } from 'graphql'; + +export const POSTGRES_INT4_MIN = -2_147_483_648; +export const POSTGRES_INT4_MAX = 2_147_483_647; +export const MAX_SEARCH_QUERY_LENGTH = 200; + +const DIGITS_ONLY = /^\d+$/; + +// UTC timestamp with six fractional digits, matching PostgreSQL timestamptz +// microsecond precision. A JS Date keeps only milliseconds, so cursors carry +// the formatted database text and validate its shape before SQL sees it. +const EXACT_UTC_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/; + +export function isValidInt4(value: unknown): value is number { + return ( + typeof value === 'number' && + Number.isInteger(value) && + value >= POSTGRES_INT4_MIN && + value <= POSTGRES_INT4_MAX + ); +} + +export function isPositiveInt4(value: unknown): value is number { + return ( + typeof value === 'number' && + Number.isInteger(value) && + value >= 1 && + value <= POSTGRES_INT4_MAX + ); +} + +export function parsePositiveInt4(value: string, errorMessage: string): number { + if (!DIGITS_ONLY.test(value)) { + throw new GraphQLError(errorMessage); + } + const id = Number(value); + if (!isPositiveInt4(id)) { + throw new GraphQLError(errorMessage); + } + return id; +} + +export function parseNumericId(value: string, label: string): number { + return parsePositiveInt4(value, `Invalid ${label} id.`); +} + +export function encodeBase64UrlJson(payload: unknown): string { + return Buffer.from(JSON.stringify(payload)).toString('base64url'); +} + +export function decodeBase64UrlJson(encoded: string, errorMessage: string): unknown { + try { + return JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')) as unknown; + } catch { + throw new GraphQLError(errorMessage); + } +} + +export function isExactUtcTimestamp(text: string): boolean { + if (!EXACT_UTC_TIMESTAMP.test(text)) return false; + const milliseconds = Date.parse(text); + // Date.parse rolls 30 February over to 2 March; a real date survives the round trip. + return ( + !Number.isNaN(milliseconds) && + new Date(milliseconds).toISOString().startsWith(text.slice(0, 19)) + ); +} + +export type TimestampCursor = { timestamp: string; id: number }; + +export function encodeTimestampCursor(cursor: TimestampCursor): string { + return encodeBase64UrlJson([cursor.timestamp, cursor.id]); +} + +export function decodeTimestampCursor(encoded: string, label: string): TimestampCursor { + const message = `Invalid ${label} cursor.`; + const parsed = decodeBase64UrlJson(encoded, message); + if (!Array.isArray(parsed) || parsed.length !== 2) { + throw new GraphQLError(message); + } + const [timestamp, id] = parsed as unknown[]; + if ( + typeof timestamp !== 'string' || + !isExactUtcTimestamp(timestamp) || + !isPositiveInt4(id) + ) { + throw new GraphQLError(message); + } + return { timestamp, id }; +}