Move all attribute work into base class.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / AssertionConsumerService.cpp
index e89ecfc..7d675b6 100644 (file)
 #include "Application.h"
 #include "exceptions.h"
 #include "ServiceProvider.h"
-#include "attribute/resolver/AttributeResolver.h"
-#include "attribute/resolver/ResolutionContext.h"
 #include "handler/AssertionConsumerService.h"
 #include "util/SPConstants.h"
 
-#include <saml/SAMLConfig.h>
-#include <saml/saml1/core/Assertions.h>
-#include <saml/util/CommonDomainCookie.h>
+# include <ctime>
+#ifndef SHIBSP_LITE
+# include "attribute/Attribute.h"
+# include "attribute/filtering/AttributeFilter.h"
+# include "attribute/filtering/BasicFilteringContext.h"
+# include "attribute/resolver/AttributeExtractor.h"
+# include "attribute/resolver/AttributeResolver.h"
+# include "attribute/resolver/ResolutionContext.h"
+# include "security/SecurityPolicy.h"
+# include <saml/SAMLConfig.h>
+# include <saml/saml1/core/Assertions.h>
+# include <saml/util/CommonDomainCookie.h>
+using namespace samlconstants;
+#else
+# include "lite/CommonDomainCookie.h"
+#endif
 
 using namespace shibspconstants;
-using namespace samlconstants;
 using namespace shibsp;
 using namespace opensaml;
 using namespace xmltooling;
-using namespace log4cpp;
 using namespace std;
 
