Disallow metadata that's statically invalid at the time of load.
[shibboleth/cpp-opensaml.git] / saml / saml2 / metadata / impl / DynamicMetadataProvider.cpp
index a23308f..b7b53f1 100644 (file)
@@ -1,6 +1,6 @@
 /*
  *  Copyright 2001-2007 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
 
 /**
  * DynamicMetadataProvider.cpp
- * 
- * Base class for caching metadata providers.
+ *
+ * Simple implementation of a dynamic caching MetadataProvider.
  */
 
 #include "internal.h"
+#include "binding/SAMLArtifact.h"
 #include "saml2/metadata/Metadata.h"
 #include "saml2/metadata/DynamicMetadataProvider.h"
 
-#include <xercesc/framework/Wrapper4InputSource.hpp>\r
-#include <xercesc/framework/URLInputSource.hpp>\r
-#include <xercesc/util/XMLUniDefs.hpp>\r
-#include <xmltooling/logging.h>\r
+#include <xercesc/framework/Wrapper4InputSource.hpp>
+#include <xercesc/framework/URLInputSource.hpp>
+#include <xercesc/util/XMLUniDefs.hpp>
+#include <xmltooling/logging.h>
 #include <xmltooling/util/XMLHelper.h>
 
 using namespace opensaml::saml2md;
@@ -35,7 +36,12 @@ using namespace xmltooling::logging;
 using namespace xmltooling;
 using namespace std;
 
-static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);\r
+# ifndef min
+#  define min(a,b)            (((a) < (b)) ? (a) : (b))
+# endif
+
+static const XMLCh maxCacheDuration[] = UNICODE_LITERAL_16(m,a,x,C,a,c,h,e,D,u,r,a,t,i,o,n);
+static const XMLCh validate[] =         UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
 
 namespace opensaml {
     namespace saml2md {
@@ -47,10 +53,16 @@ namespace opensaml {
 };
 
 DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e)
-    : AbstractMetadataProvider(e), m_lock(RWLock::create())
+    : AbstractMetadataProvider(e), m_maxCacheDuration(28800), m_lock(RWLock::create())
 {
-    const XMLCh* flag=e ? e->getAttributeNS(NULL,validate) : NULL;\r
-    m_validate=(XMLString::equals(flag,xmlconstants::XML_TRUE) || XMLString::equals(flag,xmlconstants::XML_ONE));\r
+    const XMLCh* flag=e ? e->getAttributeNS(NULL,validate) : NULL;
+    m_validate=(XMLString::equals(flag,xmlconstants::XML_TRUE) || XMLString::equals(flag,xmlconstants::XML_ONE));
+    flag = e ? e->getAttributeNS(NULL,maxCacheDuration) : NULL;
+    if (flag && *flag) {
+        m_maxCacheDuration = XMLString::parseInt(flag);
+        if (m_maxCacheDuration == 0)
+            m_maxCacheDuration = 28800;
+    }
 }
 
 DynamicMetadataProvider::~DynamicMetadataProvider()
@@ -60,61 +72,109 @@ DynamicMetadataProvider::~DynamicMetadataProvider()
     delete m_lock;
 }
 
