Convert role lookups to find_if algorithm.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML2SessionInitiator.cpp
index 160be51..1e1e0e2 100644 (file)
 #include "handler/SessionInitiator.h"
 #include "util/SPConstants.h"
 
-#include <saml/SAMLConfig.h>
-#include <saml/binding/MessageEncoder.h>
-#include <saml/saml2/core/Protocols.h>
-#include <saml/saml2/metadata/EndpointManager.h>
-#include <saml/saml2/metadata/Metadata.h>
-#include <saml/saml2/metadata/MetadataCredentialCriteria.h>
-
-using namespace shibsp;
+#ifndef SHIBSP_LITE
+# include <saml/SAMLConfig.h>
+# include <saml/saml2/core/Protocols.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;
 using namespace opensaml::saml2md;
+#endif
+
+using namespace shibsp;
 using namespace opensaml;
 using namespace xmltooling;
-using namespace log4cpp;
 using namespace std;
 
 namespace shibsp {
@@ -58,11 +58,13 @@ namespace shibsp {
     public:
         SAML2SessionInitiator(const DOMElement* e, const char* appId);
         virtual ~SAML2SessionInitiator() {
+#ifndef SHIBSP_LITE
             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
                 XMLString::release(&m_outgoing);
                 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
                 delete m_requestTemplate;
             }
+#endif
         }
         
         void setParent(const PropertySet* parent);
@@ -85,10 +87,12 @@ namespace shibsp {
             ) const;
 
         string m_appId;
+#ifndef SHIBSP_LITE
         XMLCh* m_outgoing;
         vector<const XMLCh*> m_bindings;
         map<const XMLCh*,MessageEncoder*> m_encoders;
         AuthnRequest* m_requestTemplate;
+#endif
     };
 
 #if defined (_MSC_VER)
@@ -103,8 +107,11 @@ namespace shibsp {
 };
 
 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
-    : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator")), m_appId(appId), m_outgoing(NULL), m_requestTemplate(NULL)
+    : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAML2")), m_appId(appId)
 {
+#ifndef SHIBSP_LITE
+    m_outgoing=NULL;
+    m_requestTemplate=NULL;
     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
         // Check for a template AuthnRequest to build from.
         DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
@@ -115,13 +122,13 @@ SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* ap
         pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
         if (outgoing.first) {
             m_outgoing = XMLString::replicate(outgoing.second);
+            XMLString::trim(m_outgoing);
         }
         else {
             // No override, so we'll install a default binding precedence.
             string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
                 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
             m_outgoing = XMLString::transcode(prec.c_str());
-            XMLString::trim(m_outgoing);
         }
 
         int pos;
@@ -133,9 +140,11 @@ SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* ap
             m_bindings.push_back(start);
             try {
                 auto_ptr_char b(start);
-                MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),e);
+                MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
+                    b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL)
+                    );
                 m_encoders[start] = encoder;
-                m_log.info("supporting outgoing binding (%s)", b.get());
+                m_log.debug("supporting outgoing binding (%s)", b.get());
             }
             catch (exception& ex) {
                 m_log.error("error building MessageEncoder: %s", ex.what());
@@ -146,6 +155,7 @@ SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* ap
                 break;
         }
     }
+#endif
 
     // If Location isn't set, defer address registration until the setParent call.
     pair<bool,const char*> loc = getString("Location");
