Skip to content

Commit

Permalink
fix: more informative error message to tell that the server doesn't m…
Browse files Browse the repository at this point in the history
…atch http/1.1 protocol (#2055)

* fix: http2 error message

* test: fix

* test: fix
  • Loading branch information
songkeys authored May 3, 2023
1 parent c1c8d83 commit ab2e0ce
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 5 deletions.
5 changes: 4 additions & 1 deletion lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,10 @@ class Parser {
/* istanbul ignore else: difficult to make a test case for */
if (ptr) {
const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
message = Buffer.from(llhttp.memory.buffer, ptr, len).toString()
message =
'Response does not match the HTTP/1.1 protocol (' +
Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
')'
}
throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))
}
Expand Down
32 changes: 32 additions & 0 deletions test/http2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'use strict'

const { test } = require('tap')
const { Client, errors } = require('..')
const { createSecureServer } = require('http2')
const pem = require('https-pem')

test('throw http2 not supported error', (t) => {
t.plan(1)

const server = createSecureServer({ key: pem.key, cert: pem.cert }, (req, res) => {
res.stream.respond({ 'content-type': 'text/plain' })
res.stream.end('hello')
}).on('unknownProtocol', (socket) => {
// continue sending data in http2 to our http1.1 client to trigger error
socket.write('PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n')
})
t.teardown(server.close.bind(server))

server.listen(0, () => {
const client = new Client(`https://localhost:${server.address().port}`, {
tls: {
rejectUnauthorized: false
}
})
t.teardown(client.close.bind(client))

client.request({ path: '/', method: 'GET' }, (err, data) => {
t.type(err, errors.HTTPParserError)
})
})
})
7 changes: 3 additions & 4 deletions test/parser-issues.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const net = require('net')
const { test } = require('tap')
const { Client } = require('..')
const { Client, errors } = require('..')

test('https://github.com/mcollina/undici/issues/268', (t) => {
t.plan(2)
Expand Down Expand Up @@ -40,7 +40,7 @@ test('https://github.com/mcollina/undici/issues/268', (t) => {
})

test('parser fail', (t) => {
t.plan(3)
t.plan(2)

const server = net.createServer(socket => {
socket.write('HTT/1.1 200 OK\r\n')
Expand All @@ -56,8 +56,7 @@ test('parser fail', (t) => {
path: '/'
}, (err, data) => {
t.ok(err)
t.equal(err.code, 'HPE_INVALID_CONSTANT')
t.equal(err.message, 'Expected HTTP/')
t.type(err, errors.HTTPParserError)
})
})
})
Expand Down

0 comments on commit ab2e0ce

Please sign in to comment.