sqlshield 0.0.1__tar.gz → 0.0.3__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.

@@ -0,0 +1,232 @@
1
+ Metadata-Version: 2.1
2
+ Name: sqlshield
3
+ Version: 0.0.3
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
+
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sqlshield"
3
- version = "0.0.1"
3
+ version = "0.0.3"
4
4
  authors = [
5
5
  { name="Sandeep Giri", email="sandeepgiri@gmail.com" },
6
6
  ]
@@ -3,60 +3,70 @@ 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['primary_key']
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 == None:
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 == None:
50
+ if pub_name is None:
43
51
  pub_name = self.name
44
52
  self.pub_name = pub_name
45
- self.filters = filters # template/Format string containing {var1}
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
-
60
+
52
61
  def get_alias_sql(self, params):
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
- query = sql_template % (colsql, self.name, filterSQL, self.pub_name)
67
+ query = sql_template % (colsql, self.name, filterSQL, self.pub_name)
59
68
  return query
69
+
60
70
  def generate_schema(self):
61
71
  cols_info_arr = []
62
72
  for col in self.columns:
@@ -64,6 +74,7 @@ class MTable(Table):
64
74
  col_info = ',\n\t'.join(cols_info_arr)
65
75
  sql_template = 'CREATE TABLE [%s](\n\t%s\n\t);' % (self.pub_name, col_info)
66
76
  return sql_template
77
+
67
78
  def drop_columns(self, col_names_set):
68
79
  to_drop = set()
69
80
  for col in self.columns:
@@ -71,20 +82,22 @@ class MTable(Table):
71
82
  to_drop.add(col)
72
83
  self.columns = self.columns.difference(to_drop)
73
84
 
85
+
74
86
  class MDatabase():
75
87
  def __init__(self):
76
88
  self.tables = set()
77
- self.allowed_commands = ['show databases']
78
- self.allowed_all_tables = []
89
+ # self.allowed_commands = ['show databases']
90
+ # self.allowed_all_tables = []
91
+
79
92
  def generate_schema(self):
80
93
  schema_arr = []
81
94
  for table in self.tables:
82
95
  schema_arr.append(table.generate_schema())
83
96
  return '\n'.join(schema_arr)
97
+
84
98
  def from_inspector(inspector):
85
99
  mdb = MDatabase()
86
100
  schemas = inspector.get_schema_names()
87
- result = {}
88
101
  for schema in schemas[:1]:
89
102
  for table_name in inspector.get_table_names(schema=schema):
90
103
  mtable = MTable(table_name)
@@ -93,11 +106,13 @@ class MDatabase():
93
106
  mc = MColumn(**col)
94
107
  mtable.columns.add(mc)
95
108
  return mdb
109
+
96
110
  def get_table_dict(self):
97
111
  d = {}
98
112
  for tbl in self.tables:
99
113
  d[tbl.name] = tbl
100
114
  return d
115
+
101
116
  def keep_only_tables(self, keep_tbls):
102
117
  new_tables = set()
103
118
  for tbl in self.tables:
@@ -0,0 +1,41 @@
1
+ from sqlglot import parse_one, exp
2
+
3
+
4
+ class Session():
5
+ def __init__(self, db, params):
6
+ self.database = db
7
+ self.params = params
8
+
9
+ def is_type(tree, _type):
10
+ if len(list(tree.find_all(_type))) > 0:
11
+ return True
12
+ return False
13
+
14
+ def generateNativeSQL(self, aSql):
15
+ tree = parse_one(aSql)
16
+ if type(tree) != exp.Select:
17
+ raise Exception('As of now, only select statements are supported.', aSql)
18
+ blocked = [exp.DML, exp.DDL, exp.Command, exp.Commit, exp.Drop, exp.TruncateTable]
19
+ for _type in blocked:
20
+ if Session.is_type(tree, _type):
21
+ raise Exception('The SQL contains either DML or DDL', aSql)
22
+ # prepare_table_map
23
+ tbl_map = {}
24
+ for tbl in self.database.tables:
25
+ tbl_map[tbl.pub_name.lower()] = tbl
26
+
27
+ print("Input: ", aSql)
28
+
29
+ def transformer(node):
30
+ if isinstance(node, exp.Table):
31
+ tbl_name_c = node.this.this
32
+ tbl_name = tbl_name_c.lower()
33
+ if tbl_name not in tbl_map:
34
+ raise Exception('No such table found.', tbl_name_c)
35
+ mtable = tbl_map[tbl_name]
36
+ msql = mtable.get_alias_sql(self.params)
37
+ return parse_one(msql)
38
+ return node
39
+
40
+ new_tree = tree.transform(transformer)
41
+ return new_tree.sql()
@@ -0,0 +1,232 @@
1
+ Metadata-Version: 2.1
2
+ Name: sqlshield
3
+ Version: 0.0.3
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
+
@@ -7,4 +7,5 @@ src/sqlshield/shield.py
7
7
  src/sqlshield.egg-info/PKG-INFO
