import random
from django.http import HttpResponse

class SidebandCoverTrafficMiddleware(object):
    """
    HTTP traffic (even under SSL) can be observed for information leakage based on 
    response lengths; this is more important with AJAX providing many small requests.
    
    See http://www.freedom-to-tinker.com/blog/felten/side-channel-leaks-web-applications
    
    A mitigation is to add some padding to responses to obscure the original lengths.
    """
    SUPPORTED_MIMETYPES = (
        'text/*',
    )
    SUPPORTED_STATUSES = (
        200,
    )
    EXTRA_PADDING_MAX = 1024

    def should_process(self, response):
        if not response.status_code in self.SUPPORTED_STATUSES:
            return False
        ct = response['content-type']
        ct_prefix = ct.split('/')[0] + '/*'
        if not (ct_prefix in self.SUPPORTED_MIMETYPES or 
                ct in self.SUPPORTED_MIMETYPES):
            return False
        return True

    def process_response(self, request, response):
        if self.should_process(response):
            return HttpResponse(response.content + ' ' * random.randint(0, self.EXTRA_PADDING_MAX), 
                    content_type=ct,
                    status=response.status_code
                    )
