Simpler config and regex support in entity matcher
[shibboleth/cpp-opensaml.git] / saml / saml2 / metadata / impl / EntityAttributesEntityMatcher.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  * EntityAttributesEntityMatcher.cpp
23  *
24  * EntityMatcher that applies a set of input attributes.
25  */
26
27 #include "internal.h"
28 #include "saml2/metadata/EntityMatcher.h"
29 #include "saml2/metadata/Metadata.h"
30
31 #include <boost/scoped_ptr.hpp>
32 #include <boost/shared_ptr.hpp>
33 #include <boost/iterator/indirect_iterator.hpp>
34 #include <boost/lambda/bind.hpp>
35 #include <boost/lambda/casts.hpp>
36 #include <boost/lambda/lambda.hpp>
37 #include <xercesc/util/XMLUniDefs.hpp>
38 #include <xercesc/util/regx/RegularExpression.hpp>
39 #include <xmltooling/logging.h>
40 #include <xmltooling/util/XMLHelper.h>
41
42 using namespace opensaml::saml2md;
43 using namespace opensaml::saml2;
44 using namespace opensaml;
45 using namespace xmltooling::logging;
46 using namespace xmltooling;
47 using namespace boost::lambda;
48 using namespace boost;
49 using namespace std;
50
51 namespace opensaml {
52     namespace saml2md {
53         class SAML_DLLLOCAL EntityAttributesEntityMatcher : public EntityMatcher
54         {
55         public:
56             EntityAttributesEntityMatcher(const DOMElement* e);
57             ~EntityAttributesEntityMatcher() {}
58
59             bool matches(const EntityDescriptor& entity) const;
60
61         private:
62             bool _matches(const EntityAttributes*, const Attribute*) const;
63
64             bool m_trimTags;
65             vector< boost::shared_ptr<Attribute> > m_tags;
66         };
67
68         EntityMatcher* SAML_DLLLOCAL EntityAttributesEntityMatcherFactory(const DOMElement* const & e)
69         {
70             return new EntityAttributesEntityMatcher(e);
71         }
72
73         static const XMLCh attributeName[] =        UNICODE_LITERAL_13(a,t,t,r,i,b,u,t,e,N,a,m,e);
74         static const XMLCh attributeNameFormat[] =  UNICODE_LITERAL_19(a,t,t,r,i,b,u,t,e,N,a,m,e,F,o,r,m,a,t);
75         static const XMLCh attributeValue[] =       UNICODE_LITERAL_14(a,t,t,r,i,b,u,t,e,V,a,l,u,e);
76         static const XMLCh attributeValueRegex[] =  UNICODE_LITERAL_19(a,t,t,r,i,b,u,t,e,V,a,l,u,e,R,e,g,e,x);
77         static const XMLCh regex[] =                UNICODE_LITERAL_5(r,e,g,e,x);
78         static const XMLCh trimTags[] =             UNICODE_LITERAL_8(t,r,i,m,T,a,g,s);
79     };
80 };
81
82
83 EntityAttributesEntityMatcher::EntityAttributesEntityMatcher(const DOMElement* e)
84     : m_trimTags(XMLHelper::getAttrBool(e, false, trimTags))
85 {
86     // Check for shorthand syntax.
87     if (e && e->hasAttributeNS(nullptr, attributeName) && (e->hasAttributeNS(nullptr, attributeValue) || e->hasAttributeNS(nullptr, attributeValueRegex))) {
88         boost::shared_ptr<Attribute> np(AttributeBuilder::buildAttribute());
89         np->setName(e->getAttributeNS(nullptr, attributeName));
90         np->setNameFormat(e->getAttributeNS(nullptr, attributeNameFormat));
91         auto_ptr<AttributeValue> nval(AttributeValueBuilder::buildAttributeValue());
92         if (e->hasAttributeNS(nullptr, attributeValue)) {
93             nval->setTextContent(e->getAttributeNS(nullptr, attributeValue));
94         }
95         else {
96             nval->setTextContent(e->getAttributeNS(nullptr, attributeValueRegex));
97             // Use as a signal later that the value is a regex.
98             nval->setAttribute(xmltooling::QName(nullptr, regex), xmlconstants::XML_ONE);
99         }
100         np->getAttributeValues().push_back(nval.get());
101         nval.release();
102         m_tags.push_back(np);
103     }
104
105     DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20_NS, Attribute::LOCAL_NAME);
106     while (child) {
107         boost::shared_ptr<XMLObject> obj(AttributeBuilder::buildOneFromElement(child));
108         m_tags.push_back(boost::shared_dynamic_cast<Attribute>(obj));
109         child = XMLHelper::getNextSiblingElement(child, samlconstants::SAML20_NS, Attribute::LOCAL_NAME);
110     }
111
112     if (m_tags.empty())
113         throw XMLToolingException("EntityAttributes EntityMatcher requires at least one saml2:Attribute to match.");
114 }
115
116 bool EntityAttributesEntityMatcher::matches(const EntityDescriptor& entity) const
117 {
118     // Check for a tag match in the EntityAttributes extension of the entity and its parent(s).
119     const Extensions* exts = entity.getExtensions();
120     if (exts) {
121         const vector<XMLObject*>& children = exts->getUnknownXMLObjects();
122         const XMLObject* xo = find_if(children, ll_dynamic_cast<EntityAttributes*>(_1) != ((EntityAttributes*)nullptr));
123         if (xo) {
124             // If we find a matching tag, we win. Each tag is treated in OR fashion.
125             if (find_if(m_tags.begin(), m_tags.end(),
126                 lambda::bind(&EntityAttributesEntityMatcher::_matches, this, dynamic_cast<const EntityAttributes*>(xo),
127                     lambda::bind(&boost::shared_ptr<Attribute>::get, _1))) != m_tags.end()) {
128                 return true;
129             }
130         }
131     }
132
133     const EntitiesDescriptor* group = dynamic_cast<EntitiesDescriptor*>(entity.getParent());
134     while (group) {
135         exts = group->getExtensions();
136         if (exts) {
137             const vector<XMLObject*>& children = exts->getUnknownXMLObjects();
138             const XMLObject* xo = find_if(children, ll_dynamic_cast<EntityAttributes*>(_1) != ((EntityAttributes*)nullptr));
139             if (xo) {
140                 // If we find a matching tag, we win. Each tag is treated in OR fashion.
141                 if (find_if(m_tags.begin(), m_tags.end(),
142                     lambda::bind(&EntityAttributesEntityMatcher::_matches, this, dynamic_cast<const EntityAttributes*>(xo),
143                         lambda::bind(&boost::shared_ptr<Attribute>::get, _1))) != m_tags.end()) {
144                     return true;
145                 }
146             }
147         }
148         group = dynamic_cast<EntitiesDescriptor*>(group->getParent());
149     }
150
151     return false;
152 }
153
154 bool EntityAttributesEntityMatcher::_matches(const EntityAttributes* ea, const Attribute* tag) const
155 {
156     const vector<Attribute*>& attrs = ea->getAttributes();
157     const vector<XMLObject*>& tagvals = tag->getAttributeValues();
158     if (!attrs.empty() && !tagvals.empty()) {
159         // Track whether we've found every tag value.
160         vector<bool> flags(tagvals.size());
161
162         // Holds the active regex, if any.
163         scoped_ptr<RegularExpression> re;
164         xmltooling::QName regexQName(nullptr, regex);
165
166         // Check each attribute/tag in the candidate.
167         for (indirect_iterator<vector<Attribute*>::const_iterator> a = make_indirect_iterator(attrs.begin());
168                 a != make_indirect_iterator(attrs.end()); ++a) {
169             // Compare Name and NameFormat for a matching tag.
170             if (XMLString::equals(a->getName(), tag->getName()) &&
171                 (!tag->getNameFormat() || XMLString::equals(tag->getNameFormat(), Attribute::UNSPECIFIED) ||
172                     XMLString::equals(tag->getNameFormat(), a->getNameFormat()))) {
173
174                 // Check each tag value's simple content for a match.
175                 for (vector<XMLObject*>::size_type tagindex = 0; tagindex < tagvals.size(); ++tagindex) {
176                     const XMLObject* tagval = tagvals[tagindex];
177                     const XMLCh* tagvalstr = (tagval->getDOM()) ? tagval->getDOM()->getTextContent() : tagval->getTextContent();
178                     re.reset();
179
180                     // Check for a regex flag.
181                     if (dynamic_cast<const AttributeExtensibleXMLObject*>(tagval)) {
182                         const XMLCh* reflag = dynamic_cast<const AttributeExtensibleXMLObject*>(tagval)->getAttribute(regexQName);
183                         if (reflag && (*reflag == chDigit_1 || *reflag == chLatin_t)) {
184                             try {
185                                 re.reset(new RegularExpression(tagvalstr));
186                             }
187                             catch (XMLException& ex) {
188                                 auto_ptr_char msg(ex.getMessage());
189                                 Category::getInstance(SAML_LOGCAT".EntityMatcher.EntityAttributes").error(msg.get());
190                             }
191                         }
192                     }
193                     
194                     const vector<XMLObject*>& cvals = const_cast<const Attribute&>(*a).getAttributeValues();
195                     for (indirect_iterator<vector<XMLObject*>::const_iterator> cval = make_indirect_iterator(cvals.begin());
196                             cval != make_indirect_iterator(cvals.end()); ++cval) {
197                         const XMLCh* cvalstr = cval->getDOM() ? cval->getDOM()->getTextContent() : cval->getTextContent();
198                         if (tagvalstr && cvalstr) {
199                             if (re) {
200                                 try {
201                                     if (re->matches(cvalstr)) {
202                                         flags[tagindex] = true;
203                                         break;
204                                     }
205                                 }
206                                 catch (XMLException& ex) {
207                                     auto_ptr_char msg(ex.getMessage());
208                                     Category::getInstance(SAML_LOGCAT".EntityMatcher.EntityAttributes").error(msg.get());
209                                 }
210                             }
211                             else if (XMLString::equals(tagvalstr, cvalstr)) {
212                                 flags[tagindex] = true;
213                                 break;
214                             }
215                             else if (m_trimTags) {
216                                 XMLCh* dup = XMLString::replicate(cvalstr);
217                                 XMLString::trim(dup);
218                                 if (XMLString::equals(tagvalstr, dup)) {
219                                     XMLString::release(&dup);
220                                     flags[tagindex] = true;
221                                     break;
222                                 }
223                                 XMLString::release(&dup);
224                             }
225                         }
226                     }
227                 }
228             }
229         }
230
231         if (find(flags.begin(), flags.end(), false) == flags.end())
232             return true;
233     }
234     return false;
235 }