Boost related changes
[shibboleth/cpp-opensaml.git] / saml / binding / impl / ArtifactMap.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  * ArtifactMap.cpp
23  * 
24  * Helper class for SAMLArtifact mapping and retrieval. 
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "binding/ArtifactMap.h"
30 #include "binding/SAMLArtifact.h"
31
32 #include <ctime>
33 #include <boost/lambda/bind.hpp>
34 #include <boost/lambda/lambda.hpp>
35 #include <xercesc/util/XMLUniDefs.hpp>
36 #include <xmltooling/logging.h>
37 #include <xmltooling/XMLObjectBuilder.h>
38 #include <xmltooling/XMLToolingConfig.h>
39 #include <xmltooling/security/SecurityHelper.h>
40 #include <xmltooling/util/NDC.h>
41 #include <xmltooling/util/ParserPool.h>
42 #include <xmltooling/util/StorageService.h>
43 #include <xmltooling/util/XMLHelper.h>
44 #include <xmltooling/util/Threads.h>
45
46 using namespace opensaml;
47 using namespace xmltooling::logging;
48 using namespace xmltooling;
49 using namespace boost::lambda;
50 using namespace boost;
51 using namespace std;
52
53 namespace opensaml {
54     // In-memory storage of mappings instead of using storage API.
55     class SAML_DLLLOCAL ArtifactMappings
56     {
57     public:
58         ArtifactMappings() : m_lock(Mutex::create()) {}
59         ~ArtifactMappings() {}
60
61         void storeContent(XMLObject* content, const SAMLArtifact* artifact, const char* relyingParty, int TTL);
62         XMLObject* retrieveContent(const SAMLArtifact* artifact, const char* relyingParty);
63         string getRelyingParty(const SAMLArtifact* artifact);
64     
65     private:
66         struct SAML_DLLLOCAL Mapping {
67             Mapping() : m_expires(0) {}
68             auto_ptr<XMLObject> m_xml;
69             string m_relying;
70             time_t m_expires;
71         };
72
73         void removeMapping(const map<string,Mapping>::iterator& i);
74         
75         auto_ptr<Mutex> m_lock;
76         map<string,Mapping> m_artMap;
77         multimap<time_t,string> m_expMap;
78     };
79
80     static const XMLCh artifactTTL[] =  UNICODE_LITERAL_11(a,r,t,i,f,a,c,t,T,T,L);
81     static const XMLCh context[] =      UNICODE_LITERAL_7(c,o,n,t,e,x,t);
82     static const XMLCh Mapping[] =      UNICODE_LITERAL_7(M,a,p,p,i,n,g);
83     static const XMLCh _relyingParty[] = UNICODE_LITERAL_12(r,e,l,y,i,n,g,P,a,r,t,y);
84 };
85
86 void ArtifactMappings::removeMapping(const map<string,Mapping>::iterator& i)
87 {
88     // All elements in the secondary map whose key matches the expiration of the removed mapping.
89     pair<multimap<time_t,string>::iterator,multimap<time_t,string>::iterator> range =
90         m_expMap.equal_range(i->second.m_expires);
91
92     // Find an element in the matching range whose value matches the input key.
93     multimap<time_t,string>::iterator el = find_if(
94         range.first, range.second,
95         (lambda::bind(&multimap<time_t,string>::value_type::second, _1) == boost::ref(i->first))
96         );
97     if (el != range.second) {
98         m_expMap.erase(el);
99     }
100
101     m_artMap.erase(i);
102 }
103
104 void ArtifactMappings::storeContent(XMLObject* content, const SAMLArtifact* artifact, const char* relyingParty, int TTL)
105 {
106     Lock wrapper(m_lock.get());
107
108     // Garbage collect any expired artifacts.
109     time_t now = time(nullptr);
110     multimap<time_t,string>::iterator stop = m_expMap.upper_bound(now);
111     for (multimap<time_t,string>::iterator i = m_expMap.begin(); i != stop; m_expMap.erase(i++)) {
112         m_artMap.erase(i->second);
113     }
114     
115     // Key is the hexed handle.
116     string hexed = SAMLArtifact::toHex(artifact->getMessageHandle());
117     Mapping& m = m_artMap[hexed];
118     m.m_xml.reset(content);
119     if (relyingParty)
120         m.m_relying = relyingParty;
121     m.m_expires = now + TTL;
122     m_expMap.insert(pair<const time_t,string>(m.m_expires,hexed));
123 }
124
125 XMLObject* ArtifactMappings::retrieveContent(const SAMLArtifact* artifact, const char* relyingParty)
126 {
127     Category& log=Category::getInstance(SAML_LOGCAT".ArtifactMap");
128     Lock wrapper(m_lock.get());
129
130     map<string,Mapping>::iterator i = m_artMap.find(SAMLArtifact::toHex(artifact->getMessageHandle()));
131     if (i == m_artMap.end())
132         throw BindingException("Requested artifact not in map or may have expired.");
133     
134     if (!(i->second.m_relying.empty())) {
135         if (!relyingParty || i->second.m_relying != relyingParty) {
136             log.warn(
137                 "request from (%s) for artifact issued to (%s)",
138                 relyingParty ? relyingParty : "unknown", i->second.m_relying.c_str()
139                 );
140             removeMapping(i);
141             throw BindingException("Unauthorized artifact mapping request.");
142         }
143     }
144     
145     if (time(nullptr) >= i->second.m_expires) {
146         removeMapping(i);
147         throw BindingException("Requested artifact has expired.");
148     }
149     
150     log.debug("resolved artifact for (%s)", relyingParty ? relyingParty : "unknown");
151     XMLObject* ret = i->second.m_xml.release();
152     removeMapping(i);
153     return ret;
154 }
155
156 string ArtifactMappings::getRelyingParty(const SAMLArtifact* artifact)
157 {
158     map<string,Mapping>::iterator i = m_artMap.find(SAMLArtifact::toHex(artifact->getMessageHandle()));
159     if (i == m_artMap.end())
160         throw BindingException("Requested artifact not in map or may have expired.");
161     return i->second.m_relying;
162 }
163
164 ArtifactMap::ArtifactMap(xmltooling::StorageService* storage, const char* context, unsigned int artifactTTL)
165     : m_storage(storage), m_context((context && *context) ? context : "opensaml::ArtifactMap"), m_artifactTTL(artifactTTL)
166 {
167     if (!m_storage)
168         m_mappings.reset(new ArtifactMappings());
169 }
170
171 ArtifactMap::ArtifactMap(const DOMElement* e, xmltooling::StorageService* storage)
172     : m_storage(storage), m_artifactTTL(180)
173 {
174     if (e) {
175         auto_ptr_char c(e->getAttributeNS(nullptr, context));
176         if (c.get() && *c.get()) {
177             m_context = c.get();
178             if (storage && m_context.length() > m_storage->getCapabilities().getContextSize()) {
179                 throw IOException("ArtifactMap context length exceeds capacity of storage service.");
180             }
181         }
182         else {
183             m_context = "opensaml::ArtifactMap";
184         }
185
186         const XMLCh* TTL = e->getAttributeNS(nullptr, artifactTTL);
187         if (TTL) {
188             m_artifactTTL = XMLString::parseInt(TTL);
189             if (!m_artifactTTL)
190                 m_artifactTTL = 180;
191         }
192     }
193     
194     if (!m_storage)
195         m_mappings.reset(new ArtifactMappings());
196 }
197
198 ArtifactMap::~ArtifactMap()
199 {
200 }
201
202 void ArtifactMap::storeContent(XMLObject* content, const SAMLArtifact* artifact, const char* relyingParty)
203 {
204     if (content->getParent())
205         throw BindingException("Cannot store artifact mapping for XML content with parent.");
206     else if (!m_storage)
207         return m_mappings->storeContent(content, artifact, relyingParty, m_artifactTTL);
208     
209     // Marshall with defaulted document, to reuse existing DOM and/or create a bound Document.
210     DOMElement* root = content->marshall();
211     
212     // Build a DOM with the same document to store the relyingParty mapping.
213     if (relyingParty) {
214         auto_ptr_XMLCh temp(relyingParty);
215         root = root->getOwnerDocument()->createElementNS(nullptr,Mapping);
216         root->setAttributeNS(nullptr,_relyingParty,temp.get());
217         root->appendChild(content->getDOM());
218     }
219     
220     // Serialize the root element, whatever it is, for storage.
221     string xmlbuf;
222     XMLHelper::serialize(root, xmlbuf);
223
224     // Use hex form of message handler as storage key unless it's too big.
225     string key = artifact->getMessageHandle();
226     if (key.length() > m_storage->getCapabilities().getKeySize())
227         key = SecurityHelper::doHash("SHA1", key.data(), key.length());
228     else
229         key = SAMLArtifact::toHex(key);
230
231     if (!m_storage->createText(
232         m_context.c_str(),
233         key.c_str(),
234         xmlbuf.c_str(),
235         time(nullptr) + m_artifactTTL
236         )) {
237         throw IOException("Attempt to insert duplicate artifact into map.");
238     }
239         
240     // Cleanup by destroying XML.
241     delete content;
242 }
243
244 XMLObject* ArtifactMap::retrieveContent(const SAMLArtifact* artifact, const char* relyingParty)
245 {
246 #ifdef _DEBUG
247     xmltooling::NDC ndc("retrieveContent");
248 #endif
249     Category& log=Category::getInstance(SAML_LOGCAT".ArtifactMap");
250
251     if (!m_storage)
252         return m_mappings->retrieveContent(artifact, relyingParty);
253
254     // Use hex form of message handler as storage key unless it's too big.
255     string key = artifact->getMessageHandle();
256     if (key.length() > m_storage->getCapabilities().getKeySize())
257         key = SecurityHelper::doHash("SHA1", key.data(), key.length());
258     else
259         key = SAMLArtifact::toHex(key);
260
261     // Read the mapping and then delete it.
262     string xmlbuf;
263     if (!m_storage->readText(m_context.c_str(), key.c_str(), &xmlbuf))
264         throw BindingException("Artifact not found in mapping database.");
265     m_storage->deleteText(m_context.c_str(), key.c_str());
266     
267     // Parse the data back into XML.
268     istringstream is(xmlbuf);
269     DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(is);
270     XercesJanitor<DOMDocument> janitor(doc);
271     
272     // Check the root element.
273     DOMElement* messageRoot = doc->getDocumentElement();
274     if (XMLHelper::isNodeNamed(messageRoot, nullptr, Mapping)) {
275         auto_ptr_char temp(messageRoot->getAttributeNS(nullptr,_relyingParty));
276         if (!relyingParty || strcmp(temp.get(),relyingParty)) {
277             log.warn("request from (%s) for artifact issued to (%s)", relyingParty ? relyingParty : "unknown", temp.get());
278             throw BindingException("Unauthorized artifact mapping request.");
279         }
280         messageRoot = XMLHelper::getFirstChildElement(messageRoot);
281     }
282     
283     // Unmarshall...
284     XMLObject* xmlObject = XMLObjectBuilder::buildOneFromElement(messageRoot, true);    // bind document
285     janitor.release();
286     
287     log.debug("resolved artifact for (%s)", relyingParty ? relyingParty : "unknown");
288     return xmlObject;
289 }
290
291 string ArtifactMap::getRelyingParty(const SAMLArtifact* artifact)
292 {
293     if (!m_storage)
294         return m_mappings->getRelyingParty(artifact);
295
296     // Use hex form of message handler as storage key unless it's too big.
297     string key = artifact->getMessageHandle();
298     if (key.length() > m_storage->getCapabilities().getKeySize())
299         key = SecurityHelper::doHash("SHA1", key.data(), key.length());
300     else
301         key = SAMLArtifact::toHex(key);
302
303     string xmlbuf;
304     if (!m_storage->readText(m_context.c_str(), key.c_str(), &xmlbuf))
305         throw BindingException("Artifact not found in mapping database.");
306     
307     // Parse the data back into XML.
308     istringstream is(xmlbuf);
309     DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(is);
310     XercesJanitor<DOMDocument> janitor(doc);
311     
312     // Check the root element.
313     DOMElement* messageRoot = doc->getDocumentElement();
314     if (XMLHelper::isNodeNamed(messageRoot, nullptr, Mapping)) {
315         auto_ptr_char temp(messageRoot->getAttributeNS(nullptr,_relyingParty));
316         return temp.get();
317     }
318     return string();
319 }