Factor out LogoutInitiator class, simpler API to get ACS by binding.
[shibboleth/sp.git] / shibsp / handler / impl / SAML2LogoutInitiator.cpp
index ff813d3..cba23f6 100644 (file)
@@ -1,6 +1,6 @@
 /*
- *  Copyright 2001-2007 Internet2
- * 
+ *  Copyright 2001-2010 Internet2
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
@@ -16,7 +16,7 @@
 
 /**
  * SAML2LogoutInitiator.cpp
- * 
+ *
  * Triggers SP-initiated logout for SAML 2.0 sessions.
  */
 
 #include "ServiceProvider.h"
 #include "SessionCache.h"
 #include "handler/AbstractHandler.h"
-#include "handler/LogoutHandler.h"
+#include "handler/LogoutInitiator.h"
 
 #ifndef SHIBSP_LITE
 # include "binding/SOAPClient.h"
+# include "metadata/MetadataProviderCriteria.h"
+# include "security/SecurityPolicy.h"
+# include <saml/exceptions.h>
 # include <saml/SAMLConfig.h>
 # include <saml/saml2/core/Protocols.h>
 # include <saml/saml2/binding/SAML2SOAPClient.h>
 # include <saml/saml2/metadata/EndpointManager.h>
+# include <saml/saml2/metadata/Metadata.h>
 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
 using namespace opensaml::saml2;
 using namespace opensaml::saml2p;
