Skip to content

Commit cf0cc0d

Browse files
authored
Restore compatibility with iptools.IpRangeList (#1929)
1 parent a0f0df9 commit cf0cc0d

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

debug_toolbar/middleware.py

+12-3
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,14 @@ def show_toolbar(request):
2020
"""
2121
Default function to determine whether to show the toolbar on a given page.
2222
"""
23-
internal_ips = list(settings.INTERNAL_IPS)
23+
if not settings.DEBUG:
24+
return False
2425

26+
# Test: settings
27+
if request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS:
28+
return True
29+
30+
# Test: Docker
2531
try:
2632
# This is a hack for docker installations. It attempts to look
2733
# up the IP address of the docker host.
@@ -31,11 +37,14 @@ def show_toolbar(request):
3137
".".join(socket.gethostbyname("host.docker.internal").rsplit(".")[:-1])
3238
+ ".1"
3339
)
34-
internal_ips.append(docker_ip)
40+
if request.META.get("REMOTE_ADDR") == docker_ip:
41+
return True
3542
except socket.gaierror:
3643
# It's fine if the lookup errored since they may not be using docker
3744
pass
38-
return settings.DEBUG and request.META.get("REMOTE_ADDR") in internal_ips
45+
46+
# No test passed
47+
return False
3948

4049

4150
@lru_cache(maxsize=None)

tests/test_integration.py

+22
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,28 @@ def test_show_toolbar_docker(self, mocked_gethostbyname):
7575
self.assertTrue(show_toolbar(self.request))
7676
mocked_gethostbyname.assert_called_once_with("host.docker.internal")
7777

78+
def test_not_iterating_over_INTERNAL_IPS(self):
79+
"""Verify that the middleware does not iterate over INTERNAL_IPS in some way.
80+
81+
Some people use iptools.IpRangeList for their INTERNAL_IPS. This is a class
82+
that can quickly answer the question if the setting contain a certain IP address,
83+
but iterating over this object will drain all performance / blow up.
84+
"""
85+
86+
class FailOnIteration:
87+
def __iter__(self):
88+
raise RuntimeError(
89+
"The testcase failed: the code should not have iterated over INTERNAL_IPS"
90+
)
91+
92+
def __contains__(self, x):
93+
return True
94+
95+
with self.settings(INTERNAL_IPS=FailOnIteration()):
96+
response = self.client.get("/regular/basic/")
97+
self.assertEqual(response.status_code, 200)
98+
self.assertContains(response, "djDebug") # toolbar
99+
78100
def test_should_render_panels_RENDER_PANELS(self):
79101
"""
80102
The toolbar should force rendering panels on each request

0 commit comments

Comments
 (0)