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