-const EntityDescriptor* DynamicMetadataProvider::getEntityDescriptor(const char* name, bool strict) const
+pair<const EntityDescriptor*,const RoleDescriptor*> DynamicMetadataProvider::getEntityDescriptor(const Criteria& criteria) const
 {
     // Check cache while holding the read lock.
-    const EntityDescriptor* entity = AbstractMetadataProvider::getEntityDescriptor(name, strict);
-    if (entity)
+    pair<const EntityDescriptor*,const RoleDescriptor*> entity = AbstractMetadataProvider::getEntityDescriptor(criteria);
+    if (entity.first)   // even if the role isn't found, we're done
+        return entity;
+
+    string name;
+    if (criteria.entityID_ascii)
+        name = criteria.entityID_ascii;
+    else if (criteria.entityID_unicode) {
+        auto_ptr_char temp(criteria.entityID_unicode);
+        name = temp.get();
+    }
+    else if (criteria.artifact)
+        name = criteria.artifact->getSource();
+    else
         return entity;
 
     Category& log = Category::getInstance(SAML_LOGCAT".MetadataProvider.Dynamic");
-    log.info("resolving metadata for (%s)", name);
+    log.info("resolving metadata for (%s)", name.c_str());
 
-    // Try resolving it.
-    auto_ptr<EntityDescriptor> entity2(resolve(name));
+    try {
+        // Try resolving it.
+        auto_ptr<EntityDescriptor> entity2(resolve(criteria));
 
-    // Filter it, which may throw.
-    doFilters(*entity2.get());
+        // Verify the entityID.
+        if (criteria.entityID_unicode && !XMLString::equals(criteria.entityID_unicode, entity2->getEntityID())) {
+            Category::getInstance(SAML_LOGCAT".MetadataProvider.Dynamic").error("metadata instance did not match expected entityID");
+            return entity;
+        }
+        else {
+            auto_ptr_XMLCh temp2(name.c_str());
+            if (!XMLString::equals(temp2.get(), entity2->getEntityID())) {
+                Category::getInstance(SAML_LOGCAT".MetadataProvider.Dynamic").error("metadata instance did not match expected entityID");
+                return entity;
+            }
+        }
 
-    log.info("caching resolved metadata for (%s)", name);
+        // Filter it, which may throw.
+        doFilters(*entity2.get());
 
-    // Translate cacheDuration into validUntil.
-    if (entity2->getCacheDuration())
-        entity2->setValidUntil(time(NULL) + entity2->getCacheDurationEpoch());
+        time_t now = time(NULL);
 
-    // Upgrade our lock so we can cache the new metadata.
-    m_lock->unlock();
-    m_lock->wrlock();
+        if (entity2->getValidUntil() && entity2->getValidUntilEpoch() < now + 60)
+            throw MetadataException("Metadata was already invalid at the time of retrieval.");
 
-    // Notify observers.
-    emitChangeEvent();
+        log.info("caching resolved metadata for (%s)", name.c_str());
 
-    // Make sure we clear out any existing copies, including stale metadata or if somebody snuck in.
-    index(entity2.release(), SAMLTIME_MAX, true);
+        // Upgrade our lock so we can cache the new metadata.
+        m_lock->unlock();
+        m_lock->wrlock();
 
-    // Downgrade back to a read lock.
-    m_lock->unlock();
-    m_lock->rdlock();
+        // Notify observers.
+        emitChangeEvent();
+
+        // Make sure we clear out any existing copies, including stale metadata or if somebody snuck in.
+        time_t exp = m_maxCacheDuration;
+        if (entity2->getCacheDuration())
+            exp = min(m_maxCacheDuration, entity2->getCacheDurationEpoch());
+        exp += now;
+        index(entity2.release(), exp, true);
+
+        // Downgrade back to a read lock.
+        m_lock->unlock();
+        m_lock->rdlock();
+    }
+    catch (exception& e) {
+        Category::getInstance(SAML_LOGCAT".MetadataProvider.Dynamic").error(
+            "error while resolving entityID (%s): %s", name.c_str(), e.what()
+            );
+        return entity;
+    }
 
     // Rinse and repeat.
-    return getEntityDescriptor(name, strict);
+    return getEntityDescriptor(criteria);
 }
 
-EntityDescriptor* DynamicMetadataProvider::resolve(const char* entityID) const
+EntityDescriptor* DynamicMetadataProvider::resolve(const Criteria& criteria) const
 {
-    try {\r
-        DOMDocument* doc=NULL;\r
-        auto_ptr_XMLCh widenit(entityID);\r
-        URLInputSource src(widenit.get());\r
-        Wrapper4InputSource dsrc(&src,false);\r
-        if (m_validate)\r
-            doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);\r
-        else\r
-            doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);\r
-\r
+    string name;
+    if (criteria.entityID_ascii)
+        name = criteria.entityID_ascii;
+    else if (criteria.entityID_unicode) {
+        auto_ptr_char temp(criteria.entityID_unicode);
+        name = temp.get();
+    }
+    else if (criteria.artifact)
+        name = criteria.artifact->getSource();
+
+    try {
+        DOMDocument* doc=NULL;
+        auto_ptr_XMLCh widenit(name.c_str());
+        URLInputSource src(widenit.get());
+        Wrapper4InputSource dsrc(&src,false);
+        if (m_validate)
+            doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);
+        else
+            doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
+
         // Wrap the document for now.
         XercesJanitor<DOMDocument> docjanitor(doc);
-                
+
         // Unmarshall objects, binding the document.
         auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
         docjanitor.release();
@@ -126,20 +186,14 @@ EntityDescriptor* DynamicMetadataProvider::resolve(const char* entityID) const
                 "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
                 );
         }
-        xmlObject.release();\r
-        return entity;\r
-    }\r
-    catch (XMLException& e) {\r
-        auto_ptr_char msg(e.getMessage());\r
-        Category::getInstance(SAML_LOGCAT".MetadataProvider.Dynamic").error(\r
-            "Xerces error while resolving entityID (%s): %s", entityID, msg.get()\r
-            );\r
-        throw MetadataException(msg.get());\r
-    }\r
-    catch (exception& e) {\r
-        Category::getInstance(SAML_LOGCAT".MetadataProvider.Dynamic").error(\r
-            "error while resolving entityID (%s): %s", entityID, e.what()\r
-            );\r
-        throw;\r
-    }\r
+        xmlObject.release();
+        return entity;
+    }
+    catch (XMLException& e) {
+        auto_ptr_char msg(e.getMessage());
+        Category::getInstance(SAML_LOGCAT".MetadataProvider.Dynamic").error(
+            "Xerces error while resolving entityID (%s): %s", name.c_str(), msg.get()
+            );
+        throw MetadataException(msg.get());
+    }
 }