|
| 1 | +from typing import Dict, cast |
| 2 | +from xml.etree.ElementTree import Element |
| 3 | + |
| 4 | +from django.conf import settings |
| 5 | +from django.http.response import HttpResponse |
| 6 | +from django.test.utils import ContextList, override_settings |
| 7 | +from html5lib.constants import E |
| 8 | +from html5lib.html5parser import HTMLParser |
| 9 | + |
| 10 | +from debug_toolbar.toolbar import DebugToolbar |
| 11 | + |
| 12 | +from .base import IntegrationTestCase |
| 13 | + |
| 14 | + |
| 15 | +def get_namespaces(element: Element) -> Dict[str, str]: |
| 16 | + """ |
| 17 | + Return the default `xmlns`. See |
| 18 | + https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml-with-namespaces |
| 19 | + """ |
| 20 | + if not element.tag.startswith("{"): |
| 21 | + return {} |
| 22 | + return {"": element.tag[1:].split("}", maxsplit=1)[0]} |
| 23 | + |
| 24 | + |
| 25 | +@override_settings(DEBUG=True) |
| 26 | +class CspRenderingTestCase(IntegrationTestCase): |
| 27 | + """Testing if `csp-nonce` renders.""" |
| 28 | + |
| 29 | + def setUp(self): |
| 30 | + super().setUp() |
| 31 | + self.parser = HTMLParser() |
| 32 | + |
| 33 | + def _fail_if_missing( |
| 34 | + self, root: Element, path: str, namespaces: Dict[str, str], nonce: str |
| 35 | + ): |
| 36 | + """ |
| 37 | + Search elements, fail if a `nonce` attribute is missing on them. |
| 38 | + """ |
| 39 | + elements = root.findall(path=path, namespaces=namespaces) |
| 40 | + for item in elements: |
| 41 | + if item.attrib.get("nonce") != nonce: |
| 42 | + raise self.failureException(f"{item} has no nonce attribute.") |
| 43 | + |
| 44 | + def _fail_if_found(self, root: Element, path: str, namespaces: Dict[str, str]): |
| 45 | + """ |
| 46 | + Search elements, fail if a `nonce` attribute is found on them. |
| 47 | + """ |
| 48 | + elements = root.findall(path=path, namespaces=namespaces) |
| 49 | + for item in elements: |
| 50 | + if "nonce" in item.attrib: |
| 51 | + raise self.failureException(f"{item} has a nonce attribute.") |
| 52 | + |
| 53 | + def _fail_on_invalid_html(self, content: bytes, parser: HTMLParser): |
| 54 | + """Fail if the passed HTML is invalid.""" |
| 55 | + if parser.errors: |
| 56 | + default_msg = ["Content is invalid HTML:"] |
| 57 | + lines = content.split(b"\n") |
| 58 | + for position, error_code, data_vars in parser.errors: |
| 59 | + default_msg.append(" %s" % E[error_code] % data_vars) |
| 60 | + default_msg.append(" %r" % lines[position[0] - 1]) |
| 61 | + msg = self._formatMessage(None, "\n".join(default_msg)) |
| 62 | + raise self.failureException(msg) |
| 63 | + |
| 64 | + @override_settings( |
| 65 | + MIDDLEWARE=settings.MIDDLEWARE + ["csp.middleware.CSPMiddleware"] |
| 66 | + ) |
| 67 | + def test_exists(self): |
| 68 | + """A `nonce` should exist when using the `CSPMiddleware`.""" |
| 69 | + response = cast(HttpResponse, self.client.get(path="/regular/basic/")) |
| 70 | + self.assertEqual(response.status_code, 200) |
| 71 | + |
| 72 | + html_root: Element = self.parser.parse(stream=response.content) |
| 73 | + self._fail_on_invalid_html(content=response.content, parser=self.parser) |
| 74 | + self.assertContains(response, "djDebug") |
| 75 | + |
| 76 | + namespaces = get_namespaces(element=html_root) |
| 77 | + toolbar = list(DebugToolbar._store.values())[0] |
| 78 | + nonce = str(toolbar.request.csp_nonce) |
| 79 | + self._fail_if_missing( |
| 80 | + root=html_root, path=".//link", namespaces=namespaces, nonce=nonce |
| 81 | + ) |
| 82 | + self._fail_if_missing( |
| 83 | + root=html_root, path=".//script", namespaces=namespaces, nonce=nonce |
| 84 | + ) |
| 85 | + |
| 86 | + @override_settings( |
| 87 | + DEBUG_TOOLBAR_CONFIG={"DISABLE_PANELS": set()}, |
| 88 | + MIDDLEWARE=settings.MIDDLEWARE + ["csp.middleware.CSPMiddleware"], |
| 89 | + ) |
| 90 | + def test_redirects_exists(self): |
| 91 | + response = cast(HttpResponse, self.client.get(path="/regular/basic/")) |
| 92 | + self.assertEqual(response.status_code, 200) |
| 93 | + |
| 94 | + html_root: Element = self.parser.parse(stream=response.content) |
| 95 | + self._fail_on_invalid_html(content=response.content, parser=self.parser) |
| 96 | + self.assertContains(response, "djDebug") |
| 97 | + |
| 98 | + namespaces = get_namespaces(element=html_root) |
| 99 | + context: ContextList = response.context # pyright: ignore[reportAttributeAccessIssue] |
| 100 | + nonce = str(context["toolbar"].request.csp_nonce) |
| 101 | + self._fail_if_missing( |
| 102 | + root=html_root, path=".//link", namespaces=namespaces, nonce=nonce |
| 103 | + ) |
| 104 | + self._fail_if_missing( |
| 105 | + root=html_root, path=".//script", namespaces=namespaces, nonce=nonce |
| 106 | + ) |
| 107 | + |
| 108 | + @override_settings( |
| 109 | + MIDDLEWARE=settings.MIDDLEWARE + ["csp.middleware.CSPMiddleware"] |
| 110 | + ) |
| 111 | + def test_panel_content_nonce_exists(self): |
| 112 | + response = cast(HttpResponse, self.client.get(path="/regular/basic/")) |
| 113 | + self.assertEqual(response.status_code, 200) |
| 114 | + |
| 115 | + toolbar = list(DebugToolbar._store.values())[0] |
| 116 | + panels_to_check = ["HistoryPanel", "TimerPanel"] |
| 117 | + for panel in panels_to_check: |
| 118 | + content = toolbar.get_panel_by_id(panel).content |
| 119 | + html_root: Element = self.parser.parse(stream=content) |
| 120 | + namespaces = get_namespaces(element=html_root) |
| 121 | + nonce = str(toolbar.request.csp_nonce) |
| 122 | + self._fail_if_missing( |
| 123 | + root=html_root, path=".//link", namespaces=namespaces, nonce=nonce |
| 124 | + ) |
| 125 | + self._fail_if_missing( |
| 126 | + root=html_root, path=".//script", namespaces=namespaces, nonce=nonce |
| 127 | + ) |
| 128 | + |
| 129 | + def test_missing(self): |
| 130 | + """A `nonce` should not exist when not using the `CSPMiddleware`.""" |
| 131 | + response = cast(HttpResponse, self.client.get(path="/regular/basic/")) |
| 132 | + self.assertEqual(response.status_code, 200) |
| 133 | + |
| 134 | + html_root: Element = self.parser.parse(stream=response.content) |
| 135 | + self._fail_on_invalid_html(content=response.content, parser=self.parser) |
| 136 | + self.assertContains(response, "djDebug") |
| 137 | + |
| 138 | + namespaces = get_namespaces(element=html_root) |
| 139 | + self._fail_if_found(root=html_root, path=".//link", namespaces=namespaces) |
| 140 | + self._fail_if_found(root=html_root, path=".//script", namespaces=namespaces) |
0 commit comments