Skip to content

Commit

Permalink
fix: return 431 status code on HTTP header overflow error
Browse files Browse the repository at this point in the history
  • Loading branch information
nflaig committed Jun 27, 2023
1 parent 6e06229 commit 59a7d01
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
5 changes: 5 additions & 0 deletions fastify.js
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,11 @@ function fastify (options) {
errorStatus = http.STATUS_CODES[errorCode]
body = `{"error":"${errorStatus}","message":"Client Timeout","statusCode":408}`
errorLabel = 'timeout'
} else if (err.code === 'HPE_HEADER_OVERFLOW') {
errorCode = '431'
errorStatus = http.STATUS_CODES[errorCode]
body = `{"error":"${errorStatus}","message":"Exceeded maximum allowed HTTP header size","statusCode":431}`
errorLabel = 'header_overflow'
} else {
errorCode = '400'
errorStatus = http.STATUS_CODES[errorCode]
Expand Down
65 changes: 65 additions & 0 deletions test/header-overflow.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
'use strict'

const t = require('tap')
const test = t.test
const Fastify = require('..')
const sget = require('simple-get').concat

const maxHeaderSize = 1024

test('Should return 431 if request header fields are too large', t => {
t.plan(3)

const fastify = Fastify({ http: { maxHeaderSize } })
fastify.route({
method: 'GET',
url: '/',
handler: (_req, reply) => {
reply.send({ hello: 'world' })
}
})

fastify.listen({ port: 0 }, function (err) {
t.error(err)

sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port,
headers: {
'Large-Header': 'a'.repeat(maxHeaderSize)
}
}, (err, res) => {
t.error(err)
t.equal(res.statusCode, 431)
})
})

t.teardown(() => fastify.close())
})

test('Should return 431 if URI is too long', t => {
t.plan(3)

const fastify = Fastify({ http: { maxHeaderSize } })
fastify.route({
method: 'GET',
url: '/',
handler: (_req, reply) => {
reply.send({ hello: 'world' })
}
})

fastify.listen({ port: 0 }, function (err) {
t.error(err)

sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port + `/${'a'.repeat(maxHeaderSize)}`
}, (err, res) => {
t.error(err)
t.equal(res.statusCode, 431)
})
})

t.teardown(() => fastify.close())
})

0 comments on commit 59a7d01

Please sign in to comment.