Skip to content

Restore compatibility with iptools.IpRangeList #1929

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

Merged
merged 1 commit into from
Jun 1, 2024
Merged
Show file tree
Hide file tree
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
15 changes: 12 additions & 3 deletions debug_toolbar/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,14 @@ def show_toolbar(request):
"""
Default function to determine whether to show the toolbar on a given page.
"""
internal_ips = list(settings.INTERNAL_IPS)
if not settings.DEBUG:
return False

# Test: settings
if request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS:
return True

# Test: Docker
try:
# This is a hack for docker installations. It attempts to look
# up the IP address of the docker host.
Expand All @@ -31,11 +37,14 @@ def show_toolbar(request):
".".join(socket.gethostbyname("host.docker.internal").rsplit(".")[:-1])
+ ".1"
)
internal_ips.append(docker_ip)
if request.META.get("REMOTE_ADDR") == docker_ip:
return True
except socket.gaierror:
# It's fine if the lookup errored since they may not be using docker
pass
return settings.DEBUG and request.META.get("REMOTE_ADDR") in internal_ips

# No test passed
return False


@lru_cache(maxsize=None)
Expand Down
22 changes: 22 additions & 0 deletions tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,28 @@ def test_show_toolbar_docker(self, mocked_gethostbyname):
self.assertTrue(show_toolbar(self.request))
mocked_gethostbyname.assert_called_once_with("host.docker.internal")

def test_not_iterating_over_INTERNAL_IPS(self):
"""Verify that the middleware does not iterate over INTERNAL_IPS in some way.

Some people use iptools.IpRangeList for their INTERNAL_IPS. This is a class
that can quickly answer the question if the setting contain a certain IP address,
but iterating over this object will drain all performance / blow up.
"""

class FailOnIteration:
def __iter__(self):
raise RuntimeError(
"The testcase failed: the code should not have iterated over INTERNAL_IPS"
)

def __contains__(self, x):
return True

with self.settings(INTERNAL_IPS=FailOnIteration()):
response = self.client.get("/regular/basic/")
self.assertEqual(response.status_code, 200)
self.assertContains(response, "djDebug") # toolbar

def test_should_render_panels_RENDER_PANELS(self):
"""
The toolbar should force rendering panels on each request
Expand Down