Add protocol family property to protocol handlers, and fix up error handling to recog...
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML2ArtifactResolution.cpp
index 8235d07..0d0cc76 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  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.
  */
 
 #include "internal.h"
-#include "Application.h"
 #include "exceptions.h"
+#include "Application.h"
 #include "ServiceProvider.h"
+#include "SPRequest.h"
 #include "handler/AbstractHandler.h"
 #include "handler/RemotedHandler.h"
 #include "util/SPConstants.h"
 
 #ifndef SHIBSP_LITE
 # include "security/SecurityPolicy.h"
+# include "security/SecurityPolicyProvider.h"
+# include <saml/exceptions.h>
 # include <saml/SAMLConfig.h>
 # include <saml/binding/ArtifactMap.h>
 # include <saml/binding/MessageEncoder.h>
 using namespace opensaml::saml2md;
 using namespace opensaml::saml2p;
 using namespace opensaml::saml2;
-using namespace samlconstants;
+using namespace opensaml;
+#else
+# include "lite/SAMLConstants.h"
 #endif
 
 #include <xmltooling/soap/SOAP.h>
 
 using namespace shibspconstants;
 using namespace shibsp;
-using namespace opensaml;
 using namespace soap11;
 using namespace xmltooling;
-using namespace log4cpp;
 using namespace std;
 
 namespace shibsp {
@@ -70,21 +73,54 @@ namespace shibsp {
         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
         void receive(DDF& in, ostream& out);
 
+#ifndef SHIBSP_LITE
+        const char* getType() const {
+            return "ArtifactResolutionService";
+        }
+
+        void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
+            // Initial guess at index to use.
+            pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
+            if (!strncmp(handlerURL, "https", 5))
+                ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
+            if (!ix.first)
+                ix = getUnsignedInt("index");
+            if (!ix.first)
+                ix.second = 1;
+
+            // Find maximum index in use and go one higher.
+            const vector<ArtifactResolutionService*>& services = const_cast<const SPSSODescriptor&>(role).getArtifactResolutionServices();
+            if (!services.empty() && ix.second <= services.back()->getIndex().second)
+                ix.second = services.back()->getIndex().second + 1;
+
+            const char* loc = getString("Location").second;
+            string hurl(handlerURL);
+            if (*loc != '/')
+                hurl += '/';
+            hurl += loc;
+            auto_ptr_XMLCh widen(hurl.c_str());
+
+            ArtifactResolutionService* ep = ArtifactResolutionServiceBuilder::buildArtifactResolutionService();
+            ep->setLocation(widen.get());
+            ep->setBinding(getXMLString("Binding").second);
+            ep->setIndex(ix.second);
+            role.getArtifactResolutionServices().push_back(ep);
+        }
+#endif
+        const XMLCh* getProtocolFamily() const {
+            return samlconstants::SAML20P_NS;
+        }
+
     private:
         pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
 #ifndef SHIBSP_LITE
-        pair<bool,long> samlError(
-            const Application& app,
-            const ArtifactResolve& request,
-            HTTPResponse& httpResponse,
-            const XMLCh* code,
-            const XMLCh* subcode=NULL,
-            const char* msg=NULL
+        pair<bool,long> emptyResponse(
+            const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const EntityDescriptor* recipient
             ) const;
 
         MessageEncoder* m_encoder;
         MessageDecoder* m_decoder;
-        QName m_role;
+        xmltooling::QName m_role;
 #endif
     };
 
@@ -100,18 +136,22 @@ namespace shibsp {
 };
 
 SAML2ArtifactResolution::SAML2ArtifactResolution(const DOMElement* e, const char* appId)
-    : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SAML2ArtifactResolution"))
+    : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".ArtifactResolution.SAML2"))
 #ifndef SHIBSP_LITE
-        ,m_encoder(NULL), m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
+        ,m_encoder(nullptr), m_decoder(nullptr), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
 #endif
 {
 #ifndef SHIBSP_LITE
     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
         try {
-            m_encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(getString("Binding").second,e);
-            m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(getString("Binding").second,e);
+            m_encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
+                getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,nullptr)
+                );
+            m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
+                getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,nullptr)
+                );
         }
