|
3 | 3 | const { test, before } = require('node:test') |
4 | 4 | const fastify = require('..') |
5 | 5 | const helper = require('./helper') |
| 6 | +const Request = require('../lib/request') |
| 7 | +const buildRequest = Request.buildRequest |
6 | 8 |
|
7 | 9 | const fetchForwardedRequest = async (fastifyServer, forHeader, path, protoHeader) => { |
8 | 10 | const headers = { |
@@ -219,3 +221,54 @@ test('trust proxy reads forwarded headers from trusted connections', async t => |
219 | 221 | } |
220 | 222 | }) |
221 | 223 | }) |
| 224 | + |
| 225 | +test('trust proxy with number and undefined socket remoteAddress', t => { |
| 226 | + t.plan(3) |
| 227 | + |
| 228 | + // Test case for issue #6606: trustProxy: 1 with undefined/null socket.remoteAddress |
| 229 | + // This simulates IISNode on Windows where socket.remoteAddress may be undefined |
| 230 | + const headers = { |
| 231 | + 'x-forwarded-for': '2.2.2.2, 1.1.1.1', |
| 232 | + 'x-forwarded-host': 'fastify.test', |
| 233 | + 'x-forwarded-proto': 'https' |
| 234 | + } |
| 235 | + // socket must exist but remoteAddress can be undefined |
| 236 | + // This is what happens in IISNode with enableXFF="true" |
| 237 | + const req = { |
| 238 | + method: 'GET', |
| 239 | + url: '/', |
| 240 | + socket: { remoteAddress: undefined }, |
| 241 | + headers |
| 242 | + } |
| 243 | + |
| 244 | + const TpRequest = buildRequest(Request, 1) |
| 245 | + const request = new TpRequest('id', 'params', req, 'query', 'log') |
| 246 | + // Even with undefined socket.remoteAddress, req.ip should be populated from X-Forwarded-For |
| 247 | + t.assert.ok(request.ip, 'ip is defined') |
| 248 | + // With trustProxy: 1, we trust 1 hop from socket. Since socket.remoteAddress is undefined, |
| 249 | + // the hop count check should skip it and we get 1.1.1.1 (the first trusted address from X-Forwarded-For) |
| 250 | + t.assert.strictEqual(request.ip, '1.1.1.1', 'gets ip from x-forwarded-for') |
| 251 | + // The host should also work correctly |
| 252 | + t.assert.strictEqual(request.host, 'fastify.test', 'gets host from x-forwarded-host') |
| 253 | +}) |
| 254 | + |
| 255 | +test('trust proxy with number and null socket remoteAddress', t => { |
| 256 | + t.plan(2) |
| 257 | + |
| 258 | + // Test case for trustProxy: 1 with null socket.remoteAddress |
| 259 | + const headers = { |
| 260 | + 'x-forwarded-for': '2.2.2.2, 1.1.1.1', |
| 261 | + 'x-forwarded-host': 'fastify.test' |
| 262 | + } |
| 263 | + const req = { |
| 264 | + method: 'GET', |
| 265 | + url: '/', |
| 266 | + socket: { remoteAddress: null }, |
| 267 | + headers |
| 268 | + } |
| 269 | + |
| 270 | + const TpRequest = buildRequest(Request, 1) |
| 271 | + const request = new TpRequest('id', 'params', req, 'query', 'log') |
| 272 | + t.assert.ok(request.ip, 'ip is defined') |
| 273 | + t.assert.strictEqual(request.ip, '1.1.1.1', 'gets ip from x-forwarded-for') |
| 274 | +}) |
0 commit comments