source: TI12-security/trunk/python/ndg.security.test/ndg/security/test/credwallet/test_credwallet.py @ 4290

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg-security/TI12-security/trunk/python/ndg.security.test/ndg/security/test/credwallet/test_credwallet.py@4290
Revision 4290, 11.7 KB checked in by pjkersha, 12 years ago (diff)

Refactoring of CredWallet? - added unit tests for AA getAttCert call with a userId (as in DEWS) and with a personal X.509 cert.

Line 
1#!/usr/bin/env python
2"""Unit tests for Credential Wallet class
3
4NERC Data Grid Project
5"""
6__author__ = "P J Kershaw"
7__date__ = "03/10/08"
8__copyright__ = "(C) 2008 STFC & NERC"
9__license__ = \
10"""This software may be distributed under the terms of the Q Public
11License, version 1.0 or later."""
12__contact__ = "P.J.Kershaw@rl.ac.uk"
13__revision__ = '$Id$'
14
15import unittest
16import os, sys, getpass, re
17import traceback
18
19from ndg.security.common.utils.ConfigFileParsers import \
20                                                    CaseSensitiveConfigParser
21from ndg.security.common.X509 import X509CertParse
22from ndg.security.common.CredWallet import *
23
24from os.path import expandvars as xpdVars
25from os.path import join as jnPath
26mkPath = lambda file: jnPath(os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'],file)
27
28import logging
29logging.basicConfig(level=logging.DEBUG)
30
31
32class CredWalletTestCase(unittest.TestCase):
33    """Unit test case for ndg.security.common.CredWallet.CredWallet class.
34   
35    """
36   
37    def setUp(self):
38       
39        if 'NDGSEC_INT_DEBUG' in os.environ:
40            import pdb
41            pdb.set_trace()
42       
43        if 'NDGSEC_CREDWALLET_UNITTEST_DIR' not in os.environ:
44            os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'] = \
45                os.path.abspath(os.path.dirname(__file__))
46       
47        self.cfg = CaseSensitiveConfigParser()
48        configFilePath = jnPath(os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'],
49                                "credWalletTest.cfg")
50        self.cfg.read(configFilePath)
51       
52
53    def test1ReadOnlyClassVariables(self):
54       
55        try:
56            CredWallet.accessDenied = 'yes'
57            self.fail("accessDenied class variable should be read-only")
58        except Exception, e:
59            print("PASS - accessDenied class variable is read-only")
60
61        try:
62            CredWallet.accessGranted = False
63            self.fail("accessGranted class variable should be read-only")
64        except Exception, e:
65            print("PASS - accessGranted class variable is read-only")
66           
67        assert(not CredWallet.accessDenied)
68        assert(CredWallet.accessGranted)
69       
70       
71    def test2SetAttributes(self):
72       
73        credWallet = CredWallet()
74        credWallet.userX509Cert = \
75'''-----BEGIN CERTIFICATE-----
76MIICazCCAdSgAwIBAgICAPcwDQYJKoZIhvcNAQEEBQAwLzEMMAoGA1UEChMDTkRH
77MQ0wCwYDVQQLEwRCQURDMRAwDgYDVQQDEwdUZXN0IENBMB4XDTA4MDEwNDEwMTk0
78N1oXDTA5MDEwMzEwMTk0N1owLDEMMAoGA1UEChMDTkRHMQ0wCwYDVQQLEwRCQURD
79MQ0wCwYDVQQDEwR0ZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
80rpbuNUHWVRwhjHzhTOdym+fcZdmD7HbaeoFdef2V//Wj41xMieMZy9XQft2dFBDY
81ZIHLElojVhZTHoowMkwXxsmLt7hZF8fL7j3ssU/lflM9E0Uk2dZxaAt97zXEruEH
82JoNqHTEQlH0qMALfuUrAaZEIXHDdTQDNRJl4oXvjJWaqS8Y5Je8QREThIE5hRd9F
83oUlgfMNNnwzLyIH7s0KBci2yryeubAG/Qig5LkulbpnhxYLCcLvs3THQ3kO5qYYb
84B0g11YOBgshZ0SpNwEEyhDzHUt3Ii2XmAh25/II08BR61fhMZvSJ/tVGJY4HfWG7
85B4PZzYwo5vn/tYH1mk7w5QIDAQABoxUwEzARBglghkgBhvhCAQEEBAMCBPAwDQYJ
86KoZIhvcNAQEEBQADgYEAFKEdr2FwlposAGRDHBMX9d48TKm1gXzOMEvReTYIaq46
87aMpDDuApsbjpRqohvKIrngGa2e1p81tOTL5kbuusNjcNsagXkNgeO6qcGZCly/Bl
889Kxfynaned5jmgWgoxJP7VtOynvlLqJfrS/cEwOWDYpyPjJDRx2cZgEd3P4WfYI=
89-----END CERTIFICATE-----
90'''
91        print("userCert=%s" % credWallet.userX509Cert)
92        credWallet.userId = 'ndg-user'
93        print("userId=%s" % credWallet.userId)
94       
95        try:
96            credWallet.blah = 'blah blah'
97            self.fail("Attempting to set attribute not in __slots__ class "
98                      "variable should fail")
99        except AttributeError:
100            print("PASS - expected AttributeError when setting attribute "
101                  "not in __slots__ class variable")
102           
103        credWallet.caCertFilePathList=None
104        credWallet.attributeAuthorityURI='http://localhost/AttributeAuthority'
105           
106        credWallet.attributeAuthority = None
107        credWallet.credentialRepository = None
108        credWallet.mapFromTrustedHosts = False
109        credWallet.rtnExtAttCertList = True
110        credWallet.attCertRefreshElapse = 7200
111           
112    def test3GetAttCertWithUserId(self):
113                   
114        credWallet = CredWallet(cfg=self.cfg.get('setUp', 'cfgFilePath'))
115        attCert = credWallet.getAttCert()
116       
117        # No user X.509 cert is set so the resulting Attribute Certificate
118        # user ID should be the same as that set for the wallet
119        assert(attCert.userId == credWallet.userId)
120        print "Attribute Certificate:\n%s" % attCert
121       
122    def test4GetAttCertWithUserX509Cert(self):
123                   
124        credWallet = CredWallet(cfg=self.cfg.get('setUp', 'cfgFilePath'))
125       
126        # Set a test individual user certificate to override the client
127        # cert. and private key in WS-Security settings in the config file
128        credWallet.userX509Cert = """
129-----BEGIN CERTIFICATE-----
130MIICazCCAdSgAwIBAgICAPcwDQYJKoZIhvcNAQEEBQAwLzEMMAoGA1UEChMDTkRH
131MQ0wCwYDVQQLEwRCQURDMRAwDgYDVQQDEwdUZXN0IENBMB4XDTA4MDEwNDEwMTk0
132N1oXDTA5MDEwMzEwMTk0N1owLDEMMAoGA1UEChMDTkRHMQ0wCwYDVQQLEwRCQURD
133MQ0wCwYDVQQDEwR0ZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
134rpbuNUHWVRwhjHzhTOdym+fcZdmD7HbaeoFdef2V//Wj41xMieMZy9XQft2dFBDY
135ZIHLElojVhZTHoowMkwXxsmLt7hZF8fL7j3ssU/lflM9E0Uk2dZxaAt97zXEruEH
136JoNqHTEQlH0qMALfuUrAaZEIXHDdTQDNRJl4oXvjJWaqS8Y5Je8QREThIE5hRd9F
137oUlgfMNNnwzLyIH7s0KBci2yryeubAG/Qig5LkulbpnhxYLCcLvs3THQ3kO5qYYb
138B0g11YOBgshZ0SpNwEEyhDzHUt3Ii2XmAh25/II08BR61fhMZvSJ/tVGJY4HfWG7
139B4PZzYwo5vn/tYH1mk7w5QIDAQABoxUwEzARBglghkgBhvhCAQEEBAMCBPAwDQYJ
140KoZIhvcNAQEEBQADgYEAFKEdr2FwlposAGRDHBMX9d48TKm1gXzOMEvReTYIaq46
141aMpDDuApsbjpRqohvKIrngGa2e1p81tOTL5kbuusNjcNsagXkNgeO6qcGZCly/Bl
1429Kxfynaned5jmgWgoxJP7VtOynvlLqJfrS/cEwOWDYpyPjJDRx2cZgEd3P4WfYI=
143-----END CERTIFICATE-----
144"""
145        credWallet.userPriKey = """
146-----BEGIN RSA PRIVATE KEY-----
147MIIEowIBAAKCAQEArpbuNUHWVRwhjHzhTOdym+fcZdmD7HbaeoFdef2V//Wj41xM
148ieMZy9XQft2dFBDYZIHLElojVhZTHoowMkwXxsmLt7hZF8fL7j3ssU/lflM9E0Uk
1492dZxaAt97zXEruEHJoNqHTEQlH0qMALfuUrAaZEIXHDdTQDNRJl4oXvjJWaqS8Y5
150Je8QREThIE5hRd9FoUlgfMNNnwzLyIH7s0KBci2yryeubAG/Qig5LkulbpnhxYLC
151cLvs3THQ3kO5qYYbB0g11YOBgshZ0SpNwEEyhDzHUt3Ii2XmAh25/II08BR61fhM
152ZvSJ/tVGJY4HfWG7B4PZzYwo5vn/tYH1mk7w5QIDAQABAoIBAQCQdxly/iBxWo60
153Jh1zukxOj4QCzwLnps1P8z27FMeK/eJ33scCjeWpkios4An7MZktSW0UqXt135E1
154wxjwdaBzABDZm/Q0xkGLyLfTXI5EgnI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pLtGEdE8ojJnISjvkIyLUCCJdq8HYC
17125UDHqKuoqHBiXWazfZ6MOlcIm6vp1FpVDygu59JHPROMxW+BAg/
172-----END RSA PRIVATE KEY-----
173"""
174        credWallet.createAttributeAuthorityClnt()
175        attCert = credWallet.getAttCert()
176       
177        # A user X.509 cert. was set so this cert's DN should be set in the
178        # userId field of the resulting Attribute Certificate
179        assert(attCert.userId == str(credWallet.userX509Cert.dn))
180        print "Attribute Certificate:\n%s" % attCert
181         
182#
183#
184#    def test6aGetAttCertRefusedWithSessID(self):
185#        """test6aGetAttCertRefusedWithSessID: make an attribute request using
186#        a sessID as authentication credential requesting an AC from an
187#        Attribute Authority where the user is NOT registered"""
188#
189#        self.sessionMgrConnect()
190#       
191#        aaURI = self.cfg.get('test6aGetAttCertRefusedWithSessID', 'aauri')
192#       
193#        attCert, errMsg, extAttCertList = self.credWallet.getAttCert(sessID=self.sessID,
194#                                         aaURI=aaURI,
195#                                         mapFromTrustedHosts=False)
196#        if errMsg:
197#            print "SUCCESS - obtained expected result: %s" % errMsg
198#            return
199#       
200#        self.fail("Request allowed from AA where user is NOT registered!")
201#
202#    def test6bGetMappedAttCertWithSessID(self):
203#        """test6bGetMappedAttCertWithSessID: make an attribute request using
204#        a session ID as authentication credential"""
205#
206#        self.sessionMgrConnect()
207#       
208#        # Attribute Certificate cached in test 6 can be used to get a mapped
209#        # AC for this test ...
210#        self.credWallet = self.test6GetAttCertWithSessID()
211#
212#        aaURI = self.cfg.get('test6bGetMappedAttCertWithSessID', 'aauri')
213#       
214#        attCert, errMsg, extAttCertList=self.credWallet.getAttCert(sessID=self.sessID,
215#                                                   aaURI=aaURI,
216#                                                   mapFromTrustedHosts=True)
217#        if errMsg:
218#            self.fail(errMsg)
219#           
220#        print "Attribute Certificate:\n%s" % attCert 
221#
222#    def test6cGetAttCertWithExtAttCertListWithSessID(self):
223#        """test6cGetAttCertWithSessID: make an attribute request using
224#        a session ID as authentication credential"""
225#       
226#        self.sessionMgrConnect()
227#       
228#        aaURI = \
229#            self.cfg.get('test6cGetAttCertWithExtAttCertListWithSessID', 'aauri')
230#       
231#        # Use output from test6GetAttCertWithSessID!
232#        extACFilePath = \
233#        xpdVars(self.cfg.get('test6cGetAttCertWithExtAttCertListWithSessID',
234#                             'extacfilepath'))   
235#        extAttCert = open(extACFilePath).read()
236#       
237#        attCert, errMsg, extAttCertList = self.credWallet.getAttCert(
238#                                                   sessID=self.sessID,
239#                                                   aaURI=aaURI,
240#                                                   extAttCertList=[extAttCert])
241#        if errMsg:
242#            self.fail(errMsg)
243#         
244#        print "Attribute Certificate:\n%s" % attCert 
245#
246#
247#    def test7GetAttCertWithUserCert(self):
248#        """test7GetAttCertWithUserCert: make an attribute request using
249#        a user cert as authentication credential"""
250#        self.sessionMgrConnect()
251#
252#        # Request an attribute certificate from an Attribute Authority
253#        # using the userCert returned from connect()
254#       
255#        aaURI = self.cfg.get('test7GetAttCertWithUserCert', 'aauri')
256#        attCert, errMsg, extAttCertList = self.credWallet.getAttCert(\
257#                                     userCert=self.userCert, aaURI=aaURI)
258#        if errMsg:
259#            self.fail(errMsg)
260#         
261#        print "Attribute Certificate:\n%s" % attCert 
262#
263#
264#class CredWalletTestSuite(unittest.TestSuite):
265#   
266#    def __init__(self):
267#        print "CredWalletTestSuite ..."
268#        smTestCaseMap = map(CredWalletTestCase,
269#                          (
270#                            "test1Connect",
271#                            "test6GetAttCertWithSessID",
272#                            "test6bGetMappedAttCertWithSessID",
273#                            "test6cGetAttCertWithExtAttCertListWithSessID",
274#                            "test7GetAttCertWithUserCert",
275#                          ))
276#        unittest.TestSuite.__init__(self, smTestCaseMap)
277           
278                                                   
279if __name__ == "__main__":
280#    suite = CredWalletTestSuite()
281#    unittest.TextTestRunner(verbosity=2).run(suite)
282    unittest.main()       
Note: See TracBrowser for help on using the repository browser.