Changeset 6730


Ignore:
Timestamp:
16/03/10 08:37:55 (10 years ago)
Author:
pjkersha
Message:
  • Working Credential Wallet refactored for Python 2.6
  • Pruned out more old code: ZSI and Twisted SAOP/WSDL wrappers, Session Manager and WS-Security, Test 'Site B' Attribute Authority - for testing role mapping.
  • Started XACML package ElementTree based parser.
Location:
TI12-security/trunk/NDGSecurity/python
Files:
4 added
11 deleted
7 edited

Legend:

Unmodified
Added
Removed
  • TI12-security/trunk/NDGSecurity/python/ndg_security_common/ndg/security/common/authz/xacml/__init__.py

    r6673 r6730  
     1class XACMLError(Exception): 
     2    """Base class for XACML package exception types""" 
     3     
     4     
     5class XMLParseError(XACMLError): 
     6    """XACML package XML Parsing error""" 
     7     
     8     
    19class PolicyComponent(object): 
    210    """Base class for Policy and Policy subelements""" 
  • TI12-security/trunk/NDGSecurity/python/ndg_security_common/ndg/security/common/authz/xacml/policy.py

    r6643 r6730  
    3939 
    4040class Policy(PolicyComponent): 
    41     """NDG MSI Policy."""    
     41    """NDG MSI Policy."""  
     42    POLICY_ID_ATTRIB_NAME = "PolicyId" 
     43    RULE_COMBINING_ALG_ID_ATTRIB_NAME = "RuleCombiningAlgId" 
     44       
    4245    DESCRIPTION_LOCALNAME = "Description" 
    4346    TARGET_LOCALNAME = "Target" 
     47    POLICY_DEFAULTS_LOCALNAME = "PolicyDefaults" 
     48    OBLIGATIONS_LOCALNAME = "Obligations" 
     49    RULE_LOCALNAME = "Rule" 
    4450     
    4551    # Plan to support permit overrides in a future release 
  • TI12-security/trunk/NDGSecurity/python/ndg_security_common/ndg/security/common/credentialwallet.py

    r6673 r6730  
    1616import os 
    1717import warnings 
    18 import traceback 
    1918 
    2019# Check Attribute Certificate validity times 
     
    2625from ndg.saml.saml2.core import Assertion 
    2726 
    28 # Access Attribute Authority's web service using ZSI - allow pass if not  
    29 # loaded since it's possible to make AttributeAuthority instance locally 
    30 # without using the WS 
    31 aaImportError = True 
    32 try: 
    33     # AttributeAuthority client package resides with CredentialWallet module in  
    34     # ndg.security.common 
    35     from ndg.security.common.attributeauthority import ( 
    36         AttributeAuthorityClient, AttributeAuthorityClientError,  
    37         AttributeRequestDenied, NoMatchingRoleInTrustedHosts) 
    38     aaImportError = False 
    39 except ImportError: 
    40     pass 
    41  
    42 # Likewise - may not want to use WS and use AttributeAuthority locally in which 
    43 # case no need to import it 
    44 try: 
    45     from ndg.security.server.attributeauthority import (AttributeAuthority,  
    46         AttributeAuthorityError, AttributeAuthorityAccessDenied) 
    47     aaImportError = False 
    48 except ImportError: 
    49     pass 
    50  
    51 if aaImportError: 
    52     raise ImportError("Either AttributeAuthority or AttributeAuthorityClient " 
    53                       "classes must be present to allow interoperation with " 
    54                       "Attribute Authorities: %s" % traceback.format_exc()) 
    55  
    56 # Authentication X.509 Certificate 
    57 from ndg.security.common.X509 import X509Cert 
    58 from M2Crypto import X509, BIO, RSA 
    59  
    60 # Authorisation - attribute certificate  
    61 from ndg.security.common.AttCert import AttCert, AttCertError 
    62 from ndg.security.common.wssecurity.signaturehandler.dom import SignatureHandler 
    63  
    64 # generic parser to read INI/XML properties file 
    65 from ndg.security.common.utils.configfileparsers import \ 
    66                                                 INIPropertyFileWithValidation 
    67  
    68 from ndg.security.common.utils import TypedList 
    6927from ndg.security.common.utils.configfileparsers import (      
    7028                                                    CaseSensitiveConfigParser,) 
     
    178136    __slots__ = tuple(["__%s" % n for n in __ATTRIBUTE_NAMES]) 
    179137     
    180     def __init__(self, type=None): 
     138    def __init__(self, _type=None): 
    181139        self.__type = None 
    182         self.type = type 
     140        self.type = _type 
    183141         
    184142        self.__id = -1 
     
    700658     
    701659    def __init__(self, propFilePath=None, dbPPhrase=None, **prop): 
    702         pass 
     660        """Null Credential Repository __init__ placeholder""" 
    703661 
    704662    def addUser(self, userId): 
    705         pass 
     663        """Null Credential Repository addUser placeholder""" 
    706664                             
    707665    def auditCredentials(self, **attCertValidKeys): 
    708         pass 
     666        """Null Credential Repository addUser placeholder""" 
    709667 
    710668    def getCredentials(self, userId): 
     669        """Null Credential Repository getCredentials placeholder""" 
    711670        return [] 
    712671        
    713672    def addCredentials(self, userId, attCertList): 
    714         pass 
     673        """Null Credential Repository addCredentials placeholder""" 
  • TI12-security/trunk/NDGSecurity/python/ndg_security_common/ndg/security/common/utils/__init__.py

    r5870 r6730  
    7676     
    7777        return super(TypedList, self).append(item) 
     78 
     79class RestrictedKeyNamesDict(dict): 
     80    """Utility class for holding a constrained list of key names 
     81    """ 
     82     
     83    def __init__(self, *arg, **kw): 
     84        """Alter standard dict() initialisation to fix key names set at  
     85        initialisation 
     86        """ 
     87        super(RestrictedKeyNamesDict, self).__init__(*arg, **kw) 
     88        self.__keyNames = self.keys()  
     89           
     90    def __setitem__(self, key, val): 
     91        if key not in self.__keyNames: 
     92            raise KeyError('Key name %r not recognised.  Valid key names ' 
     93                           'are: %r' % (key, self.__keyNames)) 
     94             
     95        dict.__setitem__(self, key, val) 
     96 
     97    def update(self, d, **kw):         
     98        for dictArg in (d, kw): 
     99            for k in dictArg: 
     100                if k not in self.__keyNames: 
     101                    raise KeyError('Key name "%s" not recognised.  Valid ' 
     102                                   'key names are: %s' %  
     103                                   self.__keyNames) 
     104         
     105        dict.update(self, d, **kw) 
  • TI12-security/trunk/NDGSecurity/python/ndg_security_server/ndg/security/server/attributeauthority.py

    r6721 r6730  
    3838from ndg.security.common.saml_utils.esg import EsgSamlNamespaces 
    3939from ndg.security.common.X509 import X500DN 
    40 from ndg.security.common.utils import TypedList 
     40from ndg.security.common.utils import TypedList, RestrictedKeyNamesDict 
    4141from ndg.security.common.utils.classfactory import instantiateClass 
    4242from ndg.security.common.utils.configfileparsers import ( 
     
    9393    ISSUER_NAME_OPTNAME = 'issuerName' 
    9494    ASSERTION_LIFETIME_OPTNAME = 'assertionLifetime' 
    95     DN_SEPARATOR_OPTNAME = 'dnSeparator' 
    9695     
    9796    ATTRIBUTE_INTERFACE_OPTPREFIX = 'attributeInterface' 
     
    113112        ISSUER_NAME_OPTNAME:            '', 
    114113        ASSERTION_LIFETIME_OPTNAME:     -1, 
    115         DN_SEPARATOR_OPTNAME:           '/', 
    116114        ATTRIBUTE_INTERFACE_OPTPREFIX:  ATTRIBUTE_INTERFACE_PROPERTY_DEFAULTS 
    117115    } 
     
    119117    __slots__ = ( 
    120118        '__assertionLifetime',  
    121         '__dnSeparator', 
    122119        '__propFilePath', 
    123120        '__propFileSection', 
     
    133130        # Initial config file property based attributes 
    134131        self.__assertionLifetime = None 
    135         self.__dnSeparator = None 
    136132         
    137133        self.__propFilePath = None         
     
    139135        self.__propPrefix = '' 
    140136         
    141         self.__attributeInterfaceCfg = {} 
     137        self.__attributeInterfaceCfg = RestrictedKeyNamesDict( 
     138                    AttributeAuthority.ATTRIBUTE_INTERFACE_PROPERTY_DEFAULTS) 
    142139         
    143140    def __getstate__(self): 
     
    189186                                     doc="Settings for Attribute Interface " 
    190187                                         "initialisation") 
    191      
    192     def _get_dnSeparator(self): 
    193         return self.__dnSeparator 
    194      
    195     def _set_dnSeparator(self, value): 
    196         if not isinstance(value, basestring): 
    197             raise TypeError('Expecting string type for "dnSeparator"; got ' 
    198                             '%r' % type(value)) 
    199         self.__dnSeparator = value 
    200           
    201     dnSeparator = property(fget=_get_dnSeparator,  
    202                            fset=_set_dnSeparator, 
    203                            doc="Distinguished Name separator character used " 
    204                                "with X.509 Certificate issuer certificate") 
    205188 
    206189    def setPropFilePath(self, val=None): 
  • TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/config/attributeauthority/sitea/site-a.ini

    r6721 r6730  
    4747# Lifetime is measured in seconds 
    4848attributeAuthority.assertionLifetime: 28800  
    49  
    50 attributeAuthority.dnSeparator:/ 
    5149 
    5250# Settings for custom AttributeInterface derived class to get user roles for given  
  • TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/unit/credentialwallet/test_credentialwallet.py

    r6615 r6730  
    11#!/usr/bin/env python 
    2 """Unit tests for Credential Wallet classes 
     2"""Unit tests for Credential Wallet class 
    33 
    44NERC DataGrid Project 
     
    1010__contact__ = "Philip.Kershaw@stfc.ac.uk" 
    1111__revision__ = '$Id: $' 
     12import logging 
     13logging.basicConfig(level=logging.DEBUG) 
    1214 
    1315import unittest 
    14 import os, sys, getpass, re 
    15 import traceback 
     16import os 
    1617 
    1718from string import Template 
     
    2324from time import sleep 
    2425from datetime import datetime, timedelta 
     26 
    2527from ndg.saml.utils import SAMLDateTime 
    2628from ndg.saml.xml.etree import AssertionElementTree 
    2729 
    2830from ndg.security.test.unit import BaseTestCase 
     31from ndg.security.common.utils.etree import prettyPrint 
     32from ndg.security.common.credentialwallet import SAMLCredentialWallet 
    2933 
    30 from ndg.security.common.utils.configfileparsers import ( 
    31                                                     CaseSensitiveConfigParser) 
    32 from ndg.security.common.utils.etree import prettyPrint 
    33 from ndg.security.common.X509 import X509CertParse 
    34 from ndg.security.common.credentialwallet import (NDGCredentialWallet,  
    35     CredentialWalletAttributeRequestDenied, SAMLCredentialWallet) 
    36 from ndg.security.server.attributeauthority import AttributeAuthority 
    37  
    38 from os.path import expandvars as xpdVars 
    39 from os.path import join as jnPath 
    40 mkPath = lambda file: jnPath(os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'], file) 
    41  
    42 import logging 
    43 logging.basicConfig(level=logging.DEBUG) 
    44  
    45  
    46 class NDGCredentialWalletTestCase(BaseTestCase): 
    47     """Unit test case for  
    48     ndg.security.common.credentialwallet.NDGCredentialWallet class. 
    49     """ 
    50     THIS_DIR = os.path.dirname(__file__) 
    51     PICKLE_FILENAME = 'NDGCredentialWalletPickle.dat' 
    52     PICKLE_FILEPATH = os.path.join(THIS_DIR, PICKLE_FILENAME) 
    53  
    54     def __init__(self, *arg, **kw): 
    55         super(NDGCredentialWalletTestCase, self).__init__(*arg, **kw) 
    56         self.startAttributeAuthorities() 
    57      
    58     def setUp(self): 
    59         super(NDGCredentialWalletTestCase, self).setUp() 
    60          
    61         if 'NDGSEC_INT_DEBUG' in os.environ: 
    62             import pdb 
    63             pdb.set_trace() 
    64          
    65         if 'NDGSEC_CREDWALLET_UNITTEST_DIR' not in os.environ: 
    66             os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'] = \ 
    67                 os.path.abspath(os.path.dirname(__file__)) 
    68          
    69         self.cfg = CaseSensitiveConfigParser() 
    70         configFilePath = jnPath(os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'], 
    71                                 "credWalletTest.cfg") 
    72         self.cfg.read(configFilePath) 
    73  
    74         self.userX509CertFilePath=self.cfg.get('setUp', 'userX509CertFilePath') 
    75         self.userPriKeyFilePath=self.cfg.get('setUp', 'userPriKeyFilePath') 
    76          
    77  
    78     def test01ReadOnlyClassVariables(self): 
    79          
    80         try: 
    81             NDGCredentialWallet.accessDenied = 'yes' 
    82             self.fail("accessDenied class variable should be read-only") 
    83         except Exception, e: 
    84             print("PASS - accessDenied class variable is read-only") 
    85  
    86         try: 
    87             NDGCredentialWallet.accessGranted = False 
    88             self.fail("accessGranted class variable should be read-only") 
    89         except Exception, e: 
    90             print("PASS - accessGranted class variable is read-only") 
    91              
    92         assert(not NDGCredentialWallet.accessDenied) 
    93         assert(NDGCredentialWallet.accessGranted) 
    94          
    95          
    96     def test02SetAttributes(self): 
    97          
    98         credWallet = NDGCredentialWallet() 
    99         credWallet.userX509Cert=open(xpdVars(self.userX509CertFilePath)).read() 
    100         print("userX509Cert=%s" % credWallet.userX509Cert) 
    101         credWallet.userId = 'ndg-user' 
    102         print("userId=%s" % credWallet.userId) 
    103          
    104         try: 
    105             credWallet.blah = 'blah blah' 
    106             self.fail("Attempting to set attribute not in __slots__ class " 
    107                       "variable should fail") 
    108         except AttributeError: 
    109             print("PASS - expected AttributeError when setting attribute " 
    110                   "not in __slots__ class variable") 
    111              
    112         credWallet.caCertFilePathList=None 
    113         credWallet.attributeAuthorityURI='http://localhost/AttributeAuthority' 
    114              
    115         credWallet.attributeAuthority = None 
    116         credWallet._credentialRepository = None 
    117         credWallet.mapFromTrustedHosts = False 
    118         credWallet.rtnExtAttCertList = True 
    119         credWallet.attCertRefreshElapse = 7200 
    120       
    121              
    122     def test03GetAttCertWithUserId(self): 
    123                      
    124         credWallet = NDGCredentialWallet(cfg=self.cfg.get('setUp',  
    125                                                           'cfgFilePath')) 
    126         attCert = credWallet.getAttCert() 
    127          
    128         # No user X.509 cert is set so the resulting Attribute Certificate 
    129         # user ID should be the same as that set for the wallet 
    130         assert(attCert.userId == credWallet.userId) 
    131         print("Attribute Certificate:\n%s" % attCert) 
    132          
    133     def test04GetAttCertWithUserX509Cert(self): 
    134                      
    135         credWallet = NDGCredentialWallet(cfg=self.cfg.get('setUp',  
    136                                                           'cfgFilePath')) 
    137          
    138         # Set a test individual user certificate to override the client  
    139         # cert. and private key in WS-Security settings in the config file 
    140         credWallet.userX509Cert=open(xpdVars(self.userX509CertFilePath)).read() 
    141         credWallet.userPriKey=open(xpdVars(self.userPriKeyFilePath)).read() 
    142         attCert = credWallet.getAttCert() 
    143          
    144         # A user X.509 cert. was set so this cert's DN should be set in the 
    145         # userId field of the resulting Attribute Certificate 
    146         assert(attCert.userId == str(credWallet.userX509Cert.dn)) 
    147         print("Attribute Certificate:\n%s" % attCert) 
    148  
    149     def test05GetAttCertRefusedWithUserX509Cert(self): 
    150          
    151         # Keyword mapFromTrustedHosts overrides any setting in the config file 
    152         # This flag prevents role mapping from a trusted AA and so in this case 
    153         # forces refusal of the request 
    154         credWallet = NDGCredentialWallet(cfg=self.cfg.get('setUp',  
    155                                                           'cfgFilePath'), 
    156                                          mapFromTrustedHosts=False)     
    157         credWallet.userX509CertFilePath = self.userX509CertFilePath 
    158         credWallet.userPriKeyFilePath = self.userPriKeyFilePath 
    159          
    160         # Set AA URI AFTER user PKI settings so that these are picked in the 
    161         # implicit call to create a new AA Client when the URI is set 
    162         credWallet.attributeAuthorityURI = self.cfg.get('setUp',  
    163                                                         'attributeAuthorityURI') 
    164         try: 
    165             attCert = credWallet.getAttCert() 
    166         except CredentialWalletAttributeRequestDenied, e: 
    167             print("ok - obtained expected result: %s" % e) 
    168             return 
    169          
    170         self.fail("Request allowed from Attribute Authority where user is NOT " 
    171                   "registered!") 
    172  
    173     def test06GetMappedAttCertWithUserId(self): 
    174          
    175         # Call Site A Attribute Authority where user is registered 
    176         credWallet = NDGCredentialWallet(cfg=self.cfg.get('setUp',  
    177                                                           'cfgFilePath')) 
    178         attCert = credWallet.getAttCert() 
    179  
    180         # Use Attribute Certificate cached in wallet to get a mapped  
    181         # Attribute Certificate from Site B's Attribute Authority 
    182         siteBURI = self.cfg.get('setUp', 'attributeAuthorityURI')         
    183         attCert = credWallet.getAttCert(attributeAuthorityURI=siteBURI) 
    184              
    185         print("Mapped Attribute Certificate from Site B Attribute " 
    186               "Authority:\n%s" % attCert) 
    187                          
    188     def test07GetAttCertFromLocalAAInstance(self): 
    189         thisSection = 'test07GetAttCertFromLocalAAInstance' 
    190         aaPropFilePath = self.cfg.get(thisSection, 
    191                                       'attributeAuthorityPropFilePath')  
    192                    
    193         credWallet = NDGCredentialWallet(cfg=self.cfg.get('setUp',  
    194                                                           'cfgFilePath')) 
    195         credWallet.attributeAuthority = AttributeAuthority.fromPropertyFile( 
    196                                             propFilePath=aaPropFilePath) 
    197         attCert = credWallet.getAttCert() 
    198          
    199         # No user X.509 cert is set so the resulting Attribute Certificate 
    200         # user ID should be the same as that set for the wallet 
    201         assert(attCert.userId == credWallet.userId) 
    202         print("Attribute Certificate:\n%s" % attCert)   
    203  
    204     def test08Pickle(self): 
    205         credWallet = NDGCredentialWallet(cfg=self.cfg.get('setUp',  
    206                                                           'cfgFilePath')) 
    207  
    208         outFile = open(NDGCredentialWalletTestCase.PICKLE_FILEPATH, 'w') 
    209         pickle.dump(credWallet, outFile) 
    210         outFile.close() 
    211          
    212         inFile = open(NDGCredentialWalletTestCase.PICKLE_FILEPATH) 
    213         unpickledCredWallet = pickle.load(inFile) 
    214         self.assert_(unpickledCredWallet.userId == credWallet.userId) 
    215          
    21634 
    21735class SAMLCredentialWalletTestCase(BaseTestCase): 
Note: See TracChangeset for help on using the changeset viewer.