UPDATE: 'ORDER BY' in de regex is now optional
If enabled while coding just keep track of your console output for:
<<< WARNING >>> Query execution without ownership clause, called from "process_response"
Happy coding
Regards,
Gerard.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | 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']
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
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.
#
Please login first before commenting.