Skip to content
Myr

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 ---------

authored by Jon Church · committed by GitHub · parent ee40a88 · Browse files · 4 files+141 added−112 removed
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

4 files+141 added−112 removed

modified:lib/response.js+19 added-9 removed
13 unmodified lines
1415var Buffer = require('safe-buffer').Buffer16var contentDisposition = require('content-disposition');17var createError = require('http-errors')18var deprecate = require('depd')('express');18var encodeUrl = require('encodeurl');19var escapeHtml = require('escape-html');20var http = require('http');21var onFinished = require('on-finished');
33 unmodified lines
5556var schemaAndHostRegExp = /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)?\/\/[^\\\/\?]+/;5758/**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 */7071res.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 }8081 this.statusCode = code;82 return this;83};84
106 unmodified lines
191 }192 }193194 // freshness185 if (req.fresh) this.statusCode = 304;195 if (req.fresh) this.status(304);196197 // strip irrelevant headers198 if (204 === this.statusCode || 304 === this.statusCode) {199 this.removeHeader('Content-Type');
123 unmodified lines
323324res.sendStatus = function sendStatus(statusCode) {325 var body = statuses.message[statusCode] || String(statusCode)326317 this.statusCode = statusCode;327 this.status(statusCode);328 this.type('txt');329330 return this.send(body);331};
524 unmodified lines
856 }857 });858859 // Respond850 this.statusCode = status;860 this.status(status);861 this.set('Content-Length', Buffer.byteLength(body));862863 if (this.req.method === 'HEAD') {864 this.end();
187 unmodified lines
modified:test/res.sendStatus.js+12 added
modified:test/res.status.js+103 added-103 removed
1'use strict'2const express = require('../.');3const request = require('supertest');43var express = require('../')4var request = require('supertest')56var isIoJs = process.release7 ? process.release.name === 'io.js'8 : ['v1.', 'v2.', 'v3.'].indexOf(process.version.slice(0, 3)) !== -195describe('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()720 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();1024 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 });1436 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 });1920 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()2425 app.use(function (req, res) {41 res.status(null).end()26 res.status(101).end()27 })2829 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 })3356 describe('when "code" is 201', function () {34 it('should set the response status code to 201', function (done) {35 var app = express()3637 app.use(function (req, res) {
3 unmodified lines
41 request(app)42 .get('/')43 .expect(201, done)44 })68 })4570 describe('when "code" is 302', function () {46 it('should set the response status code to 302', function (done) {47 var app = express()4849 app.use(function (req, res) {
3 unmodified lines
53 request(app)54 .get('/')55 .expect(302, done)56 })82 })5784 describe('when "code" is 403', function () {58 it('should set the response status code to 403', function (done) {59 var app = express()6061 app.use(function (req, res) {
3 unmodified lines
65 request(app)66 .get('/')67 .expect(403, done)68 })96 })6998 describe('when "code" is 501', function () {70 it('should set the response status code to 501', function (done) {71 var app = express()7273 app.use(function (req, res) {
3 unmodified lines
77 request(app)78 .get('/')79 .expect(501, done)80 })110 })81112 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()8485 app.use(function (req, res) {117 res.status('410').end()86 res.status(700).end()87 })8889 request(app)90 .get('/')122 .expect(410, done)91 .expect(700, done)92 })124 })93126 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()9697 app.use(function (req, res) {131 res.status(410.1).end()98 res.status(800).end()99 })100101 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 })105146 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()108109 app.use(function (req, res) {151 res.status(1000).end()110 res.status(900).end()111 })112113 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 })118166 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();122123 app.use(function (req, res) {171 res.status(99).end()172 })124 res.status(99).end();125 });126127 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 });131186 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();134135 app.use(function (req, res) {191 res.status(-401).end()192 })136 res.status(1000).end();137 });138139 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 });143144 it('should raise error for non-integer status codes', function (done) {145 var app = express();146147 app.use(function (req, res) {148 res.status(200.1).end();149 });150151 request(app)152 .get('/')153 .expect(500, /Invalid status code/, done);154 });155156 it('should raise error for undefined status code', function (done) {157 var app = express();158159 app.use(function (req, res) {160 res.status(undefined).end();161 });162163 request(app)164 .get('/')165 .expect(500, /Invalid status code/, done);166 });167168 it('should raise error for null status code', function (done) {169 var app = express();170171 app.use(function (req, res) {172 res.status(null).end();173 });174175 request(app)176 .get('/')177 .expect(500, /Invalid status code/, done);178 });179180 it('should raise error for string status code', function (done) {181 var app = express();182183 app.use(function (req, res) {184 res.status("200").end();185 });186187 request(app)188 .get('/')189 .expect(500, /Invalid status code/, done);190 });191192 it('should raise error for NaN status code', function (done) {193 var app = express();194195 app.use(function (req, res) {196 res.status(NaN).end();197 });198199 request(app)200 .get('/')201 .expect(500, /Invalid status code/, done);202 });203 });204 });205});206
modified:History.md+7 added
1unreleased2=========================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 inputs785.0.0-beta.3 / 2024-03-259=========================1011This incorporates all changes after 4.19.1 up to 4.19.2.
3780 unmodified lines