-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequirements.py
More file actions
389 lines (317 loc) · 13.5 KB
/
requirements.py
File metadata and controls
389 lines (317 loc) · 13.5 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
"""Define requirements for SAST tools and their fulfillment status."""
from __future__ import annotations
import re
import shutil
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Literal
import typer
from packaging import version
from rich import print
from codesectools.utils import USER_CACHE_DIR, USER_CONFIG_DIR, run_command
if TYPE_CHECKING:
from pathlib import Path
class SASTRequirement(ABC):
"""Represent a single requirement for a SAST tool to be functional."""
def __init__(
self,
name: str,
depends_on: list[SASTRequirement] | None = None,
instruction: str | None = None,
url: str | None = None,
doc: bool = False,
) -> None:
"""Initialize a SASTRequirement instance.
Args:
name: The name of the requirement.
depends_on: A list of other requirements that must be fulfilled first.
instruction: A short instruction on how to download the requirement.
url: A URL for more detailed instructions.
doc: A flag indicating if the instruction is available in the documentation.
"""
self.name = name
self.depends_on = depends_on
self.instruction = instruction
self.url = url
self.doc = doc
@abstractmethod
def is_fulfilled(self, **kwargs: Any) -> bool:
"""Check if the requirement is met."""
pass
def dependencies_fulfilled(self) -> bool:
"""Check if all dependencies for this requirement are fulfilled."""
if not self.depends_on:
return True
return all(dependency.is_fulfilled() for dependency in self.depends_on)
def __repr__(self) -> str:
"""Return a developer-friendly string representation of the requirement."""
return f"{self.__class__.__name__}({self.name})"
class DownloadableRequirement(SASTRequirement):
"""Represent a SAST requirement that can be downloaded automatically."""
def __init__(
self,
name: str,
depends_on: list[SASTRequirement] | None = None,
instruction: str | None = None,
url: str | None = None,
doc: bool = False,
) -> None:
"""Initialize a DownloadableRequirement instance.
Sets a standard instruction message on how to download the requirement using the CLI.
Args:
name: The name of the requirement.
depends_on: A list of other requirements that must be fulfilled first.
instruction: A short instruction on how to download the requirement.
url: A URL for more detailed instructions.
doc: A flag indicating if the instruction is available in the documentation.
"""
instruction = f"cstools download {name}"
super().__init__(
name=name, depends_on=depends_on, instruction=instruction, url=url, doc=doc
)
@abstractmethod
def download(self, **kwargs: Any) -> None:
"""Download the requirement."""
pass
class Config(SASTRequirement):
"""Represent a configuration file requirement for a SAST tool."""
def __init__(
self,
name: str,
sast_name: str,
depends_on: list[SASTRequirement] | None = None,
instruction: str | None = None,
url: str | None = None,
doc: bool = False,
) -> None:
"""Initialize a Config instance.
Args:
name: The name of the requirement.
sast_name: The name of the SAST tool this config belongs to.
depends_on: A list of other requirements that must be fulfilled first.
instruction: A short instruction on how to download the requirement.
url: A URL for more detailed instructions.
doc: A flag indicating if the instruction is available in the documentation.
"""
self.sast_name = sast_name
super().__init__(
name=name, depends_on=depends_on, instruction=instruction, url=url, doc=doc
)
def is_fulfilled(self, **kwargs: Any) -> bool:
"""Check if the configuration file exists for the given SAST tool."""
return (USER_CONFIG_DIR / self.sast_name / self.name).is_file()
class BinaryVersion:
"""Represent a version requirement for a binary."""
def __init__(self, command_flag: str, pattern: str, expected: str) -> None:
"""Initialize a Version instance.
Args:
command_flag: The command line flag to get the version string (e.g., '--version').
pattern: A regex pattern to extract the version number from the output.
expected: The minimum expected version string.
"""
self.command_flag = command_flag
self.pattern = pattern
self.expected = version.parse(expected)
def check(self, binary: Binary) -> bool:
"""Check if the binary's version meets the requirement.
Args:
binary: The Binary requirement object to check.
Returns:
True if the version is sufficient, False otherwise.
"""
retcode, output = run_command([binary.name, self.command_flag])
if m := re.search(self.pattern, output):
detected_version = version.parse(m.group(1))
return detected_version >= self.expected
return False
class Binary(SASTRequirement):
"""Represent a binary executable requirement for a SAST tool."""
def __init__(
self,
name: str,
depends_on: list[SASTRequirement] | None = None,
version: BinaryVersion | None = None,
instruction: str | None = None,
url: str | None = None,
doc: bool = False,
) -> None:
"""Initialize a Binary instance.
Args:
name: The name of the requirement.
depends_on: A list of other requirements that must be fulfilled first.
version: An optional BinaryVersion object to check for a minimum version.
instruction: A short instruction on how to download the requirement.
url: A URL for more detailed instructions.
doc: A flag indicating if the instruction is available in the documentation.
"""
super().__init__(
name=name, depends_on=depends_on, instruction=instruction, url=url, doc=doc
)
self.version = version
def __repr__(self) -> str:
"""Return a developer-friendly string representation of the requirement."""
if self.version:
return f"{self.__class__.__name__}({self.name}>={self.version.expected})"
else:
return super().__repr__()
def is_fulfilled(self, **kwargs: Any) -> bool:
"""Check if the binary is available in the system's PATH."""
if bool(shutil.which(self.name)):
if self.version:
return self.version.check(self)
return True
else:
return False
class GitRepo(DownloadableRequirement):
"""Represent a Git repository requirement that can be downloaded."""
def __init__(
self,
name: str,
repo_url: str,
license: str,
license_url: str,
depends_on: list[SASTRequirement] | None = None,
instruction: str | None = None,
url: str | None = None,
doc: bool = False,
) -> None:
"""Initialize a GitRepo requirement instance.
Args:
name: The name of the requirement.
repo_url: The URL of the Git repository to clone.
license: The license of the repository.
license_url: A URL for the repository's license.
depends_on: A list of other requirements that must be fulfilled first.
instruction: A short instruction on how to download the requirement.
url: A URL for more detailed instructions.
doc: A flag indicating if the instruction is available in the documentation.
"""
super().__init__(
name=name, depends_on=depends_on, instruction=instruction, url=url, doc=doc
)
self.repo_url = repo_url
self.license = license
self.license_url = license_url
self.directory = USER_CACHE_DIR / self.name
def is_fulfilled(self, **kwargs: Any) -> bool:
"""Check if the Git repository has been cloned."""
return (self.directory / ".complete").is_file()
def download(self, **kwargs: Any) -> None:
"""Prompt for license agreement and clone the Git repository."""
from git import Repo
from rich.panel import Panel
from rich.progress import Progress
panel = Panel(
f"""Repository:\t[b]{self.name}[/b]
Repository URL:\t[u]{self.repo_url.rstrip(".git")}[/u]
License:\t[b]{self.license}[/b]
License URL:\t[u]{self.license_url}[/u]
Please review the license of the repository at the URL above.
By proceeding, you agree to abide by its terms.""",
title="[b]License Agreement[/b]",
)
print(panel)
agreed = typer.confirm("Do you accept the license terms and wish to proceed?")
if not agreed:
print("[red]License agreement declined. Download aborted.[/red]")
raise typer.Exit(code=1)
with Progress() as progress:
progress.add_task(f"Cloning repository [b]{self.name}[/b]...", total=None)
Repo.clone_from(
self.repo_url,
self.directory,
depth=1,
)
(self.directory / ".complete").write_bytes(b"\x42")
print(f"[b]{self.name}[/b] has been downloaded at {self.directory}.")
class File(DownloadableRequirement):
"""Represent a file requirement that can be downloaded."""
def __init__(
self,
name: str,
parent_dir: Path,
file_url: str,
license: str,
license_url: str,
depends_on: list[SASTRequirement] | None = None,
instruction: str | None = None,
url: str | None = None,
doc: bool = False,
) -> None:
"""Initialize a File requirement instance.
Args:
name: The name of the requirement.
parent_dir: The directory where the file should be saved.
file_url: The URL to download the file from.
license: The license of the file.
license_url: A URL for the file's license.
depends_on: A list of other requirements that must be fulfilled first.
instruction: A short instruction on how to download the requirement.
url: A URL for more detailed instructions.
doc: A flag indicating if the instruction is available in the documentation.
"""
super().__init__(
name=name, depends_on=depends_on, instruction=instruction, url=url, doc=doc
)
self.parent_dir = parent_dir
self.file_url = file_url
self.license = license
self.license_url = license_url
def is_fulfilled(self, **kwargs: Any) -> bool:
"""Check if the file has been downloaded."""
return bool(list(self.parent_dir.glob(self.name)))
def download(self, **kwargs: Any) -> None:
"""Prompt for license agreement and download the file."""
import requests
from rich.panel import Panel
from rich.progress import Progress
panel = Panel(
f"""File:\t\t[b]{self.name}[/b]
Download URL:\t[u]{self.file_url}[/u]
License:\t[b]{self.license}[/b]
License URL:\t[u]{self.license_url}[/u]
Please review the license of the repository at the URL above.
By proceeding, you agree to abide by its terms.""",
title="[b]License Agreement[/b]",
)
print(panel)
agreed = typer.confirm("Do you accept the license terms and wish to proceed?")
if not agreed:
print("[red]License agreement declined. Download aborted.[/red]")
raise typer.Exit(code=1)
with Progress() as progress:
progress.add_task(f"Downloading file [b]{self.name}[/b]...", total=None)
response = requests.get(self.file_url)
(self.parent_dir / self.name).write_bytes(response.content)
print(f"[b]{self.name}[/b] has been downloaded at {self.parent_dir}.")
class SASTRequirements:
"""Manage the requirements for a SAST tool and determine its operational status."""
def __init__(
self, full_reqs: list[SASTRequirement], partial_reqs: list[SASTRequirement]
) -> None:
"""Initialize a SASTRequirements instance.
Args:
full_reqs: A list of requirements for full functionality.
partial_reqs: A list of requirements for partial functionality.
"""
self.name = None
self.full = full_reqs
self.partial = partial_reqs
self.all = full_reqs + partial_reqs
def get_status(self) -> Literal["full"] | Literal["partial"] | Literal["none"]:
"""Determine the operational status (full, partial, none) based on fulfilled requirements."""
# full: can run sast analysis and result parsing
# partial: can run result parsing
# none: nothing
status = "none"
if all(req.is_fulfilled(sast_name=self.name) for req in self.partial):
status = "partial"
if all(req.is_fulfilled(sast_name=self.name) for req in self.full):
status = "full"
return status
def get_missing(self) -> list[SASTRequirement]:
"""Get a list of all unfulfilled requirements."""
missing = []
for req in self.all:
if not req.is_fulfilled(sast_name=self.name):
missing.append(req)
return missing