Changeset 1343


Ignore:
Timestamp:
31/07/06 14:06:58 (13 years ago)
Author:
pjkersha
Message:

Working version of SecurityCGI with split ServiceProviderSecurityCGI and IdentityProviderSecurityCGI classes.

Tests/SecurityCGItest.py: added test for IdentityProviderSecurityCGI._returnCredsResponse()

www/cgi-bin/idp.py: call without named local var for IdPcgi?.

www/cgi-bin/sp.py: showCredsReceived renamed -> onCredsSet; fized returnURI link path.

NDG/SecurityCGI.py:

  • processFields - made lambdas for more complicated if conditions. Added extra case for where a cookie is

already present in the environment

  • showIdPsiteSelect - added bodyTxt keyword
  • showCredsReceived renamed onCredsSet - it's now called when a new cookie has been created from credentials

returned from IdP and also, if a security cookie already exists.

NDG/Session.py: fixed bug in UserSession?.createSecurityCookie - missed out 'raise' in no expiry time set error
block.

Location:
TI12-security/trunk/python
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • TI12-security/trunk/python/NDG/SecurityCGI.py

    r1340 r1343  
    9595                                  key to enable encryption of return traffic 
    9696                                  from NDG security WSs.  IF THIS KEYWORD IS 
    97                                   NOT SET, RETURN TRAFFIC IS UNENCRYPTED. 
     97                                  NOT SET, RETURN TRAFFIC IS NOT ENCRYPTED. 
    9898        clntPriKeyFilePath:       file path to client private key. 
    9999        clntPriKeyPwd:            password protecting the private key.  If no  
     
    390390        """Call appropriate actions according to the fields set""" 
    391391 
     392        # Check for security tags returned from Identity Provider URI 
     393        credTagsSet = lambda tags: \ 
     394            not [True for tag in UserSession.cookieTags if tag not in tags] 
     395          
     396        # Check for existing security cookie    
     397        credsPresent = lambda environ: 'HTTP_COOKIE' in environ and \ 
     398            UserSession.isValidSecurityCookie(environ['HTTP_COOKIE'])  
     399              
     400  
    392401        if self.requestURItag in self: 
    393402            # Request credentials from user's identity provider 
    394403            self._requestCreds(**kwargs) 
    395404 
    396         elif not [True for tag in UserSession.cookieTags if tag not in self]: 
     405        elif credTagsSet(self): 
    397406            # Credentials tags were set -  set a new cookie at service  
    398407            # provider site 
    399             encodedExpiry='expires' in self and self['expires'].value or None 
    400  
    401             self._receiveCredsResponse(encodedExpiry=encodedExpiry, **kwargs) 
    402  
     408            self._receiveCredsResponse(**kwargs) 
     409 
     410        elif credsPresent(os.environ): 
     411            self.onCredsSet(**kwargs) 
     412             
    403413        else: 
    404414            # Default to list of sites for user to select for login 
     
    408418    #_________________________________________________________________________ 
    409419    def showIdPsiteSelect(self, 
    410                           trustedIdPs=None, 
    411                           scriptName=None, 
    412                           contentTypeHdr=True, 
    413                           htmlTag=True, 
    414                           hdrTag=True, 
    415                           hdrTxt=_defStyle, 
    416                           bodyTag=True, 
    417                           pageTitle="Select your home site ..."): 
     420                      trustedIdPs=None, 
     421                      scriptName=None, 
     422                      contentTypeHdr=True, 
     423                      htmlTag=True, 
     424                      hdrTag=True, 
     425                      hdrTxt=_defStyle, 
     426                      bodyTag=True, 
     427                      bodyTxt="<h2>Security Credentials are Required</h2>", 
     428                      pageTitle="Select your home site ..."): 
    418429        """Display a list of Identity Provider sites for the user to select 
    419430        to retrieve their credentials.  The user must have an account with one 
     
    458469        if bodyTag: 
    459470            print "<body>" 
    460  
     471         
     472        if bodyTxt: 
     473            print bodyTxt 
     474             
    461475        # Form containing droplist for the trusted hosts 
    462476        print """    <form action="%s" method="POST"> 
     
    494508 
    495509    #_________________________________________________________________________ 
    496     def showCredsReceived(self,  
    497                           sessCookie, 
    498                           pageTitle='Credentials Received', 
    499                           hdrTxt=_defStyle, 
    500                           bodyTxt='NDG Security session cookie set'): 
    501         """Called from _receiveCredsResponse() once a cookie has been created. 
    502         Makes a page to set the cookie and display to the user that they have 
    503         been authenticated.  Derived class should override this method as 
    504         required""" 
    505          
    506         print """Content-type: text/html" 
     510    def onCredsSet(self,  
     511                   sessCookie=None, 
     512                   pageTitle='Credentials Set', 
     513                   hdrTxt=_defStyle, 
     514                   bodyTxt='<h2>NDG Security session cookie set</h2>'): 
     515        """This method is called when either: 
     516         
     517        a) a user security cookie is already present in the Service  
     518        Provider URI's environment. 
     519         
     520        or  
     521         
     522        b) a new cookie has been created from credentials returned from an 
     523        Identity Provider. 
     524         
     525        For b) this method should set the cookie in HTML sent to user's  
     526        browser. 
     527         
     528        This method can be overridden by a derived class.  From this point 
     529        on, the user is authenticated and a connection has been established to 
     530        their session manager so the authorisation steps to set up access to 
     531        a secured resource can now proceed.  Code in this method can initiate  
     532        these next steps. 
     533         
     534        Nb. If SP and IdP are in the same domain sessCookie will not be 
     535        set when the user authenticates because the cookie set at the  
     536        IdP login URI will be visible from the SP return URI as well. 
     537         
     538        sessCookie:    NDG Security Cookie passed as a SimpleCookie type.  If 
     539                       set, this method should set it in HTML output so that 
     540                       it is transfered to the user's browser. 
     541        pageTitle:     set a page title for the page output. 
     542        hdTxt:         set HTML within <head>...</head> 
     543        bodyTxt:       set HTML within <body>...</body> 
     544         
     545        pageTitle, hdrTxt and BodyTxt can be ignored completely in a method of 
     546        a derived class if required.""" 
     547         
     548        print """Content-type: text/html 
    507549%s 
    508550 
     
    515557    %s 
    516558</body> 
    517 </html>""" % (sessCookie.output(), pageTitle, hdrTxt, bodyTxt) 
     559</html>""" % (sessCookie and sessCookie.output() or '',  
     560              pageTitle,  
     561              hdrTxt,  
     562              bodyTxt) 
    518563 
    519564 
     
    619664 
    620665    #_________________________________________________________________________ 
    621     def _receiveCredsResponse(self, encodedExpiry=None): 
    622         """Remote site receives returned credentials and creates a new cookie 
    623         for its domain""" 
     666    def _receiveCredsResponse(self, encodedExpiry=None, **kwargs): 
     667        """Service Provider site receives returned credentials and creates a  
     668        new cookie for its domain""" 
     669         
     670        if not encodedExpiry and 'expires' in self: 
     671            encodedExpiry = self['expires'].value 
     672 
    624673        sessCookie = self._createCookie(encodedExpiry=encodedExpiry) 
    625         self.showCredsReceived(sessCookie) 
     674        self.onCredsSet(sessCookie=sessCookie, **kwargs) 
    626675         
    627676 
     
    792841 
    793842                                          
    794         if setCookie: 
    795             cookieTxt = sessCookie.output() + os.linesep 
    796         else: 
    797             cookieTxt = '' 
     843        cookieTxt = setCookie and sessCookie.output() + os.linesep or '' 
    798844 
    799845 
     
    802848        cookieDomain = sessCookie[UserSession.cookieTags[0]]['domain'] 
    803849        if cookieDomain and cookieDomain in returnURI: 
    804             credArgs = '' 
    805              
     850            credArgs = ''             
    806851        else: 
    807852            # returnURI is in a different domain - return the credentials 
     
    820865                  
    821866             
    822             print """Content-type: text/html 
     867        print """Content-type: text/html 
    823868%s 
    824869<html> 
  • TI12-security/trunk/python/NDG/Session.py

    r1340 r1343  
    355355             
    356356        elif not expiryStr or not isinstance(expiryStr, basestring): 
    357             UserSessionError, "No cookie expiry was set" 
     357            raise UserSessionError, "No cookie expiry was set" 
    358358             
    359359             
  • TI12-security/trunk/python/Tests/SecurityCGItest.py

    r1340 r1343  
    1313import unittest 
    1414import os 
     15import base64 
     16from datetime import datetime 
     17from datetime import timedelta 
     18from NDG.Session import UserSession, UserSessionError 
    1519 
    1620from NDG.SecurityCGI import IdentityProviderSecurityCGI, \ 
     
    2125 
    2226    def setUp(self): 
    23         returnURI = "https://gabriel.bnsc.rl.ac.uk/sp.py" 
     27        self.returnURI = "https://gabriel.bnsc.rl.ac.uk/sp.py" 
    2428         
    2529        smWSDLuri = "http://gabriel.bnsc.rl.ac.uk/sessionMgr.wsdl" 
     
    4145         
    4246        self.spCGI = ServiceProviderSecurityCGI(os.path.basename(__file__), 
    43                                         returnURI, 
     47                                        self.returnURI, 
    4448                                        aaWSDLuri, 
    4549                                        aaPubKeyFilePath=aaPubKeyFilePath, 
     
    4852                                        clntPriKeyPwd=clntPriKeyPwd) 
    4953         
     54        tagsDict = {}.fromkeys(UserSession.cookieTags, 
     55                               base64.urlsafe_b64encode(os.urandom(64))) 
     56        dtExpiry = datetime.utcnow() + timedelta(seconds=7200) 
     57        self.sessCookie = UserSession.createSecurityCookie(dtExpiry=dtExpiry, 
     58                                                           **tagsDict) 
     59 
    5060 
    5161    def testIdPshowLogin(self): 
     
    5969    def testSPshowIdPsiteSelect(self): 
    6070         
    61         #import pdb;pdb.set_trace() 
    6271        try: 
    6372            self.spCGI.showIdPsiteSelect() 
     
    6675            self.fail(str(e)) 
    6776 
    68     def testSPshowCredsReceived(self): 
     77    def testSPonCredsSet(self): 
     78         
     79        try:             
     80            self.spCGI.onCredsSet(sessCookie=self.sessCookie) 
     81             
     82        except Exception, e: 
     83            self.fail(str(e)) 
     84 
     85    def test_returnCredsResponse(self): 
    6986         
    7087        try: 
    71             import base64 
    72             from NDG.Session import UserSession, UserSessionError 
    73              
    74             tagsDict = {}.fromkeys(UserSession.cookieTags, 
    75                                    base64.urlsafe_b64encode(os.urandom(64))) 
    76             sessCookie =  UserSession.createSecurityCookie(**tagsDict) 
    77             self.spCGI.showCredsReceived(sessCookie) 
     88            self.idpCGI._returnCredsResponse(self.sessCookie, 
     89                         self.returnURI, 
     90                         setCookie=True, 
     91                         pageTitle="Return Creds Unit Test", 
     92                         redirectMsg="Unit Test: Redirecting Credentials") 
    7893             
    7994        except Exception, e: 
  • TI12-security/trunk/python/www/cgi-bin/idp.py

    r1340 r1343  
    3434    clntPriKeyFilePath = "../certs/GabrielCGI-key.pem" 
    3535 
    36     idpCGI = IdPcgi(os.path.basename(__file__), 
    37                     smWSDLuri, 
    38                     smPubKeyFilePath=smPubKeyFilePath, 
    39                     clntPubKeyFilePath=clntPubKeyFilePath, 
    40                     clntPriKeyFilePath=clntPriKeyFilePath) 
    41     idpCGI() 
     36    IdPcgi(os.path.basename(__file__), 
     37           smWSDLuri, 
     38           smPubKeyFilePath=smPubKeyFilePath, 
     39           clntPubKeyFilePath=clntPubKeyFilePath, 
     40           clntPriKeyFilePath=clntPriKeyFilePath)() 
  • TI12-security/trunk/python/www/cgi-bin/sp.py

    r1340 r1343  
    2929 
    3030    #_________________________________________________________________________ 
    31     def showCredsReceived(self, 
    32                               sessCookie, 
    33                                                   pageTitle='Credentials returned from IdP', 
    34                           bodyTxt='New Cookie set from credentials'): 
    35         """Called from receiveCredsResponse() once a cookie has been created. 
    36         Makes a page to set the cookie and display to the user that they have 
    37         been authenticated.  Derived class should override this method as 
    38         required""" 
    39         super(SPcgi, self).showCredsReceived(sessCookie, 
    40                                              pageTitle=pageTitle, 
    41                                              bodyTxt=bodyTxt) 
     31    def onCredsSet(self, 
     32                   sessCookie=None, 
     33                                   pageTitle='Credentials returned from IdP', 
     34                   bodyTxt='<h2>NDG Security Cookie is present</h2>'): 
     35         
     36        super(SPcgi, self).onCredsSet(sessCookie=sessCookie, 
     37                                      pageTitle=pageTitle, 
     38                                      bodyTxt=bodyTxt) 
    4239 
    4340 
     
    4542if __name__ == "__main__": 
    4643 
    47     returnURI = 'https://gabriel.bnsc.rl.ac.uk/sp.py' 
     44    returnURI = 'https://gabriel.bnsc.rl.ac.uk/cgi-bin/sp.py' 
    4845    aaWSDL = 'http://gabriel.bnsc.rl.ac.uk/attAuthority.wsdl' 
    4946    aaPubKeyFilePath = "/usr/local/NDG/conf/certs/gabriel-aa-cert.pem" 
     
    5249    clntPriKeyFilePath = "../certs/GabrielCGI-key.pem" 
    5350 
    54     spCGI = SPcgi(os.path.basename(__file__), 
    55                   returnURI, 
    56                   aaWSDL, 
    57                   aaPubKeyFilePath=aaPubKeyFilePath, 
    58                   clntPubKeyFilePath=clntPubKeyFilePath, 
    59                   clntPriKeyFilePath=clntPriKeyFilePath) 
    60     spCGI() 
     51    SPcgi(os.path.basename(__file__), 
     52          returnURI, 
     53          aaWSDL, 
     54          aaPubKeyFilePath=aaPubKeyFilePath, 
     55          clntPubKeyFilePath=clntPubKeyFilePath, 
     56          clntPriKeyFilePath=clntPriKeyFilePath)() 
     57 
Note: See TracChangeset for help on using the changeset viewer.