|
| 1 | +import json |
| 2 | +from dataclasses import dataclass |
| 3 | +from typing import Dict, Optional |
| 4 | + |
| 5 | +from scanoss.scanossbase import ScanossBase |
| 6 | +from scanoss.scanossgrpc import ScanossGrpc |
| 7 | +from scanoss.utils.abstract_presenter import AbstractPresenter |
| 8 | +from scanoss.utils.file import validate_json_file |
| 9 | + |
| 10 | + |
| 11 | +class ScanossCryptographyError(Exception): |
| 12 | + pass |
| 13 | + |
| 14 | + |
| 15 | +@dataclass |
| 16 | +class CryptographyConfig: |
| 17 | + debug: bool = False |
| 18 | + trace: bool = False |
| 19 | + quiet: bool = False |
| 20 | + get_range: bool = False |
| 21 | + purl: str = None |
| 22 | + input_file: str = None |
| 23 | + output_file: str = None |
| 24 | + header: str = None |
| 25 | + |
| 26 | + |
| 27 | +def create_cryptography_config_from_args(args) -> CryptographyConfig: |
| 28 | + return CryptographyConfig( |
| 29 | + debug=getattr(args, 'debug', None), |
| 30 | + trace=getattr(args, 'trace', None), |
| 31 | + quiet=getattr(args, 'quiet', None), |
| 32 | + get_range=getattr(args, 'range', None), |
| 33 | + purl=getattr(args, 'purl', None), |
| 34 | + input_file=getattr(args, 'input', None), |
| 35 | + output_file=getattr(args, 'output', None), |
| 36 | + header=getattr(args, 'header', None), |
| 37 | + ) |
| 38 | + |
| 39 | + |
| 40 | +class Cryptography: |
| 41 | + """ |
| 42 | + Cryptography Class |
| 43 | +
|
| 44 | + This class is used to decorate purls with cryptography information. |
| 45 | + """ |
| 46 | + |
| 47 | + def __init__( |
| 48 | + self, |
| 49 | + config: CryptographyConfig, |
| 50 | + client: ScanossGrpc, |
| 51 | + ): |
| 52 | + """ |
| 53 | + Initialize the Cryptography. |
| 54 | +
|
| 55 | + Args: |
| 56 | + config (CryptographyConfig): Configuration parameters for the cryptography. |
| 57 | + client (ScanossGrpc): gRPC client for communicating with the scanning service. |
| 58 | + """ |
| 59 | + self.base = ScanossBase( |
| 60 | + debug=config.debug, |
| 61 | + trace=config.trace, |
| 62 | + quiet=config.quiet, |
| 63 | + ) |
| 64 | + self.presenter = CryptographyPresenter( |
| 65 | + self, |
| 66 | + debug=config.debug, |
| 67 | + trace=config.trace, |
| 68 | + quiet=config.quiet, |
| 69 | + ) |
| 70 | + |
| 71 | + self.client = client |
| 72 | + self.config = config |
| 73 | + self.purls_request = self._build_purls_request() |
| 74 | + self.results = None |
| 75 | + |
| 76 | + def get_algorithms(self) -> Optional[Dict]: |
| 77 | + """ |
| 78 | + Get the cryptographic algorithms for the provided purl or input file. |
| 79 | +
|
| 80 | + Returns: |
| 81 | + Optional[Dict]: The folder hash response from the gRPC client, or None if an error occurs. |
| 82 | + """ |
| 83 | + |
| 84 | + try: |
| 85 | + self.base.print_stderr( |
| 86 | + f'Getting cryptographic algorithms for {", ".join([p["purl"] for p in self.purls_request["purls"]])}' |
| 87 | + ) |
| 88 | + if self.config.get_range: |
| 89 | + response = self.client.get_crypto_algorithms_in_range_for_purl(self.purls_request) |
| 90 | + else: |
| 91 | + response = self.client.get_crypto_algorithms_for_purl(self.purls_request) |
| 92 | + if response: |
| 93 | + self.results = response |
| 94 | + except Exception as e: |
| 95 | + raise ScanossCryptographyError(f'Problem with purl input file. {e}') |
| 96 | + |
| 97 | + return self.results |
| 98 | + |
| 99 | + def _build_purls_request( |
| 100 | + self, |
| 101 | + ) -> Optional[dict]: |
| 102 | + """ |
| 103 | + Load the specified purls from a JSON file or a list of PURLs and return a dictionary |
| 104 | +
|
| 105 | + Args: |
| 106 | + json_file (Optional[str], optional): The JSON file containing the PURLs. Defaults to None. |
| 107 | + purls (Optional[List[str]], optional): The list of PURLs. Defaults to None. |
| 108 | +
|
| 109 | + Returns: |
| 110 | + Optional[dict]: The dictionary containing the PURLs |
| 111 | + """ |
| 112 | + if self.config.input_file: |
| 113 | + input_file_validation = validate_json_file(self.config.input_file) |
| 114 | + if not input_file_validation.is_valid: |
| 115 | + self.base.print_stderr( |
| 116 | + f'ERROR: The supplied input file "{self.config.input_file}" was not found or is empty.' |
| 117 | + ) |
| 118 | + raise Exception(f'Problem with purl input file. {input_file_validation.error}') |
| 119 | + # Validate the input file is in PurlRequest format |
| 120 | + if ( |
| 121 | + not isinstance(input_file_validation.data, dict) |
| 122 | + or 'purls' not in input_file_validation.data |
| 123 | + or not isinstance(input_file_validation.data['purls'], list) |
| 124 | + or not all(isinstance(p, dict) and 'purl' in p for p in input_file_validation.data['purls']) |
| 125 | + ): |
| 126 | + raise Exception('The supplied input file is not in the correct PurlRequest format.') |
| 127 | + return input_file_validation.data |
| 128 | + if self.config.purl: |
| 129 | + return {'purls': [{'purl': p} for p in self.config.purl]} |
| 130 | + return None |
| 131 | + |
| 132 | + def present(self, output_format: str = None, output_file: str = None): |
| 133 | + """Present the results in the selected format""" |
| 134 | + self.presenter.present(output_format=output_format, output_file=output_file) |
| 135 | + |
| 136 | + |
| 137 | +class CryptographyPresenter(AbstractPresenter): |
| 138 | + """ |
| 139 | + Cryptography presenter class |
| 140 | + Handles the presentation of the cryptography results |
| 141 | + """ |
| 142 | + |
| 143 | + def __init__(self, cryptography: Cryptography, **kwargs): |
| 144 | + super().__init__(**kwargs) |
| 145 | + self.cryptography = cryptography |
| 146 | + |
| 147 | + def _format_json_output(self) -> str: |
| 148 | + """ |
| 149 | + Format the scan output data into a JSON object |
| 150 | +
|
| 151 | + Returns: |
| 152 | + str: The formatted JSON string |
| 153 | + """ |
| 154 | + return json.dumps(self.cryptography.results, indent=2) |
| 155 | + |
| 156 | + def _format_plain_output(self) -> str: |
| 157 | + """ |
| 158 | + Format the scan output data into a plain text string |
| 159 | + """ |
| 160 | + return ( |
| 161 | + json.dumps(self.cryptography.results, indent=2) |
| 162 | + if isinstance(self.cryptography.results, dict) |
| 163 | + else str(self.cryptography.results) |
| 164 | + ) |
| 165 | + |
| 166 | + def _format_cyclonedx_output(self) -> str: |
| 167 | + raise NotImplementedError('CycloneDX output is not implemented') |
| 168 | + |
| 169 | + def _format_spdxlite_output(self) -> str: |
| 170 | + raise NotImplementedError('SPDXlite output is not implemented') |
| 171 | + |
| 172 | + def _format_csv_output(self) -> str: |
| 173 | + raise NotImplementedError('CSV output is not implemented') |
| 174 | + |
| 175 | + def _format_raw_output(self) -> str: |
| 176 | + raise NotImplementedError('Raw output is not implemented') |
0 commit comments