diff --git a/packages/apollo/tests/subscriptions/graphql-ws-custom-server.spec.ts b/packages/apollo/tests/subscriptions/graphql-ws-custom-server.spec.ts new file mode 100644 index 000000000..ea27899eb --- /dev/null +++ b/packages/apollo/tests/subscriptions/graphql-ws-custom-server.spec.ts @@ -0,0 +1,181 @@ +import { DynamicModule, INestApplication } from '@nestjs/common'; +import { FastifyAdapter } from '@nestjs/platform-fastify'; +import { Test } from '@nestjs/testing'; +import { GRAPHQL_TRANSPORT_WS_PROTOCOL } from 'graphql-ws'; +import ws, { WebSocketServer } from 'ws'; +import { AppModule } from './app/app.module.js'; +import { FederationAppModule } from './federation-app/federation-app.module.js'; + +type ModuleFactory = (server: WebSocketServer) => DynamicModule; + +const cases: Array<[string, ModuleFactory, () => FastifyAdapter | undefined]> = + [ + [ + 'ApolloDriver, Express', + (server) => + AppModule.forRoot({ subscriptions: { 'graphql-ws': { server } } }), + () => undefined, + ], + [ + 'ApolloDriver, Fastify', + (server) => + AppModule.forRoot({ subscriptions: { 'graphql-ws': { server } } }), + () => new FastifyAdapter(), + ], + [ + 'ApolloFederationDriver, Express', + (server) => + FederationAppModule.forRoot({ + subscriptions: { 'graphql-ws': { server } }, + }), + () => undefined, + ], + ]; + +const withTimeout = (promise: Promise, ms = 2000) => + Promise.race([ + promise, + new Promise((resolve) => setTimeout(() => resolve('timeout'), ms)), + ]); + +const connect = (url: string, protocol = GRAPHQL_TRANSPORT_WS_PROTOCOL) => { + const socket = new ws(url, protocol); + const acked = new Promise((resolve, reject) => { + socket.once('error', reject); + socket.once('open', () => + socket.send(JSON.stringify({ type: 'connection_init' })), + ); + socket.on('message', (data) => { + if (JSON.parse(data.toString()).type === 'connection_ack') { + resolve(); + } + }); + }); + const closed = new Promise((resolve) => + socket.once('close', (code) => resolve(code)), + ); + return { socket, acked, closed }; +}; + +describe.each(cases)( + 'graphql-ws custom server (%s)', + (_name, moduleFactory, adapterFactory) => { + let app: INestApplication; + let server: WebSocketServer; + let port: number; + let socket: ws | undefined; + let closing: Promise | undefined; + const onConnection = vi.fn(); + + beforeEach(async () => { + onConnection.mockClear(); + server = new WebSocketServer({ + noServer: true, + path: '/subscriptions', + maxPayload: 1024, + }); + server.on('connection', onConnection); + + const module = await Test.createTestingModule({ + imports: [moduleFactory(server)], + }).compile(); + const adapter = adapterFactory(); + app = adapter + ? module.createNestApplication(adapter) + : module.createNestApplication(); + await app.listen(0, '127.0.0.1'); + port = app.getHttpServer().address().port; + }); + + afterEach(async () => { + socket?.terminate(); + socket = undefined; + await (closing ?? app.close()); + closing = undefined; + }); + + it('routes connections on its own path to the custom server', async () => { + const client = connect(`ws://127.0.0.1:${port}/subscriptions`); + socket = client.socket; + + expect(await withTimeout(client.acked.then(() => 'acked'))).toBe('acked'); + expect(onConnection).toHaveBeenCalledTimes(1); + expect(server.clients.size).toBe(1); + }); + + it('applies the options of the custom server', async () => { + const client = connect(`ws://127.0.0.1:${port}/subscriptions`); + socket = client.socket; + await client.acked; + + client.socket.send('x'.repeat(2048)); + + // 1009: message too big, enforced by the custom server's maxPayload + expect(await withTimeout(client.closed)).toBe(1009); + }); + + it('closes the custom server when the application closes', async () => { + const client = connect(`ws://127.0.0.1:${port}/subscriptions`); + socket = client.socket; + await client.acked; + + // Don't await app.close() itself: a lingering socket may keep it pending. + closing = app.close(); + + expect(await withTimeout(client.closed)).toBe(1001); + // graphql-ws disposed the server: its listeners are gone + expect(server.listenerCount('connection')).toBe(0); + await vi.waitFor(() => expect(server.clients.size).toBe(0)); + }); + }, +); + +describe('graphql-ws custom server validation', () => { + it('rejects a server that was not created with "noServer: true"', async () => { + const server = new WebSocketServer({ port: 0, host: '127.0.0.1' }); + try { + const module = await Test.createTestingModule({ + imports: [ + AppModule.forRoot({ subscriptions: { 'graphql-ws': { server } } }), + ], + }).compile(); + const app = module.createNestApplication(); + + await expect(app.init()).rejects.toThrow( + 'Custom WebSocketServer passed to "graphql-ws" must be instantiated with "noServer: true".', + ); + await app.close(); + } finally { + await new Promise((resolve) => server.close(resolve)); + } + }); +}); + +describe('graphql-ws default server', () => { + let app: INestApplication; + let socket: ws | undefined; + + beforeEach(async () => { + const module = await Test.createTestingModule({ + imports: [AppModule.forRoot({ subscriptions: { 'graphql-ws': {} } })], + }).compile(); + app = module.createNestApplication(); + await app.listen(0, '127.0.0.1'); + }); + + afterEach(async () => { + socket?.terminate(); + await app.close(); + }); + + it('answers upgrades that use an unsupported subprotocol', async () => { + const { port } = app.getHttpServer().address(); + // "graphql-ws" is the subprotocol of the legacy subscriptions-transport-ws + const client = connect(`ws://127.0.0.1:${port}/graphql`, 'graphql-ws'); + socket = client.socket; + + expect( + await withTimeout(client.acked.catch((err: Error) => err.message)), + ).toBe('Server sent no subprotocol'); + }); +}); diff --git a/packages/graphql/lib/services/gql-subscription.service.ts b/packages/graphql/lib/services/gql-subscription.service.ts index 310850d22..804bb25c3 100644 --- a/packages/graphql/lib/services/gql-subscription.service.ts +++ b/packages/graphql/lib/services/gql-subscription.service.ts @@ -11,6 +11,22 @@ import { import { useServer } from 'graphql-ws/use/ws'; import { WebSocketServer } from 'ws'; +/** + * The members of a `ws` `WebSocketServer` that Nest relies on. Typed + * structurally, so that the public types of `@nestjs/graphql` don't depend on + * `@types/ws`: pass a `new WebSocketServer({ noServer: true, ... })` instance. + */ +export interface GraphQLWsServer { + options: { noServer?: boolean; path?: string }; + handleUpgrade( + request: any, + socket: any, + upgradeHead: any, + callback: (client: any, request: any) => void, + ): void; + emit(event: 'connection', ...args: any[]): boolean; +} + export type GraphQLWsSubscriptionsConfig = Partial< Pick< ServerOptions, @@ -23,6 +39,19 @@ export type GraphQLWsSubscriptionsConfig = Partial< > > & { path?: string; + /** + * A `ws` WebSocketServer to use instead of the default one, e.g. to set + * `perMessageDeflate`, `maxPayload` or `verifyClient`. + * + * It must be created with `{ noServer: true }`: Nest routes the HTTP + * upgrade requests to it. Its `path`, when set, takes precedence over + * `path` above and the GraphQL module path. + * + * The server is handed over to graphql-ws, which replaces its + * `handleProtocols` option and, on application shutdown, closes it and + * removes all of its listeners. Use a separate server per GraphQL module. + */ + server?: GraphQLWsServer; }; export type SubscriptionConfig = { @@ -39,18 +68,33 @@ export interface GqlSubscriptionServiceOptions extends SubscriptionConfig { export class GqlSubscriptionService { private readonly wss: WebSocketServer; + private readonly path?: string; private wsGqlDisposable: Disposable; constructor( private readonly options: GqlSubscriptionServiceOptions, private readonly httpServer: any, ) { - this.wss = new WebSocketServer({ - path: - (this.options['graphql-ws'] as GraphQLWsSubscriptionsConfig)?.path ?? - this.options.path, - noServer: true, - }); + const graphqlWsConfig = + typeof this.options['graphql-ws'] === 'object' + ? this.options['graphql-ws'] + : undefined; + const customServer = graphqlWsConfig?.server; + + if (customServer && !customServer.options?.noServer) { + throw new Error( + 'Custom WebSocketServer passed to "graphql-ws" must be instantiated with "noServer: true".', + ); + } + + this.path = + customServer?.options.path ?? graphqlWsConfig?.path ?? this.options.path; + this.wss = + (customServer as WebSocketServer | undefined) ?? + new WebSocketServer({ + path: this.path, + noServer: true, + }); this.initialize(); } @@ -59,8 +103,13 @@ export class GqlSubscriptionService { this.options; if ('graphql-ws' in this.options) { - const graphqlWsOptions = - this.options['graphql-ws'] === true ? {} : this.options['graphql-ws']; + const { + server: _wsServer, + path: _wsPath, + ...graphqlWsOptions + } = this.options['graphql-ws'] === true + ? ({} as GraphQLWsSubscriptionsConfig) + : (this.options['graphql-ws'] as GraphQLWsSubscriptionsConfig); this.wsGqlDisposable = useServer( { schema: this.options.schema, @@ -89,7 +138,7 @@ export class GqlSubscriptionService { const wss = this.wss; - if (req.url?.startsWith(wss.options.path)) { + if (this.path && req.url?.startsWith(this.path)) { wss.handleUpgrade(req, socket, head, (ws) => { wss.emit('connection', ws, req); }); diff --git a/packages/graphql/tests/services/gql-subscription.service.spec.ts b/packages/graphql/tests/services/gql-subscription.service.spec.ts new file mode 100644 index 000000000..f7fa79104 --- /dev/null +++ b/packages/graphql/tests/services/gql-subscription.service.spec.ts @@ -0,0 +1,315 @@ +import { EventEmitter } from 'events'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { WebSocketServer } from 'ws'; +import { + GqlSubscriptionService, + GqlSubscriptionServiceOptions, +} from '../../lib/services/gql-subscription.service.js'; + +const createMockSocket = () => { + const socket = new EventEmitter() as any; + socket.write = vi.fn(); + socket.end = vi.fn(); + socket.destroy = vi.fn(); + socket.setTimeout = vi.fn(); + socket.setNoDelay = vi.fn(); + socket.setKeepAlive = vi.fn(); + socket.readable = true; + socket.writable = true; + socket.remoteAddress = '127.0.0.1'; + return socket; +}; + +const { mockUseServer } = vi.hoisted(() => ({ + mockUseServer: vi.fn().mockReturnValue({ dispose: vi.fn() }), +})); + +// Only mock useServer from graphql-ws; use the real WebSocketServer from 'ws' +vi.mock('graphql-ws/use/ws', () => ({ + useServer: mockUseServer, +})); + +vi.mock('graphql-ws', () => ({ + GRAPHQL_TRANSPORT_WS_PROTOCOL: 'graphql-transport-ws', +})); + +describe('GqlSubscriptionService', () => { + let mockHttpServer: any; + + beforeEach(() => { + vi.clearAllMocks(); + mockHttpServer = { + on: vi.fn(), + }; + }); + + describe('constructor', () => { + it('should create default WebSocketServer instance when no custom server is provided', () => { + const options: GqlSubscriptionServiceOptions = { + schema: {} as any, + path: '/graphql', + 'graphql-ws': {}, + }; + + const service = new GqlSubscriptionService(options, mockHttpServer); + const wss: WebSocketServer = (service as any).wss; + + expect(wss).toBeInstanceOf(WebSocketServer); + expect(wss.options.path).toBe('/graphql'); + expect(wss.options.noServer).toBe(true); + }); + + it('should use custom WebSocketServer instance when provided', () => { + const customWss = new WebSocketServer({ + noServer: true, + path: '/subscriptions', + }); + + const options: GqlSubscriptionServiceOptions = { + schema: {} as any, + path: '/graphql', + 'graphql-ws': { + server: customWss, + }, + }; + + const service = new GqlSubscriptionService(options, mockHttpServer); + + expect((service as any).wss).toBe(customWss); + expect((service as any).wss.options.path).toBe('/subscriptions'); + }); + + it('should throw an error if custom server is not instantiated with noServer: true', () => { + const invalidWss = { + options: { + noServer: false, + path: '/custom', + }, + } as any; + + const options: GqlSubscriptionServiceOptions = { + schema: {} as any, + path: '/graphql', + 'graphql-ws': { + server: invalidWss, + }, + }; + + expect(() => new GqlSubscriptionService(options, mockHttpServer)).toThrow( + 'Custom WebSocketServer passed to "graphql-ws" must be instantiated with "noServer: true".', + ); + }); + + it('should handle boolean true for graphql-ws (default behavior)', () => { + const options: GqlSubscriptionServiceOptions = { + schema: {} as any, + path: '/graphql', + 'graphql-ws': true, + }; + + const service = new GqlSubscriptionService(options, mockHttpServer); + const wss: WebSocketServer = (service as any).wss; + + expect(wss).toBeInstanceOf(WebSocketServer); + expect(wss.options.path).toBe('/graphql'); + expect(wss.options.noServer).toBe(true); + }); + }); + + describe('initialize & upgrade handling', () => { + it('should not pass server or path to useServer options', () => { + const options: GqlSubscriptionServiceOptions = { + schema: {} as any, + path: '/graphql', + 'graphql-ws': { + path: '/ws', + connectionInitWaitTimeout: 5000, + }, + }; + + new GqlSubscriptionService(options, mockHttpServer); + + const callArgs = mockUseServer.mock.calls[0][0]; + expect(callArgs).not.toHaveProperty('path'); + expect(callArgs).not.toHaveProperty('server'); + expect(callArgs).toHaveProperty('connectionInitWaitTimeout', 5000); + }); + + it('should prioritize custom server path over driver default path', () => { + const customWss = new WebSocketServer({ + noServer: true, + path: '/subscriptions', + }); + + const handleUpgradeSpy = vi.spyOn(customWss, 'handleUpgrade'); + + const options: GqlSubscriptionServiceOptions = { + schema: {} as any, + path: '/graphql', // Driver default + 'graphql-ws': { + server: customWss, // Custom server with path: '/subscriptions' + }, + }; + + new GqlSubscriptionService(options, mockHttpServer); + const upgradeHandler = mockHttpServer.on.mock.calls.find( + (call: any[]) => call[0] === 'upgrade', + )[1]; + + // 1. Request to custom server path '/subscriptions' should be handled + const mockReqValid = { + url: '/subscriptions', + headers: { + 'sec-websocket-protocol': 'graphql-transport-ws', + 'sec-websocket-key': 'dGhlIHNhbXBsZSBub25jZQ==', + 'sec-websocket-version': '13', + upgrade: 'websocket', + connection: 'Upgrade', + }, + method: 'GET', + }; + const mockSocket = createMockSocket(); + const mockHead = Buffer.alloc(0); + + upgradeHandler(mockReqValid, mockSocket, mockHead); + expect(handleUpgradeSpy).toHaveBeenCalledWith( + mockReqValid, + mockSocket, + mockHead, + expect.any(Function), + ); + + handleUpgradeSpy.mockClear(); + + // 2. Request to driver path '/graphql' should NOT be handled because custom server's path is '/subscriptions' + const mockReqInvalid = { + url: '/graphql', + headers: { + 'sec-websocket-protocol': 'graphql-transport-ws', + 'sec-websocket-key': 'dGhlIHNhbXBsZSBub25jZQ==', + 'sec-websocket-version': '13', + upgrade: 'websocket', + connection: 'Upgrade', + }, + method: 'GET', + }; + + upgradeHandler(mockReqInvalid, createMockSocket(), mockHead); + expect(handleUpgradeSpy).not.toHaveBeenCalled(); + }); + + it('should use explicit graphql-ws path when custom server has no internal path', () => { + const customWss = new WebSocketServer({ + noServer: true, + }); + + const handleUpgradeSpy = vi.spyOn(customWss, 'handleUpgrade'); + + const options: GqlSubscriptionServiceOptions = { + schema: {} as any, + path: '/graphql', + 'graphql-ws': { + server: customWss, + path: '/explicit-path', + }, + }; + + new GqlSubscriptionService(options, mockHttpServer); + const upgradeHandler = mockHttpServer.on.mock.calls.find( + (call: any[]) => call[0] === 'upgrade', + )[1]; + + const mockReq = { + url: '/explicit-path', + headers: { + 'sec-websocket-protocol': 'graphql-transport-ws', + 'sec-websocket-key': 'dGhlIHNhbXBsZSBub25jZQ==', + 'sec-websocket-version': '13', + upgrade: 'websocket', + connection: 'Upgrade', + }, + method: 'GET', + }; + const mockSocket = createMockSocket(); + const mockHead = Buffer.alloc(0); + + upgradeHandler(mockReq, mockSocket, mockHead); + expect(handleUpgradeSpy).toHaveBeenCalledWith( + mockReq, + mockSocket, + mockHead, + expect.any(Function), + ); + }); + + it('should fail closed and not handle upgrade if no path resolves', () => { + const customWss = new WebSocketServer({ + noServer: true, + // No path configured on custom wss + }); + + const handleUpgradeSpy = vi.spyOn(customWss, 'handleUpgrade'); + + const options: GqlSubscriptionServiceOptions = { + schema: {} as any, + path: undefined, // No path on driver + 'graphql-ws': { + server: customWss, + }, + }; + + new GqlSubscriptionService(options, mockHttpServer); + const upgradeHandler = mockHttpServer.on.mock.calls.find( + (call: any[]) => call[0] === 'upgrade', + )[1]; + + const mockReq = { + url: '/any-random-url', + headers: { 'sec-websocket-protocol': 'graphql-transport-ws' }, + }; + + upgradeHandler(mockReq, {}, {}); + // Should fail closed: not handle random requests + expect(handleUpgradeSpy).not.toHaveBeenCalled(); + }); + + it('should hand upgrades with another subprotocol to the server to reject', () => { + const options: GqlSubscriptionServiceOptions = { + schema: {} as any, + path: '/graphql', + 'graphql-ws': true, + }; + + const service = new GqlSubscriptionService(options, mockHttpServer); + const handleUpgradeSpy = vi.spyOn((service as any).wss, 'handleUpgrade'); + + const upgradeHandler = mockHttpServer.on.mock.calls.find( + (call: any[]) => call[0] === 'upgrade', + )[1]; + + const mockReq = { + url: '/graphql', + headers: { 'sec-websocket-protocol': 'other-protocol' }, + }; + + upgradeHandler(mockReq, createMockSocket(), Buffer.alloc(0)); + expect(handleUpgradeSpy).toHaveBeenCalled(); + }); + }); + + describe('stop', () => { + it('should dispose graphql-ws', async () => { + const options: GqlSubscriptionServiceOptions = { + schema: {} as any, + path: '/graphql', + 'graphql-ws': true, + }; + + const service = new GqlSubscriptionService(options, mockHttpServer); + + await service.stop(); + + expect((service as any).wsGqlDisposable.dispose).toHaveBeenCalled(); + }); + }); +});