Changeset 7154


Ignore:
Timestamp:
01/07/10 16:59:59 (9 years ago)
Author:
pjkersha
Message:

Incomplete - task 2: XACML-Security Integration

  • added test_attributeservice_paster - tests an attribute service over an SSL connection
Location:
TI12-security/trunk/ndg_saml/ndg/saml
Files:
7 added
8 edited

Legend:

Unmodified
Added
Removed
  • TI12-security/trunk/ndg_saml/ndg/saml/saml2/binding/soap/client/attributequery.py

    r7130 r7154  
    121121    def __init__(self, **kw): 
    122122        if not AttributeQuerySslSOAPBinding.SSL_CONTEXT_PROXY_SUPPORT: 
    123             raise ImportError("ndg.security.common.utils.m2crypto import " 
     123            raise ImportError("ndg.saml.utils.m2crypto import " 
    124124                              "failed - missing M2Crypto package?") 
    125125         
  • TI12-security/trunk/ndg_saml/ndg/saml/test/binding/__init__.py

    r7140 r7154  
     1"""NDG SAML SOAP Binding unit test package 
     2 
     3NERC DataGrid Project 
     4""" 
     5__author__ = "P J Kershaw" 
     6__date__ = "30/06/10" 
     7__copyright__ = "(C) 2010 Science and Technology Facilities Council" 
     8__license__ = "http://www.apache.org/licenses/LICENSE-2.0" 
     9__contact__ = "Philip.Kershaw@stfc.ac.uk" 
     10__revision__ = '$Id:$' 
  • TI12-security/trunk/ndg_saml/ndg/saml/test/binding/soap/__init__.py

    r7143 r7154  
    1 """NDG SAML 
    2  
    3 Test SAML Attribute Query Interface 
     1"""NDG SAML SOAP Binding unit test package 
    42 
    53NERC DataGrid Project 
     
    1311import os 
    1412import unittest 
     13import socket 
    1514import paste.fixture 
    1615from paste.deploy import loadapp 
     16 
     17from ndg.soap.test import PasteDeployAppServer 
    1718 
    1819 
     
    3233 
    3334 
    34 class SoapSamlInterfaceMiddlewareTestCase(unittest.TestCase): 
     35class WithPasteFixtureBaseTestCase(unittest.TestCase): 
     36    """Base class for testing SAML SOAP Binding Query/Response interface 
     37    using a Paste Deploy ini file and Paste Fixture 
     38    """ 
    3539    HERE_DIR = os.path.dirname(os.path.abspath(__file__)) 
    36     CONFIG_FILENAME = 'test.ini' 
     40    CONFIG_FILENAME = None # Set in derived class 
    3741     
    3842    def __init__(self, *args, **kwargs): 
     
    4347          
    4448        unittest.TestCase.__init__(self, *args, **kwargs) 
     49         
     50     
     51class WithPasterBaseTestCase(unittest.TestCase): 
     52    """Base class for testing SAML SOAP Binding Query/Response interface 
     53    using a Paste Deploy ini file and Paste Fixture 
     54    """ 
     55    THIS_DIR = os.path.dirname(os.path.abspath(__file__)) 
     56    CONFIG_FILENAME = None # Set in derived class 
     57    SERVICE_PORTNUM = 5443 
     58    SERVER_CERT_FILEPATH = os.path.join(THIS_DIR, 'localhost.crt') 
     59    SERVER_PRIKEY_FILEPATH = os.path.join(THIS_DIR, 'localhost.key') 
     60     
     61    def __init__(self, *arg, **kw): 
     62        withSSL = kw.pop('withSSL', False) 
     63        unittest.TestCase.__init__(self, *arg, **kw) 
     64         
     65        self.services = [] 
     66        self.disableServiceStartup = False 
     67        cfgFilePath = os.path.join(self.__class__.THIS_DIR,  
     68                                   self.__class__.CONFIG_FILENAME) 
     69         
     70        self.addService(cfgFilePath=cfgFilePath, 
     71                        withSSL=withSSL, 
     72                        port=self.__class__.SERVICE_PORTNUM) 
     73         
     74    def addService(self, *arg, **kw): 
     75        """Utility for setting up threads to run Paste HTTP based services with 
     76        unit tests 
     77         
     78        @param arg: tuple contains ini file path setting for the service 
     79        @type arg: tuple 
     80        @param kw: keywords including "port" - port number to run the service  
     81        from 
     82        @type kw: dict 
     83        """ 
     84        if self.disableServiceStartup: 
     85            return 
     86         
     87        withSSL = kw.pop('withSSL', False) 
     88        if withSSL: 
     89            from OpenSSL import SSL 
     90             
     91            certFilePath = self.__class__.SERVER_CERT_FILEPATH 
     92            priKeyFilePath = self.__class__.SERVER_PRIKEY_FILEPATH 
     93             
     94            kw['ssl_context'] = SSL.Context(SSL.SSLv23_METHOD) 
     95            kw['ssl_context'].set_options(SSL.OP_NO_SSLv2) 
     96         
     97            kw['ssl_context'].use_privatekey_file(priKeyFilePath) 
     98            kw['ssl_context'].use_certificate_file(certFilePath) 
     99         
     100        try: 
     101            self.services.append(PasteDeployAppServer(*arg, **kw)) 
     102            self.services[-1].startThread() 
     103             
     104        except socket.error: 
     105            pass 
     106 
     107    def __del__(self): 
     108        """Stop any services started with the addService method and clean up 
     109        the CA directory following the trust roots call 
     110        """ 
     111        if hasattr(self, 'services'): 
     112            for service in self.services: 
     113                service.terminateThread() 
  • TI12-security/trunk/ndg_saml/ndg/saml/test/binding/soap/attribute-interface.ini

    r7148 r7154  
    3636paste.filter_app_factory = ndg.saml.test.binding.soap.test_attributeservice:TestAttributeServiceMiddleware 
    3737queryInterfaceKeyName = attributeQueryInterface 
     38 
     39# Logging configuration 
     40[loggers] 
     41keys = root, ndg 
     42 
     43[handlers] 
     44keys = console 
     45 
     46[formatters] 
     47keys = generic 
     48 
     49[logger_root] 
     50level = INFO 
     51handlers = console 
     52 
     53[logger_ndg] 
     54level = DEBUG 
     55handlers =  
     56qualname = ndg 
     57 
     58[handler_console] 
     59class = StreamHandler 
     60args = (sys.stderr,) 
     61level = NOTSET 
     62formatter = generic 
     63 
     64[formatter_generic] 
     65format = %(asctime)s.%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s 
     66datefmt = %Y/%m/%d %H:%M:%S 
  • TI12-security/trunk/ndg_saml/ndg/saml/test/binding/soap/authz-decision-interface.ini

    r7148 r7154  
    4040queryInterfaceKeyName = AUTHZ_DECISION_QUERY_FUNC 
    4141 
     42# Logging configuration 
     43[loggers] 
     44keys = root, ndg 
     45 
     46[handlers] 
     47keys = console 
     48 
     49[formatters] 
     50keys = generic 
     51 
     52[logger_root] 
     53level = INFO 
     54handlers = console 
     55 
     56[logger_ndg] 
     57level = DEBUG 
     58handlers =  
     59qualname = ndg 
     60 
     61[handler_console] 
     62class = StreamHandler 
     63args = (sys.stderr,) 
     64level = NOTSET 
     65formatter = generic 
     66 
     67[formatter_generic] 
     68format = %(asctime)s.%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s 
     69datefmt = %Y/%m/%d %H:%M:%S 
  • TI12-security/trunk/ndg_saml/ndg/saml/test/binding/soap/test_attributeservice.py

    r7149 r7154  
    2323from ndg.saml.xml import XMLConstants 
    2424from ndg.saml.xml.etree import AttributeQueryElementTree, ResponseElementTree 
    25 from ndg.saml.test.binding.soap import SoapSamlInterfaceMiddlewareTestCase 
     25from ndg.saml.test.binding.soap import WithPasteFixtureBaseTestCase 
    2626 
    2727 
     
    161161 
    162162class SOAPAttributeInterfaceMiddlewareTestCase( 
    163                                         SoapSamlInterfaceMiddlewareTestCase): 
     163                                        WithPasteFixtureBaseTestCase): 
    164164    CONFIG_FILENAME = 'attribute-interface.ini' 
    165165    SERVICE_URI = '/attributeauthority' 
  • TI12-security/trunk/ndg_saml/ndg/saml/test/binding/soap/test_authzservice.py

    r7149 r7154  
    2323from ndg.saml.xml.etree import (AuthzDecisionQueryElementTree,  
    2424                                ResponseElementTree) 
    25 from ndg.saml.test.binding.soap import SoapSamlInterfaceMiddlewareTestCase 
     25from ndg.saml.test.binding.soap import WithPasteFixtureBaseTestCase 
    2626 
    2727 
     
    110110     
    111111class SOAPAuthzDecisionInterfaceMiddlewareTestCase( 
    112                                         SoapSamlInterfaceMiddlewareTestCase): 
     112                                        WithPasteFixtureBaseTestCase): 
    113113    CONFIG_FILENAME = 'authz-decision-interface.ini' 
    114114    RESOURCE_URI = TestAuthorisationServiceMiddleware.RESOURCE_URI 
  • TI12-security/trunk/ndg_saml/ndg/saml/test/binding/soap/test_queryresponseinterface.py

    r7152 r7154  
    1 """SAML Generic SOAP Binding Query/Response Interface unit test package 
     1"""SAML Generic SOAP Binding Query/Response Interface unit test module 
    22 
    33NERC DataGrid Project 
     
    287287        self.assert_(response.assertions[0].subject.nameID.value == \ 
    288288                     attributeQuery.subject.nameID.value) 
    289        
    290     def test02AttributeQueryWithSOAPClient(self): 
    291              
    292         # Thread a separate attribute authority instance 
    293         self.startSiteAAttributeAuthority() 
    294            
    295         client = UrlLib2SOAPClient() 
    296          
    297         # ElementTree based envelope class 
    298         client.responseEnvelopeClass = SOAPEnvelope 
    299          
    300         request = UrlLib2SOAPRequest() 
    301         request.url = 'http://localhost:5000/AttributeAuthority' 
    302         request.envelope = SOAPEnvelope() 
    303         request.envelope.create() 
    304          
    305         # Make an attribute query 
    306         attributeQuery = AttributeQuery() 
    307         attributeQuery.version = SAMLVersion(SAMLVersion.VERSION_20) 
    308         attributeQuery.id = str(uuid4()) 
    309         attributeQuery.issueInstant = datetime.utcnow() 
    310          
    311         attributeQuery.issuer = Issuer() 
    312         attributeQuery.issuer.format = Issuer.X509_SUBJECT 
    313         attributeQuery.issuer.value = \ 
    314                         "/O=NDG/OU=BADC/CN=attributeauthority.badc.rl.ac.uk" 
    315  
    316         attributeQuery.subject = Subject()   
    317         attributeQuery.subject.nameID = NameID() 
    318         attributeQuery.subject.nameID.format = SamlSoapBindingApp.NAMEID_FORMAT 
    319         attributeQuery.subject.nameID.value = \ 
    320                             "https://esg.prototype.ucar.edu/myopenid/testUser" 
    321          
    322         # special case handling for 'FirstName' attribute 
    323         fnAttribute = Attribute() 
    324         fnAttribute.name = SamlSoapBindingApp.FIRSTNAME_ATTRNAME 
    325         fnAttribute.nameFormat = "http://www.w3.org/2001/XMLSchema#string" 
    326         fnAttribute.friendlyName = "FirstName" 
    327  
    328         attributeQuery.attributes.append(fnAttribute) 
    329      
    330         # special case handling for 'LastName' attribute 
    331         lnAttribute = Attribute() 
    332         lnAttribute.name = SamlSoapBindingApp.LASTNAME_ATTRNAME 
    333         lnAttribute.nameFormat = "http://www.w3.org/2001/XMLSchema#string" 
    334         lnAttribute.friendlyName = "LastName" 
    335  
    336         attributeQuery.attributes.append(lnAttribute) 
    337      
    338         # special case handling for 'LastName' attribute 
    339         emailAddressAttribute = Attribute() 
    340         emailAddressAttribute.name = SamlSoapBindingApp.EMAILADDRESS_ATTRNAME 
    341         emailAddressAttribute.nameFormat = XMLConstants.XSD_NS+"#"+\ 
    342                                     XSStringAttributeValue.TYPE_LOCAL_NAME 
    343         emailAddressAttribute.friendlyName = "emailAddress" 
    344  
    345         attributeQuery.attributes.append(emailAddressAttribute)                                    
    346          
    347         attributeQueryElem = AttributeQueryElementTree.toXML(attributeQuery) 
    348  
    349         # Attach query to SOAP body 
    350         request.envelope.body.elem.append(attributeQueryElem) 
    351          
    352         from M2Crypto.m2urllib2 import HTTPSHandler 
    353         from urllib2 import URLError 
    354  
    355         client.openerDirector.add_handler(HTTPSHandler()) 
    356         try: 
    357             response = client.send(request) 
    358         except URLError, e: 
    359             self.fail("Error calling Attribute Service") 
    360          
    361         print("Response from server:\n\n%s" % response.envelope.serialize()) 
    362          
    363         if len(response.envelope.body.elem) != 1: 
    364             self.fail("Expecting single child element is SOAP body") 
    365              
    366         if QName.getLocalPart(response.envelope.body.elem[0].tag)!='Response': 
    367             self.fail('Expecting "Response" element in SOAP body') 
    368              
    369         response = ResponseElementTree.fromXML(response.envelope.body.elem[0]) 
    370         self.assert_(response) 
    371289 
    372290    def _parseResponse(self, responseStr): 
Note: See TracChangeset for help on using the changeset viewer.