8
8
  src/sqlshield.egg-info/SOURCES.txt
9
9
  src/sqlshield.egg-info/dependency_links.txt
10
- src/sqlshield.egg-info/top_level.txt
10
+ src/sqlshield.egg-info/top_level.txt
11
+ tests/test_malicious_sql.py
@@ -0,0 +1,59 @@
1
+
2
+ # export PYTHONPATH=../src/
3
+ # python insert_test.py
4
+
5
+ import sqlalchemy
6
+ from sqlalchemy import inspect
7
+ from sqlalchemy import text
8
+
9
+ from sqlshield.models import *
10
+ from sqlshield.shield import *
11
+
12
+ def loadDb():
13
+ engine = sqlalchemy.create_engine('sqlite:///chinook.db')
14
+ inspector = inspect(engine)
15
+
16
+ # Load default DB
17
+ return MDatabase.from_inspector(inspector)
18
+
19
+ def build_protection(mDb):
20
+ mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine']))
21
+
22
+ tables = mDb.get_table_dict()
23
+ print("Tables: ", tables)
24
+ customer_table = tables['Customer']
25
+
26
+ # Change Name of table
27
+ customer_table.pub_name = 'Customers'
28
+
29
+ # Add a filter
30
+ customer_table.filters = 'where company = {company}'
31
+
32
+ # Drop some colums
33
+ customer_table.drop_columns(set(['Address']))
34
+
35
+ if __name__ == "__main__":
36
+ mDb = loadDb()
37
+ build_protection(mDb)
38
+ # Column renaming
39
+ d = {'company':'\'Telus\''}
40
+ sess = Session(mDb, d)
41
+ sqls = [
42
+ 'drop table t1;'
43
+ 'insert into Customers Values(1,2)',
44
+ 'create table t (age int)',
45
+ "GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost'; ",
46
+ # "REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;",
47
+ "COMMIT;",
48
+ 'select * from Employee;drop table Employee;',
49
+ 'select * from cusTomers',
50
+ 'select * from cusTomer',
51
+ ]
52
+ for sql in sqls:
53
+ try:
54
+ gSQL = sess.generateNativeSQL(sql)
55
+ # GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost';
56
+ print("Native SQL: ", gSQL)
57
+ except Exception as e:
58
+ print("ERROR: ", e.args)
59
+
sqlshield-0.0.1/PKG-INFO DELETED
@@ -1,123 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: sqlshield
3
- Version: 0.0.1
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
- `llm-sql-shield` is A Shield for your LLM generated SQL Queries.
18
-
19
- # Background
20
- Large Language Models (LLM) prove to be extraordinally good when it comes to SQL query generation. This has lead to a revolution in generating SQL using large language models.
21
-
22
- But there is a huge challenge, there is threat to database. The queries generted by LLMs can access the data that they aren't supposed to. No matter how you constraint the prompt is, it is always possible to jailbreak. Given the nature of LLMs, I don't think they can ever be controlled deterministically.
23
-
24
- We can secure our database but it is too dificult to achieve it:
25
-
26
- 1. Databases are usually controlled and management 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 database is dificult.
28
- 3. Database security is designed for handful of roles and users. Achieving the security for thousand of users is dificult.
29
- 4. Row based security can be achieved by predefined views but if we have to have dynamic view or parameterised views, it is not possible in databases as of now.
30
- 5. LLMs require the table names and column names to be self explainatory. To achieve the same, in database, you will have to clone the database and make modifications to it but then making the data sync in these tables becomes dificult task.
31
-
32
- # LLM SQL Shield - Features
33
- With SQL Shield, you can:
34
-
35
- 1. Limit the tables that you expose to LLM.
36
- 2. You can also rename the tables as per your wish by setting proper `pub_name`
37
- 3. You can limit the columns from each table.
38
- 4. You can rename the columns to make them more meaningful by setting proper `pub_name`
39
- 5. You can limit the rows that can be accessed by providing `filters`.
40
- 6. The `filters` can have variables that you can fill in at the time of query generation and execution.
41
-
42
- # Install
43
- ```
44
- pip install sqlshield
45
- pip install openai
46
- pip install sqlalchemy
47
-
48
- ```
49
- # Example
50
-
51
- Here is an example
52
-
53
- ```
54
-
55
- import sqlalchemy
56
- from sqlalchemy import inspect
57
- from sqlalchemy import text
58
-
59
- from sqlshield.models import *
60
- from sqlshield.shield import *
61
- import os
62
-
63
- # TODO: Specify correct OpenAI key
64
- os.environ["OPENAI_API_KEY"] = 'sk-XXXXXXXXX'
65
-
66
- # TODO: You can download this SQLite3 DB file: https://github.com/terno-ai/llm-sql-shield/raw/main/doc/db/chinook.db
67
- # And save it in your current directory
68
- # Connect to DB
69
- engine = sqlalchemy.create_engine('sqlite:///chinook.db')
70
- inspector = inspect(engine)
71
-
72
- # Load default DB
73
- mDb = MDatabase.from_inspector(inspector)
74
-
75
- mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine']))
76
-
77
- tables = mDb.get_table_dict()
78
- customer_table = tables['Customer']
79
-
80
- # Change Name of table
81
- customer_table.pub_name = 'Customers'
82
-
83
- # Add a filter
84
- customer_table.filters = 'where company = {company}'
85
-
86
- # Drop some colums
87
- customer_table.drop_columns(set(['Address']))
88
-
89
- # Column renaming
90
-
91
- question = "Show me all customers."
92
-
93
- from openai import OpenAI
94
- client = OpenAI()
95
-
96
- schema_generated = mDb.generate_schema()
97
- print('The following schema was generated: ', schema_generated)
98
-
99
- response = client.chat.completions.create(
100
- model="gpt-3.5-turbo",
101
- messages=[
102
- {"role": "system", "content": "You are an SQL Analyst. Your role is to generate the SQL given a question. Only generate SQL nothing else."},
103
- {"role": "user", "content": question},
104
- {"role": "assistant", "content": "The tables schema is follows: " + schema_generated},
105
- ]
106
- )
107
-
108
- aSql = response.choices[0].message.content
109
- print('SQL Generated by LLM: ', aSql)
110
-
111
- d = {'company':'\'Telus\''}
112
- sess = Session(mDb, d)
113
- gSQL = sess.generateNativeSQL(aSql)
114
- print("Native SQL: ", gSQL)
115
-
116
- print(" ===================== ")
117
- with engine.connect() as con:
118
- rs = con.execute(text(gSQL))
119
- for row in rs:
120
- print(row)
121
-
122
- ```
123
-
sqlshield-0.0.1/README.md DELETED
@@ -1,109 +0,0 @@
1
- # LLM SQL Shield
2
-
3
- `llm-sql-shield` is A Shield for your LLM generated SQL Queries.
4
-
5
- # Background
6
- Large Language Models (LLM) prove to be extraordinally good when it comes to SQL query generation. This has lead to a revolution in generating SQL using large language models.
7
-
8
- But there is a huge challenge, there is threat to database. The queries generted by LLMs can access the data that they aren't supposed to. No matter how you constraint the prompt is, it is always possible to jailbreak. Given the nature of LLMs, I don't think they can ever be controlled deterministically.
9
-
10
- We can secure our database but it is too dificult to achieve it:
11
-
12
- 1. Databases are usually controlled and management 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 database is dificult.
14
- 3. Database security is designed for handful of roles and users. Achieving the security for thousand of users is dificult.
15
- 4. Row based security can be achieved by predefined views but if we have to have dynamic view or parameterised views, it is not possible in databases as of now.
16
- 5. LLMs require the table names and column names to be self explainatory. To achieve the same, in database, you will have to clone the database and make modifications to it but then making the data sync in these tables becomes dificult task.
17
-
18
- # LLM SQL Shield - Features
19
- With SQL Shield, you can:
20
-
21
- 1. Limit the tables that you expose to LLM.
22
- 2. You can also rename the tables as per your wish by setting proper `pub_name`
23
- 3. You can limit the columns from each table.
24
- 4. You can rename the columns to make them more meaningful by setting proper `pub_name`
25
- 5. You can limit the rows that can be accessed by providing `filters`.
26
- 6. The `filters` can have variables that you can fill in at the time of query generation and execution.
27
-
28
- # Install
29
- ```
30
- pip install sqlshield
31
- pip install openai
32
- pip install sqlalchemy
33
-
34
- ```
35
- # Example
36
-
37
- Here is an example
38
-
39
- ```
40
-
41
- import sqlalchemy
42
- from sqlalchemy import inspect
43
- from sqlalchemy import text
44
-
45
- from sqlshield.models import *
46
- from sqlshield.shield import *
47
- import os
48
-
49
- # TODO: Specify correct OpenAI key
50
- os.environ["OPENAI_API_KEY"] = 'sk-XXXXXXXXX'
51
-
52
- # TODO: You can download this SQLite3 DB file: https://github.com/terno-ai/llm-sql-shield/raw/main/doc/db/chinook.db
53
- # And save it in your current directory
54
- # Connect to DB
55
- engine = sqlalchemy.create_engine('sqlite:///chinook.db')
56
- inspector = inspect(engine)
57
-
58
- # Load default DB
59
- mDb = MDatabase.from_inspector(inspector)
60
-
61
- mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine']))
62
-
63
- tables = mDb.get_table_dict()
64
- customer_table = tables['Customer']
65
-
66
- # Change Name of table
67
- customer_table.pub_name = 'Customers'
68
-
69
- # Add a filter
70
- customer_table.filters = 'where company = {company}'
71
-
72
- # Drop some colums
73
- customer_table.drop_columns(set(['Address']))
74
-
75
- # Column renaming
76
-
77
- question = "Show me all customers."
78
-
79
- from openai import OpenAI
80
- client = OpenAI()
81
-
82
- schema_generated = mDb.generate_schema()
83
- print('The following schema was generated: ', schema_generated)
84
-
85
- response = client.chat.completions.create(
86
- model="gpt-3.5-turbo",
87
- messages=[
88
- {"role": "system", "content": "You are an SQL Analyst. Your role is to generate the SQL given a question. Only generate SQL nothing else."},
89
- {"role": "user", "content": question},
90
- {"role": "assistant", "content": "The tables schema is follows: " + schema_generated},
91
- ]
92
- )
93
-
94
- aSql = response.choices[0].message.content
95
- print('SQL Generated by LLM: ', aSql)
96
-
97
- d = {'company':'\'Telus\''}
98
- sess = Session(mDb, d)
99
- gSQL = sess.generateNativeSQL(aSql)
100
- print("Native SQL: ", gSQL)
101
-
102
- print(" ===================== ")
103
- with engine.connect() as con:
104
- rs = con.execute(text(gSQL))
105
- for row in rs:
106
- print(row)
107
-
108
- ```
109
-
@@ -1,26 +0,0 @@
1
- from sqlglot import parse_one, exp
2
- from pprint import pprint
3
-
4
- class Session():
5
- def __init__(self, db, params):
6
- self.database = db
7
- self.params = params
8
-
9
- def generateNativeSQL(self, aSql):
10
- # prepare_table_map
11
- tbl_map = {}
12
- for tbl in self.database.tables:
13
- tbl_map[tbl.pub_name] = tbl
14
-
15
- print("Input: ", aSql)
16
- def transformer(node):
17
- if isinstance(node, exp.Table):
18
- tbl_name = node.this.this
19
- mtable = tbl_map[tbl_name]
20
- msql = mtable.get_alias_sql(self.params)
21
- return parse_one(msql)
22
- return node
23
- tree = parse_one(aSql)
24
- new_tree = tree.transform(transformer)
25
- return new_tree.sql()
26
-
@@ -1,123 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: sqlshield
3
- Version: 0.0.1
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
- `llm-sql-shield` is A Shield for your LLM generated SQL Queries.
18
-
19
- # Background
20
- Large Language Models (LLM) prove to be extraordinally good when it comes to SQL query generation. This has lead to a revolution in generating SQL using large language models.
21
-
22
- But there is a huge challenge, there is threat to database. The queries generted by LLMs can access the data that they aren't supposed to. No matter how you constraint the prompt is, it is always possible to jailbreak. Given the nature of LLMs, I don't think they can ever be controlled deterministically.
23
-
24
- We can secure our database but it is too dificult to achieve it:
25
-
26
- 1. Databases are usually controlled and management 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 database is dificult.
28
- 3. Database security is designed for handful of roles and users. Achieving the security for thousand of users is dificult.
29
- 4. Row based security can be achieved by predefined views but if we have to have dynamic view or parameterised views, it is not possible in databases as of now.
30
- 5. LLMs require the table names and column names to be self explainatory. To achieve the same, in database, you will have to clone the database and make modifications to it but then making the data sync in these tables becomes dificult task.
31
-
32
- # LLM SQL Shield - Features
33
- With SQL Shield, you can:
34
-
35
- 1. Limit the tables that you expose to LLM.
36
- 2. You can also rename the tables as per your wish by setting proper `pub_name`
37
- 3. You can limit the columns from each table.
38
- 4. You can rename the columns to make them more meaningful by setting proper `pub_name`
39
- 5. You can limit the rows that can be accessed by providing `filters`.
40
- 6. The `filters` can have variables that you can fill in at the time of query generation and execution.
41
-
42
- # Install
43
- ```
44
- pip install sqlshield
45
- pip install openai
46
- pip install sqlalchemy
47
-
48
- ```
49
- # Example
50
-
51
- Here is an example
52
-
53
- ```
54
-
55
- import sqlalchemy
56
- from sqlalchemy import inspect
57
- from sqlalchemy import text
58
-
59
- from sqlshield.models import *
60
- from sqlshield.shield import *
61
- import os
62
-
63
- # TODO: Specify correct OpenAI key
64
- os.environ["OPENAI_API_KEY"] = 'sk-XXXXXXXXX'
65
-
66
- # TODO: You can download this SQLite3 DB file: https://github.com/terno-ai/llm-sql-shield/raw/main/doc/db/chinook.db
67
- # And save it in your current directory
68
- # Connect to DB
69
- engine = sqlalchemy.create_engine('sqlite:///chinook.db')
70
- inspector = inspect(engine)
71
-
72
- # Load default DB
73
- mDb = MDatabase.from_inspector(inspector)
74
-
75
- mDb.keep_only_tables(set(['Customer', 'Employee', 'Invoice', 'InvoiceLine']))
76
-
77
- tables = mDb.get_table_dict()
78
- customer_table = tables['Customer']
79
-
80
- # Change Name of table
81
- customer_table.pub_name = 'Customers'
82
-
83
- # Add a filter
84
- customer_table.filters = 'where company = {company}'
85
-
86
- # Drop some colums
87
- customer_table.drop_columns(set(['Address']))
88
-
89
- # Column renaming
90
-
91
- question = "Show me all customers."
92
-
93
- from openai import OpenAI
94
- client = OpenAI()
95
-
96
- schema_generated = mDb.generate_schema()
97
- print('The following schema was generated: ', schema_generated)
98
-
99
- response = client.chat.completions.create(
100
- model="gpt-3.5-turbo",
101
- messages=[
102
- {"role": "system", "content": "You are an SQL Analyst. Your role is to generate the SQL given a question. Only generate SQL nothing else."},
103
- {"role": "user", "content": question},
104
- {"role": "assistant", "content": "The tables schema is follows: " + schema_generated},
105
- ]
106
- )
107
-
108
- aSql = response.choices[0].message.content
109
- print('SQL Generated by LLM: ', aSql)
110
-
111
- d = {'company':'\'Telus\''}
112
- sess = Session(mDb, d)
113
- gSQL = sess.generateNativeSQL(aSql)
114
- print("Native SQL: ", gSQL)
115
-
116
- print(" ===================== ")
117
- with engine.connect() as con:
118
- rs = con.execute(text(gSQL))
119
- for row in rs:
120
- print(row)
121
-
122
- ```
123
-
File without changes
File without changes