Skip to content

Commit

Permalink
fix(encoding): Fix double-encoding of HTTP response (#220)
Browse files Browse the repository at this point in the history
ecba3ea added a call to encode
the response body before sending it to the server if the body is
of type str.

This is the correct behavior for python 3, where str represents a
an unencoded string, but is incorrect for python 2. In python 2,
str represents an already-encoded string and unicode represents
an unencoded string.

This is breaking for prometheus monitoring, which is sending already-
encoded bytes to the respond() function. In python 2, those have type
str, so we're trying to re-encode them. This works fine as long as there
are only ASCII characters in the string, but breaks otherwise.

In order to support both python 2 and 3, try to use 'unicode' (as
exists in 2) and if it's absent assign str to unicode.
  • Loading branch information
ezimanyi committed Oct 7, 2019
1 parent 431d5e3 commit 59cbbec
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions spinnaker-monitoring-daemon/spinnaker-monitoring/http_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,13 @@
HTTPServer,
BaseHTTPRequestHandler)
from urllib.request import unquote as urllibUnquote


# The unicode type only exists in python 2; it has been renamed str in python 3
# In order to support python 2 and 3, alias unicode to str if it's not present
try:
unicode
except NameError:
unicode = str

def build_html_document(body, title=None):
"""Produces the HTML document wrapper for a text/html response."""
Expand Down Expand Up @@ -73,7 +79,7 @@ def respond(self, code, headers, body=None):
self.send_header(key, value)
self.end_headers()
if body:
if isinstance(body, str):
if isinstance(body, unicode):
body = body.encode('utf-8')
self.wfile.write(body)

Expand Down

0 comments on commit 59cbbec

Please sign in to comment.