Changeset 5681


Ignore:
Timestamp:
02/09/09 16:50:32 (10 years ago)
Author:
pjkersha
Message:

Integrated SOAP SAML Attribute Query interface into Attribute Authority Client unit tests.

Location:
TI12-security/trunk/python
Files:
3 added
7 edited

Legend:

Unmodified
Added
Removed
  • TI12-security/trunk/python/ndg_security_common/ndg/security/common/soap/client.py

    r5589 r5681  
    1313from ndg.security.common.soap import SOAPEnvelopeBase 
    1414 
    15 class HTTPException(Exception): 
     15class SOAPClientError(Exception): 
     16    """Base class for SOAP Client exceptions""" 
     17     
     18class HTTPException(SOAPClientError): 
    1619    """Server returned HTTP code error code""" 
    1720    def __init__(self, *arg, **kw): 
    1821        Exception.__init__(self, *arg, **kw) 
    1922        self.urllib2Response = None 
    20          
     23 
     24class SOAPParseError(SOAPClientError): 
     25    """Error parsing SOAP response""" 
     26     
     27            
    2128class SOAPClientBase(object): 
    2229    """Handle client request to a SOAP Service""" 
     
    109116        super(UrlLib2SOAPClient, self).__init__() 
    110117        self.__openerDirector = urllib2.OpenerDirector() 
     118        self.__openerDirector.add_handler(urllib2.UnknownHandler()) 
     119        self.__openerDirector.add_handler(urllib2.HTTPHandler()) 
    111120        self.__timeout = None 
    112121 
     
    173182        soapResponse.fileObject = response 
    174183        soapResponse.envelope = self.responseEnvelopeClass()   
    175         soapResponse.envelope.parse(soapResponse.fileObject) 
    176184         
     185        try: 
     186            soapResponse.envelope.parse(soapResponse.fileObject) 
     187        except Exception, e: 
     188            raise SOAPParseError("Error parsing response for request to [%s]: " 
     189                                 "%s" 
     190                                 % (soapRequest.url, e)) 
     191             
    177192        return soapResponse 
    178193 
  • TI12-security/trunk/python/ndg_security_server/ndg/security/server/attributeauthority.py

    r5663 r5681  
    11071107            return samlResponse 
    11081108         
    1109         # Gather requested attributes and pass to attribute interface for 
    1110         # retrieval of values 
    1111         requestedAttributeNames = [attribute.name  
    1112                                    for attribute in attributeQuery.attributes] 
    1113          
    11141109        try: 
    11151110            # Return a dictionary of name, value pairs 
    1116             attributes = self.attributeInterface.getAttributes( 
    1117                                         attributeQuery.subject.nameID.value, 
    1118                                         requestedAttributeNames, 
    1119                                         attributeQuery.issuer.value) 
     1111            self.attributeInterface.getAttributes(attributeQuery,  
     1112                                                  samlResponse, 
     1113                                                  self.attCertLifetime) 
     1114             
    11201115        except InvalidUserId, e: 
    11211116            log.exception(e) 
     
    11561151            # Server error in this case 
    11571152            raise  
    1158          
    1159         # Create a new assertion to hold the attributes to be returned 
    1160         assertion = Assertion() 
    1161          
    1162         assertion.version = SAMLVersion(SAMLVersion.VERSION_20) 
    1163         assertion.id = str(uuid4()) 
    1164         assertion.issueInstant = samlResponse.issueInstant 
    1165          
    1166         assertion.conditions = Conditions() 
    1167         assertion.conditions.notBefore = assertion.issueInstant 
    1168         assertion.conditions.notOnOrAfter = assertion.conditions.notBefore + \ 
    1169             timedelta(seconds=self.attCertLifetime) 
    1170          
    1171         assertion.subject = Subject()   
    1172         assertion.subject.nameID = NameID() 
    1173         assertion.subject.nameID.format = attributeQuery.subject.nameID.format 
    1174         assertion.subject.nameID.value = attributeQuery.subject.nameID.value 
    1175  
    1176         attributeStatement = AttributeStatement() 
    1177          
    1178         for samlAttribute in attributes: 
    1179             attributeStatement.attributes.append(samlAttribute) 
    1180   
    1181         assertion.attributeStatements.append(attributeStatement)        
    1182         samlResponse.assertions.append(assertion) 
    1183          
    1184         # Add mapping for ESG Group/Role Attribute Value to enable ElementTree 
    1185         # Attribute Value factory to render the XML output 
    1186         toXMLTypeMap = { 
    1187             XSGroupRoleAttributeValue: XSGroupRoleAttributeValueElementTree 
    1188         } 
    11891153 
    11901154        return samlResponse 
     
    16321596        raise NotImplementedError(self.getRoles.__doc__) 
    16331597  
    1634     def getAttributes(self, userId, requestedAttributeNames, requestorId): 
     1598    def getAttributes(self, attributeQuery, response, assertionLifetime): 
    16351599        """Virtual method should be implemented in a derived class to enable 
    16361600        AttributeAuthority.samlAttributeQuery - The derived method should  
     
    16381602        an exception 
    16391603         
    1640         @type userId: string  
    1641         @param userId: user identity e.g. user Distinguished Name 
    1642         @type requestedAttributeNames: list  
    1643         @param requestedAttributeNames: list of attribute names set in the  
    1644         attribute query 
    1645         @type requestorId: basestring 
    1646         @param requestorId: identity of the agent making the attribute query 
    1647         @rtype: saml.saml2.core.Attribute 
    1648         @return: list of attributes for the given user ID 
     1604        @type attributeQuery: saml.saml2.core.AttributeQuery  
     1605        @param userId: query containing requested attributes 
     1606        @type: saml.saml2.core.Response 
     1607        @param: Response - add an assertion with the list of attributes  
     1608        for the given subject ID in the query or set an error Status code and 
     1609        message 
    16491610        @raise AttributeInterfaceError: an error occured requesting  
    16501611        attributes 
  • TI12-security/trunk/python/ndg_security_server/ndg/security/server/wsgi/saml/__init__.py

    r5675 r5681  
    145145            return self._app(environ, start_response) 
    146146           
    147         # Ignore non-SOAP requests 
    148         if not SOAPAttributeInterfaceMiddleware.isSOAPMessage(environ): 
     147        # Ignore non-POST requests 
     148        if environ.get('REQUEST_METHOD') != 'POST': 
    149149            return self._app(environ, start_response) 
    150150         
  • TI12-security/trunk/python/ndg_security_test/ndg/security/test/config/attributeauthority/sitea/siteAUserRoles.py

    r5663 r5681  
    1111__revision__ = '$Id:siteAUserRoles.py 4371 2008-10-29 09:44:51Z pjkersha $' 
    1212 
     13from datetime import datetime, timedelta 
     14from uuid import uuid4 
     15 
    1316 
    1417from ndg.security.server.attributeauthority import AttributeInterface, \ 
     
    1619    UserIdNotKnown 
    1720from saml.common.xml import SAMLConstants 
    18 from saml.saml2.core import Attribute, XSStringAttributeValue 
     21from saml.saml2.core import Response, Assertion, Attribute, AttributeValue, \ 
     22    AttributeStatement, SAMLVersion, Subject, NameID, Issuer, AttributeQuery, \ 
     23    XSStringAttributeValue, XSGroupRoleAttributeValue, Conditions, Status, \ 
     24    StatusCode 
    1925 
    2026 
     
    6975        ]  
    7076 
    71     def getAttributes(self, userId, requestedAttributeNames, requestorId): 
     77    def getAttributes(self, attributeQuery, response, assertionLifetime): 
    7278        '''Test Attribute Authority SAML Attribute Query interface''' 
    7379         
     80        userId = attributeQuery.subject.nameID.value 
     81        requestedAttributeNames = [attribute.name  
     82                                   for attribute in attributeQuery.attributes] 
     83        requestorId = attributeQuery.issuer.value 
     84         
    7485        if userId not in TestUserRoles.VALID_USER_IDS: 
    75             raise UserIdNotKnown('User Id "%s" is not known to this authority' 
    76                                  % userId) 
     86            raise UserIdNotKnown('Subject Id "%s" is not known to this ' 
     87                                 'authority' % userId) 
    7788             
    7889        if requestorId not in TestUserRoles.VALID_REQUESTOR_IDS: 
     
    92103                                         'requestor "%s"' % requestorId) 
    93104         
    94         return TestUserRoles.SAML_ATTRIBUTES 
     105        # Create a new assertion to hold the attributes to be returned 
     106        assertion = Assertion() 
     107         
     108        assertion.version = SAMLVersion(SAMLVersion.VERSION_20) 
     109        assertion.id = str(uuid4()) 
     110        assertion.issueInstant = response.issueInstant 
     111         
     112        assertion.conditions = Conditions() 
     113        assertion.conditions.notBefore = assertion.issueInstant 
     114        assertion.conditions.notOnOrAfter = assertion.conditions.notBefore + \ 
     115            timedelta(seconds=assertionLifetime) 
     116         
     117        assertion.subject = Subject()   
     118        assertion.subject.nameID = NameID() 
     119        assertion.subject.nameID.format = attributeQuery.subject.nameID.format 
     120        assertion.subject.nameID.value = attributeQuery.subject.nameID.value 
     121 
     122        attributeStatement = AttributeStatement() 
     123         
     124        # Add test set of attributes 
     125        for attribute in TestUserRoles.SAML_ATTRIBUTES: 
     126            attributeStatement.attributes.append(attribute) 
     127  
     128        assertion.attributeStatements.append(attributeStatement)        
     129        response.assertions.append(assertion) 
     130  
  • TI12-security/trunk/python/ndg_security_test/ndg/security/test/unit/attributeauthority/test_attributeauthority.cfg

    r5465 r5681  
    4646issuingClntCertFilePath = $NDGSEC_TEST_CONFIG_DIR/pki/user.crt 
    4747userAttCertFilePathList = $NDGSEC_AA_UNITTEST_DIR/ac-clnt.xml 
     48 
  • TI12-security/trunk/python/ndg_security_test/ndg/security/test/unit/attributeauthorityclient/attAuthorityClientTest.cfg

    r5465 r5681  
    4848userAttCertFilePathList = $NDGSEC_AACLNT_UNITTEST_DIR/ac-clnt.xml 
    4949 
     50[test10SAMLAttributeQuery] 
     51uri = http://localhost:5000/attributeauthority/saml 
     52 
    5053[wsse] 
    5154# WS-Security settings for unit test AA clients 
  • TI12-security/trunk/python/ndg_security_test/ndg/security/test/unit/attributeauthorityclient/test_attributeauthorityclient.py

    r5290 r5681  
    1010__contact__ = "Philip.Kershaw@stfc.ac.uk" 
    1111__revision__ = '$Id:test_attributeauthorityclient.py 4372 2008-10-29 09:45:39Z pjkersha $' 
     12import logging 
     13logging.basicConfig() 
    1214 
    1315import unittest 
    1416import os, sys, getpass, re 
    15 import logging 
    16 logging.basicConfig() 
     17     
     18from os.path import expandvars as xpdVars 
     19from os.path import join as jnPath 
     20mkPath = lambda file: jnPath(os.environ['NDGSEC_AACLNT_UNITTEST_DIR'], file) 
     21 
     22from datetime import datetime 
     23from uuid import uuid4 
    1724 
    1825from ndg.security.test.unit import BaseTestCase 
     
    2431from ndg.security.common.utils.configfileparsers import \ 
    2532    CaseSensitiveConfigParser 
    26      
    27 from os.path import expandvars as xpdVars 
    28 from os.path import join as jnPath 
    29 mkPath = lambda file: jnPath(os.environ['NDGSEC_AACLNT_UNITTEST_DIR'], file) 
     33 
     34from saml.common.xml import SAMLConstants 
     35from saml.saml2.core import Response, Assertion, Attribute, AttributeValue, \ 
     36    AttributeStatement, SAMLVersion, Subject, NameID, Issuer, AttributeQuery, \ 
     37    XSStringAttributeValue, XSGroupRoleAttributeValue, Conditions, Status, \ 
     38    StatusCode 
     39     
     40from ndg.security.common.saml.bindings import SOAPBinding as SamlSoapBinding 
    3041 
    3142 
     
    282293                msgFile.write('Failed for "%s": %s\n' % (acFilePath, e)) 
    283294              
    284               
    285 class AttributeAuthorityClientTestSuite(unittest.TestSuite): 
    286     def __init__(self): 
    287         map = map(AttributeAuthorityClientTestCase, 
    288                   ( 
    289                     "test01GetHostInfo", 
    290                     "test02GetTrustedHostInfo", 
    291                     "test03GetTrustedHostInfoWithNoMatchingRoleFound", 
    292                     "test04GetTrustedHostInfoWithNoRole", 
    293                     "test05GetAllHostsInfo", 
    294                     "test06GetAttCert", 
    295                     "test07GetAttCertWithUserIdSet", 
    296                     "test08GetMappedAttCert", 
    297                     "test09GetMappedAttCertStressTest", 
    298                   )) 
    299         unittest.TestSuite.__init__(self, map) 
     295    def test10SAMLAttributeQuery(self): 
     296        _cfg = self.cfg['test10SAMLAttributeQuery'] 
     297         
     298        attributeQuery = AttributeQuery() 
     299        attributeQuery.version = SAMLVersion(SAMLVersion.VERSION_20) 
     300        attributeQuery.id = str(uuid4()) 
     301        attributeQuery.issueInstant = datetime.utcnow() 
     302         
     303        attributeQuery.issuer = Issuer() 
     304        attributeQuery.issuer.format = "urn:esg:issuer" 
     305        attributeQuery.issuer.value = "Site A"     
     306                         
     307        attributeQuery.subject = Subject()   
     308        attributeQuery.subject.nameID = NameID() 
     309        attributeQuery.subject.nameID.format = "urn:esg:openid" 
     310        attributeQuery.subject.nameID.value = \ 
     311                                    "https://openid.localhost/philip.kershaw" 
     312         
     313        fnAttribute = Attribute() 
     314        fnAttribute.name = "urn:esg:first:name" 
     315        fnAttribute.nameFormat = "http://www.w3.org/2001/XMLSchema#string" 
     316        fnAttribute.friendlyName = "FirstName" 
     317 
     318        attributeQuery.attributes.append(fnAttribute) 
     319     
     320        lnAttribute = Attribute() 
     321        lnAttribute.name = "urn:esg:last:name" 
     322        lnAttribute.nameFormat = "http://www.w3.org/2001/XMLSchema#string" 
     323        lnAttribute.friendlyName = "LastName" 
     324 
     325        attributeQuery.attributes.append(lnAttribute) 
     326     
     327        emailAddressAttribute = Attribute() 
     328        emailAddressAttribute.name = "urn:esg:email:address" 
     329        emailAddressAttribute.nameFormat = SAMLConstants.XSD_NS+"#"+\ 
     330                                    XSStringAttributeValue.TYPE_LOCAL_NAME 
     331        emailAddressAttribute.friendlyName = "emailAddress" 
     332 
     333        attributeQuery.attributes.append(emailAddressAttribute)                                    
     334 
     335        binding = SamlSoapBinding() 
     336        response = binding.attributeQuery(attributeQuery, _cfg['uri']) 
     337         
     338        self.assert_(response.status.statusCode.value==StatusCode.SUCCESS_URI) 
     339        print response 
     340         
    300341                                         
    301342if __name__ == "__main__": 
Note: See TracChangeset for help on using the changeset viewer.