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 * AbstractMetadataProvider.cpp
24 * Base class for caching metadata providers.
28 #include "binding/SAMLArtifact.h"
29 #include "saml2/metadata/Metadata.h"
30 #include "saml2/metadata/AbstractMetadataProvider.h"
31 #include "saml2/metadata/MetadataCredentialContext.h"
32 #include "saml2/metadata/MetadataCredentialCriteria.h"
34 #include <boost/iterator/indirect_iterator.hpp>
35 #include <boost/lambda/bind.hpp>
36 #include <boost/lambda/if.hpp>
37 #include <boost/lambda/lambda.hpp>
38 #include <xercesc/util/XMLUniDefs.hpp>
39 #include <xmltooling/logging.h>
40 #include <xmltooling/XMLToolingConfig.h>
41 #include <xmltooling/security/Credential.h>
42 #include <xmltooling/security/KeyInfoResolver.h>
43 #include <xmltooling/security/SecurityHelper.h>
44 #include <xmltooling/util/DateTime.h>
45 #include <xmltooling/util/Threads.h>
46 #include <xmltooling/util/XMLHelper.h>
48 using namespace opensaml::saml2md;
49 using namespace xmltooling::logging;
50 using namespace xmltooling;
51 using namespace boost::lambda;
52 using namespace boost;
54 using opensaml::SAMLArtifact;
56 static const XMLCh _KeyInfoResolver[] = UNICODE_LITERAL_15(K,e,y,I,n,f,o,R,e,s,o,l,v,e,r);
57 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
59 AbstractMetadataProvider::AbstractMetadataProvider(const DOMElement* e)
60 : ObservableMetadataProvider(e), m_lastUpdate(0), m_resolver(nullptr), m_credentialLock(Mutex::create())
62 e = XMLHelper::getFirstChildElement(e, _KeyInfoResolver);
64 string t = XMLHelper::getAttrString(e, nullptr, _type);
66 m_resolverWrapper.reset(XMLToolingConfig::getConfig().KeyInfoResolverManager.newPlugin(t.c_str(), e));
67 m_resolver = m_resolverWrapper.get();
70 throw UnknownExtensionException("<KeyInfoResolver> element found with no type attribute");
75 AbstractMetadataProvider::~AbstractMetadataProvider()
77 for (credmap_t::iterator c = m_credentialMap.begin(); c!=m_credentialMap.end(); ++c)
78 for_each(c->second.begin(), c->second.end(), xmltooling::cleanup<Credential>());
81 void AbstractMetadataProvider::outputStatus(ostream& os) const
83 os << "<MetadataProvider";
85 if (getId() && *getId()) {
86 os << " id='" << getId() << "'";
89 if (m_lastUpdate > 0) {
90 DateTime ts(m_lastUpdate);
92 auto_ptr_char timestamp(ts.getFormattedString());
93 os << " lastUpdate='" << timestamp.get() << "'";
99 void AbstractMetadataProvider::emitChangeEvent() const
101 for (credmap_t::iterator c = m_credentialMap.begin(); c!=m_credentialMap.end(); ++c)
102 for_each(c->second.begin(), c->second.end(), xmltooling::cleanup<Credential>());
103 m_credentialMap.clear();
104 ObservableMetadataProvider::emitChangeEvent();
107 void AbstractMetadataProvider::indexEntity(EntityDescriptor* site, time_t& validUntil, bool replace) const
109 // If child expires later than input, reset child, otherwise lower input to match.
110 if (validUntil < site->getValidUntilEpoch())
111 site->setValidUntil(validUntil);
113 validUntil = site->getValidUntilEpoch();
115 auto_ptr_char id(site->getEntityID());
118 // The data structure here needs work.
119 // We have to find all the sites stored against the replaced ID. Then we have to
120 // search for those sites in the entire set of sites tracked by the sources map and
121 // remove them from both places.
122 set<const EntityDescriptor*> existingSites;
123 pair<sitemap_t::iterator,sitemap_t::iterator> existingRange = m_sites.equal_range(id.get());
124 static pair<set<const EntityDescriptor*>::iterator,bool> (set<const EntityDescriptor*>::* ins)(const EntityDescriptor* const &) =
125 &set<const EntityDescriptor*>::insert;
127 existingRange.first, existingRange.second,
128 lambda::bind(ins, boost::ref(existingSites), lambda::bind(&sitemap_t::value_type::second, _1))
130 m_sites.erase(existingRange.first, existingRange.second);
131 for (sitemap_t::iterator s = m_sources.begin(); s != m_sources.end();) {
132 if (existingSites.count(s->second) > 0) {
133 sitemap_t::iterator temp = s;
135 m_sources.erase(temp);
142 m_sites.insert(sitemap_t::value_type(id.get(),site));
145 // Process each IdP role.
146 const vector<IDPSSODescriptor*>& roles = const_cast<const EntityDescriptor*>(site)->getIDPSSODescriptors();
147 for (vector<IDPSSODescriptor*>::const_iterator i = roles.begin(); i != roles.end(); i++) {
149 if ((*i)->hasSupport(samlconstants::SAML10_PROTOCOL_ENUM) || (*i)->hasSupport(samlconstants::SAML11_PROTOCOL_ENUM)) {
150 // Check for SourceID extension element.
151 const Extensions* exts = (*i)->getExtensions();
152 if (exts && exts->hasChildren()) {
153 const vector<XMLObject*>& children = exts->getUnknownXMLObjects();
154 for (vector<XMLObject*>::const_iterator ext = children.begin(); ext != children.end(); ++ext) {
155 SourceID* sid = dynamic_cast<SourceID*>(*ext);
157 auto_ptr_char sourceid(sid->getID());
158 if (sourceid.get()) {
159 m_sources.insert(sitemap_t::value_type(sourceid.get(),site));
167 m_sources.insert(sitemap_t::value_type(SecurityHelper::doHash("SHA1", id.get(), strlen(id.get())),site));
169 // Load endpoints for type 0x0002 artifacts.
170 const vector<ArtifactResolutionService*>& locs = const_cast<const IDPSSODescriptor*>(*i)->getArtifactResolutionServices();
171 for (vector<ArtifactResolutionService*>::const_iterator loc = locs.begin(); loc != locs.end(); loc++) {
172 auto_ptr_char location((*loc)->getLocation());
174 m_sources.insert(sitemap_t::value_type(location.get(),site));
179 if ((*i)->hasSupport(samlconstants::SAML20P_NS)) {
181 m_sources.insert(sitemap_t::value_type(SecurityHelper::doHash("SHA1", id.get(), strlen(id.get())),site));
186 void AbstractMetadataProvider::indexGroup(EntitiesDescriptor* group, time_t& validUntil) const
188 // If child expires later than input, reset child, otherwise lower input to match.
189 if (validUntil < group->getValidUntilEpoch())
190 group->setValidUntil(validUntil);
192 validUntil = group->getValidUntilEpoch();
194 auto_ptr_char name(group->getName());
196 m_groups.insert(groupmap_t::value_type(name.get(),group));
199 // Track the smallest validUntil amongst the children.
200 time_t minValidUntil = validUntil;
202 const vector<EntitiesDescriptor*>& groups = const_cast<const EntitiesDescriptor*>(group)->getEntitiesDescriptors();
203 for (vector<EntitiesDescriptor*>::const_iterator i = groups.begin(); i != groups.end(); i++) {
204 // Use the current validUntil fence for each child, but track the smallest we find.
205 time_t subValidUntil = validUntil;
206 indexGroup(*i, subValidUntil);
207 if (subValidUntil < minValidUntil)
208 minValidUntil = subValidUntil;
211 const vector<EntityDescriptor*>& sites = const_cast<const EntitiesDescriptor*>(group)->getEntityDescriptors();
212 for (vector<EntityDescriptor*>::const_iterator j = sites.begin(); j != sites.end(); j++) {
213 // Use the current validUntil fence for each child, but track the smallest we find.
214 time_t subValidUntil = validUntil;
215 indexEntity(*j, subValidUntil);
216 if (subValidUntil < minValidUntil)
217 minValidUntil = subValidUntil;
220 // Pass back up the smallest child we found.
221 if (minValidUntil < validUntil)
222 validUntil = minValidUntil;
225 void AbstractMetadataProvider::index(EntityDescriptor* site, time_t validUntil, bool replace) const
227 indexEntity(site, validUntil, replace);
230 void AbstractMetadataProvider::index(EntitiesDescriptor* group, time_t validUntil) const
232 indexGroup(group, validUntil);
235 void AbstractMetadataProvider::clearDescriptorIndex(bool freeSites)
238 for_each(m_sites.begin(), m_sites.end(), cleanup_const_pair<string,EntityDescriptor>());
244 const EntitiesDescriptor* AbstractMetadataProvider::getEntitiesDescriptor(const char* name, bool strict) const
246 pair<groupmap_t::const_iterator,groupmap_t::const_iterator> range=const_cast<const groupmap_t&>(m_groups).equal_range(name);
248 time_t now=time(nullptr);
249 for (groupmap_t::const_iterator i=range.first; i!=range.second; i++)
250 if (now < i->second->getValidUntilEpoch())
253 if (range.first != range.second) {
254 Category& log = Category::getInstance(SAML_LOGCAT".MetadataProvider");
256 log.warn("ignored expired metadata group (%s)", range.first->first.c_str());
259 log.info("no valid metadata found, returning expired metadata group (%s)", range.first->first.c_str());
260 return range.first->second;
267 pair<const EntityDescriptor*,const RoleDescriptor*> AbstractMetadataProvider::getEntityDescriptor(const Criteria& criteria) const
269 pair<sitemap_t::const_iterator,sitemap_t::const_iterator> range;
270 if (criteria.entityID_ascii)
271 range = const_cast<const sitemap_t&>(m_sites).equal_range(criteria.entityID_ascii);
272 else if (criteria.entityID_unicode) {
273 auto_ptr_char id(criteria.entityID_unicode);
274 range = const_cast<const sitemap_t&>(m_sites).equal_range(id.get());
276 else if (criteria.artifact)
277 range = const_cast<const sitemap_t&>(m_sources).equal_range(criteria.artifact->getSource());
279 return pair<const EntityDescriptor*,const RoleDescriptor*>(nullptr,nullptr);
281 pair<const EntityDescriptor*,const RoleDescriptor*> result;
282 result.first = nullptr;
283 result.second = nullptr;
285 time_t now=time(nullptr);
286 for (sitemap_t::const_iterator i=range.first; i!=range.second; i++) {
287 if (now < i->second->getValidUntilEpoch()) {
288 result.first = i->second;
293 if (!result.first && range.first!=range.second) {
294 Category& log = Category::getInstance(SAML_LOGCAT".MetadataProvider");
295 if (criteria.validOnly) {
296 log.warn("ignored expired metadata instance for (%s)", range.first->first.c_str());
299 log.info("no valid metadata found, returning expired instance for (%s)", range.first->first.c_str());
300 result.first = range.first->second;
304 if (result.first && criteria.role) {
305 result.second = result.first->getRoleDescriptor(*criteria.role, criteria.protocol);
306 if (!result.second && criteria.protocol2)
307 result.second = result.first->getRoleDescriptor(*criteria.role, criteria.protocol2);
313 const Credential* AbstractMetadataProvider::resolve(const CredentialCriteria* criteria) const
315 const MetadataCredentialCriteria* metacrit = dynamic_cast<const MetadataCredentialCriteria*>(criteria);
317 throw MetadataException("Cannot resolve credentials without a MetadataCredentialCriteria object.");
319 Lock lock(m_credentialLock.get());
320 const credmap_t::mapped_type& creds = resolveCredentials(metacrit->getRole());
322 // Indirect iterator derefs the pointers in the vector to pass to the matches() method by reference.
323 credmap_t::mapped_type::const_iterator c = find_if(
324 creds.begin(), creds.end(), lambda::bind(&CredentialCriteria::matches, metacrit, boost::ref(*_1))
326 if (c != creds.end())
331 vector<const Credential*>::size_type AbstractMetadataProvider::resolve(
332 vector<const Credential*>& results, const CredentialCriteria* criteria
335 const MetadataCredentialCriteria* metacrit = dynamic_cast<const MetadataCredentialCriteria*>(criteria);
337 throw MetadataException("Cannot resolve credentials without a MetadataCredentialCriteria object.");
339 Lock lock(m_credentialLock.get());
340 const credmap_t::mapped_type& creds = resolveCredentials(metacrit->getRole());
342 // Add matching creds to results array.
343 static void (vector<const Credential*>::* push_back)(const Credential* const &) = &vector<const Credential*>::push_back;
345 creds.begin(), creds.end(),
346 if_(lambda::bind(&CredentialCriteria::matches, metacrit, boost::ref(*_1)))[lambda::bind(push_back, boost::ref(results), _1)]
349 return results.size();
352 const AbstractMetadataProvider::credmap_t::mapped_type& AbstractMetadataProvider::resolveCredentials(const RoleDescriptor& role) const
354 credmap_t::const_iterator i = m_credentialMap.find(&role);
355 if (i != m_credentialMap.end())
358 const KeyInfoResolver* resolver = m_resolver ? m_resolver : XMLToolingConfig::getConfig().getKeyInfoResolver();
359 const vector<KeyDescriptor*>& keys = role.getKeyDescriptors();
360 AbstractMetadataProvider::credmap_t::mapped_type& resolved = m_credentialMap[&role];
361 for (indirect_iterator<vector<KeyDescriptor*>::const_iterator> k = make_indirect_iterator(keys.begin());
362 k != make_indirect_iterator(keys.end()); ++k) {
363 if (k->getKeyInfo()) {
364 auto_ptr<MetadataCredentialContext> mcc(new MetadataCredentialContext(*k));
365 Credential* c = resolver->resolve(mcc.get());
367 resolved.push_back(c);