source: TI12-security/trunk/python/ndg.security.test/ndg/security/test/unit/credentialwallet/test_credentialwallet.py @ 5648

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.test/ndg/security/test/unit/credentialwallet/test_credentialwallet.py@5648
Revision 5648, 7.5 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.

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) 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$'
12
13import unittest
14import os, sys, getpass, re
15import traceback
16
17from ndg.security.test.unit import BaseTestCase
18
19from ndg.security.common.utils.configfileparsers import \
20                                                    CaseSensitiveConfigParser
21from ndg.security.common.X509 import X509CertParse
22from ndg.security.common.credentialwallet import CredentialWallet, \
23                                        CredentialWalletAttributeRequestDenied
24from ndg.security.server.attributeauthority import AttributeAuthority
25
26from os.path import expandvars as xpdVars
27from os.path import join as jnPath
28mkPath = lambda file: jnPath(os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'],file)
29
30import logging
31logging.basicConfig(level=logging.DEBUG)
32
33
34class CredentialWalletTestCase(BaseTestCase):
35    """Unit test case for ndg.security.common.credentialwallet.CredentialWallet
36    class.
37    """
38   
39    def setUp(self):
40        super(CredentialWalletTestCase, self).setUp()
41       
42        if 'NDGSEC_INT_DEBUG' in os.environ:
43            import pdb
44            pdb.set_trace()
45       
46        if 'NDGSEC_CREDWALLET_UNITTEST_DIR' not in os.environ:
47            os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'] = \
48                os.path.abspath(os.path.dirname(__file__))
49       
50        self.cfg = CaseSensitiveConfigParser()
51        configFilePath = jnPath(os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'],
52                                "credWalletTest.cfg")
53        self.cfg.read(configFilePath)
54
55        self.userX509CertFilePath=self.cfg.get('setUp', 'userX509CertFilePath')
56        self.userPriKeyFilePath=self.cfg.get('setUp', 'userPriKeyFilePath')
57       
58
59    def test01ReadOnlyClassVariables(self):
60       
61        try:
62            CredentialWallet.accessDenied = 'yes'
63            self.fail("accessDenied class variable should be read-only")
64        except Exception, e:
65            print("PASS - accessDenied class variable is read-only")
66
67        try:
68            CredentialWallet.accessGranted = False
69            self.fail("accessGranted class variable should be read-only")
70        except Exception, e:
71            print("PASS - accessGranted class variable is read-only")
72           
73        assert(not CredentialWallet.accessDenied)
74        assert(CredentialWallet.accessGranted)
75       
76       
77    def test02SetAttributes(self):
78       
79        credWallet = CredentialWallet()
80        credWallet.userX509Cert=open(xpdVars(self.userX509CertFilePath)).read()
81        print("userX509Cert=%s" % credWallet.userX509Cert)
82        credWallet.userId = 'ndg-user'
83        print("userId=%s" % credWallet.userId)
84       
85        try:
86            credWallet.blah = 'blah blah'
87            self.fail("Attempting to set attribute not in __slots__ class "
88                      "variable should fail")
89        except AttributeError:
90            print("PASS - expected AttributeError when setting attribute "
91                  "not in __slots__ class variable")
92           
93        credWallet.caCertFilePathList=None
94        credWallet.attributeAuthorityURI='http://localhost/AttributeAuthority'
95           
96        credWallet.attributeAuthority = None
97        credWallet.credentialRepository = None
98        credWallet.mapFromTrustedHosts = False
99        credWallet.rtnExtAttCertList = True
100        credWallet.attCertRefreshElapse = 7200
101     
102           
103    def test03GetAttCertWithUserId(self):
104                   
105        credWallet = CredentialWallet(cfg=self.cfg.get('setUp', 'cfgFilePath'))
106        attCert = credWallet.getAttCert()
107       
108        # No user X.509 cert is set so the resulting Attribute Certificate
109        # user ID should be the same as that set for the wallet
110        assert(attCert.userId == credWallet.userId)
111        print("Attribute Certificate:\n%s" % attCert)
112       
113    def test04GetAttCertWithUserX509Cert(self):
114                   
115        credWallet = CredentialWallet(cfg=self.cfg.get('setUp', 'cfgFilePath'))
116       
117        # Set a test individual user certificate to override the client
118        # cert. and private key in WS-Security settings in the config file
119        credWallet.userX509Cert=open(xpdVars(self.userX509CertFilePath)).read()
120        credWallet.userPriKey=open(xpdVars(self.userPriKeyFilePath)).read()
121        attCert = credWallet.getAttCert()
122       
123        # A user X.509 cert. was set so this cert's DN should be set in the
124        # userId field of the resulting Attribute Certificate
125        assert(attCert.userId == str(credWallet.userX509Cert.dn))
126        print("Attribute Certificate:\n%s" % attCert)
127         
128
129
130    def test05GetAttCertRefusedWithUserX509Cert(self):
131       
132        # Keyword mapFromTrustedHosts overrides any setting in the config file
133        # This flag prevents role mapping from a trusted AA and so in this case
134        # forces refusal of the request
135        credWallet = CredentialWallet(cfg=self.cfg.get('setUp', 'cfgFilePath'),
136                                      mapFromTrustedHosts=False)   
137        credWallet.userX509CertFilePath = self.userX509CertFilePath
138        credWallet.userPriKeyFilePath = self.userPriKeyFilePath
139       
140        # Set AA URI AFTER user PKI settings so that these are picked in the
141        # implicit call to create a new AA Client when the URI is set
142        credWallet.attributeAuthorityURI = self.cfg.get('setUp', 
143                                                    'attributeAuthorityURI')
144        try:
145            attCert = credWallet.getAttCert()
146        except CredentialWalletAttributeRequestDenied, e:
147            print("SUCCESS - obtained expected result: %s" % e)
148            return
149       
150        self.fail("Request allowed from Attribute Authority where user is NOT "
151                  "registered!")
152
153    def test06GetMappedAttCertWithUserId(self):
154       
155        # Call Site A Attribute Authority where user is registered
156        credWallet = CredentialWallet(cfg=self.cfg.get('setUp', 'cfgFilePath'))
157        attCert = credWallet.getAttCert()
158
159        # Use Attribute Certificate cached in wallet to get a mapped
160        # Attribute Certificate from Site B's Attribute Authority
161        siteBURI = self.cfg.get('setUp', 'attributeAuthorityURI')       
162        attCert = credWallet.getAttCert(attributeAuthorityURI=siteBURI)
163           
164        print("Mapped Attribute Certificate from Site B Attribute "
165              "Authority:\n%s" % attCert)
166                       
167    def test07GetAttCertFromLocalAAInstance(self):
168        thisSection = 'test07GetAttCertFromLocalAAInstance'
169        aaPropFilePath = self.cfg.get(thisSection,
170                                      'attributeAuthorityPropFilePath') 
171                 
172        credWallet = CredentialWallet(cfg=self.cfg.get('setUp', 'cfgFilePath'))
173        credWallet.attributeAuthority = AttributeAuthority.fromPropertyFile(
174                                            propFilePath=aaPropFilePath)
175        attCert = credWallet.getAttCert()
176       
177        # No user X.509 cert is set so the resulting Attribute Certificate
178        # user ID should be the same as that set for the wallet
179        assert(attCert.userId == credWallet.userId)
180        print("Attribute Certificate:\n%s" % attCert) 
181                                                         
182if __name__ == "__main__":
183    unittest.main()       
Note: See TracBrowser for help on using the repository browser.