source: TI12-security/trunk/python/ndg.security.test/ndg/security/test/unit/sessionmanager/test_sessionmanager.py @ 5648

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.test/ndg/security/test/unit/sessionmanager/test_sessionmanager.py@5648
Revision 5648, 16.7 KB checked in by pjkersha, 11 years ago (diff)

ndg.security.server.attributeauthority.AttributeAuthority?: added samlAttributeQuery method and new AttributeInterface?.getAttributes plugin class method to enable SAML support as need for ESG.

  • Property svn:executable set to *
Line 
1#!/usr/bin/env python
2"""Test harness for NDG Session Manager - makes requests for
3authentication and attribute retrieval.  Attribute Authority services must be
4running for *AttCert* test methods.  See README in this directory for details
5
6NERC Data Grid Project
7"""
8__author__ = "P J Kershaw"
9__date__ = "20/11/07"
10__copyright__ = "(C) 2009 Science and Technology Facilities Council"
11__license__ = "BSD - see LICENSE file in top-level directory"
12__contact__ = "Philip.Kershaw@stfc.ac.uk"
13__revision__ = '$Id$'
14import logging
15logging.basicConfig(level=logging.DEBUG)
16
17import unittest
18import os, sys, getpass, re
19from ConfigParser import SafeConfigParser
20
21from os.path import expandvars as xpdVars
22from os.path import join as jnPath
23mkPath = lambda file: jnPath(os.environ['NDGSEC_SM_UNITTEST_DIR'], file)
24
25from ndg.security.test.unit import BaseTestCase
26
27from ndg.security.common.utils.configfileparsers import \
28    CaseSensitiveConfigParser
29from ndg.security.common.X509 import X509CertParse
30from ndg.security.server.sessionmanager import SessionManager, \
31    CredentialWalletAttributeRequestDenied
32from ndg.security.server.attributeauthority import AttributeAuthority
33
34
35class SessionManagerTestCase(BaseTestCase):
36    """Unit test case for ndg.security.server.sessionmanager.SessionManager
37    class.
38   
39    This class manages server side sessions"""
40   
41    passphrase = None
42    test4Passphrase = None
43   
44    def setUp(self):
45        super(SessionManagerTestCase, self).setUp()
46       
47        if 'NDGSEC_INT_DEBUG' in os.environ:
48            import pdb
49            pdb.set_trace()
50       
51        if 'NDGSEC_SM_UNITTEST_DIR' not in os.environ:
52            os.environ['NDGSEC_SM_UNITTEST_DIR'] = \
53                os.path.abspath(os.path.dirname(__file__))
54       
55        self.cfg = CaseSensitiveConfigParser()
56        configFilePath = jnPath(os.environ['NDGSEC_SM_UNITTEST_DIR'],
57                                "sessionMgrTest.cfg")
58        self.cfg.read(configFilePath)
59                   
60        # Initialise the Session Manager client connection
61        # Omit traceFile keyword to leave out SOAP debug info
62        self.propFilePath = xpdVars(self.cfg.get('setUp', 'propFilePath'))
63        self.sm = SessionManager(propFilePath=self.propFilePath)
64
65    def _connect(self):
66        '''Helper method to set up connections'''
67        print "Connecting to session manager..."
68        section = 'DEFAULT'
69       
70        username = self.cfg.get(section, 'username')
71        if SessionManagerTestCase.passphrase is None and \
72           self.cfg.has_option(section, 'passphrase'):
73            SessionManagerTestCase.passphrase=self.cfg.get(section,
74                                                           'passphrase')
75       
76        if not SessionManagerTestCase.passphrase:
77            SessionManagerTestCase.passphrase = getpass.getpass(
78                            prompt="\nPass-phrase for user %s: " % username)
79
80        print("Connecting to session manager as user: %s..." % username)
81        userX509Cert, userPriKey, issuingCert, self.sessID = \
82            self.sm.connect(username=username, 
83                            passphrase=SessionManagerTestCase.passphrase)
84
85        print("User '%s' connected to Session Manager:\n%s" % (username, 
86                                                               self.sessID))
87        print("Finished setting up connection")
88
89    def _connect2UserX509CertAuthNService(self):
90        '''Same as _connect but Session Manager is using an Authentication
91        Service that returns PKI credentials i.e. like MyProxy'''
92       
93        section = 'DEFAULT'
94
95        print("Connecting to session manager with AuthN service returning "
96              "PKI creds...")
97               
98        # Change to alternative authentication service
99        userX509CertFilePath = self.cfg.get(section, 'userX509CertFilePath')
100        userPriKeyFilePath = self.cfg.get(section, 'userPriKeyFilePath')
101        userPriKeyPwd = self.cfg.get(section, 'userPriKeyPwd')
102                                         
103        self.sm['authNService'] = {
104            'moduleFilePath': os.environ['NDGSEC_SM_UNITTEST_DIR'],
105            'moduleName': 'userx509certauthn',
106            'className': 'UserX509CertAuthN',
107            'userX509CertFilePath': userX509CertFilePath,
108            'userPriKeyFilePath': userPriKeyFilePath
109        }
110
111        self.sm.initAuthNService()
112       
113        username = self.cfg.get(section, 'username')
114        if SessionManagerTestCase.passphrase is None and \
115           self.cfg.has_option(section, 'passphrase'):
116            SessionManagerTestCase.passphrase=self.cfg.get(section, 
117                                                           'passphrase')
118       
119        if not SessionManagerTestCase.passphrase:
120            SessionManagerTestCase.passphrase = getpass.getpass(\
121                prompt="\nPass-phrase for user %s: " % username)
122
123        print("Connecting to session manager as user: %s..." % username)
124        userX509Cert, self.userPriKey, self.issuingCert, self.sessID = \
125            self.sm.connect(username=username, 
126                            passphrase=SessionManagerTestCase.passphrase)
127        self.userX509Cert = X509CertParse(userX509Cert)
128       
129        print("User '%s' connected to Session Manager:\n%s" % (username, 
130                                                               self.sessID))
131        print("Finished setting up connection")
132   
133    def test01Connect2AuthNServiceWithNoUserX509CertReturned(self):
134       
135        thisSection = 'test01Connect2AuthNServiceWithNoUserX509CertReturned'
136        username = self.cfg.get(thisSection, 'username')
137        if SessionManagerTestCase.passphrase is None and \
138           self.cfg.has_option(thisSection, 'passphrase'):
139            SessionManagerTestCase.passphrase=self.cfg.get(thisSection, 
140                                                           'passphrase')
141       
142        if not SessionManagerTestCase.passphrase:
143            SessionManagerTestCase.passphrase = getpass.getpass(
144                prompt="\ntest1Connect pass-phrase for user %s: " % username)
145
146        print "Connecting to session manager as user: %s..." %username
147        userX509Cert, userPriKey, issuingCert, sessID = self.sm.connect(
148                                username=username, 
149                                passphrase=SessionManagerTestCase.passphrase)
150        assert(userX509Cert is None)
151        assert(userPriKey is None)
152        assert(issuingCert is None)
153       
154        print("User '%s' connected to Session Manager:\n%s"%(username, sessID))     
155                                 
156    def test02Connect2AuthNServiceReturningAUserX509Cert(self):
157       
158        section = 'test02Connect2AuthNServiceReturningAUserX509Cert'
159       
160        # Change to alternative authentication service
161        userX509CertFilePath = self.cfg.get('DEFAULT', 'userX509CertFilePath')
162        userPriKeyFilePath = self.cfg.get('DEFAULT', 'userPriKeyFilePath')
163        userPriKeyPwd = self.cfg.get('DEFAULT', 'userPriKeyPwd')
164        outputCredFilePath = self.cfg.get(section, 'outputCredsFilePath')
165                                         
166        self.sm['authNService'] = {
167            'moduleFilePath': os.environ['NDGSEC_SM_UNITTEST_DIR'],
168            'moduleName': 'userx509certauthn',
169            'className': 'UserX509CertAuthN',
170            'userX509CertFilePath': userX509CertFilePath,
171            'userPriKeyFilePath': userPriKeyFilePath
172        }
173
174        self.sm.initAuthNService()
175       
176        print("Connecting to session manager...")
177        userX509Cert, self.userPriKey, self.issuingCert, sessID = self.sm.connect(
178                                                    passphrase=userPriKeyPwd)
179        self.userX509Cert = X509CertParse(userX509Cert)
180       
181        print("Connected to Session Manager:\n%s" % sessID)
182        creds='\n'.join((self.issuingCert or '',
183                         self.userX509Cert.asPEM().strip(),
184                         self.userPriKey))
185        open(mkPath(outputCredFilePath), "w").write(creds)
186   
187           
188    def test03GetSessionStatus(self):
189        """test03GetSessionStatus: check a session is alive"""
190       
191        self._connect()
192        assert self.sm.getSessionStatus(sessID=self.sessID), "Session is dead"
193        print "User connected to Session Manager with sessID=%s" % self.sessID
194
195        assert not self.sm.getSessionStatus(sessID='abc'), \
196            "sessID=abc shouldn't exist!"
197           
198        print "CORRECT: sessID=abc doesn't exist"
199       
200    def test04ConnectNoCreateServerSess(self):
201        """test04ConnectNoCreateServerSess: Connect to retrieve credentials
202        only - no session is created.  This makes sense only for an AuthN
203        Service that returns user credentials"""
204        section = 'test04ConnectNoCreateServerSess'
205       
206        # Change to alternative authentication service
207        userX509CertFilePath = self.cfg.get('DEFAULT', 'userX509CertFilePath')
208        userPriKeyFilePath = self.cfg.get('DEFAULT', 'userPriKeyFilePath')
209        userPriKeyPwd = self.cfg.get('DEFAULT', 'userPriKeyPwd')
210                                         
211        self.sm['authNService'] = {
212            'moduleFilePath': os.environ['NDGSEC_SM_UNITTEST_DIR'],
213            'moduleName': 'userx509certauthn',
214            'className': 'UserX509CertAuthN',
215            'userX509CertFilePath': userX509CertFilePath,
216            'userPriKeyFilePath': userPriKeyFilePath
217        }
218
219        self.sm.initAuthNService()
220       
221       
222        username = self.cfg.get(section, 'username')
223
224        if SessionManagerTestCase.test4Passphrase is None and \
225           self.cfg.has_option(section, 'passphrase'):
226            SessionManagerTestCase.test4Passphrase = self.cfg.get(section, 
227                                                                  'passphrase')
228       
229        if not SessionManagerTestCase.test4Passphrase:
230            SessionManagerTestCase.test4Passphrase = getpass.getpass(prompt=\
231                                            "\n%s pass-phrase for user %s: " % 
232                                            (section, username))
233
234        userX509Cert, userPriKey, issuingCert, sessID = \
235            self.sm.connect(username=username, 
236                            passphrase=SessionManagerTestCase.test4Passphrase,
237                            createServerSess=False)
238       
239        # Expect null session ID
240        assert not sessID, "Expecting a null session ID!"
241         
242        print("User '%s' retrieved creds. from Session Manager:\n%s" % 
243                                                    (username, sessID))
244           
245
246    def test05DisconnectWithSessID(self):
247        """test05DisconnectWithSessID: disconnect as if acting as a browser
248        client
249        """
250       
251        self._connect()       
252        self.sm.deleteUserSession(sessID=self.sessID)
253       
254        print "User disconnected from Session Manager:\n%s" % self.sessID
255           
256
257    def test06DisconnectWithUserX509Cert(self):
258        """test5DisconnectWithUserX509Cert: Disconnect based on a user X.509
259        cert. credential from an earlier call to connect
260        """
261       
262        self._connect2UserX509CertAuthNService()
263       
264        # User cert DN determines ID of session to delete
265        self.sm.deleteUserSession(userX509Cert=self.userX509Cert)
266        print "User disconnected from Session Manager:\n%s" % self.userX509Cert
267
268
269    def test07GetAttCertWithSessID(self):
270        """test07GetAttCertWithSessID: make an attribute request using
271        a session ID as authentication credential"""
272
273        self._connect()
274       
275        section = 'test07GetAttCertWithSessID'
276        aaURI = self.cfg.get(section, 'aaURI')
277        attCert = self.sm.getAttCert(sessID=self.sessID, 
278                                     attributeAuthorityURI=aaURI)
279        print("Attribute Certificate:\n%s" % attCert) 
280        attCert.filePath = xpdVars(self.cfg.get(section, 'acOutputFilePath')) 
281        attCert.write()
282
283
284    def test08GetAttCertRefusedWithSessID(self):
285        """test08GetAttCertRefusedWithSessID: make an attribute request using
286        a sessID as authentication credential requesting an AC from an
287        Attribute Authority where the user is NOT registered"""
288
289        self._connect()
290       
291        aaURI = self.cfg.get('test08GetAttCertRefusedWithSessID', 'aaURI')
292       
293        try:
294            attCert = self.sm.getAttCert(sessID=self.sessID, 
295                                         attributeAuthorityURI=aaURI,
296                                         mapFromTrustedHosts=False)
297        except CredentialWalletAttributeRequestDenied, e:
298            print("SUCCESS - obtained expected result: %s" % e)
299            return
300       
301        self.fail("Request allowed from AA where user is NOT registered!")
302
303
304    def test09GetMappedAttCertWithSessID(self):
305        """test09GetMappedAttCertWithSessID: make an attribute request using
306        a session ID as authentication credential"""
307
308        self._connect()
309       
310        # Attribute Certificate cached in test 6 can be used to get a mapped
311        # AC for this test ...
312        self.test07GetAttCertWithSessID()
313
314        aaURI = self.cfg.get('test09GetMappedAttCertWithSessID', 'aaURI')
315       
316        attCert = self.sm.getAttCert(sessID=self.sessID,
317                                     attributeAuthorityURI=aaURI,
318                                     mapFromTrustedHosts=True)
319           
320        print("Attribute Certificate:\n%s" % attCert) 
321
322
323    def test10GetAttCertWithExtAttCertListWithSessID(self):
324        """test10GetAttCertWithExtAttCertListWithSessID: make an attribute
325        request using a session ID as authentication credential"""
326       
327        self._connect()
328        section = 'test10GetAttCertWithExtAttCertListWithSessID'
329        aaURI = self.cfg.get(section, 'aaURI')
330       
331        # Use output from test6GetAttCertWithSessID!
332        extACFilePath = xpdVars(self.cfg.get(section, 'extACFilePath'))   
333        extAttCert = open(extACFilePath).read()
334       
335        attCert = self.sm.getAttCert(sessID=self.sessID, 
336                                     attributeAuthorityURI=aaURI,
337                                     extAttCertList=[extAttCert])
338        print("Attribute Certificate:\n%s" % attCert) 
339
340
341    def test11GetAttCertWithUserX509Cert(self):
342        """test11GetAttCertWithUserX509Cert: make an attribute request using
343        a user cert as authentication credential"""
344        self._connect2UserX509CertAuthNService()
345
346        # Request an attribute certificate from an Attribute Authority
347        # using the userX509Cert returned from connect()
348       
349        aaURI = self.cfg.get('test11GetAttCertWithUserX509Cert', 'aaURI')
350        attCert = self.sm.getAttCert(userX509Cert=self.userX509Cert, 
351                                     attributeAuthorityURI=aaURI)
352        print("Attribute Certificate:\n%s" % attCert) 
353
354
355    def test12GetAttCertFromLocalAAInstance(self):
356        """test12GetAttCertFromLocalAAInstance: make an attribute request to a
357        locally instantiated Attribute Authority"""
358
359        self._connect()
360       
361        section = 'test12GetAttCertFromLocalAAInstance'
362        aaPropFilePath = self.cfg.get(section, 'aaPropFilePath')
363        attributeAuthority=AttributeAuthority.fromPropertyFile(
364                                                propFilePath=aaPropFilePath)
365       
366        attCert = self.sm.getAttCert(sessID=self.sessID, 
367                                     attributeAuthority=attributeAuthority)           
368        print("Attribute Certificate:\n%s" % attCert) 
369        attCert.filePath = xpdVars(self.cfg.get(section, 'acOutputFilePath')) 
370        attCert.write()
371
372
373class SessionManagerTestSuite(unittest.TestSuite):
374   
375    def __init__(self):
376        print "SessionManagerTestSuite ..."
377        smTestCaseMap = map(SessionManagerTestCase,
378                          (
379                            "test01Connect2AuthNServiceWithNoUserX509CertReturned",
380                            "test02Connect2AuthNServiceReturningAUserX509Cert",
381                            "test03GetSessionStatus",
382                            "test04ConnectNoCreateServerSess",
383                            "test05DisconnectWithSessID",
384                            "test06DisconnectWithUserX509Cert",
385                            "test07GetAttCertWithSessID",
386                            "test08GetAttCertRefusedWithSessID",
387                            "test09GetMappedAttCertWithSessID",
388                            "test10GetAttCertWithExtAttCertListWithSessID",
389                            "test11GetAttCertWithUserX509Cert",
390                            "test12GetAttCertFromLocalAAInstance",
391                          ))
392        unittest.TestSuite.__init__(self, smTestCaseMap)
393           
394                                                   
395if __name__ == "__main__":
396#    suite = SessionManagerTestSuite()
397#    unittest.TextTestRunner(verbosity=2).run(suite)
398    unittest.main()       
Note: See TracBrowser for help on using the repository browser.