Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(django): Added SDK logic that honors the X-Forwarded-For header #1037

Merged
merged 5 commits into from
Mar 2, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion sentry_sdk/integrations/django/__init__.py
Original file line number Diff line number Diff line change
@@ -120,7 +120,13 @@ def sentry_patched_wsgi_handler(self, environ, start_response):

bound_old_app = old_app.__get__(self, WSGIHandler)

return SentryWsgiMiddleware(bound_old_app)(environ, start_response)
from django.conf import settings

use_x_forwarded_for = settings.USE_X_FORWARDED_HOST

return SentryWsgiMiddleware(bound_old_app, use_x_forwarded_for)(
environ, start_response
)

WSGIHandler.__call__ = sentry_patched_wsgi_handler

35 changes: 22 additions & 13 deletions sentry_sdk/integrations/wsgi.py
Original file line number Diff line number Diff line change
@@ -54,10 +54,16 @@ def wsgi_decoding_dance(s, charset="utf-8", errors="replace"):
return s.encode("latin1").decode(charset, errors)


def get_host(environ):
# type: (Dict[str, str]) -> str
def get_host(environ, use_x_forwarded_for=False):
# type: (Dict[str, str], bool) -> str
"""Return the host for the given WSGI environment. Yanked from Werkzeug."""
if environ.get("HTTP_HOST"):
if use_x_forwarded_for and "HTTP_X_FORWARDED_HOST" in environ:
rv = environ["HTTP_X_FORWARDED_HOST"]
if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"):
rv = rv[:-3]
elif environ["wsgi.url_scheme"] == "https" and rv.endswith(":443"):
rv = rv[:-4]
elif environ.get("HTTP_HOST"):
rv = environ["HTTP_HOST"]
if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"):
rv = rv[:-3]
@@ -77,23 +83,24 @@ def get_host(environ):
return rv


def get_request_url(environ):
# type: (Dict[str, str]) -> str
def get_request_url(environ, use_x_forwarded_for=False):
# type: (Dict[str, str], bool) -> str
"""Return the absolute URL without query string for the given WSGI
environment."""
return "%s://%s/%s" % (
environ.get("wsgi.url_scheme"),
get_host(environ),
get_host(environ, use_x_forwarded_for),
wsgi_decoding_dance(environ.get("PATH_INFO") or "").lstrip("/"),
)


class SentryWsgiMiddleware(object):
__slots__ = ("app",)
__slots__ = ("app", "use_x_forwarded_for")

def __init__(self, app):
# type: (Callable[[Dict[str, str], Callable[..., Any]], Any]) -> None
def __init__(self, app, use_x_forwarded_for=False):
# type: (Callable[[Dict[str, str], Callable[..., Any]], Any], bool) -> None
self.app = app
self.use_x_forwarded_for = use_x_forwarded_for

def __call__(self, environ, start_response):
# type: (Dict[str, str], Callable[..., Any]) -> _ScopedResponse
@@ -110,7 +117,9 @@ def __call__(self, environ, start_response):
scope.clear_breadcrumbs()
scope._name = "wsgi"
scope.add_event_processor(
_make_wsgi_event_processor(environ)
_make_wsgi_event_processor(
environ, self.use_x_forwarded_for
)
)

transaction = Transaction.continue_from_environ(
@@ -269,8 +278,8 @@ def close(self):
reraise(*_capture_exception(self._hub))


def _make_wsgi_event_processor(environ):
# type: (Dict[str, str]) -> EventProcessor
def _make_wsgi_event_processor(environ, use_x_forwarded_for):
# type: (Dict[str, str], bool) -> EventProcessor
# It's a bit unfortunate that we have to extract and parse the request data
# from the environ so eagerly, but there are a few good reasons for this.
#
@@ -284,7 +293,7 @@ def _make_wsgi_event_processor(environ):
# https://github.com/unbit/uwsgi/issues/1950

client_ip = get_client_ip(environ)
request_url = get_request_url(environ)
request_url = get_request_url(environ, use_x_forwarded_for)
query_string = environ.get("QUERY_STRING")
method = environ.get("REQUEST_METHOD")
env = dict(_get_environ(environ))
44 changes: 44 additions & 0 deletions tests/integrations/django/test_basic.py
Original file line number Diff line number Diff line change
@@ -40,6 +40,50 @@ def test_view_exceptions(sentry_init, client, capture_exceptions, capture_events
assert event["exception"]["values"][0]["mechanism"]["type"] == "django"


def test_ensures_x_forwarded_header_is_honored_in_sdk_when_enabled_in_django(
sentry_init, client, capture_exceptions, capture_events
):
"""
Test that ensures if django settings.USE_X_FORWARDED_HOST is set to True
then the SDK sets the request url to the `HTTP_X_FORWARDED_FOR`
"""
from django.conf import settings

settings.USE_X_FORWARDED_HOST = True
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of importing settings I suggest using the settings pytest fixture, then your change is automatically reverted at the end of the test

def test_foo(settings):
    settings.USE_X_FORWARDED_HOST = True
    ...


sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)
exceptions = capture_exceptions()
events = capture_events()
client.get(reverse("view_exc"), headers={"X_FORWARDED_HOST": "example.com"})

(error,) = exceptions
assert isinstance(error, ZeroDivisionError)

(event,) = events
assert event["request"]["url"] == "http://example.com/view-exc"

settings.USE_X_FORWARDED_HOST = False


def test_ensures_x_forwarded_header_is_not_honored_when_unenabled_in_django(
sentry_init, client, capture_exceptions, capture_events
):
"""
Test that ensures if django settings.USE_X_FORWARDED_HOST is set to False
then the SDK sets the request url to the `HTTP_POST`
"""
sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)
exceptions = capture_exceptions()
events = capture_events()
client.get(reverse("view_exc"), headers={"X_FORWARDED_HOST": "example.com"})

(error,) = exceptions
assert isinstance(error, ZeroDivisionError)

(event,) = events
assert event["request"]["url"] == "http://localhost/view-exc"


def test_middleware_exceptions(sentry_init, client, capture_exceptions):
sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)
exceptions = capture_exceptions()