Skip to content

Commit

Permalink
Fixed #276 -- Ensured 500 response when app sends malformed headers.
Browse files Browse the repository at this point in the history
  • Loading branch information
carltongibson committed Nov 13, 2019
1 parent 7032f8e commit cad920e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
7 changes: 6 additions & 1 deletion daphne/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,12 @@ async def handle_reply(self, protocol, message):
"disconnected", None
):
return
self.check_headers_type(message)
try:
self.check_headers_type(message)
except ValueError as e:
# Ensure to send SOME reply.
protocol.basic_error(500, b"Server Error", "Server Error")
raise
# Let the protocol handle it
protocol.handle_reply(message)

Expand Down
8 changes: 6 additions & 2 deletions tests/http_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,16 @@ def run_daphne_http(
# Return scope, messages, response
return test_app.get_received() + (response,)

def run_daphne_raw(self, data, timeout=1):
def run_daphne_raw(self, data, *, responses=None, timeout=1):
"""
Runs daphne and sends it the given raw bytestring over a socket. Returns what it sends back.
Runs Daphne and sends it the given raw bytestring over a socket.
Accepts list of response messages the application will reply with.
Returns what Daphne sends back.
"""
assert isinstance(data, bytes)
with DaphneTestingInstance() as test_app:
if responses is not None:
test_app.add_send_messages(responses)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Expand Down
19 changes: 19 additions & 0 deletions tests/test_http_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from hypothesis import given, settings

import http_strategies
from daphne.testing import TestApplication
from http_base import DaphneTestCase


Expand Down Expand Up @@ -169,3 +170,21 @@ def test_headers_type(self):
str(context.exception),
"Header value 'True' expected to be `bytes`, but got `<class 'bool'>`",
)

def test_headers_type_raw(self):
"""
Daphne returns a 500 error response if the application sends invalid
headers.
"""
response = self.run_daphne_raw(
b"GET / HTTP/1.0\r\n\r\n",
responses=[
{
"type": "http.response.start",
"status": 200,
"headers": [["foo", b"bar"]],
},
{"type": "http.response.body", "body": b""},
],
)
self.assertTrue(response.startswith(b"HTTP/1.0 500 Internal Server Error"))

0 comments on commit cad920e

Please sign in to comment.