ai_sec 0.0.1__tar.gz
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.
- ai_sec-0.0.1/CHANGELOG.md +8 -0
- ai_sec-0.0.1/PKG-INFO +209 -0
- ai_sec-0.0.1/README.md +182 -0
- ai_sec-0.0.1/pyproject.toml +58 -0
- ai_sec-0.0.1/src/ai_sec/__init__.py +0 -0
- ai_sec-0.0.1/src/ai_sec/ai_assist/__init__.py +0 -0
- ai_sec-0.0.1/src/ai_sec/ai_assist/issue_handler.py +143 -0
- ai_sec-0.0.1/src/ai_sec/config.py +55 -0
- ai_sec-0.0.1/src/ai_sec/lint_factory.py +61 -0
- ai_sec-0.0.1/src/ai_sec/linter_runner.py +287 -0
- ai_sec-0.0.1/src/ai_sec/linters/__init__.py +0 -0
- ai_sec-0.0.1/src/ai_sec/linters/base_linter.py +41 -0
- ai_sec-0.0.1/src/ai_sec/linters/checkov.py +123 -0
- ai_sec-0.0.1/src/ai_sec/linters/tflint.py +75 -0
- ai_sec-0.0.1/src/ai_sec/linters/tfsec.py +116 -0
- ai_sec-0.0.1/src/ai_sec/models/__init__.py +0 -0
- ai_sec-0.0.1/src/ai_sec/models/checkov_model.py +126 -0
- ai_sec-0.0.1/src/ai_sec/models/tflint_model.py +54 -0
- ai_sec-0.0.1/src/ai_sec/models/tfsec_model.py +50 -0
- ai_sec-0.0.1/src/ai_sec/processor/__init__.py +0 -0
- ai_sec-0.0.1/src/ai_sec/processor/ai_processor.py +30 -0
- ai_sec-0.0.1/src/ai_sec/processor/checkov_processor.py +123 -0
- ai_sec-0.0.1/src/ai_sec/processor/lint_processor.py +17 -0
- ai_sec-0.0.1/src/ai_sec/processor/tflint_processor.py +38 -0
- ai_sec-0.0.1/src/ai_sec/processor/tfsec_processor.py +39 -0
- ai_sec-0.0.1/src/ai_sec/reporting/__init__.py +0 -0
- ai_sec-0.0.1/src/ai_sec/reporting/app_layout.py +177 -0
- ai_sec-0.0.1/src/ai_sec/reporting/assets/custom.css +635 -0
- ai_sec-0.0.1/src/ai_sec/reporting/assets/custom.js +79 -0
- ai_sec-0.0.1/src/ai_sec/reporting/assets/home-solid.svg +1 -0
- ai_sec-0.0.1/src/ai_sec/reporting/assets/home.svg +1 -0
- ai_sec-0.0.1/src/ai_sec/reporting/assets/logo.webp +0 -0
- ai_sec-0.0.1/src/ai_sec/reporting/base.py +38 -0
- ai_sec-0.0.1/src/ai_sec/reporting/bugfixes.txt +78 -0
- ai_sec-0.0.1/src/ai_sec/reporting/callbacks.py +215 -0
- ai_sec-0.0.1/src/ai_sec/reporting/components.py +175 -0
- ai_sec-0.0.1/src/ai_sec/reporting/dashboard.py +187 -0
- ai_sec-0.0.1/src/ai_sec/reporting/data_loader.py +24 -0
- ai_sec-0.0.1/src/ai_sec/resources/__init__.py +0 -0
- ai_sec-0.0.1/src/ai_sec/resources/config.yaml +16 -0
- ai_sec-0.0.1/src/ai_sec/utils/__init__.py +0 -0
- ai_sec-0.0.1/src/ai_sec/utils/config_utils.py +25 -0
- ai_sec-0.0.1/src/ai_sec/utils/file_utils.py +67 -0
- ai_sec-0.0.1/src/ai_sec/utils/infra_utils.py +52 -0
- ai_sec-0.0.1/src/ai_sec/utils/linter_checker.py +34 -0
- ai_sec-0.0.1/src/ai_sec/utils/report_generator.py +46 -0
ai_sec-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: ai_sec
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Linting, security scanning, and reporting on infrastructure code and Kubernetes config
|
|
5
|
+
License: MIT
|
|
6
|
+
Author: Darren Rabbitt
|
|
7
|
+
Maintainer: Darren Rabbitt
|
|
8
|
+
Maintainer-email: dev@darrenrabbitt.com
|
|
9
|
+
Requires-Python: >=3.10,<4.0
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Requires-Dist: Jinja2 (>=3.1.4,<4.0.0)
|
|
17
|
+
Requires-Dist: PyYAML (>=6.0.2,<7.0.0)
|
|
18
|
+
Requires-Dist: aiofiles (>=24.1.0,<25.0.0)
|
|
19
|
+
Requires-Dist: checkov (>=3.2.267,<4.0.0)
|
|
20
|
+
Requires-Dist: click (>=8.1.7,<9.0.0)
|
|
21
|
+
Requires-Dist: dash (>=2.18.0,<3.0.0)
|
|
22
|
+
Requires-Dist: dash-bootstrap-components (>=1.6.0,<2.0.0)
|
|
23
|
+
Requires-Dist: ijson (>=3.3.0,<4.0.0)
|
|
24
|
+
Requires-Dist: pandas (>=2.2.2,<3.0.0)
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# AI_Sec
|
|
28
|
+
|
|
29
|
+
AI_Sec is a powerful command-line tool for linting, security scanning, and reporting on infrastructure-as-code (IaC) such as Terraform and CloudFormation. It supports a variety of linters and security checkers, making it an essential tool for maintaining high-quality infrastructure code, with a focus on best practices and security.
|
|
30
|
+
|
|
31
|
+
## Table of Contents
|
|
32
|
+
|
|
33
|
+
- [Motivation](#motivation)
|
|
34
|
+
- [Python Versions](#python-versions)
|
|
35
|
+
- [Features](#features)
|
|
36
|
+
- [Installation](#installation)
|
|
37
|
+
- [Option 1: Using a Virtual Environment and Symbolic Links](#option-1-using-a-virtual-environment-and-symbolic-links)
|
|
38
|
+
- [Option 2: Installing Directly to System Python](#option-2-installing-directly-to-system-python)
|
|
39
|
+
- [Setting Up](#setting-up)
|
|
40
|
+
- [Commands](#commands)
|
|
41
|
+
- [Sample Configuration](#sample-configuration)
|
|
42
|
+
- [Contact](#contact)
|
|
43
|
+
|
|
44
|
+
## Motivation
|
|
45
|
+
|
|
46
|
+
Managing infrastructure code in a secure and scalable way is essential, especially with the rise of cloud-native technologies. AI_Sec was developed to automate the process of ensuring that your infrastructure code adheres to best practices by utilizing various linters and security scanners, generating detailed reports to highlight issues.
|
|
47
|
+
|
|
48
|
+
AI_Sec ensures that your infrastructure is both secure and follows the necessary guidelines by default using **Checkov**, while also supporting other popular linters such as **TFLint** and **TFSec**. The tool is designed to work with IaC frameworks like **Terraform** and **CloudFormation**, giving you comprehensive coverage.
|
|
49
|
+
|
|
50
|
+
## Python Versions
|
|
51
|
+
|
|
52
|
+
This project supports Python versions specified in the `pyproject.toml` file:
|
|
53
|
+
|
|
54
|
+
```toml
|
|
55
|
+
[tool.poetry.dependencies]
|
|
56
|
+
python = ">=3.10,<4.0"
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Features
|
|
60
|
+
|
|
61
|
+
- **Lint Terraform and CloudFormation Code**: Support for Checkov by default, with optional support for TFLint (v0.53.0) and TFSec (v1.28.0).
|
|
62
|
+
- **Security Scanning**: Detect vulnerabilities in your infrastructure code using popular security tools.
|
|
63
|
+
- **Customizable Reports**: Generate detailed reports in JSON or HTML format.
|
|
64
|
+
- **Dashboard for Issue Navigation**: Navigate and explore identified issues through an interactive dashboard. The dashboard categorizes and presents issues by severity, linter type, and more, providing an easy way to investigate and resolve problems.
|
|
65
|
+
- **Configurable Color Scheme**: Customize the color scheme for different severity levels (CRITICAL, HIGH, MEDIUM, LOW, INFO).
|
|
66
|
+
- **AI-Generated Insights**: Automatically infer severity and context for high-severity issues using OpenAI.
|
|
67
|
+
- **Caching for AI Responses**: To reduce repeated calls to OpenAI, Ai_sec caches AI-generated insights for faster subsequent runs.
|
|
68
|
+
- **Modular Linter Support**: Easily enable or disable linters through the configuration file.
|
|
69
|
+
|
|
70
|
+
## Installation
|
|
71
|
+
|
|
72
|
+
Ensure you are using Python 3.10 or above.
|
|
73
|
+
|
|
74
|
+
### Option 1: Using a Virtual Environment and Symbolic Links
|
|
75
|
+
|
|
76
|
+
1. **Ensure Python Version**
|
|
77
|
+
|
|
78
|
+
- Verify you have Python 3.10 or later:
|
|
79
|
+
```bash
|
|
80
|
+
python --version
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
2. **Create and Activate Virtual Environment**
|
|
84
|
+
|
|
85
|
+
- **Create**:
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
python -m venv myenv
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
- **Activate**:
|
|
92
|
+
- **Windows**:
|
|
93
|
+
```bash
|
|
94
|
+
myenv\\Scripts\\activate
|
|
95
|
+
```
|
|
96
|
+
- **macOS/Linux**:
|
|
97
|
+
```bash
|
|
98
|
+
source myenv/bin/activate
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
3. **Install Ai_sec**
|
|
102
|
+
```bash
|
|
103
|
+
pip install ai_sec
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### Option 2: Installing Directly to System Python
|
|
107
|
+
|
|
108
|
+
1. **Ensure Python Version**
|
|
109
|
+
|
|
110
|
+
- Verify you have Python 3.10 or later:
|
|
111
|
+
```bash
|
|
112
|
+
python --version
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
2. **Install AI_Sec**
|
|
116
|
+
```bash
|
|
117
|
+
python -m pip install ai_sec
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Setting Up
|
|
121
|
+
|
|
122
|
+
To configure AI_Sec, follow these steps:
|
|
123
|
+
|
|
124
|
+
1. You can export the default config by running `ai_sec export-config`.
|
|
125
|
+
|
|
126
|
+
2. The default configuration file will be exported to `~/.ai_sec/config.yaml`.
|
|
127
|
+
|
|
128
|
+
3. By default, Checkov is the main linter used, but you can enable TFLint and TFSec as needed if you have them installed.
|
|
129
|
+
|
|
130
|
+
4. Edit the `config.yaml` file to enable/disable linters and set the report output format.
|
|
131
|
+
|
|
132
|
+
## Sample Configuration
|
|
133
|
+
|
|
134
|
+
Here’s the default `config.yaml`
|
|
135
|
+
Before running AI_Sec, you need to set up the default configuration file. You can automatically export the default configuration to the `~/.ai_sec/config.yaml` directory by running the following command:
|
|
136
|
+
|
|
137
|
+
```bash
|
|
138
|
+
ai_sec export-config
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
```yaml
|
|
142
|
+
linters:
|
|
143
|
+
tflint:
|
|
144
|
+
enabled: false
|
|
145
|
+
tfsec:
|
|
146
|
+
enabled: false
|
|
147
|
+
checkov:
|
|
148
|
+
enabled: true
|
|
149
|
+
framework: terraform # Default framework can also be Cloudformation
|
|
150
|
+
output:
|
|
151
|
+
format: json
|
|
152
|
+
save_to: ./reports/report.json
|
|
153
|
+
color_scheme:
|
|
154
|
+
CRITICAL: "#FF6F61"
|
|
155
|
+
HIGH: "#FFA07A"
|
|
156
|
+
MEDIUM: "#FFD700"
|
|
157
|
+
LOW: "#90EE90"
|
|
158
|
+
INFO: "#B0C4DE"
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## Open AI Insights
|
|
162
|
+
|
|
163
|
+
AI_Sec integrates with OpenAI to provide enhanced insights on infrastructure issues. This includes determining the severity of issues and providing additional context and resolution suggestions for critical and high-severity issues. These insights can be particularly useful in understanding the nature of the problems and how to resolve them.
|
|
164
|
+
|
|
165
|
+
### How to Enable OpenAI Insights
|
|
166
|
+
|
|
167
|
+
To enable OpenAI insights, you will need an API key from OpenAI
|
|
168
|
+
|
|
169
|
+
1. Set the OpenAI API Key: You must set an environment variable OPENAI_API_KEY with your OpenAI API key.
|
|
170
|
+
You can export it in your terminal before running the tool:
|
|
171
|
+
bash` export OPENAI_API_KEY="your-openai-api-key"`
|
|
172
|
+
2. Enable OpenAI Insights in the Configuration: Ensure that the OpenAI integration is enabled in the configuration file. By default, if the API key is set, the insights will automatically be enabled when issues are found.
|
|
173
|
+
|
|
174
|
+
### How OpenAI Insights Work
|
|
175
|
+
|
|
176
|
+
When a linter detects an issue, AI_Sec sends a request to OpenAI to analyze the issue and provide:
|
|
177
|
+
|
|
178
|
+
**Severity**: The issue’s severity level (CRITICAL, HIGH, MEDIUM, or LOW).
|
|
179
|
+
**Context and Resolution**: For critical and high-severity issues, additional context and resolution suggestions will be provided.
|
|
180
|
+
|
|
181
|
+
These insights are added to the linting report and can be viewed in the AI_Sec Dashboard.
|
|
182
|
+
|
|
183
|
+
### Caching of OpenAI Responses
|
|
184
|
+
|
|
185
|
+
To avoid repeated API calls and improve performance, OpenAI responses are cached locally. The cache is created in the user’s home directory under ~/.ai_sec/openai_cache.json. This means if the same issue is analyzed multiple times, the tool will retrieve the result from the cache instead of querying OpenAI again.
|
|
186
|
+
|
|
187
|
+
Note: The cache key is generated based on the issue description and the framework used, so identical issues will have the same result retrieved from the cache.
|
|
188
|
+
|
|
189
|
+
### Important Considerations
|
|
190
|
+
|
|
191
|
+
**API Limits**: Depending on your OpenAI subscription, you may have limits on the number of requests. Using the cache can help minimize the number of API calls.
|
|
192
|
+
**Performance**: Querying OpenAI can add some additional time to the analysis, especially for large codebases or complex issues. The caching system helps mitigate this for repeated runs.
|
|
193
|
+
**Error Handling**: If an error occurs while querying OpenAI (e.g., invalid API key, connection issues), the tool will log the error and continue running without OpenAI insights.
|
|
194
|
+
|
|
195
|
+
## Commands
|
|
196
|
+
|
|
197
|
+
Here are some useful commands to interact with AI_Sec:
|
|
198
|
+
|
|
199
|
+
- `ai_sec run <path>`: Run the linters on the specified path and generate a report.
|
|
200
|
+
- `ai_sec export-config` - exports default config
|
|
201
|
+
|
|
202
|
+
## Changelog
|
|
203
|
+
|
|
204
|
+
For detailed information about changes in each version, see the [Changelog](CHANGELOG.md).
|
|
205
|
+
|
|
206
|
+
## Contact
|
|
207
|
+
|
|
208
|
+
If you encounter any issues or have any suggestions, please feel free to send them to dev@darrenrabbitt.com. Thank you for your support!
|
|
209
|
+
|
ai_sec-0.0.1/README.md
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# AI_Sec
|
|
2
|
+
|
|
3
|
+
AI_Sec is a powerful command-line tool for linting, security scanning, and reporting on infrastructure-as-code (IaC) such as Terraform and CloudFormation. It supports a variety of linters and security checkers, making it an essential tool for maintaining high-quality infrastructure code, with a focus on best practices and security.
|
|
4
|
+
|
|
5
|
+
## Table of Contents
|
|
6
|
+
|
|
7
|
+
- [Motivation](#motivation)
|
|
8
|
+
- [Python Versions](#python-versions)
|
|
9
|
+
- [Features](#features)
|
|
10
|
+
- [Installation](#installation)
|
|
11
|
+
- [Option 1: Using a Virtual Environment and Symbolic Links](#option-1-using-a-virtual-environment-and-symbolic-links)
|
|
12
|
+
- [Option 2: Installing Directly to System Python](#option-2-installing-directly-to-system-python)
|
|
13
|
+
- [Setting Up](#setting-up)
|
|
14
|
+
- [Commands](#commands)
|
|
15
|
+
- [Sample Configuration](#sample-configuration)
|
|
16
|
+
- [Contact](#contact)
|
|
17
|
+
|
|
18
|
+
## Motivation
|
|
19
|
+
|
|
20
|
+
Managing infrastructure code in a secure and scalable way is essential, especially with the rise of cloud-native technologies. AI_Sec was developed to automate the process of ensuring that your infrastructure code adheres to best practices by utilizing various linters and security scanners, generating detailed reports to highlight issues.
|
|
21
|
+
|
|
22
|
+
AI_Sec ensures that your infrastructure is both secure and follows the necessary guidelines by default using **Checkov**, while also supporting other popular linters such as **TFLint** and **TFSec**. The tool is designed to work with IaC frameworks like **Terraform** and **CloudFormation**, giving you comprehensive coverage.
|
|
23
|
+
|
|
24
|
+
## Python Versions
|
|
25
|
+
|
|
26
|
+
This project supports Python versions specified in the `pyproject.toml` file:
|
|
27
|
+
|
|
28
|
+
```toml
|
|
29
|
+
[tool.poetry.dependencies]
|
|
30
|
+
python = ">=3.10,<4.0"
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Features
|
|
34
|
+
|
|
35
|
+
- **Lint Terraform and CloudFormation Code**: Support for Checkov by default, with optional support for TFLint (v0.53.0) and TFSec (v1.28.0).
|
|
36
|
+
- **Security Scanning**: Detect vulnerabilities in your infrastructure code using popular security tools.
|
|
37
|
+
- **Customizable Reports**: Generate detailed reports in JSON or HTML format.
|
|
38
|
+
- **Dashboard for Issue Navigation**: Navigate and explore identified issues through an interactive dashboard. The dashboard categorizes and presents issues by severity, linter type, and more, providing an easy way to investigate and resolve problems.
|
|
39
|
+
- **Configurable Color Scheme**: Customize the color scheme for different severity levels (CRITICAL, HIGH, MEDIUM, LOW, INFO).
|
|
40
|
+
- **AI-Generated Insights**: Automatically infer severity and context for high-severity issues using OpenAI.
|
|
41
|
+
- **Caching for AI Responses**: To reduce repeated calls to OpenAI, Ai_sec caches AI-generated insights for faster subsequent runs.
|
|
42
|
+
- **Modular Linter Support**: Easily enable or disable linters through the configuration file.
|
|
43
|
+
|
|
44
|
+
## Installation
|
|
45
|
+
|
|
46
|
+
Ensure you are using Python 3.10 or above.
|
|
47
|
+
|
|
48
|
+
### Option 1: Using a Virtual Environment and Symbolic Links
|
|
49
|
+
|
|
50
|
+
1. **Ensure Python Version**
|
|
51
|
+
|
|
52
|
+
- Verify you have Python 3.10 or later:
|
|
53
|
+
```bash
|
|
54
|
+
python --version
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
2. **Create and Activate Virtual Environment**
|
|
58
|
+
|
|
59
|
+
- **Create**:
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
python -m venv myenv
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
- **Activate**:
|
|
66
|
+
- **Windows**:
|
|
67
|
+
```bash
|
|
68
|
+
myenv\\Scripts\\activate
|
|
69
|
+
```
|
|
70
|
+
- **macOS/Linux**:
|
|
71
|
+
```bash
|
|
72
|
+
source myenv/bin/activate
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
3. **Install Ai_sec**
|
|
76
|
+
```bash
|
|
77
|
+
pip install ai_sec
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### Option 2: Installing Directly to System Python
|
|
81
|
+
|
|
82
|
+
1. **Ensure Python Version**
|
|
83
|
+
|
|
84
|
+
- Verify you have Python 3.10 or later:
|
|
85
|
+
```bash
|
|
86
|
+
python --version
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
2. **Install AI_Sec**
|
|
90
|
+
```bash
|
|
91
|
+
python -m pip install ai_sec
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Setting Up
|
|
95
|
+
|
|
96
|
+
To configure AI_Sec, follow these steps:
|
|
97
|
+
|
|
98
|
+
1. You can export the default config by running `ai_sec export-config`.
|
|
99
|
+
|
|
100
|
+
2. The default configuration file will be exported to `~/.ai_sec/config.yaml`.
|
|
101
|
+
|
|
102
|
+
3. By default, Checkov is the main linter used, but you can enable TFLint and TFSec as needed if you have them installed.
|
|
103
|
+
|
|
104
|
+
4. Edit the `config.yaml` file to enable/disable linters and set the report output format.
|
|
105
|
+
|
|
106
|
+
## Sample Configuration
|
|
107
|
+
|
|
108
|
+
Here’s the default `config.yaml`
|
|
109
|
+
Before running AI_Sec, you need to set up the default configuration file. You can automatically export the default configuration to the `~/.ai_sec/config.yaml` directory by running the following command:
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
ai_sec export-config
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
```yaml
|
|
116
|
+
linters:
|
|
117
|
+
tflint:
|
|
118
|
+
enabled: false
|
|
119
|
+
tfsec:
|
|
120
|
+
enabled: false
|
|
121
|
+
checkov:
|
|
122
|
+
enabled: true
|
|
123
|
+
framework: terraform # Default framework can also be Cloudformation
|
|
124
|
+
output:
|
|
125
|
+
format: json
|
|
126
|
+
save_to: ./reports/report.json
|
|
127
|
+
color_scheme:
|
|
128
|
+
CRITICAL: "#FF6F61"
|
|
129
|
+
HIGH: "#FFA07A"
|
|
130
|
+
MEDIUM: "#FFD700"
|
|
131
|
+
LOW: "#90EE90"
|
|
132
|
+
INFO: "#B0C4DE"
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## Open AI Insights
|
|
136
|
+
|
|
137
|
+
AI_Sec integrates with OpenAI to provide enhanced insights on infrastructure issues. This includes determining the severity of issues and providing additional context and resolution suggestions for critical and high-severity issues. These insights can be particularly useful in understanding the nature of the problems and how to resolve them.
|
|
138
|
+
|
|
139
|
+
### How to Enable OpenAI Insights
|
|
140
|
+
|
|
141
|
+
To enable OpenAI insights, you will need an API key from OpenAI
|
|
142
|
+
|
|
143
|
+
1. Set the OpenAI API Key: You must set an environment variable OPENAI_API_KEY with your OpenAI API key.
|
|
144
|
+
You can export it in your terminal before running the tool:
|
|
145
|
+
bash` export OPENAI_API_KEY="your-openai-api-key"`
|
|
146
|
+
2. Enable OpenAI Insights in the Configuration: Ensure that the OpenAI integration is enabled in the configuration file. By default, if the API key is set, the insights will automatically be enabled when issues are found.
|
|
147
|
+
|
|
148
|
+
### How OpenAI Insights Work
|
|
149
|
+
|
|
150
|
+
When a linter detects an issue, AI_Sec sends a request to OpenAI to analyze the issue and provide:
|
|
151
|
+
|
|
152
|
+
**Severity**: The issue’s severity level (CRITICAL, HIGH, MEDIUM, or LOW).
|
|
153
|
+
**Context and Resolution**: For critical and high-severity issues, additional context and resolution suggestions will be provided.
|
|
154
|
+
|
|
155
|
+
These insights are added to the linting report and can be viewed in the AI_Sec Dashboard.
|
|
156
|
+
|
|
157
|
+
### Caching of OpenAI Responses
|
|
158
|
+
|
|
159
|
+
To avoid repeated API calls and improve performance, OpenAI responses are cached locally. The cache is created in the user’s home directory under ~/.ai_sec/openai_cache.json. This means if the same issue is analyzed multiple times, the tool will retrieve the result from the cache instead of querying OpenAI again.
|
|
160
|
+
|
|
161
|
+
Note: The cache key is generated based on the issue description and the framework used, so identical issues will have the same result retrieved from the cache.
|
|
162
|
+
|
|
163
|
+
### Important Considerations
|
|
164
|
+
|
|
165
|
+
**API Limits**: Depending on your OpenAI subscription, you may have limits on the number of requests. Using the cache can help minimize the number of API calls.
|
|
166
|
+
**Performance**: Querying OpenAI can add some additional time to the analysis, especially for large codebases or complex issues. The caching system helps mitigate this for repeated runs.
|
|
167
|
+
**Error Handling**: If an error occurs while querying OpenAI (e.g., invalid API key, connection issues), the tool will log the error and continue running without OpenAI insights.
|
|
168
|
+
|
|
169
|
+
## Commands
|
|
170
|
+
|
|
171
|
+
Here are some useful commands to interact with AI_Sec:
|
|
172
|
+
|
|
173
|
+
- `ai_sec run <path>`: Run the linters on the specified path and generate a report.
|
|
174
|
+
- `ai_sec export-config` - exports default config
|
|
175
|
+
|
|
176
|
+
## Changelog
|
|
177
|
+
|
|
178
|
+
For detailed information about changes in each version, see the [Changelog](CHANGELOG.md).
|
|
179
|
+
|
|
180
|
+
## Contact
|
|
181
|
+
|
|
182
|
+
If you encounter any issues or have any suggestions, please feel free to send them to dev@darrenrabbitt.com. Thank you for your support!
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
name = "ai_sec"
|
|
3
|
+
version = "0.0.1"
|
|
4
|
+
description = "Linting, security scanning, and reporting on infrastructure code and Kubernetes config"
|
|
5
|
+
authors = ["Darren Rabbitt"]
|
|
6
|
+
maintainers = ["Darren Rabbitt <dev@darrenrabbitt.com>"]
|
|
7
|
+
license = "MIT"
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
packages = [
|
|
10
|
+
{ include = "ai_sec", from = "src" }
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
# Add include section to explicitly include config.yaml
|
|
14
|
+
include = [
|
|
15
|
+
"src/ai_sec/resources/config.yaml",
|
|
16
|
+
"CHANGELOG.md" # Explicitly include changelog in package
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[tool.poetry.dependencies]
|
|
20
|
+
python = ">=3.10,<4.0"
|
|
21
|
+
PyYAML = "^6.0.2"
|
|
22
|
+
Jinja2 = "^3.1.4"
|
|
23
|
+
checkov = "^3.2.267"
|
|
24
|
+
dash = "^2.18.0"
|
|
25
|
+
pandas = "^2.2.2"
|
|
26
|
+
dash-bootstrap-components = "^1.6.0"
|
|
27
|
+
click = "^8.1.7"
|
|
28
|
+
ijson = "^3.3.0"
|
|
29
|
+
aiofiles = "^24.1.0"
|
|
30
|
+
|
|
31
|
+
[tool.poetry.scripts]
|
|
32
|
+
ai_sec = "ai_sec.linter_runner:cli"
|
|
33
|
+
# Uncomment if you need multiple command names
|
|
34
|
+
# inf_lint = "infra_lint.linter_runner:cli"
|
|
35
|
+
# ilint = "infra_lint.linter_runner:cli"
|
|
36
|
+
|
|
37
|
+
[tool.poetry.dev-dependencies]
|
|
38
|
+
black = "^24.8.0"
|
|
39
|
+
flake8 = "^7.1.1"
|
|
40
|
+
bandit = "^1.7.9"
|
|
41
|
+
pytest = "^7.2.2"
|
|
42
|
+
pytest-mock = "^3.10.0"
|
|
43
|
+
mypy = "^1.11.0"
|
|
44
|
+
safety = "^3.2.4"
|
|
45
|
+
pylint = "^3.2.6"
|
|
46
|
+
types-pyyaml = "^6.0.12.20240724"
|
|
47
|
+
# Only keep these if you're using boto3 and requests
|
|
48
|
+
types-boto3 = "^1.0.2"
|
|
49
|
+
types-requests = "^2.28.11.7"
|
|
50
|
+
|
|
51
|
+
[tool.mypy]
|
|
52
|
+
files = "src, tests"
|
|
53
|
+
ignore_missing_imports = true
|
|
54
|
+
disallow_untyped_calls = false
|
|
55
|
+
disallow_untyped_defs = false
|
|
56
|
+
disallow_untyped_decorators = false
|
|
57
|
+
warn_return_any = true
|
|
58
|
+
warn_unused_ignores = true
|
|
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
|
|
@@ -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
|