source: TI12-security/trunk/python/ndg_security_test/ndg/security/test/unit/wsgi/authn/test_authn.py @ 5757

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg_security_test/ndg/security/test/unit/wsgi/authn/test_authn.py@5757
Revision 5757, 4.7 KB checked in by pjkersha, 10 years ago (diff)

Testing SSL Client Authentication middleware with session and redirect middleware to enable wget support for NDG Security.

Line 
1#!/usr/bin/env python
2"""Unit tests for WSGI Authentication redirect handler
3
4NERC DataGrid Project
5"""
6__author__ = "P J Kershaw"
7__date__ = "23/02/06"
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.test.unit import BaseTestCase
31from ndg.security.common.X509 import X509Cert
32from ndg.security.server.wsgi.ssl import AuthKitSSLAuthnMiddleware
33
34
35class TestAuthnApp(object):
36    '''Test Application for the Authentication handler to protect'''
37    response = "Test Authentication redirect application"
38       
39    def __init__(self, app_conf, **local_conf):
40        pass
41   
42    def __call__(self, environ, start_response):
43       
44        if environ['PATH_INFO'] == '/test_401WithNotLoggedIn':
45            status = "401 Unauthorized"
46           
47        elif environ['PATH_INFO'] == '/test_401WithLoggedIn':
48            status = "401 Unauthorized"
49           
50        elif environ['PATH_INFO'] == '/test_200WithNotLoggedIn':
51            status = "200 OK"
52           
53        elif environ['PATH_INFO'] == '/test_200WithLoggedIn':
54            environ['REMOTE_USER'] = 'testuser'
55            status = "200 OK"
56        else:
57            status = "404 Not found"
58               
59        start_response(status,
60                       [('Content-length', 
61                         str(len(TestAuthnApp.response))),
62                        ('Content-type', 'text/plain')])
63        return [TestAuthnApp.response]
64
65
66class WSGIAuthNTestController(unittest.TestCase):
67
68    def __init__(self, *args, **kwargs):
69        here_dir = os.path.dirname(os.path.abspath(__file__))
70        wsgiapp = loadapp('config:test.ini', relative_to=here_dir)
71        self.app = paste.fixture.TestApp(wsgiapp)
72         
73        unittest.TestCase.__init__(self, *args, **kwargs)
74       
75    def test01Catch401WithNotLoggedIn(self):
76        response = self.app.get('/test_401WithNotLoggedIn')
77        self.assert_(response.status == 302)
78       
79        try:
80            redirectResponse = response.follow()
81        except paste.fixture.AppError, e:
82            self.failIf('404 Not found' not in str(e), 
83                        "Expecting 404 Not found")
84
85    def test02Skip200WithLoggedIn(self):
86        response = self.app.get('/test_200WithLoggedIn',
87                                extra_environ={'REMOTE_USER': 'testuser'})
88
89    def test03Catch401WithLoggedIn(self):
90        response = self.app.get('/test_401WithLoggedIn', 
91                                extra_environ={'REMOTE_USER': 'testuser'},
92                                status=401)
93       
94    def test04Catch200WithNotLoggedIn(self):
95        response = self.app.get('/test_200WithNotLoggedIn')
96        self.assert_(response.status == 302)
97       
98        try:
99            redirectResponse = response.follow()
100        except paste.fixture.AppError, e:
101            self.failIf('404 Not found' not in str(e), 
102                        "Expecting 404 Not found")
103
104
105class WsgiSSLClientAuthnTestController(BaseTestCase):
106    """Extend Authentication middleware test to use SSL Client Authentication
107    middleware"""
108   
109    def __init__(self, *arg, **kw):
110        here_dir = os.path.dirname(os.path.abspath(__file__))
111        wsgiapp = loadapp('config:ssl-test.ini', relative_to=here_dir)
112        self.app = paste.fixture.TestApp(wsgiapp)
113         
114        BaseTestCase.__init__(self, *arg, **kw)
115       
116    def test01Catch401WithNotLoggedIn(self):
117        thisDir = os.path.dirname(__file__)
118        sslClientCertFilePath = os.path.join(
119                                os.environ[BaseTestCase.configDirEnvVarName],
120                                'pki',
121                                'test.crt')
122        sslClientCert = X509Cert.Read(sslClientCertFilePath).toString()
123        extra_environ = {'HTTPS':'1', 'SSL_CLIENT_CERT': sslClientCert}
124
125        response = self.app.get('/test_401WithNotLoggedIn',
126                                extra_environ=extra_environ,
127                                status=302)
128       
129        redirectResponse = response.follow(extra_environ=extra_environ,
130                                           status=302)
131       
132        finalResponse = redirectResponse.follow(extra_environ=extra_environ)
133       
134        print finalResponse
135       
136   
137if __name__ == "__main__":
138    unittest.main()       
Note: See TracBrowser for help on using the repository browser.