codefactory-cli 0.20.1__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.
- codefactory/__init__.py +3 -0
- codefactory/__main__.py +5 -0
- codefactory/accept.py +68 -0
- codefactory/analyzers/__init__.py +55 -0
- codefactory/analyzers/generic.py +392 -0
- codefactory/analyzers/parallel.py +113 -0
- codefactory/analyzers/python.py +279 -0
- codefactory/analyzers/python_parse.py +402 -0
- codefactory/analyzers/treewalk.py +299 -0
- codefactory/analyzers/ts_helper.js +483 -0
- codefactory/analyzers/typescript.py +118 -0
- codefactory/apple.py +80 -0
- codefactory/audit.py +227 -0
- codefactory/baseline.py +58 -0
- codefactory/brief.py +330 -0
- codefactory/cache.py +93 -0
- codefactory/checks.py +608 -0
- codefactory/cli.py +782 -0
- codefactory/config.py +157 -0
- codefactory/coverage.py +104 -0
- codefactory/deps.py +182 -0
- codefactory/diff.py +197 -0
- codefactory/efficiency.py +250 -0
- codefactory/flags.py +263 -0
- codefactory/graph.py +95 -0
- codefactory/hotspots.py +344 -0
- codefactory/infra.py +242 -0
- codefactory/intent.py +106 -0
- codefactory/layers.py +143 -0
- codefactory/org.py +131 -0
- codefactory/owners.py +72 -0
- codefactory/patch.py +81 -0
- codefactory/paths.py +93 -0
- codefactory/plan.py +476 -0
- codefactory/privacy.py +221 -0
- codefactory/profile.py +667 -0
- codefactory/rerank.py +161 -0
- codefactory/review.py +1504 -0
- codefactory/rules.py +50 -0
- codefactory/sarif.py +661 -0
- codefactory/sbom.py +78 -0
- codefactory/security.py +537 -0
- codefactory/similar.py +199 -0
- codefactory/skill.py +144 -0
- codefactory/skill_template/SKILL.md +68 -0
- codefactory/skill_template/__init__.py +0 -0
- codefactory/sqlgraph.py +109 -0
- codefactory/suppress.py +92 -0
- codefactory/taint.py +439 -0
- codefactory/trace.py +72 -0
- codefactory/viewer/__init__.py +19 -0
- codefactory/viewer/dashboard.html +43 -0
- codefactory/viewer/factory.css +61 -0
- codefactory/viewer/factory.js +665 -0
- codefactory/viewer/template.html +47 -0
- codefactory_cli-0.20.1.dist-info/METADATA +250 -0
- codefactory_cli-0.20.1.dist-info/RECORD +61 -0
- codefactory_cli-0.20.1.dist-info/WHEEL +5 -0
- codefactory_cli-0.20.1.dist-info/entry_points.txt +2 -0
- codefactory_cli-0.20.1.dist-info/licenses/LICENSE +21 -0
- codefactory_cli-0.20.1.dist-info/top_level.txt +1 -0
codefactory/sarif.py
ADDED
|
@@ -0,0 +1,661 @@
|
|
|
1
|
+
"""SARIF 2.1.0 output, the format GitHub code scanning, VS Code (SARIF Viewer) and most CI tools read: every issue
|
|
2
|
+
shows on its line, in pull requests and in the editor. Also GitHub workflow annotations (`::warning file=…::`), which
|
|
3
|
+
appear on pull requests without code scanning.
|
|
4
|
+
|
|
5
|
+
Results carry stable fingerprints (kind, file, function, not line numbers), so GitHub tracks an alert across edits;
|
|
6
|
+
silenced issues are included as suppressed (with the reason), and with a baseline each result says new or unchanged.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
from collections import Counter
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
from .baseline import issue_key
|
|
17
|
+
from .checks import scan_sources, source_files
|
|
18
|
+
|
|
19
|
+
SCHEMA = "https://json.schemastore.org/sarif-2.1.0.json"
|
|
20
|
+
LEVEL = {"high": "error", "warn": "warning", "info": "note"}
|
|
21
|
+
HOME = "https://github.com/dominickkubica/codefactory"
|
|
22
|
+
|
|
23
|
+
# rule id -> (name, short description, help, level, tags, security severity)
|
|
24
|
+
RULES: dict[str, tuple] = {
|
|
25
|
+
"cycle": (
|
|
26
|
+
"ImportLoop",
|
|
27
|
+
"Files import each other in a circle",
|
|
28
|
+
"Move what both sides need into a module that imports neither, or pass the dependency in.",
|
|
29
|
+
"high",
|
|
30
|
+
["maintainability", "architecture"],
|
|
31
|
+
None,
|
|
32
|
+
),
|
|
33
|
+
"layer_violation": (
|
|
34
|
+
"LayerViolation",
|
|
35
|
+
"An import factory.toml forbids",
|
|
36
|
+
"Move the code into an allowed layer, or invert the dependency.",
|
|
37
|
+
"high",
|
|
38
|
+
["architecture"],
|
|
39
|
+
None,
|
|
40
|
+
),
|
|
41
|
+
"io_in_loop": (
|
|
42
|
+
"IoInLoop",
|
|
43
|
+
"Database, network or file call once per loop iteration",
|
|
44
|
+
"Load everything the loop needs with one batched query (WHERE id IN (…), a JOIN) or request before "
|
|
45
|
+
"the loop. Writes: keep them in one transaction, batch if many.",
|
|
46
|
+
"warn",
|
|
47
|
+
["performance"],
|
|
48
|
+
None,
|
|
49
|
+
),
|
|
50
|
+
"duplicate": (
|
|
51
|
+
"DuplicateFunction",
|
|
52
|
+
"Same code in more than one place",
|
|
53
|
+
"Merge into one function in the lowest layer the callers share; `codefactory plan` lists the steps.",
|
|
54
|
+
"warn",
|
|
55
|
+
["maintainability"],
|
|
56
|
+
None,
|
|
57
|
+
),
|
|
58
|
+
"similar": (
|
|
59
|
+
"NearDuplicateFunction",
|
|
60
|
+
"A copy that was edited afterwards",
|
|
61
|
+
"Compare the copies, fold the differences into parameters, and merge.",
|
|
62
|
+
"warn",
|
|
63
|
+
["maintainability"],
|
|
64
|
+
None,
|
|
65
|
+
),
|
|
66
|
+
"unused": (
|
|
67
|
+
"UnusedFunction",
|
|
68
|
+
"Nothing calls or references this",
|
|
69
|
+
"Search for the name (frameworks may call by name); delete it if unused.",
|
|
70
|
+
"warn",
|
|
71
|
+
["maintainability"],
|
|
72
|
+
None,
|
|
73
|
+
),
|
|
74
|
+
"test_only": (
|
|
75
|
+
"TestOnlyFunction",
|
|
76
|
+
"Only tests call this",
|
|
77
|
+
"Wire it into the product, move it next to the tests, or delete both.",
|
|
78
|
+
"info",
|
|
79
|
+
["maintainability"],
|
|
80
|
+
None,
|
|
81
|
+
),
|
|
82
|
+
"quadratic_scan": (
|
|
83
|
+
"SearchInLoop",
|
|
84
|
+
"Array search inside a loop (O(n²))",
|
|
85
|
+
"If the list can grow, build a Map or Set once before the loop.",
|
|
86
|
+
"info",
|
|
87
|
+
["performance"],
|
|
88
|
+
None,
|
|
89
|
+
),
|
|
90
|
+
"sequential_await": (
|
|
91
|
+
"AwaitInLoop",
|
|
92
|
+
"Awaits wait for each round in turn",
|
|
93
|
+
"If the iterations are independent, run them together (Promise.all / asyncio.gather).",
|
|
94
|
+
"info",
|
|
95
|
+
["performance"],
|
|
96
|
+
None,
|
|
97
|
+
),
|
|
98
|
+
"hub": (
|
|
99
|
+
"Hub",
|
|
100
|
+
"Called from many files",
|
|
101
|
+
"Change carefully: check callers with `codefactory context`.",
|
|
102
|
+
"info",
|
|
103
|
+
["maintainability"],
|
|
104
|
+
None,
|
|
105
|
+
),
|
|
106
|
+
"large_file": (
|
|
107
|
+
"LargeFile",
|
|
108
|
+
"Very large file",
|
|
109
|
+
"Split along the responsibilities it holds.",
|
|
110
|
+
"info",
|
|
111
|
+
["maintainability"],
|
|
112
|
+
None,
|
|
113
|
+
),
|
|
114
|
+
"long_function": (
|
|
115
|
+
"LongFunction",
|
|
116
|
+
"Very long function",
|
|
117
|
+
"Extract the parts that have names of their own.",
|
|
118
|
+
"info",
|
|
119
|
+
["maintainability"],
|
|
120
|
+
None,
|
|
121
|
+
),
|
|
122
|
+
"secret": (
|
|
123
|
+
"CredentialInSource",
|
|
124
|
+
"A credential is written in the source",
|
|
125
|
+
"Rotate it, remove it from the code and history, load it from the environment or a secret store.",
|
|
126
|
+
"high",
|
|
127
|
+
["security"],
|
|
128
|
+
"9.0",
|
|
129
|
+
),
|
|
130
|
+
"eval": (
|
|
131
|
+
"DynamicCodeExecution",
|
|
132
|
+
"eval / exec / pickle / unsafe YAML",
|
|
133
|
+
"Parse explicitly (JSON, a lookup table); never unpickle or yaml.load untrusted data.",
|
|
134
|
+
"high",
|
|
135
|
+
["security"],
|
|
136
|
+
"8.1",
|
|
137
|
+
),
|
|
138
|
+
"shell": (
|
|
139
|
+
"ShellString",
|
|
140
|
+
"A shell command built at runtime",
|
|
141
|
+
"Pass arguments as a list without a shell (subprocess.run([...]), execFile/spawn).",
|
|
142
|
+
"high",
|
|
143
|
+
["security"],
|
|
144
|
+
"8.1",
|
|
145
|
+
),
|
|
146
|
+
"tls_off": (
|
|
147
|
+
"TlsVerificationDisabled",
|
|
148
|
+
"TLS certificate checks turned off",
|
|
149
|
+
"Remove the override; trust a private CA explicitly if needed.",
|
|
150
|
+
"high",
|
|
151
|
+
["security"],
|
|
152
|
+
"7.4",
|
|
153
|
+
),
|
|
154
|
+
"sql_built": (
|
|
155
|
+
"SqlFromStrings",
|
|
156
|
+
"SQL assembled from strings",
|
|
157
|
+
"Bind values as parameters; check table or column names against a fixed list where the SQL is built.",
|
|
158
|
+
"warn",
|
|
159
|
+
["security"],
|
|
160
|
+
"6.5",
|
|
161
|
+
),
|
|
162
|
+
"raw_html": (
|
|
163
|
+
"RawHtml",
|
|
164
|
+
"Raw HTML inserted into a page",
|
|
165
|
+
"Render as text or sanitize (e.g. DOMPurify) right before inserting.",
|
|
166
|
+
"warn",
|
|
167
|
+
["security"],
|
|
168
|
+
"6.1",
|
|
169
|
+
),
|
|
170
|
+
"plain_http": ("PlainHttp", "Plain-HTTP URL", "Use https:// where the host supports it.", "info", ["security"], "4.3"),
|
|
171
|
+
"secret_key_literal": (
|
|
172
|
+
"SigningKeyInSource",
|
|
173
|
+
"A signing key is written in the code",
|
|
174
|
+
"Load it from the environment or a secret store, and rotate it.",
|
|
175
|
+
"high",
|
|
176
|
+
["security"],
|
|
177
|
+
"8.1",
|
|
178
|
+
),
|
|
179
|
+
"jwt_unverified": (
|
|
180
|
+
"JwtUnverified",
|
|
181
|
+
"JWT verification turned off",
|
|
182
|
+
"Verify the signature with an explicit algorithm list; keep expiry checks on.",
|
|
183
|
+
"high",
|
|
184
|
+
["security"],
|
|
185
|
+
"8.1",
|
|
186
|
+
),
|
|
187
|
+
"weak_cipher": (
|
|
188
|
+
"WeakCipher",
|
|
189
|
+
"Broken cipher or mode (ECB, DES, RC4)",
|
|
190
|
+
"Use AES-GCM or a vetted library.",
|
|
191
|
+
"high",
|
|
192
|
+
["security"],
|
|
193
|
+
"7.5",
|
|
194
|
+
),
|
|
195
|
+
"weak_hash": (
|
|
196
|
+
"WeakHash",
|
|
197
|
+
"MD5 / SHA-1 used for security",
|
|
198
|
+
"bcrypt/scrypt/argon2 for passwords; HMAC-SHA-256 for signatures.",
|
|
199
|
+
"warn",
|
|
200
|
+
["security"],
|
|
201
|
+
"5.9",
|
|
202
|
+
),
|
|
203
|
+
"weak_random": (
|
|
204
|
+
"PredictableRandom",
|
|
205
|
+
"Predictable random numbers for a secret",
|
|
206
|
+
"Use `secrets` / `crypto.randomBytes` / `crypto.getRandomValues`.",
|
|
207
|
+
"warn",
|
|
208
|
+
["security"],
|
|
209
|
+
"5.9",
|
|
210
|
+
),
|
|
211
|
+
"cors_any": (
|
|
212
|
+
"CorsAnyOrigin",
|
|
213
|
+
"Any website may call this API (CORS *)",
|
|
214
|
+
"List the origins that need access.",
|
|
215
|
+
"warn",
|
|
216
|
+
["security"],
|
|
217
|
+
"5.3",
|
|
218
|
+
),
|
|
219
|
+
"insecure_cookie": (
|
|
220
|
+
"InsecureCookie",
|
|
221
|
+
"Session cookie without Secure / HttpOnly",
|
|
222
|
+
"Set Secure, HttpOnly and SameSite on session and auth cookies.",
|
|
223
|
+
"warn",
|
|
224
|
+
["security"],
|
|
225
|
+
"5.3",
|
|
226
|
+
),
|
|
227
|
+
"debug_on": (
|
|
228
|
+
"DebugEnabled",
|
|
229
|
+
"Debug mode switched on in code",
|
|
230
|
+
"Enable it from the environment for development only.",
|
|
231
|
+
"warn",
|
|
232
|
+
["security"],
|
|
233
|
+
"5.3",
|
|
234
|
+
),
|
|
235
|
+
"sensitive_storage": (
|
|
236
|
+
"SensitiveStorage",
|
|
237
|
+
"Token or password in unencrypted storage",
|
|
238
|
+
"Use Keychain/Keystore (SecureStore) or an HttpOnly cookie.",
|
|
239
|
+
"warn",
|
|
240
|
+
["security"],
|
|
241
|
+
"5.5",
|
|
242
|
+
),
|
|
243
|
+
"history_secret": (
|
|
244
|
+
"CredentialInHistory",
|
|
245
|
+
"A credential is in git history",
|
|
246
|
+
"Rotate it: history can't be unpublished.",
|
|
247
|
+
"high",
|
|
248
|
+
["security"],
|
|
249
|
+
"8.5",
|
|
250
|
+
),
|
|
251
|
+
"docker_secret": (
|
|
252
|
+
"SecretInImage",
|
|
253
|
+
"A secret is baked into a container image",
|
|
254
|
+
"Pass secrets at runtime, never in ENV/ARG.",
|
|
255
|
+
"high",
|
|
256
|
+
["security"],
|
|
257
|
+
"8.1",
|
|
258
|
+
),
|
|
259
|
+
"gha_injection": (
|
|
260
|
+
"WorkflowInjection",
|
|
261
|
+
"Untrusted text run as a shell command in CI",
|
|
262
|
+
"Pass it through an environment variable and quote it.",
|
|
263
|
+
"high",
|
|
264
|
+
["security"],
|
|
265
|
+
"8.8",
|
|
266
|
+
),
|
|
267
|
+
"gha_pr_target": (
|
|
268
|
+
"PullRequestTarget",
|
|
269
|
+
"pull_request_target workflow",
|
|
270
|
+
"Don't check out or build PR code under pull_request_target.",
|
|
271
|
+
"warn",
|
|
272
|
+
["security"],
|
|
273
|
+
"7.0",
|
|
274
|
+
),
|
|
275
|
+
"mobile_cleartext": (
|
|
276
|
+
"CleartextTraffic",
|
|
277
|
+
"App allows unencrypted HTTP",
|
|
278
|
+
"Remove the exception or limit it to hosts.",
|
|
279
|
+
"warn",
|
|
280
|
+
["security"],
|
|
281
|
+
"5.3",
|
|
282
|
+
),
|
|
283
|
+
"docker_root": ("ContainerRoot", "Container runs as root", "Add a non-root USER.", "warn", ["security"], "4.7"),
|
|
284
|
+
"gha_unpinned": (
|
|
285
|
+
"UnpinnedAction",
|
|
286
|
+
"Third-party CI action not pinned to a commit",
|
|
287
|
+
"Pin it to a full commit SHA.",
|
|
288
|
+
"info",
|
|
289
|
+
["security"],
|
|
290
|
+
"4.0",
|
|
291
|
+
),
|
|
292
|
+
"taint": (
|
|
293
|
+
"TaintedFlow",
|
|
294
|
+
"Request data reaches a dangerous call",
|
|
295
|
+
"Validate or convert the value (int(), an allow-list), or use the safe API (bound SQL parameters, argument lists, "
|
|
296
|
+
"an allow-listed URL or path).",
|
|
297
|
+
"high",
|
|
298
|
+
["security"],
|
|
299
|
+
"9.1",
|
|
300
|
+
),
|
|
301
|
+
"ios_usage_missing": (
|
|
302
|
+
"IosUsageDescriptionMissing",
|
|
303
|
+
"iOS permission used without a usage description",
|
|
304
|
+
"Add the Info.plist usage description.",
|
|
305
|
+
"high",
|
|
306
|
+
["privacy", "security"],
|
|
307
|
+
"6.5",
|
|
308
|
+
),
|
|
309
|
+
"ios_privacy_manifest": (
|
|
310
|
+
"IosPrivacyManifestMissing",
|
|
311
|
+
"Required-reason API without a privacy manifest",
|
|
312
|
+
"Add PrivacyInfo.xcprivacy with the reason codes.",
|
|
313
|
+
"high",
|
|
314
|
+
["privacy"],
|
|
315
|
+
"6.0",
|
|
316
|
+
),
|
|
317
|
+
"privacy_analytics": (
|
|
318
|
+
"PersonalDataToAnalytics",
|
|
319
|
+
"Personal data sent to analytics or crash reporting",
|
|
320
|
+
"Send an opaque id or a coarse value instead.",
|
|
321
|
+
"high",
|
|
322
|
+
["privacy"],
|
|
323
|
+
"6.5",
|
|
324
|
+
),
|
|
325
|
+
"privacy_log": (
|
|
326
|
+
"PersonalDataInLogs",
|
|
327
|
+
"Personal data written to logs",
|
|
328
|
+
"Log an id or a redacted value instead.",
|
|
329
|
+
"warn",
|
|
330
|
+
["privacy"],
|
|
331
|
+
"5.0",
|
|
332
|
+
),
|
|
333
|
+
"privacy_storage": (
|
|
334
|
+
"PersonalDataUnencrypted",
|
|
335
|
+
"Personal data in unencrypted storage",
|
|
336
|
+
"Keep it in a protected database or the platform's encrypted store.",
|
|
337
|
+
"warn",
|
|
338
|
+
["privacy"],
|
|
339
|
+
"5.0",
|
|
340
|
+
),
|
|
341
|
+
"config_secret": (
|
|
342
|
+
"ConfigCredential",
|
|
343
|
+
"Credential in a configuration file",
|
|
344
|
+
"Rotate it; read it from the environment.",
|
|
345
|
+
"high",
|
|
346
|
+
["security"],
|
|
347
|
+
"9.0",
|
|
348
|
+
),
|
|
349
|
+
"compose_secret": (
|
|
350
|
+
"ComposePassword",
|
|
351
|
+
"Password in docker-compose",
|
|
352
|
+
"Use an .env file or Compose secrets.",
|
|
353
|
+
"warn",
|
|
354
|
+
["security"],
|
|
355
|
+
"7.5",
|
|
356
|
+
),
|
|
357
|
+
"k8s_secret": (
|
|
358
|
+
"CommittedK8sSecret",
|
|
359
|
+
"Kubernetes Secret committed with values",
|
|
360
|
+
"Keep values out of git.",
|
|
361
|
+
"high",
|
|
362
|
+
["security"],
|
|
363
|
+
"7.5",
|
|
364
|
+
),
|
|
365
|
+
"shell_pipe": (
|
|
366
|
+
"CurlPipeShell",
|
|
367
|
+
"Download piped into a shell",
|
|
368
|
+
"Verify a checksum before running.",
|
|
369
|
+
"warn",
|
|
370
|
+
["security", "supply-chain"],
|
|
371
|
+
"6.5",
|
|
372
|
+
),
|
|
373
|
+
"html_no_sri": (
|
|
374
|
+
"NoSubresourceIntegrity",
|
|
375
|
+
"Third-party script without integrity",
|
|
376
|
+
"Add integrity=.",
|
|
377
|
+
"warn",
|
|
378
|
+
["security", "supply-chain"],
|
|
379
|
+
"6.1",
|
|
380
|
+
),
|
|
381
|
+
"html_mixed": ("MixedContent", "Resource or form over plain HTTP", "Use https://.", "warn", ["security"], "5.3"),
|
|
382
|
+
"compose_exposed": (
|
|
383
|
+
"ExposedDatabasePort",
|
|
384
|
+
"Database port published on every interface",
|
|
385
|
+
"Bind to 127.0.0.1.",
|
|
386
|
+
"warn",
|
|
387
|
+
["security"],
|
|
388
|
+
"6.5",
|
|
389
|
+
),
|
|
390
|
+
"compose_privileged": (
|
|
391
|
+
"PrivilegedCompose",
|
|
392
|
+
"Privileged container or host network",
|
|
393
|
+
"Drop privileges.",
|
|
394
|
+
"warn",
|
|
395
|
+
["security"],
|
|
396
|
+
"6.0",
|
|
397
|
+
),
|
|
398
|
+
"k8s_privileged": (
|
|
399
|
+
"PrivilegedPod",
|
|
400
|
+
"Privileged or root container",
|
|
401
|
+
"runAsNonRoot, no privilege escalation.",
|
|
402
|
+
"warn",
|
|
403
|
+
["security"],
|
|
404
|
+
"6.0",
|
|
405
|
+
),
|
|
406
|
+
"k8s_host": (
|
|
407
|
+
"HostNamespacePod",
|
|
408
|
+
"Pod using host network, PID, IPC or paths",
|
|
409
|
+
"Remove host access.",
|
|
410
|
+
"warn",
|
|
411
|
+
["security"],
|
|
412
|
+
"6.0",
|
|
413
|
+
),
|
|
414
|
+
"shell_rm_var": (
|
|
415
|
+
"RmRfEmptyVariable",
|
|
416
|
+
"rm -rf on a variable that may be empty",
|
|
417
|
+
'Use "${VAR:?}".',
|
|
418
|
+
"warn",
|
|
419
|
+
["reliability"],
|
|
420
|
+
None,
|
|
421
|
+
),
|
|
422
|
+
"shell_eval": ("ShellEval", "Shell eval of a variable", "Run the command directly.", "warn", ["security"], "6.0"),
|
|
423
|
+
"go_server_timeout": (
|
|
424
|
+
"GoServerNoTimeout",
|
|
425
|
+
"HTTP server without timeouts",
|
|
426
|
+
"Set ReadHeaderTimeout.",
|
|
427
|
+
"info",
|
|
428
|
+
["reliability"],
|
|
429
|
+
None,
|
|
430
|
+
),
|
|
431
|
+
"config_http": ("ConfigPlainHttp", "Plain-HTTP URL in configuration", "Use https://.", "info", ["security"], None),
|
|
432
|
+
"main_thread_io": (
|
|
433
|
+
"MainThreadIO",
|
|
434
|
+
"Disk or database work on the main thread",
|
|
435
|
+
"Move it off the main thread.",
|
|
436
|
+
"warn",
|
|
437
|
+
["performance"],
|
|
438
|
+
None,
|
|
439
|
+
),
|
|
440
|
+
"swift_retain_cycle": (
|
|
441
|
+
"RetainCycle",
|
|
442
|
+
"Closure kept by self captures self strongly",
|
|
443
|
+
"Capture [weak self].",
|
|
444
|
+
"warn",
|
|
445
|
+
["reliability"],
|
|
446
|
+
None,
|
|
447
|
+
),
|
|
448
|
+
"swift_force": ("ForceTryCast", "try! / as! crash on failure", "Use do/catch, try? or as?.", "info", ["reliability"], None),
|
|
449
|
+
"entitlement_weakened": (
|
|
450
|
+
"WeakenedEntitlement",
|
|
451
|
+
"Code-signing protection turned off",
|
|
452
|
+
"Remove the entitlement.",
|
|
453
|
+
"warn",
|
|
454
|
+
["security"],
|
|
455
|
+
"5.0",
|
|
456
|
+
),
|
|
457
|
+
"custom": ("CustomRule", "A custom rule from factory.toml matched", "See the rule's message.", "warn", ["custom"], None),
|
|
458
|
+
"docker_latest": (
|
|
459
|
+
"UnpinnedBaseImage",
|
|
460
|
+
"Container base image not pinned",
|
|
461
|
+
"Pin a version tag or digest.",
|
|
462
|
+
"info",
|
|
463
|
+
["maintainability"],
|
|
464
|
+
None,
|
|
465
|
+
),
|
|
466
|
+
"swallowed": (
|
|
467
|
+
"SwallowedError",
|
|
468
|
+
"An error is caught and dropped",
|
|
469
|
+
"Record it (log, local error file, crash reporting) before recovering; keep empty catches only for "
|
|
470
|
+
"expected cases, with a comment.",
|
|
471
|
+
"warn",
|
|
472
|
+
["reliability"],
|
|
473
|
+
None,
|
|
474
|
+
),
|
|
475
|
+
"fetch_no_timeout": (
|
|
476
|
+
"NoTimeout",
|
|
477
|
+
"Network call without a timeout",
|
|
478
|
+
"Give it a deadline (AbortSignal.timeout(ms) / requests' timeout=).",
|
|
479
|
+
"warn",
|
|
480
|
+
["reliability"],
|
|
481
|
+
None,
|
|
482
|
+
),
|
|
483
|
+
"module_state": (
|
|
484
|
+
"ModuleState",
|
|
485
|
+
"Mutable state at module level",
|
|
486
|
+
"Keep it in an owner with a lifecycle (a store, a context, an instance) and pass it explicitly.",
|
|
487
|
+
"info",
|
|
488
|
+
["reliability"],
|
|
489
|
+
None,
|
|
490
|
+
),
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def _rule(rid: str) -> dict:
|
|
495
|
+
name, short, fix, sev, tags, sec = RULES.get(
|
|
496
|
+
rid, (rid.title().replace("_", ""), f"Saved query: {rid}", "See factory.toml [[queries]].", "warn", ["custom"], None)
|
|
497
|
+
)
|
|
498
|
+
props = {"tags": tags, "precision": "medium"}
|
|
499
|
+
if sec:
|
|
500
|
+
props["security-severity"] = sec
|
|
501
|
+
return {
|
|
502
|
+
"id": rid,
|
|
503
|
+
"name": name,
|
|
504
|
+
"shortDescription": {"text": short},
|
|
505
|
+
"fullDescription": {"text": f"{short}. {fix}"},
|
|
506
|
+
"help": {"text": fix, "markdown": f"**{short}.** {fix}\n\n[codefactory]({HOME}#what-it-flags)"},
|
|
507
|
+
"helpUri": f"{HOME}#what-it-flags",
|
|
508
|
+
"defaultConfiguration": {"level": LEVEL[sev]},
|
|
509
|
+
"properties": props,
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def _fp(*parts: str) -> str:
|
|
514
|
+
return hashlib.sha256("|".join(parts).encode("utf-8", "surrogatepass")).hexdigest()[:32]
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def _loc(file: str, line: int, message: str | None = None, end: int | None = None) -> dict:
|
|
518
|
+
region = {"startLine": max(1, line or 1)}
|
|
519
|
+
if end and end >= region["startLine"]:
|
|
520
|
+
region["endLine"] = end
|
|
521
|
+
loc = {"physicalLocation": {"artifactLocation": {"uri": file, "uriBaseId": "%SRCROOT%"}, "region": region}}
|
|
522
|
+
if message:
|
|
523
|
+
loc["message"] = {"text": message}
|
|
524
|
+
return loc
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def build_sarif(graph: dict, root: Path | None = None, new_keys: Counter | None = None, min_level: str = "info") -> dict:
|
|
528
|
+
"""graph: from load_graph. root: the repo, to add the source checks (secrets, SQL from strings, …).
|
|
529
|
+
new_keys: issue keys new since the baseline (baselineState); None = no baseline."""
|
|
530
|
+
order = {"high": 0, "warn": 1, "info": 2}
|
|
531
|
+
fns = {f["id"]: f for f in graph["functions"]}
|
|
532
|
+
results, seen, used = [], Counter(), set()
|
|
533
|
+
|
|
534
|
+
def add(rule: str, sev: str, message: str, loc: dict, key: str, related=(), suppressed: str | None = None, state=None):
|
|
535
|
+
if order[sev] > order[min_level]:
|
|
536
|
+
return
|
|
537
|
+
seen[key] += 1
|
|
538
|
+
if related: # GitHub and VS Code turn [text](n) into links to the related locations
|
|
539
|
+
links = ", ".join(f"[{rl['message']['text']}]({i})" for i, rl in enumerate(related, 1) if rl.get("message"))
|
|
540
|
+
message = f"{message} See: {links}." if links else message
|
|
541
|
+
r = {
|
|
542
|
+
"ruleId": rule,
|
|
543
|
+
"level": LEVEL[sev],
|
|
544
|
+
"message": {"text": message},
|
|
545
|
+
"locations": [loc],
|
|
546
|
+
"partialFingerprints": {"codefactory/v1": _fp(key, str(seen[key]))},
|
|
547
|
+
}
|
|
548
|
+
if related:
|
|
549
|
+
r["relatedLocations"] = [dict(rl, id=i) for i, rl in enumerate(related, 1)]
|
|
550
|
+
if suppressed is not None:
|
|
551
|
+
r["suppressions"] = [{"kind": "inSource", "justification": suppressed or "marked as intended"}]
|
|
552
|
+
if state:
|
|
553
|
+
r["baselineState"] = state
|
|
554
|
+
results.append(r)
|
|
555
|
+
used.add(rule)
|
|
556
|
+
|
|
557
|
+
new_left = Counter(new_keys) if new_keys is not None else None
|
|
558
|
+
for flags, quiet in ((graph["flags"], False), (graph.get("silenced", []), True)):
|
|
559
|
+
for f in flags:
|
|
560
|
+
fn = fns.get(f["target"])
|
|
561
|
+
file = fn["file"] if fn else f["target"]
|
|
562
|
+
line = f.get("line") or (fn["line"] if fn else 1)
|
|
563
|
+
related = []
|
|
564
|
+
for rid in f.get("related", [])[:10]:
|
|
565
|
+
other = fns.get(rid)
|
|
566
|
+
if other:
|
|
567
|
+
related.append(_loc(other["file"], other["line"], f"{other['qualname']} ({other['file']}:{other['line']})"))
|
|
568
|
+
elif "/" in rid:
|
|
569
|
+
related.append(_loc(rid, 1, rid))
|
|
570
|
+
key = issue_key(graph, f, fns)
|
|
571
|
+
state = None
|
|
572
|
+
if new_left is not None and not quiet:
|
|
573
|
+
state = "new" if new_left[key] > 0 else "unchanged"
|
|
574
|
+
if new_left[key] > 0:
|
|
575
|
+
new_left[key] -= 1
|
|
576
|
+
add(
|
|
577
|
+
f["kind"],
|
|
578
|
+
f["severity"],
|
|
579
|
+
f["message"],
|
|
580
|
+
_loc(file, line),
|
|
581
|
+
key,
|
|
582
|
+
related,
|
|
583
|
+
f.get("reason", "") if quiet else None,
|
|
584
|
+
state,
|
|
585
|
+
)
|
|
586
|
+
|
|
587
|
+
if root is not None: # line-level source checks (as in the review)
|
|
588
|
+
sev_of = {k: v[3] for k, v in RULES.items()}
|
|
589
|
+
from .audit import current_secrets
|
|
590
|
+
from .audit import scan as audit_scan
|
|
591
|
+
|
|
592
|
+
sources = source_files(root, graph) # parsed or not: line checks need no parser
|
|
593
|
+
checks = scan_sources(root, sources)
|
|
594
|
+
checks.update(audit_scan(root, current_secrets(checks["secret"]))[0])
|
|
595
|
+
from .privacy import scan as privacy_scan
|
|
596
|
+
|
|
597
|
+
checks.update(privacy_scan(root, sources))
|
|
598
|
+
from .apple import scan as apple_scan
|
|
599
|
+
|
|
600
|
+
checks.update(apple_scan(root, sources))
|
|
601
|
+
from .config import load_config
|
|
602
|
+
from .infra import scan as infra_scan
|
|
603
|
+
|
|
604
|
+
checks.update(infra_scan(root, set(load_config(root).ignore)))
|
|
605
|
+
for key, check in checks.items():
|
|
606
|
+
if key not in RULES:
|
|
607
|
+
continue
|
|
608
|
+
for e in check.hits:
|
|
609
|
+
text = {
|
|
610
|
+
"sql_built": "SQL built from strings"
|
|
611
|
+
+ (f" (interpolates: {', '.join(check.data.get(e.at(), []))})" if check.data.get(e.at()) else ""),
|
|
612
|
+
}.get(key, RULES[key][1])
|
|
613
|
+
add(key, sev_of[key], f"{text}: {e.text}", _loc(e.file, e.line), f"{key}|{e.file}|{e.text}")
|
|
614
|
+
|
|
615
|
+
from .owners import load as load_owners
|
|
616
|
+
|
|
617
|
+
owners = load_owners(Path(graph["root"])) if graph.get("root") else None
|
|
618
|
+
if owners: # route each result to its team (CODEOWNERS)
|
|
619
|
+
for r in results:
|
|
620
|
+
uri = r["locations"][0]["physicalLocation"]["artifactLocation"]["uri"]
|
|
621
|
+
if who := owners.of(uri):
|
|
622
|
+
r.setdefault("properties", {})["owners"] = who
|
|
623
|
+
|
|
624
|
+
return {
|
|
625
|
+
"$schema": SCHEMA,
|
|
626
|
+
"version": "2.1.0",
|
|
627
|
+
"runs": [
|
|
628
|
+
{
|
|
629
|
+
"tool": {
|
|
630
|
+
"driver": {
|
|
631
|
+
"name": "codefactory",
|
|
632
|
+
"version": __version__,
|
|
633
|
+
"semanticVersion": __version__,
|
|
634
|
+
"informationUri": HOME,
|
|
635
|
+
"rules": [_rule(r) for r in sorted(used)],
|
|
636
|
+
}
|
|
637
|
+
},
|
|
638
|
+
"automationDetails": {"id": "codefactory/"},
|
|
639
|
+
**({"originalUriBaseIds": {"%SRCROOT%": {"uri": root.resolve().as_uri() + "/"}}} if root is not None else {}),
|
|
640
|
+
"columnKind": "unicodeCodePoints",
|
|
641
|
+
"results": results,
|
|
642
|
+
}
|
|
643
|
+
],
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def github_annotations(graph: dict, flags: list[dict], limit: int = 50) -> str:
|
|
648
|
+
"""GitHub Actions workflow commands: each issue becomes an annotation on its line in the pull request."""
|
|
649
|
+
fns = {f["id"]: f for f in graph["functions"]}
|
|
650
|
+
cmd = {"high": "error", "warn": "warning", "info": "notice"}
|
|
651
|
+
out = []
|
|
652
|
+
for f in flags[:limit]:
|
|
653
|
+
fn = fns.get(f["target"])
|
|
654
|
+
file = fn["file"] if fn else f["target"]
|
|
655
|
+
line = f.get("line") or (fn["line"] if fn else 1)
|
|
656
|
+
msg = f["message"].replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
|
|
657
|
+
title = f"codefactory {f['kind']}".replace(",", " ").replace("::", " ")
|
|
658
|
+
out.append(f"::{cmd[f['severity']]} file={file},line={line},title={title}::{msg}")
|
|
659
|
+
if len(flags) > limit:
|
|
660
|
+
out.append(f"::notice title=codefactory::{len(flags) - limit} more issues not annotated (codefactory flags lists all)")
|
|
661
|
+
return "\n".join(out)
|