Middleware: Record ownership screener

 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

  1. YUI Loader as Django middleware by akaihola 5 years, 12 months ago
  2. Template filter that divides a list into exact columns by davmuz 2 years, 2 months ago
  3. Python Calendar wrapper template tag by dokterbob 4 years, 11 months ago
  4. Link filter by sean2000 6 years, 4 months ago
  5. Yet another SQL debugging facility by miracle2k 6 years, 8 months ago

Comments

gerardjp (on October 26, 2009):

WARNING:

Found a query that was missed during use, a combined WHERE clause

WHERE (myapp_model1.owner_id = 2 AND myapp_model2.object_id = 5 )

Will update soon.

#

(Forgotten your password?)