Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: verify request socket before access attributes #3420

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 9 additions & 3 deletions lib/request.js
Expand Up @@ -102,7 +102,9 @@ function buildRequestWithTrustProxy (R, trustProxy) {
if (this.headers['x-forwarded-proto']) {
return getLastEntryInMultiHeaderValue(this.headers['x-forwarded-proto'])
}
return this.socket.encrypted ? 'https' : 'http'
if (this.socket) {
return this.socket.encrypted ? 'https' : 'http'
}
}
}
})
Expand Down Expand Up @@ -158,7 +160,9 @@ Object.defineProperties(Request.prototype, {
},
ip: {
get () {
return this.socket.remoteAddress
if (this.socket) {
return this.socket.remoteAddress
}
}
},
hostname: {
Expand All @@ -168,7 +172,9 @@ Object.defineProperties(Request.prototype, {
},
protocol: {
get () {
return this.socket.encrypted ? 'https' : 'http'
if (this.socket) {
return this.socket.encrypted ? 'https' : 'http'
}
}
},
headers: {
Expand Down
47 changes: 47 additions & 0 deletions test/internals/request.test.js
Expand Up @@ -213,3 +213,50 @@ test('Request with trust proxy - plain', t => {
const request = new TpRequest('id', 'params', req, 'query', 'log')
t.same(request.protocol, 'http')
})

test('Request with undefined socket', t => {
t.plan(15)
const headers = {
host: 'hostname'
}
const req = {
method: 'GET',
url: '/',
socket: undefined,
headers
}
const request = new Request('id', 'params', req, 'query', 'log')
t.type(request, Request)
t.equal(request.id, 'id')
t.equal(request.params, 'params')
t.same(request.raw, req)
t.equal(request.query, 'query')
t.equal(request.headers, headers)
t.equal(request.log, 'log')
t.equal(request.ip, undefined)
t.equal(request.ips, undefined)
t.equal(request.hostname, 'hostname')
t.equal(request.body, null)
t.equal(request.method, 'GET')
t.equal(request.url, '/')
t.equal(request.protocol, undefined)
t.same(request.socket, req.socket)
})

test('Request with trust proxy and undefined socket', t => {
t.plan(1)
const headers = {
'x-forwarded-for': '2.2.2.2, 1.1.1.1',
'x-forwarded-host': 'example.com'
}
const req = {
method: 'GET',
url: '/',
socket: undefined,
headers
}

const TpRequest = Request.buildRequest(Request, true)
const request = new TpRequest('id', 'params', req, 'query', 'log')
t.same(request.protocol, undefined)
})