2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * DynamicMetadataProvider.cpp
24 * Simple implementation of a dynamic caching MetadataProvider.
28 #include "binding/SAMLArtifact.h"
29 #include "saml2/metadata/Metadata.h"
30 #include "saml2/metadata/DynamicMetadataProvider.h"
32 #include <xercesc/framework/Wrapper4InputSource.hpp>
33 #include <xercesc/util/XMLUniDefs.hpp>
34 #include <xmltooling/logging.h>
35 #include <xmltooling/XMLToolingConfig.h>
36 #include <xmltooling/util/ParserPool.h>
37 #include <xmltooling/util/Threads.h>
38 #include <xmltooling/util/XMLHelper.h>
39 #include <xmltooling/validation/ValidatorSuite.h>
41 using namespace opensaml::saml2md;
42 using namespace xmltooling::logging;
43 using namespace xmltooling;
47 # define min(a,b) (((a) < (b)) ? (a) : (b))
50 static const XMLCh id[] = UNICODE_LITERAL_2(i,d);
51 static const XMLCh maxCacheDuration[] = UNICODE_LITERAL_16(m,a,x,C,a,c,h,e,D,u,r,a,t,i,o,n);
52 static const XMLCh minCacheDuration[] = UNICODE_LITERAL_16(m,i,n,C,a,c,h,e,D,u,r,a,t,i,o,n);
53 static const XMLCh refreshDelayFactor[] = UNICODE_LITERAL_18(r,e,f,r,e,s,h,D,e,l,a,y,F,a,c,t,o,r);
54 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
58 MetadataProvider* SAML_DLLLOCAL DynamicMetadataProviderFactory(const DOMElement* const & e)
60 return new DynamicMetadataProvider(e);
65 DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e)
66 : AbstractMetadataProvider(e),
67 m_validate(XMLHelper::getAttrBool(e, false, validate)),
68 m_id(XMLHelper::getAttrString(e, "Dynamic", id)),
69 m_lock(RWLock::create()),
70 m_refreshDelayFactor(0.75),
71 m_minCacheDuration(XMLHelper::getAttrInt(e, 600, minCacheDuration)),
72 m_maxCacheDuration(XMLHelper::getAttrInt(e, 28800, maxCacheDuration))
74 if (m_minCacheDuration > m_maxCacheDuration) {
75 Category::getInstance(SAML_LOGCAT ".MetadataProvider.Dynamic").error(
76 "minCacheDuration setting exceeds maxCacheDuration setting, lowering to match it"
78 m_minCacheDuration = m_maxCacheDuration;
81 const XMLCh* delay = e ? e->getAttributeNS(nullptr, refreshDelayFactor) : nullptr;
82 if (delay && *delay) {
83 auto_ptr_char temp(delay);
84 m_refreshDelayFactor = atof(temp.get());
85 if (m_refreshDelayFactor <= 0.0 || m_refreshDelayFactor >= 1.0) {
86 Category::getInstance(SAML_LOGCAT ".MetadataProvider.Dynamic").error(
87 "invalid refreshDelayFactor setting, using default"
89 m_refreshDelayFactor = 0.75;
94 DynamicMetadataProvider::~DynamicMetadataProvider()
96 // Each entity in the map is unique (no multimap semantics), so this is safe.
97 clearDescriptorIndex(true);
100 const XMLObject* DynamicMetadataProvider::getMetadata() const
102 throw MetadataException("getMetadata operation not implemented on this provider.");
105 Lockable* DynamicMetadataProvider::lock()
111 void DynamicMetadataProvider::unlock()
116 void DynamicMetadataProvider::init()
120 const char* DynamicMetadataProvider::getId() const
125 pair<const EntityDescriptor*,const RoleDescriptor*> DynamicMetadataProvider::getEntityDescriptor(const Criteria& criteria) const
127 Category& log = Category::getInstance(SAML_LOGCAT ".MetadataProvider.Dynamic");
129 // First we check the underlying cache.
130 pair<const EntityDescriptor*,const RoleDescriptor*> entity = AbstractMetadataProvider::getEntityDescriptor(criteria);
132 // Check to see if we're within the caching interval for a lookup of this entity.
133 // This applies *even if we didn't get a hit* because the cache map tracks failed
134 // lookups also, to prevent constant reload attempts.
135 cachemap_t::iterator cit;
137 cit = m_cacheMap.find(entity.first->getEntityID());
139 else if (criteria.entityID_ascii) {
140 auto_ptr_XMLCh widetemp(criteria.entityID_ascii);
141 cit = m_cacheMap.find(widetemp.get());
143 else if (criteria.entityID_unicode) {
144 cit = m_cacheMap.find(criteria.entityID_unicode);
146 else if (criteria.artifact) {
147 auto_ptr_XMLCh widetemp(criteria.artifact->getSource().c_str());
148 cit = m_cacheMap.find(widetemp.get());
151 cit = m_cacheMap.end();
153 if (cit != m_cacheMap.end()) {
154 if (time(nullptr) <= cit->second)
156 m_cacheMap.erase(cit);
160 if (criteria.entityID_ascii) {
161 name = criteria.entityID_ascii;
163 else if (criteria.entityID_unicode) {
164 auto_ptr_char temp(criteria.entityID_unicode);
167 else if (criteria.artifact) {
168 name = criteria.artifact->getSource();
175 log.info("metadata for (%s) is beyond caching interval, attempting to refresh", name.c_str());
177 log.info("resolving metadata for (%s)", name.c_str());
181 auto_ptr<EntityDescriptor> entity2(resolve(criteria));
183 // Verify the entityID.
184 if (criteria.entityID_unicode && !XMLString::equals(criteria.entityID_unicode, entity2->getEntityID())) {
185 log.error("metadata instance did not match expected entityID");
189 auto_ptr_XMLCh temp2(name.c_str());
190 if (!XMLString::equals(temp2.get(), entity2->getEntityID())) {
191 log.error("metadata instance did not match expected entityID");
196 // Preprocess the metadata (even if we schema-validated).
198 SchemaValidators.validate(entity2.get());
200 catch (exception& ex) {
201 log.error("metadata intance failed manual validation checking: %s", ex.what());
202 throw MetadataException("Metadata instance failed manual validation checking.");
205 // Filter it, which may throw.
208 time_t now = time(nullptr);
209 if (entity2->getValidUntil() && entity2->getValidUntilEpoch() < now + 60)
210 throw MetadataException("Metadata was already invalid at the time of retrieval.");
212 log.info("caching resolved metadata for (%s)", name.c_str());
214 // Compute the smaller of the validUntil / cacheDuration constraints.
215 time_t cacheExp = (entity2->getValidUntil() ? entity2->getValidUntilEpoch() : SAMLTIME_MAX) - now;
216 if (entity2->getCacheDuration())
217 cacheExp = min(cacheExp, entity2->getCacheDurationEpoch());
219 // Adjust for the delay factor.
220 cacheExp *= m_refreshDelayFactor;
222 // Bound by max and min.
223 if (cacheExp > m_maxCacheDuration)
224 cacheExp = m_maxCacheDuration;
225 else if (cacheExp < m_minCacheDuration)
226 cacheExp = m_minCacheDuration;
228 log.info("next refresh of metadata for (%s) no sooner than %u seconds", name.c_str(), cacheExp);
230 // Upgrade our lock so we can cache the new metadata.
235 emitChangeEvent(*entity2);
237 // Record the proper refresh time.
238 m_cacheMap[entity2->getEntityID()] = now + cacheExp;
240 // Make sure we clear out any existing copies, including stale metadata or if somebody snuck in.
241 cacheExp = SAMLTIME_MAX;
242 indexEntity(entity2.get(), cacheExp, true);
247 // Downgrade back to a read lock.
251 catch (exception& e) {
252 log.error("error while resolving entityID (%s): %s", name.c_str(), e.what());
253 // This will return entries that are beyond their cache period,
254 // but not beyond their validity unless that criteria option was set.
255 // If it is a cache-expired entry, bump the cache period to prevent retries.
257 m_cacheMap[entity.first->getEntityID()] = time(nullptr) + m_minCacheDuration;
258 else if (criteria.entityID_unicode)
259 m_cacheMap[criteria.entityID_unicode] = time(nullptr) + m_minCacheDuration;
261 auto_ptr_XMLCh widetemp(name.c_str());
262 m_cacheMap[widetemp.get()] = time(nullptr) + m_minCacheDuration;
264 log.warn("next refresh of metadata for (%s) no sooner than %u seconds", name.c_str(), m_minCacheDuration);
269 return getEntityDescriptor(criteria);
272 EntityDescriptor* DynamicMetadataProvider::resolve(const Criteria& criteria) const
275 if (criteria.entityID_ascii) {
276 name = criteria.entityID_ascii;
278 else if (criteria.entityID_unicode) {
279 auto_ptr_char temp(criteria.entityID_unicode);
282 else if (criteria.artifact) {
283 throw MetadataException("Unable to resolve metadata dynamically from an artifact.");
287 DOMDocument* doc=nullptr;
288 auto_ptr_XMLCh widenit(name.c_str());
289 URLInputSource src(widenit.get());
290 Wrapper4InputSource dsrc(&src,false);
292 doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);
294 doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
296 // Wrap the document for now.
297 XercesJanitor<DOMDocument> docjanitor(doc);
299 // Unmarshall objects, binding the document.
300 auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
301 docjanitor.release();
303 // Make sure it's metadata.
304 EntityDescriptor* entity = dynamic_cast<EntityDescriptor*>(xmlObject.get());
306 throw MetadataException(
307 "Root of metadata instance not recognized: $1", params(1,xmlObject->getElementQName().toString().c_str())
313 catch (XMLException& e) {
314 auto_ptr_char msg(e.getMessage());
315 Category::getInstance(SAML_LOGCAT ".MetadataProvider.Dynamic").error(
316 "Xerces error while resolving entityID (%s): %s", name.c_str(), msg.get()
318 throw MetadataException(msg.get());