opentelemetry-python-contrib: DisallowedHost exception for Django instrumentation
Describe your environment
- Django 4.1.7
- Python 3.11.1
- opentelemetry-instrumentation-django 0.38b0
Steps to reproduce Create basic django app:
mkdir django-test && cd django-test
python -m venv .venv
source .venv/bin/activate
pip install django
django-admin startproject django_test .
python manage.py migrate
cat <<EOF > gunicorn.config.py
from opentelemetry.instrumentation.django import DjangoInstrumentor
def post_fork(server, worker):
DjangoInstrumentor().instrument()
EOF
Only allow hosts from a specific origin. This is best practice in terms of security.
Change the following variables in django_test/settings.py
:
DEBUG = False
ALLOWED_HOSTS = ['example.com']
Create a health check middleware. The middleware is added at the beginning of the middleware array, since we don’t want the allowed hosts rule to apply to the health check, since we’ll likely be receiving health checks from the load balancer, which does not have the correct host.
cat <<EOF > django_test/middleware.py
from django.http import HttpResponse
class HealthCheckMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.path == "/api/health":
return HttpResponse("ok\n")
return self.get_response(request)
EOF
Add to the array in django_test.settings.py
:
MIDDLEWARE = [
'django_test.middleware.HealthCheckMiddleware',
# ... other middlewares here
]
Now the health check route works as expected when we run the server:
python manage.py runserver
❯ curl localhost:8000/api/health
ok
Now we need to add open telemetry django and gunicorn:
pip install opentelemetry-instrumentation-django
pip install gunicorn
Now we run django with instrumentation:
DJANGO_SETTINGS_MODULE=django_test.settings OTEL_SERVICE_NAME=TestApi gunicorn django_test.wsgi:application -c gunicorn.config.py
The healthcheck endpoint fails with 400 now, because of the DisallowedHost exception. More specifically, the error is raised here on the request.build_absolute_uri
call.
What is the expected behavior?
The healthcheck endpoint should not fail when telemetry is enabled.
I’m not sure what the best solution for this is, but I guess we want to build the absolute URI without calling request.build_absolute_uri
, since it will throw an exception.
EDIT: since I’m new to the library, I’m not sure what the best solution would be. But if you have any pointers feel free to say them that I can try to fix the issue as well.
About this issue
- Original URL
- State: open
- Created a year ago
- Reactions: 2
- Comments: 16 (13 by maintainers)
it could be the index or name of the middleware to come after/before or by some other way to place it in the right position.