0

I have a Node server which can reject requests based upon security headers. If I reject a request, is it necessary to use blank data and end handlers to read the request body or can I just send the response, a 401, and leave the request unread?

It seems that if I leave the response unread then I get occasional "The existing connection has been forcibly closed by the remote host" errors at the client. Adding code to wait for the request body to be read does seem to fix the issue but then again, adding delays at various points in the server code also seems to have a beneficial effect. It can be hard to tell with an intermittent fault.

The coffeescript code that seems to fix the issue is:

 @res.writeHead status, message, @headers
 @req.on 'data', (d) ->
 # wait for request to be completely read before ending response stream
 @req.on 'end', => @res.end()

The empty data handler is required to get the end event and the end event is possibly required to avoid the error at the client. Given that the request body might be megabytes is this the best way to send a 401 response or is there a better way that doesn't require reading the whole request.

Andy Bisson
  • 580
  • 5
  • 19

1 Answers1

0

Further investigation has revealed a large can of worms. It would seem that there is no properly implemented method to kill the request stream without potentially causing an error at the client.

This question covers the difficulty of terminating a request early without causing an error: How to cancel HTTP upload from data events?

I have decided to abort very long requests and to allow shorter ones to complete. In my application this should only normally abort requests that are probably a DOS attack (legitimate requests are usually short)

Community
  • 1
  • 1
Andy Bisson
  • 580
  • 5
  • 19