from django.db import connection
import re
"""
QueryScreener is a middleware development tool. This tool helps to avoid
unwanted data disclosure once you go into production.
It monitors queries to the models in your model_list and warns you when queries
are executed that do not contain a ownership where clause. And thus can be a
potential data disclosure hazard.
It requires a owner attribute in your model definition, e.g:
owner = models.ForeignKey(User, editable=False)
Edit the 'model_list' below for what models should be monitored. And add
QueryScreener to MIDDLEWARE_CLASSES in you settings.py
Note: This can/should only be used while running Django's testserver command
with e.g: ./manage.py runserver 192.168.1.81:8000
"""
class QueryScreener(object):
model_list = ['myapp_mymodel1', 'myapp_mymodel2', 'myapp_mymodel3']
def process_view(self, request, view_func, view_args, view_kwargs):
if len(connection.queries) > 0:
query_parse(connection.queries, self.model_list, 'process_view')
def process_response(self, request, response):
if len(connection.queries) > 0:
query_parse(connection.queries, self.model_list, 'process_response')
return response
def query_parse(self, model_list, caller_process):
for query in connection.queries:
for modelname in model_list:
modelstring = 'FROM `'+modelname
if re.search(modelstring, query['sql']):
reg = re.compile(r'^SELECT.*WHERE.*owner.*(ORDER BY.*)?$',
re.DOTALL)
if not reg.search(query['sql']):
print ('<<< WARNING >>> Query execution without ownership '
'clause, called from "' + caller_process + '"')
print query['sql']
Comments
WARNING:
Found a query that was missed during use, a combined WHERE clause
WHERE (
myapp_model1.owner_id= 2 ANDmyapp_model2.object_id= 5 )Will update soon.
#