@@ -185,13 +195,16 @@ pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, const char* entit
 
     if (isHandler) {
         option=request.getParameter("acsIndex");
-        if (option)
+        if (option) {
             ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
+            if (!ACS)
+                request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using default ACS location");
+        }
 
         option = request.getParameter("target");
         if (option)
             target = option;
-        if (!acsByIndex.first || !acsByIndex.second) {
+        if (acsByIndex.first && !acsByIndex.second) {
             // Since we're passing the ACS by value, we need to compute the return URL,
             // so we'll need the target resource for real.
             recoverRelayState(request.getApplication(), request, target, false);
@@ -228,13 +241,24 @@ pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, const char* entit
 
     m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID);
 
-    // To invoke the request builder, the key requirement is to figure out how and whether
+    if (!ACS) {
+        pair<bool,unsigned int> index = getUnsignedInt("defaultACSIndex");
+        if (index.first) {
+            ACS = app.getAssertionConsumerServiceByIndex(index.second);
+            if (!ACS)
+                request.log(SPRequest::SPWarn, "invalid defaultACSIndex, using default ACS location");
+        }
+        if (!ACS)
+            ACS = app.getDefaultAssertionConsumerService();
+    }
+
+    // To invoke the request builder, the key requirement is to figure out how
     // to express the ACS, by index or value, and if by value, where.
 
     SPConfig& conf = SPConfig::getConfig();
     if (conf.isEnabled(SPConfig::OutOfProcess)) {
-        if (acsByIndex.first && acsByIndex.second) {
-            // Pass by Index. This also allows for defaulting it entirely and sending nothing.
+        if (!acsByIndex.first || acsByIndex.second) {
+            // Pass by Index.
             if (isHandler) {
                 // We may already have RelayState set if we looped back here,
                 // but just in case target is a resource, we reset it back.
@@ -254,9 +278,6 @@ pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, const char* entit
         }
 
         // Since we're not passing by index, we need to fully compute the return URL and binding.
-        if (!ACS)
-            ACS = app.getDefaultAssertionConsumerService();
-
         // Compute the ACS URL. We add the ACS location to the base handlerURL.
         string ACSloc=request.getHandlerURL(target.c_str());
         pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
@@ -294,15 +315,12 @@ pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, const char* entit
         in.addmember("authnContextClassRef").string(acClass.second);
     if (acComp.first)
         in.addmember("authnContextComparison").string(acComp.second);
-    if (acsByIndex.first && acsByIndex.second) {
+    if (!acsByIndex.first || acsByIndex.second) {
         if (ACS)
             in.addmember("acsIndex").string(ACS->getString("index").second);
     }
     else {
         // Since we're not passing by index, we need to fully compute the return URL and binding.
-        if (!ACS)
-            ACS = app.getDefaultAssertionConsumerService();
-
         // Compute the ACS URL. We add the ACS location to the base handlerURL.
         string ACSloc=request.getHandlerURL(target.c_str());
         pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
@@ -381,15 +399,17 @@ pair<bool,long> SAML2SessionInitiator::doRequest(
     string& relayState
     ) const
 {
+#ifndef SHIBSP_LITE
     // Use metadata to locate the IdP's SSO service.
     MetadataProvider* m=app.getMetadataProvider();
     Locker locker(m);
     const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
     if (!entity) {
         m_log.error("unable to locate metadata for provider (%s)", entityID);
-        return make_pair(false,0);
+        throw MetadataException("Unable to locate metadata for identity provider ($entityID)",
+            namedparams(1, "entityID", entityID));
     }
-    const IDPSSODescriptor* role=entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
+    const IDPSSODescriptor* role=find_if(entity->getIDPSSODescriptors(), isValidForProtocol(samlconstants::SAML20P_NS));
     if (!role) {
         m_log.error("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
         return make_pair(false,0);
@@ -422,13 +442,13 @@ pair<bool,long> SAML2SessionInitiator::doRequest(
     }
 
     req->setDestination(ep->getLocation());
-    if (acsIndex)
+    if (acsIndex && *acsIndex)
         req->setAssertionConsumerServiceIndex(acsIndex);
     if (acsLocation) {
         auto_ptr_XMLCh wideloc(acsLocation);
         req->setAssertionConsumerServiceURL(wideloc.get());
     }
-    if (acsBinding)
+    if (acsBinding && *acsBinding)
         req->setProtocolBinding(acsBinding);
     if (isPassive)
         req->IsPassive(isPassive);
@@ -466,43 +486,12 @@ pair<bool,long> SAML2SessionInitiator::doRequest(
 
     auto_ptr_char dest(ep->getLocation());
 
-    // Check for signing.
-    const PropertySet* relyingParty = app.getRelyingParty(entity);
-    pair<bool,bool> flag = relyingParty->getBool("signRequests");
-    if ((flag.first && flag.second) || role->WantAuthnRequestsSigned()) {
-        CredentialResolver* credResolver=app.getCredentialResolver();
-        if (credResolver) {
-            Locker credLocker(credResolver);
-            // Fill in criteria to use.
-            MetadataCredentialCriteria mcc(*role);
-            mcc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
-            pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signatureAlg");
-            if (sigalg.first)
-                mcc.setXMLAlgorithm(sigalg.second);
-            const Credential* cred = credResolver->resolve(&mcc);
-            if (cred) {
-                // Signed request.
-                long ret = encoder->encode(
-                    httpResponse,
-                    req.get(),
-                    dest.get(),
-                    entityID,
-                    relayState.c_str(),
-                    cred,
-                    sigalg.second,
-                    relyingParty->getXMLString("digestAlg").second
-                    );
-                req.release();  // freed by encoder
-                return make_pair(true,ret);
-            }
-            else {
-                m_log.warn("no signing credential resolved, leaving AuthnRequest unsigned");
-            }
-        }
-    }
-
-    // Unsigned request.
-    long ret = encoder->encode(httpResponse, req.get(), dest.get(), entityID, relayState.c_str());
+    long ret = sendMessage(
+        *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role->WantAuthnRequestsSigned()
+        );
     req.release();  // freed by encoder
     return make_pair(true,ret);
+#else
+    return make_pair(false,0);
+#endif
 }