codewatch-scan 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. codewatch/__init__.py +0 -0
  2. codewatch/__main__.py +14 -0
  3. codewatch/asgi.py +16 -0
  4. codewatch/settings.py +175 -0
  5. codewatch/urls.py +40 -0
  6. codewatch/wsgi.py +16 -0
  7. codewatch_scan-0.1.0.dist-info/METADATA +81 -0
  8. codewatch_scan-0.1.0.dist-info/RECORD +136 -0
  9. codewatch_scan-0.1.0.dist-info/WHEEL +5 -0
  10. codewatch_scan-0.1.0.dist-info/entry_points.txt +4 -0
  11. codewatch_scan-0.1.0.dist-info/licenses/LICENSE +21 -0
  12. codewatch_scan-0.1.0.dist-info/top_level.txt +2 -0
  13. core/__init__.py +0 -0
  14. core/analyzers/__init__.py +19 -0
  15. core/analyzers/accessibility.py +199 -0
  16. core/analyzers/base.py +192 -0
  17. core/analyzers/body_models.py +154 -0
  18. core/analyzers/codewatch_checks.py +394 -0
  19. core/analyzers/constant_branches.py +251 -0
  20. core/analyzers/containers.py +316 -0
  21. core/analyzers/coverage.py +131 -0
  22. core/analyzers/dependencies.py +347 -0
  23. core/analyzers/drf_serializers.py +65 -0
  24. core/analyzers/else_branches.py +106 -0
  25. core/analyzers/extra.py +400 -0
  26. core/analyzers/flask_resources.py +65 -0
  27. core/analyzers/inline_scripts.py +50 -0
  28. core/analyzers/jinja_sandboxes.py +63 -0
  29. core/analyzers/match_statements.py +148 -0
  30. core/analyzers/multi_tools.py +888 -0
  31. core/analyzers/php_template_sinks.py +444 -0
  32. core/analyzers/project_checks.py +150 -0
  33. core/analyzers/python_tools.py +333 -0
  34. core/analyzers/route_converters.py +237 -0
  35. core/analyzers/slices.py +94 -0
  36. core/analyzers/starred_targets.py +42 -0
  37. core/analyzers/stored_fields.py +386 -0
  38. core/analyzers/summaries.py +1387 -0
  39. core/analyzers/template_sinks.py +162 -0
  40. core/api.py +360 -0
  41. core/apps.py +6 -0
  42. core/benchmark.py +955 -0
  43. core/bundled/catalog/codewatch/rules/javascript-crypto.yml +224 -0
  44. core/bundled/catalog/codewatch/rules/javascript-injection.yml +116 -0
  45. core/bundled/catalog/codewatch/rules/javascript-taint.yml +1539 -0
  46. core/bundled/catalog/codewatch/rules/javascript-web.yml +562 -0
  47. core/bundled/catalog/codewatch/rules/php-web.yml +719 -0
  48. core/bundled/catalog/codewatch/rules/python-crypto.yml +203 -0
  49. core/bundled/catalog/codewatch/rules/python-django.yml +267 -0
  50. core/bundled/catalog/codewatch/rules/python-injection.yml +115 -0
  51. core/bundled/catalog/codewatch/rules/python-web.yml +3382 -0
  52. core/bundled/catalog/custom/mappings.json +360 -0
  53. core/bundled/catalog/custom/overrides.json +4 -0
  54. core/bundled/catalog/custom/rules/django-settings.yml +19 -0
  55. core/bundled/catalog/imported/changes.json +5 -0
  56. core/bundled/catalog/imported/docs.json +1143 -0
  57. core/bundled/catalog/imported/meta.json +54 -0
  58. core/bundled/catalog/imported/rules.json +85421 -0
  59. core/bundled/catalog/imported/standards.json +11191 -0
  60. core/bundled/tools/analyzers.lock +786 -0
  61. core/bundled/tools/axe-scan.mjs +45 -0
  62. core/bundled/tools/checkov.lock +2463 -0
  63. core/bundled/tools/codewatch-checks.mjs +99 -0
  64. core/bundled/tools/eslint-a11y.config.js +16 -0
  65. core/bundled/tools/eslint-quality.config.js +63 -0
  66. core/bundled/tools/eslint-typed.config.js +18 -0
  67. core/bundled/tools/package-lock.json +6102 -0
  68. core/bundled/tools/package.json +32 -0
  69. core/bundled/tools/rule-metadata.mjs +56 -0
  70. core/bundled/tools/semgrep.lock +1232 -0
  71. core/bundled/tools/stylelint.config.json +11 -0
  72. core/catalog/__init__.py +190 -0
  73. core/catalog/build.py +84 -0
  74. core/catalog/merge.py +122 -0
  75. core/catalog/sources.py +418 -0
  76. core/catalog/standards.py +119 -0
  77. core/catalog/update.py +99 -0
  78. core/catalog_views.py +115 -0
  79. core/client.py +645 -0
  80. core/collect.py +518 -0
  81. core/duplicates.py +60 -0
  82. core/fingerprint.py +25 -0
  83. core/folders.py +73 -0
  84. core/gate.py +77 -0
  85. core/git.py +149 -0
  86. core/jobs.py +86 -0
  87. core/management/__init__.py +0 -0
  88. core/management/commands/__init__.py +0 -0
  89. core/management/commands/addproject.py +40 -0
  90. core/management/commands/buildcatalog.py +15 -0
  91. core/management/commands/scan.py +74 -0
  92. core/management/commands/updatecatalog.py +14 -0
  93. core/mcp_server.py +140 -0
  94. core/middleware.py +17 -0
  95. core/migrations/0001_initial.py +115 -0
  96. core/migrations/0002_auth_tokens_a11y.py +60 -0
  97. core/migrations/0003_default_admin.py +43 -0
  98. core/migrations/0004_project_members.py +28 -0
  99. core/migrations/0005_uploads_and_sources.py +55 -0
  100. core/migrations/0006_thresholds.py +28 -0
  101. core/migrations/0007_also_reported_by.py +18 -0
  102. core/migrations/0008_new_code_period.py +18 -0
  103. core/migrations/0009_resolution_safe.py +18 -0
  104. core/migrations/0010_analysis_progress.py +18 -0
  105. core/migrations/0011_overall_gate_conditions.py +20 -0
  106. core/migrations/__init__.py +0 -0
  107. core/models.py +323 -0
  108. core/network.py +41 -0
  109. core/paths.py +29 -0
  110. core/ratings.py +67 -0
  111. core/runner.py +168 -0
  112. core/templates/core/account.html +30 -0
  113. core/templates/core/analysis.html +49 -0
  114. core/templates/core/base.html +121 -0
  115. core/templates/core/form_table.html +12 -0
  116. core/templates/core/gate_badge.html +1 -0
  117. core/templates/core/index.html +26 -0
  118. core/templates/core/issues.html +38 -0
  119. core/templates/core/login.html +13 -0
  120. core/templates/core/new_project.html +27 -0
  121. core/templates/core/password_change.html +10 -0
  122. core/templates/core/project.html +40 -0
  123. core/templates/core/rating.html +1 -0
  124. core/templates/core/ratings.html +32 -0
  125. core/templates/core/rule.html +33 -0
  126. core/templates/core/rules.html +42 -0
  127. core/templates/core/scan_progress.html +2 -0
  128. core/templates/core/settings.html +36 -0
  129. core/templates/core/source.html +15 -0
  130. core/templates/core/standards.html +30 -0
  131. core/templates/core/user_edit.html +15 -0
  132. core/templates/core/users.html +18 -0
  133. core/templatetags/__init__.py +0 -0
  134. core/templatetags/codewatch.py +42 -0
  135. core/tool_setup.py +68 -0
  136. core/views.py +564 -0
