snok / django-guid

Inject an ID into every log message from a Django request. ASGI compatible, integrates with Sentry, and works with Celery

Home Page:https://django-guid.readthedocs.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[BUG] Can't add/override HTTP headers in other middlewares

alessiofachechi opened this issue · comments

Describe the bug
Putting the middleware on top of middleware list — as suggested by doc — doesn't allow next middlewares to potentially add/override HTTP headers through:

request.META['HTTP_CUSTOM_HEADER'] = "CUSTOM VALUE"

This is due to using django_guid.utils.get_id_from_header() in django_guid.middleware.process_incoming_request(), which triggers an earlier immutable HttpHeader object build, so any add/override headers intent has no impact.
Would be better to use request.META to get/set headers.

To Reproduce

  1. Create a middleware

    def foo_middleware(get_response):
        def middleware(request):
            request.META["HTTP_X_FOO"] = "foo"
            return get_response(request)
    
        return middleware
  2. Add middleware after django_guid

    MIDDLEWARE = [
        "django_guid.middleware.guid_middleware",
        "foo.foo_middleware",
    ]
  3. Try to access the header in a view

    @api_view(["GET"])
    def test_view(request):
        assert request.headers.get("X-Foo") == "foo"
  4. Now retry by removing "django_guid.middleware.guid_middleware" from MIDDLEWARE.

Hi, please see discussion in #95 and the PR #97. I’m out of the country, so hopefully this resolves your issues.

[...] hopefully this resolves your issues.

Unfortunately not @JonasKs.

def get_id_from_header(request: 'HttpRequest') -> str:
    # ...
    header: str = request.headers.get(settings.guid_header_name) 

should theoretically become something like

def get_id_from_header(request: 'HttpRequest') -> str:
    # ...
    header: str = request.META.get(settings.guid_header_name) 

to avoid next middlewares potentially break.

Would you mind linking me docs for this? I don't use Django anymore, and I can't remember this behavior.

Anyway, I'm very happy to accept a fix with a test for this if you'd like to contribute. I will probably, unfortunately not be able to review for at least a week.