|
| 1 | +import http from 'http'; |
| 2 | +import { NotificationServer } from '../websocket-server.js'; |
| 3 | +import WebSocket, { Server as WS } from 'ws'; |
| 4 | + |
| 5 | +// Helper to create a mock HTTP server |
| 6 | +function createHttpServer(): http.Server { |
| 7 | + const server = http.createServer(); |
| 8 | + server.listen(0); |
| 9 | + return server; |
| 10 | +} |
| 11 | + |
| 12 | +describe('NotificationServer WebSocket authentication', () => { |
| 13 | + const originalEnv = process.env; |
| 14 | + |
| 15 | + beforeEach(() => { |
| 16 | + jest.resetModules(); |
| 17 | + process.env = { ...originalEnv, GEMINI_API_KEY: 'test-secret-key' }; |
| 18 | + }); |
| 19 | + |
| 20 | + afterAll(() => { |
| 21 | + process.env = originalEnv; |
| 22 | + }); |
| 23 | + |
| 24 | + test('rejects connection without Authorization header', (done) => { |
| 25 | + const httpServer = createHttpServer(); |
| 26 | + const ns = new NotificationServer(httpServer, { allowedOrigins: [] }); |
| 27 | + const wsPort = (httpServer.address() as any).port; |
| 28 | + const ws = new WebSocket(`ws://localhost:${wsPort}?userId=user123`); |
| 29 | + ws.on('error', (err) => { |
| 30 | + // Server should close with code 4000 (custom close) -> ws error |
| 31 | + expect(err).toBeDefined(); |
| 32 | + httpServer.close(); |
| 33 | + done(); |
| 34 | + }); |
| 35 | + ws.on('open', () => { |
| 36 | + // Should not open |
| 37 | + }); |
| 38 | + }); |
| 39 | + |
| 40 | + test('accepts connection with correct Bearer token', (done) => { |
| 41 | + const httpServer = createHttpServer(); |
| 42 | + const ns = new NotificationServer(httpServer, { allowedOrigins: [] }); |
| 43 | + const wsPort = (httpServer.address() as any).port; |
| 44 | + const ws = new WebSocket(`ws://localhost:${wsPort}?userId=user123`, { |
| 45 | + headers: { Authorization: 'Bearer test-secret-key' }, |
| 46 | + }); |
| 47 | + ws.on('open', () => { |
| 48 | + // Connection succeeded |
| 49 | + ws.close(); |
| 50 | + httpServer.close(); |
| 51 | + done(); |
| 52 | + }); |
| 53 | + ws.on('error', (err) => { |
| 54 | + // Should not error |
| 55 | + httpServer.close(); |
| 56 | + done(err); |
| 57 | + }); |
| 58 | + }); |
| 59 | +}); |
0 commit comments