Revise attribute APIs to use vectors in place of multimaps.
[shibboleth/cpp-sp.git] / shibsp / attribute / resolver / impl / XMLAttributeExtractor.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * XMLAttributeExtractor.cpp
19  * 
20  * AttributeExtractor based on an XML mapping file.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "ServiceProvider.h"
26 #include "attribute/AttributeDecoder.h"
27 #include "attribute/resolver/AttributeExtractor.h"
28 #include "util/SPConstants.h"
29
30 #include <saml/saml1/core/Assertions.h>
31 #include <saml/saml2/core/Assertions.h>
32 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
33 #include <xmltooling/util/NDC.h>
34 #include <xmltooling/util/ReloadableXMLFile.h>
35 #include <xmltooling/util/XMLHelper.h>
36 #include <xercesc/util/XMLUniDefs.hpp>
37
38 using namespace shibsp;
39 using namespace opensaml::saml2md;
40 using namespace opensaml;
41 using namespace xmltooling;
42 using namespace std;
43 using saml1::NameIdentifier;
44 using saml2::NameID;
45 using saml2::EncryptedAttribute;
46
47 namespace shibsp {
48
49 #if defined (_MSC_VER)
50     #pragma warning( push )
51     #pragma warning( disable : 4250 )
52 #endif
53
54     class XMLExtractorImpl
55     {
56     public:
57         XMLExtractorImpl(const DOMElement* e, Category& log);
58         ~XMLExtractorImpl() {
59             for (attrmap_t::iterator i = m_attrMap.begin(); i!=m_attrMap.end(); ++i)
60                 delete i->second.first;
61             if (m_document)
62                 m_document->release();
63         }
64
65         void setDocument(DOMDocument* doc) {
66             m_document = doc;
67         }
68
69         void extractAttributes(
70             const Application& application, const char* assertingParty, const NameIdentifier& nameid, vector<Attribute*>& attributes
71             ) const;
72         void extractAttributes(
73             const Application& application, const char* assertingParty, const NameID& nameid, vector<Attribute*>& attributes
74             ) const;
75         void extractAttributes(
76             const Application& application, const char* assertingParty, const saml1::Attribute& attr, vector<Attribute*>& attributes
77             ) const;
78         void extractAttributes(
79             const Application& application, const char* assertingParty, const saml2::Attribute& attr, vector<Attribute*>& attributes
80             ) const;
81
82         void getAttributeIds(vector<string>& attributes) const {
83             attributes.insert(attributes.end(), m_attributeIds.begin(), m_attributeIds.end());
84         }
85
86     private:
87         Category& m_log;
88         DOMDocument* m_document;
89 #ifdef HAVE_GOOD_STL
90         typedef map< pair<xstring,xstring>,pair<AttributeDecoder*,string> > attrmap_t;
91 #else
92         typedef map< pair<string,string>,pair<AttributeDecoder*,string> > attrmap_t;
93 #endif
94         attrmap_t m_attrMap;
95         vector<string> m_attributeIds;
96     };
97     
98     class XMLExtractor : public AttributeExtractor, public ReloadableXMLFile
99     {
100     public:
101         XMLExtractor(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AttributeExtractor")), m_impl(NULL) {
102             load();
103         }
104         ~XMLExtractor() {
105             delete m_impl;
106         }
107         
108         void extractAttributes(
109             const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
110             ) const;
111
112         void getAttributeIds(std::vector<std::string>& attributes) const {
113             if (m_impl)
114                 m_impl->getAttributeIds(attributes);
115         }
116
117     protected:
118         pair<bool,DOMElement*> load();
119
120     private:
121         XMLExtractorImpl* m_impl;
122     };
123
124 #if defined (_MSC_VER)
125     #pragma warning( pop )
126 #endif
127
128     AttributeExtractor* SHIBSP_DLLLOCAL XMLAttributeExtractorFactory(const DOMElement* const & e)
129     {
130         return new XMLExtractor(e);
131     }
132     
133     static const XMLCh _AttributeDecoder[] =    UNICODE_LITERAL_16(A,t,t,r,i,b,u,t,e,D,e,c,o,d,e,r);
134     static const XMLCh Attributes[] =           UNICODE_LITERAL_10(A,t,t,r,i,b,u,t,e,s);
135     static const XMLCh _id[] =                  UNICODE_LITERAL_2(i,d);
136     static const XMLCh _name[] =                UNICODE_LITERAL_4(n,a,m,e);
137     static const XMLCh nameFormat[] =           UNICODE_LITERAL_10(n,a,m,e,F,o,r,m,a,t);
138 };
139
140 void SHIBSP_API shibsp::registerAttributeExtractors()
141 {
142     SPConfig::getConfig().AttributeExtractorManager.registerFactory(XML_ATTRIBUTE_EXTRACTOR, XMLAttributeExtractorFactory);
143 }
144
145 XMLExtractorImpl::XMLExtractorImpl(const DOMElement* e, Category& log) : m_log(log), m_document(NULL)
146 {
147 #ifdef _DEBUG
148     xmltooling::NDC ndc("XMLExtractorImpl");
149 #endif
150     
151     if (!XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, Attributes))
152         throw ConfigurationException("XML AttributeExtractor requires am:Attributes at root of configuration.");
153
154     DOMElement* child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
155     while (child) {
156         // Check for missing name or id.
157         const XMLCh* name = child->getAttributeNS(NULL, _name);
158         if (!name || !*name) {
159             m_log.warn("skipping Attribute with no name");
160             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
161             continue;
162         }
163
164         auto_ptr_char id(child->getAttributeNS(NULL, _id));
165         if (!id.get() || !*id.get()) {
166             m_log.warn("skipping Attribute with no id");
167             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
168             continue;
169         }
170         else if (!strcmp(id.get(), "REMOTE_USER")) {
171             m_log.warn("skipping Attribute, id of REMOTE_USER is a reserved name");
172             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
173             continue;
174         }
175
176         AttributeDecoder* decoder=NULL;
177         try {
178             DOMElement* dchild = XMLHelper::getFirstChildElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _AttributeDecoder);
179             if (dchild) {
180                 auto_ptr<QName> q(XMLHelper::getXSIType(dchild));
181                 if (q.get())
182                     decoder = SPConfig::getConfig().AttributeDecoderManager.newPlugin(*q.get(), dchild);
183             }
184             if (!decoder)
185                 decoder = SPConfig::getConfig().AttributeDecoderManager.newPlugin(StringAttributeDecoderType, NULL);
186         }
187         catch (exception& ex) {
188             m_log.error("skipping Attribute (%s), error building AttributeDecoder: %s", id.get(), ex.what());
189         }
190
191         if (!decoder) {
192             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
193             continue;
194         }
195
196         // Empty NameFormat implies the usual Shib URI naming defaults.
197         const XMLCh* format = child->getAttributeNS(NULL, nameFormat);
198         if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI) ||
199                 XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
200             format = &chNull;  // ignore default Format/Namespace values
201
202         // Fetch/create the map entry and see if it's a duplicate rule.
203 #ifdef HAVE_GOOD_STL
204         pair<AttributeDecoder*,string>& decl = m_attrMap[make_pair(name,format)];
205 #else
206         auto_ptr_char n(name);
207         auto_ptr_char f(format);
208         pair<AttributeDecoder*,string>& decl = m_attrMap[make_pair(n.get(),f.get())];
209 #endif
210         if (decl.first) {
211             m_log.warn("skipping duplicate Attribute mapping (same name and nameFormat)");
212             delete decoder;
213             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
214             continue;
215         }
216
217         if (m_log.isInfoEnabled()) {
218 #ifdef HAVE_GOOD_STL
219             auto_ptr_char n(name);
220             auto_ptr_char f(format);
221 #endif
222             m_log.info("creating mapping for Attribute %s%s%s", n.get(), *f.get() ? ", Format/Namespace:" : "", f.get());
223         }
224         
225         decl.first = decoder;
226         decl.second = id.get();
227         m_attributeIds.push_back(id.get());
228         
229         child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
230     }
231 }
232
233 void XMLExtractorImpl::extractAttributes(
234     const Application& application, const char* assertingParty, const NameIdentifier& nameid, vector<Attribute*>& attributes
235     ) const
236 {
237 #ifdef HAVE_GOOD_STL
238     map< pair<xstring,xstring>,pair<AttributeDecoder*,string> >::const_iterator rule;
239 #else
240     map< pair<string,string>,pair<AttributeDecoder*,string> >::const_iterator rule;
241 #endif
242
243     const XMLCh* format = nameid.getFormat();
244     if (!format || !*format)
245         format = NameIdentifier::UNSPECIFIED;
246 #ifdef HAVE_GOOD_STL
247     if ((rule=m_attrMap.find(make_pair(format,xstring()))) != m_attrMap.end()) {
248 #else
249     auto_ptr_char temp(format);
250     if ((rule=m_attrMap.find(make_pair(temp.get(),string()))) != m_attrMap.end()) {
251 #endif
252         Attribute* a = rule->second.first->decode(rule->second.second.c_str(), &nameid, assertingParty, application.getString("entityID").second);
253         if (a)
254             attributes.push_back(a);
255     }
256 }
257
258 void XMLExtractorImpl::extractAttributes(
259     const Application& application, const char* assertingParty, const NameID& nameid, vector<Attribute*>& attributes
260     ) const
261 {
262 #ifdef HAVE_GOOD_STL
263     map< pair<xstring,xstring>,pair<AttributeDecoder*,string> >::const_iterator rule;
264 #else
265     map< pair<string,string>,pair<AttributeDecoder*,string> >::const_iterator rule;
266 #endif
267
268     const XMLCh* format = nameid.getFormat();
269     if (!format || !*format)
270         format = NameID::UNSPECIFIED;
271 #ifdef HAVE_GOOD_STL
272     if ((rule=m_attrMap.find(make_pair(format,xstring()))) != m_attrMap.end()) {
273 #else
274     auto_ptr_char temp(format);
275     if ((rule=m_attrMap.find(make_pair(temp.get(),string()))) != m_attrMap.end()) {
276 #endif
277         Attribute* a = rule->second.first->decode(rule->second.second.c_str(), &nameid, assertingParty, application.getString("entityID").second);
278         if (a)
279             attributes.push_back(a);
280     }
281 }
282
283 void XMLExtractorImpl::extractAttributes(
284     const Application& application, const char* assertingParty, const saml1::Attribute& attr, vector<Attribute*>& attributes
285     ) const
286 {
287 #ifdef HAVE_GOOD_STL
288     map< pair<xstring,xstring>,pair<AttributeDecoder*,string> >::const_iterator rule;
289 #else
290     map< pair<string,string>,pair<AttributeDecoder*,string> >::const_iterator rule;
291 #endif
292
293     const XMLCh* name = attr.getAttributeName();
294     const XMLCh* format = attr.getAttributeNamespace();
295     if (!name || !*name)
296         return;
297     if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI))
298         format = &chNull;
299 #ifdef HAVE_GOOD_STL
300     if ((rule=m_attrMap.find(make_pair(name,format))) != m_attrMap.end()) {
301 #else
302     auto_ptr_char temp1(name);
303     auto_ptr_char temp2(format);
304     if ((rule=m_attrMap.find(make_pair(temp1.get(),temp2.get()))) != m_attrMap.end()) {
305 #endif
306         Attribute* a = rule->second.first->decode(rule->second.second.c_str(), &attr, assertingParty, application.getString("entityID").second);
307         if (a)
308             attributes.push_back(a);
309     }
310 }
311
312 void XMLExtractorImpl::extractAttributes(
313     const Application& application, const char* assertingParty, const saml2::Attribute& attr, vector<Attribute*>& attributes
314     ) const
315 {
316 #ifdef HAVE_GOOD_STL
317     map< pair<xstring,xstring>,pair<AttributeDecoder*,string> >::const_iterator rule;
318 #else
319     map< pair<string,string>,pair<AttributeDecoder*,string> >::const_iterator rule;
320 #endif
321
322     const XMLCh* name = attr.getName();
323     const XMLCh* format = attr.getNameFormat();
324     if (!name || !*name)
325         return;
326     if (!format || !*format)
327         format = saml2::Attribute::UNSPECIFIED;
328     else if (XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
329         format = &chNull;
330 #ifdef HAVE_GOOD_STL
331     if ((rule=m_attrMap.find(make_pair(name,format))) != m_attrMap.end()) {
332 #else
333     auto_ptr_char temp1(name);
334     auto_ptr_char temp2(format);
335     if ((rule=m_attrMap.find(make_pair(temp1.get(),temp2.get()))) != m_attrMap.end()) {
336 #endif
337         Attribute* a = rule->second.first->decode(rule->second.second.c_str(), &attr, assertingParty, application.getString("entityID").second);
338         if (a)
339             attributes.push_back(a);
340     }
341 }
342
343 void XMLExtractor::extractAttributes(
344     const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
345     ) const
346 {
347     if (!m_impl)
348         return;
349
350     // Check for assertions.
351     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Assertion::LOCAL_NAME)) {
352         const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(&xmlObject);
353         if (token2) {
354             auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
355             const vector<saml2::AttributeStatement*>& statements = token2->getAttributeStatements();
356             for (vector<saml2::AttributeStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
357                 const vector<saml2::Attribute*>& attrs = const_cast<const saml2::AttributeStatement*>(*s)->getAttributes();
358                 for (vector<saml2::Attribute*>::const_iterator a = attrs.begin(); a!=attrs.end(); ++a)
359                     m_impl->extractAttributes(application, assertingParty.get(), *(*a), attributes);
360
361                 const vector<saml2::EncryptedAttribute*>& encattrs = const_cast<const saml2::AttributeStatement*>(*s)->getEncryptedAttributes();
362                 for (vector<saml2::EncryptedAttribute*>::const_iterator ea = encattrs.begin(); ea!=encattrs.end(); ++ea)
363                     extractAttributes(application, issuer, *(*ea), attributes);
364             }
365             return;
366         }
367
368         const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(&xmlObject);
369         if (token1) {
370             auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
371             const vector<saml1::AttributeStatement*>& statements = token1->getAttributeStatements();
372             for (vector<saml1::AttributeStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
373                 const vector<saml1::Attribute*>& attrs = const_cast<const saml1::AttributeStatement*>(*s)->getAttributes();
374                 for (vector<saml1::Attribute*>::const_iterator a = attrs.begin(); a!=attrs.end(); ++a)
375                     m_impl->extractAttributes(application, assertingParty.get(), *(*a), attributes);
376             }
377             return;
378         }
379
380         throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
381     }
382
383     // Check for attributes.
384     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Attribute::LOCAL_NAME)) {
385         auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
386
387         const saml2::Attribute* attr2 = dynamic_cast<const saml2::Attribute*>(&xmlObject);
388         if (attr2)
389             return m_impl->extractAttributes(application, assertingParty.get(), *attr2, attributes);
390
391         const saml1::Attribute* attr1 = dynamic_cast<const saml1::Attribute*>(&xmlObject);
392         if (attr1)
393             return m_impl->extractAttributes(application, assertingParty.get(), *attr1, attributes);
394
395         throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
396     }
397
398     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), EncryptedAttribute::LOCAL_NAME)) {
399         const EncryptedAttribute* encattr = dynamic_cast<const EncryptedAttribute*>(&xmlObject);
400         if (encattr) {
401             const XMLCh* recipient = application.getXMLString("entityID").second;
402             CredentialResolver* cr = application.getCredentialResolver();
403             if (!cr) {
404                 m_log.warn("found encrypted attribute, but no CredentialResolver was available");
405                 return;
406             }
407
408             try {
409                 Locker credlocker(cr);
410                 if (issuer) {
411                     MetadataCredentialCriteria mcc(*issuer);
412                     auto_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient, &mcc));
413                     return extractAttributes(application, issuer, *(decrypted.get()), attributes);
414                 }
415                 else {
416                     auto_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient));
417                     return extractAttributes(application, issuer, *(decrypted.get()), attributes);
418                 }
419             }
420             catch (exception& ex) {
421                 m_log.error("caught exception decrypting Attribute: %s", ex.what());
422                 return;
423             }
424         }
425     }
426
427     // Check for NameIDs.
428     const NameID* name2 = dynamic_cast<const NameID*>(&xmlObject);
429     if (name2) {
430         auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
431         return m_impl->extractAttributes(application, assertingParty.get(), *name2, attributes);
432     }
433
434     const NameIdentifier* name1 = dynamic_cast<const NameIdentifier*>(&xmlObject);
435     if (name1) {
436         auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
437         return m_impl->extractAttributes(application, assertingParty.get(), *name1, attributes);
438     }
439
440     throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
441 }
442
443 pair<bool,DOMElement*> XMLExtractor::load()
444 {
445     // Load from source using base class.
446     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
447     
448     // If we own it, wrap it.
449     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
450
451     XMLExtractorImpl* impl = new XMLExtractorImpl(raw.second, m_log);
452     
453     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
454     impl->setDocument(docjanitor.release());
455
456     delete m_impl;
457     m_impl = impl;
458
459     return make_pair(false,(DOMElement*)NULL);
460 }