-        catch (exception& ex) {
+        catch (exception&) {
             m_log.error("error building MessageEncoder/Decoder pair for binding (%s)", getString("Binding").second);
             delete m_encoder;
             delete m_decoder;
@@ -145,7 +185,7 @@ pair<bool,long> SAML2ArtifactResolution::run(SPRequest& request, bool isHandler)
         }
         else {
             // When not out of process, we remote all the message processing.
-            DDF out,in = wrap(request, NULL, true);
+            DDF out,in = wrap(request, nullptr, true);
             DDFJanitor jin(in), jout(out);
             
             out=request.getServiceProvider().getListenerService()->send(in);
@@ -167,7 +207,7 @@ pair<bool,long> SAML2ArtifactResolution::run(SPRequest& request, bool isHandler)
         fs->setString(msg.get());
 #ifndef SHIBSP_LITE
         // Use MessageEncoder to send back the fault.
-        long ret = m_encoder->encode(request, fault.get(), NULL);
+        long ret = m_encoder->encode(request, fault.get(), nullptr);
         fault.release();
         return make_pair(true, ret);
 #else
@@ -189,7 +229,7 @@ void SAML2ArtifactResolution::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 artifact resolution", aid ? aid : "(missing)");
@@ -201,7 +241,7 @@ void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
     //m_log.debug("found %d client certificates", req->getClientCertificates().size());
 
     // Wrap a response shim.
-    DDF ret(NULL);
+    DDF ret(nullptr);
     DDFJanitor jout(ret);
     auto_ptr<HTTPResponse> resp(getResponse(ret));
         
@@ -226,7 +266,7 @@ void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
         pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
         auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
         fs->setString(msg.get());
-        m_encoder->encode(*resp.get(), fault.get(), NULL);
+        m_encoder->encode(*resp.get(), fault.get(), nullptr);
         fault.release();
         out << ret;
 #else
@@ -249,30 +289,30 @@ pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& appli
     if (!policyId.first)
         policyId = application.getString("policyId");   // unqualified in Application(s) element
         
-    // Access policy properties.
-    const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
-    pair<bool,bool> validate = settings->getBool("validate");
-
     // Lock metadata for use by policy.
     Locker metadataLocker(application.getMetadataProvider());
 
     // Create the policy.
-    shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
+    auto_ptr<SecurityPolicy> policy(
+        application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &m_role, policyId.second)
+        );
     
     // Decode the message and verify that it's a secured ArtifactResolve request.
     string relayState;
-    auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
+    auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, *policy.get()));
     if (!msg.get())
         throw BindingException("Failed to decode a SAML request.");
     const ArtifactResolve* req = dynamic_cast<const ArtifactResolve*>(msg.get());
     if (!req)
         throw FatalProfileException("Decoded message was not a samlp::ArtifactResolve request.");
 
+    const EntityDescriptor* entity = policy->getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy->getIssuerMetadata()->getParent()) : nullptr;
+
     try {
-        auto_ptr_char artifact(req->getArtifact() ? req->getArtifact()->getArtifact() : NULL);
+        auto_ptr_char artifact(req->getArtifact() ? req->getArtifact()->getArtifact() : nullptr);
         if (!artifact.get() || !*artifact.get())
-            return samlError(application, *req, httpResponse, StatusCode::REQUESTER, NULL, "Request did not contain an artifact to resolve.");
-        auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
+            return emptyResponse(application, *req, httpResponse, entity);
+        auto_ptr_char issuer(policy->getIssuer() ? policy->getIssuer()->getName() : nullptr);
 
         m_log.info("resolving artifact (%s) for (%s)", artifact.get(), issuer.get() ? issuer.get() : "unknown");
 
@@ -280,9 +320,9 @@ pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& appli
         auto_ptr<SAMLArtifact> artobj(SAMLArtifact::parse(artifact.get()));
         auto_ptr<XMLObject> payload(artmap->retrieveContent(artobj.get(), issuer.get()));
 
-        if (!policy.isSecure()) {
+        if (!policy->isAuthenticated()) {
             m_log.error("request for artifact was unauthenticated, purging the artifact mapping");
-            return samlError(application, *req, httpResponse, StatusCode::REQUESTER, StatusCode::AUTHN_FAILED, "Unable to authenticate request.");
+            return emptyResponse(application, *req, httpResponse, entity);
         }
 
         m_log.debug("artifact resolved, preparing response");
@@ -291,36 +331,36 @@ pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& appli
         auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
         resp->setInResponseTo(req->getID());
         Issuer* me = IssuerBuilder::buildIssuer();
-        me->setName(application.getXMLString("entityID").second);
+        me->setName(application.getRelyingParty(entity)->getXMLString("entityID").second);
         resp->setPayload(payload.release());
 
         long ret = sendMessage(
-            *m_encoder, resp.get(), relayState.c_str(), NULL, policy.getIssuerMetadata(), application, httpResponse, "signResponses"
+            *m_encoder, resp.get(), relayState.c_str(), nullptr, policy->getIssuerMetadata(), application, httpResponse, "signResponses"
             );
         resp.release();  // freed by encoder
         return make_pair(true,ret);
     }
     catch (exception& ex) {
-        // Trap localized errors in a SAML Response.
-        m_log.error("error processing artifact request, returning SAML error: %s", ex.what());
-        return samlError(application, *req, httpResponse, StatusCode::RESPONDER, NULL, ex.what());
+        // Trap localized errors.
+        m_log.error("error processing artifact request: %s", ex.what());
+        return emptyResponse(application, *req, httpResponse, entity);
     }
 #else
-    return make_pair(false,0);
+    return make_pair(false,0L);
 #endif
 }
 
 #ifndef SHIBSP_LITE
-pair<bool,long> SAML2ArtifactResolution::samlError(
-    const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const XMLCh* code, const XMLCh* subcode, const char* msg
+pair<bool,long> SAML2ArtifactResolution::emptyResponse(
+    const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const EntityDescriptor* recipient
     ) const
 {
     auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
     resp->setInResponseTo(request.getID());
     Issuer* me = IssuerBuilder::buildIssuer();
-    me->setName(app.getXMLString("entityID").second);
-    fillStatus(*resp.get(), code, subcode, msg);
-    long ret = m_encoder->encode(httpResponse, resp.get(), NULL);
+    me->setName(app.getRelyingParty(recipient)->getXMLString("entityID").second);
+    fillStatus(*resp.get(), StatusCode::SUCCESS);
+    long ret = m_encoder->encode(httpResponse, resp.get(), nullptr);
     resp.release();  // freed by encoder
     return make_pair(true,ret);
 }