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

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@4293
Revision 4293, 9.5 KB checked in by pjkersha, 12 years ago (diff)

Refactoring of CredWallet?

  • added tests for getting mapped AC
  • unit tests now complete
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 CredWallet, \
23                                            CredWalletAttributeRequestDenied
24
25from os.path import expandvars as xpdVars
26from os.path import join as jnPath
27mkPath = lambda file: jnPath(os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'],file)
28
29import logging
30logging.basicConfig(level=logging.DEBUG)
31
32
33class CredWalletTestCase(unittest.TestCase):
34    """Unit test case for ndg.security.common.CredWallet.CredWallet class.
35   
36    """
37   
38    def setUp(self):
39       
40        if 'NDGSEC_INT_DEBUG' in os.environ:
41            import pdb
42            pdb.set_trace()
43       
44        if 'NDGSEC_CREDWALLET_UNITTEST_DIR' not in os.environ:
45            os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'] = \
46                os.path.abspath(os.path.dirname(__file__))
47       
48        self.cfg = CaseSensitiveConfigParser()
49        configFilePath = jnPath(os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'],
50                                "credWalletTest.cfg")
51        self.cfg.read(configFilePath)
52       
53
54    def test1ReadOnlyClassVariables(self):
55       
56        try:
57            CredWallet.accessDenied = 'yes'
58            self.fail("accessDenied class variable should be read-only")
59        except Exception, e:
60            print("PASS - accessDenied class variable is read-only")
61
62        try:
63            CredWallet.accessGranted = False
64            self.fail("accessGranted class variable should be read-only")
65        except Exception, e:
66            print("PASS - accessGranted class variable is read-only")
67           
68        assert(not CredWallet.accessDenied)
69        assert(CredWallet.accessGranted)
70       
71       
72    def test2SetAttributes(self):
73       
74        credWallet = CredWallet()
75        credWallet.userX509Cert = \
76'''-----BEGIN CERTIFICATE-----
77MIICazCCAdSgAwIBAgICAPcwDQYJKoZIhvcNAQEEBQAwLzEMMAoGA1UEChMDTkRH
78MQ0wCwYDVQQLEwRCQURDMRAwDgYDVQQDEwdUZXN0IENBMB4XDTA4MDEwNDEwMTk0
79N1oXDTA5MDEwMzEwMTk0N1owLDEMMAoGA1UEChMDTkRHMQ0wCwYDVQQLEwRCQURD
80MQ0wCwYDVQQDEwR0ZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
81rpbuNUHWVRwhjHzhTOdym+fcZdmD7HbaeoFdef2V//Wj41xMieMZy9XQft2dFBDY
82ZIHLElojVhZTHoowMkwXxsmLt7hZF8fL7j3ssU/lflM9E0Uk2dZxaAt97zXEruEH
83JoNqHTEQlH0qMALfuUrAaZEIXHDdTQDNRJl4oXvjJWaqS8Y5Je8QREThIE5hRd9F
84oUlgfMNNnwzLyIH7s0KBci2yryeubAG/Qig5LkulbpnhxYLCcLvs3THQ3kO5qYYb
85B0g11YOBgshZ0SpNwEEyhDzHUt3Ii2XmAh25/II08BR61fhMZvSJ/tVGJY4HfWG7
86B4PZzYwo5vn/tYH1mk7w5QIDAQABoxUwEzARBglghkgBhvhCAQEEBAMCBPAwDQYJ
87KoZIhvcNAQEEBQADgYEAFKEdr2FwlposAGRDHBMX9d48TKm1gXzOMEvReTYIaq46
88aMpDDuApsbjpRqohvKIrngGa2e1p81tOTL5kbuusNjcNsagXkNgeO6qcGZCly/Bl
899Kxfynaned5jmgWgoxJP7VtOynvlLqJfrS/cEwOWDYpyPjJDRx2cZgEd3P4WfYI=
90-----END CERTIFICATE-----
91'''
92        print("userCert=%s" % credWallet.userX509Cert)
93        credWallet.userId = 'ndg-user'
94        print("userId=%s" % credWallet.userId)
95       
96        try:
97            credWallet.blah = 'blah blah'
98            self.fail("Attempting to set attribute not in __slots__ class "
99                      "variable should fail")
100        except AttributeError:
101            print("PASS - expected AttributeError when setting attribute "
102                  "not in __slots__ class variable")
103           
104        credWallet.caCertFilePathList=None
105        credWallet.attributeAuthorityURI='http://localhost/AttributeAuthority'
106           
107        credWallet.attributeAuthority = None
108        credWallet.credentialRepository = None
109        credWallet.mapFromTrustedHosts = False
110        credWallet.rtnExtAttCertList = True
111        credWallet.attCertRefreshElapse = 7200
112           
113    def test3GetAttCertWithUserId(self):
114                   
115        credWallet = CredWallet(cfg=self.cfg.get('setUp', 'cfgFilePath'))
116        attCert = credWallet.getAttCert()
117       
118        # No user X.509 cert is set so the resulting Attribute Certificate
119        # user ID should be the same as that set for the wallet
120        assert(attCert.userId == credWallet.userId)
121        print "Attribute Certificate:\n%s" % attCert
122       
123    def test4GetAttCertWithUserX509Cert(self):
124                   
125        credWallet = CredWallet(cfg=self.cfg.get('setUp', 'cfgFilePath'))
126       
127        # Set a test individual user certificate to override the client
128        # cert. and private key in WS-Security settings in the config file
129        credWallet.userX509Cert = """
130-----BEGIN CERTIFICATE-----
131MIICazCCAdSgAwIBAgICAPcwDQYJKoZIhvcNAQEEBQAwLzEMMAoGA1UEChMDTkRH
132MQ0wCwYDVQQLEwRCQURDMRAwDgYDVQQDEwdUZXN0IENBMB4XDTA4MDEwNDEwMTk0
133N1oXDTA5MDEwMzEwMTk0N1owLDEMMAoGA1UEChMDTkRHMQ0wCwYDVQQLEwRCQURD
134MQ0wCwYDVQQDEwR0ZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
135rpbuNUHWVRwhjHzhTOdym+fcZdmD7HbaeoFdef2V//Wj41xMieMZy9XQft2dFBDY
136ZIHLElojVhZTHoowMkwXxsmLt7hZF8fL7j3ssU/lflM9E0Uk2dZxaAt97zXEruEH
137JoNqHTEQlH0qMALfuUrAaZEIXHDdTQDNRJl4oXvjJWaqS8Y5Je8QREThIE5hRd9F
138oUlgfMNNnwzLyIH7s0KBci2yryeubAG/Qig5LkulbpnhxYLCcLvs3THQ3kO5qYYb
139B0g11YOBgshZ0SpNwEEyhDzHUt3Ii2XmAh25/II08BR61fhMZvSJ/tVGJY4HfWG7
140B4PZzYwo5vn/tYH1mk7w5QIDAQABoxUwEzARBglghkgBhvhCAQEEBAMCBPAwDQYJ
141KoZIhvcNAQEEBQADgYEAFKEdr2FwlposAGRDHBMX9d48TKm1gXzOMEvReTYIaq46
142aMpDDuApsbjpRqohvKIrngGa2e1p81tOTL5kbuusNjcNsagXkNgeO6qcGZCly/Bl
1439Kxfynaned5jmgWgoxJP7VtOynvlLqJfrS/cEwOWDYpyPjJDRx2cZgEd3P4WfYI=
144-----END CERTIFICATE-----
145"""
146        credWallet.userPriKey = """
147-----BEGIN RSA PRIVATE KEY-----
148MIIEowIBAAKCAQEArpbuNUHWVRwhjHzhTOdym+fcZdmD7HbaeoFdef2V//Wj41xM
149ieMZy9XQft2dFBDYZIHLElojVhZTHoowMkwXxsmLt7hZF8fL7j3ssU/lflM9E0Uk
1502dZxaAt97zXEruEHJoNqHTEQlH0qMALfuUrAaZEIXHDdTQDNRJl4oXvjJWaqS8Y5
151Je8QREThIE5hRd9FoUlgfMNNnwzLyIH7s0KBci2yryeubAG/Qig5LkulbpnhxYLC
152cLvs3THQ3kO5qYYbB0g11YOBgshZ0SpNwEEyhDzHUt3Ii2XmAh25/II08BR61fhM
153ZvSJ/tVGJY4HfWG7B4PZzYwo5vn/tYH1mk7w5QIDAQABAoIBAQCQdxly/iBxWo60
154Jh1zukxOj4QCzwLnps1P8z27FMeK/eJ33scCjeWpkios4An7MZktSW0UqXt135E1
155wxjwdaBzABDZm/Q0xkGL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yHHoMiVnan9jpLtGEdE8ojJnISjvkIyLUCCJdq8HYC
17225UDHqKuoqHBiXWazfZ6MOlcIm6vp1FpVDygu59JHPROMxW+BAg/
173-----END RSA PRIVATE KEY-----
174"""
175        credWallet.createAttributeAuthorityClnt()
176        attCert = credWallet.getAttCert()
177       
178        # A user X.509 cert. was set so this cert's DN should be set in the
179        # userId field of the resulting Attribute Certificate
180        assert(attCert.userId == str(credWallet.userX509Cert.dn))
181        print "Attribute Certificate:\n%s" % attCert
182         
183
184
185    def test5GetAttCertRefusedWithUserCert(self):
186       
187        credWallet = CredWallet(cfg=self.cfg.get('setUp', 'cfgFilePath'))   
188        credWallet.userX509CertFilePath = self.cfg.get('setUp',
189                                                       'userX509CertFilePath')
190        credWallet.userPriKeyFilePath = self.cfg.get('setUp',
191                                                     'userPriKeyFilePath')
192       
193        # Set AA URI AFTER user PKI settings so that these are picked in the
194        # implicit call to create a new AA Client when the URI is set
195        credWallet.attributeAuthorityURI = self.cfg.get('setUp', 
196                                                    'attributeAuthorityURI')
197        try:
198            attCert = credWallet.getAttCert()
199        except CredWalletAttributeRequestDenied, e:
200            print "SUCCESS - obtained expected result: %s" % e
201            return
202       
203        self.fail("Request allowed from Attribute Authority where user is NOT "
204                  "registered!")
205
206    def test6GetMappedAttCertWithUserId(self):
207       
208        # Call Site A Attribute Authority where user is registered
209        credWallet = CredWallet(cfg=self.cfg.get('setUp', 'cfgFilePath'))
210        attCert = credWallet.getAttCert()
211
212        # Use Attribute Certificate cached in wallet to get a mapped
213        # Attribute Certificate from Site B's Attribute Authority
214        siteBURI = self.cfg.get('setUp', 'attributeAuthorityURI')       
215        attCert = credWallet.getAttCert(attributeAuthorityURI=siteBURI)
216           
217        print("Mapped Attribute Certificate from Site B Attribute "
218              "Authority:\n%s" % attCert)
219           
220                                                   
221if __name__ == "__main__":
222    unittest.main()       
Note: See TracBrowser for help on using the repository browser.