@@ -0,0 +1,42 @@
1
+ """Unstar starred assignment targets (`[*parts, ext] = x` -> `[parts , ext] = x`) for Semgrep's taint.
2
+
3
+ Semgrep OSS taints every name an unpacking assigns from tainted data, except a starred one: `head, *rest =
4
+ request.path.split("/")` leaves rest clean. Dagster's log download (GHSA-q93c) unpacked the request path that way
5
+ before the file response. Without the star the copy still parses and rest is tainted like head. The copy is only
6
+ ever scanned, never run, and the name moves left over its star (a space after it), so the line keeps its length and
7
+ indentation: blanking the star instead would indent `*parts, ext = ...` at the start of a statement.
8
+ """
9
+ import ast
10
+
11
+
12
+ def starred_targets(tree):
13
+ """(line, column, name) of the star of each starred name in an assignment or for-loop target."""
14
+ targets = []
15
+ for node in ast.walk(tree):
16
+ if isinstance(node, ast.Assign):
17
+ targets += node.targets
18
+ elif isinstance(node, (ast.For, ast.AsyncFor, ast.comprehension)):
19
+ targets.append(node.target)
20
+ return [(node.lineno, node.col_offset, node.value.id) for target in targets for node in ast.walk(target)
21
+ if isinstance(node, ast.Starred) and isinstance(node.value, ast.Name)]
22
+
23
+
24
+ def unstar_targets(source):
25
+ """The source with starred targets unstarred, or None if it has none (or doesn't parse)."""
26
+ if "*" not in source:
27
+ return None
28
+ try:
29
+ stars = starred_targets(ast.parse(source))
30
+ except (SyntaxError, ValueError):
31
+ return None
32
+ if not stars:
33
+ return None
34
+ lines = source.splitlines(keepends=True)
35
+ for row, col, name in stars:
36
+ line = lines[row - 1]
37
+ # ast columns count UTF-8 bytes; a line with other characters before the star is left alone.
38
+ if line[col:col + 1 + len(name)] != "*" + name:
39
+ continue
40
+ lines[row - 1] = line[:col] + name + " " + line[col + 1 + len(name):]
41
+ result = "".join(lines)
42
+ return None if result == source else result
@@ -0,0 +1,386 @@
1
+ """Django model fields the project fills from request data, read back as XSS sources (stored XSS).
2
+
3
+ A request value saved in one view and printed by another isn't a flow Semgrep can follow: the database is between
4
+ them. Making every database read a source would flag every page; matching fields by name alone is too coarse
5
+ (PLAN.md step 43: calibre-web writes `shelf.name` from requests, which says nothing about `author.name`). So this
6
+ works per model. It reads the project with ast for:
7
+
8
+ - each model's text fields: CharField, TextField, file and similar fields without `choices=` (a number, a date, a
9
+ foreign key or a fixed choice can't carry markup);
10
+ - the fields of each model the project writes from request data: `Model.objects.create(field=...)` or
11
+ `Model(field=...)` with a value taken from the request, `obj.field = ...` on an object made or looked up from
12
+ that model, and the fields of a ModelForm or DRF ModelSerializer for it (both save what the client sent);
13
+
14
+ and adds, to the XSS rule only, a source for reads of those fields where the model is known: `obj.field` in the
15
+ methods of a ModelAdmin registered for the model, `self.field` in the model's own methods, and `x.field` after
16
+ `x = Model.objects...(...)` or `x = get_object_or_404(Model, ...)`. A field the project never writes from a
17
+ request stays out, so its unescaped output is left to the hotspot rules.
18
+ """
19
+ import ast
20
+ import re
21
+
22
+ from .base import python_tree
23
+
24
+ RULE = "codewatch.python.web.xss"
25
+ FIELD = "$FIELD"
26
+ TEXT_FIELDS = {"CharField", "TextField", "EmailField", "URLField", "SlugField", "FileField", "ImageField",
27
+ "FilePathField", "JSONField", "GenericIPAddressField"}
28
+ MODEL_BASE_RE = re.compile(r"Model$")
29
+ FORM_BASE_RE = re.compile(r"^(ModelForm|ModelSerializer|HyperlinkedModelSerializer)$")
30
+ REQUEST_NAMES = {"request", "req"}
31
+ # A file field's .url is the storage's URL for the stored name, percent-encoded (Django's filepath_to_uri), so it
32
+ # can't break out of an HTML attribute: mark_safe(f'<img src="{self.image.url}">').
33
+ FILE_FIELDS = {"FileField", "ImageField"}
34
+
35
+
36
+ def last_name(node):
37
+ """`models.Model` -> Model, `forms.ModelForm[X]` -> ModelForm, `Foo` -> Foo."""
38
+ if isinstance(node, ast.Subscript):
39
+ node = node.value
40
+ if isinstance(node, ast.Attribute):
41
+ return node.attr
42
+ return getattr(node, "id", "")
43
+
44
+
45
+ def text_fields(cls, kinds=TEXT_FIELDS):
46
+ """Names of a model class's text fields (or fields of the given kinds) without fixed choices."""
47
+ found = set()
48
+ for item in cls.body:
49
+ if not (isinstance(item, ast.Assign) and len(item.targets) == 1 and isinstance(item.targets[0], ast.Name)
50
+ and isinstance(item.value, ast.Call)):
51
+ continue
52
+ if last_name(item.value.func) in kinds and not any(k.arg == "choices" for k in item.value.keywords):
53
+ found.add(item.targets[0].id)
54
+ return found
55
+
56
+
57
+ def is_signed_in_user(node):
58
+ """request.user / self.request.user: the account the server signed in, not what the client sent."""
59
+ return (isinstance(node, ast.Attribute) and node.attr == "user"
60
+ and (getattr(node.value, "id", "") in REQUEST_NAMES
61
+ or (isinstance(node.value, ast.Attribute) and node.value.attr == "request")))
62
+
63
+
64
+ def is_self_request(node):
65
+ return isinstance(node, ast.Attribute) and node.attr == "request" and getattr(node.value, "id", "") == "self"
66
+
67
+
68
+ def passes_request(node, names, returners):
69
+ """A call to a project function that hands request data back, given request data."""
70
+ return (isinstance(node, ast.Call) and last_name(node.func) in returners
71
+ and any(mentions(a, names, returners) for a in [*node.args, *(k.value for k in node.keywords)]))
72
+
73
+
74
+ def mentions(node, names, returners=frozenset()):
75
+ """Whether node reads the request (request.x, self.request.x), one of names, or calls a project function
76
+ that hands request data back (returners) with request data."""
77
+ if is_signed_in_user(node):
78
+ return False
79
+ if isinstance(node, ast.Name):
80
+ return node.id in REQUEST_NAMES or node.id in names
81
+ if is_self_request(node) or passes_request(node, names, returners):
82
+ return True
83
+ return any(mentions(child, names, returners) for child in ast.iter_child_nodes(node))
84
+
85
+
86
+ def manager_model(func, models):
87
+ """The model of a Model.objects... chain, or None."""
88
+ node = func
89
+ while isinstance(node, (ast.Attribute, ast.Call)):
90
+ node = node.func if isinstance(node, ast.Call) else node.value
91
+ if isinstance(node, ast.Attribute) and node.attr == "objects" and last_name(node.value) in models:
92
+ return last_name(node.value)
93
+ return None
94
+
95
+
96
+ def model_of(call, models):
97
+ """The model a call makes or looks up: Model(...), Model.objects.x(...)..., get_object_or_404(Model, ...)."""
98
+ if not isinstance(call, ast.Call):
99
+ return None
100
+ func = call.func
101
+ if isinstance(func, ast.Name) and func.id in models:
102
+ return func.id
103
+ if last_name(func) in ("get_object_or_404", "get_list_or_404") and call.args:
104
+ return last_name(call.args[0]) if last_name(call.args[0]) in models else None
105
+ return manager_model(func, models)
106
+
107
+
108
+ class Flow:
109
+ """What one function does with request data, built statement by statement (function_flow)."""
110
+
111
+ def __init__(self, models, seeded, returners):
112
+ self.models, self.returners = models, returners
113
+ self.tainted, self.objects, self.writes = set(seeded), {}, set()
114
+
115
+ def reads(self, node):
116
+ return mentions(node, self.tainted, self.returners)
117
+
118
+ def loops(self, func):
119
+ """A for loop over request data taints its target names."""
120
+ for node in ast.walk(func):
121
+ if isinstance(node, ast.For) and self.reads(node.iter):
122
+ self.tainted.update(n.id for n in ast.walk(node.target) if isinstance(n, ast.Name))
123
+
124
+ def call_writes(self, value):
125
+ """Model(field=...) or Model.objects.create(field=...) with request data."""
126
+ for call in (n for n in ast.walk(value) if isinstance(n, ast.Call)):
127
+ if (model := model_of(call, self.models)) is not None:
128
+ self.writes.update((model, k.arg) for k in call.keywords if k.arg and self.reads(k.value))
129
+
130
+ def name_target(self, name, value):
131
+ if (model := model_of(value, self.models)) is not None:
132
+ self.objects[name] = model
133
+ elif self.reads(value):
134
+ self.tainted.add(name)
135
+
136
+ def assign(self, target, value):
137
+ if isinstance(target, ast.Name):
138
+ self.name_target(target.id, value)
139
+ elif isinstance(target, ast.Tuple):
140
+ if self.reads(value):
141
+ self.tainted.update(n.id for n in ast.walk(target) if isinstance(n, ast.Name))
142
+ elif (isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name)
143
+ and target.value.id in self.objects and self.reads(value)):
144
+ self.writes.add((self.objects[target.value.id], target.attr))
145
+
146
+ def statement(self, node):
147
+ value = node.value
148
+ if value is None:
149
+ return
150
+ self.call_writes(value)
151
+ targets = node.targets if isinstance(node, ast.Assign) else [getattr(node, "target", None)]
152
+ for target in filter(None, targets):
153
+ self.assign(target, value)
154
+
155
+ def calls(self, func):
156
+ """{project function name: argument positions and keywords given request data}."""
157
+ calls = {}
158
+ for call in (n for n in ast.walk(func) if isinstance(n, ast.Call)):
159
+ hit = {i for i, a in enumerate(call.args) if self.reads(a)}
160
+ hit |= {k.arg for k in call.keywords if k.arg and self.reads(k.value)}
161
+ if hit:
162
+ calls.setdefault(last_name(call.func), set()).update(hit)
163
+ return calls
164
+
165
+ def returns(self, func):
166
+ return any(isinstance(n, ast.Return) and n.value is not None and self.reads(n.value) for n in ast.walk(func))
167
+
168
+
169
+ def function_flow(func, models, seeded=(), returners=frozenset()):
170
+ """What a function does with request data: ({(model, field)} it fills, {name: tainted argument positions and
171
+ keywords} for the project functions it calls, whether it returns request data). seeded: its parameters that
172
+ callers fill with request data."""
173
+ flow = Flow(models, seeded, returners)
174
+ flow.loops(func)
175
+ # Assignments in source order, so a value read from the request earlier taints what it's copied into.
176
+ for node in sorted((n for n in ast.walk(func) if isinstance(n, (ast.Assign, ast.AnnAssign, ast.Expr))),
177
+ key=lambda n: (n.lineno, n.col_offset)):
178
+ flow.statement(node)
179
+ return flow.writes, flow.calls(func), flow.returns(func)
180
+
181
+
182
+ def parameters(func):
183
+ """{position or name: parameter name}, positions counted as a caller passes them (self/cls skipped)."""
184
+ names = [a.arg for a in [*func.args.posonlyargs, *func.args.args]]
185
+ if names and names[0] in ("self", "cls"):
186
+ names = names[1:]
187
+ out = dict(enumerate(names))
188
+ out.update({n: n for n in names + [a.arg for a in func.args.kwonlyargs]})
189
+ return out
190
+
191
+
192
+ def defined_once(functions):
193
+ """{name: function} for the names defined once in the project."""
194
+ by_name = {}
195
+ for func in functions:
196
+ by_name.setdefault(func.name, []).append(func)
197
+ return {name: funcs[0] for name, funcs in by_name.items() if len(funcs) == 1}
198
+
199
+
200
+ def seed_callees(calls, unique, seeded):
201
+ """Mark the parameters of the project functions called with request data; whether any were new."""
202
+ changed = False
203
+ for name, hit in calls.items():
204
+ if name not in unique:
205
+ continue
206
+ callee = unique[name]
207
+ params = parameters(callee)
208
+ if new := {params[h] for h in hit if h in params} - seeded.get(id(callee), set()):
209
+ seeded.setdefault(id(callee), set()).update(new)
210
+ changed = True
211
+ return changed
212
+
213
+
214
+ def project_writes(functions, models):
215
+ """{(model, field)} the project fills from request data, following request data into the parameters of the
216
+ project's functions and back out of their returns. Only names defined once in the project are followed, so
217
+ two save() methods don't mix."""
218
+ unique = defined_once(functions)
219
+ seeded, returners, writes = {}, set(), set()
220
+ for _ in range(6):
221
+ changed, writes = False, set()
222
+ for func in functions:
223
+ found, calls, returns = function_flow(func, models, seeded.get(id(func), ()), frozenset(returners))
224
+ writes |= found
225
+ if returns and func.name in unique and func.name not in returners:
226
+ returners.add(func.name)
227
+ changed = True
228
+ changed |= seed_callees(calls, unique, seeded)
229
+ if not changed:
230
+ break
231
+ return writes
232
+
233
+
234
+ def meta_values(cls):
235
+ """{name: value} assigned in a form's inner Meta class, or None if it has none."""
236
+ meta = next((i for i in cls.body if isinstance(i, ast.ClassDef) and i.name == "Meta"), None)
237
+ if meta is None:
238
+ return None
239
+ return {t.id: i.value for i in meta.body if isinstance(i, ast.Assign) for t in i.targets if isinstance(t, ast.Name)}
240
+
241
+
242
+ def string_items(node):
243
+ return {e.value for e in node.elts if isinstance(e, ast.Constant) and isinstance(e.value, str)}
244
+
245
+
246
+ def declared_fields(fields, model_fields):
247
+ """Meta.fields as names: '__all__' is every field; None for anything else."""
248
+ if isinstance(fields, ast.Constant) and fields.value == "__all__":
249
+ return set(model_fields)
250
+ if isinstance(fields, (ast.List, ast.Tuple)):
251
+ return string_items(fields)
252
+ return None
253
+
254
+
255
+ def form_fields(cls, models):
256
+ """{(model, field)} a ModelForm or ModelSerializer saves: its Meta.fields ('__all__' is every field)."""
257
+ values = meta_values(cls)
258
+ if not values or "model" not in values:
259
+ return set()
260
+ model = last_name(values["model"])
261
+ if model not in models:
262
+ return set()
263
+ names = declared_fields(values.get("fields"), models[model])
264
+ if names is None:
265
+ return set()
266
+ excluded = values.get("exclude")
267
+ if isinstance(excluded, (ast.List, ast.Tuple)):
268
+ names -= {e.value for e in excluded.elts if isinstance(e, ast.Constant)}
269
+ return {(model, name) for name in names}
270
+
271
+
272
+ def decorated_admin(node, models):
273
+ """{admin class: model} from @admin.register(Model) on a class."""
274
+ registered = [last_name(arg) for dec in node.decorator_list
275
+ if isinstance(dec, ast.Call) and last_name(dec.func) == "register"
276
+ for arg in dec.args if last_name(arg) in models]
277
+ return {node.name: registered[-1]} if registered else {}
278
+
279
+
280
+ def admin_models(tree, models):
281
+ """{admin class name: model} from @admin.register(Model) and admin.site.register(Model, AdminClass)."""
282
+ found = {}
283
+ for node in ast.walk(tree):
284
+ if isinstance(node, ast.ClassDef):
285
+ found |= decorated_admin(node, models)
286
+ elif (isinstance(node, ast.Call) and last_name(node.func) == "register" and len(node.args) >= 2
287
+ and last_name(node.args[0]) in models):
288
+ found[last_name(node.args[1])] = last_name(node.args[0])
289
+ return found
290
+
291
+
292
+ def is_model(node):
293
+ return any(MODEL_BASE_RE.search(last_name(b)) for b in node.bases) and not is_form(node)
294
+
295
+
296
+ def is_form(node):
297
+ return any(FORM_BASE_RE.search(last_name(b)) for b in node.bases)
298
+
299
+
300
+ def model_classes(trees):
301
+ """({model: its text fields}, {model: its file fields}) for models with text fields."""
302
+ models, files = {}, {}
303
+ for node in (n for tree in trees for n in ast.walk(tree) if isinstance(n, ast.ClassDef) and is_model(n)):
304
+ models.setdefault(node.name, set()).update(text_fields(node))
305
+ files.setdefault(node.name, set()).update(text_fields(node, FILE_FIELDS))
306
+ return {m: f for m, f in models.items() if f}, files
307
+
308
+
309
+ def project_written(trees, models):
310
+ """({(model, field)} written from request data, {admin class: model})."""
311
+ writes, admins, functions = set(), {}, []
312
+ for tree in trees:
313
+ admins.update(admin_models(tree, models))
314
+ for node in ast.walk(tree):
315
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
316
+ functions.append(node)
317
+ elif isinstance(node, ast.ClassDef) and is_form(node):
318
+ writes |= form_fields(node, models)
319
+ return writes | project_writes(functions, models), admins
320
+
321
+
322
+ def stored_fields(texts):
323
+ """({model: request-written text fields}, {admin class: model}, {model: its file fields}) for the project's
324
+ Python sources."""
325
+ trees = [tree for tree in map(python_tree, texts) if tree is not None]
326
+ models, files = model_classes(trees)
327
+ if not models:
328
+ return {}, {}, {}
329
+ writes, admins = project_written(trees, models)
330
+ stored = {}
331
+ for model, field in writes:
332
+ if field in models.get(model, ()):
333
+ stored.setdefault(model, set()).add(field)
334
+ return stored, {a: m for a, m in admins.items() if m in stored}, stored_files(files, stored)
335
+
336
+
337
+ def stored_files(files, stored):
338
+ """{model: its request-written file fields}."""
339
+ return {m: f & stored[m] for m, f in files.items() if m in stored and f & stored[m]}
340
+
341
+
342
+ def field_regex(fields):
343
+ return "^(" + "|".join(sorted(map(re.escape, fields))) + ")$"
344
+
345
+
346
+ def sources(stored, admins):
347
+ out = []
348
+ for admin, model in sorted(admins.items()):
349
+ out.append({"patterns": [
350
+ {"pattern-inside": f"class {admin}(...):\n ...\n"},
351
+ {"pattern-inside": "def $F(self, $OBJ, ...):\n ...\n"},
352
+ {"pattern": "$OBJ.$FIELD"},
353
+ {"metavariable-regex": {"metavariable": FIELD, "regex": field_regex(stored[model])}},
354
+ ]})
355
+ for model, fields in sorted(stored.items()):
356
+ out.append({"patterns": [
357
+ {"pattern-inside": f"class {model}(...):\n ...\n"},
358
+ {"pattern": "self.$FIELD"},
359
+ {"metavariable-regex": {"metavariable": FIELD, "regex": field_regex(fields)}},
360
+ ]})
361
+ out.append({"patterns": [
362
+ {"pattern-either": [
363
+ {"pattern-inside": f"$X = {model}.objects.$Q(...)\n...\n"},
364
+ {"pattern-inside": f"$X = {model}.objects.$Q(...).$R(...)\n...\n"},
365
+ {"pattern-inside": f"$X = get_object_or_404({model}, ...)\n...\n"},
366
+ {"pattern-inside": f"for $X in {model}.objects.$Q(...):\n ...\n"},
367
+ {"pattern-inside": f"for $X in {model}.objects.$Q(...).$R(...):\n ...\n"},
368
+ ]},
369
+ {"pattern": "$X.$FIELD"},
370
+ {"metavariable-regex": {"metavariable": FIELD, "regex": field_regex(fields)}},
371
+ ]})
372
+ return out
373
+
374
+
375
+ def with_stored_sources(rules, texts):
376
+ """The rules, with sources for request-written model fields on the Python XSS rule."""
377
+ stored, admins, files = stored_fields(texts)
378
+ if not stored:
379
+ return rules
380
+ extra = sources(stored, admins)
381
+ names = set().union(*files.values()) if files else set()
382
+ url = [{"patterns": [{"pattern": "$X.$FIELD.url"},
383
+ {"metavariable-regex": {"metavariable": FIELD, "regex": field_regex(names)}}]}] if names else []
384
+ return [{**rule, "pattern-sources": [*rule["pattern-sources"], *extra],
385
+ "pattern-sanitizers": [*rule.get("pattern-sanitizers", []), *url]} if rule.get("id") == RULE else rule
386
+ for rule in rules]