Remove extra header
[shibboleth/cpp-sp.git] / shibsp / attribute / resolver / impl / SimpleAggregationAttributeResolver.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  * SimpleAggregationAttributeResolver.cpp
23  *
24  * AttributeResolver based on SAML queries to third-party AA sources.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "Application.h"
30 #include "ServiceProvider.h"
31 #include "SessionCache.h"
32 #include "attribute/NameIDAttribute.h"
33 #include "attribute/SimpleAttribute.h"
34 #include "attribute/filtering/AttributeFilter.h"
35 #include "attribute/filtering/BasicFilteringContext.h"
36 #include "attribute/resolver/AttributeExtractor.h"
37 #include "attribute/resolver/AttributeResolver.h"
38 #include "attribute/resolver/ResolutionContext.h"
39 #include "binding/SOAPClient.h"
40 #include "metadata/MetadataProviderCriteria.h"
41 #include "security/SecurityPolicy.h"
42 #include "security/SecurityPolicyProvider.h"
43 #include "util/SPConstants.h"
44
45 #include <boost/algorithm/string.hpp>
46 #include <boost/iterator/indirect_iterator.hpp>
47 #include <boost/ptr_container/ptr_vector.hpp>
48 #include <saml/exceptions.h>
49 #include <saml/SAMLConfig.h>
50 #include <saml/saml2/binding/SAML2SOAPClient.h>
51 #include <saml/saml2/core/Protocols.h>
52 #include <saml/saml2/metadata/Metadata.h>
53 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
54 #include <saml/saml2/metadata/MetadataProvider.h>
55 #include <xmltooling/XMLToolingConfig.h>
56 #include <xmltooling/security/TrustEngine.h>
57 #include <xmltooling/util/NDC.h>
58 #include <xmltooling/util/URLEncoder.h>
59 #include <xmltooling/util/XMLHelper.h>
60 #include <xercesc/util/XMLUniDefs.hpp>
61
62 using namespace shibsp;
63 using namespace opensaml::saml2;
64 using namespace opensaml::saml2p;
65 using namespace opensaml::saml2md;
66 using namespace opensaml;
67 using namespace xmltooling;
68 using namespace boost;
69 using namespace std;
70
71 namespace shibsp {
72
73     class SHIBSP_DLLLOCAL SimpleAggregationContext : public ResolutionContext
74     {
75     public:
76         SimpleAggregationContext(const Application& application, const Session& session)
77             : m_app(application),
78               m_session(&session),
79               m_nameid(nullptr),
80               m_class(session.getAuthnContextClassRef()),
81               m_decl(session.getAuthnContextDeclRef()),
82               m_inputTokens(nullptr),
83               m_inputAttributes(nullptr) {
84         }
85
86         SimpleAggregationContext(
87             const Application& application,
88             const NameID* nameid=nullptr,
89             const XMLCh* entityID=nullptr,
90             const XMLCh* authncontext_class=nullptr,
91             const XMLCh* authncontext_decl=nullptr,
92             const vector<const opensaml::Assertion*>* tokens=nullptr,
93             const vector<shibsp::Attribute*>* attributes=nullptr
94             ) : m_app(application),
95                 m_session(nullptr),
96                 m_nameid(nameid),
97                 m_entityid(entityID),
98                 m_class(authncontext_class),
99                 m_decl(authncontext_decl),
100                 m_inputTokens(tokens),
101                 m_inputAttributes(attributes) {
102         }
103
104         ~SimpleAggregationContext() {
105             for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<shibsp::Attribute>());
106             for_each(m_assertions.begin(), m_assertions.end(), xmltooling::cleanup<opensaml::Assertion>());
107         }
108
109         const Application& getApplication() const {
110             return m_app;
111         }
112         const char* getEntityID() const {
113             return m_session ? m_session->getEntityID() : m_entityid.get();
114         }
115         const NameID* getNameID() const {
116             return m_session ? m_session->getNameID() : m_nameid;
117         }
118         const XMLCh* getClassRef() const {
119             return m_class.get();
120         }
121         const XMLCh* getDeclRef() const {
122             return m_decl.get();
123         }
124         const Session* getSession() const {
125             return m_session;
126         }
127         const vector<shibsp::Attribute*>* getInputAttributes() const {
128             return m_inputAttributes;
129         }
130         const vector<const opensaml::Assertion*>* getInputTokens() const {
131             return m_inputTokens;
132         }
133         vector<shibsp::Attribute*>& getResolvedAttributes() {
134             return m_attributes;
135         }
136         vector<opensaml::Assertion*>& getResolvedAssertions() {
137             return m_assertions;
138         }
139
140     private:
141         const Application& m_app;
142         const Session* m_session;
143         const NameID* m_nameid;
144         auto_ptr_char m_entityid;
145         auto_ptr_XMLCh m_class;
146         auto_ptr_XMLCh m_decl;
147         const vector<const opensaml::Assertion*>* m_inputTokens;
148         const vector<shibsp::Attribute*>* m_inputAttributes;
149         vector<shibsp::Attribute*> m_attributes;
150         vector<opensaml::Assertion*> m_assertions;
151     };
152
153     class SHIBSP_DLLLOCAL SimpleAggregationResolver : public AttributeResolver
154     {
155     public:
156         SimpleAggregationResolver(const DOMElement* e);
157         ~SimpleAggregationResolver() {}
158
159         Lockable* lock() {return this;}
160         void unlock() {}
161
162         ResolutionContext* createResolutionContext(
163             const Application& application,
164             const EntityDescriptor* issuer,
165             const XMLCh* protocol,
166             const NameID* nameid=nullptr,
167             const XMLCh* authncontext_class=nullptr,
168             const XMLCh* authncontext_decl=nullptr,
169             const vector<const opensaml::Assertion*>* tokens=nullptr,
170             const vector<shibsp::Attribute*>* attributes=nullptr
171             ) const {
172             return new SimpleAggregationContext(
173                 application, nameid, (issuer ? issuer->getEntityID() : nullptr), authncontext_class, authncontext_decl, tokens, attributes
174                 );
175         }
176
177         ResolutionContext* createResolutionContext(const Application& application, const Session& session) const {
178             return new SimpleAggregationContext(application,session);
179         }
180
181         void resolveAttributes(ResolutionContext& ctx) const;
182
183         void getAttributeIds(vector<string>& attributes) const {
184             // Nothing to do, only the extractor would actually generate them.
185         }
186
187     private:
188         void doQuery(SimpleAggregationContext& ctx, const char* entityID, const NameID* name) const;
189
190         Category& m_log;
191         string m_policyId;
192         bool m_subjectMatch;
193         vector<string> m_attributeIds;
194         xstring m_format;
195         scoped_ptr<MetadataProvider> m_metadata;
196         scoped_ptr<TrustEngine> m_trust;
197         ptr_vector<saml2::Attribute> m_designators;
198         vector< pair<string,bool> > m_sources;
199         vector<string> m_exceptionId;
200     };
201
202     AttributeResolver* SHIBSP_DLLLOCAL SimpleAggregationResolverFactory(const DOMElement* const & e)
203     {
204         return new SimpleAggregationResolver(e);
205     }
206
207     static const XMLCh attributeId[] =          UNICODE_LITERAL_11(a,t,t,r,i,b,u,t,e,I,d);
208     static const XMLCh Entity[] =               UNICODE_LITERAL_6(E,n,t,i,t,y);
209     static const XMLCh EntityReference[] =      UNICODE_LITERAL_15(E,n,t,i,t,y,R,e,f,e,r,e,n,c,e);
210     static const XMLCh exceptionId[] =          UNICODE_LITERAL_11(e,x,c,e,p,t,i,o,n,I,d);
211     static const XMLCh format[] =               UNICODE_LITERAL_6(f,o,r,m,a,t);
212     static const XMLCh _MetadataProvider[] =    UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
213     static const XMLCh policyId[] =             UNICODE_LITERAL_8(p,o,l,i,c,y,I,d);
214     static const XMLCh subjectMatch[] =         UNICODE_LITERAL_12(s,u,b,j,e,c,t,M,a,t,c,h);
215     static const XMLCh _TrustEngine[] =         UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
216     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);
217 };
218
219 SimpleAggregationResolver::SimpleAggregationResolver(const DOMElement* e)
220     : m_log(Category::getInstance(SHIBSP_LOGCAT".AttributeResolver.SimpleAggregation")),
221         m_policyId(XMLHelper::getAttrString(e, nullptr, policyId)),
222         m_subjectMatch(XMLHelper::getAttrBool(e, false, subjectMatch))
223 {
224 #ifdef _DEBUG
225     xmltooling::NDC ndc("SimpleAggregationResolver");
226 #endif
227
228     const XMLCh* aid = e ? e->getAttributeNS(nullptr, attributeId) : nullptr;
229     if (aid && *aid) {
230         auto_ptr_char dup(aid);
231         string sdup(dup.get());
232         split(m_attributeIds, sdup, is_space(), algorithm::token_compress_on);
233
234         aid = e->getAttributeNS(nullptr, format);
235         if (aid && *aid)
236             m_format = aid;
237     }
238
239     string exid(XMLHelper::getAttrString(e, nullptr, exceptionId));
240     if (!exid.empty())
241         m_exceptionId.push_back(exid);
242
243     DOMElement* child = XMLHelper::getFirstChildElement(e, _MetadataProvider);
244     if (child) {
245         string t(XMLHelper::getAttrString(child, nullptr, _type));
246         if (t.empty())
247             throw ConfigurationException("MetadataProvider element missing type attribute.");
248         m_log.info("building MetadataProvider of type %s...", t.c_str());
249         m_metadata.reset(SAMLConfig::getConfig().MetadataProviderManager.newPlugin(t.c_str(), child));
250         m_metadata->init();
251     }
252
253     child = XMLHelper::getFirstChildElement(e,  _TrustEngine);
254     if (child) {
255         string t(XMLHelper::getAttrString(child, nullptr, _type));
256         if (t.empty())
257             throw ConfigurationException("TrustEngine element missing type attribute.");
258         m_log.info("building TrustEngine of type %s...", t.c_str());
259         m_trust.reset(XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child));
260     }
261
262     child = XMLHelper::getFirstChildElement(e);
263     while (child) {
264         if (child->hasChildNodes() && XMLString::equals(child->getLocalName(), Entity)) {
265             aid = child->getFirstChild()->getNodeValue();
266             if (aid && *aid) {
267                 auto_ptr_char taid(aid);
268                 m_sources.push_back(pair<string,bool>(taid.get(),true));
269             }
270         }
271         else if (child->hasChildNodes() && XMLString::equals(child->getLocalName(), EntityReference)) {
272             aid = child->getFirstChild()->getNodeValue();
273             if (aid && *aid) {
274                 auto_ptr_char taid(aid);
275                 m_sources.push_back(pair<string,bool>(taid.get(),false));
276             }
277         }
278         else if (XMLHelper::isNodeNamed(child, samlconstants::SAML20_NS, saml2::Attribute::LOCAL_NAME)) {
279             try {
280                 auto_ptr<XMLObject> obj(saml2::AttributeBuilder::buildOneFromElement(child));
281                 saml2::Attribute* down = dynamic_cast<saml2::Attribute*>(obj.get());
282                 if (down) {
283                     m_designators.push_back(down);
284                     obj.release();
285                 }
286             }
287             catch (std::exception& ex) {
288                 m_log.error("exception loading attribute designator: %s", ex.what());
289             }
290         }
291         child = XMLHelper::getNextSiblingElement(child);
292     }
293 }
294
295 void SimpleAggregationResolver::doQuery(SimpleAggregationContext& ctx, const char* entityID, const NameID* name) const
296 {
297 #ifdef _DEBUG
298     xmltooling::NDC ndc("doQuery");
299 #endif
300     const Application& application = ctx.getApplication();
301     MetadataProviderCriteria mc(application, entityID, &AttributeAuthorityDescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
302     Locker mlocker(m_metadata.get());
303     const AttributeAuthorityDescriptor* AA=nullptr;
304     pair<const EntityDescriptor*,const RoleDescriptor*> mdresult =
305         (m_metadata ? m_metadata.get() : application.getMetadataProvider())->getEntityDescriptor(mc);
306     if (!mdresult.first) {
307         m_log.warn("unable to locate metadata for provider (%s)", entityID);
308         return;
309     }
310     else if (!(AA=dynamic_cast<const AttributeAuthorityDescriptor*>(mdresult.second))) {
311         m_log.warn("no SAML 2 AttributeAuthority role found in metadata for (%s)", entityID);
312         return;
313     }
314
315     const PropertySet* relyingParty = application.getRelyingParty(mdresult.first);
316     pair<bool,bool> signedAssertions = relyingParty->getBool("requireSignedAssertions");
317     pair<bool,const char*> encryption = relyingParty->getString("encryption");
318
319     // Locate policy key.
320     const char* policyId = m_policyId.empty() ? application.getString("policyId").second : m_policyId.c_str();
321
322     // Set up policy and SOAP client.
323     scoped_ptr<SecurityPolicy> policy(
324         application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, nullptr, policyId)
325         );
326     if (m_metadata)
327         policy->setMetadataProvider(m_metadata.get());
328     if (m_trust)
329         policy->setTrustEngine(m_trust.get());
330     policy->getAudiences().push_back(relyingParty->getXMLString("entityID").second);
331
332     MetadataCredentialCriteria mcc(*AA);
333     shibsp::SOAPClient soaper(*policy.get());
334
335     auto_ptr_XMLCh binding(samlconstants::SAML20_BINDING_SOAP);
336     auto_ptr<saml2p::StatusResponseType> srt;
337     const vector<AttributeService*>& endpoints=AA->getAttributeServices();
338     for (indirect_iterator<vector<AttributeService*>::const_iterator> ep = make_indirect_iterator(endpoints.begin());
339             !srt.get() && ep != make_indirect_iterator(endpoints.end()); ++ep) {
340         if (!XMLString::equals(ep->getBinding(), binding.get())  || !ep->getLocation())
341             continue;
342         auto_ptr_char loc(ep->getLocation());
343         try {
344             auto_ptr<saml2::Subject> subject(saml2::SubjectBuilder::buildSubject());
345
346             // Encrypt the NameID?
347             if (encryption.first && (!strcmp(encryption.second, "true") || !strcmp(encryption.second, "back"))) {
348                 auto_ptr<EncryptedID> encrypted(EncryptedIDBuilder::buildEncryptedID());
349                 encrypted->encrypt(
350                     *name,
351                     *(policy->getMetadataProvider()),
352                     mcc,
353                     false,
354                     relyingParty->getXMLString("encryptionAlg").second
355                     );
356                 subject->setEncryptedID(encrypted.get());
357                 encrypted.release();
358             }
359             else {
360                 subject->setNameID(name->cloneNameID());
361             }
362
363             saml2p::AttributeQuery* query = saml2p::AttributeQueryBuilder::buildAttributeQuery();
364             query->setSubject(subject.release());
365             Issuer* iss = IssuerBuilder::buildIssuer();
366             iss->setName(relyingParty->getXMLString("entityID").second);
367             query->setIssuer(iss);
368             for (ptr_vector<saml2::Attribute>::const_iterator ad = m_designators.begin(); ad != m_designators.end(); ++ad) {
369                 auto_ptr<saml2::Attribute> adwrapper(ad->cloneAttribute());
370                 query->getAttributes().push_back(adwrapper.get());
371                 adwrapper.release();
372             }
373
374             SAML2SOAPClient client(soaper, false);
375             client.sendSAML(query, application.getId(), mcc, loc.get());
376             srt.reset(client.receiveSAML());
377         }
378         catch (std::exception& ex) {
379             m_log.error("exception during SAML query to %s: %s", loc.get(), ex.what());
380             soaper.reset();
381         }
382     }
383
384     if (!srt.get()) {
385         m_log.error("unable to obtain a SAML response from attribute authority (%s)", entityID);
386         throw BindingException("Unable to obtain a SAML response from attribute authority.");
387     }
388
389     saml2p::Response* response = dynamic_cast<saml2p::Response*>(srt.get());
390     if (!response) {
391         m_log.error("message was not a samlp:Response");
392         throw FatalProfileException("Attribute authority returned an unrecognized message.");
393     }
394     else if (!response->getStatus() || !response->getStatus()->getStatusCode() ||
395             !XMLString::equals(response->getStatus()->getStatusCode()->getValue(), saml2p::StatusCode::SUCCESS)) {
396         m_log.error("attribute authority (%s) returned a SAML error", entityID);
397         throw FatalProfileException("Attribute authority returned a SAML error.");
398     }
399
400     saml2::Assertion* newtoken = nullptr;
401     auto_ptr<saml2::Assertion> newtokenwrapper;
402     const vector<saml2::Assertion*>& assertions = const_cast<const saml2p::Response*>(response)->getAssertions();
403     if (assertions.empty()) {
404         // Check for encryption.
405         const vector<saml2::EncryptedAssertion*>& encassertions =
406             const_cast<const saml2p::Response*>(response)->getEncryptedAssertions();
407         if (encassertions.empty()) {
408             m_log.warn("response from attribute authority was empty");
409             return;
410         }
411         else if (encassertions.size() > 1) {
412             m_log.warn("simple resolver only supports one assertion in the query response");
413         }
414
415         CredentialResolver* cr=application.getCredentialResolver();
416         if (!cr) {
417             m_log.warn("found encrypted assertion, but no CredentialResolver was available");
418             throw FatalProfileException("Assertion was encrypted, but no decryption credentials are available.");
419         }
420
421         // Attempt to decrypt it.
422         try {
423             Locker credlocker(cr);
424             auto_ptr<XMLObject> tokenwrapper(encassertions.front()->decrypt(*cr, relyingParty->getXMLString("entityID").second, &mcc));
425             newtoken = dynamic_cast<saml2::Assertion*>(tokenwrapper.get());
426             if (newtoken) {
427                 tokenwrapper.release();
428                 newtokenwrapper.reset(newtoken);
429                 if (m_log.isDebugEnabled())
430                     m_log.debugStream() << "decrypted Assertion: " << *newtoken << logging::eol;
431             }
432         }
433         catch (std::exception& ex) {
434             m_log.error(ex.what());
435             throw;
436         }
437     }
438     else {
439         if (assertions.size() > 1)
440             m_log.warn("simple resolver only supports one assertion in the query response");
441         newtoken = assertions.front();
442     }
443
444     if (!newtoken->getSignature() && signedAssertions.first && signedAssertions.second) {
445         m_log.error("assertion unsigned, rejecting it based on signedAssertions policy");
446         throw SecurityPolicyException("Rejected unsigned assertion based on local policy.");
447     }
448
449     try {
450         // We're going to insist that the assertion issuer is the same as the peer.
451         // Reset the policy's message bits and extract them from the assertion.
452         policy->reset(true);
453         policy->setMessageID(newtoken->getID());
454         policy->setIssueInstant(newtoken->getIssueInstantEpoch());
455         policy->setIssuer(newtoken->getIssuer());
456         policy->evaluate(*newtoken);
457
458         // Now we can check the security status of the policy.
459         if (!policy->isAuthenticated())
460             throw SecurityPolicyException("Security of SAML 2.0 query result not established.");
461
462         if (m_subjectMatch) {
463             // Check for subject match.
464             auto_ptr<NameID> nameIDwrapper;
465             NameID* respName = newtoken->getSubject() ? newtoken->getSubject()->getNameID() : nullptr;
466             if (!respName) {
467                 // Check for encryption.
468                 EncryptedID* encname = newtoken->getSubject() ? newtoken->getSubject()->getEncryptedID() : nullptr;
469                 if (encname) {
470                     CredentialResolver* cr=application.getCredentialResolver();
471                     if (!cr)
472                         m_log.warn("found EncryptedID, but no CredentialResolver was available");
473                     else {
474                         Locker credlocker(cr);
475                         auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr, relyingParty->getXMLString("entityID").second, &mcc));
476                         respName = dynamic_cast<NameID*>(decryptedID.get());
477                         if (respName) {
478                             decryptedID.release();
479                             nameIDwrapper.reset(respName);
480                             if (m_log.isDebugEnabled())
481                                 m_log.debugStream() << "decrypted NameID: " << *respName << logging::eol;
482                         }
483                     }
484                 }
485             }
486
487             if (!respName || !XMLString::equals(respName->getName(), name->getName()) ||
488                 !XMLString::equals(respName->getFormat(), name->getFormat()) ||
489                 !XMLString::equals(respName->getNameQualifier(), name->getNameQualifier()) ||
490                 !XMLString::equals(respName->getSPNameQualifier(), name->getSPNameQualifier())) {
491                 if (respName)
492                     m_log.warnStream() << "ignoring Assertion without strongly matching NameID in Subject: " <<
493                         *respName << logging::eol;
494                 else
495                     m_log.warn("ignoring Assertion without NameID in Subject");
496                 return;
497             }
498         }
499     }
500     catch (std::exception& ex) {
501         m_log.error("assertion failed policy validation: %s", ex.what());
502         throw;
503     }
504
505     // If the token's embedded, detach it.
506     if (!newtokenwrapper.get()) {
507         newtoken->detach();
508         srt.release();  // detach blows away the Response, so avoid a double free
509         newtokenwrapper.reset(newtoken);
510     }
511     ctx.getResolvedAssertions().push_back(newtoken);
512     newtokenwrapper.release();
513
514     // Finally, extract and filter the result.
515     try {
516         AttributeExtractor* extractor = application.getAttributeExtractor();
517         if (extractor) {
518             Locker extlocker(extractor);
519             extractor->extractAttributes(application, AA, *newtoken, ctx.getResolvedAttributes());
520         }
521
522         AttributeFilter* filter = application.getAttributeFilter();
523         if (filter) {
524             BasicFilteringContext fc(application, ctx.getResolvedAttributes(), AA, ctx.getClassRef(), ctx.getDeclRef());
525             Locker filtlocker(filter);
526             filter->filterAttributes(fc, ctx.getResolvedAttributes());
527         }
528     }
529     catch (std::exception& ex) {
530         m_log.error("caught exception extracting/filtering attributes from query result: %s", ex.what());
531         for_each(ctx.getResolvedAttributes().begin(), ctx.getResolvedAttributes().end(), xmltooling::cleanup<shibsp::Attribute>());
532         ctx.getResolvedAttributes().clear();
533         throw;
534     }
535 }
536
537 void SimpleAggregationResolver::resolveAttributes(ResolutionContext& ctx) const
538 {
539 #ifdef _DEBUG
540     xmltooling::NDC ndc("resolveAttributes");
541 #endif
542
543     SimpleAggregationContext& qctx = dynamic_cast<SimpleAggregationContext&>(ctx);
544
545     // First we manufacture the appropriate NameID to use.
546     scoped_ptr<NameID> n;
547     for (vector<string>::const_iterator a = m_attributeIds.begin(); !n.get() && a != m_attributeIds.end(); ++a) {
548         const Attribute* attr=nullptr;
549         if (qctx.getSession()) {
550             // Input attributes should be available via multimap.
551             pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> range =
552                 qctx.getSession()->getIndexedAttributes().equal_range(*a);
553             for (; !attr && range.first != range.second; ++range.first) {
554                 if (range.first->second->valueCount() > 0)
555                     attr = range.first->second;
556             }
557         }
558         else if (qctx.getInputAttributes()) {
559             // Have to loop over unindexed set.
560             const vector<Attribute*>* matches = qctx.getInputAttributes();
561             for (indirect_iterator<vector<Attribute*>::const_iterator> match = make_indirect_iterator(matches->begin());
562                     !attr && match != make_indirect_iterator(matches->end()); ++match) {
563                 if (*a == match->getId() && match->valueCount() > 0)
564                     attr = &(*match);
565             }
566         }
567
568         if (attr) {
569             m_log.debug("using input attribute (%s) as identifier for queries", attr->getId());
570             n.reset(NameIDBuilder::buildNameID());
571             const NameIDAttribute* down = dynamic_cast<const NameIDAttribute*>(attr);
572             if (down) {
573                 // We can create a NameID directly from the source material.
574                 const NameIDAttribute::Value& v = down->getValues().front();
575                 auto_arrayptr<XMLCh> val(fromUTF8(v.m_Name.c_str()));
576                 n->setName(val.get());
577
578                 if (!v.m_Format.empty()) {
579                     auto_arrayptr<XMLCh> format(fromUTF8(v.m_Format.c_str()));
580                     n->setFormat(format.get());
581                 }
582                 if (!v.m_NameQualifier.empty()) {
583                     auto_arrayptr<XMLCh> nq(fromUTF8(v.m_NameQualifier.c_str()));
584                     n->setNameQualifier(nq.get());
585                 }
586                 if (!v.m_SPNameQualifier.empty()) {
587                     auto_arrayptr<XMLCh> spnq(fromUTF8(v.m_SPNameQualifier.c_str()));
588                     n->setSPNameQualifier(spnq.get());
589                 }
590                 if (!v.m_SPProvidedID.empty()) {
591                     auto_arrayptr<XMLCh> sppid(fromUTF8(v.m_SPProvidedID.c_str()));
592                     n->setSPProvidedID(sppid.get());
593                 }
594             }
595             else {
596                 // We have to mock up the NameID.
597                 auto_arrayptr<XMLCh> val(fromUTF8(attr->getSerializedValues().front().c_str()));
598                 n->setName(val.get());
599                 if (!m_format.empty())
600                     n->setFormat(m_format.c_str());
601             }
602         }
603     }
604
605     if (!n) {
606         if (qctx.getNameID() && m_attributeIds.empty()) {
607             m_log.debug("using authenticated NameID as identifier for queries");
608         }
609         else {
610             m_log.warn("unable to resolve attributes, no suitable query identifier found");
611             return;
612         }
613     }
614
615     set<string> history;
616
617     // Put initial IdP into history to prevent extra query.
618     if (qctx.getEntityID())
619         history.insert(qctx.getEntityID());
620
621     // Prepare to track exceptions.
622     auto_ptr<SimpleAttribute> exceptAttr;
623     if (!m_exceptionId.empty())
624         exceptAttr.reset(new SimpleAttribute(m_exceptionId));
625
626     // We have a master loop over all the possible sources of material.
627     for (vector< pair<string,bool> >::const_iterator source = m_sources.begin(); source != m_sources.end(); ++source) {
628         if (source->second) {
629             // A literal entityID to query.
630             if (history.count(source->first) == 0) {
631                 m_log.debug("issuing SAML query to (%s)", source->first.c_str());
632                 try {
633                     doQuery(qctx, source->first.c_str(), n ? n.get() : qctx.getNameID());
634                 }
635                 catch (std::exception& ex) {
636                     if (exceptAttr.get())
637                         exceptAttr->getValues().push_back(XMLToolingConfig::getConfig().getURLEncoder()->encode(ex.what()));
638                 }
639                 history.insert(source->first);
640             }
641             else {
642                 m_log.debug("skipping previously queried attribute source (%s)", source->first.c_str());
643             }
644         }
645         else {
646             m_log.debug("using attribute sources referenced in attribute (%s)", source->first.c_str());
647             if (qctx.getSession()) {
648                 // Input attributes should be available via multimap.
649                 pair<multimap<string,const Attribute*>::const_iterator, multimap<string,const Attribute*>::const_iterator> range =
650                     qctx.getSession()->getIndexedAttributes().equal_range(source->first);
651                 for (; range.first != range.second; ++range.first) {
652                     const vector<string>& links = range.first->second->getSerializedValues();
653                     for (vector<string>::const_iterator link = links.begin(); link != links.end(); ++link) {
654                         if (history.count(*link) == 0) {
655                             m_log.debug("issuing SAML query to (%s)", link->c_str());
656                             try {
657                                 doQuery(qctx, link->c_str(), n ? n.get() : qctx.getNameID());
658                             }
659                             catch (std::exception& ex) {
660                                 if (exceptAttr.get())
661                                     exceptAttr->getValues().push_back(XMLToolingConfig::getConfig().getURLEncoder()->encode(ex.what()));
662                             }
663                             history.insert(*link);
664                         }
665                         else {
666                             m_log.debug("skipping previously queried attribute source (%s)", link->c_str());
667                         }
668                     }
669                 }
670             }
671             else if (qctx.getInputAttributes()) {
672                 // Have to loop over unindexed set.
673                 const vector<Attribute*>* matches = qctx.getInputAttributes();
674                 for (indirect_iterator<vector<Attribute*>::const_iterator> match = make_indirect_iterator(matches->begin());
675                         match != make_indirect_iterator(matches->end()); ++match) {
676                     if (source->first == match->getId()) {
677                         const vector<string>& links = match->getSerializedValues();
678                         for (vector<string>::const_iterator link = links.begin(); link != links.end(); ++link) {
679                             if (history.count(*link) == 0) {
680                                 m_log.debug("issuing SAML query to (%s)", link->c_str());
681                                 try {
682                                     doQuery(qctx, link->c_str(), n ? n.get() : qctx.getNameID());
683                                 }
684                                 catch (std::exception& ex) {
685                                     if (exceptAttr.get())
686                                         exceptAttr->getValues().push_back(XMLToolingConfig::getConfig().getURLEncoder()->encode(ex.what()));
687                                 }
688                                 history.insert(*link);
689                             }
690                             else {
691                                 m_log.debug("skipping previously queried attribute source (%s)", link->c_str());
692                             }
693                         }
694                     }
695                 }
696             }
697         }
698     }
699
700     if (exceptAttr.get()) {
701         qctx.getResolvedAttributes().push_back(exceptAttr.get());
702         exceptAttr.release();
703     }
704 }