Boost changes
[shibboleth/cpp-opensaml.git] / saml / saml2 / metadata / impl / AbstractMetadataProvider.cpp
1 /**
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.
6  *
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
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  */
20
21 /**
22  * AbstractMetadataProvider.cpp
23  * 
24  * Base class for caching metadata providers.
25  */
26
27 #include "internal.h"
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"
33
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>
47
48 using namespace opensaml::saml2md;
49 using namespace xmltooling::logging;
50 using namespace xmltooling;
51 using namespace boost::lambda;
52 using namespace boost;
53 using namespace std;
54 using opensaml::SAMLArtifact;
55
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);
58
59 AbstractMetadataProvider::AbstractMetadataProvider(const DOMElement* e)
60     : ObservableMetadataProvider(e), m_lastUpdate(0),  m_resolver(nullptr), m_credentialLock(Mutex::create())
61 {
62     e = XMLHelper::getFirstChildElement(e, _KeyInfoResolver);
63     if (e) {
64         string t = XMLHelper::getAttrString(e, nullptr, _type);
65         if (!t.empty()) {
66             m_resolverWrapper.reset(XMLToolingConfig::getConfig().KeyInfoResolverManager.newPlugin(t.c_str(), e));
67             m_resolver = m_resolverWrapper.get();
68         }
69         else {
70             throw UnknownExtensionException("<KeyInfoResolver> element found with no type attribute");
71         }
72     }
73 }
74
75 AbstractMetadataProvider::~AbstractMetadataProvider()
76 {
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>());
79 }
80
81 void AbstractMetadataProvider::outputStatus(ostream& os) const
82 {
83     os << "<MetadataProvider";
84
85     if (getId() && *getId()) {
86         os << " id='" << getId() << "'";
87     }
88
89     if (m_lastUpdate > 0) {
90         DateTime ts(m_lastUpdate);
91         ts.parseDateTime();
92         auto_ptr_char timestamp(ts.getFormattedString());
93         os << " lastUpdate='" << timestamp.get() << "'";
94     }
95
96     os << "/>";
97 }
98
99 void AbstractMetadataProvider::emitChangeEvent() const
100 {
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();
105 }
106
107 void AbstractMetadataProvider::indexEntity(EntityDescriptor* site, time_t& validUntil, bool replace) const
108 {
109     // If child expires later than input, reset child, otherwise lower input to match.
110     if (validUntil < site->getValidUntilEpoch())
111         site->setValidUntil(validUntil);
112     else
113         validUntil = site->getValidUntilEpoch();
114
115     auto_ptr_char id(site->getEntityID());
116     if (id.get()) {
117         if (replace) {
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::const_iterator,sitemap_t::const_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;
126             for_each(
127                 existingRange.first, existingRange.second,
128                 lambda::bind(ins, boost::ref(existingSites), lambda::bind(&sitemap_t::value_type::second, _1))
129                 );
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;
134                     ++s;
135                     m_sources.erase(temp);
136                 }
137                 else {
138                     ++s;
139                 }
140             }
141         }
142         m_sites.insert(sitemap_t::value_type(id.get(),site));
143     }
144     
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++) {
148         // SAML 1.x?
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);
156                     if (sid) {
157                         auto_ptr_char sourceid(sid->getID());
158                         if (sourceid.get()) {
159                             m_sources.insert(sitemap_t::value_type(sourceid.get(),site));
160                             break;
161                         }
162                     }
163                 }
164             }
165             
166             // Hash the ID.
167             m_sources.insert(sitemap_t::value_type(SecurityHelper::doHash("SHA1", id.get(), strlen(id.get())),site));
168                 
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());
173                 if (location.get())
174                     m_sources.insert(sitemap_t::value_type(location.get(),site));
175             }
176         }
177         
178         // SAML 2.0?
179         if ((*i)->hasSupport(samlconstants::SAML20P_NS)) {
180             // Hash the ID.
181             m_sources.insert(sitemap_t::value_type(SecurityHelper::doHash("SHA1", id.get(), strlen(id.get())),site));
182         }
183     }
184 }
185
186 void AbstractMetadataProvider::indexGroup(EntitiesDescriptor* group, time_t& validUntil) const
187 {
188     // If child expires later than input, reset child, otherwise lower input to match.
189     if (validUntil < group->getValidUntilEpoch())
190         group->setValidUntil(validUntil);
191     else
192         validUntil = group->getValidUntilEpoch();
193
194     auto_ptr_char name(group->getName());
195     if (name.get()) {
196         m_groups.insert(groupmap_t::value_type(name.get(),group));
197     }
198     
199     // Track the smallest validUntil amongst the children.
200     time_t minValidUntil = validUntil;
201
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;
209     }
210
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;
218     }
219
220     // Pass back up the smallest child we found.
221     if (minValidUntil < validUntil)
222         validUntil = minValidUntil;
223 }
224
225 void AbstractMetadataProvider::index(EntityDescriptor* site, time_t validUntil, bool replace) const
226 {
227     indexEntity(site, validUntil, replace);
228 }
229
230 void AbstractMetadataProvider::index(EntitiesDescriptor* group, time_t validUntil) const
231 {
232     indexGroup(group, validUntil);
233 }
234
235 void AbstractMetadataProvider::clearDescriptorIndex(bool freeSites)
236 {
237     if (freeSites)
238         for_each(m_sites.begin(), m_sites.end(), cleanup_const_pair<string,EntityDescriptor>());
239     m_sites.clear();
240     m_groups.clear();
241     m_sources.clear();
242 }
243
244 const EntitiesDescriptor* AbstractMetadataProvider::getEntitiesDescriptor(const char* name, bool strict) const
245 {
246     pair<groupmap_t::const_iterator,groupmap_t::const_iterator> range=const_cast<const groupmap_t&>(m_groups).equal_range(name);
247
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())
251             return i->second;
252     
253     if (range.first != range.second) {
254         Category& log = Category::getInstance(SAML_LOGCAT".MetadataProvider");
255         if (strict) {
256             log.warn("ignored expired metadata group (%s)", range.first->first.c_str());
257         }
258         else {
259             log.info("no valid metadata found, returning expired metadata group (%s)", range.first->first.c_str());
260             return range.first->second;
261         }
262     }
263
264     return nullptr;
265 }
266
267 pair<const EntityDescriptor*,const RoleDescriptor*> AbstractMetadataProvider::getEntityDescriptor(const Criteria& criteria) const
268 {
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());
275     }
276     else if (criteria.artifact)
277         range = const_cast<const sitemap_t&>(m_sources).equal_range(criteria.artifact->getSource());
278     else
279         return pair<const EntityDescriptor*,const RoleDescriptor*>(nullptr,nullptr);
280     
281     pair<const EntityDescriptor*,const RoleDescriptor*> result;
282     result.first = nullptr;
283     result.second = nullptr;
284     
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;
289             break;
290         }
291     }
292     
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());
297         }
298         else {
299             log.info("no valid metadata found, returning expired instance for (%s)", range.first->first.c_str());
300             result.first = range.first->second;
301         }
302     }
303
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);
308     }
309     
310     return result;
311 }
312
313 const Credential* AbstractMetadataProvider::resolve(const CredentialCriteria* criteria) const
314 {
315     const MetadataCredentialCriteria* metacrit = dynamic_cast<const MetadataCredentialCriteria*>(criteria);
316     if (!metacrit)
317         throw MetadataException("Cannot resolve credentials without a MetadataCredentialCriteria object.");
318
319     Lock lock(m_credentialLock.get());
320     const credmap_t::mapped_type& creds = resolveCredentials(metacrit->getRole());
321
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))
325         );
326     if (c != creds.end())
327         return *c;
328     return nullptr;
329 }
330
331 vector<const Credential*>::size_type AbstractMetadataProvider::resolve(
332     vector<const Credential*>& results, const CredentialCriteria* criteria
333     ) const
334 {
335     const MetadataCredentialCriteria* metacrit = dynamic_cast<const MetadataCredentialCriteria*>(criteria);
336     if (!metacrit)
337         throw MetadataException("Cannot resolve credentials without a MetadataCredentialCriteria object.");
338
339     Lock lock(m_credentialLock.get());
340     const credmap_t::mapped_type& creds = resolveCredentials(metacrit->getRole());
341
342     // Add matching creds to results array.
343     static void (vector<const Credential*>::* push_back)(const Credential* const &) = &vector<const Credential*>::push_back;
344     for_each(
345         creds.begin(), creds.end(),
346         if_(lambda::bind(&CredentialCriteria::matches, metacrit, boost::ref(*_1)))[lambda::bind(push_back, boost::ref(results), _1)]
347         );
348     
349     return results.size();
350 }
351
352 const AbstractMetadataProvider::credmap_t::mapped_type& AbstractMetadataProvider::resolveCredentials(const RoleDescriptor& role) const
353 {
354     credmap_t::const_iterator i = m_credentialMap.find(&role);
355     if (i != m_credentialMap.end())
356         return i->second;
357
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());
366             mcc.release();
367             resolved.push_back(c);
368         }
369     }
370     return resolved;
371 }