Package myproxy :: Package ws :: Package test :: Module test_myproxywsgi
[hide private]

Source Code for Module myproxy.ws.test.test_myproxywsgi

  1  #!/usr/bin/env python 
  2  """Unit tests for MyProxy WSGI Middleware classes and Application.  These are 
  3  run using paste.fixture i.e. tests stubs to a web application server 
  4  """ 
  5  __author__ = "P J Kershaw" 
  6  __date__ = "21/05/10" 
  7  __copyright__ = "(C) 2010 Science and Technology Facilities Council" 
  8  __license__ = "BSD - see LICENSE file in top-level directory" 
  9  __contact__ = "Philip.Kershaw@stfc.ac.uk" 
 10  __revision__ = '$Id$' 
 11  import logging 
 12  logging.basicConfig(level=logging.DEBUG) 
 13   
 14  import unittest 
 15  import os 
 16  import base64 
 17  from getpass import getpass 
 18  from ConfigParser import SafeConfigParser, NoOptionError 
 19   
 20  from OpenSSL import crypto 
 21  import paste.fixture 
 22  from paste.deploy import loadapp 
 23   
 24  from myproxy.ws.server.wsgi.middleware import MyProxyLogonWSMiddleware 
 25   
 26   
27 -class TestMyProxyClientMiddlewareApp(object):
28 '''Test Application for MyClientProxyMiddleware''' 29 RESPONSE = "Test MyProxyClientMiddleware" 30
31 - def __call__(self, environ, start_response):
32 33 assert(environ[MyProxyLogonWSMiddleware.DEFAULT_CLIENT_ENV_KEYNAME]) 34 status = "200 OK" 35 36 start_response(status, 37 [('Content-length', 38 str(len(self.__class__.RESPONSE))), 39 ('Content-type', 'text/plain')]) 40 return [self.__class__.RESPONSE]
41 42
43 -class MyProxyClientMiddlewareTestCase(unittest.TestCase):
44 - def __init__(self, *args, **kwargs):
45 app = TestMyProxyClientMiddlewareApp() 46 app = MyProxyLogonWSMiddleware.filter_app_factory(app, {}, prefix='') 47 self.app = paste.fixture.TestApp(app) 48 49 unittest.TestCase.__init__(self, *args, **kwargs)
50
52 # Check the middleware has set the MyProxy client object in environ 53 response = self.app.get('/', status=200) 54 self.assert_(response)
55 56
57 -class MyProxyPasteDeployTestCaseBase(unittest.TestCase):
58 """Base class for common Paste Deploy related set-up""" 59 INI_FILENAME = 'myproxywsgi.ini' 60 THIS_DIR = os.path.abspath(os.path.dirname(__file__)) 61 CONFIG_FILENAME = 'test_myproxywsgi.cfg' 62 CONFIG_FILEPATH = os.path.join(THIS_DIR, CONFIG_FILENAME) 63
64 - def __init__(self, *args, **kwargs):
65 here_dir = os.path.dirname(os.path.abspath(__file__)) 66 wsgiapp = loadapp('config:' + self.__class__.INI_FILENAME, 67 relative_to=here_dir) 68 self.app = paste.fixture.TestApp(wsgiapp) 69 70 self.cfg = SafeConfigParser({'here': self.__class__.THIS_DIR}) 71 self.cfg.optionxform = str 72 self.cfg.read(self.__class__.CONFIG_FILEPATH) 73 74 unittest.TestCase.__init__(self, *args, **kwargs)
75 76
77 -class MyProxyLogonAppTestCase(MyProxyPasteDeployTestCaseBase):
78 """Test HTTP MyProxy logon interface""" 79
80 - def _createRequestCreds(self):
81 keyPair = crypto.PKey() 82 keyPair.generate_key(crypto.TYPE_RSA, 1024) 83 84 certReq = crypto.X509Req() 85 86 # Create public key object 87 certReq.set_pubkey(keyPair) 88 89 # Add the public key to the request 90 certReq.sign(keyPair, "md5") 91 92 pemCertReq = crypto.dump_certificate_request(crypto.FILETYPE_PEM, 93 certReq) 94 return keyPair, pemCertReq
95
96 - def test01Logon(self):
97 # Test successful logon 98 username = self.cfg.get('MyProxyLogonAppTestCase.test01Logon', 99 'username') 100 try: 101 password = self.cfg.get('MyProxyLogonAppTestCase.test01Logon', 102 'password') 103 except NoOptionError: 104 password = getpass('MyProxyLogonAppTestCase.test01Logon password: ') 105 106 base64String = base64.encodestring('%s:%s' % (username, password))[:-1] 107 authHeader = "Basic %s" % base64String 108 headers = {'Authorization': authHeader} 109 110 # Create key pair and certificate request 111 keyPair, certReq = self._createRequestCreds() 112 113 postData = { 114 MyProxyLogonWSMiddleware.CERT_REQ_POST_PARAM_KEYNAME: certReq 115 } 116 response = self.app.post('/logon', postData, headers=headers, 117 status=200) 118 print response 119 self.assert_(response)
120 122 # Test failure with omission of HTTP Basic Auth header - a 401 result is 123 # expected. 124 125 # Create key pair and certificate request 126 keyPair, certReq = self._createRequestCreds() 127 response = self.app.post('/logon', certReq, status=401) 128 print response 129 self.assert_(response)
130
131 - def test03NoCertificateRequestSent(self):
132 # Test with missing certificate request 133 134 # Username and password don't matter - exception is raised in server 135 # middleware prior to authentication 136 username = '' 137 password = '' 138 139 base64String = base64.encodestring('%s:%s' % (username, password))[:-1] 140 authHeader = "Basic %s" % base64String 141 headers = {'Authorization': authHeader} 142 143 # Bad POST'ed content 144 response = self.app.post('/logon', 'x', headers=headers, status=400) 145 print response 146 self.assert_(response)
147
148 - def test04GET(self):
149 # Test HTTP GET request - should be rejected - POST is expected 150 151 # Username and password don't matter - exception is raised in server 152 # middleware prior to authentication 153 username = '' 154 password = '' 155 base64String = base64.encodestring('%s:%s' % (username, password))[:-1] 156 authHeader = "Basic %s" % base64String 157 headers = {'Authorization': authHeader} 158 159 response = self.app.get('/logon', headers=headers, status=405) 160 print response 161 self.assert_(response)
162 163
164 -class MyProxyGetTrustRootsMiddlewareTestCase(MyProxyPasteDeployTestCaseBase):
165 """Test HTTP MyProxy get trust roots interface""" 166
167 - def test01(self):
168 response = self.app.get('/get-trustroots', status=200) 169 self.assert_(response) 170 print response 171 172 # Test deserialisation 173 for line in response.body.split('\n'): 174 fieldName, val = line.split('=', 1) 175 print("%s: %s\n" % (fieldName, base64.b64decode(val)))
176 177 if __name__ == "__main__": 178 unittest.main() 179