source: TI12-security/trunk/python/ndg.security.test/ndg/security/test/unit/wsgi/authz/test_authz.py @ 5329

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.test/ndg/security/test/unit/wsgi/authz/test_authz.py@5329
Revision 5329, 5.8 KB checked in by pjkersha, 11 years ago (diff)
  • Added AuthorizationMiddleware? unit tests: ndg.security.test.unit.wsgi.authz
  • Added check for ndg.security.server.wsgi.authz.PEPFilter to catch beaker session not set in a custom PEPFilter exception type
Line 
1#!/usr/bin/env python
2"""Unit tests for WSGI Authorization handler
3
4NERC DataGrid Project
5"""
6__author__ = "P J Kershaw"
7__date__ = "21/05/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$'
12import logging
13
14
15import unittest
16import os
17import sys
18import getpass
19import re
20import base64
21import urllib2
22
23from os.path import expandvars as xpdVars
24from os.path import join as jnPath
25mkPath = lambda file: jnPath(os.environ['NDGSEC_COMBINED_SRVS_UNITTEST_DIR'], 
26                             file)
27
28import paste.fixture
29from paste.deploy import loadapp
30from ndg.security.server.wsgi.authz import PEPFilterConfigError
31
32class TestAuthZMiddleware(object):
33    '''Test Application for the Authentication handler to protect'''
34    response = "Test Authorization application"
35       
36    def __init__(self, app_conf, **local_conf):
37        pass
38   
39    def __call__(self, environ, start_response):
40       
41        if environ['PATH_INFO'] == '/test_401':
42            status = "401 Unauthorized"
43           
44        elif environ['PATH_INFO'] == '/test_403':
45            status = "403 Forbidden"
46           
47        elif environ['PATH_INFO'] == '/test_200':
48            status = "200 OK"
49           
50        elif environ['PATH_INFO'] == '/test_accessDeniedToSecuredURI':
51            # Nb. AuthZ middleware should intercept the request and bypass this
52            # response
53            status = "200 OK"
54           
55        elif environ['PATH_INFO'] == '/test_accessGrantedToSecuredURI':
56            status = "200 OK"
57        else:
58            status = "404 Not found"
59               
60        start_response(status,
61                       [('Content-length', 
62                         str(len(TestAuthZMiddleware.response))),
63                        ('Content-type', 'text/plain')])
64        return [TestAuthZMiddleware.response]
65
66class BeakerSessionStub(dict):
67    """Emulate beaker.session session object for purposes of the unit tests
68    """
69    def save(self):
70        pass
71   
72class WSGIAuthZTestController(unittest.TestCase):
73
74    def __init__(self, *args, **kwargs):
75        here_dir = os.path.dirname(os.path.abspath(__file__))
76        wsgiapp = loadapp('config:test.ini', relative_to=here_dir)
77        self.app = paste.fixture.TestApp(wsgiapp)
78         
79        unittest.TestCase.__init__(self, *args, **kwargs)
80       
81
82    def test01CatchNoBeakerSessionFound(self):
83       
84        # PEPFilterConfigError is raised if no beaker.session is set in
85        # environ
86        try:
87            response = self.app.get('/test_200')
88        except PEPFilterConfigError, e:
89            print("PASS - expected: %s exception: %s" % (e.__class__, e))
90       
91    def test02Ensure200WithNotLoggedInAndUnsecuredURI(self):
92       
93        # Check the authZ middleware leaves the response alone if the URI
94        # is not matched in the policy
95       
96        # Simulate a beaker.session in the environ
97        extra_environ={'beaker.session.ndg.security':BeakerSessionStub()}
98        response = self.app.get('/test_200',
99                                extra_environ=extra_environ)
100
101    def test03Catch401WithLoggedIn(self):
102       
103        # Check that the application being secured can raise a HTTP 401
104        # response and that this respected by the Authorization middleware
105        # even though a user is set in the session
106       
107        extra_environ={'beaker.session.ndg.security':
108                       BeakerSessionStub(username='testuser')}
109        response = self.app.get('/test_401', 
110                                extra_environ=extra_environ,
111                                status=401)
112
113    def test04Catch403WithLoggedIn(self):
114       
115        # Check that the application being secured can raise a HTTP 403
116        # response and that this respected by the Authorization middleware
117        # even though a user is set in the session
118       
119        extra_environ={'beaker.session.ndg.security':
120                       BeakerSessionStub(username='testuser')}
121        response = self.app.get('/test_403', 
122                                extra_environ=extra_environ,
123                                status=403)
124
125    def test05Catch401WithNotLoggedInAndSecuredURI(self):
126       
127        # AuthZ middleware grants access because the URI requested is not
128        # targeted in the policy
129       
130        # AuthZ middleware checks for username key in session set by AuthN
131        # handler
132        extra_environ={'beaker.session.ndg.security':BeakerSessionStub()}       
133        response = self.app.get('/test_accessDeniedToSecuredURI',
134                                extra_environ=extra_environ,
135                                status=401)
136       
137    def test06AccessDeniedForSecuredURI(self):
138       
139        # User is logged in but doesn't have the required credentials for
140        # access
141        extra_environ={'beaker.session.ndg.security':
142                       BeakerSessionStub(username='testuser')}
143       
144        response = self.app.get('/test_accessDeniedToSecuredURI',
145                                extra_environ=extra_environ,
146                                status=403)
147        self.assert_(
148                "Insufficient privileges to access the resource" in response)
149        print response
150       
151    def test07AccessGrantedForSecuredURI(self):
152       
153        # User is logged in but doesn't have the required credentials for
154        # access
155        extra_environ={'beaker.session.ndg.security':
156                       BeakerSessionStub(username='testuser')}
157       
158        response = self.app.get('/test_accessGrantedToSecuredURI',
159                                extra_environ=extra_environ,
160                                status=200)
161        self.assert_(TestAuthZMiddleware.response in response)
162        print response
163
164if __name__ == "__main__":
165    unittest.main()       
Note: See TracBrowser for help on using the repository browser.