Revision 8ae38ff8 snf-common/synnefo/lib/middleware/cleanse.py

b/snf-common/synnefo/lib/middleware/cleanse.py
39 39

  
40 40
import re
41 41

  
42
HIDDEN_ALL = settings.HIDDEN_COOKIES + settings.HIDDEN_HEADERS
43

  
42 44

  
43 45
def mail_admins_safe(subject, message, fail_silently=False, connection=None):
44 46
    '''
45 47
    Wrapper function to cleanse email body from sensitive content before
46 48
    sending it
47 49
    '''
50
    new_msg = ""
51

  
52
    if len(message) > settings.MAIL_MAX_LEN:
53
        new_msg += "Mail size over limit (truncated)\n\n"
54
        message = message[:settings.MAIL_MAX_LEN]
55

  
56
    for line in message.splitlines():
57
        # Lines of interest in the mail are in the form of
58
        # key:value.
59
        try:
60
            (key, value) = line.split(':', 1)
61
        except ValueError:
62
            new_msg += line + '\n'
63
            continue
64

  
65
        new_msg += key + ':'
66

  
67
        # Special case when the first header / cookie printed
68
        # (prefixed by 'META:{' or 'COOKIES:{') needs to be hidden.
69
        if value.startswith('{'):
70
            try:
71
                (newkey, newval) = value.split(':', 1)
72
            except ValueError:
73
                new_msg += value + '\n'
74
                continue
48 75

  
49
    HIDDEN_ALL = settings.HIDDEN_SETTINGS + "|" + settings.HIDDEN_COOKIES
50
    message = re.sub("((\S+)?(%s)(\S+)?(:|\=)( )?)('|\"?)\S+('|\"?)"
51
                     % HIDDEN_ALL, r"\1*******", message)
76
            new_msg += newkey + ':'
77
            key = newkey.lstrip('{')
78
            value = newval
52 79

  
53
    return mail.mail_admins_plain(subject, message, fail_silently, connection)
80
        if key.strip(" '") not in HIDDEN_ALL:
81
            new_msg += value + '\n'
82
            continue
83

  
84
        # Append value[-1] to the clensed string, so that commas / closing
85
        # brackets are printed correctly.
86
        # (it will 'eat up' the closing bracket if the header is the last one
87
        # printed)
88
        new_msg += ' ' + '*'*8 + value[-1] + '\n'
89

  
90
    return mail.mail_admins_plain(subject, new_msg, fail_silently, connection)
54 91

  
55 92

  
56 93
class CleanseSettingsMiddleware(object):
94
    '''
95
    Prevent django from printing sensitive information (paswords, tokens
96
    etc), when handling server errors (for both DEBUG and no-DEBUG
97
    deployments.
98
    '''
57 99
    def __init__(self):
58
        '''
59
        Prevent django from printing sensitive information (paswords, tokens
60
        etc), when handling server errors (for both DEBUG and no-DEBUG
61
        deployments.
62
        '''
63 100
        debug.HIDDEN_SETTINGS = re.compile(settings.HIDDEN_SETTINGS)
64 101

  
65 102
        if not hasattr(mail, 'mail_admins_plain'):

Also available in: Unified diff