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

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@6033
Revision 6033, 8.1 KB checked in by pjkersha, 10 years ago (diff)

Refactoring Credential Wallet to enable caching of SAML assertions.

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