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 <xercesc/util/XMLUniDefs.hpp>
35 #include <xmltooling/logging.h>
36 #include <xmltooling/XMLToolingConfig.h>
37 #include <xmltooling/security/Credential.h>
38 #include <xmltooling/security/KeyInfoResolver.h>
39 #include <xmltooling/security/SecurityHelper.h>
40 #include <xmltooling/util/DateTime.h>
41 #include <xmltooling/util/Threads.h>
42 #include <xmltooling/util/XMLHelper.h>
44 using namespace opensaml::saml2md;
45 using namespace xmltooling::logging;
46 using namespace xmltooling;
48 using opensaml::SAMLArtifact;
50 static const XMLCh _KeyInfoResolver[] = UNICODE_LITERAL_15(K,e,y,I,n,f,o,R,e,s,o,l,v,e,r);
51 static const XMLCh type[] = UNICODE_LITERAL_4(t,y,p,e);
53 AbstractMetadataProvider::AbstractMetadataProvider(const DOMElement* e)
54 : ObservableMetadataProvider(e), m_lastUpdate(0), m_resolver(nullptr), m_credentialLock(nullptr)
56 e = XMLHelper::getFirstChildElement(e, _KeyInfoResolver);
58 string t = XMLHelper::getAttrString(e, nullptr, type);
60 m_resolver = XMLToolingConfig::getConfig().KeyInfoResolverManager.newPlugin(t.c_str(), e);
62 throw UnknownExtensionException("<KeyInfoResolver> element found with no type attribute");
64 m_credentialLock = Mutex::create();
67 AbstractMetadataProvider::~AbstractMetadataProvider()
69 for (credmap_t::iterator c = m_credentialMap.begin(); c!=m_credentialMap.end(); ++c)
70 for_each(c->second.begin(), c->second.end(), xmltooling::cleanup<Credential>());
71 delete m_credentialLock;
75 void AbstractMetadataProvider::outputStatus(ostream& os) const
77 os << "<MetadataProvider";
79 if (getId() && *getId()) {
80 os << " id='" << getId() << "'";
83 if (m_lastUpdate > 0) {
84 DateTime ts(m_lastUpdate);
86 auto_ptr_char timestamp(ts.getFormattedString());
87 os << " lastUpdate='" << timestamp.get() << "'";
93 void AbstractMetadataProvider::emitChangeEvent() const
95 for (credmap_t::iterator c = m_credentialMap.begin(); c!=m_credentialMap.end(); ++c)
96 for_each(c->second.begin(), c->second.end(), xmltooling::cleanup<Credential>());
97 m_credentialMap.clear();
98 ObservableMetadataProvider::emitChangeEvent();
101 void AbstractMetadataProvider::indexEntity(EntityDescriptor* site, time_t& validUntil, bool replace) const
103 // If child expires later than input, reset child, otherwise lower input to match.
104 if (validUntil < site->getValidUntilEpoch())
105 site->setValidUntil(validUntil);
107 validUntil = site->getValidUntilEpoch();
109 auto_ptr_char id(site->getEntityID());
112 m_sites.erase(id.get());
113 for (sitemap_t::iterator s = m_sources.begin(); s != m_sources.end();) {
114 if (s->second == site) {
115 sitemap_t::iterator temp = s;
117 m_sources.erase(temp);
124 m_sites.insert(sitemap_t::value_type(id.get(),site));
127 // Process each IdP role.
128 const vector<IDPSSODescriptor*>& roles = const_cast<const EntityDescriptor*>(site)->getIDPSSODescriptors();
129 for (vector<IDPSSODescriptor*>::const_iterator i = roles.begin(); i != roles.end(); i++) {
131 if ((*i)->hasSupport(samlconstants::SAML10_PROTOCOL_ENUM) || (*i)->hasSupport(samlconstants::SAML11_PROTOCOL_ENUM)) {
132 // Check for SourceID extension element.
133 const Extensions* exts = (*i)->getExtensions();
134 if (exts && exts->hasChildren()) {
135 const vector<XMLObject*>& children = exts->getUnknownXMLObjects();
136 for (vector<XMLObject*>::const_iterator ext = children.begin(); ext != children.end(); ++ext) {
137 SourceID* sid = dynamic_cast<SourceID*>(*ext);
139 auto_ptr_char sourceid(sid->getID());
140 if (sourceid.get()) {
141 m_sources.insert(sitemap_t::value_type(sourceid.get(),site));
149 m_sources.insert(sitemap_t::value_type(SecurityHelper::doHash("SHA1", id.get(), strlen(id.get())),site));
151 // Load endpoints for type 0x0002 artifacts.
152 const vector<ArtifactResolutionService*>& locs = const_cast<const IDPSSODescriptor*>(*i)->getArtifactResolutionServices();
153 for (vector<ArtifactResolutionService*>::const_iterator loc = locs.begin(); loc != locs.end(); loc++) {
154 auto_ptr_char location((*loc)->getLocation());
156 m_sources.insert(sitemap_t::value_type(location.get(),site));
161 if ((*i)->hasSupport(samlconstants::SAML20P_NS)) {
163 m_sources.insert(sitemap_t::value_type(SecurityHelper::doHash("SHA1", id.get(), strlen(id.get())),site));
168 void AbstractMetadataProvider::indexGroup(EntitiesDescriptor* group, time_t& validUntil) const
170 // If child expires later than input, reset child, otherwise lower input to match.
171 if (validUntil < group->getValidUntilEpoch())
172 group->setValidUntil(validUntil);
174 validUntil = group->getValidUntilEpoch();
176 auto_ptr_char name(group->getName());
178 m_groups.insert(groupmap_t::value_type(name.get(),group));
181 // Track the smallest validUntil amongst the children.
182 time_t minValidUntil = validUntil;
184 const vector<EntitiesDescriptor*>& groups = const_cast<const EntitiesDescriptor*>(group)->getEntitiesDescriptors();
185 for (vector<EntitiesDescriptor*>::const_iterator i = groups.begin(); i != groups.end(); i++) {
186 // Use the current validUntil fence for each child, but track the smallest we find.
187 time_t subValidUntil = validUntil;
188 indexGroup(*i, subValidUntil);
189 if (subValidUntil < minValidUntil)
190 minValidUntil = subValidUntil;
193 const vector<EntityDescriptor*>& sites = const_cast<const EntitiesDescriptor*>(group)->getEntityDescriptors();
194 for (vector<EntityDescriptor*>::const_iterator j = sites.begin(); j != sites.end(); j++) {
195 // Use the current validUntil fence for each child, but track the smallest we find.
196 time_t subValidUntil = validUntil;
197 indexEntity(*j, subValidUntil);
198 if (subValidUntil < minValidUntil)
199 minValidUntil = subValidUntil;
202 // Pass back up the smallest child we found.
203 if (minValidUntil < validUntil)
204 validUntil = minValidUntil;
207 void AbstractMetadataProvider::index(EntityDescriptor* site, time_t validUntil, bool replace) const
209 indexEntity(site, validUntil, replace);
212 void AbstractMetadataProvider::index(EntitiesDescriptor* group, time_t validUntil) const
214 indexGroup(group, validUntil);
217 void AbstractMetadataProvider::clearDescriptorIndex(bool freeSites)
220 for_each(m_sites.begin(), m_sites.end(), cleanup_const_pair<string,EntityDescriptor>());
226 const EntitiesDescriptor* AbstractMetadataProvider::getEntitiesDescriptor(const char* name, bool strict) const
228 pair<groupmap_t::const_iterator,groupmap_t::const_iterator> range=const_cast<const groupmap_t&>(m_groups).equal_range(name);
230 time_t now=time(nullptr);
231 for (groupmap_t::const_iterator i=range.first; i!=range.second; i++)
232 if (now < i->second->getValidUntilEpoch())
235 if (range.first != range.second) {
236 Category& log = Category::getInstance(SAML_LOGCAT".MetadataProvider");
238 log.warn("ignored expired metadata group (%s)", range.first->first.c_str());
241 log.info("no valid metadata found, returning expired metadata group (%s)", range.first->first.c_str());
242 return range.first->second;
249 pair<const EntityDescriptor*,const RoleDescriptor*> AbstractMetadataProvider::getEntityDescriptor(const Criteria& criteria) const
251 pair<sitemap_t::const_iterator,sitemap_t::const_iterator> range;
252 if (criteria.entityID_ascii)
253 range = const_cast<const sitemap_t&>(m_sites).equal_range(criteria.entityID_ascii);
254 else if (criteria.entityID_unicode) {
255 auto_ptr_char id(criteria.entityID_unicode);
256 range = const_cast<const sitemap_t&>(m_sites).equal_range(id.get());
258 else if (criteria.artifact)
259 range = const_cast<const sitemap_t&>(m_sources).equal_range(criteria.artifact->getSource());
261 return pair<const EntityDescriptor*,const RoleDescriptor*>(nullptr,nullptr);
263 pair<const EntityDescriptor*,const RoleDescriptor*> result;
264 result.first = nullptr;
265 result.second = nullptr;
267 time_t now=time(nullptr);
268 for (sitemap_t::const_iterator i=range.first; i!=range.second; i++) {
269 if (now < i->second->getValidUntilEpoch()) {
270 result.first = i->second;
275 if (!result.first && range.first!=range.second) {
276 Category& log = Category::getInstance(SAML_LOGCAT".MetadataProvider");
277 if (criteria.validOnly) {
278 log.warn("ignored expired metadata instance for (%s)", range.first->first.c_str());
281 log.info("no valid metadata found, returning expired instance for (%s)", range.first->first.c_str());
282 result.first = range.first->second;
286 if (result.first && criteria.role) {
287 result.second = result.first->getRoleDescriptor(*criteria.role, criteria.protocol);
288 if (!result.second && criteria.protocol2)
289 result.second = result.first->getRoleDescriptor(*criteria.role, criteria.protocol2);
295 const Credential* AbstractMetadataProvider::resolve(const CredentialCriteria* criteria) const
297 const MetadataCredentialCriteria* metacrit = dynamic_cast<const MetadataCredentialCriteria*>(criteria);
299 throw MetadataException("Cannot resolve credentials without a MetadataCredentialCriteria object.");
301 Lock lock(m_credentialLock);
302 const credmap_t::mapped_type& creds = resolveCredentials(metacrit->getRole());
304 for (credmap_t::mapped_type::const_iterator c = creds.begin(); c!=creds.end(); ++c)
305 if (metacrit->matches(*(*c)))
310 vector<const Credential*>::size_type AbstractMetadataProvider::resolve(
311 vector<const Credential*>& results, const CredentialCriteria* criteria
314 const MetadataCredentialCriteria* metacrit = dynamic_cast<const MetadataCredentialCriteria*>(criteria);
316 throw MetadataException("Cannot resolve credentials without a MetadataCredentialCriteria object.");
318 Lock lock(m_credentialLock);
319 const credmap_t::mapped_type& creds = resolveCredentials(metacrit->getRole());
321 for (credmap_t::mapped_type::const_iterator c = creds.begin(); c!=creds.end(); ++c)
322 if (metacrit->matches(*(*c)))
323 results.push_back(*c);
324 return results.size();
327 const AbstractMetadataProvider::credmap_t::mapped_type& AbstractMetadataProvider::resolveCredentials(const RoleDescriptor& role) const
329 credmap_t::const_iterator i = m_credentialMap.find(&role);
330 if (i!=m_credentialMap.end())
333 const KeyInfoResolver* resolver = m_resolver ? m_resolver : XMLToolingConfig::getConfig().getKeyInfoResolver();
334 const vector<KeyDescriptor*>& keys = role.getKeyDescriptors();
335 AbstractMetadataProvider::credmap_t::mapped_type& resolved = m_credentialMap[&role];
336 for (vector<KeyDescriptor*>::const_iterator k = keys.begin(); k!=keys.end(); ++k) {
337 if ((*k)->getKeyInfo()) {
338 auto_ptr<MetadataCredentialContext> mcc(new MetadataCredentialContext(*(*k)));
339 Credential* c = resolver->resolve(mcc.get());
341 resolved.push_back(c);