@@ -53,8 +57,8 @@ namespace shibsp {
     #pragma warning( push )
     #pragma warning( disable : 4250 )
 #endif
-    
-    class SHIBSP_DLLLOCAL SAML2LogoutInitiator : public AbstractHandler, public LogoutHandler
+
+    class SHIBSP_DLLLOCAL SAML2LogoutInitiator : public AbstractHandler, public LogoutInitiator
     {
     public:
         SAML2LogoutInitiator(const DOMElement* e, const char* appId);
@@ -66,16 +70,14 @@ namespace shibsp {
             }
 #endif
         }
-        
+
         void setParent(const PropertySet* parent);
         void receive(DDF& in, ostream& out);
         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
 
-#ifndef SHIBSP_LITE
-        const char* getType() const {
-            return "LogoutInitiator";
+        const XMLCh* getProtocolFamily() const {
+            return samlconstants::SAML20P_NS;
         }
-#endif
 
     private:
         pair<bool,long> doRequest(
@@ -85,7 +87,7 @@ namespace shibsp {
         string m_appId;
 #ifndef SHIBSP_LITE
         LogoutRequest* buildRequest(
-            const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder=NULL
+            const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder=nullptr
             ) const;
 
         XMLCh* m_outgoing;
@@ -108,7 +110,7 @@ namespace shibsp {
 SAML2LogoutInitiator::SAML2LogoutInitiator(const DOMElement* e, const char* appId)
     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".LogoutInitiator.SAML2")), m_appId(appId),
 #ifndef SHIBSP_LITE
-        m_outgoing(NULL),
+        m_outgoing(nullptr),
 #endif
         m_protocol(samlconstants::SAML20P_NS)
 {
@@ -137,9 +139,15 @@ SAML2LogoutInitiator::SAML2LogoutInitiator(const DOMElement* e, const char* appI
             try {
                 auto_ptr_char b(start);
                 MessageEncoder * encoder =
-                    SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL));
-                m_encoders[start] = encoder;
-                m_log.debug("supporting outgoing binding (%s)", b.get());
+                    SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),pair<const DOMElement*,const XMLCh*>(e,nullptr));
+                if (encoder->isUserAgentPresent() && XMLString::equals(getProtocolFamily(), encoder->getProtocolFamily())) {
+                    m_encoders[start] = encoder;
+                    m_log.debug("supporting outgoing binding (%s)", b.get());
+                }
+                else {
+                    delete encoder;
+                    m_log.warn("skipping outgoing binding (%s), not a SAML 2.0 front-channel mechanism", b.get());
+                }
             }
             catch (exception& ex) {
                 m_log.error("error building MessageEncoder: %s", ex.what());
@@ -182,7 +190,7 @@ pair<bool,long> SAML2LogoutInitiator::run(SPRequest& request, bool isHandler) co
     // At this point we know the front-channel is handled.
     // We need the session to do any other work.
 
-    Session* session = NULL;
+    Session* session = nullptr;
     try {
         session = request.getSession(false, true, false);  // don't cache it and ignore all checks
         if (!session)
@@ -223,24 +231,24 @@ void SAML2LogoutInitiator::receive(DDF& in, ostream& out)
 
     // Find application.
     const char* aid=in["application_id"].string();
-    const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
+    const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
     if (!app) {
         // Something's horribly wrong.
         m_log.error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
         throw ConfigurationException("Unable to locate application for logout, deleted?");
     }
-    
+
     // Unpack the request.
     auto_ptr<HTTPRequest> req(getRequest(in));
 
     // Set up a response shim.
-    DDF ret(NULL);
+    DDF ret(nullptr);
     DDFJanitor jout(ret);
     auto_ptr<HTTPResponse> resp(getResponse(ret));
-    
-    Session* session = NULL;
+
+    Session* session = nullptr;
     try {
-         session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), NULL, NULL);
+         session = app->getServiceProvider().getSessionCache()->find(*app, *req.get(), nullptr, nullptr);
     }
     catch (exception& ex) {
         m_log.error("error accessing current session: %s", ex.what());
@@ -255,7 +263,7 @@ void SAML2LogoutInitiator::receive(DDF& in, ostream& out)
             doRequest(*app, *req.get(), *resp.get(), session);
         }
         else {
-             m_log.error("no NameID or issuing entityID found in session");
+             m_log.log(getParent() ? Priority::WARN : Priority::ERROR, "bypassing SAML 2.0 logout, no NameID or issuing entityID found in session");
              session->unlock();
              app->getServiceProvider().getSessionCache()->remove(*app, *req.get(), resp.get());
         }
@@ -275,7 +283,7 @@ pair<bool,long> SAML2LogoutInitiator::doRequest(
     if (!notifyBackChannel(application, httpRequest.getRequestURL(), sessions, false)) {
         session->unlock();
         application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
-        return sendLogoutPage(application, httpRequest, httpResponse, true, "Partial logout failure.");
+        return sendLogoutPage(application, httpRequest, httpResponse, "partial");
     }
 
 #ifndef SHIBSP_LITE
@@ -284,7 +292,7 @@ pair<bool,long> SAML2LogoutInitiator::doRequest(
         // With a session in hand, we can create a LogoutRequest message, if we can find a compatible endpoint.
         MetadataProvider* m = application.getMetadataProvider();
         Locker metadataLocker(m);
-        MetadataProvider::Criteria mc(session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
+        MetadataProviderCriteria mc(application, session->getEntityID(), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
         pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
         if (!entity.first) {
             throw MetadataException(
@@ -298,8 +306,14 @@ pair<bool,long> SAML2LogoutInitiator::doRequest(
         }
 
         const IDPSSODescriptor* role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
-        const EndpointType* ep=NULL;
-        const MessageEncoder* encoder=NULL;
+        if (role->getSingleLogoutServices().empty()) {
+            throw MetadataException(
+                "No SingleLogoutService endpoints in metadata for identity provider ($entityID).", namedparams(1, "entityID", session->getEntityID())
+                );
+        }
+
+        const EndpointType* ep=nullptr;
+        const MessageEncoder* encoder=nullptr;
         vector<const XMLCh*>::const_iterator b;
         for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
             if (ep=EndpointManager<SingleLogoutService>(role->getSingleLogoutServices()).getByBinding(*b)) {
@@ -310,12 +324,12 @@ pair<bool,long> SAML2LogoutInitiator::doRequest(
             }
         }
         if (!ep || !encoder) {
-            m_log.warn("no compatible front channel SingleLogoutService, trying back channel...");
+            m_log.debug("no compatible front channel SingleLogoutService, trying back channel...");
             shibsp::SecurityPolicy policy(application);
             shibsp::SOAPClient soaper(policy);
             MetadataCredentialCriteria mcc(*role);
 
-            LogoutResponse* logoutResponse=NULL;
+            LogoutResponse* logoutResponse=nullptr;
             auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
             const vector<SingleLogoutService*>& endpoints=role->getSingleLogoutServices();
             for (vector<SingleLogoutService*>::const_iterator epit=endpoints.begin(); !logoutResponse && epit!=endpoints.end(); ++epit) {
@@ -339,28 +353,41 @@ pair<bool,long> SAML2LogoutInitiator::doRequest(
                 }
             }
 
-            if (!logoutResponse)
-                ret = sendLogoutPage(application, httpRequest, httpResponse, false, "Identity provider did not respond to logout request.");
-            else if (!logoutResponse->getStatus() || !logoutResponse->getStatus()->getStatusCode() ||
-                   !XMLString::equals(logoutResponse->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
-                delete logoutResponse;
-                ret = sendLogoutPage(application, httpRequest, httpResponse, false, "Identity provider returned a SAML error in response to logout request.");
+            // No answer at all?
+            if (!logoutResponse) {
+                if (endpoints.empty())
+                    m_log.info("IdP doesn't support single logout protocol over a compatible binding");
+                else
+                    m_log.warn("IdP didn't respond to logout request");
+                ret = sendLogoutPage(application, httpRequest, httpResponse, "partial");
             }
             else {
+                // Check the status, looking for non-success or a partial logout code.
+                const StatusCode* sc = logoutResponse->getStatus() ? logoutResponse->getStatus()->getStatusCode() : nullptr;
+                bool partial = (!sc || !XMLString::equals(sc->getValue(), StatusCode::SUCCESS));
+                if (!partial && sc->getStatusCode()) {
+                    // Success, but still need to check for partial.
+                    partial = XMLString::equals(sc->getStatusCode()->getValue(), StatusCode::PARTIAL_LOGOUT);
+                }
                 delete logoutResponse;
-                const char* returnloc = httpRequest.getParameter("return");
-                if (returnloc) {
-                    ret.second = httpResponse.sendRedirect(returnloc);
-                    ret.first = true;
+                if (partial)
+                    ret = sendLogoutPage(application, httpRequest, httpResponse, "partial");
+                else {
+                    const char* returnloc = httpRequest.getParameter("return");
+                    if (returnloc) {
+                        ret.second = httpResponse.sendRedirect(returnloc);
+                        ret.first = true;
+                    }
+                    ret = sendLogoutPage(application, httpRequest, httpResponse, "global");
                 }
-                ret = sendLogoutPage(application, httpRequest, httpResponse, false, "Logout completed successfully.");
             }
 
             if (session) {
                 session->unlock();
-                session = NULL;
+                session = nullptr;
                 application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
             }
+
             return ret;
         }
 
@@ -386,7 +413,7 @@ pair<bool,long> SAML2LogoutInitiator::doRequest(
 
     if (session) {
         session->unlock();
-        session = NULL;
+        session = nullptr;
         application.getServiceProvider().getSessionCache()->remove(application, httpRequest, &httpResponse);
     }
 
@@ -404,10 +431,12 @@ LogoutRequest* SAML2LogoutInitiator::buildRequest(
     const Application& application, const Session& session, const RoleDescriptor& role, const MessageEncoder* encoder
     ) const
 {
+    const PropertySet* relyingParty = application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role.getParent()));
+
     auto_ptr<LogoutRequest> msg(LogoutRequestBuilder::buildLogoutRequest());
     Issuer* issuer = IssuerBuilder::buildIssuer();
     msg->setIssuer(issuer);
-    issuer->setName(application.getXMLString("entityID").second);
+    issuer->setName(relyingParty->getXMLString("entityID").second);
     auto_ptr_XMLCh index(session.getSessionIndex());
     if (index.get() && *index.get()) {
         SessionIndex* si = SessionIndexBuilder::buildSessionIndex();
@@ -416,7 +445,6 @@ LogoutRequest* SAML2LogoutInitiator::buildRequest(
     }
 
     const NameID* nameid = session.getNameID();
-    const PropertySet* relyingParty = application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role.getParent()));
     pair<bool,const char*> flag = relyingParty->getString("encryption");
     if (flag.first &&
         (!strcmp(flag.second, "true") || (encoder && !strcmp(flag.second, "front")) || (!encoder && !strcmp(flag.second, "back")))) {
@@ -431,48 +459,8 @@ LogoutRequest* SAML2LogoutInitiator::buildRequest(
             );
         msg->setEncryptedID(encrypted.release());
     }
-
-    if (!encoder) {
-        // No encoder being used, so sign for SOAP client manually.
-        flag = relyingParty->getString("signing");
-        if (flag.first && (!strcmp(flag.second, "true") || !strcmp(flag.second, "back"))) {
-            CredentialResolver* credResolver=application.getCredentialResolver();
-            if (credResolver) {
-                Locker credLocker(credResolver);
-                // Fill in criteria to use.
-                MetadataCredentialCriteria mcc(role);
-                mcc.setUsage(Credential::SIGNING_CREDENTIAL);
-                pair<bool,const char*> keyName = relyingParty->getString("keyName");
-                if (keyName.first)
-                    mcc.getKeyNames().insert(keyName.second);
-                pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
-                if (sigalg.first)
-                    mcc.setXMLAlgorithm(sigalg.second);
-                const Credential* cred = credResolver->resolve(&mcc);
-                if (cred) {
-                    xmlsignature::Signature* sig = xmlsignature::SignatureBuilder::buildSignature();
-                    msg->setSignature(sig);
-                    if (sigalg.first)
-                        sig->setSignatureAlgorithm(sigalg.second);
-                    sigalg = relyingParty->getXMLString("digestAlg");
-                    if (sigalg.first) {
-                        ContentReference* cr = dynamic_cast<ContentReference*>(sig->getContentReference());
-                        if (cr)
-                            cr->setDigestAlgorithm(sigalg.second);
-                    }
-            
-                    // Sign response while marshalling.
-                    vector<xmlsignature::Signature*> sigs(1,sig);
-                    msg->marshall((DOMDocument*)NULL,&sigs,cred);
-                }
-                else {
-                    m_log.warn("no signing credential resolved, leaving message unsigned");
-                }
-            }
-            else {
-                m_log.warn("no credential resolver installed, leaving message unsigned");
-            }
-        }
+    else {
+        msg->setNameID(nameid->cloneNameID());
     }
 
     return msg.release();