Skip to content

Don't use request stream since it can only be read once preventing other... - #1380

Closed
stephenmcd wants to merge 1 commit into
encode:masterfrom
kouio:master
Closed

stephenmcd wants to merge 1 commit into
encode:masterfrom
kouio:master

Conversation

@stephenmcd

Copy link
Copy Markdown

... middleware (particularly sentry) from accessing it.

Pretty sure this is the wrong fix, but here it is nonetheless.

As I roughly understand, calling request.read() means that none of the post data is accessible on the original Django request object anymore. This breaks things like sentry which capture the request body in middleware for error reporting. You could easily imagine other stuff it might break too.

If there's a better fix, please disregard this and either way - thanks for the great software!

…her middleware (particularly sentry) from accessing it.
@dcramer

dcramer commented Feb 1, 2014

Copy link
Copy Markdown

I'm not sure there's a good solution to solving capturing bodies of streaming requests, unless you read up to X bytes into a buffer then decided it could be too big to capture.

@lovelydinosaur

Copy link
Copy Markdown
Member

@stephenmcd - There simply isn't a reasonable way to do this - REST framework has to treat incoming request data as a stream, or else risk using too much memory per request for upload type requests. This can only really be resolved if:

  1. REST framework dealt with request parsing & various other mechanics in middleware, and sentry was aware of the request.DATA attribute and would log it along with (or instead of?) request.POST.
  2. Django gets customizable request parsing built in directly, and request.DATA becomes a part of Django's API (again, with Sentry then needing to be updated to deal with that.). See this thread for more information on that, although given the 1.7 alpha there's no possibility of that happening anytime before 1.8 (and no guarantee that it'll be accepted/happen by then either.)

The constraint that sentry won't be able to log stream request bodies, and that REST framework isn't something I see any obvious way around.

@lovelydinosaur

Copy link
Copy Markdown
Member

Actually I guess we could do something like check the request length - for small requests read the body into memory so it can be properly logged, for large requests treat it as a stream.

@stephenmcd

Copy link
Copy Markdown
Author

Thanks Tom - the tradefoff makes sense. I guess in my case checking the length would be ideal. My api request bodies are always small and the data is really useful in sentry.

I feel like every time I add a setting to something I've been defeated in some little way, but do you think it'd be worth adding a setting for defining the length that needs to be reached, and then using streams if that's exceeded? Happy to work on that if you like.

@pySilver

Copy link
Copy Markdown

@stephenmcd, any updates on this issue? That would be great to have an ability to capture request body to sentry. There are lots of cases when one receives strange 500 error from sentry but, without request body it is simply impossible to easily understand what is really causing error.

@stephenmcd

Copy link
Copy Markdown
Author

Not that I know of.

@pySilver

Copy link
Copy Markdown

@tomchristie what if we modify rest_framework.views.APIView#handle_exception a little bit and provide optional request parameter? So developers will be able to handle exceptions & perform any logging from custom EXCEPTION_HANDLER ?

def exception_handler(exc, request=None):
    """
    Returns the response that should be used for any given exception.

    By default we handle the REST framework `APIException`, and also
    Django's builtin `Http404` and `PermissionDenied` exceptions.

    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """
    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['X-Throttle-Wait-Seconds'] = '%d' % exc.wait

        return Response({'detail': exc.detail},
                        status=exc.status_code,
                        headers=headers)

    elif isinstance(exc, Http404):
        return Response({'detail': 'Not found'},
                        status=status.HTTP_404_NOT_FOUND)

    elif isinstance(exc, PermissionDenied):
        return Response({'detail': 'Permission denied'},
                        status=status.HTTP_403_FORBIDDEN)

    # here you can log exception and request.DATA ...

    # Note: Unhandled exceptions will raise a 500 error.
    return None

def handle_exception(self, exc):
        """
        Handle any exception that occurs, by returning an appropriate response,
        or re-raising the error.
        """
        if isinstance(exc, (exceptions.NotAuthenticated,
                            exceptions.AuthenticationFailed)):
            # WWW-Authenticate header for 401 responses, else coerce to 403
            auth_header = self.get_authenticate_header(self.request)

            if auth_header:
                exc.auth_header = auth_header
            else:
                exc.status_code = status.HTTP_403_FORBIDDEN

        response = self.settings.EXCEPTION_HANDLER(exc, request=self.request)

        if response is None:
            raise

        response.exception = True
        return response

@pySilver

Copy link
Copy Markdown

@stephenmcd here is a working example for Raven integration:

First: Monkey patch APIView (until @tomchristie approve idea to provide request to exception handler)

from rest_framework import exceptions, status
from rest_framework.views import APIView


original_handle_exception = APIView.handle_exception


def _handle_exception(self, exc):
    """
    Monkey patch for rest_framework.views.APIView#handle_exception
    that allows to access request object from exception handler
    """
    if isinstance(exc, (exceptions.NotAuthenticated,
                        exceptions.AuthenticationFailed)):
        # WWW-Authenticate header for 401 responses, else coerce to 403
        auth_header = self.get_authenticate_header(self.request)

        if auth_header:
            exc.auth_header = auth_header
        else:
            exc.status_code = status.HTTP_403_FORBIDDEN

    response = self.settings.EXCEPTION_HANDLER(exc, self.request)

    if response is None:
        raise

    response.exception = True
    return response


# apply patch
if APIView.handle_exception != _handle_exception:
    APIView.handle_exception = _handle_exception

and apply custom exception handler (put it in settings.EXCEPTION_HANDLER)

def exception_handler(exc, drf_request=None):
    """
    Replace request.POST with drf_request.DATA so Sentry
    can log request properly.

    @param exc: Exception
    @param drf_request: Request
    @return: None
    """
    response = views.exception_handler(exc)
    if response is None and drf_request is not None \
            and drf_request.method not in ['GET', 'HEAD', 'OPTIONS']:
        request = get_request()
        request.POST = drf_request.DATA

    return response

Then install middleware that allows to get request at any point of time

from django.dispatch import Signal

__doc__ = """
If you want to get a reference to the current HttpRequest:

from core.signals import get_request
http_request = get_request()
"""


class UnauthorizedSignalReceiver(Exception):
    pass


class SingleHandlerSignal(Signal):

    allowed_receiver = 'core.middleware.RequestProvider'

    def __init__(self, providing_args=None):
        super(SingleHandlerSignal, self).__init__(providing_args)

    def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
        receiver_name = '.'.join([receiver.__class__.__module__,
                                  receiver.__class__.__name__])
        if receiver_name != self.allowed_receiver:
            raise UnauthorizedSignalReceiver()
        super(SingleHandlerSignal, self).connect(
            receiver, sender, weak, dispatch_uid)


request_accessor = SingleHandlerSignal()


def get_request():
    signal_response = request_accessor.send(None)
    if not signal_response:
        return None
    return signal_response[0][1]

# add this middleware to settings
class RequestProvider(object):

    def __init__(self):
        self._request = None
        request_accessor.connect(self)

    def process_request(self, request):
        self._request = request
        return None

    def __call__(self, **kwargs):
        return self._request

Thats it

@stephenmcd

Copy link
Copy Markdown
Author

Cool, this isn't really on my radar right now so I'll leave you guys to it - but for Tom's sake why don't you put this into a pull request instead.

@askaliuk

Copy link
Copy Markdown

@pySilver thank you for sharing your solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

5 participants