Skip to content

Commit 33298ce

Browse files
fix: reject signed hx kwargs that collide with URLconf kwargs
dispatch merged the signed template-tag kwargs into the view's URLconf kwargs with dict.update(), so a template-tag kwarg named e.g. `pk` silently shadowed the URL <pk> the page view relies on. Detect the collision and raise ImproperlyConfigured naming the offending key(s) instead. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent de8b6e7 commit 33298ce

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

hx_requests/views.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from urllib.parse import parse_qs, urlparse
55

66
from django.conf import settings
7+
from django.core.exceptions import ImproperlyConfigured
78
from django.http import Http404, HttpRequest
89
from django.utils.decorators import method_decorator
910
from django.views.decorators.csrf import ensure_csrf_cookie
@@ -51,7 +52,15 @@ def dispatch(self, request, *args, **kwargs):
5152
and request.method.lower() in self.http_method_names
5253
):
5354
request = self._resolve_hx_token(request)
54-
kwargs.update(self.get_hx_extra_kwargs(request))
55+
extra_kwargs = self.get_hx_extra_kwargs(request)
56+
collisions = set(kwargs) & set(extra_kwargs)
57+
if collisions:
58+
raise ImproperlyConfigured(
59+
f"hx-requests kwarg(s) {sorted(collisions)} collide with URLconf "
60+
f"kwargs on view {self.__class__.__name__}. A signed template-tag "
61+
"kwarg must not shadow a URL kwarg -- rename the template-tag kwarg."
62+
)
63+
kwargs.update(extra_kwargs)
5564
hx_request = self._setup_hx_request(request, *args, **kwargs)
5665

5766
# Use request from hx_request, in case use_current_url is set to True

tests/test_base_hx_request.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,15 @@ def test_tampered_hx_token_raises_404():
409409
BaseView.as_view()(request)
410410

411411

412+
def test_hx_kwarg_colliding_with_urlconf_kwarg_is_rejected():
413+
# A template-tag kwarg must not silently shadow a URLconf kwarg (e.g. a
414+
# URL <pk> the page view relies on). The collision is a misconfiguration.
415+
from django.core.exceptions import ImproperlyConfigured
416+
417+
with pytest.raises(ImproperlyConfigured, match="pk"):
418+
hx_get(hx.SimpleGetHx, BaseView, view_kwargs={"pk": 1}, hx_kwargs={"pk": 2})
419+
420+
412421
def test_unknown_hx_request_name_raises_404():
413422
request = RequestFactory().get("/", data={HX_TOKEN_PARAM: sign_hx_payload("does_not_exist")})
414423
request.META["HTTP_HX_REQUEST"] = True

0 commit comments

Comments
 (0)