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,418 @@
1
+ """Rule collectors, one per analyzer. Each reads the installed tool's own metadata (or a free online source).
2
+
3
+ A collected rule may carry "_doc" (Markdown explaining what's wrong and how to fix it, with examples) and
4
+ "_same_as" (IDs of rules in other tools that perform the same check); build.py moves those into docs.json
5
+ and the duplicate index. Documentation is only copied from permissively licensed tools.
6
+ """
7
+ import inspect
8
+ import json
9
+ import re
10
+ import subprocess
11
+ import tempfile
12
+ import urllib.request
13
+ from concurrent.futures import ThreadPoolExecutor
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+
17
+ import defusedxml.ElementTree as ET
18
+ from markdown_it import MarkdownIt
19
+
20
+ from ..analyzers.accessibility import HTML_VALIDATE_CONFIG
21
+ from ..analyzers.base import (
22
+ ACCESSIBILITY,
23
+ BLOCKER,
24
+ BUG,
25
+ CODE_SMELL,
26
+ HOTSPOT,
27
+ MAJOR,
28
+ MINOR,
29
+ TOOLS_DIR,
30
+ VULNERABILITY,
31
+ by_prefix,
32
+ isolated_tool,
33
+ node_tool,
34
+ tool_path,
35
+ )
36
+ from ..analyzers.extra import eslint_classify
37
+ from ..analyzers.multi_tools import CPPCHECK_NOISE, CPPCHECK_SEVERITY, SEMGREP_SEVERITY, semgrep_type
38
+ from ..analyzers.python_tools import BANDIT_SEVERITY, RUFF_EXTEND_IGNORE, RUFF_RULES
39
+
40
+ PYTHON, JS, C, HTML, CSS, WEB, IAC, ANY = "python", "javascript", "c/c++", "html", "css", "web", "iac", "any"
41
+ # Tool names, not secrets: detect-secrets matches the word "secret".
42
+ BANDIT, ESLINT, DETECT_SECRETS = "bandit", "eslint", "detect-secrets" # pragma: allowlist secret
43
+ VARIES = "varies" # a tool whose findings each carry their own severity
44
+ SEMGREP_PACK_URL = "https://semgrep.dev/c/p/default"
45
+ ESLINT_DOC_URL = "https://raw.githubusercontent.com/eslint/eslint/main/docs/src/rules/{}.md"
46
+ CWE_RE = re.compile(r"CWE-(\d+)")
47
+ MARKDOWN = MarkdownIt("commonmark")
48
+ BANDIT_DOC_RE = re.compile(r"/(b\d{3})[_-]", re.IGNORECASE)
49
+ JS_LANGS = {"javascript", "typescript", "js", "ts"}
50
+
51
+
52
+ def fetch(url, timeout=120):
53
+ req = urllib.request.Request(url, headers={"User-Agent": "codewatch-catalog"})
54
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
55
+ return resp.read()
56
+
57
+
58
+ def run(*args, cwd=None):
59
+ return subprocess.run(list(args), capture_output=True, text=True, check=False, cwd=cwd).stdout
60
+
61
+
62
+ def humanize(name):
63
+ words = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", " ", name.replace("-", " ").replace("_", " ")).split()
64
+ return " ".join(words).capitalize() if words else name
65
+
66
+
67
+ @dataclass
68
+ class RuleSpec:
69
+ tool: str
70
+ code: str
71
+ title: str
72
+ languages: list
73
+ type: str
74
+ severity: str
75
+ license_: str
76
+ summary: str = ""
77
+ docs: str = ""
78
+ refs: list = field(default_factory=list)
79
+ cwe: list = field(default_factory=list)
80
+ wcag: list = field(default_factory=list)
81
+ owasp: list = field(default_factory=list)
82
+ doc: str | None = None
83
+ same_as: list = field(default_factory=list)
84
+
85
+ def entry(self):
86
+ entry = {
87
+ "id": f"{self.tool}/{self.code}", "tool": self.tool, "code": self.code, "title": self.title,
88
+ "languages": list(self.languages), "type": self.type, "severity": self.severity,
89
+ "summary": self.summary, "docs": self.docs, "license": self.license_, "references": list(self.refs),
90
+ "cwe": sorted(set(self.cwe)), "wcag": sorted(set(self.wcag)), "owasp": list(self.owasp),
91
+ }
92
+ if self.doc:
93
+ entry["_doc"] = self.doc
94
+ if self.same_as:
95
+ entry["_same_as"] = list(self.same_as)
96
+ return entry
97
+
98
+
99
+ def rule(*args, **fields):
100
+ """Catalogue entry: tool, code, title, languages, type, severity, then keyword fields of RuleSpec."""
101
+ return RuleSpec(*args, **fields).entry()
102
+
103
+
104
+ def link_tokens(text):
105
+ """(href, label) for each Markdown link, via the parser rather than a regex."""
106
+ for block in MARKDOWN.parse(text or ""):
107
+ children = block.children or []
108
+ for i, tok in enumerate(children):
109
+ if tok.type == "link_open":
110
+ following = children[i + 1] if i + 1 < len(children) else None
111
+ yield str(tok.attrGet("href") or ""), following.content if following and following.type == "text" else ""
112
+
113
+
114
+ def links_in(text):
115
+ """External links in Markdown documentation."""
116
+ seen, out = set(), []
117
+ for url, label in link_tokens(text):
118
+ if url.startswith(("http://", "https://")) and url not in seen:
119
+ seen.add(url)
120
+ out.append({"label": label or url, "url": url})
121
+ return out
122
+
123
+
124
+ # --- Python ---------------------------------------------------------------------------------------------
125
+
126
+
127
+ def ruff():
128
+ data = json.loads(run(tool_path("ruff"), "rule", "--all", "--output-format", "json") or "[]")
129
+ out = []
130
+ for r in data:
131
+ if not r.get("code") or r["code"] in RUFF_EXTEND_IGNORE:
132
+ continue
133
+ severity, type_ = by_prefix(r["code"], RUFF_RULES, (MINOR, CODE_SMELL))
134
+ # flake8-bandit codes mirror bandit's: S105 is B105.
135
+ same = [f"bandit/B{r['code'][1:]}"] if re.fullmatch(r"S\d{3}", r["code"]) else []
136
+ out.append(rule("ruff", r["code"], humanize(r["name"]), [PYTHON], type_, severity, license_="MIT (ruff)",
137
+ summary=r["summary"], docs=f"https://docs.astral.sh/ruff/rules/{r['name']}/",
138
+ refs=links_in(r.get("explanation")), doc=r.get("explanation"), same_as=same))
139
+ return out
140
+
141
+
142
+ def rst_to_markdown(doc):
143
+ """Bandit docstrings are reStructuredText; enough conversion for headings and code blocks to read well."""
144
+ out, in_code = [], False
145
+ for line in doc.splitlines():
146
+ if line.strip().startswith(".. code-block::"):
147
+ out.append("```")
148
+ in_code = True
149
+ continue
150
+ if in_code and line and not line.startswith((" ", "\t")):
151
+ out.append("```")
152
+ in_code = False
153
+ if line.strip().startswith((".. seealso::", ".. versionadded::", ".. versionchanged::")):
154
+ continue
155
+ out.append(line[4:] if in_code and line.startswith(" ") else line)
156
+ if in_code:
157
+ out.append("```")
158
+ text = "\n".join(out).replace(":Example:", "**Example:**")
159
+ return re.sub(r"^\*\*B\d{3}:.*?\*\*\s*", "", text.strip())
160
+
161
+
162
+ def bandit():
163
+ from bandit.core import extension_loader, issue
164
+
165
+ manager = extension_loader.MANAGER
166
+ out = [bandit_plugin(p, issue) for p in manager.plugins]
167
+ out += [bandit_blacklist(bid, b) for bid, b in sorted(manager.blacklist_by_id.items())]
168
+ return out
169
+
170
+
171
+ def bandit_plugin(plugin, issue):
172
+ fn = plugin.plugin
173
+ module = inspect.getmodule(fn)
174
+ source = inspect.getsource(module) if module else ""
175
+ cwes = {getattr(issue.Cwe, n) for n in re.findall(r"cwe=issue\.Cwe\.(\w+)", source)} - {0}
176
+ doc = inspect.getdoc(fn) or ""
177
+ paragraphs = [p for p in doc.split("\n\n")[1:] if p and not p.startswith(("..", ":"))]
178
+ return rule(BANDIT, f"{fn._test_id}:{plugin.name}", humanize(plugin.name), [PYTHON], HOTSPOT, VARIES,
179
+ license_="Apache-2.0 (bandit)", summary=" ".join(paragraphs[0].split())[:400] if paragraphs else "",
180
+ docs=f"https://bandit.readthedocs.io/en/latest/plugins/{fn._test_id.lower()}_{plugin.name}.html",
181
+ cwe=cwes, doc=rst_to_markdown(doc), refs=links_in(doc))
182
+
183
+
184
+ def bandit_blacklist(bid, b):
185
+ return rule(BANDIT, f"{bid}:blacklist", humanize(b["name"]), [PYTHON], HOTSPOT,
186
+ BANDIT_SEVERITY.get(b.get("level", "MEDIUM"), MINOR), license_="Apache-2.0 (bandit)",
187
+ summary=b["message"], docs="https://bandit.readthedocs.io/en/latest/blacklists/",
188
+ cwe=[b["cwe"]] if b.get("cwe") else [],
189
+ doc=f"{b['message']}\n\nFlagged calls and imports: " + ", ".join(f"`{q}`" for q in b["qualnames"]))
190
+
191
+
192
+ def basedpyright():
193
+ binary = tool_path("basedpyright")
194
+ bundle = next(Path(binary).resolve().parents[1].glob(
195
+ "lib/python*/site-packages/basedpyright/dist/pyright.js"), None) if binary else None
196
+ names = sorted(set(re.findall(r'"(report[A-Z][A-Za-z]+)"', bundle.read_text(errors="replace")))) if bundle else []
197
+ return [rule("basedpyright", n, humanize(n.removeprefix("report")), [PYTHON], BUG, MAJOR,
198
+ license_="MIT (basedpyright)",
199
+ docs=f"https://docs.basedpyright.com/latest/configuration/config-files/#{n}")
200
+ for n in names]
201
+
202
+
203
+ def detect_secrets():
204
+ kinds = ", ".join(humanize(n.removesuffix("Detector")) for n in run(
205
+ tool_path(DETECT_SECRETS) or DETECT_SECRETS, "scan", "--list-all-plugins").split())
206
+ return [rule(DETECT_SECRETS, "hard-coded-secret", "Hard-coded secret or API key", [ANY], VULNERABILITY,
207
+ BLOCKER, license_="Apache-2.0 (detect-secrets)",
208
+ summary=f"Detects: {kinds}. Matches found only by entropy or keyword are reported as security "
209
+ "hotspots.", docs="https://github.com/Yelp/detect-secrets#currently-supported-plugins")]
210
+
211
+
212
+ def single():
213
+ return [
214
+ rule("radon", "cyclomatic-complexity", "Function too complex (cyclomatic complexity)", [PYTHON],
215
+ CODE_SMELL, MAJOR, license_="MIT (radon)", summary="Too many independent paths through one function.",
216
+ docs="https://radon.readthedocs.io/en/latest/intro.html#cyclomatic-complexity",
217
+ refs=[{"label": "McCabe, A Complexity Measure (IEEE TSE, 1976)",
218
+ "url": "https://doi.org/10.1109/TSE.1976.233837"},
219
+ {"label": "NIST SP 500-235: Structured Testing",
220
+ "url": "https://www.nist.gov/publications/structured-testing-testing-methodology-using-cyclomatic-complexity-metric"}]),
221
+ rule("lizard", "cyclomatic-complexity", "Function too complex (cyclomatic complexity)", [JS, C],
222
+ CODE_SMELL, MAJOR, license_="MIT (lizard)", summary="Too many independent paths through one function.",
223
+ docs="https://github.com/terryyin/lizard"),
224
+ rule("complexipy", "cognitive-complexity", "Function hard to follow (cognitive complexity)", [PYTHON],
225
+ CODE_SMELL, MAJOR, license_="MIT (complexipy)",
226
+ summary="Nesting and breaks in linear control flow make code hard to read.",
227
+ docs="https://github.com/rohaquinlop/complexipy",
228
+ refs=[{"label": "G. Ann Campbell, Cognitive Complexity (2018, ACM TechDebt)",
229
+ "url": "https://doi.org/10.1145/3194164.3194186"}]),
230
+ rule("jscpd", "duplicated-block", "Duplicated code block", [ANY], CODE_SMELL, MINOR,
231
+ license_="MIT (jscpd)", summary="The same block of code appears in more than one place.",
232
+ docs="https://github.com/kucherenko/jscpd"),
233
+ rule("pip-audit", "vulnerable-dependency", "Dependency with a known vulnerability", [PYTHON],
234
+ VULNERABILITY, VARIES, license_="Apache-2.0 (pip-audit)",
235
+ summary="A dependency has a published advisory (severity taken from the advisory).",
236
+ docs="https://github.com/pypa/pip-audit", cwe=[1395], owasp=["A03:2025"],
237
+ refs=[{"label": "OSV vulnerability database", "url": "https://osv.dev"},
238
+ {"label": "PyPA Advisory Database", "url": "https://github.com/pypa/advisory-database"}]),
239
+ rule("osv", "vulnerable-dependency", "Dependency with a known vulnerability", [JS],
240
+ VULNERABILITY, VARIES, license_="CC-BY-4.0 (OSV data)",
241
+ summary="A package version pinned in package-lock.json, yarn.lock or pnpm-lock.yaml has a published "
242
+ "advisory (severity taken from the advisory).",
243
+ docs="https://google.github.io/osv.dev/post-v1-querybatch/", cwe=[1395], owasp=["A03:2025"],
244
+ refs=[{"label": "OSV vulnerability database", "url": "https://osv.dev"},
245
+ {"label": "GitHub Advisory Database", "url": "https://github.com/advisories"}]),
246
+ ]
247
+
248
+
249
+ # --- C/C++ and infrastructure ---------------------------------------------------------------------------
250
+
251
+
252
+ def cppcheck():
253
+ path = tool_path("cppcheck")
254
+ if not path:
255
+ return []
256
+ out = []
257
+ for e in ET.fromstring(run(path, "--errorlist")).iter("error"):
258
+ level, code, cwe = e.get("severity", ""), e.get("id", ""), e.get("cwe", "0")
259
+ if level not in CPPCHECK_SEVERITY or code in CPPCHECK_NOISE:
260
+ continue
261
+ severity, type_ = CPPCHECK_SEVERITY[level]
262
+ # cppcheck's messages are GPL; the catalogue keeps the ID, classification and CWE only.
263
+ out.append(rule("cppcheck", code, humanize(code), [C], type_, severity,
264
+ license_="GPL-3.0 (cppcheck): ID only", docs="https://cppcheck.sourceforge.io/manual.html",
265
+ cwe=[int(cwe)] if cwe != "0" else []))
266
+ return out
267
+
268
+
269
+ def checkov():
270
+ binary = isolated_tool("checkov")
271
+ if not binary:
272
+ return []
273
+ out, seen = [], set()
274
+ for framework in ("dockerfile", "terraform", "github_actions", "kubernetes"):
275
+ # --list only prints a Markdown table: | n | Id | Type | Entity | Policy | IaC | Resource Link |
276
+ for line in run(binary, "--list", "--framework", framework).splitlines():
277
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
278
+ if len(cells) < 7 or not cells[1].startswith("CKV") or cells[1] in seen:
279
+ continue
280
+ seen.add(cells[1])
281
+ out.append(rule("checkov", cells[1], cells[4], [IAC], HOTSPOT, MAJOR,
282
+ license_="Apache-2.0 (checkov)", summary=f"{framework} check", docs=cells[6]))
283
+ return out
284
+
285
+
286
+ # --- Node tools -----------------------------------------------------------------------------------------
287
+
288
+
289
+ def node_metadata():
290
+ with tempfile.NamedTemporaryFile("w", suffix=".json") as cfg:
291
+ json.dump(HTML_VALIDATE_CONFIG, cfg)
292
+ cfg.flush()
293
+ return json.loads(run("node", str(TOOLS_DIR / "rule-metadata.mjs"), cfg.name, cwd=TOOLS_DIR) or "{}")
294
+
295
+
296
+ def clean_eslint_doc(text):
297
+ """ESLint's docs use front matter and ::: correct/incorrect containers; turn those into plain Markdown."""
298
+ text = re.sub(r"\A---\n.*?\n---\n", "", text, flags=re.DOTALL)
299
+ text = re.sub(r"^::: ?(incorrect|correct)[^\n]*$", lambda m: f"**{m[1].capitalize()} code:**", text, flags=re.MULTILINE)
300
+ text = re.sub(r"^:::\s*$", "", text, flags=re.MULTILINE)
301
+ return re.sub(r"\{%[^%]{0,500}%\}", "", text).strip()
302
+
303
+
304
+ def local_doc(path):
305
+ try:
306
+ return clean_eslint_doc(path.read_text())
307
+ except OSError:
308
+ return None
309
+
310
+
311
+ def eslint_doc(rule_id):
312
+ if rule_id.startswith("security/"):
313
+ return local_doc(TOOLS_DIR / "node_modules/eslint-plugin-security/docs/rules" / f"{rule_id[9:]}.md")
314
+ try:
315
+ return clean_eslint_doc(fetch(ESLINT_DOC_URL.format(rule_id), timeout=30).decode())
316
+ except OSError:
317
+ return None
318
+
319
+
320
+ def eslint(data):
321
+ ids = [r["id"] for r in data.get(ESLINT, [])]
322
+ with ThreadPoolExecutor(max_workers=8) as pool:
323
+ texts = dict(zip(ids, pool.map(eslint_doc, ids), strict=True))
324
+ out = []
325
+ for r in data.get(ESLINT, []):
326
+ severity, type_ = eslint_classify(r["id"], 2)
327
+ lic = "Apache-2.0 (eslint-plugin-security)" if r["id"].startswith("security/") else "MIT (ESLint)"
328
+ out.append(rule(ESLINT, r["id"], r["description"] or humanize(r["id"]), [JS], type_, severity,
329
+ license_=lic, docs=r["url"], doc=texts.get(r["id"]), refs=links_in(texts.get(r["id"]))))
330
+ return out
331
+
332
+
333
+ def jsx_a11y(data):
334
+ docs_dir = TOOLS_DIR / "node_modules/eslint-plugin-jsx-a11y/docs/rules"
335
+ return [rule("jsx-a11y", r["id"], r["description"] or humanize(r["id"]), [JS], ACCESSIBILITY, MAJOR,
336
+ license_="MIT (eslint-plugin-jsx-a11y)", docs=r["url"],
337
+ doc=local_doc(docs_dir / f"{r['id'].removeprefix('jsx-a11y/')}.md"))
338
+ for r in data.get("jsx-a11y", [])]
339
+
340
+
341
+ def html_a11y(data):
342
+ out = []
343
+ for r in data.get("html-a11y", []):
344
+ technique = r["id"].removeprefix("wcag/").upper() if r["id"].startswith("wcag/") else None
345
+ refs = [{"label": f"WCAG technique {technique}",
346
+ "url": f"https://www.w3.org/WAI/WCAG22/Techniques/html/{technique}"}] if technique else []
347
+ out.append(rule("html-a11y", r["id"], humanize(r["id"].replace("wcag/", "WCAG ")), [HTML], ACCESSIBILITY,
348
+ MAJOR, license_="MIT (html-validate)", docs=r["url"], refs=refs))
349
+ return out
350
+
351
+
352
+ def stylelint(data):
353
+ docs_dir = TOOLS_DIR / "node_modules/stylelint/lib/rules"
354
+ return [rule("stylelint", r["id"], humanize(r["id"]), [CSS], CODE_SMELL if r["warning"] else BUG,
355
+ MINOR if r["warning"] else MAJOR, license_="MIT (stylelint)", docs=r["url"],
356
+ doc=local_doc(docs_dir / r["id"] / "README.md"))
357
+ for r in data.get("stylelint", [])]
358
+
359
+
360
+ def axe(data):
361
+ out = []
362
+ for r in data.get("axe", []):
363
+ wcag = [".".join(t[4:]) for t in r["tags"] if re.fullmatch(r"wcag\d{3,4}", t)]
364
+ refs = [{"label": f"WCAG 2.2 SC {sc}", "url": f"https://www.w3.org/WAI/WCAG22/quickref/#{sc}"} for sc in wcag]
365
+ out.append(rule("axe", r["id"], r["help"], [WEB], ACCESSIBILITY, VARIES, license_="MPL-2.0 (axe-core)",
366
+ summary=r["description"], docs=r["url"], refs=refs, wcag=wcag))
367
+ return out
368
+
369
+
370
+ def node():
371
+ if not node_tool(ESLINT):
372
+ return []
373
+ data = node_metadata()
374
+ return eslint(data) + jsx_a11y(data) + html_a11y(data) + stylelint(data) + axe(data)
375
+
376
+
377
+ # --- Semgrep registry -----------------------------------------------------------------------------------
378
+
379
+
380
+ def catalog_language(lang):
381
+ if lang in JS_LANGS:
382
+ return JS
383
+ return C if lang in ("c", "cpp") else lang
384
+
385
+
386
+ def bandit_equivalent(meta):
387
+ """Semgrep rules ported from bandit link to the bandit check they came from."""
388
+ source = str(meta.get("source-rule-url") or "")
389
+ match = BANDIT_DOC_RE.search(source) if BANDIT in source else None
390
+ return [f"bandit-code/{match[1].upper()}"] if match else []
391
+
392
+
393
+ def cwe_numbers(values):
394
+ return [int(m) for c in values or [] for m in CWE_RE.findall(c)]
395
+
396
+
397
+ def semgrep_entry(r):
398
+ meta = r.get("metadata") or {}
399
+ # Semgrep Rules License: only the ID, languages and the CWE/OWASP facts are recorded, not rule text.
400
+ return rule("semgrep", r["id"], humanize(r["id"].rsplit(".", 1)[-1]),
401
+ sorted({catalog_language(lang) for lang in r.get("languages", [])}), semgrep_type(r["id"], meta),
402
+ SEMGREP_SEVERITY.get(r.get("severity"), MINOR), license_="Semgrep Rules License v1.0: ID only",
403
+ docs=f"https://semgrep.dev/r/{r['id']}", cwe=cwe_numbers(meta.get("cwe")),
404
+ owasp=[o.split(" ")[0] for o in meta.get("owasp") or [] if "2025" in o],
405
+ same_as=bandit_equivalent(meta))
406
+
407
+
408
+ def semgrep():
409
+ import yaml
410
+
411
+ return [semgrep_entry(r) for r in yaml.safe_load(fetch(SEMGREP_PACK_URL))["rules"]]
412
+
413
+
414
+ SOURCES = [
415
+ ("ruff", ruff), (BANDIT, bandit), ("basedpyright", basedpyright), ("single-rule tools", single),
416
+ (DETECT_SECRETS, detect_secrets), ("cppcheck", cppcheck), ("checkov", checkov), ("Node tools", node),
417
+ ("semgrep registry", semgrep),
418
+ ]
@@ -0,0 +1,119 @@
1
+ """Free standards data: MITRE CWE (incl. the Top 25 and the OWASP Top 10 mapping) and W3C WCAG 2.2."""
2
+ import io
3
+ import json
4
+ import re
5
+ import zipfile
6
+
7
+ import defusedxml.ElementTree as ET
8
+
9
+ CWE_XML_URL = "https://cwe.mitre.org/data/xml/cwec_latest.xml.zip"
10
+ WCAG_JSON_URL = "https://www.w3.org/WAI/WCAG22/wcag.json"
11
+ TOP25_VIEW = "1435"
12
+ OWASP_VIEW = "1450"
13
+ BLOCK_TAGS = {"div", "p", "li", "ul", "ol", "br", "pre"}
14
+ MAX_MITIGATIONS = 4
15
+ MAX_EXAMPLES = 2
16
+
17
+
18
+ def local(tag):
19
+ return tag.rsplit("}", 1)[-1]
20
+
21
+
22
+ def xhtml_text(element):
23
+ """Text of a CWE XHTML fragment, keeping line breaks so example code stays readable."""
24
+ if element is None:
25
+ return ""
26
+ parts = []
27
+
28
+ def walk(node):
29
+ if node.text:
30
+ parts.append(node.text)
31
+ for child in node:
32
+ walk(child)
33
+ if local(child.tag) in BLOCK_TAGS:
34
+ parts.append("\n")
35
+ if child.tail:
36
+ parts.append(child.tail)
37
+
38
+ walk(element)
39
+ text = "\n".join(line.rstrip() for line in "".join(parts).splitlines())
40
+ return re.sub(r"\n{3,}", "\n\n", text).strip()
41
+
42
+
43
+ class Cwe:
44
+ def __init__(self, xml_zip):
45
+ with zipfile.ZipFile(io.BytesIO(xml_zip)) as z:
46
+ self.root = ET.fromstring(z.read(next(n for n in z.namelist() if n.endswith(".xml"))))
47
+ self.ns = {"c": self.root.tag.split("}")[0][1:]}
48
+ self.weaknesses = {int(w.get("ID", "0")): w for w in self.root.iterfind(".//c:Weakness", self.ns)}
49
+
50
+ def find(self, path, node=None):
51
+ return (node if node is not None else self.root).iterfind(path, self.ns)
52
+
53
+ def parents(self, weakness):
54
+ return sorted({int(r.get("CWE_ID")) for r in self.find(".//c:Related_Weakness", weakness)
55
+ if r.get("Nature") == "ChildOf" and r.get("View_ID") == "1000"})
56
+
57
+ def owasp_categories(self, views):
58
+ groupings = {g.get("ID"): g for g in self.find(".//c:Grouping")}
59
+ out = []
60
+ for member in self.find(".//c:Has_Member", views[OWASP_VIEW]):
61
+ g = groupings[member.get("CWE_ID")]
62
+ code, _, title = g.get("Name").split("Category ", 1)[1].partition(" - ")
63
+ out.append({"id": code, "name": title, "cwe_grouping": int(g.get("ID")),
64
+ "cwes": sorted(int(m.get("CWE_ID")) for m in self.find(".//c:Has_Member", g)),
65
+ "url": "https://owasp.org/Top10/2025/"})
66
+ return out
67
+
68
+ def summary(self):
69
+ views = {v.get("ID"): v for v in self.find(".//c:View")}
70
+ parents = {wid: self.parents(w) for wid, w in self.weaknesses.items()}
71
+ return {
72
+ "source": "MITRE CWE (https://cwe.mitre.org), used under the CWE Terms of Use",
73
+ "cwe_version": self.root.get("Version"),
74
+ "cwe_date": self.root.get("Date"),
75
+ "top25": {"name": views[TOP25_VIEW].get("Name"), "view": int(TOP25_VIEW),
76
+ "cwes": [int(m.get("CWE_ID")) for m in self.find(".//c:Has_Member", views[TOP25_VIEW])],
77
+ "url": "https://cwe.mitre.org/top25/"},
78
+ "owasp": {"name": "OWASP Top 10 (2025)", "view": int(OWASP_VIEW),
79
+ "categories": self.owasp_categories(views)},
80
+ "cwe_names": {str(k): w.get("Name") for k, w in sorted(self.weaknesses.items())},
81
+ "cwe_parents": {str(k): v for k, v in sorted(parents.items()) if v},
82
+ }
83
+
84
+ def details(self, cwe_id):
85
+ """What's wrong, how to fix it and example code for one weakness, from MITRE's entry."""
86
+ w = self.weaknesses.get(cwe_id)
87
+ if w is None:
88
+ return None
89
+ mitigations = [{"phase": ", ".join(p.text for p in self.find("c:Phase", m)),
90
+ "text": xhtml_text(m.find("c:Description", self.ns))}
91
+ for m in self.find("c:Potential_Mitigations/c:Mitigation", w)][:MAX_MITIGATIONS]
92
+ return {
93
+ "description": xhtml_text(w.find("c:Description", self.ns)),
94
+ "extended": xhtml_text(w.find("c:Extended_Description", self.ns))[:1500],
95
+ "mitigations": [m for m in mitigations if m["text"]],
96
+ "examples": [self.example(e) for e in self.find("c:Demonstrative_Examples/c:Demonstrative_Example", w)
97
+ ][:MAX_EXAMPLES],
98
+ "url": f"https://cwe.mitre.org/data/definitions/{cwe_id}.html",
99
+ }
100
+
101
+ def example(self, node):
102
+ codes = [{"language": c.get("Language", ""), "nature": c.get("Nature", ""), "code": xhtml_text(c)}
103
+ for c in self.find("c:Example_Code", node)]
104
+ return {"intro": xhtml_text(node.find("c:Intro_Text", self.ns)), "code": codes,
105
+ "body": " ".join(xhtml_text(b) for b in self.find("c:Body_Text", node))[:1200]}
106
+
107
+
108
+ def wcag(wcag_json):
109
+ data = json.loads(wcag_json)
110
+ return {
111
+ "name": "WCAG 2.2",
112
+ "source": "W3C Web Content Accessibility Guidelines 2.2 (https://www.w3.org/TR/WCAG22/), W3C Document License",
113
+ "criteria": [
114
+ {"sc": sc["num"], "title": sc["handle"], "level": sc["level"],
115
+ "url": f"https://www.w3.org/WAI/WCAG22/Understanding/{sc['id']}.html"}
116
+ for p in data["principles"] for g in p["guidelines"] for sc in g["successcriteria"]
117
+ if "2.2" in sc.get("versions", ["2.2"])
118
+ ],
119
+ }
core/catalog/update.py ADDED
@@ -0,0 +1,99 @@
1
+ """Keeping the imported rules current: on demand (button / command) or on a schedule.
2
+
3
+ An update optionally upgrades the analyzers themselves (new tool versions bring new rules), then re-imports.
4
+ """
5
+ import json
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ from datetime import UTC, datetime, timedelta
10
+
11
+ from ..paths import CHECKOUT
12
+ from ..tool_setup import install_tools
13
+ from . import RUNTIME_DIR, imported_dir, read_json, reload
14
+ from .build import build
15
+
16
+ STATUS_FILE = RUNTIME_DIR / "status.json"
17
+ STALE_RUN = timedelta(hours=2)
18
+
19
+
20
+ def update_interval():
21
+ return timedelta(days=float(os.environ.get("CODEWATCH_CATALOG_UPDATE_DAYS", "7")))
22
+
23
+
24
+ def status():
25
+ return read_json(STATUS_FILE, {})
26
+
27
+
28
+ def write_status(**fields):
29
+ STATUS_FILE.parent.mkdir(parents=True, exist_ok=True)
30
+ STATUS_FILE.write_text(json.dumps({**status(), **fields}, indent=1))
31
+
32
+
33
+ def upgrade_tools(log):
34
+ """Re-install the analyzers that are installed, at the versions in tools/*.lock and tools/package-lock.json."""
35
+ return install_tools(log, create_venvs=False, browser=True)
36
+
37
+
38
+ def run_update(upgrade=False, log=print):
39
+ """Re-import into the server's cache directory; catalog/custom/ is never modified."""
40
+ lines = []
41
+
42
+ def record(message):
43
+ lines.append(message)
44
+ log(message)
45
+
46
+ write_status(state="running", started_at=now(), upgrade=upgrade, pid=os.getpid())
47
+ try:
48
+ if upgrade:
49
+ record("Upgrading analyzers")
50
+ upgrade_tools(record)
51
+ previous = read_json(imported_dir() / "rules.json", [])
52
+ meta = build(RUNTIME_DIR / "imported", log=record, previous=previous)
53
+ except Exception as exc:
54
+ write_status(state="failed", finished_at=now(), log=lines[-200:], error=str(exc)[:2000])
55
+ raise
56
+ reload()
57
+ write_status(state="done", finished_at=now(), log=lines[-200:], rules=meta["rules"],
58
+ failed_sources=meta["failed_sources"])
59
+ return meta
60
+
61
+
62
+ def now():
63
+ return datetime.now(UTC).isoformat(timespec="seconds")
64
+
65
+
66
+ def running():
67
+ s = status()
68
+ if s.get("state") != "running":
69
+ return False
70
+ started = datetime.fromisoformat(s["started_at"])
71
+ return datetime.now(UTC) - started < STALE_RUN
72
+
73
+
74
+ def due():
75
+ interval = update_interval()
76
+ if interval <= timedelta(0) or running():
77
+ return False
78
+ imported = read_json(imported_dir() / "meta.json", {}).get("imported_at")
79
+ if not imported:
80
+ return True
81
+ return datetime.now(UTC) - datetime.fromisoformat(imported) >= interval
82
+
83
+
84
+ def launch(upgrade=False):
85
+ """Start `manage.py updatecatalog` (as `python -m codewatch`, which an installed package has too) in the
86
+ background."""
87
+ RUNTIME_DIR.mkdir(parents=True, exist_ok=True)
88
+ write_status(state="running", started_at=now(), upgrade=upgrade)
89
+ args = [sys.executable, "-m", "codewatch", "updatecatalog"] + (["--upgrade-tools"] if upgrade else [])
90
+ with open(RUNTIME_DIR / "update.log", "w") as out:
91
+ subprocess.Popen(args, stdout=out, stderr=subprocess.STDOUT, start_new_session=True, cwd=CHECKOUT)
92
+
93
+
94
+ def maybe_launch():
95
+ """Called on page loads: start the scheduled update when it's due. Cheap when it isn't."""
96
+ if due():
97
+ launch(upgrade=os.environ.get("CODEWATCH_CATALOG_UPGRADE_TOOLS") == "1")
98
+ return True
99
+ return False