Throw on invalid status codes (#4212)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* check status code is integer, or string integer, in range * fix tests, update jsdoc comment for res.status * throw if number is string * narrow valid range to between 1xx and 5xx * disambiguate the error message * update skipped tests, remove invalid string test * remove invalid float test * fixup! remove invalid float test * fix invalid range tests error assertions * remove unused deprecate function * add test to assert on 200.00 coming through as 200 this is the behavior of node's underlying HTTP module * revert back to throwing only on > 999 and < 100 * update implementation for > 999 * add test for 700 status code * update history with change * update jsdoc * clarify jsdoc comment * one more round of jsdoc * update 501 test * add invalid status code test for res.sendStatus * add test describe block for valid range * fixup! add test describe block for valid range * reduce the describe nesting * switch to testing status 100, to avoid 100-continue behavior * fix 900 test * stringify code in thrown RangeError message * remove accidentally duplicated res.status method * fix error range message Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com> * update sendStatus invalid code test to use sendStatus ---------
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>
Diff stats
4 files+141 added−112 removed
- tests:+115 added−103 removed
- other:+26 added−9 removed
Provenance
- Commit
723b545- Tree
1d19dfc- Author
Jon Church <me@jonchurch.com>- Committer
GitHub <noreply@github.com>- Parent
ee40a88
4 files changed+141 added−112 removed
modified:lib/response.js+19 added-9 removed
13 unmodified lines14 15 var Buffer = require('safe-buffer').Buffer16 var contentDisposition = require('content-disposition');17 var createError = require('http-errors')18-var deprecate = require('depd')('express');18 var encodeUrl = require('encodeurl');19 var escapeHtml = require('escape-html');20 var http = require('http');21 var onFinished = require('on-finished');33 unmodified lines55 56 var schemaAndHostRegExp = /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)?\/\/[^\\\/\?]+/;57 58 /**60- * Set status `code`.59+ * Set the HTTP status code for the response.60 *62- * @param {Number} code63- * @return {ServerResponse}61+ * Expects an integer value between 100 and 999 inclusive.62+ * Throws an error if the provided status code is not an integer or if it's outside the allowable range.63+ *64+ * @param {number} code - The HTTP status code to set.65+ * @return {ServerResponse} - Returns itself for chaining methods.66+ * @throws {TypeError} If `code` is not an integer.67+ * @throws {RangeError} If `code` is outside the range 100 to 999.68 * @public69 */70 71 res.status = function status(code) {68- if ((typeof code === 'string' || Math.floor(code) !== code) && code > 99 && code < 1000) {69- deprecate('res.status(' + JSON.stringify(code) + '): use res.status(' + Math.floor(code) + ') instead')72+ // Check if the status code is not an integer73+ if (!Number.isInteger(code)) {74+ throw new TypeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be an integer.`);75 }76+ // Check if the status code is outside of Node's valid range77+ if (code < 100 || code > 999) {78+ throw new RangeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be greater than 99 and less than 1000.`);79+ }80+81 this.statusCode = code;82 return this;83 };84 106 unmodified lines191 }192 }193 194 // freshness185- if (req.fresh) this.statusCode = 304;195+ if (req.fresh) this.status(304);196 197 // strip irrelevant headers198 if (204 === this.statusCode || 304 === this.statusCode) {199 this.removeHeader('Content-Type');123 unmodified lines323 324 res.sendStatus = function sendStatus(statusCode) {325 var body = statuses.message[statusCode] || String(statusCode)326 317- this.statusCode = statusCode;327+ this.status(statusCode);328 this.type('txt');329 330 return this.send(body);331 };524 unmodified lines856 }857 });858 859 // Respond850- this.statusCode = status;860+ this.status(status);861 this.set('Content-Length', Buffer.byteLength(body));862 863 if (this.req.method === 'HEAD') {864 this.end();187 unmodified linesmodified:test/res.sendStatus.js+12 added
26 unmodified lines27282930313233343536373839404142434426 unmodified lines request(app) .get('/') .expect(599, '599', done); })
it('should raise error for invalid status code', function (done) { var app = express()
app.use(function (req, res) { res.sendStatus(undefined).end() })
request(app) .get('/') .expect(500, /TypeError: Invalid status code/, done) }) })})modified:test/res.status.js+103 added-103 removed
1 'use strict'2+const express = require('../.');3+const request = require('supertest');4 3-var express = require('../')4-var request = require('supertest')5-6-var isIoJs = process.release7- ? process.release.name === 'io.js'8- : ['v1.', 'v2.', 'v3.'].indexOf(process.version.slice(0, 3)) !== -19-5 describe('res', function () {6 describe('.status(code)', function () {12- // This test fails in node 4.0.013- // https://github.com/expressjs/express/pull/2237/checks14- // As this will all be removed when https://github.com/expressjs/express/pull/421215- // lands I am skipping for now and we can delete with that PR16- describe.skip('when "code" is undefined', function () {17- it('should raise error for invalid status code', function (done) {18- var app = express()7 20- app.use(function (req, res) {21- res.status(undefined).end()22- })8+ it('should set the status code when valid', function (done) {9+ var app = express();10 24- request(app)25- .get('/')26- .expect(500, /Invalid status code/, function (err) {27- if (isIoJs) {28- done(err ? null : new Error('expected error'))29- } else {30- done(err)31- }32- })33- })34- })11+ app.use(function (req, res) {12+ res.status(200).end();13+ });14 36- describe.skip('when "code" is null', function () {37- it('should raise error for invalid status code', function (done) {15+ request(app)16+ .get('/')17+ .expect(200, done);18+ });19+20+ describe('accept valid ranges', function() {21+ // not testing w/ 100, because that has specific meaning and behavior in Node as Expect: 100-continue22+ it('should set the response status code to 101', function (done) {23 var app = express()24 25 app.use(function (req, res) {41- res.status(null).end()26+ res.status(101).end()27 })28 29 request(app)30 .get('/')46- .expect(500, /Invalid status code/, function (err) {47- if (isIoJs) {48- done(err ? null : new Error('expected error'))49- } else {50- done(err)51- }52- })31+ .expect(101, done)32 })54- })33 56- describe('when "code" is 201', function () {34 it('should set the response status code to 201', function (done) {35 var app = express()36 37 app.use(function (req, res) {3 unmodified lines41 request(app)42 .get('/')43 .expect(201, done)44 })68- })45 70- describe('when "code" is 302', function () {46 it('should set the response status code to 302', function (done) {47 var app = express()48 49 app.use(function (req, res) {3 unmodified lines53 request(app)54 .get('/')55 .expect(302, done)56 })82- })57 84- describe('when "code" is 403', function () {58 it('should set the response status code to 403', function (done) {59 var app = express()60 61 app.use(function (req, res) {3 unmodified lines65 request(app)66 .get('/')67 .expect(403, done)68 })96- })69 98- describe('when "code" is 501', function () {70 it('should set the response status code to 501', function (done) {71 var app = express()72 73 app.use(function (req, res) {3 unmodified lines77 request(app)78 .get('/')79 .expect(501, done)80 })110- })81 112- describe('when "code" is "410"', function () {113- it('should set the response status code to 410', function (done) {82+ it('should set the response status code to 700', function (done) {83 var app = express()84 85 app.use(function (req, res) {117- res.status('410').end()86+ res.status(700).end()87 })88 89 request(app)90 .get('/')122- .expect(410, done)91+ .expect(700, done)92 })124- })93 126- describe.skip('when "code" is 410.1', function () {127- it('should set the response status code to 410', function (done) {94+ it('should set the response status code to 800', function (done) {95 var app = express()96 97 app.use(function (req, res) {131- res.status(410.1).end()98+ res.status(800).end()99 })100 101 request(app)102 .get('/')136- .expect(410, function (err) {137- if (isIoJs) {138- done(err ? null : new Error('expected error'))139- } else {140- done(err)141- }142- })103+ .expect(800, done)104 })144- })105 146- describe.skip('when "code" is 1000', function () {147- it('should raise error for invalid status code', function (done) {106+ it('should set the response status code to 900', function (done) {107 var app = express()108 109 app.use(function (req, res) {151- res.status(1000).end()110+ res.status(900).end()111 })112 113 request(app)114 .get('/')156- .expect(500, /Invalid status code/, function (err) {157- if (isIoJs) {158- done(err ? null : new Error('expected error'))159- } else {160- done(err)161- }162- })115+ .expect(900, done)116 })117 })118 166- describe.skip('when "code" is 99', function () {167- it('should raise error for invalid status code', function (done) {168- var app = express()119+ describe('invalid status codes', function () {120+ it('should raise error for status code below 100', function (done) {121+ var app = express();122 123 app.use(function (req, res) {171- res.status(99).end()172- })124+ res.status(99).end();125+ });126 127 request(app)128 .get('/')176- .expect(500, /Invalid status code/, function (err) {177- if (isIoJs) {178- done(err ? null : new Error('expected error'))179- } else {180- done(err)181- }182- })183- })184- })129+ .expect(500, /Invalid status code/, done);130+ });131 186- describe.skip('when "code" is -401', function () {187- it('should raise error for invalid status code', function (done) {188- var app = express()132+ it('should raise error for status code above 999', function (done) {133+ var app = express();134 135 app.use(function (req, res) {191- res.status(-401).end()192- })136+ res.status(1000).end();137+ });138 139 request(app)140 .get('/')196- .expect(500, /Invalid status code/, function (err) {197- if (isIoJs) {198- done(err ? null : new Error('expected error'))199- } else {200- done(err)201- }202- })203- })204- })205- })206-})141+ .expect(500, /Invalid status code/, done);142+ });143+144+ it('should raise error for non-integer status codes', function (done) {145+ var app = express();146+147+ app.use(function (req, res) {148+ res.status(200.1).end();149+ });150+151+ request(app)152+ .get('/')153+ .expect(500, /Invalid status code/, done);154+ });155+156+ it('should raise error for undefined status code', function (done) {157+ var app = express();158+159+ app.use(function (req, res) {160+ res.status(undefined).end();161+ });162+163+ request(app)164+ .get('/')165+ .expect(500, /Invalid status code/, done);166+ });167+168+ it('should raise error for null status code', function (done) {169+ var app = express();170+171+ app.use(function (req, res) {172+ res.status(null).end();173+ });174+175+ request(app)176+ .get('/')177+ .expect(500, /Invalid status code/, done);178+ });179+180+ it('should raise error for string status code', function (done) {181+ var app = express();182+183+ app.use(function (req, res) {184+ res.status("200").end();185+ });186+187+ request(app)188+ .get('/')189+ .expect(500, /Invalid status code/, done);190+ });191+192+ it('should raise error for NaN status code', function (done) {193+ var app = express();194+195+ app.use(function (req, res) {196+ res.status(NaN).end();197+ });198+199+ request(app)200+ .get('/')201+ .expect(500, /Invalid status code/, done);202+ });203+ });204+ });205+});206+modified:History.md+7 added
1+unreleased2+=========================3+* breaking:4+ * `res.status()` accepts only integers, and input must be greater than 99 and less than 10005+ * will throw a `RangeError: Invalid status code: ${code}. Status code must be greater than 99 and less than 1000.` for inputs outside this range6+ * will throw a `TypeError: Invalid status code: ${code}. Status code must be an integer.` for non integer inputs7+8 5.0.0-beta.3 / 2024-03-259 =========================10 11 This incorporates all changes after 4.19.1 up to 4.19.2.3780 unmodified lines