-
Notifications
You must be signed in to change notification settings - Fork 0
/
shouty.py
2075 lines (1888 loc) · 85 KB
/
shouty.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import logging
import sys
from collections import namedtuple
from django.core import checks
try:
from django.utils.encoding import force_str as force_text
except ImportError:
from django.utils.encoding import force_text
try:
from collections.abc import Sized
except ImportError:
from collections import Sized
from difflib import get_close_matches
from django.apps import AppConfig
from django.conf import settings
from django.template import Context
from django.template.base import (
Variable,
VariableDoesNotExist,
UNKNOWN_SOURCE,
Origin,
Node,
Token,
NodeList,
Template,
)
from django.template.context import BaseContext
from django.template.defaulttags import URLNode, IfNode, TemplateLiteral
from django.template.exceptions import TemplateSyntaxError, TemplateDoesNotExist
from django.forms import Form
try:
from typing import (
Any,
Tuple,
Text,
Optional,
Type,
Set,
Dict,
List,
Iterator,
Union,
)
except ImportError:
pass
__version_info__ = "0.2.0"
__version__ = "0.2.0"
version = "0.2.0"
VERSION = "0.2.0"
def get_version():
# type: () -> Text
return version
__all__ = ["MissingVariable", "patch", "Shout", "default_app_config", "get_version"]
logger = logging.getLogger(__name__)
class MissingVariable(TemplateSyntaxError): # type: ignore
"""
Django will raise TemplateSyntaxError in various scenarios, so this
subclass is used to differentiate shouty errors, while still getting the
same functionality.
"""
def __init__(self, *args, token, template_name, all_template_names):
super().__init__(*args)
self.token = token
self.template_name = template_name
self.all_template_names = all_template_names
old_resolve_lookup = Variable._resolve_lookup
old_url_render = URLNode.render
old_if_render = IfNode.render
ANY_TEMPLATE = "*"
ANY_VARIABLE = "*"
# The following values throw an exception when used as {{ var.name }}
VARIABLE_BLACKLIST = {
# When trying to render the technical 500 template, it accesses
# settings.SETTINGS_MODULE, which ordinarily is there. But if using
# a UserSettingsHolder, it doesn't seem to be. I've not looked into
# it fully, but it's a smashing great error that prevents the debug 500
# from working otherwise.
# TODO: Get fixed upstream?
"settings.SETTINGS_MODULE": (ANY_TEMPLATE,),
# django-debug-toolbar SQL panel, makes use of a dictionary of queries,
# whose values aren't always available.
# TODO: Get fixed upstream?
"query.starts_trans": ("debug_toolbar/panels/sql.html",),
"query.ends_trans": ("debug_toolbar/panels/sql.html",),
"query.in_trans": ("debug_toolbar/panels/sql.html",),
"query.similar_count": ("debug_toolbar/panels/sql.html",),
"query.similar_color": ("debug_toolbar/panels/sql.html",),
"query.duplicate_count": ("debug_toolbar/panels/sql.html",),
"query.duplicate_color": ("debug_toolbar/panels/sql.html",),
"query.iso_level": ("debug_toolbar/panels/sql.html",),
"query.trans_status": ("debug_toolbar/panels/sql.html",),
# Django admin
# TODO: Get fixed upstream?
"subtitle": ("admin/base_site.html",),
"model.add_url": (
"admin/index.html",
"admin/app_index.html",
), # used on the site/app index
"model.admin_url": (
"admin/index.html",
"admin/app_index.html",
), # used on the site/app index
"is_popup": (
ANY_TEMPLATE,
), # Used all over the shop: (), but not declared everywhere.
"cl.formset.errors": (
"admin/change_list.html",
), # Used on the changelist even if there's no formset?
"show": (ANY_TEMPLATE,),
# date_hierarchy for the changelist doesn't actually always return a dictionary ...
"cl.formset.is_multipart": (
"admin/change_list.html",
), # Used on the changelist even if there's no formset?
"result.form.non_field_errors": (
"admin/change_list_results.html",
), # Used on the changelist ...
"can_change_related": (ANY_TEMPLATE,), # Used by related_widget_wrapper
"can_add_related": (ANY_TEMPLATE,), # Used by related_widget_wrapper
"can_delete_related": (ANY_TEMPLATE,), # Used by related_widget_wrapper
# Django's technical 500 templates (text & html) via get_traceback_data
"exception_type": (ANY_TEMPLATE,),
"exception_value": (ANY_TEMPLATE,),
"lastframe": (ANY_TEMPLATE,),
"request_GET_items": (ANY_TEMPLATE,),
"request_FILES_items": (ANY_TEMPLATE,),
"request_COOKIES_items": (ANY_TEMPLATE,),
# Django's "debug" context processor only fills debug and sql_queries if
# DEBUG=True and the user's IP is in INTERNAL_IPS
"debug": (ANY_TEMPLATE,),
"sql_queries": (ANY_TEMPLATE,),
"site_title": ("admin_honeypot/login.html",),
"site_header": ("admin_honeypot/login.html",),
# Django pipeline templates.
"media": ("pipeline/css.html",),
# In Django 3.1 this ... might be necessary. IDK I can't recall
# if the request context processor being missing actually causes
# a system check error for the admin.
"request.path": ("admin/app_list.html",),
# In Django 3.1+ this has turned up...
"show_changelinks": ("admin/app_list.html",),
"is_nav_sidebar_enabled": ("admin/base_site.html",),
# These can occur in the technical 500 page.
"template_info.name": (UNKNOWN_SOURCE,),
"template_info.line": (UNKNOWN_SOURCE,),
"template_info.top": (UNKNOWN_SOURCE,),
"template_info.bottom": (UNKNOWN_SOURCE,),
"template_info.total": (UNKNOWN_SOURCE,),
"template_info.source_lines": (UNKNOWN_SOURCE,),
# accessing admindocs views will have this in file admin_doc/view_index.html
"view.title": ("admin_doc/view_index.html",),
} # type: Dict[str, Tuple[Text,...]]
# The following values throw an exception when used in an if like {% if forloop.last and pat.name %}
IF_VARIABLE_BLACKLIST = {
# When trying to render the technical 404 template, {% if forloop.last and pat.name %} gets used
# in file <unknown source>
"pat.name": (UNKNOWN_SOURCE,),
# Accessing admindocs index will trigger this: {% if title %}<h1>{{ title }}</h1>{% endif %}
# in file admin_doc/index.html and every subpage therein...
"title": (
"admin/base.html",
"admin/base_site.html",
"pipeline/css.html",
),
"subtitle": (
"admin/base.html",
"admin/base_site.html",
),
# accessing admindocs detailed model information has: {% if field.help_text %} - ...
# in file admin_doc/model_detail.html
"field.help_text": ("admin_doc/model_detail.html",),
# accessing admindocs views detail will have these in file admin_doc/view_detail.html
"meta.Context": ("admin_doc/view_detail.html",),
"meta.Templates": ("admin_doc/view_detail.html",),
# Rest framework...
"name": ("rest_framework/base.html",),
"code_style": ("rest_framework/base.html",),
"style.hide_label": (
"rest_framework/horizontal/checkbox.html",
"rest_framework/horizontal/checkbox_multiple.html",
"rest_framework/horizontal/dict_field.html",
"rest_framework/horizontal/fieldset.html",
"rest_framework/horizontal/input.html",
"rest_framework/horizontal/list_field.html",
"rest_framework/horizontal/list_fieldset.html",
"rest_framework/horizontal/radio.html",
"rest_framework/horizontal/select.html",
"rest_framework/horizontal/select_multiple.html",
"rest_framework/horizontal/textarea.html",
"rest_framework/vertical/checkbox.html",
"rest_framework/vertical/checkbox_multiple.html",
"rest_framework/vertical/dict_field.html",
"rest_framework/vertical/fieldset.html",
"rest_framework/vertical/input.html",
"rest_framework/vertical/list_field.html",
"rest_framework/vertical/list_fieldset.html",
"rest_framework/vertical/radio.html",
"rest_framework/vertical/select.html",
"rest_framework/vertical/select_multiple.html",
"rest_framework/vertical/textarea.html",
),
"style.placeholder": (
"rest_framework/horizontal/input.html",
"rest_framework/horizontal/textarea.html",
"rest_framework/inline/input.html",
"rest_framework/inline/textarea.html",
"rest_framework/vertical/input.html",
"rest_framework/vertical/textarea.html",
),
"style.autofocus": (
"rest_framework/horizontal/input.html",
"rest_framework/inline/input.html",
"rest_framework/vertical/input.html",
),
# Django pipeline templates.
"charset": ("pipeline/css.html",),
"async": ("pipeline/js.html",),
"defer": ("pipeline/js.html",),
} # type: Dict[str, Tuple[Text,...]]
# The following IfNode contents don't have an else but do have an elif, so
# need to be silenced.
IF_ELSE_BLACKLIST = {
# Django admin
"if model.admin_url and show_changelinks": ("admin/app_list.html",),
"if not line.fields|length_is:'1'": ("admin/includes/fieldset.html",),
}
def variable_blacklist():
# type: () -> Dict[Text, List[Text]]
# TODO: make this memoized/cached?
variables_by_template = {} # type: Dict[Text, List[Text]]
for var, templates in VARIABLE_BLACKLIST.items():
variables_by_template.setdefault(var, [])
variables_by_template[var].extend(templates)
for var, templates in IF_VARIABLE_BLACKLIST.items():
variables_by_template.setdefault(var, [])
variables_by_template[var].extend(templates)
user_blacklist = getattr(settings, "SHOUTY_VARIABLE_BLACKLIST", ())
if hasattr(user_blacklist, "items") and callable(user_blacklist.items):
for var, templates in user_blacklist.items():
variables_by_template.setdefault(var, [])
variables_by_template[var].extend(templates)
else:
for var in user_blacklist:
variables_by_template.setdefault(var, [])
variables_by_template[var].append(ANY_TEMPLATE)
return variables_by_template
def if_else_blacklist():
# type: () -> Dict[Text, List[Text]]
variables_by_template = {} # type: Dict[Text, List[Text]]
# Is compounding the IF specific checks with the normal checks silencing
# anything incorrectly, I wonder? ...
for var, templates in IF_ELSE_BLACKLIST.items():
variables_by_template.setdefault(var, [])
variables_by_template[var].extend(templates)
user_blacklist = getattr(settings, "SHOUTY_VARIABLE_BLACKLIST", ())
if hasattr(user_blacklist, "items") and callable(user_blacklist.items):
for var, templates in user_blacklist.items():
variables_by_template.setdefault(var, [])
variables_by_template[var].extend(templates)
else:
for var in user_blacklist:
variables_by_template.setdefault(var, [])
variables_by_template[var].append(ANY_TEMPLATE)
return variables_by_template
def is_silenced(whole_var, template_name, blacklist, all_template_names):
ignored_templates_for_this_var = blacklist.get(whole_var, [])
ignored_templates_for_any_var = blacklist.get(ANY_VARIABLE, [])
if ANY_TEMPLATE in ignored_templates_for_this_var:
logger.debug(
"Ignoring '%s' globally via * (of %s)",
whole_var,
ignored_templates_for_this_var,
)
return True
elif template_name in ignored_templates_for_this_var:
logger.debug(
"Ignoring '%s' for template '%s' (of %s)",
whole_var,
template_name,
ignored_templates_for_this_var,
)
return True
elif any(x in ignored_templates_for_this_var for x in all_template_names):
logger.debug(
"Ignoring '%s' for template '%s' (of %s)",
whole_var,
template_name,
all_template_names,
)
return True
elif any(x in ignored_templates_for_any_var for x in all_template_names):
logger.debug(
"Ignoring '%s' for template '%s' (of %s) due to * over %s",
whole_var,
template_name,
all_template_names,
ignored_templates_for_any_var,
)
return True
elif template_name in ignored_templates_for_any_var:
logger.debug(
"Ignoring '%s' for template '%s' (of %s) due to * over %s",
whole_var,
template_name,
all_template_names,
ignored_templates_for_any_var,
)
return True
else:
return False
def create_exception_with_template_debug(context, part, node):
# type: (Context, Text, Optional[Node]) -> Tuple[Text, Dict[Text, Any], List[Text]]
"""
Between Django 2.0 and Django 3.x at least, painting template exceptions
can do so via the "wrong" template, which highlights nothing.
Pretty sure it has also done them wrong in niche cases throughout the 1.x
lifecycle, as I've got utterly used to ignoring that area of the technical 500.
Anyway, this method attempts to make up for that for our loud error messages
by eagerly binding what might hopefully be the right candidate variable/url
to the exception attribute searched for by Django.
This is still only going to be correct sometimes, because the same variable
might appear multiple times in a template (or set of templates) and may also
appear in both line & block comments which won't actually trigger an exception.
False positives abound!
https://code.djangoproject.com/ticket/31478
https://code.djangoproject.com/ticket/28935
https://code.djangoproject.com/ticket/27956
"""
__traceback_hide__ = settings.DEBUG
faketoken = namedtuple("faketoken", "position")
contexts_to_search = [] # type: List[Union[Template, Origin]]
all_potential_contexts = [] # type: List[Union[Template, Origin]]
token = None # type: Optional[Token]
origin = None # type: Optional[Origin]
if node is not None:
token = node.token
origin = node.origin
if origin is not None:
contexts_to_search.append(origin)
all_potential_contexts.append(origin)
render_context = context.render_context
# Prefer extends origins
if "extends_context" in render_context and render_context["extends_context"]:
all_potential_contexts.extend(render_context.get("extends_context", []))
# Who knows which order might be right for context or render context? not me.
# It's possible for the template attribute to not exist OR for it to be None
# in theory, so we'll guard against that.
render_context_template = getattr(
render_context, "template", None
) # type: Optional[Template]
if render_context_template is not None:
all_potential_contexts.append(render_context_template)
context_template = getattr(context, "template", None) # type: Optional[Template]
if context_template is not None:
all_potential_contexts.append(context.template)
render_context_flat = render_context.flatten()
# Inclusion nodes put their template into the context with themselves as a key.
for k in render_context_flat:
if isinstance(render_context_flat[k], Template):
all_potential_contexts.append(render_context_flat[k])
context_flat = context.flatten()
for k in context_flat:
if isinstance(context_flat[k], Template):
all_potential_contexts.append(context_flat[k])
for ctx in all_potential_contexts:
if ctx not in contexts_to_search:
contexts_to_search.append(ctx)
assert len(contexts_to_search) <= len(all_potential_contexts)
template_names = [] # type: List[Text]
for parent in contexts_to_search:
if isinstance(parent, Origin):
# an Origin without a template name would crash deep down in
# find_template with
# TypeError: join() argument must be str, bytes, or os.PathLike object, not 'NoneType'
if parent.template_name:
try:
_template, _origin = context.template.engine.find_template(
parent.template_name,
skip=None,
)
except TemplateDoesNotExist:
# Got an Origin without the Template backing it being findable...
# So just fake one.
_origin = parent
_template = Template("", origin=_origin, name=parent)
else:
_origin = parent
_template = Template("", origin=_origin, name=parent)
else:
_template = parent
_origin = parent.origin
if _origin.template_name is None:
template_names.append(UNKNOWN_SOURCE)
else:
template_names.append(_origin.template_name)
src = _template.source # type: Text
# Just skip every subsequent check if the token/variable/part isn't anywhere in the template
# which is sometimes the case if walking backwards through a series of templates, and sometimes
# (eg: in crispy_forms) the variable never exists in any template file (html5_required) so we can
# short circuit here.
if part not in src:
continue
# Using a DebugLexer instead of a Lexer, so we have positions.
if token is not None and getattr(token, "position", None) is not None:
start = src.find(part, token.position[0]) # type: int
if start > -1:
end = start + len(part)
highlight_part = faketoken(position=(start, end))
exc_info = _template.get_exception_info(
ValueError("ignored"), highlight_part
)
return (
_template.origin.template_name or UNKNOWN_SOURCE,
exc_info,
template_names,
)
if UNKNOWN_SOURCE not in template_names:
template_names.append(UNKNOWN_SOURCE)
return UNKNOWN_SOURCE, {}, template_names
def new_resolve_lookup(self, context):
# type: (Variable, Any) -> Any
"""
Call the original _resolve_lookup method, and if it fails with an exception
which would ordinarily be suppressed by the Django Template Language,
instead re-format it and re-raise it as another, uncaught exception type.
"""
__traceback_hide__ = settings.DEBUG
parent_frame = sys._getframe()
parent_node = None # type: Optional[Node]
while parent_frame.f_locals:
if "self" in parent_frame.f_locals:
obj = parent_frame.f_locals["self"]
if (
isinstance(obj, Node)
and hasattr(obj, "origin")
and hasattr(obj, "token")
):
parent_node = obj
break
parent_frame = parent_frame.f_back
try:
return old_resolve_lookup(self, context)
except VariableDoesNotExist as e:
# Given the token {{ xyz }}
# it should be possible to NOT raise the MissingVariable exception by setting:
# "xyz": ['*']
# "xyz": ['path/to/specific/template.html', 'other/template.html']
# "*": ['path/to/template.html']
whole_var = self.var
blacklist = variable_blacklist()
ignored_templates_for_this_var = blacklist.get(whole_var, [])
ignored_templates_for_any_var = blacklist.get(ANY_VARIABLE, [])
not_being_ignored = whole_var not in blacklist
has_per_template_ignores = (len(ignored_templates_for_this_var) > 0) or (
len(ignored_templates_for_any_var) > 0
)
if not_being_ignored or has_per_template_ignores:
try:
(
template_name,
exc_info,
all_template_names,
) = create_exception_with_template_debug(
context, whole_var, parent_node
)
except Exception as e2:
logger.warning(
"failed to create template_debug information", exc_info=e2
)
# In case my code is terrible, and raises an exception, let's
# just carry on and let Django try for itself to set up relevant
# debug info
template_name = UNKNOWN_SOURCE
exc_info = {}
all_template_names = [UNKNOWN_SOURCE]
bit = e.params[0] # type: Text
current = e.params[1]
if isinstance(current, BaseContext):
possibilities = set(current.flatten().keys())
elif hasattr(current, "keys") and callable(current.keys):
possibilities = set(current.keys())
elif isinstance(current, Sized) and bit.isdigit():
possibilities = set(str(x) for x in range(0, len(current)))
elif isinstance(current, Form):
possibilities = set(current.fields.keys())
else:
possibilities = set()
possibilities = {x for x in possibilities if not x[0] == "_"} | {
x for x in dir(current) if not x[0] == "_"
}
# maybe you typed csrf_token instead of CSRF_TOKEN or what-have-you.
# But difflib considers case when calculating close matches.
# So we'll compare everything lower-case, and convert back...
# Based on https://stackoverflow.com/q/11384714
possibilities_mapped = {poss.lower(): poss for poss in possibilities}
# self.var might be 'request.user.pk' but part might just be 'pk'
if bit != whole_var:
msg = "Token '{token}' of '{var}' in template '{template}' does not resolve."
else:
msg = "Variable '{token}' in template '{template}' does not resolve."
# Find close names case-insensitively, and if there are any, map
# them back to their original case/form (so that "csrf_token"
# might map back to "CSRF_TOKEN" or "Csrf_Token")
closest = get_close_matches(bit.lower(), possibilities_mapped.keys())
if closest:
closest = [
possibilities_mapped[match]
for match in closest
if match in possibilities_mapped
]
if len(closest) > 1:
msg += "\nPossibly you meant one of: '{closest_matches}'."
elif closest:
msg += "\nPossibly you meant to use '{closest_matches}'."
if all_template_names:
msg += "\nSilence this occurance only by adding '{var}': ['{template}'] to the settings.SHOUTY_VARIABLE_BLACKLIST dictionary."
msg += "\nSilence this globally by adding '{var}': ['*'] to the settings.SHOUTY_VARIABLE_BLACKLIST dictionary."
msg = msg.format(
token=bit,
var=whole_var,
template=template_name,
closest_matches="', '".join(closest), # type: ignore
templates="', '".join(all_template_names),
)
exc = MissingVariable(
msg,
token=whole_var,
template_name=template_name,
all_template_names=all_template_names,
)
if context.template.engine.debug and exc_info:
exc_info["message"] = msg
exc.template_debug = exc_info
if not is_silenced(whole_var, template_name, blacklist, all_template_names):
raise exc
else:
# Let the VariableDoesNotExist bubble back up to whereever it's
# actually suppressed, to avoid having to decide wtf value to
# return ("", or None?)
raise e
def new_if_render(self, context):
# type: (IfNode, Context) -> Any
"""
Simple if cases in the template, like {% if x %}{% endif %} are already caught
by new_resolve_lookup it seems, but more complex cases like {% if x and y or z %}
are not, because of the way those conditionals are stacked up and nested.
Worse still, they're dynamically generated Operator classes which do not
exist at module scope, and where they do exist on the module scope, it's
as a closure over a lambda, so patching the eval method is pain.
Instead if we got back a falsy value (which is "" - no output to render)
we go to some lengths to extract all the individual nodes of all the conditions
(nested or otherwise) and error for any that don't exist, if the exception
is an instance of our special subclass.
{% if x %} should be fine.
{% if x and y %} will error on y if it is not in the context.
{% if x or y and z and 1 == 2 %} would error on z if it's not in the context, regardless of evaluation result.
"""
__traceback_hide__ = settings.DEBUG
whole_var = self.token.contents
# Attempt to handle the case where there's an {% if %} followed by an {% elif %} but no {% else %}
# Note to self: I always have access to the top of the node (self.token), so possibly can refactor
# some other places to parse less?
if (
len(self.conditions_nodelists) > 1
and self.conditions_nodelists[-1][0] is not None
):
blacklist = if_else_blacklist()
ignored_templates_for_this_var = blacklist.get(whole_var, [])
ignored_templates_for_any_var = blacklist.get(ANY_VARIABLE, [])
not_being_ignored = whole_var not in blacklist
has_per_template_ignores = (len(ignored_templates_for_this_var) > 0) or (
len(ignored_templates_for_any_var) > 0
)
if not_being_ignored or has_per_template_ignores:
try:
(
template_name,
exc_info,
all_template_names,
) = create_exception_with_template_debug(context, whole_var, self)
except Exception as e2:
logger.warning(
"failed to create template_debug information", exc_info=e2
)
# In case my code is terrible, and raises an exception, let's
# just carry on and let Django try for itself to set up relevant
# debug info
template_name = UNKNOWN_SOURCE
all_template_names = [template_name]
exc_info = {}
if context.template.engine.debug and exc_info is not None:
msg = (
"No `else` statement found for '{{% {ifnode} %}}{{% elif ... %}}{{% endif %}}' in '{template}'"
"\nSilence this by adding '{ifnode}': ['{template}'] to the settings.SHOUTY_VARIABLE_BLACKLIST dictionary.".format(
ifnode=whole_var, template=template_name
)
)
exc = MissingVariable(
msg,
token=whole_var,
template_name=template_name,
all_template_names=all_template_names,
)
exc_info["message"] = msg
exc.template_debug = exc_info
if not is_silenced(
whole_var,
exc.template_name,
blacklist,
exc.all_template_names,
):
raise exc
# I need to collect all the conditions from all the nodelists BEFORE calling
# the original render method, to allow for peeking at which nodelist was
# rendered. When exhaustive {% if %}{% elif %} checking occurs and FORCES
# an else condition, that else condition may something other than "", so requires
# knowing that the ELSE nodelist was the one which was rendered, whilst
# still collecting the individual conditions that made up all the if components
# to check which ones failed with a MissingVariable exception rather than just
# evaluating falsy...
conditions_seen = set() # type: Set[TemplateLiteral]
conditions = [] # type: List[TemplateLiteral]
def extract_first_second_from_branch(_cond):
# type: (Any) -> Iterator[TemplateLiteral]
first = getattr(_cond, "first", None)
second = getattr(_cond, "second", None)
if first is not None and first:
for subcond in extract_first_second_from_branch(first):
yield subcond
if second is not None and second:
for subcond in extract_first_second_from_branch(second):
yield subcond
if first is None and second is None:
yield _cond
for index, condition_nodelist in enumerate(self.conditions_nodelists, start=1):
condition, nodelist = condition_nodelist
if condition is not None:
for _cond in extract_first_second_from_branch(condition):
if _cond not in conditions_seen:
conditions.append(_cond)
conditions_seen.add(_cond)
for condition in conditions:
if hasattr(condition, "value") and hasattr(condition.value, "resolve"):
condition.value.resolve(context)
return old_if_render(self, context)
URL_BLACKLIST = (
# Admin login
("admin_password_reset", "password_reset_url"),
# Admin header (every page)
("django-admindocs-docroot", "docsroot"),
) # type: Tuple[Tuple[Text, Text], ...]
def url_blacklist():
# type: () -> Tuple[Tuple[Text, Text], ...]
# TODO: make this memoized/cached?
return URL_BLACKLIST + tuple(getattr(settings, "SHOUTY_URL_BLACKLIST", ()))
def new_url_render(self, context):
# type: (URLNode, Any) -> Any
"""
Call the original render method, and if it returns nothing AND has been
put into the context, raise an exception.
eg:
{% url '...' %} is fine. Will raise NoReverseMatch anyway.
{% url '...' as x %} is fine if ... resolves.
{% url '...' as x %} will now blow up if ... doesn't put something sensible
into the context (it should've thrown a NoReverseMatch)
"""
__traceback_hide__ = settings.DEBUG
value = old_url_render(self, context)
outvar = self.asvar
if outvar is not None and context[outvar] == "":
key = (str(self.view_name.var), str(outvar))
if key not in url_blacklist():
try:
(
template_name,
exc_info,
all_template_names,
) = create_exception_with_template_debug(context, outvar, self)
except Exception as e2:
logger.warning(
"failed to create template_debug information", exc_info=e2
)
# In case my code is terrible, and raises an exception, let's
# just carry on and let Django try for itself to set up relevant
# debug info
template_name = UNKNOWN_SOURCE
all_template_names = [template_name]
exc_info = {}
msg = "{{% url {token!s} ... as {asvar!s} %}} in template '{template} did not resolve.\nYou may silence this globally by adding {key!r} to settings.SHOUTY_URL_BLACKLIST".format(
token=self.view_name,
asvar=outvar,
key=key,
template=template_name,
)
exc = MissingVariable(
msg,
token=key,
template_name=template_name,
all_template_names=all_template_names,
)
if context.template.engine.debug and exc_info is not None:
exc_info["message"] = msg
exc.template_debug = exc_info
raise exc
return value
def patch(invalid_variables, invalid_urls):
# type: (bool, bool) -> bool
"""
Monkeypatch the Django Template Language's Variable class, replacing
the `_resolve_lookup` method with `new_resolve_lookup` in this module.
Also allows for turning on loud errors if using `{% url ... as outvar %}`
where the url resolved to nothing.
Calling it multiple times should be a no-op
"""
if not settings.DEBUG:
return False
if invalid_variables is True:
patched_var = getattr(Variable, "_shouty", False)
if patched_var is False:
Variable._resolve_lookup = new_resolve_lookup
Variable._shouty = True
# Provides exhaustive if/elif/else checking as well as all conditional
# in context checking ...
patched_if = getattr(IfNode, "_shouty", False)
if patched_if is False:
IfNode.render = new_if_render
IfNode._shouty = True
if invalid_urls is True:
patched_url = getattr(URLNode, "_shouty", False)
if patched_url is False:
URLNode.render = new_url_render
URLNode._shouty = True
return True
def check_user_blacklists(app_configs, **kwargs):
# type: (Any, **Any) -> List[checks.Error]
errors = []
user_blacklist = getattr(settings, "SHOUTY_VARIABLE_BLACKLIST", ())
if hasattr(user_blacklist, "items") and callable(user_blacklist.items):
for var, templates in user_blacklist.items():
if force_text(var) != var:
errors.append(
checks.Error(
"Expected key {!r} to be a string".format(var),
obj="settings.SHOUTY_VARIABLE_BLACKLIST",
)
)
if force_text(templates) == templates:
errors.append(
checks.Error(
"Key {} has it's list of templates as a string".format(var),
hint="Templates should be like: ('template.html', 'template2.html')",
obj="settings.SHOUTY_VARIABLE_BLACKLIST",
)
)
try:
template_count = len(templates)
except Exception:
errors.append(
checks.Error(
"Key {} has an unexpected templates defintion".format(var),
hint="The value for templates should be like: ('template.html', 'template2.html')",
obj="settings.SHOUTY_VARIABLE_BLACKLIST",
)
)
else:
if var == ANY_VARIABLE and template_count < 1:
errors.append(
checks.Error(
"Magic variable * has an unexpected templates defintion".format(
var
),
hint="Using * requires you to specify a specific template (or set of templates) to ignore",
obj="settings.SHOUTY_VARIABLE_BLACKLIST",
)
)
elif var == ANY_VARIABLE and ANY_TEMPLATE in templates:
errors.append(
checks.Error(
"Magic variable * has an unexpected templates defintion".format(
var
),
hint="Using * for both the variable and template isn't supported, use settings.SHOUTY_VARIABLES = False",
obj="settings.SHOUTY_VARIABLE_BLACKLIST",
)
)
elif template_count < 1:
errors.append(
checks.Error(
"Key {} has an unexpected templates defintion".format(var),
hint="There are no templates whitelisted, nor the magic '*' value",
obj="settings.SHOUTY_VARIABLE_BLACKLIST",
)
)
else:
if force_text(user_blacklist) == user_blacklist:
errors.append(
checks.Error(
"Setting appears to be a string",
hint="Should be a sequence or dictionary (eg: ['myvar', 'myvar2'])",
obj="settings.SHOUTY_VARIABLE_BLACKLIST",
)
)
try:
iter(user_blacklist)
except TypeError:
errors.append(
checks.Error(
"Setting doesn't appear to be a sequence",
hint="Should be a sequence or dictionary (eg: ['myvar', 'myvar2'])",
obj="settings.SHOUTY_VARIABLE_BLACKLIST",
)
)
else:
for var in user_blacklist:
if force_text(var) != var:
errors.append(
checks.Error(
"Expected {!r} to be a string".format(var),
obj="settings.SHOUTY_VARIABLE_BLACKLIST",
)
)
return errors
class Shout(AppConfig): # type: ignore
"""
Applies the patch automatically if enabled.
If `shouty` or `shouty.Shout` is added to INSTALLED_APPS only.
"""
name = "shouty"
def ready(self):
# type: () -> bool
logger.info("Applying shouty templates patch")
checks.register(check_user_blacklists, checks.Tags.templates)
return patch(
invalid_variables=getattr(settings, "SHOUTY_VARIABLES", True),
invalid_urls=getattr(settings, "SHOUTY_URLS", True),
)
default_app_config = "shouty.Shout"
if __name__ == "__main__":
import os
try:
import coverage
except ImportError:
sys.stdout.write("coverage not installed\n")
cov = None
else:
sys.stdout.write("using coverage\n")
cov = coverage.Coverage(
include=["shouty.py"], branch=True, check_preimported=True
)
cov.start()
from unittest import skipIf
from contextlib import contextmanager
from django.test import TestCase, SimpleTestCase, override_settings
from django.test.runner import DiscoverRunner
from django.views.debug import ExceptionReporter
from django.test.client import RequestFactory
from django import setup as django_setup, VERSION as DJANGO_VERSION
from django.conf import settings as test_settings
from django.utils.functional import SimpleLazyObject
EXTRA_INSTALLED_APPS = () # type: Tuple[Text, ...]
try:
import admin_honeypot
if DJANGO_VERSION[0:2] > (1, 9):
EXTRA_INSTALLED_APPS += ("admin_honeypot",)
except ImportError:
pass
try:
import crispy_forms
EXTRA_INSTALLED_APPS += ("crispy_forms",)
except ImportError:
pass
def urlpatterns():
# type: () -> Tuple[Any, ...]
try:
from django.urls import re_path, include
except ImportError:
from django.conf.urls import url as re_path, include
from django.contrib import admin
patterns = () # type: Tuple[Any, ...]
if "admin_honeypot" in EXTRA_INSTALLED_APPS:
patterns += (re_path(r"^admin_honeypot/", include("admin_honeypot.urls")),)
patterns += (
re_path(r"^admin/doc/", include("django.contrib.admindocs.urls")),
re_path(r"^admin/", admin.site.urls),
)
return patterns
if DJANGO_VERSION[0:2] <= (1, 9):
version_specific_settings = {
"MIDDLEWARE_CLASSES": [
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
]
}
else:
version_specific_settings = {
"MIDDLEWARE": [
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
]
}
test_settings.configure(
DEBUG=True,