Add support for IdP-initiated login
[cascardo/ipsilon.git] / ipsilon / providers / saml2idp.py
index 93dcbc6..78e7778 100644 (file)
@@ -1,5 +1,6 @@
 # Copyright (C) 2014 Ipsilon project Contributors, for license see COPYING
 
+from ipsilon.login.common import LoginHelper
 from ipsilon.providers.common import ProviderBase, ProviderPageBase, \
     ProviderInstaller
 from ipsilon.providers.saml2.auth import AuthenticateRequest
@@ -8,7 +9,6 @@ from ipsilon.providers.saml2.admin import Saml2AdminPage
 from ipsilon.providers.saml2.rest import Saml2RestBase
 from ipsilon.providers.saml2.provider import IdentityProvider
 from ipsilon.providers.saml2.sessions import SAMLSessionFactory
-from ipsilon.util.data import SAML2SessionStore
 from ipsilon.tools.certs import Certificate
 from ipsilon.tools import saml2metadata as metadata
 from ipsilon.tools import files
@@ -29,14 +29,16 @@ cherrypy.tools.require_content_type = cherrypy.Tool('before_request_body',
 
 
 def is_lasso_ecp_enabled():
-    # Full ECP support appeared in lasso version 2.4.2
-    return lasso.checkVersion(2, 4, 2, lasso.CHECK_VERSION_NUMERIC)
+    # Look for an exported symbol we know was added with ECP support
+    return 'ECP_ERROR_MISSING_AUTHN_REQUEST' in dir(lasso)
 
 
-class SSO_SOAP(AuthenticateRequest):
+class SSO_SOAP(AuthenticateRequest, LoginHelper):
 
-    def __init__(self, *args, **kwargs):
-        super(SSO_SOAP, self).__init__(*args, **kwargs)
+    def __init__(self, site, provider, *args, **kwargs):
+        super(SSO_SOAP, self).__init__(site, provider, *args, **kwargs)
+        # pylint: disable=protected-access
+        self.info = provider._root.login.info
         self.binding = metadata.SAML2_SERVICE_MAP['sso-soap'][1]
 
     @cherrypy.tools.require_content_type(
@@ -50,13 +52,11 @@ class SSO_SOAP(AuthenticateRequest):
         self.debug("SSO_SOAP transaction provider=%s id=%s" %
                    (self.trans.provider, self.trans.transaction_id))
 
-        us = UserSession()
-        us.remote_login()
-        user = us.get_user()
-        self.debug("SSO_SOAP user=%s" % (user.name))
-
-        if not user:
+        username, auth_type = self.get_external_auth_info()
+        if not username:
             raise cherrypy.HTTPError(403, 'No user specified for SSO_SOAP')
+        self.debug("SSO_SOAP user=%s auth_type=%s" % (username, auth_type))
+        self.initialize_login_session(username, self.info, auth_type)
 
         soap_xml_doc = cherrypy.request.rfile.read()
         soap_xml_doc = soap_xml_doc.strip()
@@ -68,22 +68,25 @@ class SSO_SOAP(AuthenticateRequest):
 
 class Redirect(AuthenticateRequest):
 
-    def __init__(self, *args, **kwargs):
-        super(Redirect, self).__init__(*args, **kwargs)
+    def __init__(self, site, provider, *args, **kwargs):
+        super(Redirect, self).__init__(site, provider, *args, **kwargs)
         self.binding = metadata.SAML2_SERVICE_MAP['sso-redirect'][1]
 
     def GET(self, *args, **kwargs):
 
         query = cherrypy.request.query_string
 
-        login = self.saml2login(query)
+        spidentifier = kwargs.get('SPIdentifier')
+        relaystate = kwargs.get(lasso.SAML2_FIELD_RELAYSTATE)
+
+        login = self.saml2login(query, spidentifier, relaystate)
         return self.auth(login)
 
 
 class POSTAuth(AuthenticateRequest):
 
-    def __init__(self, *args, **kwargs):
-        super(POSTAuth, self).__init__(*args, **kwargs)
+    def __init__(self, site, provider, *args, **kwargs):
+        super(POSTAuth, self).__init__(site, provider, *args, **kwargs)
         self.binding = metadata.SAML2_SERVICE_MAP['sso-post'][1]
 
     def POST(self, *args, **kwargs):
@@ -113,7 +116,7 @@ class Continue(AuthenticateRequest):
         self.debug('Continue auth for %s' % user.name)
 
         if 'saml2_request' not in transdata:
-            self.debug("Couldn't find Request dump?!")
+            self.error("Couldn't find Request dump in transaction?!")
             # TODO: Return to SP with auth failed error
             raise cherrypy.HTTPError(400)
         dump = transdata['saml2_request']
@@ -121,10 +124,10 @@ class Continue(AuthenticateRequest):
         try:
             login = self.cfg.idp.get_login_handler(dump)
         except Exception, e:  # pylint: disable=broad-except
-            self.debug('Failed to load status from dump: %r' % e)
+            self.error('Failed to load login status from dump: %r' % e)
 
         if not login:
-            self.debug("Empty Request dump?!")
+            self.error("Empty login Request dump?!")
             # TODO: Return to SP with auth failed error
             raise cherrypy.HTTPError(400)
 
@@ -146,20 +149,20 @@ class Logout(LogoutRequest):
 
 class SSO(ProviderPageBase):
 
-    def __init__(self, *args, **kwargs):
-        super(SSO, self).__init__(*args, **kwargs)
-        self.Redirect = Redirect(*args, **kwargs)
-        self.POST = POSTAuth(*args, **kwargs)
-        self.Continue = Continue(*args, **kwargs)
-        self.SOAP = SSO_SOAP(*args, **kwargs)
+    def __init__(self, site, provider, *args, **kwargs):
+        super(SSO, self).__init__(site, provider)
+        self.Redirect = Redirect(site, provider, *args, **kwargs)
+        self.POST = POSTAuth(site, provider, *args, **kwargs)
+        self.Continue = Continue(site, provider, *args, **kwargs)
+        self.SOAP = SSO_SOAP(site, provider, *args, **kwargs)
 
 
 class SLO(ProviderPageBase):
 
-    def __init__(self, *args, **kwargs):
-        super(SLO, self).__init__(*args, **kwargs)
+    def __init__(self, site, provider, *args, **kwargs):
+        super(SLO, self).__init__(site, provider)
         self.debug('SLO init')
-        self.Redirect = Logout(*args, **kwargs)
+        self.Redirect = Logout(site, provider, *args, **kwargs)
 
 
 # one week
@@ -200,11 +203,11 @@ class Metadata(ProviderPageBase):
 
 class SAML2(ProviderPageBase):
 
-    def __init__(self, *args, **kwargs):
-        super(SAML2, self).__init__(*args, **kwargs)
-        self.metadata = Metadata(*args, **kwargs)
-        self.SSO = SSO(*args, **kwargs)
-        self.SLO = SLO(*args, **kwargs)
+    def __init__(self, site, provider, *args, **kwargs):
+        super(SAML2, self).__init__(site, provider)
+        self.metadata = Metadata(site, provider, *args, **kwargs)
+        self.SSO = SSO(site, provider, *args, **kwargs)
+        self.SLO = SLO(site, provider, *args, **kwargs)
 
 
 class IdpProvider(ProviderBase):
@@ -286,13 +289,8 @@ Provides SAML 2.0 authentication infrastructure. """
             logger.addHandler(lh)
             logger.setLevel(logging.DEBUG)
 
-        store = SAML2SessionStore(
-            database_url=self.get_config_value('session database url')
-        )
-        bt = cherrypy.process.plugins.BackgroundTask(
-            60, store.remove_expired_sessions
-        )
-        bt.start()
+    def get_providers(self):
+        return self.admin.providers
 
     @property
     def allow_self_registration(self):
@@ -351,6 +349,10 @@ Provides SAML 2.0 authentication infrastructure. """
         self.rest = Saml2RestBase(site, self)
         return self.page
 
+    def used_datastores(self):
+        # pylint: disable=protected-access
+        return [self.sessionfactory._ss]
+
     def init_idp(self):
         idp = None
         self.sessionfactory = SAMLSessionFactory(
@@ -361,7 +363,7 @@ Provides SAML 2.0 authentication infrastructure. """
             idp = IdentityProvider(self,
                                    sessionfactory=self.sessionfactory)
         except Exception, e:  # pylint: disable=broad-except
-            self.debug('Failed to init SAML2 provider: %r' % e)
+            self.error('Failed to init SAML2 provider: %r' % e)
             return None
 
         self._root.logout.add_handler(self.name, self.idp_initiated_logout)
@@ -377,7 +379,7 @@ Provides SAML 2.0 authentication infrastructure. """
             try:
                 idp.add_provider(sp)
             except Exception, e:  # pylint: disable=broad-except
-                self.debug('Failed to add SP %s: %r' % (sp['name'], e))
+                self.error('Failed to add SP %s: %r' % (sp['name'], e))
 
         return idp