Ignore:
Timestamp:
30/03/10 13:22:59 (11 years ago)
Author:
pjkersha
Message:

Contains important fix for OpenIDProviderMiddleware - moved OpenIDResponse object from class member to session key to preserve separation between user sessions in sign in process. This bug was manifest in users being incorrectly redirected following login.

Location:
TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test
Files:
2 added
2 deleted
10 edited

Legend:

Unmodified
Added
Removed
  • TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/integration/__init__.py

    r6276 r6788  
    2020"/test_403": "test_403", 
    2121"/test_securedURI": "test_securedURI", 
    22 "/test_accessDeniedToSecuredURI": "test_accessDeniedToSecuredURI" 
     22"/test_accessDeniedToSecuredURI": "test_accessDeniedToSecuredURI", 
     23"/logout?ndg.security.logout.r=/test_logoutWithReturn2QueryArg":  
     24    "test_logoutWithReturn2QueryArg", 
     25"/test_logoutWithReturn2QueryArg": "test_logoutWithReturn2QueryArg" 
    2326    } 
    2427    header = """        <h1>Authorisation Integration Tests:</h1> 
     
    196199                        ('Content-length', str(len(response)))]) 
    197200        return response 
    198     
     201 
     202    def test_logoutWithReturn2QueryArg(self, environ, start_response): 
     203        """Test logout setting a return to argument to explicitly set the 
     204        URI to return to following the logout action 
     205        """ 
     206        response = """<html> 
     207    <head/> 
     208    <body> 
     209        <h1>Logged Out</h1> 
     210        <p>Successfully redirected to specified return to UIR query argument  
     211        ndg.security.logout.r=%s following logout.   
     212        <a href="/">Return to tests</a></p> 
     213    </body> 
     214</html> 
     215""" % environ['PATH_INFO'] 
     216 
     217        start_response('200 OK',  
     218                       [('Content-type', 'text/html'), 
     219                        ('Content-length', str(len(response)))]) 
     220        return response 
     221     
    199222    @classmethod 
    200223    def app_factory(cls, globalConfig, **localConfig): 
  • TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/integration/authz_lite/policy.xml

    r6063 r6788  
    88            <Attribute> 
    99                <Name>urn:siteA:security:authz:1.0:attr:staff</Name> 
    10                 <AttributeAuthorityURI>https://localhost:7443/AttributeAuthority/saml</AttributeAuthorityURI> 
     10                <AttributeAuthorityURI>https://localhost:7443/AttributeAuthority</AttributeAuthorityURI> 
    1111            </Attribute> 
    1212        </Attributes> 
     
    1717            <Attribute> 
    1818                <Name>urn:siteA:security:authz:1.0:attr:forbidden</Name> 
    19                 <AttributeAuthorityURI>https://localhost:7443/AttributeAuthority/saml</AttributeAuthorityURI> 
     19                <AttributeAuthorityURI>https://localhost:7443/AttributeAuthority</AttributeAuthorityURI> 
    2020            </Attribute> 
    2121            <Attribute> 
    2222                <Name>urn:siteA:security:authz:1.0:attr:keepout</Name> 
    23                 <AttributeAuthorityURI>https://localhost:7443/AttributeAuthority/saml</AttributeAuthorityURI> 
     23                <AttributeAuthorityURI>https://localhost:7443/AttributeAuthority</AttributeAuthorityURI> 
    2424            </Attribute> 
    2525        </Attributes> 
  • TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/integration/authz_lite/securedapp.ini

    r6605 r6788  
    4949beaker.session.data_dir = %(here)s/authn/beaker/sessions 
    5050 
    51 beaker.session.cookie_domain = .localhost 
     51#beaker.session.cookie_domain = .localhost 
    5252 
    5353[filter:AuthenticationFilter] 
     
    5757# Set redirect for OpenID Relying Party in the Security Services app instance 
    5858authN.redirectURI = https://localhost:7443/verify 
    59 # Test with an SSL endpoint 
    60 #authN.redirectURI = https://localhost/verify 
     59 
     60# Default URI to return to if middleware wasn't able to set via HTTP_REFERER or 
     61# passed return to query argument 
     62authN.sessionHandler.defaultLogoutReturnToURI = https://localhost:7443/ 
    6163 
    6264# AuthKit Set-up 
     
    7476 
    7577#authkit.cookie.params.expires = 2 
    76 authkit.cookie.params.domain = .localhost 
     78#authkit.cookie.params.domain = .localhost 
    7779 
    7880# environ key name for beaker session 
  • TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/integration/authz_lite/securityservices.ini

    r6615 r6788  
    2525 
    2626# Global Attribute Authority Settings 
    27 attributeAuthorityEnvironKeyName = ndg.security.server.attributeauthority.AttributeAuthority 
    2827attributeQueryInterfaceEnvironKeyName = ndg.security.server.attributeauthority.attributeQueryInterface 
    2928 
     
    5655# Ordering of filters and app is critical 
    5756[pipeline:main] 
    58 pipeline = wsseSignatureVerificationFilter  
    59                    AttributeAuthorityFilter  
    60                    AttributeAuthorityWsdlSoapBindingFilter 
    61            wsseSignatureFilter  
     57pipeline = AttributeAuthorityFilter  
    6258           AttributeAuthoritySamlSoapBindingFilter 
    6359                   SessionMiddlewareFilter 
     
    8278beaker.session.cookie_expires = True 
    8379 
    84 beaker.session.cookie_domain = .localhost 
     80#beaker.session.cookie_domain = .localhost 
    8581 
    8682# Key name for keying into environ dictionary 
     
    104100cookie.includeip = False 
    105101 
    106 cookie.params.domain = .localhost 
     102#cookie.params.domain = .localhost 
    107103 
    108104# SSL Client Certificate based authentication is invoked if the client passed 
     
    164160authkit.cookie.secret=9wvZObs9anUEhSIAnJNoY2iJq59FfYZr 
    165161authkit.cookie.signoutpath = /logout 
    166 authkit.cookie.params.domain = .localhost 
     162#authkit.cookie.params.domain = .localhost 
    167163 
    168164# Disable inclusion of client IP address from cookie signature due to  
     
    334330prefix = attributeAuthority. 
    335331 
    336 # Key name by which the WSDL SOAP based interface may reference this 
    337 # service 
    338 attributeAuthority.environKeyName = %(attributeAuthorityEnvironKeyName)s 
    339  
    340 # Key name for the SAML SOAP binding based interface to reference this 
    341 # service's attribute query method 
    342 attributeAuthority.environKeyNameAttributeQueryInterface: %(attributeQueryInterfaceEnvironKeyName)s 
    343  
    344 # Attribute Authority settings 
    345 # 'name' setting MUST agree with map config file 'thisHost' name attribute 
    346 attributeAuthority.name: Site A 
    347  
    348332# Lifetime is measured in seconds 
    349 attributeAuthority.attCertLifetime: 28800  
    350  
    351 # Allow an offset for clock skew between servers running  
    352 # security services. NB, measured in seconds - use a minus sign for time in the 
    353 # past 
    354 attributeAuthority.attCertNotBeforeOff: 0 
    355  
    356 # All Attribute Certificates issued are recorded in this dir 
    357 attributeAuthority.attCertDir: %(testConfigDir)s/attributeauthority/sitea/attributeCertificateLog 
    358  
    359 # Files in attCertDir are stored using a rotating file handler 
    360 # attCertFileLogCnt sets the max number of files created before the first is  
    361 # overwritten 
    362 attributeAuthority.attCertFileName: ac.xml 
    363 attributeAuthority.attCertFileLogCnt: 16 
    364 attributeAuthority.dnSeparator:/ 
    365  
    366 # Location of role mapping file 
    367 attributeAuthority.mapConfigFilePath: %(testConfigDir)s/attributeauthority/sitea/siteAMapConfig.xml 
     333attributeAuthority.assertionLifetime: 28800  
    368334 
    369335# Settings for custom AttributeInterface derived class to get user roles for given  
     
    373339#attributeAuthority.attributeInterface.className: TestUserRoles 
    374340 
     341# Key name for the SAML SOAP binding based interface to reference this 
     342# service's attribute query method 
     343attributeAuthority.environKeyNameAttributeQueryInterface: %(attributeQueryInterfaceEnvironKeyName)s 
     344 
    375345# SQLAlchemy Attribute Interface 
    376346attributeAuthority.attributeInterface.connectionString: %(dbConnectionString)s 
    377 attributeAuthority.attributeInterface.modName: ndg.security.server.attributeauthority 
    378 attributeAuthority.attributeInterface.className: SQLAlchemyAttributeInterface 
    379 attributeAuthority.attributeInterface.issuerName = /O=Site A/CN=Attribute Authority 
     347attributeAuthority.attributeInterface.className: ndg.security.server.attributeauthority.SQLAlchemyAttributeInterface 
    380348attributeAuthority.attributeInterface.samlSubjectSqlQuery = select count(*) from users where openid = '${userId}' 
    381349attributeAuthority.attributeInterface.samlAttribute2SqlQuery.1 = "urn:esg:first:name" "select firstname from users where openid = '${userId}'" 
     
    387355                                                           /CN=test/O=NDG/OU=BADC 
    388356 
    389 # Config for XML signature of Attribute Certificate 
    390 attributeAuthority.signingPriKeyFilePath: %(testConfigDir)s/attributeauthority/sitea/siteA-aa.key 
    391 attributeAuthority.signingCertFilePath: %(testConfigDir)s/attributeauthority/sitea/siteA-aa.crt 
    392 attributeAuthority.caCertFilePathList: %(testConfigDir)s/ca/ndg-test-ca.crt 
    393  
    394  
    395 # SOAP WSDL Based Binding to the Attribute Authority 
    396 [filter:AttributeAuthorityWsdlSoapBindingFilter] 
    397 paste.filter_app_factory = ndg.security.server.wsgi.attributeauthority:AttributeAuthoritySOAPBindingMiddleware.filter_app_factory 
    398 prefix = service.soap.binding. 
    399 attributeAuthoritySOAPBindingPrefix = attributeauthority.service.soap.binding. 
    400  
    401 service.soap.binding.referencedFilters = filter:wsseSignatureVerificationFilter 
    402 service.soap.binding.path = /AttributeAuthority 
    403 service.soap.binding.enableWSDLQuery = True 
    404 service.soap.binding.charset = utf-8 
    405 service.soap.binding.serviceSOAPBindingEnvironKeyName = ndg.security.server.wsgi.attributeauthority.AttributeAuthoritySOAPBindingMiddleware 
    406  
    407 attributeauthority.service.soap.binding.attributeAuthorityEnvironKeyName = %(attributeAuthorityEnvironKeyName)s 
    408 attributeauthority.service.soap.binding.wsseSignatureVerificationFilterID = filter:wsseSignatureVerificationFilter 
    409  
    410  
    411357# SAML SOAP Binding to the Attribute Authority 
    412358[filter:AttributeAuthoritySamlSoapBindingFilter] 
     
    419365saml.soapbinding.serialise = ndg.security.common.saml_utils.esg.xml.etree:EsgResponseElementTree.toXML 
    420366 
    421 saml.soapbinding.pathMatchList = /AttributeAuthority/saml 
     367saml.soapbinding.pathMatchList = /AttributeAuthority 
    422368saml.soapbinding.queryInterfaceKeyName = %(attributeQueryInterfaceEnvironKeyName)s 
    423369 
    424  
    425 #______________________________________________________________________________ 
    426 # WS-Security Signature Verification 
    427 [filter:wsseSignatureVerificationFilter] 
    428 paste.filter_app_factory = ndg.security.server.wsgi.wssecurity:SignatureVerificationFilter.filter_app_factory 
    429 filterID = %(__name__)s 
    430  
    431 # Settings for WS-Security SignatureHandler class used by this filter 
    432 wsseCfgFilePrefix = wssecurity 
    433  
    434 # Verify against known CAs - Provide a space separated list of file paths 
    435 wssecurity.caCertFilePathList=%(testConfigDir)s/ca/ndg-test-ca.crt 
    436  
    437  
    438 #______________________________________________________________________________ 
    439 # Apply WS-Security Signature  
    440 [filter:wsseSignatureFilter] 
    441 paste.filter_app_factory = ndg.security.server.wsgi.wssecurity:ApplySignatureFilter.filter_app_factory 
    442  
    443 # Reference the verification filter in order to be able to apply signature 
    444 # confirmation 
    445 referencedFilters = filter:wsseSignatureVerificationFilter 
    446 wsseSignatureVerificationFilterID = filter:wsseSignatureVerificationFilter 
    447  
    448 # Last filter in chain of SOAP handlers writes the response 
    449 writeResponse = True 
    450  
    451 # Settings for WS-Security SignatureHandler class used by this filter 
    452 wsseCfgFilePrefix = wssecurity 
    453  
    454 # Certificate associated with private key used to sign a message.  The sign  
    455 # method will add this to the BinarySecurityToken element of the WSSE header.   
    456 wssecurity.signingCertFilePath=%(testConfigDir)s/pki/wsse-server.crt 
    457  
    458 # PEM encoded private key file 
    459 wssecurity.signingPriKeyFilePath=%(testConfigDir)s/pki/wsse-server.key 
    460  
    461 # Set the ValueType for the BinarySecurityToken added to the WSSE header for a 
    462 # signed message.  See __setReqBinSecTokValType method and binSecTokValType  
    463 # class variable for options - it may be one of X509, X509v3, X509PKIPathv1 or  
    464 # give full namespace to alternative - see  
    465 # ZSI.wstools.Namespaces.OASIS.X509TOKEN 
    466 # 
    467 # binSecTokValType determines whether signingCert or signingCertChain  
    468 # attributes will be used. 
    469 wssecurity.reqBinSecTokValType=X509v3 
    470  
    471 # Add a timestamp element to an outbound message 
    472 wssecurity.addTimestamp=True 
    473  
    474 # For WSSE 1.1 - service returns signature confirmation containing signature  
    475 # value sent by client 
    476 wssecurity.applySignatureConfirmation=True 
     370# Clock skew for SAML Attribute Queries - allow clockSkew number of seconds 
     371# tolerance for query issueInstant parameter. Set here to 3 minutes 
     372saml.soapbinding.clockSkewTolerance: 180.0 
     373 
     374saml.soapbinding.issuer: /O=Site A/CN=Attribute Authority 
     375 
    477376 
    478377# Logging configuration 
  • TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/unit/__init__.py

    r6721 r6788  
    6868    SITEA_SSL_ATTRIBUTEAUTHORITY_PORTNUM = 5443 
    6969    SITEA_SSL_ATTRIBUTEAUTHORITY_SAML_URI = \ 
    70         'https://localhost:%d/AttributeAuthority/saml' % \ 
     70        'https://localhost:%d/AttributeAuthority' % \ 
    7171                                    SITEA_SSL_ATTRIBUTEAUTHORITY_PORTNUM 
    7272    SSL_CERT_DN = "/C=UK/ST=Oxfordshire/O=BADC/OU=Security/CN=localhost" 
  • TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/unit/wsgi/authz/README

    r6062 r6788  
    22======================================== 
    33These tests call ndg.security.server.wsgi.authz.SAMLAuthorizationMiddleware  
    4 and ndg.security.server.wsgi.authz.NDGAuthorizationMiddleware via 
    5 paste.fixture.  An attribute authority service needs to be running in order 
    6 for the middleware to check user attributes,  In a separate terminal start 
    7 this service: 
     4via paste.fixture.  An attribute authority service is also started as a separate 
     5thread. 
    86 
    9 $ python ../../../config/attributeauthority/sitea/siteAServerApp.py 
    10  
    11 Then, to run the tests: 
     7To run the tests: 
    128 
    139$ python test_authz.py 
    1410 
    15 P J Kershaw 22/05/09 
     11P J Kershaw 22/03/10 
  • TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/unit/wsgi/authz/pep-result-handler-test.ini

    r6284 r6788  
    3232# If omitted, DN of SSL Cert is used 
    3333pip.attributeQuery.issuerName =  
    34 pip.attributeQuery.clockSkew = 0. 
     34pip.attributeQuery.clockSkewTolerance = 0. 
    3535pip.attributeQuery.queryAttributes.0 = urn:siteA:security:authz:1.0:attr, , http://www.w3.org/2001/XMLSchema#string 
    3636pip.attributeQuery.sslCACertDir=%(testConfigDir)s/ca 
  • TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/unit/wsgi/authz/saml-policy.xml

    r6062 r6788  
    99                <Name>urn:siteA:security:authz:1.0:attr:staff</Name> 
    1010                <!-- Endpoint is for SOAP/SAML based ESG Interface --> 
    11                 <AttributeAuthorityURI>https://localhost:5443/AttributeAuthority/saml</AttributeAuthorityURI> 
     11                <AttributeAuthorityURI>https://localhost:5443/AttributeAuthority</AttributeAuthorityURI> 
    1212            </Attribute> 
    1313        </Attributes> 
     
    1818            <Attribute> 
    1919                <Name>urn:siteA:security:authz:1.0:attr:forbidden</Name> 
    20                 <AttributeAuthorityURI>https://localhost:5443/AttributeAuthority/saml</AttributeAuthorityURI> 
     20                <AttributeAuthorityURI>https://localhost:5443/AttributeAuthority</AttributeAuthorityURI> 
    2121            </Attribute> 
    2222            <Attribute> 
    2323                <Name>urn:siteA:security:authz:1.0:attr:keepout</Name> 
    24                 <AttributeAuthorityURI>https://localhost:5443/AttributeAuthority/saml</AttributeAuthorityURI> 
     24                <AttributeAuthorityURI>https://localhost:5443/AttributeAuthority</AttributeAuthorityURI> 
    2525            </Attribute> 
    2626        </Attributes> 
     
    3535            <Attribute> 
    3636                <Name>urn:siteA:security:authz:1.0:attr:admin</Name> 
    37                 <AttributeAuthorityURI>https://localhost:5443/AttributeAuthority/saml</AttributeAuthorityURI> 
     37                <AttributeAuthorityURI>https://localhost:5443/AttributeAuthority</AttributeAuthorityURI> 
    3838            </Attribute> 
    3939        </Attributes> 
  • TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/unit/wsgi/authz/saml-test.ini

    r6062 r6788  
    3131# If omitted, DN of SSL Cert is used 
    3232pip.attributeQuery.issuerName =  
    33 pip.attributeQuery.clockSkew = 0. 
     33pip.attributeQuery.clockSkewTolerance = 0. 
    3434pip.attributeQuery.queryAttributes.0 = urn:siteA:security:authz:1.0:attr, , http://www.w3.org/2001/XMLSchema#string 
    3535pip.attributeQuery.sslCACertDir=%(testConfigDir)s/ca 
  • TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/unit/wsgi/authz/test_authz.py

    r6284 r6788  
    3232from ndg.security.server.wsgi.authz.result_handler.redirect import \ 
    3333    HTTPRedirectPEPResultHandlerMiddleware 
    34 from ndg.security.server.wsgi.authz import (NdgPIPMiddlewareConfigError, 
    35                                             SamlPIPMiddlewareConfigError) 
     34from ndg.security.server.wsgi.authz import SamlPIPMiddlewareConfigError 
    3635from ndg.security.common.authz.msi import Response 
    3736 
     
    9897    def save(self): 
    9998        pass 
     99 
     100         
     101class TestAuthZMiddleware(object): 
     102    '''Test Application for the Authentication handler to protect''' 
     103    response = "Test Authorization application" 
     104        
     105    def __init__(self, app_conf, **local_conf): 
     106        pass 
     107     
     108    def __call__(self, environ, start_response): 
     109         
     110        if environ['PATH_INFO'] == '/test_401': 
     111            status = "401 Unauthorized" 
     112             
     113        elif environ['PATH_INFO'] == '/test_403': 
     114            status = "403 Forbidden" 
     115             
     116        elif environ['PATH_INFO'] == '/test_200': 
     117            status = "200 OK" 
     118             
     119        elif environ['PATH_INFO'] == '/test_accessDeniedToSecuredURI': 
     120            # Nb. AuthZ middleware should intercept the request and bypass this 
     121            # response 
     122            status = "200 OK" 
     123             
     124        elif environ['PATH_INFO'] == '/test_accessGrantedToSecuredURI': 
     125            status = "200 OK" 
     126        else: 
     127            status = "404 Not found" 
     128                 
     129        start_response(status, 
     130                       [('Content-length',  
     131                         str(len(TestAuthZMiddleware.response))), 
     132                        ('Content-type', 'text/plain')]) 
     133        return [TestAuthZMiddleware.response] 
     134 
     135 
     136class BeakerSessionStub(dict): 
     137    """Emulate beaker.session session object for purposes of the unit tests 
     138    """ 
     139    def save(self): 
     140        pass 
    100141  
    101142     
    102 class NdgWSGIAuthZTestCase(BaseTestCase): 
    103     INI_FILE = 'ndg-test.ini' 
     143class SamlWSGIAuthZTestCase(BaseTestCase): 
     144    INI_FILE = 'saml-test.ini' 
    104145    THIS_DIR = os.path.dirname(os.path.abspath(__file__)) 
    105     def __init__(self, *args, **kwargs): 
     146    def __init__(self, *args, **kwargs):        
    106147        BaseTestCase.__init__(self, *args, **kwargs) 
    107          
    108          
    109         wsgiapp = loadapp('config:'+NdgWSGIAuthZTestCase.INI_FILE,  
    110                           relative_to=NdgWSGIAuthZTestCase.THIS_DIR) 
     148 
     149         
     150        wsgiapp = loadapp('config:'+SamlWSGIAuthZTestCase.INI_FILE,  
     151                          relative_to=SamlWSGIAuthZTestCase.THIS_DIR) 
    111152        self.app = paste.fixture.TestApp(wsgiapp) 
    112153         
    113         self.startSiteAAttributeAuthority() 
    114          
     154        self.startSiteAAttributeAuthority(withSSL=True, 
     155            port=SamlWSGIAuthZTestCase.SITEA_SSL_ATTRIBUTEAUTHORITY_PORTNUM) 
     156         
     157 
    115158    def test01CatchNoBeakerSessionFound(self): 
    116159         
     
    119162        try: 
    120163            response = self.app.get('/test_200') 
    121         except NdgPIPMiddlewareConfigError, e: 
     164        except SamlPIPMiddlewareConfigError, e: 
    122165            print("ok - expected: %s exception: %s" % (e.__class__, e)) 
    123166        
     
    138181        # even though a user is set in the session 
    139182         
    140         extra_environ={'beaker.session.ndg.security': 
    141                        BeakerSessionStub(username='testuser')} 
     183        extra_environ = { 
     184            'beaker.session.ndg.security': 
     185                BeakerSessionStub(username=SamlWSGIAuthZTestCase.OPENID_URI) 
     186        } 
    142187        response = self.app.get('/test_401',  
    143188                                extra_environ=extra_environ, 
     
    150195        # even though a user is set in the session 
    151196         
    152         extra_environ={'beaker.session.ndg.security': 
    153                        BeakerSessionStub(username='testuser')} 
     197        extra_environ = { 
     198            'beaker.session.ndg.security': 
     199                BeakerSessionStub(username=SamlWSGIAuthZTestCase.OPENID_URI) 
     200        } 
    154201        response = self.app.get('/test_403',  
    155202                                extra_environ=extra_environ, 
     
    172219        # User is logged in but doesn't have the required credentials for  
    173220        # access 
    174         extra_environ={'beaker.session.ndg.security': 
    175                        BeakerSessionStub(username='testuser')} 
     221        extra_environ = { 
     222            'beaker.session.ndg.security': 
     223                BeakerSessionStub(username=SamlWSGIAuthZTestCase.OPENID_URI) 
     224        } 
    176225         
    177226        response = self.app.get('/test_accessDeniedToSecuredURI', 
    178227                                extra_environ=extra_environ, 
    179228                                status=403) 
     229        print response 
    180230        self.assert_("Insufficient privileges to access the " 
    181231                     "resource" in response) 
    182         print response 
    183232 
    184233    def test07AccessGrantedForSecuredURI(self): 
     
    186235        # User is logged in and has credentials for access to a URI secured 
    187236        # by the policy file 
    188         extra_environ={'beaker.session.ndg.security': 
    189                        BeakerSessionStub(username='testuser')} 
     237        extra_environ = { 
     238            'beaker.session.ndg.security': 
     239                BeakerSessionStub(username=SamlWSGIAuthZTestCase.OPENID_URI) 
     240        } 
    190241         
    191242        response = self.app.get('/test_accessGrantedToSecuredURI', 
     
    199250        # User is logged in but doesn't have the required credentials for  
    200251        # access 
    201         extra_environ={'beaker.session.ndg.security': 
    202                        BeakerSessionStub(username='testuser')} 
     252        extra_environ = { 
     253            'beaker.session.ndg.security': 
     254                BeakerSessionStub(username=SamlWSGIAuthZTestCase.OPENID_URI) 
     255        } 
    203256         
    204257        # Try this URI with the query arg admin=1.  This will be picked up 
     
    219272        print response 
    220273 
    221          
    222 class TestAuthZMiddleware(object): 
    223     '''Test Application for the Authentication handler to protect''' 
    224     response = "Test Authorization application" 
    225         
    226     def __init__(self, app_conf, **local_conf): 
    227         pass 
    228      
    229     def __call__(self, environ, start_response): 
    230          
    231         if environ['PATH_INFO'] == '/test_401': 
    232             status = "401 Unauthorized" 
    233              
    234         elif environ['PATH_INFO'] == '/test_403': 
    235             status = "403 Forbidden" 
    236              
    237         elif environ['PATH_INFO'] == '/test_200': 
    238             status = "200 OK" 
    239              
    240         elif environ['PATH_INFO'] == '/test_accessDeniedToSecuredURI': 
    241             # Nb. AuthZ middleware should intercept the request and bypass this 
    242             # response 
    243             status = "200 OK" 
    244              
    245         elif environ['PATH_INFO'] == '/test_accessGrantedToSecuredURI': 
    246             status = "200 OK" 
    247         else: 
    248             status = "404 Not found" 
    249                  
    250         start_response(status, 
    251                        [('Content-length',  
    252                          str(len(TestAuthZMiddleware.response))), 
    253                         ('Content-type', 'text/plain')]) 
    254         return [TestAuthZMiddleware.response] 
    255  
    256  
    257 class BeakerSessionStub(dict): 
    258     """Emulate beaker.session session object for purposes of the unit tests 
    259     """ 
    260     def save(self): 
    261         pass 
    262   
    263      
    264 class SamlWSGIAuthZTestCase(BaseTestCase): 
    265     INI_FILE = 'saml-test.ini' 
    266     THIS_DIR = os.path.dirname(os.path.abspath(__file__)) 
    267     def __init__(self, *args, **kwargs):        
    268         BaseTestCase.__init__(self, *args, **kwargs) 
    269  
    270          
    271         wsgiapp = loadapp('config:'+SamlWSGIAuthZTestCase.INI_FILE,  
    272                           relative_to=SamlWSGIAuthZTestCase.THIS_DIR) 
    273         self.app = paste.fixture.TestApp(wsgiapp) 
    274          
    275         self.startSiteAAttributeAuthority(withSSL=True, 
    276             port=SamlWSGIAuthZTestCase.SITEA_SSL_ATTRIBUTEAUTHORITY_PORTNUM) 
    277          
    278  
    279     def test01CatchNoBeakerSessionFound(self): 
    280          
    281         # PEPFilterConfigError is raised if no beaker.session is set in  
    282         # environ 
    283         try: 
    284             response = self.app.get('/test_200') 
    285         except SamlPIPMiddlewareConfigError, e: 
    286             print("ok - expected: %s exception: %s" % (e.__class__, e)) 
    287         
    288     def test02Ensure200WithNotLoggedInAndUnsecuredURI(self): 
    289          
    290         # Check the authZ middleware leaves the response alone if the URI  
    291         # is not matched in the policy 
    292          
    293         # Simulate a beaker.session in the environ 
    294         extra_environ={'beaker.session.ndg.security':BeakerSessionStub()} 
    295         response = self.app.get('/test_200', 
    296                                 extra_environ=extra_environ) 
    297  
    298     def test03Catch401WithLoggedIn(self): 
    299          
    300         # Check that the application being secured can raise a HTTP 401 
    301         # response and that this respected by the Authorization middleware 
    302         # even though a user is set in the session 
    303          
    304         extra_environ = { 
    305             'beaker.session.ndg.security': 
    306                 BeakerSessionStub(username=SamlWSGIAuthZTestCase.OPENID_URI) 
    307         } 
    308         response = self.app.get('/test_401',  
    309                                 extra_environ=extra_environ, 
    310                                 status=401) 
    311  
    312     def test04Catch403WithLoggedIn(self): 
    313          
    314         # Check that the application being secured can raise a HTTP 403 
    315         # response and that this respected by the Authorization middleware 
    316         # even though a user is set in the session 
    317          
    318         extra_environ = { 
    319             'beaker.session.ndg.security': 
    320                 BeakerSessionStub(username=SamlWSGIAuthZTestCase.OPENID_URI) 
    321         } 
    322         response = self.app.get('/test_403',  
    323                                 extra_environ=extra_environ, 
    324                                 status=403) 
    325  
    326     def test05Catch401WithNotLoggedInAndSecuredURI(self): 
    327          
    328         # AuthZ middleware grants access because the URI requested is not  
    329         # targeted in the policy 
    330          
    331         # AuthZ middleware checks for username key in session set by AuthN 
    332         # handler 
    333         extra_environ={'beaker.session.ndg.security':BeakerSessionStub()}         
    334         response = self.app.get('/test_accessDeniedToSecuredURI', 
    335                                 extra_environ=extra_environ, 
    336                                 status=401) 
    337          
    338     def test06AccessDeniedForSecuredURI(self): 
    339          
    340         # User is logged in but doesn't have the required credentials for  
    341         # access 
    342         extra_environ = { 
    343             'beaker.session.ndg.security': 
    344                 BeakerSessionStub(username=SamlWSGIAuthZTestCase.OPENID_URI) 
    345         } 
    346          
    347         response = self.app.get('/test_accessDeniedToSecuredURI', 
    348                                 extra_environ=extra_environ, 
    349                                 status=403) 
    350         self.assert_("Insufficient privileges to access the " 
    351                      "resource" in response) 
    352         print response 
    353  
    354     def test07AccessGrantedForSecuredURI(self): 
    355          
    356         # User is logged in and has credentials for access to a URI secured 
    357         # by the policy file 
    358         extra_environ = { 
    359             'beaker.session.ndg.security': 
    360                 BeakerSessionStub(username=SamlWSGIAuthZTestCase.OPENID_URI) 
    361         } 
    362          
    363         response = self.app.get('/test_accessGrantedToSecuredURI', 
    364                                 extra_environ=extra_environ, 
    365                                 status=200) 
    366         self.assert_(TestAuthZMiddleware.response in response) 
    367         print response 
    368  
    369     def test08AccessDeniedForAdminQueryArg(self): 
    370          
    371         # User is logged in but doesn't have the required credentials for  
    372         # access 
    373         extra_environ = { 
    374             'beaker.session.ndg.security': 
    375                 BeakerSessionStub(username=SamlWSGIAuthZTestCase.OPENID_URI) 
    376         } 
    377          
    378         # Try this URI with the query arg admin=1.  This will be picked up 
    379         # by the policy as a request requiring admin rights.  The request is 
    380         # denied as the user doesn't have these rights but this then calls 
    381         # into play the PEP result handler defined in this module, 
    382         # RedirectFollowingAccessDenied.  This class reinvokes the request 
    383         # but without the admin query argument.  Access is then granted for 
    384         # the redirected request 
    385         response = self.app.get('/test_accessGrantedToSecuredURI', 
    386                                 params={'admin': 1}, 
    387                                 extra_environ=extra_environ, 
    388                                 status=302) 
    389         try: 
    390             redirectResponse = response.follow(extra_environ=extra_environ) 
    391         except paste.fixture.AppError, e: 
    392             self.failIf(TestAuthZMiddleware.response not in response) 
    393         print response 
    394  
    395274 
    396275class PEPResultHandlerTestCase(BaseTestCase): 
Note: See TracChangeset for help on using the changeset viewer.