sqlshield 0.0.2__tar.gz → 0.0.4__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.
Potentially problematic release.
This version of sqlshield might be problematic. Click here for more details.
- sqlshield-0.0.4/PKG-INFO +232 -0
- sqlshield-0.0.4/README.md +218 -0
- {sqlshield-0.0.2 → sqlshield-0.0.4}/pyproject.toml +1 -1
- {sqlshield-0.0.2 → sqlshield-0.0.4}/src/sqlshield/models.py +27 -10
- {sqlshield-0.0.2 → sqlshield-0.0.4}/src/sqlshield/shield.py +15 -9
- sqlshield-0.0.4/src/sqlshield.egg-info/PKG-INFO +232 -0
- {sqlshield-0.0.2 → sqlshield-0.0.4}/tests/test_malicious_sql.py +5 -3
- sqlshield-0.0.2/PKG-INFO +0 -125
- sqlshield-0.0.2/README.md +0 -111
- sqlshield-0.0.2/src/sqlshield.egg-info/PKG-INFO +0 -125
- {sqlshield-0.0.2 → sqlshield-0.0.4}/LICENSE +0 -0
- {sqlshield-0.0.2 → sqlshield-0.0.4}/setup.cfg +0 -0
- {sqlshield-0.0.2 → sqlshield-0.0.4}/src/sqlshield/__init__.py +0 -0
- {sqlshield-0.0.2 → sqlshield-0.0.4}/src/sqlshield.egg-info/SOURCES.txt +0 -0
- {sqlshield-0.0.2 → sqlshield-0.0.4}/src/sqlshield.egg-info/dependency_links.txt +0 -0
- {sqlshield-0.0.2 → sqlshield-0.0.4}/src/sqlshield.egg-info/top_level.txt +0 -0
sqlshield-0.0.4/PKG-INFO
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: sqlshield
|
|
3
|
+
Version: 0.0.4
|
|
4
|
+
Summary: A Shield for your LLM generated SQL Queries. It provides an application level control for securing the database from SQL generated by LLM.
|
|
5
|
+
Author-email: Sandeep Giri <sandeepgiri@gmail.com>
|
|
6
|
+
Project-URL: Homepage, https://github.com/terno-ai/llm-sql-shield
|
|
7
|
+
Project-URL: Issues, https://github.com/terno-ai/llm-sql-shield/issues
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Requires-Python: >=3.8
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
|
|
15
|
+
# LLM SQL Shield
|
|
16
|
+
|
|
17
|
+
A shield for your database to neutralize the SQL queries generated by Large Language Models (LLM).
|
|
18
|
+
|
|
19
|
+
## Background
|
|
20
|
+
|
|
21
|
+
Large Language Models (LLM) have proven to be extraordinarily effective in generating SQL queries, revolutionizing SQL generation using large language models.
|
|
22
|
+
|
|
23
|
+
However, there is a significant challenge: a threat to the database. The queries generated by LLMs can access data that they aren't supposed to. No matter how constrained the prompt is, it is always possible to jailbreak. Given the nature of LLMs, they can never be controlled deterministically.
|
|
24
|
+
|
|
25
|
+
Securing the database is difficult because:
|
|
26
|
+
|
|
27
|
+
1. Databases are usually controlled and managed by a different team. Therefore, any changes to the databases would take time.
|
|
28
|
+
2. Databases are usually accessed and modified by multiple different services. Therefore, making any change to the database is difficult.
|
|
29
|
+
3. Database security is designed for a handful of roles and users. Achieving security for thousands of users is difficult.
|
|
30
|
+
4. Row-based security can be achieved by predefined views, but if we have to have dynamic views or parameterized views, it is not possible in databases as of now.
|
|
31
|
+
5. LLMs require the table names and column names to be self-explanatory. To achieve the same in a database, you will have to clone the database and make modifications to it, but then making the data sync in these tables becomes a difficult task.
|
|
32
|
+
|
|
33
|
+
## LLM SQL Shield - Features
|
|
34
|
+
|
|
35
|
+
With SQL Shield, you can:
|
|
36
|
+
|
|
37
|
+
1. Limit the tables that you expose to LLM.
|
|
38
|
+
2. Rename the tables as per your wish by setting proper `pub_name`.
|
|
39
|
+
3. Limit the columns from each table.
|
|
40
|
+
4. Rename the columns to make them more meaningful by setting proper `pub_name`.
|
|
41
|
+
5. Limit the rows that can be accessed by providing `filters`.
|
|
42
|
+
6. The `filters` can have variables that you can fill in at the time of query generation and execution.
|
|
43
|
+
|
|
44
|
+
## Getting started or How does it work?
|
|
45
|
+
|
|
46
|
+
### Install
|
|
47
|
+
It is available as the pip package. You can simply install it like this:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install sqlshield
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### Prepare the Schema
|
|
54
|
+
|
|
55
|
+
Once installed, you can import the following:
|
|
56
|
+
```python
|
|
57
|
+
# Models contain the models for Table, Column, and Database.
|
|
58
|
+
from sqlshield.models import *
|
|
59
|
+
|
|
60
|
+
# The main work of handling and generating SQL is done by this
|
|
61
|
+
# The entry point is Session object.
|
|
62
|
+
from sqlshield.shield import *
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The basic idea is that you create a pseudo-schema of your database keeping track of the original table name and column names. You expose this pseudo-schema to LLM to generate a query and then translate this query to internal tables.
|
|
66
|
+
|
|
67
|
+
Further, in the pseudo-schema, you create the row filters or parameterized views that basically filter rows per user.
|
|
68
|
+
|
|
69
|
+
The first step is to create the schema. Either you can create a schema by creating instances of MDatabase, MTable, and MColumn or you can simply instantiate by loading existing tables from your database using SQLAlchemy. I would recommend the second approach because it is easier and more maintainable - think of the new tables being introduced.
|
|
70
|
+
|
|
71
|
+
Let's go ahead and load the database objects using SQLAlchemy.
|
|
72
|
+
```bash
|
|
73
|
+
pip install sqlalchemy
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
# Using SQLAlchemy
|
|
78
|
+
import sqlalchemy
|
|
79
|
+
from sqlalchemy import inspect
|
|
80
|
+
from sqlalchemy import text
|
|
81
|
+
|
|
82
|
+
engine = sqlalchemy.create_engine('sqlite:///chinook.db')
|
|
83
|
+
inspector = inspect(engine)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Now, using the inspector, you can create the SQL Shield's models: MTable, MColumn, and MDatabase automatically.
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
mDb = MDatabase.from_inspector(inspector)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Once you have the MDatabase instance ready, you can start modifying it to ensure that only minimal information is exposed to the LLMs.
|
|
93
|
+
|
|
94
|
+
The following code removes all the tables except for four tables. This also reduces the prompt size.
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine']))
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`MDatabase.keep_only_tables` is a handy utility method. To suit your business needs, you directly modify the `MDatabase.tables` object, which is a `set()`.
|
|
101
|
+
|
|
102
|
+
If you want to modify each table, you can access the table directly from `MDatabase.tables` `set()` object. Since it is easier to create a dictionary and then access it, we have provided `get_table_dict()` as shown in the below code:
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
# It is a handy method to get the tables as a dictionary.
|
|
106
|
+
# Please use the MDatabase.tables
|
|
107
|
+
tables = mDb.get_table_dict()
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Now, say we want to modify a table with the name `Customer`. We can change its name to `Customers`. Quite often the table names in your organization could be really messy and LLMs would not be able to generate good queries on this. You can give a good `pub_name` to each table. `pub_name` is what is shown to the LLM.
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
customer_table = tables['Customer']
|
|
114
|
+
# Change Name of table
|
|
115
|
+
customer_table.pub_name = 'Customers'
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
*Filters* are the most powerful feature of SQL Shield. Filters let you create subspaces for users. Using filters, you can limit the rows shown to the user. Say, there is a table that contains the data for all 500 teams in your organization. You want each team to see only their data. So you would create a filter now and at runtime, you would insert the team as part of parameters.
|
|
119
|
+
|
|
120
|
+
Here in this example, we want users to access only the rows of the `Customers` table that belong to their company.
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
# Add a filter
|
|
124
|
+
customer_table.filters = 'where company = {company}'
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
You can access the columns of an `MTable` using the `columns` which is a `set()`. It also provides a handy method `drop_columns`. I will be adding more handy methods based on the user's requests.
|
|
128
|
+
|
|
129
|
+
But you can simply access all columns from the set and modify it. Each column is `MColumn`, it has an important field `pub_name`. If you want to modify the name of a column that is visible to an LLM, just change pub_name. Don't change `name`.
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
# Drop some columns
|
|
133
|
+
customer_table.drop_columns(set(['Address']))
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
That's it. Your database is ready!
|
|
137
|
+
|
|
138
|
+
### Generate Schema for LLM
|
|
139
|
+
With this MDatabase `mDb` prepared in previous steps, we can generate schema to augment the prompt as follows:
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
schema_generated = mDb.generate_schema()
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
We can send this schema along with the question in the prompt to any LLMs and once LLMs generate SQL, we can re-write the SQL. Say, an LLM has generated a query `aSql`.
|
|
146
|
+
|
|
147
|
+
We can now, generate the safe query using the `aSQL` as follows:
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
d = {'company':'\'Telus\''}
|
|
151
|
+
sess = Session(mDb, d)
|
|
152
|
+
gSQL = sess.generateNativeSQL(aSql)
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
That's it. `gSQL` would have a query that is safe. Please note that we created a dictionary of parameters and passed it to the constructor of Session because we had parameterized filters that would limit the rows to the `company = Talus`.
|
|
156
|
+
|
|
157
|
+
Now, you can execute the `gSQL` on your actual database peacefully.
|
|
158
|
+
|
|
159
|
+
## Complete Example with Open AI
|
|
160
|
+
|
|
161
|
+
Here is an example:
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
import sqlalchemy
|
|
165
|
+
from sqlalchemy import inspect
|
|
166
|
+
from sqlalchemy import text
|
|
167
|
+
|
|
168
|
+
from sqlshield.models import *
|
|
169
|
+
from sqlshield.shield import *
|
|
170
|
+
import os
|
|
171
|
+
|
|
172
|
+
# TODO: Specify correct OpenAI key
|
|
173
|
+
os.environ["OPENAI_API_KEY"] = 'sk-XXXXXXXXX'
|
|
174
|
+
|
|
175
|
+
# TODO: You can download this SQLite3 DB file: https://github.com/terno-ai/llm-sql-shield/raw/main/tests/chinook.db
|
|
176
|
+
# And save it in your current directory
|
|
177
|
+
# Connect to DB
|
|
178
|
+
engine = sqlalchemy.create_engine('sqlite:///chinook.db')
|
|
179
|
+
inspector = inspect(engine)
|
|
180
|
+
|
|
181
|
+
# Load default DB
|
|
182
|
+
mDb = MDatabase.from_inspector(inspector)
|
|
183
|
+
|
|
184
|
+
mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine']))
|
|
185
|
+
|
|
186
|
+
tables = mDb.get_table_dict()
|
|
187
|
+
customer_table = tables['Customer']
|
|
188
|
+
|
|
189
|
+
# Change Name of table
|
|
190
|
+
customer_table.pub_name = 'Customers'
|
|
191
|
+
|
|
192
|
+
# Add a filter
|
|
193
|
+
customer_table.filters = 'where company = {company}'
|
|
194
|
+
|
|
195
|
+
# Drop some colums
|
|
196
|
+
customer_table.drop_columns(set(['Address']))
|
|
197
|
+
|
|
198
|
+
# Column renaming
|
|
199
|
+
|
|
200
|
+
question = "Show me all customers."
|
|
201
|
+
|
|
202
|
+
from openai import OpenAI
|
|
203
|
+
client = OpenAI()
|
|
204
|
+
|
|
205
|
+
schema_generated = mDb.generate_schema()
|
|
206
|
+
print('The following schema was generated: ', schema_generated)
|
|
207
|
+
|
|
208
|
+
response = client.chat.completions.create(
|
|
209
|
+
model="gpt-3.5-turbo",
|
|
210
|
+
messages=[
|
|
211
|
+
{"role": "system", "content": "You are an SQL Analyst. Your role is to generate the SQL given a question. Only generate SQL nothing else."},
|
|
212
|
+
{"role": "user", "content": question},
|
|
213
|
+
{"role": "assistant", "content": "The tables schema is follows: " + schema_generated},
|
|
214
|
+
]
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
aSql = response.choices[0].message.content
|
|
218
|
+
print('SQL Generated by LLM: ', aSql)
|
|
219
|
+
|
|
220
|
+
d = {'company':'\'Telus\''}
|
|
221
|
+
sess = Session(mDb, d)
|
|
222
|
+
gSQL = sess.generateNativeSQL(aSql)
|
|
223
|
+
print("Native SQL: ", gSQL)
|
|
224
|
+
|
|
225
|
+
print(" ===================== ")
|
|
226
|
+
with engine.connect() as con:
|
|
227
|
+
rs = con.execute(text(gSQL))
|
|
228
|
+
for row in rs:
|
|
229
|
+
print(row)
|
|
230
|
+
|
|
231
|
+
```
|
|
232
|
+
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# LLM SQL Shield
|
|
2
|
+
|
|
3
|
+
A shield for your database to neutralize the SQL queries generated by Large Language Models (LLM).
|
|
4
|
+
|
|
5
|
+
## Background
|
|
6
|
+
|
|
7
|
+
Large Language Models (LLM) have proven to be extraordinarily effective in generating SQL queries, revolutionizing SQL generation using large language models.
|
|
8
|
+
|
|
9
|
+
However, there is a significant challenge: a threat to the database. The queries generated by LLMs can access data that they aren't supposed to. No matter how constrained the prompt is, it is always possible to jailbreak. Given the nature of LLMs, they can never be controlled deterministically.
|
|
10
|
+
|
|
11
|
+
Securing the database is difficult because:
|
|
12
|
+
|
|
13
|
+
1. Databases are usually controlled and managed by a different team. Therefore, any changes to the databases would take time.
|
|
14
|
+
2. Databases are usually accessed and modified by multiple different services. Therefore, making any change to the database is difficult.
|
|
15
|
+
3. Database security is designed for a handful of roles and users. Achieving security for thousands of users is difficult.
|
|
16
|
+
4. Row-based security can be achieved by predefined views, but if we have to have dynamic views or parameterized views, it is not possible in databases as of now.
|
|
17
|
+
5. LLMs require the table names and column names to be self-explanatory. To achieve the same in a database, you will have to clone the database and make modifications to it, but then making the data sync in these tables becomes a difficult task.
|
|
18
|
+
|
|
19
|
+
## LLM SQL Shield - Features
|
|
20
|
+
|
|
21
|
+
With SQL Shield, you can:
|
|
22
|
+
|
|
23
|
+
1. Limit the tables that you expose to LLM.
|
|
24
|
+
2. Rename the tables as per your wish by setting proper `pub_name`.
|
|
25
|
+
3. Limit the columns from each table.
|
|
26
|
+
4. Rename the columns to make them more meaningful by setting proper `pub_name`.
|
|
27
|
+
5. Limit the rows that can be accessed by providing `filters`.
|
|
28
|
+
6. The `filters` can have variables that you can fill in at the time of query generation and execution.
|
|
29
|
+
|
|
30
|
+
## Getting started or How does it work?
|
|
31
|
+
|
|
32
|
+
### Install
|
|
33
|
+
It is available as the pip package. You can simply install it like this:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install sqlshield
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Prepare the Schema
|
|
40
|
+
|
|
41
|
+
Once installed, you can import the following:
|
|
42
|
+
```python
|
|
43
|
+
# Models contain the models for Table, Column, and Database.
|
|
44
|
+
from sqlshield.models import *
|
|
45
|
+
|
|
46
|
+
# The main work of handling and generating SQL is done by this
|
|
47
|
+
# The entry point is Session object.
|
|
48
|
+
from sqlshield.shield import *
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The basic idea is that you create a pseudo-schema of your database keeping track of the original table name and column names. You expose this pseudo-schema to LLM to generate a query and then translate this query to internal tables.
|
|
52
|
+
|
|
53
|
+
Further, in the pseudo-schema, you create the row filters or parameterized views that basically filter rows per user.
|
|
54
|
+
|
|
55
|
+
The first step is to create the schema. Either you can create a schema by creating instances of MDatabase, MTable, and MColumn or you can simply instantiate by loading existing tables from your database using SQLAlchemy. I would recommend the second approach because it is easier and more maintainable - think of the new tables being introduced.
|
|
56
|
+
|
|
57
|
+
Let's go ahead and load the database objects using SQLAlchemy.
|
|
58
|
+
```bash
|
|
59
|
+
pip install sqlalchemy
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
# Using SQLAlchemy
|
|
64
|
+
import sqlalchemy
|
|
65
|
+
from sqlalchemy import inspect
|
|
66
|
+
from sqlalchemy import text
|
|
67
|
+
|
|
68
|
+
engine = sqlalchemy.create_engine('sqlite:///chinook.db')
|
|
69
|
+
inspector = inspect(engine)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Now, using the inspector, you can create the SQL Shield's models: MTable, MColumn, and MDatabase automatically.
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
mDb = MDatabase.from_inspector(inspector)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Once you have the MDatabase instance ready, you can start modifying it to ensure that only minimal information is exposed to the LLMs.
|
|
79
|
+
|
|
80
|
+
The following code removes all the tables except for four tables. This also reduces the prompt size.
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine']))
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`MDatabase.keep_only_tables` is a handy utility method. To suit your business needs, you directly modify the `MDatabase.tables` object, which is a `set()`.
|
|
87
|
+
|
|
88
|
+
If you want to modify each table, you can access the table directly from `MDatabase.tables` `set()` object. Since it is easier to create a dictionary and then access it, we have provided `get_table_dict()` as shown in the below code:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
# It is a handy method to get the tables as a dictionary.
|
|
92
|
+
# Please use the MDatabase.tables
|
|
93
|
+
tables = mDb.get_table_dict()
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Now, say we want to modify a table with the name `Customer`. We can change its name to `Customers`. Quite often the table names in your organization could be really messy and LLMs would not be able to generate good queries on this. You can give a good `pub_name` to each table. `pub_name` is what is shown to the LLM.
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
customer_table = tables['Customer']
|
|
100
|
+
# Change Name of table
|
|
101
|
+
customer_table.pub_name = 'Customers'
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
*Filters* are the most powerful feature of SQL Shield. Filters let you create subspaces for users. Using filters, you can limit the rows shown to the user. Say, there is a table that contains the data for all 500 teams in your organization. You want each team to see only their data. So you would create a filter now and at runtime, you would insert the team as part of parameters.
|
|
105
|
+
|
|
106
|
+
Here in this example, we want users to access only the rows of the `Customers` table that belong to their company.
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
# Add a filter
|
|
110
|
+
customer_table.filters = 'where company = {company}'
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
You can access the columns of an `MTable` using the `columns` which is a `set()`. It also provides a handy method `drop_columns`. I will be adding more handy methods based on the user's requests.
|
|
114
|
+
|
|
115
|
+
But you can simply access all columns from the set and modify it. Each column is `MColumn`, it has an important field `pub_name`. If you want to modify the name of a column that is visible to an LLM, just change pub_name. Don't change `name`.
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
# Drop some columns
|
|
119
|
+
customer_table.drop_columns(set(['Address']))
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
That's it. Your database is ready!
|
|
123
|
+
|
|
124
|
+
### Generate Schema for LLM
|
|
125
|
+
With this MDatabase `mDb` prepared in previous steps, we can generate schema to augment the prompt as follows:
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
schema_generated = mDb.generate_schema()
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
We can send this schema along with the question in the prompt to any LLMs and once LLMs generate SQL, we can re-write the SQL. Say, an LLM has generated a query `aSql`.
|
|
132
|
+
|
|
133
|
+
We can now, generate the safe query using the `aSQL` as follows:
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
d = {'company':'\'Telus\''}
|
|
137
|
+
sess = Session(mDb, d)
|
|
138
|
+
gSQL = sess.generateNativeSQL(aSql)
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
That's it. `gSQL` would have a query that is safe. Please note that we created a dictionary of parameters and passed it to the constructor of Session because we had parameterized filters that would limit the rows to the `company = Talus`.
|
|
142
|
+
|
|
143
|
+
Now, you can execute the `gSQL` on your actual database peacefully.
|
|
144
|
+
|
|
145
|
+
## Complete Example with Open AI
|
|
146
|
+
|
|
147
|
+
Here is an example:
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
import sqlalchemy
|
|
151
|
+
from sqlalchemy import inspect
|
|
152
|
+
from sqlalchemy import text
|
|
153
|
+
|
|
154
|
+
from sqlshield.models import *
|
|
155
|
+
from sqlshield.shield import *
|
|
156
|
+
import os
|
|
157
|
+
|
|
158
|
+
# TODO: Specify correct OpenAI key
|
|
159
|
+
os.environ["OPENAI_API_KEY"] = 'sk-XXXXXXXXX'
|
|
160
|
+
|
|
161
|
+
# TODO: You can download this SQLite3 DB file: https://github.com/terno-ai/llm-sql-shield/raw/main/tests/chinook.db
|
|
162
|
+
# And save it in your current directory
|
|
163
|
+
# Connect to DB
|
|
164
|
+
engine = sqlalchemy.create_engine('sqlite:///chinook.db')
|
|
165
|
+
inspector = inspect(engine)
|
|
166
|
+
|
|
167
|
+
# Load default DB
|
|
168
|
+
mDb = MDatabase.from_inspector(inspector)
|
|
169
|
+
|
|
170
|
+
mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine']))
|
|
171
|
+
|
|
172
|
+
tables = mDb.get_table_dict()
|
|
173
|
+
customer_table = tables['Customer']
|
|
174
|
+
|
|
175
|
+
# Change Name of table
|
|
176
|
+
customer_table.pub_name = 'Customers'
|
|
177
|
+
|
|
178
|
+
# Add a filter
|
|
179
|
+
customer_table.filters = 'where company = {company}'
|
|
180
|
+
|
|
181
|
+
# Drop some colums
|
|
182
|
+
customer_table.drop_columns(set(['Address']))
|
|
183
|
+
|
|
184
|
+
# Column renaming
|
|
185
|
+
|
|
186
|
+
question = "Show me all customers."
|
|
187
|
+
|
|
188
|
+
from openai import OpenAI
|
|
189
|
+
client = OpenAI()
|
|
190
|
+
|
|
191
|
+
schema_generated = mDb.generate_schema()
|
|
192
|
+
print('The following schema was generated: ', schema_generated)
|
|
193
|
+
|
|
194
|
+
response = client.chat.completions.create(
|
|
195
|
+
model="gpt-3.5-turbo",
|
|
196
|
+
messages=[
|
|
197
|
+
{"role": "system", "content": "You are an SQL Analyst. Your role is to generate the SQL given a question. Only generate SQL nothing else."},
|
|
198
|
+
{"role": "user", "content": question},
|
|
199
|
+
{"role": "assistant", "content": "The tables schema is follows: " + schema_generated},
|
|
200
|
+
]
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
aSql = response.choices[0].message.content
|
|
204
|
+
print('SQL Generated by LLM: ', aSql)
|
|
205
|
+
|
|
206
|
+
d = {'company':'\'Telus\''}
|
|
207
|
+
sess = Session(mDb, d)
|
|
208
|
+
gSQL = sess.generateNativeSQL(aSql)
|
|
209
|
+
print("Native SQL: ", gSQL)
|
|
210
|
+
|
|
211
|
+
print(" ===================== ")
|
|
212
|
+
with engine.connect() as con:
|
|
213
|
+
rs = con.execute(text(gSQL))
|
|
214
|
+
for row in rs:
|
|
215
|
+
print(row)
|
|
216
|
+
|
|
217
|
+
```
|
|
218
|
+
|
|
@@ -3,60 +3,72 @@ class Column():
|
|
|
3
3
|
def __init__(self, **kwargs):
|
|
4
4
|
self.name = kwargs['name']
|
|
5
5
|
self.type = kwargs['type']
|
|
6
|
-
self.primary_key = kwargs
|
|
6
|
+
self.primary_key = kwargs.get('primary_key', '')
|
|
7
7
|
self.nullable = kwargs['nullable']
|
|
8
8
|
self.desc = kwargs.get('desc', '')
|
|
9
9
|
self.foreign_keys = []
|
|
10
|
+
|
|
10
11
|
def __hash__(self):
|
|
11
12
|
return hash(self.name)
|
|
13
|
+
|
|
12
14
|
def __eq__(self, __value: object) -> bool:
|
|
13
15
|
_s = self
|
|
14
16
|
_v = __value
|
|
15
17
|
return (_s.name, _s.type, _s.primary_key, _s.desc) == (_v.name, _v.type, _v.primary_key, _v.desc)
|
|
16
18
|
|
|
19
|
+
|
|
17
20
|
class MColumn(Column):
|
|
18
21
|
def __init__(self, pub_name=None, **kwargs):
|
|
19
22
|
super().__init__(**kwargs)
|
|
20
|
-
if pub_name
|
|
23
|
+
if pub_name is None:
|
|
21
24
|
pub_name = self.name
|
|
22
25
|
self.pub_name = pub_name
|
|
26
|
+
|
|
23
27
|
def generate_schema(self):
|
|
24
28
|
return '[%s] %s' % (self.pub_name, str(self.type))
|
|
25
29
|
|
|
30
|
+
|
|
26
31
|
class Table:
|
|
27
32
|
def __init__(self, **kwargs):
|
|
28
33
|
self.name = kwargs['name']
|
|
29
34
|
# self.pk = pk
|
|
30
35
|
self.columns = set()
|
|
31
36
|
self.desc = kwargs['desc']
|
|
37
|
+
|
|
32
38
|
def __hash__(self):
|
|
33
39
|
return hash(self.name)
|
|
40
|
+
|
|
34
41
|
def __eq__(self, __value: object) -> bool:
|
|
35
42
|
_s = self
|
|
36
43
|
_v = __value
|
|
37
44
|
return (_s.name, _s.pk, _s.columns, _s.desc) == (_v.name, _v.pk, _v.columns, _v.desc)
|
|
38
45
|
|
|
46
|
+
|
|
39
47
|
class MTable(Table):
|
|
40
48
|
def __init__(self, name, desc='', pub_name=None, filters=None):
|
|
41
49
|
super().__init__(name=name, desc=desc)
|
|
42
|
-
if pub_name
|
|
50
|
+
if pub_name is None:
|
|
43
51
|
pub_name = self.name
|
|
44
52
|
self.pub_name = pub_name
|
|
45
|
-
self.filters = filters
|
|
53
|
+
self.filters = filters # template/Format string containing {var1}
|
|
54
|
+
|
|
46
55
|
def _get_projections_sql(self):
|
|
47
56
|
result = []
|
|
48
57
|
for col in self.columns:
|
|
49
58
|
result.append("%s as %s" % (col.name, col.pub_name))
|
|
50
59
|
return ', '.join(result)
|
|
51
|
-
|
|
52
|
-
def get_alias_sql(self, params):
|
|
60
|
+
|
|
61
|
+
def get_alias_sql(self, params, alias=None):
|
|
53
62
|
filterSQL = ''
|
|
54
63
|
if self.filters:
|
|
55
64
|
filterSQL = self.filters.format(**params)
|
|
56
65
|
sql_template = '(select %s from %s %s) as %s'
|
|
57
66
|
colsql = self._get_projections_sql()
|
|
58
|
-
|
|
67
|
+
if alias == None:
|
|
68
|
+
alias = self.pub_name
|
|
69
|
+
query = sql_template % (colsql, self.name, filterSQL, alias)
|
|
59
70
|
return query
|
|
71
|
+
|
|
60
72
|
def generate_schema(self):
|
|
61
73
|
cols_info_arr = []
|
|
62
74
|
for col in self.columns:
|
|
@@ -64,6 +76,7 @@ class MTable(Table):
|
|
|
64
76
|
col_info = ',\n\t'.join(cols_info_arr)
|
|
65
77
|
sql_template = 'CREATE TABLE [%s](\n\t%s\n\t);' % (self.pub_name, col_info)
|
|
66
78
|
return sql_template
|
|
79
|
+
|
|
67
80
|
def drop_columns(self, col_names_set):
|
|
68
81
|
to_drop = set()
|
|
69
82
|
for col in self.columns:
|
|
@@ -71,20 +84,22 @@ class MTable(Table):
|
|
|
71
84
|
to_drop.add(col)
|
|
72
85
|
self.columns = self.columns.difference(to_drop)
|
|
73
86
|
|
|
87
|
+
|
|
74
88
|
class MDatabase():
|
|
75
89
|
def __init__(self):
|
|
76
90
|
self.tables = set()
|
|
77
|
-
self.allowed_commands = ['show databases']
|
|
78
|
-
self.allowed_all_tables = []
|
|
91
|
+
# self.allowed_commands = ['show databases']
|
|
92
|
+
# self.allowed_all_tables = []
|
|
93
|
+
|
|
79
94
|
def generate_schema(self):
|
|
80
95
|
schema_arr = []
|
|
81
96
|
for table in self.tables:
|
|
82
97
|
schema_arr.append(table.generate_schema())
|
|
83
98
|
return '\n'.join(schema_arr)
|
|
99
|
+
|
|
84
100
|
def from_inspector(inspector):
|
|
85
101
|
mdb = MDatabase()
|
|
86
102
|
schemas = inspector.get_schema_names()
|
|
87
|
-
result = {}
|
|
88
103
|
for schema in schemas[:1]:
|
|
89
104
|
for table_name in inspector.get_table_names(schema=schema):
|
|
90
105
|
mtable = MTable(table_name)
|
|
@@ -93,11 +108,13 @@ class MDatabase():
|
|
|
93
108
|
mc = MColumn(**col)
|
|
94
109
|
mtable.columns.add(mc)
|
|
95
110
|
return mdb
|
|
111
|
+
|
|
96
112
|
def get_table_dict(self):
|
|
97
113
|
d = {}
|
|
98
114
|
for tbl in self.tables:
|
|
99
115
|
d[tbl.name] = tbl
|
|
100
116
|
return d
|
|
117
|
+
|
|
101
118
|
def keep_only_tables(self, keep_tbls):
|
|
102
119
|
new_tables = set()
|
|
103
120
|
for tbl in self.tables:
|
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
from sqlglot import parse_one, exp
|
|
2
2
|
|
|
3
|
+
|
|
3
4
|
class Session():
|
|
4
5
|
def __init__(self, db, params):
|
|
5
6
|
self.database = db
|
|
6
7
|
self.params = params
|
|
8
|
+
|
|
7
9
|
def is_type(tree, _type):
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
10
|
+
if len(list(tree.find_all(_type))) > 0:
|
|
11
|
+
return True
|
|
12
|
+
return False
|
|
13
|
+
|
|
11
14
|
def generateNativeSQL(self, aSql):
|
|
12
|
-
|
|
13
15
|
tree = parse_one(aSql)
|
|
14
16
|
if type(tree) != exp.Select:
|
|
15
17
|
raise Exception('As of now, only select statements are supported.', aSql)
|
|
@@ -21,19 +23,23 @@ class Session():
|
|
|
21
23
|
tbl_map = {}
|
|
22
24
|
for tbl in self.database.tables:
|
|
23
25
|
tbl_map[tbl.pub_name.lower()] = tbl
|
|
24
|
-
|
|
26
|
+
|
|
25
27
|
print("Input: ", aSql)
|
|
28
|
+
|
|
26
29
|
def transformer(node):
|
|
27
30
|
if isinstance(node, exp.Table):
|
|
28
|
-
tbl_name_c = node.this.this
|
|
31
|
+
tbl_name_c = node.this.this
|
|
29
32
|
tbl_name = tbl_name_c.lower()
|
|
30
33
|
if tbl_name not in tbl_map:
|
|
31
34
|
raise Exception('No such table found.', tbl_name_c)
|
|
32
35
|
mtable = tbl_map[tbl_name]
|
|
33
|
-
|
|
36
|
+
if node.alias == '':
|
|
37
|
+
alias = None
|
|
38
|
+
else:
|
|
39
|
+
alias = node.alias
|
|
40
|
+
msql = mtable.get_alias_sql(self.params, alias)
|
|
34
41
|
return parse_one(msql)
|
|
35
42
|
return node
|
|
36
|
-
|
|
43
|
+
|
|
37
44
|
new_tree = tree.transform(transformer)
|
|
38
45
|
return new_tree.sql()
|
|
39
|
-
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: sqlshield
|
|
3
|
+
Version: 0.0.4
|
|
4
|
+
Summary: A Shield for your LLM generated SQL Queries. It provides an application level control for securing the database from SQL generated by LLM.
|
|
5
|
+
Author-email: Sandeep Giri <sandeepgiri@gmail.com>
|
|
6
|
+
Project-URL: Homepage, https://github.com/terno-ai/llm-sql-shield
|
|
7
|
+
Project-URL: Issues, https://github.com/terno-ai/llm-sql-shield/issues
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Requires-Python: >=3.8
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
|
|
15
|
+
# LLM SQL Shield
|
|
16
|
+
|
|
17
|
+
A shield for your database to neutralize the SQL queries generated by Large Language Models (LLM).
|
|
18
|
+
|
|
19
|
+
## Background
|
|
20
|
+
|
|
21
|
+
Large Language Models (LLM) have proven to be extraordinarily effective in generating SQL queries, revolutionizing SQL generation using large language models.
|
|
22
|
+
|
|
23
|
+
However, there is a significant challenge: a threat to the database. The queries generated by LLMs can access data that they aren't supposed to. No matter how constrained the prompt is, it is always possible to jailbreak. Given the nature of LLMs, they can never be controlled deterministically.
|
|
24
|
+
|
|
25
|
+
Securing the database is difficult because:
|
|
26
|
+
|
|
27
|
+
1. Databases are usually controlled and managed by a different team. Therefore, any changes to the databases would take time.
|
|
28
|
+
2. Databases are usually accessed and modified by multiple different services. Therefore, making any change to the database is difficult.
|
|
29
|
+
3. Database security is designed for a handful of roles and users. Achieving security for thousands of users is difficult.
|
|
30
|
+
4. Row-based security can be achieved by predefined views, but if we have to have dynamic views or parameterized views, it is not possible in databases as of now.
|
|
31
|
+
5. LLMs require the table names and column names to be self-explanatory. To achieve the same in a database, you will have to clone the database and make modifications to it, but then making the data sync in these tables becomes a difficult task.
|
|
32
|
+
|
|
33
|
+
## LLM SQL Shield - Features
|
|
34
|
+
|
|
35
|
+
With SQL Shield, you can:
|
|
36
|
+
|
|
37
|
+
1. Limit the tables that you expose to LLM.
|
|
38
|
+
2. Rename the tables as per your wish by setting proper `pub_name`.
|
|
39
|
+
3. Limit the columns from each table.
|
|
40
|
+
4. Rename the columns to make them more meaningful by setting proper `pub_name`.
|
|
41
|
+
5. Limit the rows that can be accessed by providing `filters`.
|
|
42
|
+
6. The `filters` can have variables that you can fill in at the time of query generation and execution.
|
|
43
|
+
|
|
44
|
+
## Getting started or How does it work?
|
|
45
|
+
|
|
46
|
+
### Install
|
|
47
|
+
It is available as the pip package. You can simply install it like this:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install sqlshield
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### Prepare the Schema
|
|
54
|
+
|
|
55
|
+
Once installed, you can import the following:
|
|
56
|
+
```python
|
|
57
|
+
# Models contain the models for Table, Column, and Database.
|
|
58
|
+
from sqlshield.models import *
|
|
59
|
+
|
|
60
|
+
# The main work of handling and generating SQL is done by this
|
|
61
|
+
# The entry point is Session object.
|
|
62
|
+
from sqlshield.shield import *
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The basic idea is that you create a pseudo-schema of your database keeping track of the original table name and column names. You expose this pseudo-schema to LLM to generate a query and then translate this query to internal tables.
|
|
66
|
+
|
|
67
|
+
Further, in the pseudo-schema, you create the row filters or parameterized views that basically filter rows per user.
|
|
68
|
+
|
|
69
|
+
The first step is to create the schema. Either you can create a schema by creating instances of MDatabase, MTable, and MColumn or you can simply instantiate by loading existing tables from your database using SQLAlchemy. I would recommend the second approach because it is easier and more maintainable - think of the new tables being introduced.
|
|
70
|
+
|
|
71
|
+
Let's go ahead and load the database objects using SQLAlchemy.
|
|
72
|
+
```bash
|
|
73
|
+
pip install sqlalchemy
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
# Using SQLAlchemy
|
|
78
|
+
import sqlalchemy
|
|
79
|
+
from sqlalchemy import inspect
|
|
80
|
+
from sqlalchemy import text
|
|
81
|
+
|
|
82
|
+
engine = sqlalchemy.create_engine('sqlite:///chinook.db')
|
|
83
|
+
inspector = inspect(engine)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Now, using the inspector, you can create the SQL Shield's models: MTable, MColumn, and MDatabase automatically.
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
mDb = MDatabase.from_inspector(inspector)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Once you have the MDatabase instance ready, you can start modifying it to ensure that only minimal information is exposed to the LLMs.
|
|
93
|
+
|
|
94
|
+
The following code removes all the tables except for four tables. This also reduces the prompt size.
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine']))
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`MDatabase.keep_only_tables` is a handy utility method. To suit your business needs, you directly modify the `MDatabase.tables` object, which is a `set()`.
|
|
101
|
+
|
|
102
|
+
If you want to modify each table, you can access the table directly from `MDatabase.tables` `set()` object. Since it is easier to create a dictionary and then access it, we have provided `get_table_dict()` as shown in the below code:
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
# It is a handy method to get the tables as a dictionary.
|
|
106
|
+
# Please use the MDatabase.tables
|
|
107
|
+
tables = mDb.get_table_dict()
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Now, say we want to modify a table with the name `Customer`. We can change its name to `Customers`. Quite often the table names in your organization could be really messy and LLMs would not be able to generate good queries on this. You can give a good `pub_name` to each table. `pub_name` is what is shown to the LLM.
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
customer_table = tables['Customer']
|
|
114
|
+
# Change Name of table
|
|
115
|
+
customer_table.pub_name = 'Customers'
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
*Filters* are the most powerful feature of SQL Shield. Filters let you create subspaces for users. Using filters, you can limit the rows shown to the user. Say, there is a table that contains the data for all 500 teams in your organization. You want each team to see only their data. So you would create a filter now and at runtime, you would insert the team as part of parameters.
|
|
119
|
+
|
|
120
|
+
Here in this example, we want users to access only the rows of the `Customers` table that belong to their company.
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
# Add a filter
|
|
124
|
+
customer_table.filters = 'where company = {company}'
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
You can access the columns of an `MTable` using the `columns` which is a `set()`. It also provides a handy method `drop_columns`. I will be adding more handy methods based on the user's requests.
|
|
128
|
+
|
|
129
|
+
But you can simply access all columns from the set and modify it. Each column is `MColumn`, it has an important field `pub_name`. If you want to modify the name of a column that is visible to an LLM, just change pub_name. Don't change `name`.
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
# Drop some columns
|
|
133
|
+
customer_table.drop_columns(set(['Address']))
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
That's it. Your database is ready!
|
|
137
|
+
|
|
138
|
+
### Generate Schema for LLM
|
|
139
|
+
With this MDatabase `mDb` prepared in previous steps, we can generate schema to augment the prompt as follows:
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
schema_generated = mDb.generate_schema()
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
We can send this schema along with the question in the prompt to any LLMs and once LLMs generate SQL, we can re-write the SQL. Say, an LLM has generated a query `aSql`.
|
|
146
|
+
|
|
147
|
+
We can now, generate the safe query using the `aSQL` as follows:
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
d = {'company':'\'Telus\''}
|
|
151
|
+
sess = Session(mDb, d)
|
|
152
|
+
gSQL = sess.generateNativeSQL(aSql)
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
That's it. `gSQL` would have a query that is safe. Please note that we created a dictionary of parameters and passed it to the constructor of Session because we had parameterized filters that would limit the rows to the `company = Talus`.
|
|
156
|
+
|
|
157
|
+
Now, you can execute the `gSQL` on your actual database peacefully.
|
|
158
|
+
|
|
159
|
+
## Complete Example with Open AI
|
|
160
|
+
|
|
161
|
+
Here is an example:
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
import sqlalchemy
|
|
165
|
+
from sqlalchemy import inspect
|
|
166
|
+
from sqlalchemy import text
|
|
167
|
+
|
|
168
|
+
from sqlshield.models import *
|
|
169
|
+
from sqlshield.shield import *
|
|
170
|
+
import os
|
|
171
|
+
|
|
172
|
+
# TODO: Specify correct OpenAI key
|
|
173
|
+
os.environ["OPENAI_API_KEY"] = 'sk-XXXXXXXXX'
|
|
174
|
+
|
|
175
|
+
# TODO: You can download this SQLite3 DB file: https://github.com/terno-ai/llm-sql-shield/raw/main/tests/chinook.db
|
|
176
|
+
# And save it in your current directory
|
|
177
|
+
# Connect to DB
|
|
178
|
+
engine = sqlalchemy.create_engine('sqlite:///chinook.db')
|
|
179
|
+
inspector = inspect(engine)
|
|
180
|
+
|
|
181
|
+
# Load default DB
|
|
182
|
+
mDb = MDatabase.from_inspector(inspector)
|
|
183
|
+
|
|
184
|
+
mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine']))
|
|
185
|
+
|
|
186
|
+
tables = mDb.get_table_dict()
|
|
187
|
+
customer_table = tables['Customer']
|
|
188
|
+
|
|
189
|
+
# Change Name of table
|
|
190
|
+
customer_table.pub_name = 'Customers'
|
|
191
|
+
|
|
192
|
+
# Add a filter
|
|
193
|
+
customer_table.filters = 'where company = {company}'
|
|
194
|
+
|
|
195
|
+
# Drop some colums
|
|
196
|
+
customer_table.drop_columns(set(['Address']))
|
|
197
|
+
|
|
198
|
+
# Column renaming
|
|
199
|
+
|
|
200
|
+
question = "Show me all customers."
|
|
201
|
+
|
|
202
|
+
from openai import OpenAI
|
|
203
|
+
client = OpenAI()
|
|
204
|
+
|
|
205
|
+
schema_generated = mDb.generate_schema()
|
|
206
|
+
print('The following schema was generated: ', schema_generated)
|
|
207
|
+
|
|
208
|
+
response = client.chat.completions.create(
|
|
209
|
+
model="gpt-3.5-turbo",
|
|
210
|
+
messages=[
|
|
211
|
+
{"role": "system", "content": "You are an SQL Analyst. Your role is to generate the SQL given a question. Only generate SQL nothing else."},
|
|
212
|
+
{"role": "user", "content": question},
|
|
213
|
+
{"role": "assistant", "content": "The tables schema is follows: " + schema_generated},
|
|
214
|
+
]
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
aSql = response.choices[0].message.content
|
|
218
|
+
print('SQL Generated by LLM: ', aSql)
|
|
219
|
+
|
|
220
|
+
d = {'company':'\'Telus\''}
|
|
221
|
+
sess = Session(mDb, d)
|
|
222
|
+
gSQL = sess.generateNativeSQL(aSql)
|
|
223
|
+
print("Native SQL: ", gSQL)
|
|
224
|
+
|
|
225
|
+
print(" ===================== ")
|
|
226
|
+
with engine.connect() as con:
|
|
227
|
+
rs = con.execute(text(gSQL))
|
|
228
|
+
for row in rs:
|
|
229
|
+
print(row)
|
|
230
|
+
|
|
231
|
+
```
|
|
232
|
+
|
|
@@ -17,7 +17,7 @@ def loadDb():
|
|
|
17
17
|
return MDatabase.from_inspector(inspector)
|
|
18
18
|
|
|
19
19
|
def build_protection(mDb):
|
|
20
|
-
mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine']))
|
|
20
|
+
mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine', 'Album', 'Artist', 'Track']))
|
|
21
21
|
|
|
22
22
|
tables = mDb.get_table_dict()
|
|
23
23
|
print("Tables: ", tables)
|
|
@@ -39,15 +39,18 @@ if __name__ == "__main__":
|
|
|
39
39
|
d = {'company':'\'Telus\''}
|
|
40
40
|
sess = Session(mDb, d)
|
|
41
41
|
sqls = [
|
|
42
|
+
"select t.name, al.title from track t join album al on t.AlbumId = al.AlbumId where name like '%Sex%';",
|
|
43
|
+
"select t.name, album.title from track t join album on t.AlbumId = album.AlbumId where name like '%Sex%';"
|
|
42
44
|
'drop table t1;'
|
|
43
45
|
'insert into Customers Values(1,2)',
|
|
44
46
|
'create table t (age int)',
|
|
45
47
|
"GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost'; ",
|
|
46
48
|
# "REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;",
|
|
47
49
|
"COMMIT;",
|
|
48
|
-
'select * from
|
|
50
|
+
'select * from Employee;drop table Employee;',
|
|
49
51
|
'select * from cusTomers',
|
|
50
52
|
'select * from cusTomer',
|
|
53
|
+
|
|
51
54
|
]
|
|
52
55
|
for sql in sqls:
|
|
53
56
|
try:
|
|
@@ -56,4 +59,3 @@ if __name__ == "__main__":
|
|
|
56
59
|
print("Native SQL: ", gSQL)
|
|
57
60
|
except Exception as e:
|
|
58
61
|
print("ERROR: ", e.args)
|
|
59
|
-
|
sqlshield-0.0.2/PKG-INFO
DELETED
|
@@ -1,125 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.1
|
|
2
|
-
Name: sqlshield
|
|
3
|
-
Version: 0.0.2
|
|
4
|
-
Summary: A Shield for your LLM generated SQL Queries. It provides an application level control for securing the database from SQL generated by LLM.
|
|
5
|
-
Author-email: Sandeep Giri <sandeepgiri@gmail.com>
|
|
6
|
-
Project-URL: Homepage, https://github.com/terno-ai/llm-sql-shield
|
|
7
|
-
Project-URL: Issues, https://github.com/terno-ai/llm-sql-shield/issues
|
|
8
|
-
Classifier: Programming Language :: Python :: 3
|
|
9
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
-
Classifier: Operating System :: OS Independent
|
|
11
|
-
Requires-Python: >=3.8
|
|
12
|
-
Description-Content-Type: text/markdown
|
|
13
|
-
License-File: LICENSE
|
|
14
|
-
|
|
15
|
-
# LLM SQL Shield
|
|
16
|
-
A Shield for your database to neutralize the SQL queries generated by Large Language Model (LLM)
|
|
17
|
-
|
|
18
|
-
## Background
|
|
19
|
-
|
|
20
|
-
Large Language Models (LLM) have proven to be extraordinarily effective in generating SQL queries. This has revolutionized SQL generation using large language models.
|
|
21
|
-
|
|
22
|
-
However, there is a significant challenge: a threat to the database. The queries generated by LLMs can access data that they aren't supposed to. No matter how constrained the prompt is, it is always possible to jailbreak. Given the nature of LLMs, they can never be controlled deterministically.
|
|
23
|
-
|
|
24
|
-
Securing the database is difficult because:
|
|
25
|
-
|
|
26
|
-
1. Databases are usually controlled and managed by a different team. Therefore, any changes to the databases would take time.
|
|
27
|
-
2. Databases are usually accessed and modified by multiple different services. Therefore, making any change to the database is difficult.
|
|
28
|
-
3. Database security is designed for a handful of roles and users. Achieving security for thousands of users is difficult.
|
|
29
|
-
4. Row-based security can be achieved by predefined views, but if we have to have dynamic views or parameterized views, it is not possible in databases as of now.
|
|
30
|
-
5. LLMs require the table names and column names to be self-explanatory. To achieve the same in a database, you will have to clone the database and make modifications to it, but then making the data sync in these tables becomes a difficult task.
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
## LLM SQL Shield - Features
|
|
34
|
-
|
|
35
|
-
With SQL Shield, you can:
|
|
36
|
-
|
|
37
|
-
1. Limit the tables that you expose to LLM.
|
|
38
|
-
2. Rename the tables as per your wish by setting proper `pub_name`.
|
|
39
|
-
3. Limit the columns from each table.
|
|
40
|
-
4. Rename the columns to make them more meaningful by setting proper `pub_name`.
|
|
41
|
-
5. Limit the rows that can be accessed by providing `filters`.
|
|
42
|
-
6. The `filters` can have variables that you can fill in at the time of query generation and execution.
|
|
43
|
-
|
|
44
|
-
## Install
|
|
45
|
-
```
|
|
46
|
-
pip install sqlshield
|
|
47
|
-
pip install openai
|
|
48
|
-
pip install sqlalchemy
|
|
49
|
-
|
|
50
|
-
```
|
|
51
|
-
## Example - Tutorial
|
|
52
|
-
|
|
53
|
-
Here is an example
|
|
54
|
-
|
|
55
|
-
```
|
|
56
|
-
|
|
57
|
-
import sqlalchemy
|
|
58
|
-
from sqlalchemy import inspect
|
|
59
|
-
from sqlalchemy import text
|
|
60
|
-
|
|
61
|
-
from sqlshield.models import *
|
|
62
|
-
from sqlshield.shield import *
|
|
63
|
-
import os
|
|
64
|
-
|
|
65
|
-
# TODO: Specify correct OpenAI key
|
|
66
|
-
os.environ["OPENAI_API_KEY"] = 'sk-XXXXXXXXX'
|
|
67
|
-
|
|
68
|
-
# TODO: You can download this SQLite3 DB file: https://github.com/terno-ai/llm-sql-shield/raw/main/tests/chinook.db
|
|
69
|
-
# And save it in your current directory
|
|
70
|
-
# Connect to DB
|
|
71
|
-
engine = sqlalchemy.create_engine('sqlite:///chinook.db')
|
|
72
|
-
inspector = inspect(engine)
|
|
73
|
-
|
|
74
|
-
# Load default DB
|
|
75
|
-
mDb = MDatabase.from_inspector(inspector)
|
|
76
|
-
|
|
77
|
-
mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine']))
|
|
78
|
-
|
|
79
|
-
tables = mDb.get_table_dict()
|
|
80
|
-
customer_table = tables['Customer']
|
|
81
|
-
|
|
82
|
-
# Change Name of table
|
|
83
|
-
customer_table.pub_name = 'Customers'
|
|
84
|
-
|
|
85
|
-
# Add a filter
|
|
86
|
-
customer_table.filters = 'where company = {company}'
|
|
87
|
-
|
|
88
|
-
# Drop some colums
|
|
89
|
-
customer_table.drop_columns(set(['Address']))
|
|
90
|
-
|
|
91
|
-
# Column renaming
|
|
92
|
-
|
|
93
|
-
question = "Show me all customers."
|
|
94
|
-
|
|
95
|
-
from openai import OpenAI
|
|
96
|
-
client = OpenAI()
|
|
97
|
-
|
|
98
|
-
schema_generated = mDb.generate_schema()
|
|
99
|
-
print('The following schema was generated: ', schema_generated)
|
|
100
|
-
|
|
101
|
-
response = client.chat.completions.create(
|
|
102
|
-
model="gpt-3.5-turbo",
|
|
103
|
-
messages=[
|
|
104
|
-
{"role": "system", "content": "You are an SQL Analyst. Your role is to generate the SQL given a question. Only generate SQL nothing else."},
|
|
105
|
-
{"role": "user", "content": question},
|
|
106
|
-
{"role": "assistant", "content": "The tables schema is follows: " + schema_generated},
|
|
107
|
-
]
|
|
108
|
-
)
|
|
109
|
-
|
|
110
|
-
aSql = response.choices[0].message.content
|
|
111
|
-
print('SQL Generated by LLM: ', aSql)
|
|
112
|
-
|
|
113
|
-
d = {'company':'\'Telus\''}
|
|
114
|
-
sess = Session(mDb, d)
|
|
115
|
-
gSQL = sess.generateNativeSQL(aSql)
|
|
116
|
-
print("Native SQL: ", gSQL)
|
|
117
|
-
|
|
118
|
-
print(" ===================== ")
|
|
119
|
-
with engine.connect() as con:
|
|
120
|
-
rs = con.execute(text(gSQL))
|
|
121
|
-
for row in rs:
|
|
122
|
-
print(row)
|
|
123
|
-
|
|
124
|
-
```
|
|
125
|
-
|
sqlshield-0.0.2/README.md
DELETED
|
@@ -1,111 +0,0 @@
|
|
|
1
|
-
# LLM SQL Shield
|
|
2
|
-
A Shield for your database to neutralize the SQL queries generated by Large Language Model (LLM)
|
|
3
|
-
|
|
4
|
-
## Background
|
|
5
|
-
|
|
6
|
-
Large Language Models (LLM) have proven to be extraordinarily effective in generating SQL queries. This has revolutionized SQL generation using large language models.
|
|
7
|
-
|
|
8
|
-
However, there is a significant challenge: a threat to the database. The queries generated by LLMs can access data that they aren't supposed to. No matter how constrained the prompt is, it is always possible to jailbreak. Given the nature of LLMs, they can never be controlled deterministically.
|
|
9
|
-
|
|
10
|
-
Securing the database is difficult because:
|
|
11
|
-
|
|
12
|
-
1. Databases are usually controlled and managed by a different team. Therefore, any changes to the databases would take time.
|
|
13
|
-
2. Databases are usually accessed and modified by multiple different services. Therefore, making any change to the database is difficult.
|
|
14
|
-
3. Database security is designed for a handful of roles and users. Achieving security for thousands of users is difficult.
|
|
15
|
-
4. Row-based security can be achieved by predefined views, but if we have to have dynamic views or parameterized views, it is not possible in databases as of now.
|
|
16
|
-
5. LLMs require the table names and column names to be self-explanatory. To achieve the same in a database, you will have to clone the database and make modifications to it, but then making the data sync in these tables becomes a difficult task.
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
## LLM SQL Shield - Features
|
|
20
|
-
|
|
21
|
-
With SQL Shield, you can:
|
|
22
|
-
|
|
23
|
-
1. Limit the tables that you expose to LLM.
|
|
24
|
-
2. Rename the tables as per your wish by setting proper `pub_name`.
|
|
25
|
-
3. Limit the columns from each table.
|
|
26
|
-
4. Rename the columns to make them more meaningful by setting proper `pub_name`.
|
|
27
|
-
5. Limit the rows that can be accessed by providing `filters`.
|
|
28
|
-
6. The `filters` can have variables that you can fill in at the time of query generation and execution.
|
|
29
|
-
|
|
30
|
-
## Install
|
|
31
|
-
```
|
|
32
|
-
pip install sqlshield
|
|
33
|
-
pip install openai
|
|
34
|
-
pip install sqlalchemy
|
|
35
|
-
|
|
36
|
-
```
|
|
37
|
-
## Example - Tutorial
|
|
38
|
-
|
|
39
|
-
Here is an example
|
|
40
|
-
|
|
41
|
-
```
|
|
42
|
-
|
|
43
|
-
import sqlalchemy
|
|
44
|
-
from sqlalchemy import inspect
|
|
45
|
-
from sqlalchemy import text
|
|
46
|
-
|
|
47
|
-
from sqlshield.models import *
|
|
48
|
-
from sqlshield.shield import *
|
|
49
|
-
import os
|
|
50
|
-
|
|
51
|
-
# TODO: Specify correct OpenAI key
|
|
52
|
-
os.environ["OPENAI_API_KEY"] = 'sk-XXXXXXXXX'
|
|
53
|
-
|
|
54
|
-
# TODO: You can download this SQLite3 DB file: https://github.com/terno-ai/llm-sql-shield/raw/main/tests/chinook.db
|
|
55
|
-
# And save it in your current directory
|
|
56
|
-
# Connect to DB
|
|
57
|
-
engine = sqlalchemy.create_engine('sqlite:///chinook.db')
|
|
58
|
-
inspector = inspect(engine)
|
|
59
|
-
|
|
60
|
-
# Load default DB
|
|
61
|
-
mDb = MDatabase.from_inspector(inspector)
|
|
62
|
-
|
|
63
|
-
mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine']))
|
|
64
|
-
|
|
65
|
-
tables = mDb.get_table_dict()
|
|
66
|
-
customer_table = tables['Customer']
|
|
67
|
-
|
|
68
|
-
# Change Name of table
|
|
69
|
-
customer_table.pub_name = 'Customers'
|
|
70
|
-
|
|
71
|
-
# Add a filter
|
|
72
|
-
customer_table.filters = 'where company = {company}'
|
|
73
|
-
|
|
74
|
-
# Drop some colums
|
|
75
|
-
customer_table.drop_columns(set(['Address']))
|
|
76
|
-
|
|
77
|
-
# Column renaming
|
|
78
|
-
|
|
79
|
-
question = "Show me all customers."
|
|
80
|
-
|
|
81
|
-
from openai import OpenAI
|
|
82
|
-
client = OpenAI()
|
|
83
|
-
|
|
84
|
-
schema_generated = mDb.generate_schema()
|
|
85
|
-
print('The following schema was generated: ', schema_generated)
|
|
86
|
-
|
|
87
|
-
response = client.chat.completions.create(
|
|
88
|
-
model="gpt-3.5-turbo",
|
|
89
|
-
messages=[
|
|
90
|
-
{"role": "system", "content": "You are an SQL Analyst. Your role is to generate the SQL given a question. Only generate SQL nothing else."},
|
|
91
|
-
{"role": "user", "content": question},
|
|
92
|
-
{"role": "assistant", "content": "The tables schema is follows: " + schema_generated},
|
|
93
|
-
]
|
|
94
|
-
)
|
|
95
|
-
|
|
96
|
-
aSql = response.choices[0].message.content
|
|
97
|
-
print('SQL Generated by LLM: ', aSql)
|
|
98
|
-
|
|
99
|
-
d = {'company':'\'Telus\''}
|
|
100
|
-
sess = Session(mDb, d)
|
|
101
|
-
gSQL = sess.generateNativeSQL(aSql)
|
|
102
|
-
print("Native SQL: ", gSQL)
|
|
103
|
-
|
|
104
|
-
print(" ===================== ")
|
|
105
|
-
with engine.connect() as con:
|
|
106
|
-
rs = con.execute(text(gSQL))
|
|
107
|
-
for row in rs:
|
|
108
|
-
print(row)
|
|
109
|
-
|
|
110
|
-
```
|
|
111
|
-
|
|
@@ -1,125 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.1
|
|
2
|
-
Name: sqlshield
|
|
3
|
-
Version: 0.0.2
|
|
4
|
-
Summary: A Shield for your LLM generated SQL Queries. It provides an application level control for securing the database from SQL generated by LLM.
|
|
5
|
-
Author-email: Sandeep Giri <sandeepgiri@gmail.com>
|
|
6
|
-
Project-URL: Homepage, https://github.com/terno-ai/llm-sql-shield
|
|
7
|
-
Project-URL: Issues, https://github.com/terno-ai/llm-sql-shield/issues
|
|
8
|
-
Classifier: Programming Language :: Python :: 3
|
|
9
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
-
Classifier: Operating System :: OS Independent
|
|
11
|
-
Requires-Python: >=3.8
|
|
12
|
-
Description-Content-Type: text/markdown
|
|
13
|
-
License-File: LICENSE
|
|
14
|
-
|
|
15
|
-
# LLM SQL Shield
|
|
16
|
-
A Shield for your database to neutralize the SQL queries generated by Large Language Model (LLM)
|
|
17
|
-
|
|
18
|
-
## Background
|
|
19
|
-
|
|
20
|
-
Large Language Models (LLM) have proven to be extraordinarily effective in generating SQL queries. This has revolutionized SQL generation using large language models.
|
|
21
|
-
|
|
22
|
-
However, there is a significant challenge: a threat to the database. The queries generated by LLMs can access data that they aren't supposed to. No matter how constrained the prompt is, it is always possible to jailbreak. Given the nature of LLMs, they can never be controlled deterministically.
|
|
23
|
-
|
|
24
|
-
Securing the database is difficult because:
|
|
25
|
-
|
|
26
|
-
1. Databases are usually controlled and managed by a different team. Therefore, any changes to the databases would take time.
|
|
27
|
-
2. Databases are usually accessed and modified by multiple different services. Therefore, making any change to the database is difficult.
|
|
28
|
-
3. Database security is designed for a handful of roles and users. Achieving security for thousands of users is difficult.
|
|
29
|
-
4. Row-based security can be achieved by predefined views, but if we have to have dynamic views or parameterized views, it is not possible in databases as of now.
|
|
30
|
-
5. LLMs require the table names and column names to be self-explanatory. To achieve the same in a database, you will have to clone the database and make modifications to it, but then making the data sync in these tables becomes a difficult task.
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
## LLM SQL Shield - Features
|
|
34
|
-
|
|
35
|
-
With SQL Shield, you can:
|
|
36
|
-
|
|
37
|
-
1. Limit the tables that you expose to LLM.
|
|
38
|
-
2. Rename the tables as per your wish by setting proper `pub_name`.
|
|
39
|
-
3. Limit the columns from each table.
|
|
40
|
-
4. Rename the columns to make them more meaningful by setting proper `pub_name`.
|
|
41
|
-
5. Limit the rows that can be accessed by providing `filters`.
|
|
42
|
-
6. The `filters` can have variables that you can fill in at the time of query generation and execution.
|
|
43
|
-
|
|
44
|
-
## Install
|
|
45
|
-
```
|
|
46
|
-
pip install sqlshield
|
|
47
|
-
pip install openai
|
|
48
|
-
pip install sqlalchemy
|
|
49
|
-
|
|
50
|
-
```
|
|
51
|
-
## Example - Tutorial
|
|
52
|
-
|
|
53
|
-
Here is an example
|
|
54
|
-
|
|
55
|
-
```
|
|
56
|
-
|
|
57
|
-
import sqlalchemy
|
|
58
|
-
from sqlalchemy import inspect
|
|
59
|
-
from sqlalchemy import text
|
|
60
|
-
|
|
61
|
-
from sqlshield.models import *
|
|
62
|
-
from sqlshield.shield import *
|
|
63
|
-
import os
|
|
64
|
-
|
|
65
|
-
# TODO: Specify correct OpenAI key
|
|
66
|
-
os.environ["OPENAI_API_KEY"] = 'sk-XXXXXXXXX'
|
|
67
|
-
|
|
68
|
-
# TODO: You can download this SQLite3 DB file: https://github.com/terno-ai/llm-sql-shield/raw/main/tests/chinook.db
|
|
69
|
-
# And save it in your current directory
|
|
70
|
-
# Connect to DB
|
|
71
|
-
engine = sqlalchemy.create_engine('sqlite:///chinook.db')
|
|
72
|
-
inspector = inspect(engine)
|
|
73
|
-
|
|
74
|
-
# Load default DB
|
|
75
|
-
mDb = MDatabase.from_inspector(inspector)
|
|
76
|
-
|
|
77
|
-
mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine']))
|
|
78
|
-
|
|
79
|
-
tables = mDb.get_table_dict()
|
|
80
|
-
customer_table = tables['Customer']
|
|
81
|
-
|
|
82
|
-
# Change Name of table
|
|
83
|
-
customer_table.pub_name = 'Customers'
|
|
84
|
-
|
|
85
|
-
# Add a filter
|
|
86
|
-
customer_table.filters = 'where company = {company}'
|
|
87
|
-
|
|
88
|
-
# Drop some colums
|
|
89
|
-
customer_table.drop_columns(set(['Address']))
|
|
90
|
-
|
|
91
|
-
# Column renaming
|
|
92
|
-
|
|
93
|
-
question = "Show me all customers."
|
|
94
|
-
|
|
95
|
-
from openai import OpenAI
|
|
96
|
-
client = OpenAI()
|
|
97
|
-
|
|
98
|
-
schema_generated = mDb.generate_schema()
|
|
99
|
-
print('The following schema was generated: ', schema_generated)
|
|
100
|
-
|
|
101
|
-
response = client.chat.completions.create(
|
|
102
|
-
model="gpt-3.5-turbo",
|
|
103
|
-
messages=[
|
|
104
|
-
{"role": "system", "content": "You are an SQL Analyst. Your role is to generate the SQL given a question. Only generate SQL nothing else."},
|
|
105
|
-
{"role": "user", "content": question},
|
|
106
|
-
{"role": "assistant", "content": "The tables schema is follows: " + schema_generated},
|
|
107
|
-
]
|
|
108
|
-
)
|
|
109
|
-
|
|
110
|
-
aSql = response.choices[0].message.content
|
|
111
|
-
print('SQL Generated by LLM: ', aSql)
|
|
112
|
-
|
|
113
|
-
d = {'company':'\'Telus\''}
|
|
114
|
-
sess = Session(mDb, d)
|
|
115
|
-
gSQL = sess.generateNativeSQL(aSql)
|
|
116
|
-
print("Native SQL: ", gSQL)
|
|
117
|
-
|
|
118
|
-
print(" ===================== ")
|
|
119
|
-
with engine.connect() as con:
|
|
120
|
-
rs = con.execute(text(gSQL))
|
|
121
|
-
for row in rs:
|
|
122
|
-
print(row)
|
|
123
|
-
|
|
124
|
-
```
|
|
125
|
-
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|