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

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