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.
- codewatch/__init__.py +0 -0
- codewatch/__main__.py +14 -0
- codewatch/asgi.py +16 -0
- codewatch/settings.py +175 -0
- codewatch/urls.py +40 -0
- codewatch/wsgi.py +16 -0
- codewatch_scan-0.1.0.dist-info/METADATA +81 -0
- codewatch_scan-0.1.0.dist-info/RECORD +136 -0
- codewatch_scan-0.1.0.dist-info/WHEEL +5 -0
- codewatch_scan-0.1.0.dist-info/entry_points.txt +4 -0
- codewatch_scan-0.1.0.dist-info/licenses/LICENSE +21 -0
- codewatch_scan-0.1.0.dist-info/top_level.txt +2 -0
- core/__init__.py +0 -0
- core/analyzers/__init__.py +19 -0
- core/analyzers/accessibility.py +199 -0
- core/analyzers/base.py +192 -0
- core/analyzers/body_models.py +154 -0
- core/analyzers/codewatch_checks.py +394 -0
- core/analyzers/constant_branches.py +251 -0
- core/analyzers/containers.py +316 -0
- core/analyzers/coverage.py +131 -0
- core/analyzers/dependencies.py +347 -0
- core/analyzers/drf_serializers.py +65 -0
- core/analyzers/else_branches.py +106 -0
- core/analyzers/extra.py +400 -0
- core/analyzers/flask_resources.py +65 -0
- core/analyzers/inline_scripts.py +50 -0
- core/analyzers/jinja_sandboxes.py +63 -0
- core/analyzers/match_statements.py +148 -0
- core/analyzers/multi_tools.py +888 -0
- core/analyzers/php_template_sinks.py +444 -0
- core/analyzers/project_checks.py +150 -0
- core/analyzers/python_tools.py +333 -0
- core/analyzers/route_converters.py +237 -0
- core/analyzers/slices.py +94 -0
- core/analyzers/starred_targets.py +42 -0
- core/analyzers/stored_fields.py +386 -0
- core/analyzers/summaries.py +1387 -0
- core/analyzers/template_sinks.py +162 -0
- core/api.py +360 -0
- core/apps.py +6 -0
- core/benchmark.py +955 -0
- core/bundled/catalog/codewatch/rules/javascript-crypto.yml +224 -0
- core/bundled/catalog/codewatch/rules/javascript-injection.yml +116 -0
- core/bundled/catalog/codewatch/rules/javascript-taint.yml +1539 -0
- core/bundled/catalog/codewatch/rules/javascript-web.yml +562 -0
- core/bundled/catalog/codewatch/rules/php-web.yml +719 -0
- core/bundled/catalog/codewatch/rules/python-crypto.yml +203 -0
- core/bundled/catalog/codewatch/rules/python-django.yml +267 -0
- core/bundled/catalog/codewatch/rules/python-injection.yml +115 -0
- core/bundled/catalog/codewatch/rules/python-web.yml +3382 -0
- core/bundled/catalog/custom/mappings.json +360 -0
- core/bundled/catalog/custom/overrides.json +4 -0
- core/bundled/catalog/custom/rules/django-settings.yml +19 -0
- core/bundled/catalog/imported/changes.json +5 -0
- core/bundled/catalog/imported/docs.json +1143 -0
- core/bundled/catalog/imported/meta.json +54 -0
- core/bundled/catalog/imported/rules.json +85421 -0
- core/bundled/catalog/imported/standards.json +11191 -0
- core/bundled/tools/analyzers.lock +786 -0
- core/bundled/tools/axe-scan.mjs +45 -0
- core/bundled/tools/checkov.lock +2463 -0
- core/bundled/tools/codewatch-checks.mjs +99 -0
- core/bundled/tools/eslint-a11y.config.js +16 -0
- core/bundled/tools/eslint-quality.config.js +63 -0
- core/bundled/tools/eslint-typed.config.js +18 -0
- core/bundled/tools/package-lock.json +6102 -0
- core/bundled/tools/package.json +32 -0
- core/bundled/tools/rule-metadata.mjs +56 -0
- core/bundled/tools/semgrep.lock +1232 -0
- core/bundled/tools/stylelint.config.json +11 -0
- core/catalog/__init__.py +190 -0
- core/catalog/build.py +84 -0
- core/catalog/merge.py +122 -0
- core/catalog/sources.py +418 -0
- core/catalog/standards.py +119 -0
- core/catalog/update.py +99 -0
- core/catalog_views.py +115 -0
- core/client.py +645 -0
- core/collect.py +518 -0
- core/duplicates.py +60 -0
- core/fingerprint.py +25 -0
- core/folders.py +73 -0
- core/gate.py +77 -0
- core/git.py +149 -0
- core/jobs.py +86 -0
- core/management/__init__.py +0 -0
- core/management/commands/__init__.py +0 -0
- core/management/commands/addproject.py +40 -0
- core/management/commands/buildcatalog.py +15 -0
- core/management/commands/scan.py +74 -0
- core/management/commands/updatecatalog.py +14 -0
- core/mcp_server.py +140 -0
- core/middleware.py +17 -0
- core/migrations/0001_initial.py +115 -0
- core/migrations/0002_auth_tokens_a11y.py +60 -0
- core/migrations/0003_default_admin.py +43 -0
- core/migrations/0004_project_members.py +28 -0
- core/migrations/0005_uploads_and_sources.py +55 -0
- core/migrations/0006_thresholds.py +28 -0
- core/migrations/0007_also_reported_by.py +18 -0
- core/migrations/0008_new_code_period.py +18 -0
- core/migrations/0009_resolution_safe.py +18 -0
- core/migrations/0010_analysis_progress.py +18 -0
- core/migrations/0011_overall_gate_conditions.py +20 -0
- core/migrations/__init__.py +0 -0
- core/models.py +323 -0
- core/network.py +41 -0
- core/paths.py +29 -0
- core/ratings.py +67 -0
- core/runner.py +168 -0
- core/templates/core/account.html +30 -0
- core/templates/core/analysis.html +49 -0
- core/templates/core/base.html +121 -0
- core/templates/core/form_table.html +12 -0
- core/templates/core/gate_badge.html +1 -0
- core/templates/core/index.html +26 -0
- core/templates/core/issues.html +38 -0
- core/templates/core/login.html +13 -0
- core/templates/core/new_project.html +27 -0
- core/templates/core/password_change.html +10 -0
- core/templates/core/project.html +40 -0
- core/templates/core/rating.html +1 -0
- core/templates/core/ratings.html +32 -0
- core/templates/core/rule.html +33 -0
- core/templates/core/rules.html +42 -0
- core/templates/core/scan_progress.html +2 -0
- core/templates/core/settings.html +36 -0
- core/templates/core/source.html +15 -0
- core/templates/core/standards.html +30 -0
- core/templates/core/user_edit.html +15 -0
- core/templates/core/users.html +18 -0
- core/templatetags/__init__.py +0 -0
- core/templatetags/codewatch.py +42 -0
- core/tool_setup.py +68 -0
- core/views.py +564 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": ["stylelint-config-recommended"],
|
|
3
|
+
"rules": {
|
|
4
|
+
"color-no-invalid-hex": true,
|
|
5
|
+
"declaration-block-no-duplicate-properties": true,
|
|
6
|
+
"no-duplicate-selectors": true,
|
|
7
|
+
"selector-max-id": [1, {"severity": "warning"}],
|
|
8
|
+
"declaration-no-important": [true, {"severity": "warning"}],
|
|
9
|
+
"max-nesting-depth": [4, {"severity": "warning"}]
|
|
10
|
+
}
|
|
11
|
+
}
|
core/catalog/__init__.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""codewatch's public rule catalogue, in two layers.
|
|
2
|
+
|
|
3
|
+
imported/ Generated by an import (build.py) from the analyzers' metadata and free standards (MITRE CWE, OWASP
|
|
4
|
+
via MITRE, W3C WCAG). Replaced wholesale on every import.
|
|
5
|
+
custom/ Maintained by people and never touched by an import: mappings.json (extra CWE/WCAG/OWASP mappings
|
|
6
|
+
and equivalent rules), overrides.json (per-rule severity/type/title/disabled) and rules/*.yml
|
|
7
|
+
(codewatch's own checks, in Semgrep syntax, which run in every scan).
|
|
8
|
+
|
|
9
|
+
The two are merged whenever the catalogue is loaded. A server's imports go to its cache directory and take
|
|
10
|
+
precedence over the snapshot committed in catalog/imported/.
|
|
11
|
+
"""
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
from functools import lru_cache
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from ..paths import shipped
|
|
18
|
+
from .merge import merge
|
|
19
|
+
|
|
20
|
+
BUNDLED_DIR = shipped("catalog")
|
|
21
|
+
RUNTIME_DIR = Path(os.environ.get("CODEWATCH_CACHE", Path.home() / ".cache" / "codewatch")) / "catalog"
|
|
22
|
+
CUSTOM_DIR = Path(os.environ.get("CODEWATCH_CUSTOM_RULES", BUNDLED_DIR / "custom"))
|
|
23
|
+
RULES = "rules"
|
|
24
|
+
BUILTIN_RULES_DIR = BUNDLED_DIR / "codewatch" / RULES
|
|
25
|
+
ANY = "any"
|
|
26
|
+
|
|
27
|
+
# Issues whose rule is not a catalogue code: pip-audit names the advisory, detect-secrets the secret type.
|
|
28
|
+
ISSUE_RULE_ALIASES = {
|
|
29
|
+
"pip-audit": "pip-audit/vulnerable-dependency",
|
|
30
|
+
"osv": "osv/vulnerable-dependency",
|
|
31
|
+
# A tool and rule name, not a secret: detect-secrets matches the word "secret".
|
|
32
|
+
"detect-secrets": "detect-secrets/hard-coded-secret", # pragma: allowlist secret
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def imported_dir():
|
|
37
|
+
runtime = RUNTIME_DIR / "imported"
|
|
38
|
+
return runtime if (runtime / "rules.json").exists() else BUNDLED_DIR / "imported"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def read_json(path, default):
|
|
42
|
+
return json.loads(path.read_text()) if path.exists() else default
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def custom_rule_files():
|
|
46
|
+
return sorted((CUSTOM_DIR / RULES).glob("*.y*ml"))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def builtin_rule_files():
|
|
50
|
+
return sorted(BUILTIN_RULES_DIR.glob("*.y*ml"))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def rules_in(path):
|
|
54
|
+
"""Rules from one YAML file; a broken file is skipped (and reported) rather than breaking every scan."""
|
|
55
|
+
import sys
|
|
56
|
+
|
|
57
|
+
import yaml
|
|
58
|
+
|
|
59
|
+
try:
|
|
60
|
+
return (yaml.safe_load(path.read_text()) or {}).get(RULES, [])
|
|
61
|
+
except (OSError, yaml.YAMLError) as exc:
|
|
62
|
+
print(f"codewatch: skipping rule file {path}: {exc}", file=sys.stderr)
|
|
63
|
+
return []
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def custom_semgrep_rules():
|
|
67
|
+
"""codewatch's built-in and the project's custom Semgrep rules as one config document, for scans.
|
|
68
|
+
|
|
69
|
+
Anchors in the rule files are expanded here, so semgrep receives plain YAML.
|
|
70
|
+
"""
|
|
71
|
+
import yaml
|
|
72
|
+
|
|
73
|
+
class PlainDumper(yaml.SafeDumper):
|
|
74
|
+
def ignore_aliases(self, data): # noqa: ARG002 - every alias is expanded
|
|
75
|
+
return True
|
|
76
|
+
|
|
77
|
+
rules = []
|
|
78
|
+
for path in [*builtin_rule_files(), *custom_rule_files()]:
|
|
79
|
+
rules += rules_in(path)
|
|
80
|
+
return yaml.dump({RULES: rules}, Dumper=PlainDumper, sort_keys=False) if rules else ""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@lru_cache(maxsize=1)
|
|
84
|
+
def load():
|
|
85
|
+
base = imported_dir()
|
|
86
|
+
standards = read_json(base / "standards.json", {})
|
|
87
|
+
rules = merge(
|
|
88
|
+
read_json(base / "rules.json", []),
|
|
89
|
+
standards,
|
|
90
|
+
read_json(CUSTOM_DIR / "mappings.json", {}),
|
|
91
|
+
read_json(CUSTOM_DIR / "overrides.json", {}).get(RULES, {}),
|
|
92
|
+
[*((p, "codewatch") for p in builtin_rule_files()), *((p, "custom") for p in custom_rule_files())],
|
|
93
|
+
)
|
|
94
|
+
return rules, standards
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@lru_cache(maxsize=1)
|
|
98
|
+
def index():
|
|
99
|
+
return {r["id"]: r for r in load()[0]}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@lru_cache(maxsize=1)
|
|
103
|
+
def docs():
|
|
104
|
+
return read_json(imported_dir() / "docs.json", {})
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def meta():
|
|
108
|
+
return read_json(imported_dir() / "meta.json", {})
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def changes():
|
|
112
|
+
return read_json(imported_dir() / "changes.json", {})
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def reload():
|
|
116
|
+
for cached in (load, index, docs, bandit_by_test_id):
|
|
117
|
+
cached.cache_clear()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def find(rule_id):
|
|
121
|
+
return index().get(rule_id)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@lru_cache(maxsize=1)
|
|
125
|
+
def bandit_by_test_id():
|
|
126
|
+
return {r["id"].split("/", 1)[1].split(":", 1)[0]: r for r in load()[0] if r["id"].startswith("bandit/")}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def lookup(tool, code):
|
|
130
|
+
"""Catalogue entry for an issue's tool + rule; bandit issues carry "B105:name", ruff "F841", etc."""
|
|
131
|
+
entry = find(ISSUE_RULE_ALIASES.get(tool) or f"{tool}/{code}")
|
|
132
|
+
if entry is None and tool == "bandit":
|
|
133
|
+
# bandit renames tests between releases (B324:hashlib vs B324:hashlib_insecure_functions); the id is stable.
|
|
134
|
+
entry = bandit_by_test_id().get(code.split(":", 1)[0])
|
|
135
|
+
return entry
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def ancestors(cwe, parents):
|
|
139
|
+
seen, stack = set(), [cwe]
|
|
140
|
+
while stack:
|
|
141
|
+
for p in parents.get(str(stack.pop()), []):
|
|
142
|
+
if p not in seen:
|
|
143
|
+
seen.add(p)
|
|
144
|
+
stack.append(p)
|
|
145
|
+
return seen
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def expanded_cwes(cwes, parents):
|
|
149
|
+
out = set(cwes)
|
|
150
|
+
for c in cwes:
|
|
151
|
+
out |= ancestors(c, parents)
|
|
152
|
+
return out
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def speaks(rule, lang):
|
|
156
|
+
return lang in rule["languages"] or ANY in rule["languages"]
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class Coverage:
|
|
160
|
+
"""How many rules address each standard entry, per language.
|
|
161
|
+
|
|
162
|
+
A rule counts towards a CWE if it targets it or a more specific weakness beneath it.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
def __init__(self, rules, standards):
|
|
166
|
+
self.standards = standards
|
|
167
|
+
parents = standards.get("cwe_parents", {})
|
|
168
|
+
self.covers = [(r, expanded_cwes(r["cwe"], parents)) for r in rules if not r.get("disabled")]
|
|
169
|
+
|
|
170
|
+
def count(self, cwes, lang, owasp_id=None):
|
|
171
|
+
return sum(1 for r, exp in self.covers if speaks(r, lang) and (exp & cwes or owasp_id in r["owasp"]))
|
|
172
|
+
|
|
173
|
+
def top25(self, languages):
|
|
174
|
+
names = self.standards["cwe_names"]
|
|
175
|
+
return [{"cwe": c, "rank": i + 1, "name": names.get(str(c), ""),
|
|
176
|
+
"by_language": {lang: self.count({c}, lang) for lang in languages}}
|
|
177
|
+
for i, c in enumerate(self.standards["top25"]["cwes"])]
|
|
178
|
+
|
|
179
|
+
def owasp(self, languages):
|
|
180
|
+
return [{**cat, "by_language": {lang: self.count(set(cat["cwes"]), lang, cat["id"]) for lang in languages}}
|
|
181
|
+
for cat in self.standards["owasp"]["categories"]]
|
|
182
|
+
|
|
183
|
+
def wcag(self):
|
|
184
|
+
return [{**sc, "rules": sum(1 for r, _ in self.covers if sc["sc"] in r["wcag"])}
|
|
185
|
+
for sc in self.standards.get("wcag", {}).get("criteria", [])]
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def coverage(rules, standards, languages):
|
|
189
|
+
c = Coverage(rules, standards)
|
|
190
|
+
return c.top25(languages), c.owasp(languages), c.wcag()
|
core/catalog/build.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Import: regenerate catalog/imported/ from the installed analyzers and online sources.
|
|
2
|
+
|
|
3
|
+
Only the imported layer is written; catalog/custom/ is never touched.
|
|
4
|
+
"""
|
|
5
|
+
import json
|
|
6
|
+
import subprocess
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
|
|
9
|
+
from ..analyzers.base import TOOLS_DIR, isolated_tool, tool_path
|
|
10
|
+
from . import sources, standards
|
|
11
|
+
|
|
12
|
+
VERSIONED_TOOLS = ["ruff", "bandit", "semgrep", "basedpyright", "complexipy", "detect-secrets", "cppcheck",
|
|
13
|
+
"pip-audit"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def tool_versions():
|
|
17
|
+
versions = {}
|
|
18
|
+
for name in VERSIONED_TOOLS:
|
|
19
|
+
path = isolated_tool(name) or tool_path(name)
|
|
20
|
+
if path:
|
|
21
|
+
out = subprocess.run([path, "--version"], capture_output=True, text=True, check=False).stdout.strip()
|
|
22
|
+
versions[name] = out.splitlines()[0] if out else "?"
|
|
23
|
+
package = TOOLS_DIR / "package.json"
|
|
24
|
+
if package.exists():
|
|
25
|
+
versions.update(json.loads(package.read_text()).get("dependencies", {}))
|
|
26
|
+
return versions
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def collect_rules(log):
|
|
30
|
+
rules, failures = [], {}
|
|
31
|
+
for name, collect in sources.SOURCES:
|
|
32
|
+
try:
|
|
33
|
+
found = collect()
|
|
34
|
+
except Exception as exc: # noqa: BLE001 - one unreachable source must not abort the import
|
|
35
|
+
failures[name] = str(exc)[:500]
|
|
36
|
+
log(f" {name}: FAILED ({exc})")
|
|
37
|
+
continue
|
|
38
|
+
log(f" {name}: {len(found)} rules")
|
|
39
|
+
rules += found
|
|
40
|
+
return rules, failures
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def split_docs(rules):
|
|
44
|
+
docs = {}
|
|
45
|
+
for r in rules:
|
|
46
|
+
doc = r.pop("_doc", None)
|
|
47
|
+
if doc:
|
|
48
|
+
docs[r["id"]] = doc
|
|
49
|
+
return docs
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def diff(previous, current):
|
|
53
|
+
before, after = {r["id"] for r in previous}, {r["id"] for r in current}
|
|
54
|
+
return {"added": sorted(after - before), "removed": sorted(before - after)}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def build(target, log=print, previous=None):
|
|
58
|
+
log("Fetching MITRE CWE data")
|
|
59
|
+
cwe = standards.Cwe(sources.fetch(standards.CWE_XML_URL))
|
|
60
|
+
std = cwe.summary()
|
|
61
|
+
log("Fetching W3C WCAG 2.2 data")
|
|
62
|
+
std["wcag"] = standards.wcag(sources.fetch(standards.WCAG_JSON_URL))
|
|
63
|
+
rules, failures = collect_rules(log)
|
|
64
|
+
if failures and not rules:
|
|
65
|
+
raise RuntimeError(f"Every source failed: {failures}")
|
|
66
|
+
docs = split_docs(rules)
|
|
67
|
+
referenced = sorted({c for r in rules for c in r["cwe"]})
|
|
68
|
+
std["cwe_details"] = {str(c): d for c in referenced if (d := cwe.details(c))}
|
|
69
|
+
rules.sort(key=lambda r: r["id"])
|
|
70
|
+
meta = {
|
|
71
|
+
"imported_at": datetime.now(UTC).isoformat(timespec="seconds"),
|
|
72
|
+
"rules": len(rules), "by_tool": {}, "tools": tool_versions(), "failed_sources": failures,
|
|
73
|
+
"standards": {"cwe": f"{std['cwe_version']} ({std['cwe_date']})", "wcag": "2.2", "owasp": "2025"},
|
|
74
|
+
}
|
|
75
|
+
for r in rules:
|
|
76
|
+
meta["by_tool"][r["tool"]] = meta["by_tool"].get(r["tool"], 0) + 1
|
|
77
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
78
|
+
files = {"rules.json": rules, "standards.json": std, "docs.json": docs, "meta.json": meta,
|
|
79
|
+
"changes.json": {**diff(previous or [], rules), "at": meta["imported_at"]}}
|
|
80
|
+
for name, data in files.items():
|
|
81
|
+
tmp = target / f".{name}.tmp"
|
|
82
|
+
tmp.write_text(json.dumps(data, indent=1) + "\n")
|
|
83
|
+
tmp.replace(target / name)
|
|
84
|
+
return meta
|
core/catalog/merge.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Combine imported rules with the custom layer (mappings, overrides, codewatch's own rules)."""
|
|
2
|
+
import copy
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
CWE_RE = re.compile(r"CWE-(\d+)")
|
|
6
|
+
CWE_URL = "https://cwe.mitre.org/data/definitions/{}.html"
|
|
7
|
+
WCAG_URL = "https://www.w3.org/WAI/WCAG22/quickref/#{}"
|
|
8
|
+
CODEWATCH = "codewatch"
|
|
9
|
+
OVERRIDABLE = ("severity", "type", "title", "summary", "disabled")
|
|
10
|
+
SEMGREP_SEVERITY = {"ERROR": "critical", "WARNING": "major", "INFO": "minor"}
|
|
11
|
+
SEMGREP_TYPE = {"security": "vulnerability", "correctness": "bug"}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def listed(meta, key):
|
|
15
|
+
return meta.get(key) or []
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def normal_language(lang):
|
|
19
|
+
return "javascript" if lang in ("js", "ts", "typescript") else lang
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def custom_rule(r, path, origin="custom"):
|
|
23
|
+
meta = r.get("metadata") or {}
|
|
24
|
+
return {
|
|
25
|
+
"id": f"codewatch/{r['id']}", "tool": CODEWATCH, "code": r["id"],
|
|
26
|
+
"title": meta.get("title") or r["message"].split(".")[0].strip(),
|
|
27
|
+
"languages": [normal_language(lang) for lang in r.get("languages", [])],
|
|
28
|
+
"type": meta.get("type") or SEMGREP_TYPE.get(meta.get("category", ""), "code_smell"),
|
|
29
|
+
"severity": SEMGREP_SEVERITY.get(r.get("severity"), "minor"), "summary": r["message"].strip(),
|
|
30
|
+
"docs": "", "license": f"{origin} ({path.name})", "origin": origin,
|
|
31
|
+
"references": [{"label": url, "url": url} for url in listed(meta, "references")],
|
|
32
|
+
"cwe": sorted({int(m) for c in listed(meta, "cwe") for m in CWE_RE.findall(c)}),
|
|
33
|
+
"wcag": [str(w) for w in listed(meta, "wcag")],
|
|
34
|
+
"owasp": [o.split(" ")[0] for o in listed(meta, "owasp")],
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def load_rule_files(rule_files):
|
|
39
|
+
"""Rules from (path, origin) pairs: codewatch's built-in files and the project's custom ones."""
|
|
40
|
+
from . import rules_in
|
|
41
|
+
|
|
42
|
+
return [custom_rule(r, path, origin) for path, origin in rule_files for r in rules_in(path)]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def add_mapping(rule, field, values, label):
|
|
46
|
+
new = set(values) - set(rule[field])
|
|
47
|
+
if new:
|
|
48
|
+
rule[field] = sorted(set(rule[field]) | new)
|
|
49
|
+
rule.setdefault("mapped_by", []).append(label)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def apply_mappings(rules, mappings):
|
|
53
|
+
for kind in ("cwe", "wcag", "owasp"):
|
|
54
|
+
table = mappings.get(kind, {})
|
|
55
|
+
for r in rules:
|
|
56
|
+
values = table.get(r["id"]) or table.get(f"{r['tool']}/*") or []
|
|
57
|
+
add_mapping(r, kind, values, CODEWATCH)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def source_pairs(rules, by_id):
|
|
61
|
+
"""Equivalences a source declared ("_same_as"); bandit references are by test ID, e.g. B602."""
|
|
62
|
+
bandit_codes = {r["code"].split(":")[0]: r["id"] for r in rules if r["tool"] == "bandit"}
|
|
63
|
+
pairs = []
|
|
64
|
+
for r in rules:
|
|
65
|
+
for other in r.pop("_same_as", []):
|
|
66
|
+
is_bandit = other.startswith(("bandit/", "bandit-code/"))
|
|
67
|
+
target = bandit_codes.get(other.split("/", 1)[1]) if is_bandit else other
|
|
68
|
+
if target in by_id:
|
|
69
|
+
pairs.append([r["id"], target])
|
|
70
|
+
return pairs
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def resolve_same_as(rules, mappings):
|
|
74
|
+
"""Equivalent rules across tools: from the sources themselves plus custom/mappings.json "equivalent"."""
|
|
75
|
+
by_id = {r["id"]: r for r in rules}
|
|
76
|
+
pairs = list(mappings.get("equivalent", [])) + source_pairs(rules, by_id)
|
|
77
|
+
for group in pairs:
|
|
78
|
+
members = [m for m in group if m in by_id]
|
|
79
|
+
for m in members:
|
|
80
|
+
by_id[m]["same_as"] = sorted(set(by_id[m].get("same_as", [])) | (set(members) - {m}))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def add_standard_refs(rule, standards):
|
|
84
|
+
present = {ref["url"] for ref in rule["references"]}
|
|
85
|
+
names = standards.get("cwe_names", {})
|
|
86
|
+
for c in rule["cwe"]:
|
|
87
|
+
if CWE_URL.format(c) not in present:
|
|
88
|
+
rule["references"].append({"label": f"CWE-{c}: {names.get(str(c), '')}".rstrip(": "),
|
|
89
|
+
"url": CWE_URL.format(c)})
|
|
90
|
+
for sc in rule["wcag"]:
|
|
91
|
+
if WCAG_URL.format(sc) not in present:
|
|
92
|
+
rule["references"].append({"label": f"WCAG 2.2 SC {sc}", "url": WCAG_URL.format(sc)})
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def owasp_for(cwes, standards):
|
|
96
|
+
from . import expanded_cwes
|
|
97
|
+
|
|
98
|
+
expanded = expanded_cwes(cwes, standards.get("cwe_parents", {}))
|
|
99
|
+
return [cat["id"] for cat in standards.get("owasp", {}).get("categories", []) if expanded & set(cat["cwes"])]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def builtin_rules():
|
|
103
|
+
from ..analyzers.codewatch_checks import RULES
|
|
104
|
+
|
|
105
|
+
return [{"id": f"codewatch/{r['code']}", "tool": CODEWATCH, "docs": "", "wcag": [], "owasp": [],
|
|
106
|
+
"license": CODEWATCH, "origin": CODEWATCH, **copy.deepcopy(r)} for r in RULES]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def merge(imported, standards, mappings, overrides, rule_files):
|
|
110
|
+
rules = [copy.deepcopy(r) for r in imported] + builtin_rules() + load_rule_files(rule_files)
|
|
111
|
+
for r in rules:
|
|
112
|
+
r.setdefault("origin", "imported")
|
|
113
|
+
apply_mappings(rules, mappings)
|
|
114
|
+
resolve_same_as(rules, mappings)
|
|
115
|
+
for r in rules:
|
|
116
|
+
for field, value in (overrides.get(r["id"]) or {}).items():
|
|
117
|
+
if field in OVERRIDABLE:
|
|
118
|
+
r[field] = value
|
|
119
|
+
r["overridden"] = True
|
|
120
|
+
r["owasp"] = sorted(set(r["owasp"]) | set(owasp_for(r["cwe"], standards)))
|
|
121
|
+
add_standard_refs(r, standards)
|
|
122
|
+
return sorted(rules, key=lambda r: r["id"])
|