Collapse entity/role lookup in metadata API.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / AssertionConsumerService.cpp
index c5e9080..57dacb3 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;
+using opensaml::saml2md::MetadataProvider;
+using opensaml::saml2md::RoleDescriptor;
+using opensaml::saml2md::EntityDescriptor;
+using opensaml::saml2md::IDPSSODescriptor;
+using opensaml::saml2md::SPSSODescriptor;
+#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, const char* appId, Category& log)
-    : AbstractHandler(e, log), m_decoder(NULL), m_configNS(SHIB2SPCONFIG_NS),
-        m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
+    : AbstractHandler(e, log)
+#ifndef SHIBSP_LITE
+        ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
+#endif
 {
+    if (!e)
+        return;
     string address(appId);
     address += getString("Location").second;
-    address += "::run::ACS";
     setAddress(address.c_str());
+#ifndef SHIBSP_LITE
     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
-        m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(getString("Binding").second,e);
+        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
@@ -78,7 +101,6 @@ pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler
             DDF out,in = wrap(request);
             DDFJanitor jin(in), jout(out);
             
-            in.addmember("application_id").string(request.getApplication().getId());
             try {
                 out=request.getServiceProvider().getListenerService()->send(in);
             }
@@ -87,7 +109,7 @@ pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler
                 if (ex.getProperty("RelayState"))
                     relayState = ex.getProperty("RelayState");
                 try {
-                    recoverRelayState(request, relayState);
+                    recoverRelayState(request.getApplication(), request, relayState);
                 }
                 catch (exception& ex2) {
                     m_log.error("trapped an error during RelayState recovery while handling an error: %s", ex2.what());
@@ -98,7 +120,7 @@ pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler
             // We invoke RelayState recovery one last time on this side of the boundary.
             if (out["RelayState"].isstring())
                 relayState = out["RelayState"].string(); 
-            recoverRelayState(request, relayState);
+            recoverRelayState(request.getApplication(), request, relayState);
     
             // If it worked, we have a session key.
             if (!out["key"].isstring())
@@ -157,6 +179,7 @@ string AssertionConsumerService::processMessage(
     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)
@@ -170,19 +193,13 @@ 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));
     if (!msg.get())
         throw BindingException("Failed to decode an SSO protocol response.");
-    recoverRelayState(httpRequest, relayState);
+    recoverRelayState(application, httpRequest, relayState);
     string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
 
     auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
@@ -190,6 +207,9 @@ string AssertionConsumerService::processMessage(
         entityID = issuer.get();
     
     return key;
+#else
+    throw ConfigurationException("Cannot process message using lite version of shibsp library.");
+#endif
 }
 
 pair<bool,long> AssertionConsumerService::sendRedirect(
@@ -231,35 +251,198 @@ void AssertionConsumerService::checkAddress(
     }
 }
 
+#ifndef SHIBSP_LITE
+
+void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
+    const char* loc = getString("Location").second;
+    string hurl(handlerURL);
+    if (*loc != '/')
+        hurl += '/';
+    hurl += loc;
+    auto_ptr_XMLCh widen(hurl.c_str());
+    saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
+    ep->setLocation(widen.get());
+    ep->setBinding(getXMLString("Binding").second);
+    ep->setIndex(getXMLString("index").second);
+    role.getAssertionConsumerServices().push_back(ep);
+}
+
+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 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;
+    const saml2md::EntityDescriptor* entity = issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : NULL;
+
+    // First we do the extraction of any pushed information, including from metadata.
+    vector<Attribute*> resolvedAttributes;
+    AttributeExtractor* extractor = application.getAttributeExtractor();
+    if (extractor) {
+        Locker extlocker(extractor);
+        if (entity) {
+            pair<bool,const char*> prefix = application.getString("metadataAttributePrefix");
+            if (prefix.first) {
+                m_log.debug("extracting metadata-derived attributes...");
+                try {
+                    extractor->extractAttributes(application, issuer, *entity, resolvedAttributes);
+                    for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
+                        vector<string>& ids = (*a)->getAliases();
+                        for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
+                            *id = prefix.second + *id;
+                    }
+                }
+                catch (exception& ex) {
+                    m_log.error("caught exception extracting attributes: %s", ex.what());
+                }
+            }
+        }
+        m_log.debug("extracting pushed attributes...");
+        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 {
-        m_log.debug("resolving attributes...");
-        auto_ptr<ResolutionContext> ctx(
-            resolver->createResolutionContext(application, httpRequest.getRemoteAddr().c_str(), issuer, nameid, tokens)
-            );
-        resolver->resolveAttributes(*ctx.get(), application.getAttributeIds());
-        return ctx.release();
+        AttributeResolver* resolver = application.getAttributeResolver();
+        if (resolver) {
+            m_log.debug("resolving attributes...");
+
+            Locker locker(resolver);
+            auto_ptr<ResolutionContext> ctx(
+                resolver->createResolutionContext(
+                    application,
+                    entity,
+                    protocol,
+                    nameid,
+                    authncontext_class,
+                    authncontext_decl,
+                    tokens,
+                    &resolvedAttributes
+                    )
+                );
+            resolver->resolveAttributes(*ctx.get());
+            // Copy over any pushed attributes.
+            if (!resolvedAttributes.empty())
+                ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
+            return ctx.release();
+        }
     }
     catch (exception& ex) {
         m_log.error("attribute resolution failed: %s", ex.what());
     }
     
+    if (!resolvedAttributes.empty())
+        return new DummyContext(resolvedAttributes);
     return NULL;
 }
 
+void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
+{
+    policy.setMessageID(assertion.getID());
+    policy.setIssueInstant(assertion.getIssueInstantEpoch());
+
+    if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20P_NS)) {
+        const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
+        if (a2) {
+            m_log.debug("extracting issuer from SAML 2.0 assertion");
+            policy.setIssuer(a2->getIssuer());
+        }
+    }
+    else {
+        const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
+        if (a1) {
+            m_log.debug("extracting issuer from SAML 1.x assertion");
+            policy.setIssuer(a1->getIssuer());
+        }
+    }
+
+    if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
+        m_log.debug("searching metadata for assertion issuer...");
+        MetadataProvider::Criteria mc(policy.getIssuer()->getName(), &IDPSSODescriptor::ELEMENT_QNAME, protocol);
+        pair<const EntityDescriptor*,const RoleDescriptor*> entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
+        if (!entity.first) {
+            auto_ptr_char iname(policy.getIssuer()->getName());
+            m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
+        }
+        else if (!entity.second) {
+            m_log.warn("unable to find compatible IdP role in metadata");
+        }
+        else {
+            policy.setIssuerMetadata(entity.second);
+        }
+    }
+}
+
+#endif
+
 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* entityID, const char* cookieProps) const
 {
     if (!entityID)