Add provider Id, track last update, report in status method.
[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 <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>
43
44 using namespace opensaml::saml2md;
45 using namespace xmltooling::logging;
46 using namespace xmltooling;
47 using namespace std;
48 using opensaml::SAMLArtifact;
49
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);
52
53 AbstractMetadataProvider::AbstractMetadataProvider(const DOMElement* e)
54     : ObservableMetadataProvider(e), m_lastUpdate(0),  m_resolver(nullptr), m_credentialLock(nullptr)
55 {
56     e = XMLHelper::getFirstChildElement(e, _KeyInfoResolver);
57     if (e) {
58         string t = XMLHelper::getAttrString(e, nullptr, type);
59         if (!t.empty())
60             m_resolver = XMLToolingConfig::getConfig().KeyInfoResolverManager.newPlugin(t.c_str(), e);
61         else
62             throw UnknownExtensionException("<KeyInfoResolver> element found with no type attribute");
63     }
64     m_credentialLock = Mutex::create();
65 }
66
67 AbstractMetadataProvider::~AbstractMetadataProvider()
68 {
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;
72     delete m_resolver;
73 }
74
75 void AbstractMetadataProvider::outputStatus(ostream& os) const
76 {
77     os << "<MetadataProvider";
78
79     if (getId() && *getId()) {
80         os << " id='" << getId() << "'";
81     }
82
83     if (m_lastUpdate > 0) {
84         DateTime ts(m_lastUpdate);
85         ts.parseDateTime();
86         auto_ptr_char timestamp(ts.getFormattedString());
87         os << " lastUpdate='" << timestamp.get() << "'";
88     }
89
90     os << "/>";
91 }
92
93 void AbstractMetadataProvider::emitChangeEvent() const
94 {
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();
99 }
100
101 void AbstractMetadataProvider::indexEntity(EntityDescriptor* site, time_t& validUntil, bool replace) const
102 {
103     // If child expires later than input, reset child, otherwise lower input to match.
104     if (validUntil < site->getValidUntilEpoch())
105         site->setValidUntil(validUntil);
106     else
107         validUntil = site->getValidUntilEpoch();
108
109     auto_ptr_char id(site->getEntityID());
110     if (id.get()) {
111         if (replace) {
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;
116                     ++s;
117                     m_sources.erase(temp);
118                 }
119                 else {
120                     ++s;
121                 }
122             }
123         }
124         m_sites.insert(sitemap_t::value_type(id.get(),site));
125     }
126     
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++) {
130         // SAML 1.x?
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);
138                     if (sid) {
139                         auto_ptr_char sourceid(sid->getID());
140                         if (sourceid.get()) {
141                             m_sources.insert(sitemap_t::value_type(sourceid.get(),site));
142                             break;
143                         }
144                     }
145                 }
146             }
147             
148             // Hash the ID.
149             m_sources.insert(sitemap_t::value_type(SecurityHelper::doHash("SHA1", id.get(), strlen(id.get())),site));
150                 
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());
155                 if (location.get())
156                     m_sources.insert(sitemap_t::value_type(location.get(),site));
157             }
158         }
159         
160         // SAML 2.0?
161         if ((*i)->hasSupport(samlconstants::SAML20P_NS)) {
162             // Hash the ID.
163             m_sources.insert(sitemap_t::value_type(SecurityHelper::doHash("SHA1", id.get(), strlen(id.get())),site));
164         }
165     }
166 }
167
168 void AbstractMetadataProvider::indexGroup(EntitiesDescriptor* group, time_t& validUntil) const
169 {
170     // If child expires later than input, reset child, otherwise lower input to match.
171     if (validUntil < group->getValidUntilEpoch())
172         group->setValidUntil(validUntil);
173     else
174         validUntil = group->getValidUntilEpoch();
175
176     auto_ptr_char name(group->getName());
177     if (name.get()) {
178         m_groups.insert(groupmap_t::value_type(name.get(),group));
179     }
180     
181     // Track the smallest validUntil amongst the children.
182     time_t minValidUntil = validUntil;
183
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;
191     }
192
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;
200     }
201
202     // Pass back up the smallest child we found.
203     if (minValidUntil < validUntil)
204         validUntil = minValidUntil;
205 }
206
207 void AbstractMetadataProvider::index(EntityDescriptor* site, time_t validUntil, bool replace) const
208 {
209     indexEntity(site, validUntil, replace);
210 }
211
212 void AbstractMetadataProvider::index(EntitiesDescriptor* group, time_t validUntil) const
213 {
214     indexGroup(group, validUntil);
215 }
216
217 void AbstractMetadataProvider::clearDescriptorIndex(bool freeSites)
218 {
219     if (freeSites)
220         for_each(m_sites.begin(), m_sites.end(), cleanup_const_pair<string,EntityDescriptor>());
221     m_sites.clear();
222     m_groups.clear();
223     m_sources.clear();
224 }
225
226 const EntitiesDescriptor* AbstractMetadataProvider::getEntitiesDescriptor(const char* name, bool strict) const
227 {
228     pair<groupmap_t::const_iterator,groupmap_t::const_iterator> range=const_cast<const groupmap_t&>(m_groups).equal_range(name);
229
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())
233             return i->second;
234     
235     if (range.first != range.second) {
236         Category& log = Category::getInstance(SAML_LOGCAT".MetadataProvider");
237         if (strict) {
238             log.warn("ignored expired metadata group (%s)", range.first->first.c_str());
239         }
240         else {
241             log.info("no valid metadata found, returning expired metadata group (%s)", range.first->first.c_str());
242             return range.first->second;
243         }
244     }
245
246     return nullptr;
247 }
248
249 pair<const EntityDescriptor*,const RoleDescriptor*> AbstractMetadataProvider::getEntityDescriptor(const Criteria& criteria) const
250 {
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());
257     }
258     else if (criteria.artifact)
259         range = const_cast<const sitemap_t&>(m_sources).equal_range(criteria.artifact->getSource());
260     else
261         return pair<const EntityDescriptor*,const RoleDescriptor*>(nullptr,nullptr);
262     
263     pair<const EntityDescriptor*,const RoleDescriptor*> result;
264     result.first = nullptr;
265     result.second = nullptr;
266     
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;
271             break;
272         }
273     }
274     
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());
279         }
280         else {
281             log.info("no valid metadata found, returning expired instance for (%s)", range.first->first.c_str());
282             result.first = range.first->second;
283         }
284     }
285
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);
290     }
291     
292     return result;
293 }
294
295 const Credential* AbstractMetadataProvider::resolve(const CredentialCriteria* criteria) const
296 {
297     const MetadataCredentialCriteria* metacrit = dynamic_cast<const MetadataCredentialCriteria*>(criteria);
298     if (!metacrit)
299         throw MetadataException("Cannot resolve credentials without a MetadataCredentialCriteria object.");
300
301     Lock lock(m_credentialLock);
302     const credmap_t::mapped_type& creds = resolveCredentials(metacrit->getRole());
303
304     for (credmap_t::mapped_type::const_iterator c = creds.begin(); c!=creds.end(); ++c)
305         if (metacrit->matches(*(*c)))
306             return *c;
307     return nullptr;
308 }
309
310 vector<const Credential*>::size_type AbstractMetadataProvider::resolve(
311     vector<const Credential*>& results, const CredentialCriteria* criteria
312     ) const
313 {
314     const MetadataCredentialCriteria* metacrit = dynamic_cast<const MetadataCredentialCriteria*>(criteria);
315     if (!metacrit)
316         throw MetadataException("Cannot resolve credentials without a MetadataCredentialCriteria object.");
317
318     Lock lock(m_credentialLock);
319     const credmap_t::mapped_type& creds = resolveCredentials(metacrit->getRole());
320
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();
325 }
326
327 const AbstractMetadataProvider::credmap_t::mapped_type& AbstractMetadataProvider::resolveCredentials(const RoleDescriptor& role) const
328 {
329     credmap_t::const_iterator i = m_credentialMap.find(&role);
330     if (i!=m_credentialMap.end())
331         return i->second;
332
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());
340             mcc.release();
341             resolved.push_back(c);
342         }
343     }
344     return resolved;
345 }