Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
297 lines (284 loc) · 11.2 KB
/
Copy pathcli.py
File metadata and controls
297 lines (284 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
from __future__ import annotations
import argparse
import sys
import zipfile
from datetime import UTC, datetime
from pathlib import Path
from coretrace_python import __version__, engine
from coretrace_python.analysis import AnalysisError
from coretrace_python.cache import ProjectCache
from coretrace_python.cfg import CFGError
from coretrace_python.dependency import (
dump_advisories,
import_osv,
read_osv,
render_sbom,
render_vex,
)
from coretrace_python.findings import Severity
from coretrace_python.findings.baseline import Baseline, BaselineError
from coretrace_python.frontend import HIRBuildError, ParseError, build_hir
from coretrace_python.ir.lowering import LoweringError, lower_module
from coretrace_python.ir.printer import format_module
from coretrace_python.plugins import IncompatiblePluginError, ManifestError
from coretrace_python.reporters import FORMATS, render
from coretrace_python.semantic.imports import ImportResolutionError
from coretrace_python.semantic.scopes import ScopeError
from coretrace_python.source import SourceManager
from coretrace_python.taint import ModelError
EXIT_CLEAN = 0
EXIT_FINDINGS = 1
EXIT_ERROR = 2
_ANALYSIS_ERRORS = (
BaselineError,
OSError,
UnicodeError,
ParseError,
HIRBuildError,
ImportResolutionError,
ScopeError,
CFGError,
LoweringError,
AnalysisError,
ManifestError,
IncompatiblePluginError,
ModelError,
)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog=engine.TOOL_NAME,
description="Analyze Python source with CoreTrace.",
)
parser.add_argument(
"path", type=Path, nargs="?", help="Python source file, or a directory for --check"
)
parser.add_argument(
"--emit-ir",
action="store_true",
help="print the lowered Python intermediate representation",
)
parser.add_argument(
"--ssa",
action="store_true",
help="with --emit-ir, print the static single assignment form",
)
parser.add_argument(
"--check",
action="store_true",
help="run the loaded plugins and report their findings",
)
parser.add_argument(
"--plugins",
action="append",
type=Path,
default=[],
metavar="DIR",
help="with --check, a directory searched recursively for plugin.toml, loaded on "
"top of the bundled plugins (repeatable)",
)
parser.add_argument(
"--no-bundled-plugins",
action="store_true",
help="with --check, do not load the plugins shipped with the package",
)
parser.add_argument(
"--format",
choices=sorted(FORMATS),
default=None,
help="with --check, the report format (default: text)",
)
parser.add_argument(
"--cache",
type=Path,
default=None,
metavar="DIR",
help="with --check on a directory, keep per-module results under DIR and reuse "
"them for modules unchanged since the previous run",
)
parser.add_argument(
"--jobs",
type=int,
default=None,
metavar="N",
help="with --check on a directory, analyse independent modules in N processes",
)
parser.add_argument(
"--sbom",
type=Path,
default=None,
metavar="PATH",
help="with --check on a directory, write a CycloneDX bill of materials to PATH",
)
parser.add_argument(
"--vex",
type=Path,
default=None,
metavar="PATH",
help="with --check on a directory, write to PATH an OpenVEX document saying whether "
"each advisory affecting a requirement affects the project",
)
parser.add_argument(
"--advisories",
action="append",
type=Path,
default=[],
metavar="FILE",
help="with --check on a directory, a local advisory file to read in addition to "
"advisories.json at the root (repeatable)",
)
parser.add_argument(
"--policy",
type=Path,
default=None,
metavar="FILE",
help="with --check on a directory, the dependency policy to apply instead of "
"coretrace-policy.toml at the root",
)
parser.add_argument(
"--baseline",
type=Path,
default=None,
metavar="PATH",
help="with --check, the accepted findings: written on the first run, then only "
"findings not recorded there fail the check",
)
parser.add_argument(
"--fail-on",
choices=[severity.value for severity in Severity],
default=None,
metavar="SEVERITY",
help="with --check, exit with status 1 only when a finding of this severity or "
"above was reported (info, low, medium, high, critical); default: any finding",
)
parser.add_argument(
"--import-advisories",
nargs=2,
type=Path,
default=None,
metavar=("SRC", "OUT"),
help="convert an OSV dump (a JSON file, a directory of them or a zip archive) "
"into the local advisory file OUT, then exit",
)
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
if args.import_advisories is not None:
source, out = args.import_advisories
try:
out.write_text(dump_advisories(import_osv(read_osv(source))), encoding="utf-8")
except (OSError, ValueError, zipfile.BadZipFile) as error:
print(f"error: {error}", file=sys.stderr)
return EXIT_ERROR
return EXIT_CLEAN
if not (args.emit_ir or args.check):
print("error: no action selected; pass --emit-ir or --check", file=sys.stderr)
return EXIT_ERROR
if args.path is None:
print("error: a path is required", file=sys.stderr)
return EXIT_ERROR
if args.format is not None and not args.check:
print("error: --format only applies to --check", file=sys.stderr)
return EXIT_ERROR
if args.cache is not None and not (args.check and args.path.is_dir()):
print("error: --cache only applies to --check on a directory", file=sys.stderr)
return EXIT_ERROR
if args.jobs is not None and not (args.check and args.path.is_dir()):
print("error: --jobs only applies to --check on a directory", file=sys.stderr)
return EXIT_ERROR
if args.jobs is not None and args.jobs < 1:
print("error: --jobs must be at least 1", file=sys.stderr)
return EXIT_ERROR
if args.sbom is not None and not (args.check and args.path.is_dir()):
print("error: --sbom only applies to --check on a directory", file=sys.stderr)
return EXIT_ERROR
if args.vex is not None and not (args.check and args.path.is_dir()):
print("error: --vex only applies to --check on a directory", file=sys.stderr)
return EXIT_ERROR
if args.advisories and not (args.check and args.path.is_dir()):
print("error: --advisories only applies to --check on a directory", file=sys.stderr)
return EXIT_ERROR
if args.policy is not None and not (args.check and args.path.is_dir()):
print("error: --policy only applies to --check on a directory", file=sys.stderr)
return EXIT_ERROR
if args.fail_on is not None and not args.check:
print("error: --fail-on only applies to --check", file=sys.stderr)
return EXIT_ERROR
if args.baseline is not None and not args.check:
print("error: --baseline only applies to --check", file=sys.stderr)
return EXIT_ERROR
if args.no_bundled_plugins and not args.check:
print("error: --no-bundled-plugins only applies to --check", file=sys.stderr)
return EXIT_ERROR
plugin_roots = ([] if args.no_bundled_plugins else [engine.BUNDLED_PLUGINS]) + list(args.plugins)
if args.path.is_dir() and args.emit_ir:
print(f"error: {args.path} is a directory; --emit-ir needs a file", file=sys.stderr)
return EXIT_ERROR
try:
if args.emit_ir:
source = SourceManager().load_file(args.path)
print(format_module(lower_module(build_hir(source), ssa=args.ssa)))
if args.check:
if args.path.is_dir():
cache = None if args.cache is None else ProjectCache(args.cache)
analysis = engine.analyze_project(
args.path,
plugin_roots,
cache=cache,
jobs=args.jobs or 1,
advisory_files=args.advisories,
policy_file=args.policy,
)
findings = analysis.findings
coverage = analysis.coverage
suppressed = analysis.suppressed
components = analysis.components
if args.sbom is not None:
args.sbom.write_text(
render_sbom(
analysis.dependencies, analysis.advisories, engine.TOOL_NAME, __version__, analysis.components
),
encoding="utf-8",
)
if args.vex is not None:
args.vex.write_text(
render_vex(
analysis.dependencies,
analysis.advisories,
(*analysis.findings, *analysis.suppressed, *analysis.accepted),
analysis.coverage,
args.path,
engine.TOOL_NAME,
__version__,
datetime.now(UTC),
analysis.components,
),
encoding="utf-8",
)
else:
file_analysis = engine.analyze_file(SourceManager().load_file(args.path), plugin_roots)
findings, coverage = file_analysis.findings, file_analysis.coverage
suppressed = file_analysis.suppressed
components = ()
root = args.path.resolve() if args.path.is_dir() else args.path.resolve().parent
baselined = None
if args.baseline is not None:
if args.baseline.is_file():
baseline = Baseline.load(args.baseline)
findings, baselined = baseline.partition(findings, root)
notice = baseline.transition_notice(findings)
if notice is not None:
print(f"coretrace: {args.baseline}: {notice}", file=sys.stderr)
else:
Baseline.of(findings, root).save(args.baseline)
findings, baselined = (), findings
report = engine.report(findings, coverage, root, suppressed, baselined, components)
print(render(args.format or "text", report), end="")
threshold = Severity(args.fail_on).rank if args.fail_on is not None else 0
failing = any(finding.severity.rank >= threshold for finding in findings)
return EXIT_FINDINGS if failing else EXIT_CLEAN
except _ANALYSIS_ERRORS as error:
print(f"error: {error}", file=sys.stderr)
return EXIT_ERROR
return EXIT_CLEAN
if __name__ == "__main__":
raise SystemExit(main())