Changeset 5556


Ignore:
Timestamp:
04/08/09 15:53:11 (10 years ago)
Author:
pjkersha
Message:

Refactored test_multihandler. This module is bare bones demonstration of the AuthKit? Multihandler applied to intercept HTTP 401 and 403 responses. This is the basis of the NDG Security middleware.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • TI12-security/trunk/python/Tests/wsgiStack/test_multihandler.py

    r5275 r5556  
     1"""Test module to illustrate the AuthKit Multihandler based security  
     2middleware upon which NDG Security is based 
     3  
     4NERC DataGrid Project 
     5""" 
     6__author__ = "P J Kershaw" 
     7__date__ = "04/08/09" 
     8__copyright__ = "(C) 2009 Science and Technology Facilities Council" 
     9__license__ = "BSD - see LICENSE file in top-level directory" 
     10__contact__ = "Philip.Kershaw@stfc.ac.uk" 
     11__revision__ = "$Id$" 
     12 
    113import logging 
    214logging.basicConfig(level=logging.DEBUG) 
    315log = logging.getLogger(__name__) 
    416 
    5 class App3(object): 
    6     def __init__(self, app, app_conf, **local_conf): 
    7         self.app = app 
     17from authkit.authenticate.multi import MultiHandler 
     18 
     19def myApp(environ, start_response): 
     20    """Test application to be secured""" 
     21     
     22    if environ['PATH_INFO'] == "/test_401": 
     23        status = "401 Unauthorized" 
     24        response = status 
    825         
    9     def __call__(self, environ, start_response): 
    10         log.info("App3 ...") 
    11         def app3_start_response(status, header, exc_info=None): 
    12             log.info("app3_start_response...") 
    13             return start_response(status, header, exc_info=exc_info) 
     26    elif environ['PATH_INFO'] == "/test_403": 
     27        status = "403 Forbidden" 
     28        response = status 
    1429         
    15         return self.app(environ, app3_start_response) 
     30    elif environ['PATH_INFO'] == "/secured": 
     31        status = "200 OK" 
     32        response = "Secured URI" 
     33         
     34    else: 
     35        status = "404 Not Found" 
     36        response = status 
     37         
     38    log.info("Application is setting [%s] response..." % status) 
     39    start_response(status, 
     40                   [('Content-type', 'text/plain'), 
     41                    ('Content-length', str(len(response)))]) 
     42         
     43    return [response] 
     44 
     45 
     46class AuthenticationHandlerMiddleware(object): 
     47    """Handler for HTTP 401 Unauthorized responses""" 
     48 
     49    triggerStatus = "401 Unauthorized" 
    1650     
    17 class App2(object): 
    18     def __init__(self, app, app_conf, **local_conf): 
    19         self.app = app 
    20          
    21     def __call__(self, environ, start_response): 
    22         log.info("App2 ...") 
    23         def app2_start_response(status, header, exc_info=None): 
    24             log.info("app2_start_response...") 
    25             return start_response(status, header, exc_info=exc_info) 
    26          
    27         return self.app(environ, app2_start_response) 
    28      
    29 class App2a(object): 
    30     def __init__(self, app, app_conf, **local_conf): 
    31         app = MultiHandler(app) 
    32         app.add_method("checkerID", InterceptMiddleware) 
    33         app.add_checker("checkerID", checker) 
    34         self.app = app 
    35          
    36     def __call__(self, environ, start_response): 
    37         log.info("App2a ...") 
    38         def app2a_start_response(status, header, exc_info=None): 
    39             log.info("app2a_start_response...") 
    40             return start_response(status, header, exc_info=exc_info) 
    41          
    42         if not environ.get('QUERY_STRING'): 
    43             intercept = InterceptMiddleware(None) 
    44             return intercept(environ, app2a_start_response) 
    45          
    46         return self.app(environ, app2a_start_response) 
    47     
    48 def app1(environ, start_response): 
    49     log.info("app1 ...") 
    50     if environ.get('QUERY_STRING'): 
    51         start_response('200 OK', [('Content-type', 'text/html')]) 
    52         return 'Hello' 
    53     else: 
    54         start_response('403 Forbidden', [('Content-type', 'text/html')]) 
    55         return 'Keep out!' 
    56  
    57 def app_factory(app_conf, **local_conf): 
    58     return app1 
    59  
    60 from authkit.authenticate.multi import MultiHandler 
    61 triggerStatus = "403" 
    62  
    63 class InterceptMiddleware(object): 
    6451    def __init__(self, global_conf, **app_conf): 
    6552        pass 
    6653     
    6754    def __call__(self, environ, start_response): 
    68         log.info("InterceptMiddleware ...") 
    69         resp = "Call intercepted!" 
    70         start_response('200 OK', [('Content-type', 'text/html')]) 
    71         return resp 
     55        log.info("AuthenticationHandlerMiddleware access denied response ...") 
     56        response = "HTTP 401 Unauthorised response intercepted" 
     57        start_response('200 OK', [('Content-type', 'text/plain'), 
     58                                  ('Content-length', str(len(response)))]) 
     59        return [response] 
     60        
     61    @classmethod 
     62    def trigger(cls, environ, status, headers): 
     63        if status == cls.triggerStatus: 
     64            log.info("Authentication Trigger caught status [%s]",  
     65                     cls.triggerStatus) 
     66            return True 
     67        else: 
     68            return False 
    7269 
    73 def checker(environ, status, headers): 
    74     log.info("checker received status %r, " 
    75               "headers %r", status, headers) 
     70 
     71class AuthorisationHandlerMiddleware(object): 
     72    """Handler for HTTP 403 Forbidden responses""" 
    7673     
    77     if status.startswith(triggerStatus): 
    78         log.info("checker caught status %s", triggerStatus) 
    79         return True 
    80     else: 
    81         log.info("checker skipping status [%s]", status) 
    82         return False 
     74    triggerStatus = "403 Forbidden" 
     75     
     76    def __init__(self, global_conf, **app_conf): 
     77        pass 
     78     
     79    def __call__(self, environ, start_response): 
     80        log.info("AuthorisationHandlerMiddleware access denied response ...") 
     81        response = "HTTP 403 Forbidden response intercepted" 
     82        start_response('200 OK', [('Content-type', 'text/plain'), 
     83                                  ('Content-length', str(len(response)))]) 
     84        return [response] 
     85        
     86    @classmethod 
     87    def trigger(cls, environ, status, headers): 
     88        if status == cls.triggerStatus: 
     89            log.info("Authorisation Trigger caught status [%s]",  
     90                     cls.triggerStatus) 
     91            return True 
     92        else: 
     93            return False 
    8394 
    84 if __name__ == '__main__': 
    85     import sys 
    86     if len(sys.argv) > 1: 
    87         port = int(sys.argv[1]) 
    88     else: 
    89         port = 5000 
     95 
     96class AuthorisationPolicyMiddleware(object): 
     97    """Apply a security policy based on the URI requested""" 
     98     
     99    def __init__(self, app): 
     100        self.securedURIs = ['/test_secured'] 
     101        self.app = app 
     102     
     103    def __call__(self, environ, start_response): 
     104        if environ['PATH_INFO'] in self.securedURIs: 
     105            log.info("Path [%s] is restricted by the Authorisation policy" % 
     106                     environ['PATH_INFO']) 
     107            status = "403 Forbidden" 
     108            response = status 
     109            start_response(status, [('Content-type', 'text/plain'), 
     110                                    ('Content-length', str(len(response)))]) 
     111            return [response] 
     112        else: 
     113            return self.app(environ, start_response) 
    90114         
     115         
     116if __name__ == "__main__": 
     117    app = AuthorisationPolicyMiddleware(myApp) 
     118     
     119    app = MultiHandler(app)     
     120    app.add_method("checkerID", AuthenticationHandlerMiddleware) 
     121    app.add_checker("checkerID", AuthenticationHandlerMiddleware.trigger) 
     122 
     123    app = MultiHandler(app) 
     124    app.add_method("checkerID", AuthorisationHandlerMiddleware) 
     125    app.add_checker("checkerID", AuthorisationHandlerMiddleware.trigger) 
     126 
    91127    from paste.httpserver import serve 
    92128    from paste.deploy import loadapp 
     129 
     130    serve(app, host='0.0.0.0', port=9080) 
    93131     
    94  
    95     app3 = App3(App2(app1)) 
    96      
    97     app = MultiHandler(app3) 
    98     app.add_method("checkerID", InterceptMiddleware) 
    99     app.add_checker("checkerID", checker) 
    100  
    101     serve(app, host='0.0.0.0', port=port) 
Note: See TracChangeset for help on using the changeset viewer.