ai_sec 0.0.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.
Files changed (47) hide show
  1. CHANGELOG.md +8 -0
  2. ai_sec/__init__.py +0 -0
  3. ai_sec/ai_assist/__init__.py +0 -0
  4. ai_sec/ai_assist/issue_handler.py +143 -0
  5. ai_sec/config.py +55 -0
  6. ai_sec/lint_factory.py +61 -0
  7. ai_sec/linter_runner.py +287 -0
  8. ai_sec/linters/__init__.py +0 -0
  9. ai_sec/linters/base_linter.py +41 -0
  10. ai_sec/linters/checkov.py +123 -0
  11. ai_sec/linters/tflint.py +75 -0
  12. ai_sec/linters/tfsec.py +116 -0
  13. ai_sec/models/__init__.py +0 -0
  14. ai_sec/models/checkov_model.py +126 -0
  15. ai_sec/models/tflint_model.py +54 -0
  16. ai_sec/models/tfsec_model.py +50 -0
  17. ai_sec/processor/__init__.py +0 -0
  18. ai_sec/processor/ai_processor.py +30 -0
  19. ai_sec/processor/checkov_processor.py +123 -0
  20. ai_sec/processor/lint_processor.py +17 -0
  21. ai_sec/processor/tflint_processor.py +38 -0
  22. ai_sec/processor/tfsec_processor.py +39 -0
  23. ai_sec/reporting/__init__.py +0 -0
  24. ai_sec/reporting/app_layout.py +177 -0
  25. ai_sec/reporting/assets/custom.css +635 -0
  26. ai_sec/reporting/assets/custom.js +79 -0
  27. ai_sec/reporting/assets/home-solid.svg +1 -0
  28. ai_sec/reporting/assets/home.svg +1 -0
  29. ai_sec/reporting/assets/logo.webp +0 -0
  30. ai_sec/reporting/base.py +38 -0
  31. ai_sec/reporting/bugfixes.txt +78 -0
  32. ai_sec/reporting/callbacks.py +215 -0
  33. ai_sec/reporting/components.py +175 -0
  34. ai_sec/reporting/dashboard.py +187 -0
  35. ai_sec/reporting/data_loader.py +24 -0
  36. ai_sec/resources/__init__.py +0 -0
  37. ai_sec/resources/config.yaml +16 -0
  38. ai_sec/utils/__init__.py +0 -0
  39. ai_sec/utils/config_utils.py +25 -0
  40. ai_sec/utils/file_utils.py +67 -0
  41. ai_sec/utils/infra_utils.py +52 -0
  42. ai_sec/utils/linter_checker.py +34 -0
  43. ai_sec/utils/report_generator.py +46 -0
  44. ai_sec-0.0.1.dist-info/METADATA +209 -0
  45. ai_sec-0.0.1.dist-info/RECORD +47 -0
  46. ai_sec-0.0.1.dist-info/WHEEL +4 -0
  47. ai_sec-0.0.1.dist-info/entry_points.txt +3 -0
CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## [0.2.7] - 2024-10-14
4
+
5
+ ### Changed
6
+
7
+ - Fixed bug where modal wouldn't reopen on the same row after being closed.
8
+ - Improved link handling in the modal: now handles both single strings and lists of links.
ai_sec/__init__.py ADDED
File without changes
File without changes
@@ -0,0 +1,143 @@
1
+ import hashlib
2
+ import json
3
+ import logging
4
+ import os
5
+ from typing import Dict, Optional
6
+
7
+ import openai
8
+ from openai.error import (APIConnectionError, AuthenticationError,
9
+ InvalidRequestError, OpenAIError)
10
+
11
+ logging.basicConfig(
12
+ level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
13
+ )
14
+ logger = logging.getLogger(__name__)
15
+
16
+ CACHE_FILE = os.path.expanduser("~/.ai_sec/openai_cache.json")
17
+
18
+
19
+ class AIHandlerFactory:
20
+ _instance = None
21
+
22
+ @staticmethod
23
+ def get_handler() -> "IssueHandler":
24
+ """Retrieve or create the IssueHandler instance."""
25
+ if AIHandlerFactory._instance is None:
26
+ AIHandlerFactory._instance = IssueHandler()
27
+ return AIHandlerFactory._instance
28
+
29
+
30
+ class IssueHandler:
31
+ def __init__(self, model="gpt-4", timeout=30):
32
+ self.model = model
33
+ self.timeout = timeout
34
+ self.api_key = os.getenv("OPENAI_API_KEY")
35
+ if self.api_key:
36
+ openai.api_key = self.api_key
37
+ else:
38
+ raise RuntimeError("OpenAI API key not set. Please set the API key to use this feature.")
39
+
40
+ # Load cache if it exists, otherwise create an empty dictionary
41
+ self.cache = self.load_cache()
42
+
43
+ def load_cache(self) -> Dict[str, str]:
44
+ """Load cache from a JSON file if it exists, otherwise return an empty dictionary."""
45
+ if os.path.exists(CACHE_FILE):
46
+ with open(CACHE_FILE, 'r') as cache_file:
47
+ data = json.load(cache_file)
48
+ if isinstance(data, dict):
49
+ return {str(k): str(v) for k, v in data.items()}
50
+ return {}
51
+
52
+ def save_cache(self) -> None:
53
+ """Save the cache to a file."""
54
+ with open(CACHE_FILE, 'w') as cache_file:
55
+ json.dump(self.cache, cache_file)
56
+
57
+ def get_cache_key(self, prompt: str) -> str:
58
+ """Generate a cache key by hashing the prompt."""
59
+ return hashlib.sha256(prompt.encode('utf-8')).hexdigest()
60
+
61
+ def get_openai_response(self, prompt: str) -> Optional[str]:
62
+ """Fetch a response from OpenAI, using cache if available."""
63
+ cache_key = self.get_cache_key(prompt)
64
+
65
+ # Check if the response is already cached
66
+ if cache_key in self.cache:
67
+ logger.info("Using cached response for prompt.")
68
+ return self.cache.get(cache_key) # type: ignore
69
+
70
+ # If not cached, fetch the response from OpenAI
71
+ try:
72
+ completion = openai.ChatCompletion.create(
73
+ model=self.model,
74
+ messages=[
75
+ {
76
+ "role": "system",
77
+ "content": "You are an expert in security and best practices for infrastructure."
78
+ },
79
+ {
80
+ "role": "user",
81
+ "content": prompt
82
+ },
83
+ ],
84
+ timeout=self.timeout
85
+ )
86
+ response: str = completion.choices[0].message["content"].strip()
87
+
88
+ if not response:
89
+ logger.error("Received an invalid or empty response from OpenAI.")
90
+ return None
91
+
92
+ # Cache the response and save the cache
93
+ self.cache[cache_key] = response
94
+ self.save_cache()
95
+
96
+ return response
97
+ except (AuthenticationError, APIConnectionError, InvalidRequestError, OpenAIError) as e:
98
+ logger.error(f"OpenAI error: {e}")
99
+ raise RuntimeError(f"OpenAI error: {e}")
100
+ except Exception as e:
101
+ logger.error(f"Unexpected error: {e}")
102
+ raise RuntimeError(f"Unexpected error: {e}")
103
+
104
+ def infer_severity(self, description: str, framework: str) -> str:
105
+ """Determine the severity based on the issue description."""
106
+ prompt = (
107
+ f"Based on the following issue in the {framework} framework: '{description}', "
108
+ "please determine the severity of the issue. Respond ONLY with one of the following: "
109
+ "CRITICAL, HIGH, MEDIUM, LOW. Do not provide any other text."
110
+ )
111
+ response = self.get_openai_response(prompt)
112
+ valid_severities = ["CRITICAL", "HIGH", "MEDIUM", "LOW"]
113
+
114
+ if response and response.upper().strip() in valid_severities:
115
+ return response.upper().strip()
116
+ logger.error(f"Unable to determine severity for the issue: {description}")
117
+ return "UNKNOWN"
118
+
119
+ def generate_resolution_context(self, description: str, framework: str) -> str:
120
+ """Generate additional context for CRITICAL or HIGH severity issues."""
121
+ prompt = (
122
+ f"Given the following high-severity issue in the {framework} framework: '{description}', "
123
+ "provide a short explanation of the issue and recommended resolution in one paragraph. Do not include the words 'Summary' or 'Resolution'."
124
+ )
125
+ response = self.get_openai_response(prompt)
126
+ return response or "No additional context available."
127
+
128
+ def process_issue(self, description: str, framework: str) -> Dict[str, Optional[str]]:
129
+ """Process the issue description, return severity, and optionally provide resolution context."""
130
+ result: Dict[str, Optional[str]] = {"severity": None, "context": None}
131
+
132
+ try:
133
+ severity = self.infer_severity(description, framework)
134
+ result["severity"] = severity
135
+
136
+ if severity in ["CRITICAL", "HIGH"]:
137
+ context = self.generate_resolution_context(description, framework)
138
+ result["context"] = context
139
+
140
+ return result
141
+ except RuntimeError as e:
142
+ logger.error(f"Error processing issue: {e}")
143
+ return result
ai_sec/config.py ADDED
@@ -0,0 +1,55 @@
1
+ import importlib.resources as pkg_resources
2
+ import logging
3
+ import shutil
4
+ from pathlib import Path
5
+ from typing import Optional # Import Optional
6
+
7
+ import yaml
8
+
9
+ from ai_sec import resources # Assuming `resources` is inside your package
10
+
11
+ # Set up logging
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # Define the default configuration location and the default values
15
+ CONFIG_DIR = Path.home() / ".ai_sec"
16
+ CONFIG_FILE = CONFIG_DIR / "config.yaml"
17
+
18
+
19
+ def ensure_config_exists():
20
+ """
21
+ Ensure that the configuration file exists in ~/.ai_sec. If not, copy the one from resources.
22
+ """
23
+ if not CONFIG_FILE.exists():
24
+ try:
25
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
26
+ # Copy the config file from resources
27
+ with pkg_resources.path(resources, 'config.yaml') as resource_config:
28
+ shutil.copy(resource_config, CONFIG_FILE)
29
+ logger.info(f"Default configuration copied to {CONFIG_FILE}")
30
+ except Exception as e:
31
+ logger.error(f"Failed to create default config: {e}")
32
+ raise
33
+ else:
34
+ logger.debug(f"Configuration already exists at {CONFIG_FILE}")
35
+ return CONFIG_FILE
36
+
37
+
38
+ def load_config(config_path: Optional[str] = None): # Fix by using Optional[str]
39
+ """
40
+ Load the configuration from the provided path or the default ~/.ai_sec/config.yaml.
41
+ """
42
+ config_file = Path(config_path) if config_path else CONFIG_FILE
43
+
44
+ if not config_file.exists():
45
+ logger.error(f"Config file not found at: {config_file}")
46
+ raise FileNotFoundError(f"Config file not found at: {config_file}")
47
+
48
+ try:
49
+ with config_file.open('r') as file:
50
+ config = yaml.safe_load(file)
51
+ logger.info(f"Loaded configuration from: {config_file}")
52
+ return config
53
+ except Exception as e:
54
+ logger.error(f"Failed to load configuration from {config_file}: {e}")
55
+ raise
ai_sec/lint_factory.py ADDED
@@ -0,0 +1,61 @@
1
+ import logging
2
+ from typing import Dict, List, Tuple, Type
3
+
4
+ from ai_sec.linters.checkov import CheckovLinter
5
+ from ai_sec.linters.tflint import TFLintLinter
6
+ from ai_sec.linters.tfsec import TFSecLinter
7
+ from ai_sec.models.checkov_model import CheckovResult
8
+ from ai_sec.models.tflint_model import TFLintResult
9
+ from ai_sec.models.tfsec_model import TFSecReport
10
+ from ai_sec.processor.checkov_processor import CheckovProcessor
11
+ from ai_sec.processor.tflint_processor import TFLintProcessor
12
+ from ai_sec.processor.tfsec_processor import TFSecProcessor
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class LinterFactory:
18
+ """
19
+ Factory class to dynamically return the appropriate Linter, Model, and Processor
20
+ based on configuration, including the correct framework for each linter.
21
+ """
22
+
23
+ # Define a mapping between linter names and their classes
24
+ LINTER_MAP: Dict[str, Tuple[Type, Type, Type]] = {
25
+ 'tflint': (TFLintLinter, TFLintResult, TFLintProcessor),
26
+ 'tfsec': (TFSecLinter, TFSecReport, TFSecProcessor),
27
+ 'checkov': (CheckovLinter, CheckovResult, CheckovProcessor)
28
+ }
29
+
30
+ # Define a mapping of supported frameworks per linter
31
+ SUPPORTED_FRAMEWORKS = {
32
+ 'tflint': ['terraform'], # TFLint only supports Terraform
33
+ 'tfsec': ['terraform', 'cloudformation'], # TFSec supports Terraform and CloudFormation
34
+ 'checkov': ['terraform', 'cloudformation', 'kubernetes'], # Checkov supports all three
35
+ }
36
+
37
+ @staticmethod
38
+ def get_enabled_linters(config: Dict) -> list:
39
+ """
40
+ Dynamically get the list of enabled linters based on the config and the detected infra framework.
41
+ :param config: The configuration dictionary.
42
+ :return: A list of tuples containing the linter name, LinterClass, ResultModel, and ProcessorClass.
43
+ """
44
+ enabled_linters: List[Tuple[str, Type, Type, Type]] = []
45
+
46
+ # Get the infra type (framework) from the higher level in the config
47
+ infra_type = config['linters'].get('framework')
48
+ if not infra_type:
49
+ logger.error("Framework not set in config; cannot detect infra type.")
50
+ return enabled_linters
51
+
52
+ # Loop through the linter map and check if the linter supports the detected framework
53
+ for linter_name, (LinterClass, ResultModel, ProcessorClass) in LinterFactory.LINTER_MAP.items():
54
+ # Check if the linter is enabled in the config and if it supports the detected infra type
55
+ if config['linters'].get(linter_name, {}).get('enabled', False):
56
+ if infra_type in LinterFactory.SUPPORTED_FRAMEWORKS.get(linter_name, []):
57
+ enabled_linters.append((linter_name, LinterClass, ResultModel, ProcessorClass))
58
+ else:
59
+ logger.debug(f"Linter {linter_name} does not support framework {infra_type}. Skipping...")
60
+
61
+ return enabled_linters
@@ -0,0 +1,287 @@
1
+ import importlib.resources as resources # Use importlib.resources for resource handling
2
+ import json
3
+ import logging
4
+ import os
5
+ import shutil
6
+ from typing import Dict
7
+
8
+ import click
9
+
10
+ from ai_sec.config import ensure_config_exists, load_config
11
+ from ai_sec.lint_factory import LinterFactory # Import the new LinterFactory
12
+ from ai_sec.reporting.dashboard import DashDashboard
13
+ from ai_sec.utils.infra_utils import \
14
+ detect_infra_files # Updated function name
15
+ from ai_sec.utils.linter_checker import check_linter_installed
16
+ from ai_sec.utils.report_generator import generate_report
17
+
18
+ # Configure logging
19
+ logging.basicConfig(level=logging.INFO)
20
+ logger = logging.getLogger(__name__)
21
+
22
+ DEFAULT_CONFIG_SOURCE = 'src/ai_sec/resources/config.yaml'
23
+ DEFAULT_CONFIG_DEST = os.path.expanduser('~/.ai_sec/config.yaml')
24
+
25
+
26
+ @click.group(help="""
27
+ AI_Sec
28
+ Usage:
29
+
30
+ ai_sec run <directory> [OPTIONS]
31
+ ai_sec export-config
32
+
33
+ Commands:
34
+ run Run the linters on the specified directory and generate a report.
35
+ export-config Export the default configuration to ~/.ai_sec/config.yaml.
36
+
37
+ Run 'ai_sec run --help' for more details on the available options.
38
+ """)
39
+ def cli():
40
+ """CLI group for AI_Sec."""
41
+ pass
42
+
43
+
44
+ @cli.command(help="""
45
+ Run multiple Terraform linters and generate a report. By default, it will
46
+ launch the Dash dashboard after the report is generated.
47
+
48
+ Example:
49
+
50
+ ai_sec run ./infra_directory --output json:./reports/report.json
51
+
52
+ Options:
53
+ directory The path to the directory containing infrastructure files.
54
+ --config Path to the configuration file (optional).
55
+ --output Specify the output format (json or html) and path (optional).
56
+ --no-dash Do not run the dashboard after linting.
57
+ """)
58
+ @click.argument('directory', type=click.Path(exists=True), default='.')
59
+ @click.option('--config', type=click.Path(exists=True), help="Path to the configuration file.")
60
+ @click.option('--output', type=str, help="Specify output format (json or html) and path.")
61
+ @click.option('--no-dash', is_flag=True, help="Do not run the dashboard after linting.")
62
+ def run(directory, config, output, no_dash):
63
+ """
64
+ Run multiple linters on infrastructure files (Terraform, Kubernetes, CloudFormation) and generate a report.
65
+ By default, it will launch the Dash dashboard after the report is generated.
66
+ """
67
+
68
+ # Ensure the config exists
69
+ logger.debug(f"Config file path received: {config}")
70
+ if not config:
71
+ config = ensure_config_exists()
72
+ logger.debug(f"Using default config: {config}")
73
+
74
+ # Load the config data
75
+ try:
76
+ config_data = load_config(config)
77
+ logger.debug(f"Config data loaded: {config_data}")
78
+ except FileNotFoundError as e:
79
+ logger.error(f"Configuration file not found: {e}")
80
+ return
81
+ except Exception as e:
82
+ logger.error(f"Failed to load configuration: {e}")
83
+ return
84
+
85
+ # Handle output format and path if provided
86
+ if output:
87
+ try:
88
+ output_format, output_path = output.split(':')
89
+ if validate_output_format(output_format):
90
+ config_data['output']['format'] = output_format
91
+ config_data['output']['save_to'] = output_path
92
+ else:
93
+ logger.error("Invalid output format specified.")
94
+ return
95
+ except ValueError:
96
+ logger.error(f"Invalid output format argument: {output}")
97
+ return
98
+
99
+ # Detect infrastructure type (Terraform, CloudFormation, Kubernetes) and update config
100
+ logger.debug(f"Detecting infrastructure type for directory: {directory}")
101
+ infra_type = detect_infra_files(directory)
102
+
103
+ if not infra_type:
104
+ logger.error(f"No supported infrastructure files found in directory: {directory}")
105
+ click.echo("Error: No supported infrastructure files found. Please check the directory and try again.")
106
+ return
107
+
108
+ logger.info(f"Detected {infra_type} files in directory: {directory}")
109
+
110
+ # Update the framework in the config for all linters, not just Checkov
111
+ config_data['linters']['framework'] = infra_type
112
+
113
+ # Validate and run linters
114
+ report_path = run_linters_and_generate_report(config_data, directory)
115
+ logger.info(f"Report generated at: {report_path}")
116
+
117
+ # Only skip Dash if the user specified `--no-dash`
118
+ if not no_dash:
119
+ base_directory = os.path.abspath(directory)
120
+ logger.info(f"Starting the Dash app with report from: {report_path}")
121
+ dashboard = DashDashboard(report_path=report_path, base_directory=base_directory)
122
+ dashboard.run()
123
+
124
+
125
+ @cli.command(help="""
126
+ Export the default configuration to ~/.ai_sec/config.yaml.
127
+ This command creates the necessary folder and copies the default configuration template.
128
+ """)
129
+ def export_config():
130
+ """Export default config to ~/.ai_sec/config.yaml."""
131
+ config_dir = os.path.dirname(DEFAULT_CONFIG_DEST)
132
+
133
+ # Create the directory if it does not exist
134
+ if not os.path.exists(config_dir):
135
+ os.makedirs(config_dir)
136
+ logger.info(f"Created directory: {config_dir}")
137
+
138
+ # Copy the default config using importlib.resources to access the resource
139
+ if not os.path.exists(DEFAULT_CONFIG_DEST):
140
+ try:
141
+ # Use importlib.resources to get the path to the bundled config.yaml
142
+ with resources.files('ai_sec.resources').joinpath('config.yaml').open('rb') as fsrc:
143
+ with open(DEFAULT_CONFIG_DEST, 'wb') as fdst:
144
+ shutil.copyfileobj(fsrc, fdst)
145
+
146
+ logger.info(f"Config file exported to: {DEFAULT_CONFIG_DEST}")
147
+ except Exception as e:
148
+ logger.error(f"Failed to export config file: {e}")
149
+ else:
150
+ logger.info(f"Config file already exists at: {DEFAULT_CONFIG_DEST}")
151
+
152
+
153
+ def validate_output_format(output_format):
154
+ if output_format not in ['json', 'html']:
155
+ logger.error(f"Invalid output format: {output_format}. Supported formats: json, html.")
156
+ return False
157
+ return True
158
+
159
+
160
+ def create_processor(ProcessorClass, base_directory, framework):
161
+ """
162
+ Utility function to create a processor instance.
163
+ It checks if 'base_directory' is an argument in the ProcessorClass constructor,
164
+ and initializes it accordingly.
165
+
166
+ :param ProcessorClass: The processor class to instantiate.
167
+ :param base_directory: The base directory to be passed if required by the processor.
168
+ :param framework: The framework (e.g., 'terraform', 'cloudformation', 'kubernetes').
169
+ :return: An instance of the processor.
170
+ """
171
+ if 'base_directory' in ProcessorClass.__init__.__code__.co_varnames:
172
+ # If the processor accepts base_directory, include it during initialization
173
+ return ProcessorClass(base_directory=base_directory, framework=framework)
174
+ else:
175
+ # If not, just initialize with the framework
176
+ return ProcessorClass(framework=framework)
177
+
178
+
179
+ def run_linter(linter_name, linter_instance, directory: str):
180
+ """
181
+ Runs the specified linter instance and returns raw results or error messages.
182
+ """
183
+ logger.debug(f"Checking if {linter_name} is installed...")
184
+ if check_linter_installed(linter_name):
185
+ logger.info(f"Running {linter_name} on directory: {directory}")
186
+ try:
187
+ return linter_instance.run(directory) # Pass the correct directory path
188
+ except Exception as e:
189
+ logger.error(f"Failed to run {linter_name}: {e}")
190
+ return {'error': f"Failed to run {linter_name}: {e}"}
191
+ else:
192
+ logger.error(f"{linter_name} is not installed.")
193
+ return {'error': f'{linter_name} is not installed'}
194
+
195
+
196
+ def run_linters_and_generate_report(config: Dict, directory: str) -> str:
197
+ """
198
+ Runs all configured linters, generates, and saves reports.
199
+ :param config: The configuration for the linters and output settings.
200
+ :param directory: The directory to run the linters on.
201
+ :return: The path where the report is saved.
202
+ """
203
+ results = {'summary': {'directory': directory, 'linted_files': 0}, 'linters': {}}
204
+
205
+ # Calculate base directory once
206
+ base_directory = os.path.abspath(directory)
207
+
208
+ # Get the enabled linters dynamically from the factory
209
+ linters = LinterFactory.get_enabled_linters(config)
210
+
211
+ # Extract the framework from the config, it should be detected before this step
212
+ framework = config['linters'].get('framework')
213
+
214
+ if not framework:
215
+ logger.error(f"Framework not detected in the config: {config['linters']}")
216
+ raise ValueError("Framework not detected. Ensure that the infrastructure type is detected and set correctly.")
217
+
218
+ for linter_name, LinterClass, ResultModel, ProcessorClass in linters:
219
+ logger.debug(f"Running linter {linter_name} for directory {directory}")
220
+
221
+ # Properly instantiate the linter with the detected framework
222
+ try:
223
+ linter_instance = LinterClass(framework=framework)
224
+ except TypeError as e:
225
+ logger.error(f"Failed to instantiate {LinterClass.__name__}: {e}")
226
+ continue
227
+
228
+ raw_result = run_linter(linter_name, linter_instance, directory)
229
+
230
+ # Log the raw result for debugging purposes
231
+ logger.debug(f"Raw result from {linter_name}: {raw_result}")
232
+
233
+ # Initialize parsed_json_result to avoid UnboundLocalError
234
+ parsed_json_result = None
235
+
236
+ # If raw_result is a string, try to parse it as JSON
237
+ if isinstance(raw_result, str):
238
+ try:
239
+ parsed_json_result = json.loads(raw_result)
240
+ logger.debug(f"Parsed JSON result for {linter_name}: {parsed_json_result}")
241
+ except json.JSONDecodeError as e:
242
+ logger.error(f"Failed to parse JSON from {linter_name}: {e}")
243
+ results['linters'][linter_name] = {'error': f"Failed to parse JSON: {e}"}
244
+ continue
245
+
246
+ # Only proceed if parsing was successful and there is no error in the result
247
+ if parsed_json_result and 'error' not in parsed_json_result:
248
+ try:
249
+ # Validate the result model and convert it to a structured format
250
+ parsed_result = ResultModel.from_raw_json(json.dumps(parsed_json_result))
251
+ logger.debug(f"Parsed result for {linter_name}: {parsed_result}")
252
+
253
+ # Use the utility function to create the processor
254
+ processor = create_processor(ProcessorClass, base_directory, framework)
255
+
256
+ # Process the result
257
+ processed_result = processor.process_data(parsed_result.dict())
258
+ # Save the processed result in the results dictionary
259
+ results['linters'][linter_name] = processed_result
260
+ results['summary']['linted_files'] += 1 # type: ignore
261
+
262
+ except ValueError as e:
263
+ logger.error(f"Failed to process {linter_name} output: {e}")
264
+ results['linters'][linter_name] = {'error': f'Failed to process {linter_name} output: {e}'}
265
+ else:
266
+ logger.error(f"{linter_name} returned an error: {parsed_json_result.get('error') if parsed_json_result else 'No valid result'}")
267
+ results['linters'][linter_name] = {'error': parsed_json_result.get('error') if parsed_json_result else 'No valid result'}
268
+
269
+ # Check if results contain any linter data before generating the report
270
+ if not results['linters']:
271
+ logger.warning("No linter results available, skipping report generation.")
272
+ return ""
273
+
274
+ # Generate the report
275
+ logger.info("Generating the report based on linter results.")
276
+ generate_report(results, config['output'])
277
+ # Log the final structure of the report for debugging
278
+ logger.debug(f"Final results: {results}")
279
+ return config['output']['save_to'] # type: ignore
280
+
281
+
282
+ def main():
283
+ cli()
284
+
285
+
286
+ if __name__ == "__main__":
287
+ main()
File without changes
@@ -0,0 +1,41 @@
1
+ import logging
2
+ from abc import ABC, abstractmethod
3
+
4
+ # Configure logging
5
+ logging.basicConfig(
6
+ level=logging.INFO,
7
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
8
+ )
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class BaseLinter(ABC):
13
+ def __init__(self, framework: str):
14
+ """
15
+ Initialize the base linter with the specified framework.
16
+ :param framework: Infrastructure code framework (e.g., 'terraform', 'cloudformation').
17
+ """
18
+ self.framework = framework
19
+
20
+ @abstractmethod
21
+ def run(self, directory):
22
+ """
23
+ Abstract method that must be implemented by subclasses.
24
+ This method will be responsible for running the linter
25
+ with the given directory and returning the results.
26
+ :param directory: The root directory containing the infrastructure files.
27
+ :return: A dictionary representing the linter results (e.g., errors, warnings).
28
+ """
29
+ pass
30
+
31
+ def parse_output(self, output):
32
+ """
33
+ Optional method to parse the raw output of the linter.
34
+ By default, this just returns the raw output, but subclasses
35
+ can override this method to perform custom parsing.
36
+
37
+ :param output: The raw output from the linter (as a string).
38
+ :return: Parsed output (e.g., JSON, dictionary).
39
+ """
40
+ logger.info("Parsing output")
41
+ return output