Skip to content

Commit

Permalink
Fixes crash when using a non-standard error code (#2184)
Browse files Browse the repository at this point in the history
* Fixes crash when using a non-standard error code

Updates how we validate reply status code.
Now allowing only numbers in range between 100 and 600

* adds provided status code in FST_ERR_BAD_STATUS_CODE error
  • Loading branch information
leorossi committed Apr 8, 2020
1 parent 08e0a04 commit 8ba959d
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 5 deletions.
2 changes: 1 addition & 1 deletion lib/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ createError('FST_ERR_REP_ALREADY_SENT', 'Reply was already sent.')
createError('FST_ERR_REP_SENT_VALUE', 'The only possible value for reply.sent is true.')
createError('FST_ERR_SEND_INSIDE_ONERR', 'You cannot use `send` inside the `onError` hook')
createError('FST_ERR_SEND_UNDEFINED_ERR', 'Undefined error has occured')
createError('FST_ERR_BAD_STATUS_CODE', 'Called reply with malformed status code')
createError('FST_ERR_BAD_STATUS_CODE', 'Called reply with an invalid status code: %s')

/**
* schemas
Expand Down
7 changes: 4 additions & 3 deletions lib/reply.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,11 +198,12 @@ Reply.prototype.headers = function (headers) {
}

Reply.prototype.code = function (code) {
if (statusCodes[code] === undefined) {
throw new FST_ERR_BAD_STATUS_CODE()
const intValue = parseInt(code)
if (isNaN(intValue) || intValue < 100 || intValue > 600) {
throw new FST_ERR_BAD_STATUS_CODE(String(code))
}

this.res.statusCode = code
this.res.statusCode = intValue
this[kReplyHasStatusCode] = true
return this
}
Expand Down
2 changes: 1 addition & 1 deletion test/reply-error.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ invalidErrorCodes.forEach((invalidCode) => {
} catch (err) {
t.is(err.name, 'FastifyError [FST_ERR_BAD_STATUS_CODE]')
t.is(err.code, 'FST_ERR_BAD_STATUS_CODE')
t.is(err.message, 'FST_ERR_BAD_STATUS_CODE: Called reply with malformed status code')
t.is(err.message, `FST_ERR_BAD_STATUS_CODE: Called reply with an invalid status code: ${String(invalidCode)}`)
}
})
fastify.inject({
Expand Down

0 comments on commit 8ba959d

Please sign in to comment.