-AssertionConsumerService::AssertionConsumerService(const DOMElement* e, Category& log)
-    : AbstractHandler(e, log), m_configNS(SHIB2SPCONFIG_NS),
-        m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
+AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
+    : AbstractHandler(e, log)
+#ifndef SHIBSP_LITE
+        ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
+#endif
 {
-    if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
-        m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(getString("Binding").second,e);
+    string address(appId);
+    address += getString("Location").second;
+    setAddress(address.c_str());
+#ifndef SHIBSP_LITE
+    if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
+        m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
+            getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS)
+            );
+        m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
+    }
+#endif
 }
 
 AssertionConsumerService::~AssertionConsumerService()
 {
+#ifndef SHIBSP_LITE
     delete m_decoder;
+#endif
 }
 
 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
 {
+    string relayState;
     SPConfig& conf = SPConfig::getConfig();
-    if (conf.isEnabled(SPConfig::OutOfProcess)) {
-        // When out of process, we run natively and directly process the message.
-        // RelayState will be fully handled during message processing.
-        string relayState, providerId;
-        string key = processMessage(request.getApplication(), request, providerId, relayState);
-        return sendRedirect(request, key.c_str(), providerId.c_str(), relayState.c_str());
-    }
-    else {
-        // When not out of process, we remote all the message processing.
-        DDF in = wrap(request);
-        DDFJanitor jin(in);
-        in.addmember("application_id").string(request.getApplication().getId());
-        DDF out=request.getServiceProvider().getListenerService()->send(in);
-        DDFJanitor jout(out);
-        
-        // If it worked, we have a session key.
-        if (!out["key"].isstring())
-            throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
+    
+    try {
+        if (conf.isEnabled(SPConfig::OutOfProcess)) {
+            // When out of process, we run natively and directly process the message.
+            // RelayState will be fully handled during message processing.
+            string entityID;
+            string key = processMessage(request.getApplication(), request, entityID, relayState);
+            return sendRedirect(request, key.c_str(), entityID.c_str(), relayState.c_str());
+        }
+        else {
+            // When not out of process, we remote all the message processing.
+            DDF out,in = wrap(request);
+            DDFJanitor jin(in), jout(out);
             
-        // We invoke the RelayState method one last time on this side of the process boundary.
-        string relayState;
-        if (out["RelayState"].isstring())
-            relayState = out["RelayState"].string(); 
-        recoverRelayState(request, relayState);
-        return sendRedirect(request, out["key"].string(), out["provider_id"].string(), relayState.c_str());
+            try {
+                out=request.getServiceProvider().getListenerService()->send(in);
+            }
+            catch (XMLToolingException& ex) {
+                // Try for RelayState recovery.
+                if (ex.getProperty("RelayState"))
+                    relayState = ex.getProperty("RelayState");
+                try {
+                    recoverRelayState(request.getApplication(), request, relayState);
+                }
+                catch (exception& ex2) {
+                    m_log.error("trapped an error during RelayState recovery while handling an error: %s", ex2.what());
+                }
+                throw;
+            }
+                
+            // We invoke RelayState recovery one last time on this side of the boundary.
+            if (out["RelayState"].isstring())
+                relayState = out["RelayState"].string(); 
+            recoverRelayState(request.getApplication(), request, relayState);
+    
+            // If it worked, we have a session key.
+            if (!out["key"].isstring())
+                throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
+            
+            // Take care of cookie business and wrap it up.
+            return sendRedirect(request, out["key"].string(), out["entity_id"].string(), relayState.c_str());
+        }
+    }
+    catch (XMLToolingException& ex) {
+        // Try and preserve RelayState.
+        if (!relayState.empty())
+            ex.addProperty("RelayState", relayState.c_str());
+        throw;
     }
 }
 
@@ -100,24 +146,33 @@ void AssertionConsumerService::receive(DDF& in, ostream& out)
     auto_ptr<HTTPRequest> http(getRequest(in));
     
     // Do the work.
-    string relayState, providerId;
-    string key = processMessage(*app, *http.get(), providerId, relayState);
-    
-    // Repack for return to caller.
-    DDF ret=DDF(NULL).structure();
-    DDFJanitor jret(ret);
-    ret.addmember("key").string(key.c_str());
-    if (!providerId.empty())
-        ret.addmember("provider_id").string(providerId.c_str());
-    if (!relayState.empty())
-        ret.addmember("RelayState").string(relayState.c_str());
-    out << ret;
+    string relayState, entityID;
+    try {
+        string key = processMessage(*app, *http.get(), entityID, relayState);
+
+        // Repack for return to caller.
+        DDF ret=DDF(NULL).structure();
+        DDFJanitor jret(ret);
+        ret.addmember("key").string(key.c_str());
+        if (!entityID.empty())
+            ret.addmember("entity_id").string(entityID.c_str());
+        if (!relayState.empty())
+            ret.addmember("RelayState").string(relayState.c_str());
+        out << ret;
+    }
+    catch (XMLToolingException& ex) {
+        // Try and preserve RelayState if we can.
+        if (!relayState.empty())
+            ex.addProperty("RelayState", relayState.c_str());
+        throw;
+    }
 }
 
 string AssertionConsumerService::processMessage(
-    const Application& application, HTTPRequest& httpRequest, string& providerId, string& relayState
+    const Application& application, HTTPRequest& httpRequest, string& entityID, string& relayState
     ) const
 {
+#ifndef SHIBSP_LITE
     // Locate policy key.
     pair<bool,const char*> policyId = getString("policyId", m_configNS.get());  // namespace-qualified if inside handler element
     if (!policyId.first)
@@ -131,28 +186,27 @@ string AssertionConsumerService::processMessage(
     Locker metadataLocker(application.getMetadataProvider());
 
     // Create the policy.
-    SecurityPolicy policy(
-        application.getServiceProvider().getPolicyRules(policyId.second), 
-        application.getMetadataProvider(),
-        &m_role,
-        application.getTrustEngine(),
-        validate.first && validate.second
-        );
+    shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
     
     // Decode the message and process it in a protocol-specific way.
     auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
-    recoverRelayState(httpRequest, relayState);
+    if (!msg.get())
+        throw BindingException("Failed to decode an SSO protocol response.");
+    recoverRelayState(application, httpRequest, relayState);
     string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
 
     auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
     if (issuer.get())
-        providerId = issuer.get();
+        entityID = issuer.get();
     
     return key;
+#else
+    throw ConfigurationException("Cannot process message using lite version of shibsp library.");
+#endif
 }
 
 pair<bool,long> AssertionConsumerService::sendRedirect(
-    SPRequest& request, const char* key, const char* providerId, const char* relayState
+    SPRequest& request, const char* key, const char* entityID, const char* relayState
     ) const
 {
     // We've got a good session, so set the session cookie.
@@ -162,7 +216,7 @@ pair<bool,long> AssertionConsumerService::sendRedirect(
     request.setCookie(shib_cookie.first.c_str(), k.c_str());
 
     // History cookie.
-    maintainHistory(request, providerId, shib_cookie.second);
+    maintainHistory(request, entityID, shib_cookie.second);
 
     // Now redirect to the state value. By now, it should be set to *something* usable.
     return make_pair(true, request.sendRedirect(relayState));
@@ -190,24 +244,113 @@ void AssertionConsumerService::checkAddress(
     }
 }
 
+#ifndef SHIBSP_LITE
+
+class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
+{
+public:
+    DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
+    }
+
+    virtual ~DummyContext() {
+        for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
+    }
+
+    vector<Attribute*>& getResolvedAttributes() {
+        return m_attributes;
+    }
+    vector<Assertion*>& getResolvedAssertions() {
+        return m_tokens;
+    }
+
+private:
+    vector<Attribute*> m_attributes;
+    static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
+};
+
+vector<Assertion*> DummyContext::m_tokens;
+
 ResolutionContext* AssertionConsumerService::resolveAttributes(
     const Application& application,
-    const HTTPRequest& httpRequest,
-    const saml2md::EntityDescriptor* issuer,
-    const saml2::NameID& nameid,
+    const saml2md::RoleDescriptor* issuer,
+    const XMLCh* protocol,
+    const saml1::NameIdentifier* v1nameid,
+    const saml2::NameID* nameid,
+    const XMLCh* authncontext_class,
+    const XMLCh* authncontext_decl,
     const vector<const Assertion*>* tokens
     ) const
 {
-    AttributeResolver* resolver = application.getAttributeResolver();
-    if (!resolver) {
-        m_log.info("no AttributeResolver available, skipping resolution");
-        return NULL;
+    // First we do the extraction of any pushed information.
+    vector<Attribute*> resolvedAttributes;
+    AttributeExtractor* extractor = application.getAttributeExtractor();
+    if (extractor) {
+        m_log.debug("extracting pushed attributes...");
+        Locker extlocker(extractor);
+        if (v1nameid) {
+            try {
+                extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
+            }
+            catch (exception& ex) {
+                m_log.error("caught exception extracting attributes: %s", ex.what());
+            }
+        }
+        else if (nameid) {
+            try {
+                extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
+            }
+            catch (exception& ex) {
+                m_log.error("caught exception extracting attributes: %s", ex.what());
+            }
+        }
+        if (tokens) {
+            for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
+                try {
+                    extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
+                }
+                catch (exception& ex) {
+                    m_log.error("caught exception extracting attributes: %s", ex.what());
+                }
+            }
+        }
+
+        AttributeFilter* filter = application.getAttributeFilter();
+        if (filter && !resolvedAttributes.empty()) {
+            BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
+            Locker filtlocker(filter);
+            try {
+                filter->filterAttributes(fc, resolvedAttributes);
+            }
+            catch (exception& ex) {
+                m_log.error("caught exception filtering attributes: %s", ex.what());
+                m_log.error("dumping extracted attributes due to filtering exception");
+                for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
+                resolvedAttributes.clear();
+            }
+        }
     }
     
     try {
+        AttributeResolver* resolver = application.getAttributeResolver();
+        if (!resolver && !resolvedAttributes.empty()) {
+            m_log.info("no AttributeResolver available, skipping resolution");
+            return new DummyContext(resolvedAttributes);
+        }
+        
         m_log.debug("resolving attributes...");
+
+        Locker locker(resolver);
         auto_ptr<ResolutionContext> ctx(
-            resolver->createResolutionContext(application, httpRequest.getRemoteAddr().c_str(), issuer, nameid, tokens)
+            resolver->createResolutionContext(
+                application,
+                dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()),
+                protocol,
+                nameid,
+                authncontext_class,
+                authncontext_decl,
+                tokens,
+                &resolvedAttributes
+                )
             );
         resolver->resolveAttributes(*ctx.get());
         return ctx.release();
@@ -216,12 +359,15 @@ ResolutionContext* AssertionConsumerService::resolveAttributes(
         m_log.error("attribute resolution failed: %s", ex.what());
     }
     
+    if (!resolvedAttributes.empty())
+        return new DummyContext(resolvedAttributes);
     return NULL;
 }
+#endif
 
-void AssertionConsumerService::maintainHistory(SPRequest& request, const char* providerId, const char* cookieProps) const
+void AssertionConsumerService::maintainHistory(SPRequest& request, const char* entityID, const char* cookieProps) const
 {
-    if (!providerId)
+    if (!entityID)
         return;
         
     const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
@@ -233,7 +379,7 @@ void AssertionConsumerService::maintainHistory(SPRequest& request, const char* p
         // Either leave in memory or set an expiration.
         pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
         if (!days.first || days.second==0) {
-            string c = string(cdc.set(providerId)) + cookieProps;
+            string c = string(cdc.set(entityID)) + cookieProps;
             request.setCookie(CommonDomainCookie::CDCName, c.c_str());
         }
         else {
@@ -246,7 +392,7 @@ void AssertionConsumerService::maintainHistory(SPRequest& request, const char* p
 #endif
             char timebuf[64];
             strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
-            string c = string(cdc.set(providerId)) + cookieProps + "; expires=" + timebuf;
+            string c = string(cdc.set(entityID)) + cookieProps + "; expires=" + timebuf;
             request.setCookie(CommonDomainCookie::CDCName, c.c_str());
         }
     }